@hlix/cli 0.5.0 → 0.5.1

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/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,w as p}from"./index-gf6sghpv.js";import{x as c}from"./index-11raxarr.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(`
2
+ import{b as C,c as h,e as T,f as a,x as p}from"./index-mwwmk5q2.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-90ythqvy.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};
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-n4cj07p6.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};
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ import{a as Y,c as tr,d as He,e as F,f as ie,g as ye,h as J,i as B,j as Oe,k as $r,l as Fr,m as nr,n as Hr,o as Ur,p as Tt,q as Br,r as Gr,s as Wr,t as Yr,u as Kr,v as Vr,w as qr,x as me}from"./index-mwwmk5q2.js";import"./index-f303pf32.js";import{realpathSync as Ia}from"node:fs";import{join as Dr,relative as zr,resolve as Ca}from"node:path";import{parseArgs as Ta}from"node:util";import{accessSync as Jr,constants as Zr,statSync as Qr}from"node:fs";import{delimiter as eo,join as to}from"node:path";import{createACPTool as no}from"@mastra/acp";import{createTool as ro}from"@mastra/core/tools";import{z as V}from"zod";var te={"claude-code":{harness:"claude-code",label:"Claude Code",command:"claude-agent-acp",args:[],authEnvVars:["ANTHROPIC_API_KEY"],install:"npm i -g @agentclientprotocol/claude-agent-acp"},codex:{harness:"codex",label:"Codex",command:"codex-acp",args:[],authEnvVars:["OPENAI_API_KEY"],env:{NO_BROWSER:"1"},install:"npm i -g @agentclientprotocol/codex-acp"},"cursor-agent":{harness:"cursor-agent",label:"Cursor Agent",command:"cursor-agent",args:["acp"],authEnvVars:["CURSOR_API_KEY"],install:"curl https://cursor.com/install -fsS | bash"}};function ht(e){if(e.flag)return{harness:oo(e.flag,"--harness"),source:"flag"};if(e.configured)return{harness:e.configured,source:e.configSource??"project"};return{harness:Oe,source:"default"}}function oo(e,t){if(B.includes(e))return e;throw Error(`${t} must be one of ${B.join(", ")}; got "${e}".`)}var Me="hlix_tasks_follow",so=(e)=>`hlix_coder_${e.split("-").join("_")}`;function yt(e){if(e.source==="default")return String(e.harness);let t=e.source==="flag"?"--harness":e.source;return`${e.harness} (${t})`}function bt(e,t=process.env){if(!e||e.includes("/"))return gt(e);return(t.PATH??"").split(eo).filter(Boolean).some((r)=>gt(to(r,e)))}function gt(e){if(!e)return!1;try{if(!Qr(e).isFile())return!1;return Jr(e,Zr.X_OK),!0}catch{return!1}}var Le=(e)=>`harness ${e.harness} needs \`${e.command}\` on PATH. Install it with: ${e.install}`;function io(e){let t=e.options??[],n=t.find((r)=>r.kind==="allow_once")??t.find((r)=>r.kind==="reject_once");if(!n)return{outcome:{outcome:"cancelled"}};return{outcome:{outcome:"selected",optionId:n.optionId}}}var ft=["ask_user","task_write","task_update","task_complete","task_check"],ao=(e)=>[`harness ${e} runs in the project's Coding Workspace, not on this machine.`,"Start work with `hlix cycles create`, find the tasks it plans with","`hlix tasks list`, and watch one live with `/follow <task-id>`.","Nothing runs on this machine, so a local coder binary is not used."].join(" "),xt=(e)=>[e==="unknown"?"This project's harness could not be read from the server. Do NOT guess which coder it runs — say so, and offer to check with the `hlix_harness` tool.":`This project's harness is ${e}: the platform runs ${e} for the coding work it executes, in the project's Coding Workspace.`,"Change it with the `hlix_harness` tool, which writes the project's setting.","","To do coding work here, dispatch it and then watch it:","1. `hlix_cycles_create` with the project id, a title and a description. That"," is what STARTS work — it enters the project's loop, which plans the cycle,"," creates its tasks and starts the coder. It returns no cycle id.","2. `hlix_tasks_list` with that project to find the tasks planning produced.",`3. \`${Me}\` with a task id, which streams that coder's own text and`," tool calls into this session live. Report what it did.","","`hlix_tasks_create` only adds a board row; it does not start anything, and","there is no way to start a single task. Never claim otherwise."].join(`
3
+ `),lo=(e,t)=>[`The user chose the ${e.label} harness. Do not edit files or run commands`,`yourself. Hand the whole task to \`${t}\` as one natural-language brief,`,`then report what it did. ${e.label} reads and writes the same working`,"directory you are in.","",`It authenticates from ${e.authEnvVars.join(" or ")} in this shell's`,"environment. If it reports a credential problem, say so — do not retry."].join(`
4
+ `);function St(e){if(e.sandbox==="cloud"||e.active==="hlix")return[];let t=new Set(e.unavailable??[]),n=e.model?{defaultModelId:e.model}:{},r=[{id:"hlix",name:"Hlix",description:"The hlix agent codes here, with the full toolset.",...n}];for(let o of Object.values(te)){let s=e.active===o.harness,l=so(o.harness);r.push({id:o.harness,name:o.label,description:`${o.label} runs on this machine over ACP and edits ${e.cwd}.`,instructions:lo(o,l),availableTools:t.has(o.harness)?[...e.readTools,...ft,Me]:[l,...e.readTools,...ft,Me],...t.has(o.harness)?{}:{additionalTools:{[l]:no({id:l,description:`Run a coding task with ${o.label}. Give it one natural-language brief; it reads and writes the working directory and returns its final output.`,command:o.command,args:o.args,cwd:e.cwd,...o.env?{env:o.env}:{},...e.workspace?{workspace:e.workspace}:{},onPermissionRequest:async(i)=>io(i)})}},...n,...s?{metadata:{default:!0}}:{}})}return r}function vt(e){if(!e.fromFlag||!e.modesBuilt)return null;return e.current===e.harness?null:e.harness}function je(e){let t=[...e.available],n=(o,s="none")=>({harness:e.current,available:t,action:s,message:o});if(!e.requested)return n(`harness: ${e.current}. Available here: ${t.join(", ")}.`);if(!B.includes(e.requested))return n(`/harness must name one of ${B.join(", ")}; got "${e.requested}".`);let r=e.requested;if(e.sandbox==="cloud"){let o=`${e.sandboxLine} · harness: ${r} (project preference)`;return{harness:r,available:t,action:"preference",message:r==="hlix"?o:`${o}. ${ao(r)}`}}if(!t.includes(r))return n(Le(te[r]));if(!e.modesBuilt)return n(`This session runs the hlix coder, so there is no ${r} mode to switch to. Restart with \`hlix --harness ${r}\`, or make it the default with \`hlix config set harness ${r}\`.`,"restart");return{harness:r,available:t,action:"mode",message:`${e.sandboxLine} · harness: ${r}`}}function Et(e){return ro({id:"hlix_harness",description:"Show or change the harness — which coder does the work. In a local or docker sandbox it switches this session's coder; in a cloud sandbox it writes the project's harness preference, which is what the platform runs. With no argument it reports the current harness.",inputSchema:V.object({harness:V.string().optional().describe(`One of ${B.join(", ")}. Omit to report the current one.`)}),outputSchema:V.object({harness:V.string(),available:V.array(V.string()),message:V.string()}),execute:async(t)=>{let n=e.session(),r=je({...t.harness?{requested:t.harness}:{},current:n?.mode.get()??Oe,available:e.available,sandbox:e.sandbox,sandboxLine:e.sandboxLine,modesBuilt:e.modesBuilt}),o={harness:r.harness,available:r.available,message:r.message};if(r.action==="mode"&&n)return await n.mode.switch({modeId:r.harness}),o;if(r.action==="preference"){if(!e.setProjectHarness)return{...o,message:"This folder is not bound to a hlix project, so there is no project preference to write. Run `hlix init` or pass --project <id>."};await e.setProjectHarness(r.harness)}return o}})}import{createTool as co}from"@mastra/core/tools";import{z as k}from"zod";var po=(e)=>`hlix_${e.split(" ").join("_")}`,uo=k.object({args:k.array(k.string()).optional().describe("Positional arguments that follow the command name."),flags:k.record(k.string(),k.union([k.string(),k.boolean()])).optional().describe('Options without the leading dashes, e.g. { "yes": true, "name": "api" }.')}),mo=k.object({exitCode:k.number(),stdout:k.string(),stderr:k.string()});function go(e,t,n){let r=e.name.split(" ").concat(t.args??[]);for(let[o,s]of Object.entries(t.flags??{})){if(s===!1)continue;if(r.push(`--${o}`),typeof s==="string")r.push(s)}if(!t.flags?.cwd)r.push("--cwd",n);if(e.supportsJson&&!t.flags?.json)r.push("--json");return r}async function fo(e,t,n,r=process.env){let o="",s="";return{exitCode:await ie([e],go(e,t,n),{stdout:(i)=>{o+=i},stderr:(i)=>{s+=i},env:r}),stdout:o,stderr:s}}function wt(e){let t={};for(let n of e.commands??me){let r=po(n.name);t[r]=co({id:r,description:`${n.summary}
5
+
6
+ ${n.usage}`,inputSchema:uo,outputSchema:mo,execute:async(o)=>fo(n,o,e.cwd,e.env)})}return t}import{createTool as ho}from"@mastra/core/tools";async function _t(e,t){let n=e?.agent?.toolCallId;if(!n)return;let r={type:"data-hlix-tool-progress",data:{toolCallId:n,progress:t},transient:!0},o=e?.agent?.outputWriter;if(o){await o(r);return}await e?.writer?.custom?.(r)}import{z as G}from"zod";function yo(e){switch(e.type){case"on_chat_model_stream":return e.delta?{event:"text",text:e.delta}:null;case"reasoning":return e.delta?{event:"text",text:e.delta}:null;case"on_tool_start":return{event:"tool_start",toolName:e.name,args:e.input};case"on_tool_end":return{event:"tool_end",toolName:e.name,result:e.output,isError:bo(e.output)};case"error":return{event:"finish",isError:!0,result:e.message};case"done":return{event:"finish",isError:!1};default:return null}}function bo(e){return typeof e==="object"&&e!==null&&e.status==="failed"}async function xo(e,t){let n=[],r=[],o="streamed",s="The coder's turn ended.";for await(let l of e){if(l.type==="idle"){o="idle",s="Nothing is being coded right now. The task is not in build or test.";break}if(l.type==="error")o="error",s=l.message;if(l.type==="on_chat_model_stream")n.push(l.delta);if(l.type==="on_tool_start")r.push(l.name);let i=yo(l);if(i)await t(i)}return{status:o,text:n.join(""),tools:r,message:s}}function It(e){return ho({id:"hlix_tasks_follow",description:"Watch a hlix task being coded in the cloud, live. Streams the coder's text and tool calls into this session as they happen, and returns what it did. Use it after a task starts building.",inputSchema:G.object({taskId:G.string().describe("The task to follow.")}),outputSchema:G.object({status:G.enum(["streamed","idle","error","unassigned"]),text:G.string(),tools:G.array(G.string()),message:G.string()}),execute:async(t,n)=>{let r=F(e.env??process.env,{cwd:e.cwd,flags:{}}),o=await r.tasks.get(t.taskId);if(!o.agentId)return{status:"unassigned",text:"",tools:[],message:"No agent has picked this task up yet, so there is no coder to watch. Check `hlix_tasks_get` again once it is building."};return xo(r.projects.observeAgent(o.projectId,o.agentId),(s)=>_t(n,s))}})}import{readFileSync as So,statSync as Rt}from"node:fs";import{isAbsolute as vo,join as Eo,relative as $e,resolve as q}from"node:path";var wo=["path","file","filePath","target","targetPath","dest","destination"],De=8000,_o=(e)=>{try{return Rt(e).isFile()}catch{return!1}},Io=(e)=>{try{return Rt(e).isDirectory()}catch{return!1}};function Ct(e,t){let n=$e(e,t);return n!==""&&!n.startsWith("..")&&!vo(n)}function Co(e){let t=q(e.root),n=q(t,e.touched);if(!Ct(t,n))return null;let r=Io(n)?n:q(n,"..");while(Ct(t,r)){for(let o of Tt){let s=Eo(r,o);if(_o(s))return s}r=q(r,"..")}return null}function To(e,t){let n=$e(t,e.path),r=!n||n.startsWith("..")?e.path:n;return[`Rules for ${$e(t,q(e.path,".."))||"."}/ (${r})`,"","This directory keeps its own rules. They apply to everything under it and","take precedence over the project's rules where the two differ.","",e.content].join(`
7
+ `)}function Ro(e){let t=[];for(let n of e){let r=n.content?.parts;if(!Array.isArray(r))continue;for(let o of r){if(o.type!=="tool-invocation")continue;let s=o.toolInvocation;if(!s||s.state!=="result")continue;if(typeof s.toolCallId!=="string"||s.toolCallId==="")continue;let l=ko(s.args);if(!l)continue;let i=[];for(let c of wo){let a=l[c];if(typeof a==="string"&&a.trim()!=="")i.push(a)}if(i.length>0)t.push({id:s.toolCallId,paths:i})}}return t}function ko(e){if(typeof e==="object"&&e!==null)return e;if(typeof e!=="string")return null;try{let t=JSON.parse(e);return typeof t==="object"&&t!==null?t:null}catch{return null}}class Fe{id="hlix-nested-rules";name="Nested rules";description="Adds a subdirectory's own AGENTS.md when the agent first works in it";root;skip;sent=new Map;seenCalls=new Set;constructor(e){this.root=q(e.root),this.skip=new Set((e.already??[]).map((t)=>q(t)))}loaded(){return[...this.sent.values()]}consider(e){let t=Co({touched:e,root:this.root});if(!t||this.skip.has(t)||this.sent.has(t))return null;let n;try{n=So(t,"utf8").trim()}catch{return null}if(n==="")return null;let r={path:t,content:n.length>De?`${n.slice(0,De).trimEnd()}
8
+
9
+ [truncated: ${t} is longer than ${De} characters]`:n};return this.sent.set(t,r),r}newCalls(e,t){let n=Ro(e.get.all.db()).filter((r)=>!this.seenCalls.has(r.id));for(let r of n)this.seenCalls.add(r.id);return t===0?[]:n}async processInputStep(e){for(let t of this.newCalls(e.messageList,e.stepNumber))for(let n of t.paths){let r=this.consider(n);if(!r)continue;await e.sendSignal?.({type:"reactive",tagName:"system-reminder",contents:To(r,this.root),attributes:{type:"nested-rules",path:r.path}})}return e.messageList}}import{Memory as No}from"@mastra/memory";var W="hlix",z="default",ae=(e)=>`${W}/${e}`,kt=(e)=>e.startsWith(`${W}/`)&&e.length>W.length+1;function Ao(e){return{name:W,url:`${e.baseUrl.replace(/\/+$/,"")}/v1/api/ai/w/${e.workspaceId}`,apiKey:e.apiKey,models:[...new Set([z,...e.models??[]])]}}function At(e){let t=He({env:e.env,flags:{},cwd:e.cwd});if(t.conflict||!t.credential||!t.workspaceId)return null;let n=t.credential.sessionToken||t.credential.apiKey;if(!n)return null;let r=t.binding?.config.projectId;return{...Ao({baseUrl:t.baseUrl,workspaceId:t.workspaceId,apiKey:n,...e.models?{models:e.models}:{}}),workspaceId:t.workspaceId,...r?{projectId:r}:{}}}var Po=3000;async function Pt(e){let t=He({env:e.env,flags:{},cwd:e.cwd});if(t.conflict||!t.credential||!t.workspaceId)return{};try{return{served:(await F(e.env,{cwd:e.cwd,flags:{}}).ai.models(t.workspaceId,{signal:AbortSignal.timeout(e.timeoutMs??Po)})).models.map((r)=>({id:r.id,name:r.name}))}}catch(n){return{warning:`could not read your workspace's models (${n instanceof Error?n.message:String(n)}). Offering the workspace default only.`}}}function Nt(e){if(e.configured){let t=e.configuredSource??"config";if(!e.cloud||!e.endpoint||kt(e.configured))return{id:e.configured,source:t};return{id:ae(z),source:"workspace",notice:`model ${e.configured} from ${t} is not available on the cloud sandbox; using hlix default`}}return e.endpoint?{id:ae(z),source:"workspace"}:null}var ge=200000;function fe(e){let t=Math.round(e*3/7);return{observationThreshold:t,reflectionThreshold:e-t}}var Mt=(e,t)=>`${e} · memory: ${Math.round((t.observationThreshold+t.reflectionThreshold)/1000)}k`;function Ot(e){return new No({storage:e.storage,vector:!1,options:{semanticRecall:!1,workingMemory:{enabled:!0,scope:"resource"},observationalMemory:{scope:"resource",observation:{model:()=>e.observerModel(),messageTokens:e.thresholds.observationThreshold},reflection:{model:()=>e.reflectorModel(),observationTokens:e.thresholds.reflectionThreshold}}}})}import{execFileSync as Jo}from"node:child_process";import{DockerSandbox as Zo}from"@mastra/docker";import{LocalFilesystem as Bt,LocalSandbox as Qo,Workspace as Gt}from"@mastra/core/workspace";var Mo=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Lt=/^(\s*name\s*:\s*)(.+?)\s*$/;function Oo(e,t){if(!Mo.test(t))return e;let n=e.indexOf(`
10
+ ---`,3);if(!e.startsWith("---")||n<0)return e;let o=e.slice(0,n).split(`
11
+ `),s=o.findIndex((c)=>Lt.test(c));if(s<0)return e;let l=Lt.exec(o[s]);if(!l)return e;let i=l[2].replace(/^["']|["']$/g,"").trim();if(i===t)return e;if(o[s]=`${l[1]}${t}`,!o.some((c)=>/^\s*title\s*:/.test(c)))o.push(`title: ${i}`);return`${o.join(`
12
+ `)}${e.slice(n)}`}function Lo(e){let t=e.split("/").filter((n)=>n!=="");if(t.length<2||t[t.length-1]!=="SKILL.md")return null;return t[t.length-2]}function jt(e){let t={exists:(n)=>e.exists(n),stat:(n)=>e.stat(n),readdir:(n)=>e.readdir(n),readFile:async(n)=>{let r=await e.readFile(n),o=Lo(n);if(o===null)return r;let s=typeof r==="string"?r:r.toString("utf8");return Oo(s,o)}};if(e.realpath)t.realpath=(n)=>e.realpath?.(n);return t}import{WORKSPACE_TOOLS as I}from"@mastra/core/workspace";var ne={[I.FILESYSTEM.READ_FILE]:"view",[I.FILESYSTEM.WRITE_FILE]:"write_file",[I.FILESYSTEM.EDIT_FILE]:"edit_file",[I.FILESYSTEM.LIST_FILES]:"find_files",[I.FILESYSTEM.DELETE]:"delete_file",[I.FILESYSTEM.FILE_STAT]:"file_stat",[I.FILESYSTEM.MKDIR]:"mkdir",[I.FILESYSTEM.GREP]:"search_content",[I.FILESYSTEM.AST_EDIT]:"ast_edit",[I.SANDBOX.EXECUTE_COMMAND]:"execute_command",[I.SANDBOX.GET_PROCESS_OUTPUT]:"process_output",[I.SANDBOX.KILL_PROCESS]:"kill_process",[I.LSP.LSP_INSPECT]:"lsp_inspect"},le=[I.FILESYSTEM.WRITE_FILE,I.FILESYSTEM.EDIT_FILE,I.FILESYSTEM.DELETE,I.FILESYSTEM.MKDIR,I.FILESYSTEM.AST_EDIT,I.SANDBOX.EXECUTE_COMMAND,I.SANDBOX.KILL_PROCESS].map((e)=>ne[e]),he=Object.values(ne).filter((e)=>!le.includes(e)),ce=Object.fromEntries(Object.entries(ne).map(([e,t])=>[e,{name:t}]));function A(e){return ne[e]??e}import{posix as Dt}from"node:path";import{DirectoryNotEmptyError as jo,DirectoryNotFoundError as Do,FileExistsError as $o,FileNotFoundError as Fo,FilesystemError as Ho,IsDirectoryError as Uo,MastraFilesystem as Bo,MastraSandbox as Go,NotDirectoryError as Wo,PermissionError as Yo,Workspace as Ko}from"@mastra/core/workspace";var Vo=600000,qo=["recursive","overwrite","force","maxDepth","extension"];function X(e){let t=e??{},n={};for(let r of qo)if(t[r]!==void 0)n[r]=t[r];return Object.keys(n).length>0?{options:n}:{}}var $t=(e)=>e instanceof Date?e:new Date(typeof e==="string"||typeof e==="number"?e:0);function zo(e,t,n){let r=e?.status;if(typeof r!=="number")return e;let o=e?.body,s=typeof o?.code==="string"?o.code:"",l=typeof o?.error==="string"?o.error:"",i=(c)=>l.toLowerCase().includes(c);if(r===404)return s==="ENOTDIR"||i("directory not found")?new Do(t):new Fo(t);if(r===403)return new Yo(t,n);if(r===409){if(s==="EEXIST"||i("already exists"))return new $o(t);if(s==="ENOTEMPTY"||i("not empty"))return new jo(t);if(s==="EISDIR"||i("is a directory"))return new Uo(t);if(s==="ENOTDIR"||i("not a directory"))return new Wo(t);return new Ho(l||`${n} failed`,s||"ECONFLICT",t)}return e}class Ft extends Bo{id;name="RemoteFilesystem";provider="hlix-coding-workspace";basePath;status="ready";client;constructor(e,t){super({name:"RemoteFilesystem"});this.client=e,this.basePath=t.root,this.id=t.id??`hlix-remote-fs:${t.root}`}getInfo(){return{id:this.id,name:this.name,provider:this.provider,status:this.status,metadata:{root:this.basePath}}}resolveAbsolutePath(e){return Dt.isAbsolute(e)?e:Dt.join(this.basePath,e)}async call(e){let t=this.resolveAbsolutePath(e.path);try{let{result:n}=await this.client.fs({...e,encoding:e.encoding??"utf8",path:t});return n}catch(n){throw zo(n,t,e.op)}}async readFile(e,t){let r=await this.call({op:"read",path:e,encoding:"base64"}),o=Buffer.from(r.content,r.encoding);return t?.encoding?o.toString(t.encoding):o}async writeFile(e,t,n){await this.call({op:"write",path:e,content:Buffer.from(t).toString("base64"),encoding:"base64",...X(n)})}async appendFile(e,t){await this.call({op:"append",path:e,content:Buffer.from(t).toString("base64"),encoding:"base64"})}async deleteFile(e,t){await this.call({op:"delete",path:e,...X(t)})}async copyFile(e,t,n){await this.call({op:"copy",path:e,dest:this.resolveAbsolutePath(t),...X(n)})}async moveFile(e,t,n){await this.call({op:"move",path:e,dest:this.resolveAbsolutePath(t),...X(n)})}async mkdir(e,t){await this.call({op:"mkdir",path:e,...X(t)})}async rmdir(e,t){await this.call({op:"rmdir",path:e,...X(t)})}async readdir(e,t){return await this.call({op:"readdir",path:e,...X(t)})??[]}async exists(e){return await this.call({op:"exists",path:e})===!0}async stat(e){let t=await this.call({op:"stat",path:e});return{...t,createdAt:$t(t.createdAt),modifiedAt:$t(t.modifiedAt)}}}var Xo=(e)=>`'${e.split("'").join("'\\''")}'`;class Ht extends Go{id;name="RemoteSandbox";provider="hlix-coding-workspace";status="ready";client;constructor(e,t){super({name:"RemoteSandbox"});if(this.client=e,this.id=`hlix-remote-sandbox:${t.projectId}`,t.root)this.setWorkingDirectory(t.root)}async start(){}getInfo(){return{id:this.id,name:this.name,provider:this.provider,status:this.status,createdAt:new Date(0)}}async executeCommand(e,t=[],n){let r=[e,...t.map(Xo)].join(" "),o=Date.now(),s=n?.cwd??this.workingDirectory,l=await this.client.exec({command:r,...s?{cwd:s}:{},timeoutMs:n?.timeout??Vo});return{success:l.exitCode===0,exitCode:l.exitCode,stdout:l.stdout,stderr:l.stderr,executionTimeMs:Date.now()-o,command:e,args:t}}}function Ut(e,t){let n=t.root;return new Ko({id:`hlix-project:${t.projectId}`,name:"Hlix Coding Workspace",filesystem:new Ft(e,{root:n}),sandbox:new Ht(e,{projectId:t.projectId,root:n}),tools:ce})}var Yt="node:22-bookworm",es=(e)=>`hlix-code-${e}`;function ts(e,t){if(J.includes(e))return e;throw new Y("invalid_usage",`${t==="flag"?"--sandbox":"sandbox in .hlix/config.json"} must be one of ${J.join(", ")}; got "${e}".`)}function Kt(e){let t=(n)=>n==="docker"?{image:e.dockerImage?.trim()||Yt}:{};if(e.flag){let n=e.flagSource??"flag",r=ts(e.flag,n);return{choice:r,reason:n==="flag"?`--sandbox ${e.flag}`:"config",...t(r)}}if(e.projectId)return{choice:"cloud",reason:`project ${e.projectId}`};if(e.dockerAvailable())return{choice:"docker",reason:"auto",...t("docker")};return{choice:"local",reason:"auto"}}var Vt=(e)=>`sandbox: ${e.choice} (${e.reason}${e.image?`, ${e.image}`:""})`;function qt(e=3000){try{return Jo("docker",["info"],{timeout:e,stdio:"ignore"}),!0}catch{return!1}}function Wt(e,t){if(!e||e.length===0)return{};return{skills:[...e],skillSource:jt(t)}}async function ns(e,t){let n=await e.environment();if(n.state==="absent")throw new Y("not_found",`Project ${t} has no Coding Workspace yet, so there is nothing to code in. Run \`hlix import\` from the folder, or run a task in the project, to build one.`);if(!n.repoDir)throw new Y("not_found",`This workspace's server did not say where project ${t}'s repository is. Update the server, or run with --sandbox docker|local.`);return n.repoDir}async function Ue(e,t){if(e.choice==="local"){let s=new Bt({basePath:t.cwd});return new Gt({id:"hlix-code-local",name:"Hlix Code (this machine)",filesystem:s,...Wt(t.skills,s),sandbox:new Qo({workingDirectory:t.cwd}),tools:ce})}if(e.choice==="cloud"){if(!t.remote||!t.projectId)throw new Y("invalid_usage","The cloud sandbox needs a hlix project. Run `hlix init`, pass --project <id>, or choose --sandbox docker|local.");return Ut(t.remote,{projectId:t.projectId,root:await ns(t.remote,t.projectId)})}let n="/workspace",r=e.image??Yt,o=new Bt({basePath:t.cwd});return new Gt({id:"hlix-code-docker",name:"Hlix Code (Docker)",filesystem:o,...Wt(t.skills,o),tools:ce,sandbox:new Zo({id:es(r),image:r,volumes:{[t.cwd]:n},workingDirectory:n})})}import{basename as ks}from"node:path";import{AgentController as As}from"@mastra/core/agent-controller";import{createCodingAgent as Ps}from"@mastra/core/coding-agent";import{createWorkspaceTools as Ns}from"@mastra/core/workspace";var rs=["execute_command","kill_process"],os=["updateWorkingMemory","task_write","task_update","task_complete","task_check","ask_user","submit_plan"];function Be(e){let t=e in ne?A(e):e;if(rs.includes(t))return"execute";if(le.includes(t))return"edit";if(he.includes(t)||os.includes(t))return"read";if(t.startsWith("hlix_"))return"other";return null}function zt(e=[]){let t=new Set(e);return(n)=>t.has(n)?"mcp":Be(n)}function ss(e){return Be(e)!=="read"}var Xt=[{category:"read",policy:"allow"}];function Jt(e){if(e.yolo||!ss(e.toolName))return{decision:"approve"};return{decision:"decline",reason:`Hlix Code is running with -p (no terminal to ask), so ${A(e.toolName)} was not run. Report this to the user: re-run with --yolo to let this session change things.`}}class Ge{on;constructor(e){this.on=e}get(){return this.on}set(e){this.on=e}}function Zt(e){let t=A(e),n=Be(e)??"other";return[{value:"approve",label:"Allow once",description:`Run ${t} this one time`},{value:"decline",label:"Decline",description:"Do not run it; tell the agent why"},{value:"always_allow_category",label:"Always allow",description:`Allow every ${n} tool for the rest of this session`}]}import{MastraModelGateway as is,ModelRouterLanguageModel as as}from"@mastra/core/llm";function ls(e,t){let n=[];for(let r of e??[]){if(!r.name||!r.url||r.name===W)continue;let o=r.apiKeyEnv?t[r.apiKeyEnv]:r.apiKey;if(r.apiKeyEnv&&!o)continue;n.push({name:r.name,url:r.url.replace(/\/+$/,""),apiKey:o??"",models:r.models??[]})}return n}function Qt(e){let t=e.indexOf("/");if(t<=0||t===e.length-1)return null;return{provider:e.slice(0,t),model:e.slice(t+1)}}class en extends is{id=`${W}-gateway`;name="Hlix";byProvider;constructor(e){super();this.byProvider=new Map(e.map((t)=>[t.name,t]))}modelIds(){return[...this.byProvider.values()].flatMap((e)=>e.models.map((t)=>`${e.name}/${t}`))}handlesModel(e){let t=Qt(e);return t!==null&&this.byProvider.has(t.provider)}shouldEnable(){return this.byProvider.size>0}async fetchProviders(){let e={};for(let t of this.byProvider.values())e[t.name]={name:t.name===W?"Hlix":t.name,url:t.url,apiKeyEnvVar:[],gateway:this.id,models:t.models.map((n)=>`${t.name}/${n}`)};return e}endpointFor(e){let t=Qt(e);return t?this.byProvider.get(t.provider):void 0}async buildUrl(e){return this.endpointFor(e)?.url}async getApiKey(e){let t=this.endpointFor(e);if(!t)throw Error(`Hlix Code cannot resolve the model "${e}". Run /model to pick one this workspace serves.`);return t.apiKey}resolveLanguageModel(e){let t=this.byProvider.get(e.providerId);if(!t)throw Error(`Hlix Code has no endpoint for provider "${e.providerId}".`);return new as({id:`${e.providerId}/${e.modelId}`,url:t.url,apiKey:e.apiKey||t.apiKey,...e.headers?{headers:e.headers}:{}})}}function tn(e){let t=[];if(e.endpoint)t.push({name:e.endpoint.name,url:e.endpoint.url,apiKey:e.endpoint.apiKey,models:e.endpoint.models});if(!e.cloud)t.push(...ls(e.providers,e.env));return new en(t)}import{buildBasePrompt as cs}from"@mastra/core/coding-agent";var N="Hlix Code",ds="Hlix Code",ps="noreply@hlix.ai";function us(e){if(e==="cloud")return"Your files and commands run in this project's cloud Coding Workspace, not on the user's machine.";if(e==="docker")return"Your files and commands run in a container on the user's machine, with this folder mounted.";return"Your files and commands run on the user's machine."}function nn(e){return e.sandbox==="cloud"?e.filesystemRoot??e.cwd:e.cwd}function rn(e){let t=cs({projectPath:e.projectPath,projectName:e.projectName,...e.gitBranch?{gitBranch:e.gitBranch}:{},platform:process.platform,date:new Date().toISOString().slice(0,10),mode:e.mode,...e.modelId?{modelId:e.modelId}:{},toolGuidance:us(e.sandbox),hasSubagents:e.hasSubagents??!1,productName:N,coAuthorName:ds,coAuthorEmail:ps});return e.hostInstructions?`${t}
13
+
14
+ ${e.hostInstructions}`:t}var Z="build",on="plan",ms=[Z,on];function sn(e,t=ms){let n=t.indexOf(e);return t[(n+1)%t.length]??t[0]}function We(e){let t=new Set(le);return e.filter((n)=>!t.has(n)&&!n.startsWith("hlix_"))}function gs(e){return[...new Set([...We(e),"submit_plan","task_write","task_update","task_check"])]}var fs=["You are planning, not building. Read whatever you need, then write the plan.","Do not create, edit or delete files and do not run shell commands — those tools are not available here, and asking for them instead of planning wastes the user's turn.","Call submit_plan when the plan is ready. The user approves it and you continue in build, where the writing tools and the hlix commands are available again."].join(`
15
+ `),hs=["You are building. Make the change, then verify it the way this project verifies things.","Read before you write, and prefer the smallest edit that works."].join(`
16
+ `);function an(e){let t=e.modelId?{defaultModelId:e.modelId}:{};return[{id:Z,name:"build",description:"Read, write and run. The default.",instructions:hs,metadata:{default:!0},...t},{id:on,name:"plan",description:"Read and plan; no edits, no commands.",instructions:fs,availableTools:gs(e.registeredTools),transitionsTo:Z,...t}]}import{lstatSync as ys,mkdirSync as bs,unlinkSync as xs}from"node:fs";import{homedir as Ss}from"node:os";import{join as Ye}from"node:path";import{LibSQLStore as vs}from"@mastra/libsql";function Ke(e=process.env){return Ye(e.HLIX_CONFIG_HOME??Ss(),".hlix","code")}function Es(e=process.env){return`file:${Ye(Ke(e),"threads.db")}`}var ws=["auth.json","mastra.db","mastra.db-shm","mastra.db-wal","settings.json"];function _s(e=process.env){let t=Ke(e);for(let n of ws){let r=Ye(t,n);try{if(!ys(r).isFile())continue;xs(r)}catch{}}}function ln(e=process.env){return bs(Ke(e),{recursive:!0}),_s(e),new vs({id:"hlix-code",url:Es(e)})}var cn="explore",dn="plan",pn="execute",Ve=[`You are a subagent of ${N}. You were given one task and you do not`,"see the conversation it came from, so do not guess at wider intent: answer","exactly what was asked.","Your reply is the ONLY thing that reaches the agent that called you, so it must","stand alone — name files by path, quote the lines that matter, and say plainly","when you could not find something rather than filling the gap."].join(`
17
+ `),Is=[Ve,"","You are exploring. Read the code and report what is there. You have no tools","that write, edit, delete or run commands, and that is deliberate — if the task","needs a change, say what change and where, and stop.","Be fast: search before you read, read the parts that matter, and do not walk a","whole tree to answer a question about one file."].join(`
18
+ `),Cs=[Ve,"","You are planning. Read whatever you need, then return the plan itself: the","files to change, what changes in each, the order, and how the result is","verified in THIS project (its own test or build command, not a generic one).","Do not make the change. A plan that hides a decision behind 'update as needed'","is not a plan — name the decision or say it is open and why."].join(`
19
+ `),Ts=[Ve,"","You are making one self-contained change. Read before you write, make the","smallest edit that works, then verify it the way this project verifies things.","Report what you changed, by path, and what the verification said — including","when it failed. A change reported as done that was never run is the one outcome","worse than a change that failed."].join(`
20
+ `);function un(e){let t=e.modelId?{defaultModelId:e.modelId}:{},n=e.registeredTools.filter((r)=>he.includes(r));return[{id:cn,name:"Explore",description:"Read-only investigation. Give it a question about the codebase; it searches and reads and reports what it found, without changing anything. Cheapest way to answer 'where is X' or 'how does Y work' without filling this conversation with file contents.",instructions:Is,allowedWorkspaceTools:n,...t},{id:dn,name:"Plan",description:"Works out HOW to make a change and returns the plan: files, edits, order, and how to verify. Makes no changes itself. Use it before a change big enough that the approach is the risky part.",instructions:Cs,...t},{id:pn,name:"Execute",description:"Carries out one self-contained change end to end — edit, then verify with this project's own command — and reports what it did and what the verification said. Use it for work that can be checked independently of this conversation.",instructions:Ts,...t}]}var Rs=[cn,dn,pn];function mn(e,t){let n=[],r=[];for(let o of e){if(Rs.includes(o.name)){r.push(`${o.name} (reserved by ${N})`);continue}n.push({id:o.name,name:o.name,description:o.description||`The ${o.name} agent defined by this project.`,instructions:o.instructions,...t?{defaultModelId:t}:{}})}return{subagents:n,skipped:r}}function gn(e,t){if(e.length===0&&t.length===0)return"";let n=e.map((r)=>r.id).join(", ");if(t.length===0)return`subagents: ${n}`;return`subagents: ${n} + ${t.length} from this project`}class be extends Error{constructor(){super("No hlix credential for this folder. Run `hlix auth login`.");this.name="NoCredentialError"}}function Ms(e,t){let n=t.startsWith(`${e.name}/`)?t.slice(e.name.length+1):z;return{id:`${e.name}/${n}`,url:e.url,apiKey:e.apiKey}}async function fn(e){if(!e.endpoint)throw new be;let t=e.endpoint,n=e.model?.id??ae(z),r=tn({endpoint:t,...e.providers?{providers:e.providers}:{},env:e.env,cloud:e.sandbox==="cloud"}),o=ln(e.env),s=fe(ye(e.memoryTokens)??ge),l=null,i=Ms(t,n),c=Ot({storage:o,thresholds:s,observerModel:()=>l?.om.observer.resolvedModel()??i,reflectorModel:()=>l?.om.reflector.resolvedModel()??i}),a=e.workspace?await Ns(e.workspace):{},m=e.mcpTools??{},u={...a,...e.extraTools??{},...m},f=Object.keys(u),y=un({registeredTools:f,modelId:n}),w=mn(e.projectSubagents??[],n),E=[...y,...w.subagents],_=nn({sandbox:e.sandbox,cwd:e.cwd,...e.workspace?.filesystem?.basePath?{filesystemRoot:e.workspace.filesystem.basePath}:{}}),M=Ps({id:"hlix-coder",name:N,model:i,instructions:rn({projectPath:_,projectName:ks(e.cwd),mode:Z,modelId:n,sandbox:e.sandbox,hasSubagents:E.length>0,...e.hostInstructions?{hostInstructions:e.hostInstructions}:{}}),tools:u,...e.workspace?{workspace:e.workspace}:{},...e.nestedRules?{inputProcessors:[e.nestedRules]}:{},memory:c}),O=St({sandbox:e.sandbox,cwd:e.cwd,active:e.harness,readTools:We(f),...e.workspace?{workspace:e.workspace}:{},...e.unavailableHarnesses?{unavailable:e.unavailableHarnesses}:{},model:n}),ee=O.length>0?O:an({registeredTools:f,modelId:n}),P=new As({id:"hlix-code",resourceId:t.workspaceId,agent:M,storage:o,memory:c,modes:ee,subagents:E,tools:u,gateways:[r],omConfig:{defaultObserverModelId:n,defaultReflectorModelId:n,defaultObservationThreshold:s.observationThreshold,defaultReflectionThreshold:s.reflectionThreshold},toolCategoryResolver:zt(Object.keys(m)),...e.workspace?{workspace:e.workspace}:{}});await P.init();let L=await P.createSession({resourceId:t.workspaceId,tags:{projectPath:e.cwd}});if(l=L,n)await L.model.switch({modelId:n});let j=vt({fromFlag:e.harnessFromFlag===!0,harness:e.harness,modesBuilt:O.length>0,current:L.mode.get()});if(j)await L.mode.switch({modeId:j});for(let g of Xt)await L.permissions.setForCategory(g);return{controller:P,session:L,gateway:r,store:o,memory:c,harnessModesBuilt:O.length>0,subagentLine:gn(y,w.subagents),subagentsSkipped:w.skipped,dispose:async()=>{await P.destroy().catch(()=>{}),await o.close().catch(()=>{})}}}import{Editor as ia,ProcessTerminal as aa,SelectList as Tr,Input as la,TuiMainScreen as ca,truncateToWidth as lt}from"@earendil-works/pi-tui";import{execFileSync as Os}from"node:child_process";import{readFileSync as Ls,statSync as js}from"node:fs";import{basename as Ds,extname as $s,isAbsolute as Fs,join as Hs}from"node:path";import{CombinedAutocompleteProvider as Us,Key as xe,matchesKey as Bs}from"@earendil-works/pi-tui";function Gs(e,t=Bs){if(t(e,xe.shift("tab")))return"cycle-mode";if(t(e,xe.ctrl("c")))return"interrupt";if(t(e,xe.ctrl("o")))return"expand";if(t(e,xe.escape))return"abort";return"text"}var Ws=2000;class yn{windowMs;armedAt=0;constructor(e=Ws){this.windowMs=e}press(e=Date.now()){if(this.armedAt!==0&&e-this.armedAt<=this.windowMs)return this.armedAt=0,"exit";return this.armedAt=e,"warn"}disarm(){this.armedAt=0}}function Ys(e){return[...e.entries()].map(([t,n])=>({name:t,description:n.description})).sort((t,n)=>t.name.localeCompare(n.name))}var qe="Press Ctrl-C again to leave Hlix Code.";class bn extends Us{applyCompletion(e,t,n,r,o){let s=e[t]??"";if(/^\/[^\s/]*$/.test(s.slice(0,n))){let l=[...e];return l[t]=`/${r.value} ${s.slice(n)}`,{lines:l,cursorLine:t,cursorCol:r.value.length+2}}return super.applyCompletion(e,t,n,r,o)}}function Ks(e=Os){for(let t of["fd","fdfind"])try{let n=e("which",[t],{timeout:3000,encoding:"utf8"}).trim();if(n)return n.split(`
21
+ `)[0]}catch{continue}return null}function Vs(e,t){let n=e.getFocusedComponent;if(typeof n!=="function")return!1;let r=n.call(e);return r!==void 0&&r!==null&&r!==t}function xn(e){let t=new yn;return e.editor.setAutocompleteProvider(new bn(Ys(e.commands),e.basePath,Ks())),e.editor.onSubmit=(n)=>{let r=n.trim();if(!r)return;e.editor.addToHistory(r),e.editor.setText(""),e.handlers.onSubmit(r)},e.tui.addInputListener((n)=>{switch(Gs(n)){case"cycle-mode":return e.handlers.onCycleMode(),{consume:!0};case"interrupt":if(t.press()==="exit")e.handlers.onExit();else e.handlers.onInterruptWarning(qe);return{consume:!0};case"expand":return t.disarm(),e.handlers.onExpand(),{consume:!0};case"abort":if(e.editor.isShowingAutocomplete())return;if(Vs(e.tui,e.editor))return;return t.disarm(),e.handlers.onAbort(),{consume:!0};default:t.disarm();return}})}var qs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},hn=8388608;function Sn(e,t,n=Ls,r=(o)=>js(o).size){let o=[],s=[],l=new Set;for(let i of e.matchAll(/(?:^|\s)@(\S+)/g)){let c=i[1],a=qs[$s(c).toLowerCase()];if(!a||l.has(c))continue;l.add(c);let m=Fs(c)?c:Hs(t,c);try{let u=r(m);if(u>hn){s.push(`@${c} is ${Math.round(u/1048576)} MB — too large to attach (limit ${hn/1048576} MB).`);continue}o.push({data:`data:${a};base64,${n(m).toString("base64")}`,mediaType:a,filename:Ds(c)})}catch{s.push(`@${c} could not be read, so it was not attached.`)}}return{content:e,files:o,notes:s}}import{z as D}from"zod";var Q=D.string().trim().min(1),zs=D.discriminatedUnion("kind",[D.object({kind:D.literal("project"),projectId:Q}).strict(),D.object({kind:D.literal("cycle"),projectId:Q,cycleId:Q}).strict(),D.object({kind:D.literal("task"),projectId:Q,taskId:Q}).strict(),D.object({kind:D.literal("agent"),projectId:Q,agentId:Q}).strict()]);import{z as d}from"zod";var vn=["github-compare","workspace-artifact"],Se=d.enum(["added","removed","modified","renamed","copied","changed","unchanged","unknown"]),En=d.object({path:d.string(),previousPath:d.string().nullable(),status:Se,additions:d.number().nullable(),deletions:d.number().nullable(),patch:d.string().nullable(),patchTruncated:d.boolean()}),wn=d.object({status:d.enum(["ahead","behind","identical","diverged","unknown"]),aheadBy:d.number().nullable(),behindBy:d.number().nullable()}),_n=d.object({kind:d.literal("git-archive"),reviewUrl:d.string(),sizeBytes:d.number().nullable(),capturedAt:d.string().nullable()}),In=d.object({verdict:d.enum(["approved","rejected"]),summary:d.string().nullable(),headSha:d.string().nullable(),observedAt:d.string(),stale:d.boolean()}),Xs=d.object({taskId:d.string(),repoId:d.string().nullable(),source:d.enum(vn),observedAt:d.string(),baseRef:d.string().nullable(),baseSha:d.string().nullable(),headRef:d.string().nullable(),headSha:d.string().nullable(),comparison:wn,filesChanged:d.number().nullable(),additions:d.number().nullable(),deletions:d.number().nullable(),commits:d.number().nullable(),files:d.array(En),filesTruncated:d.boolean(),evaluator:In.nullable(),artifact:_n.nullable()}),Cn=["base","head"],ze=d.enum(Cn),Tn=["open","resolved"],Xe=d.enum(Tn),Rn=d.object({pagePath:d.string().min(1).max(2048).regex(/^\/(?!\/)/,"expected a same-origin absolute path").refine((e)=>!/[?#\\]/.test(e),"query, fragment, and backslash are not allowed"),selector:d.string().min(1).max(512),viewport:d.object({width:d.number().int().min(320).max(1920),height:d.number().int().min(320).max(1200),deviceScaleFactor:d.literal(1)}).strict()}).strict(),kn=["previews-disabled","boundary-unavailable","review-head-unavailable","no-live-preview","revision-mismatch","source-not-isolated","unsafe-source"],An=d.discriminatedUnion("enabled",[d.object({enabled:d.literal(!0)}),d.object({enabled:d.literal(!1),reasonCode:d.enum(kn),reason:d.string()})]),Pn=d.string().regex(/^[0-9a-f]{40}$/i,"expected a commit sha"),Nn=d.object({id:d.string(),taskId:d.string(),projectId:d.string(),authorId:d.string(),headSha:d.string(),path:d.string().nullable(),side:ze.nullable(),lineStart:d.number().nullable(),lineEnd:d.number().nullable(),selectedText:d.string().nullable(),body:d.string(),resolution:Xe,resolvedBy:d.string().nullable(),resolvedAt:d.string().nullable(),revisionIteration:d.number().nullable(),createdAt:d.string(),updatedAt:d.string(),stale:d.boolean()}),Js=d.object({taskId:d.string(),headSha:d.string().nullable(),comments:d.array(Nn),visualContext:An.optional()}),Zs=d.object({headSha:Pn,body:d.string().min(1).max(1e4),path:d.string().min(1).max(1024).nullish(),side:ze.nullish(),lineStart:d.number().int().positive().nullish(),lineEnd:d.number().int().positive().nullish(),selectedText:d.string().max(1e4).nullish(),visualContext:Rn.optional()}).superRefine((e,t)=>{if(e.lineStart!=null&&(e.path==null||e.side==null))t.addIssue({code:d.ZodIssueCode.custom,path:["lineStart"],message:"a line comment needs both a path and a side"});if(e.lineEnd!=null&&(e.lineStart==null||e.lineEnd<e.lineStart))t.addIssue({code:d.ZodIssueCode.custom,path:["lineEnd"],message:"lineEnd must be >= lineStart"});if(e.side!=null&&e.path==null)t.addIssue({code:d.ZodIssueCode.custom,path:["side"],message:"a side needs a path"})}),Qs=d.object({resolution:Xe}),ei=d.object({headSha:Pn}),ti=d.object({taskId:d.string(),cycleId:d.string(),headSha:d.string(),commentIds:d.array(d.string()),staleSkipped:d.number(),feedback:d.string(),iteration:d.number(),started:d.boolean(),reason:d.string().nullable()});import{z as h}from"zod";var Mn=h.enum(["github","workspace"]),Je=h.object({path:h.string(),previousPath:h.string().nullable(),status:Se,additions:h.number().nullable(),deletions:h.number().nullable(),binary:h.boolean()}),On=h.object({sha:h.string(),subject:h.string(),at:h.string()}),de=h.object({ref:h.string(),sha:h.string().nullable()}),Ln=h.object({repoKey:h.string(),label:h.string(),base:de,head:de,files:h.array(Je),filesTruncated:h.boolean(),filesChanged:h.number(),additions:h.number(),deletions:h.number(),commits:h.array(On),unavailable:h.enum(["repository_unreachable"]).nullable()}),jn=h.object({taskId:h.string(),title:h.string(),repoKey:h.string(),files:h.array(Je),observedAt:h.string()}),ni=h.object({projectId:h.string(),source:Mn,environmentState:h.string().nullable(),observedAt:h.string(),repos:h.array(Ln),inFlight:h.array(jn)}),ri=h.object({repoKey:h.string(),path:h.string(),patch:h.string().nullable(),patchTruncated:h.boolean(),binary:h.boolean()}),oi=h.object({repoKey:h.string(),ref:de,paths:h.array(h.string()),truncated:h.boolean()}),si=h.object({error:h.string(),environmentState:h.string()}),ii=h.object({repoKey:h.string(),path:h.string(),ref:de,content:h.string().nullable(),truncated:h.boolean(),binary:h.boolean(),size:h.number().nullable()});var ve={"claude-opus-4-8":{provider:"anthropic",contextWindow:1e6,displayName:"Opus 4.8",tier:"frontier"},"claude-sonnet-5":{provider:"anthropic",contextWindow:1e6,displayName:"Sonnet 5",tier:"primary"},"claude-opus-4-7":{provider:"anthropic",contextWindow:200000,displayName:"Opus 4.7",tier:"frontier",picker:!1},"claude-opus-4-6":{provider:"anthropic",contextWindow:200000,displayName:"Opus 4.6",tier:"frontier",picker:!1},"claude-sonnet-4-6":{provider:"anthropic",contextWindow:200000,displayName:"Sonnet 4.6",tier:"primary",picker:!1},"claude-sonnet-4-5-20250929":{provider:"anthropic",contextWindow:200000,displayName:"Sonnet 4.5",tier:"primary",picker:!1},"claude-haiku-4-5":{provider:"anthropic",contextWindow:200000,displayName:"Haiku 4.5",tier:"fast"},"gpt-5.6-sol":{provider:"openai",contextWindow:1050000,displayName:"GPT-5.6 Sol",tier:"frontier"},"gpt-5.6-terra":{provider:"openai",contextWindow:1050000,displayName:"GPT-5.6 Terra",tier:"primary"},"gpt-5.6-luna":{provider:"openai",contextWindow:1050000,displayName:"GPT-5.6 Luna",tier:"fast"},"gpt-5.5":{provider:"openai",contextWindow:400000,displayName:"GPT-5.5",tier:"frontier",picker:!1},"gpt-5":{provider:"openai",contextWindow:256000,displayName:"GPT-5",tier:"frontier",picker:!1},"gpt-5-mini":{provider:"openai",contextWindow:128000,displayName:"GPT-5 Mini",tier:"fast",picker:!1},"gpt-4.1-mini":{provider:"openai",contextWindow:128000,displayName:"GPT-4.1 Mini",tier:"fast",picker:!1},"gemini-3.8-flash":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini 3.8 Flash",tier:"fast"},"gemini-3.6-flash":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini 3.6 Flash",tier:"fast",picker:!1},"gemini-3.5-flash":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini 3.5 Flash",tier:"fast",picker:!1},"gemini-2.5-pro":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini 2.5 Pro",tier:"primary",picker:!1},"gemini-embedding-2":{provider:"google_genai",contextWindow:8192,displayName:"Gemini Embedding 2",tier:"embedding",picker:!1},"grok-4.5":{provider:"openrouter",contextWindow:500000,displayName:"Grok 4.5",tier:"frontier"},"kimi-k3":{provider:"openrouter",contextWindow:1048576,displayName:"Kimi K3",tier:"primary"},"deepseek-v4-pro":{provider:"openrouter",contextWindow:1048576,displayName:"DeepSeek V4 Pro",tier:"primary"},"glm-5.3":{provider:"openrouter",contextWindow:1048576,displayName:"GLM 5.3",tier:"primary"},"qwen3.8-max":{provider:"openrouter",contextWindow:1e6,displayName:"Qwen 3.8 Max",tier:"primary"},auto:{provider:"openrouter",contextWindow:2000000,displayName:"Auto",tier:"primary"},"pareto-code":{provider:"openrouter",contextWindow:2000000,displayName:"Auto for coding",tier:"primary"},"opus-latest":{provider:"anthropic",contextWindow:1e6,displayName:"Claude Opus (Latest)",tier:"frontier"},"sonnet-latest":{provider:"anthropic",contextWindow:1e6,displayName:"Claude Sonnet (Latest)",tier:"primary"},"gemini-flash-latest":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini Flash (Latest)",tier:"fast"},"gpt-latest":{provider:"openai",contextWindow:1050000,displayName:"GPT (Latest)",tier:"frontier"},"whisper-1":{provider:"openrouter",contextWindow:0,displayName:"Whisper 1 (Speech-to-Text)",tier:"media",picker:!1},"voxtral-mini-tts":{provider:"openrouter",contextWindow:4096,displayName:"Voxtral Mini TTS (Text-to-Speech)",tier:"media",picker:!1},"seedream-4-5":{provider:"openrouter",contextWindow:4096,displayName:"Seedream 4.5 (Image)",tier:"media",picker:!1},"veo-3-1":{provider:"openrouter",contextWindow:0,displayName:"Veo 3.1 (Video)",tier:"media",picker:!1}};var ai=Object.keys(ve);var li={"claude-opus-4-8":"openrouter/anthropic/claude-opus-4.8","claude-sonnet-5":"openrouter/anthropic/claude-sonnet-5","claude-opus-4-7":"openrouter/anthropic/claude-opus-4.7","claude-opus-4-6":"openrouter/anthropic/claude-opus-4.6","claude-sonnet-4-6":"openrouter/anthropic/claude-sonnet-4.6","claude-sonnet-4-5-20250929":"openrouter/anthropic/claude-sonnet-4.5","claude-haiku-4-5":"openrouter/anthropic/claude-haiku-4.5","gpt-5.6-sol":"openrouter/openai/gpt-5.6-sol","gpt-5.6-terra":"openrouter/openai/gpt-5.6-terra","gpt-5.6-luna":"openrouter/openai/gpt-5.6-luna","gpt-5.5":"openrouter/openai/gpt-5.5","gpt-5":"openrouter/openai/gpt-5","gpt-5-mini":"openrouter/openai/gpt-5-mini","gpt-4.1-mini":"openrouter/openai/gpt-4.1-mini","gemini-3.8-flash":"openrouter/google/gemini-3.8-flash","gemini-3.6-flash":"openrouter/google/gemini-3.6-flash","gemini-3.5-flash":"openrouter/google/gemini-3.5-flash","gemini-2.5-pro":"openrouter/google/gemini-2.5-pro","gemini-embedding-2":"direct:google/gemini-embedding-2","grok-4.5":"openrouter/x-ai/grok-4.5","kimi-k3":"openrouter/moonshotai/kimi-k3","deepseek-v4-pro":"openrouter/deepseek/deepseek-v4-pro","glm-5.3":"openrouter/z-ai/glm-5.3","qwen3.8-max":"openrouter/qwen/qwen3.8-max",auto:"openrouter/openrouter/auto","pareto-code":"openrouter/openrouter/pareto-code","opus-latest":"openrouter/~anthropic/claude-opus-latest","sonnet-latest":"openrouter/~anthropic/claude-sonnet-latest","gemini-flash-latest":"openrouter/~google/gemini-flash-latest","gpt-latest":"openrouter/~openai/gpt-latest","whisper-1":"openrouter/openai/whisper-1","voxtral-mini-tts":"openrouter/mistralai/voxtral-mini-tts-2603","seedream-4-5":"openrouter/bytedance-seed/seedream-4.5","veo-3-1":"openrouter/google/veo-3.1"};var H="◆",ci=(()=>{let e={};for(let t of Object.keys(ve)){let n=ve[t];e[t]=n.displayName,e[li[t]]=n.displayName,e[`${n.provider}:${t}`]=n.displayName}return e})();function Ee(e){if(!e)return e;let n=ci[e]??e.split(/[/:]/).pop()??e;return`${H} ${n}`}var Ze={"claude-code":{id:"claude-code",displayName:"Claude Code",description:"Anthropic coding CLI. Flagship, always installed.",driverKind:"external-acp",capabilities:["structured-result","usage-report","model-select"],credentials:{required:["ANTHROPIC_API_KEY"],anyOf:[]},supportedPlatforms:["linux"],resultProtocol:{kind:"hlix-result-line",version:1},modelSupport:{selection:"runtime",effort:!1},available:!0},"openai-agents":{id:"openai-agents",displayName:"OpenAI Agents SDK",description:"Model-agnostic agent SDK. Not yet available for running tasks.",driverKind:"external-acp",capabilities:["structured-result","usage-report","model-select"],credentials:{required:[],anyOf:["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY"]},supportedPlatforms:["linux"],resultProtocol:{kind:"hlix-result-line",version:1},modelSupport:{selection:"runtime",effort:!1},available:!1},codex:{id:"codex",displayName:"Codex",description:"OpenAI coding CLI. Installed on demand.",driverKind:"external-acp",capabilities:["structured-result","usage-report","model-select"],credentials:{required:["OPENAI_API_KEY"],anyOf:[]},supportedPlatforms:["linux"],resultProtocol:{kind:"hlix-result-line",version:1},modelSupport:{selection:"runtime",effort:!1},available:!0},aider:{id:"aider",displayName:"Aider",description:"Model-agnostic coding CLI. Not yet available for running tasks.",driverKind:"external-acp",capabilities:["structured-result","model-select"],credentials:{required:[],anyOf:["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY"]},supportedPlatforms:["linux"],resultProtocol:{kind:"hlix-result-line",version:1},modelSupport:{selection:"runtime",effort:!1},available:!1},"cursor-agent":{id:"cursor-agent",displayName:"Cursor Agent",description:"Cursor headless coding CLI. Installed on demand.",driverKind:"external-acp",capabilities:["structured-result","usage-report"],credentials:{required:["CURSOR_API_KEY"],anyOf:[]},supportedPlatforms:["linux"],resultProtocol:{kind:"hlix-result-line",version:1},modelSupport:{selection:"none",effort:!1},available:!0},hlix:{id:"hlix",displayName:"Hlix",description:"Our own coding agent, built into hlix and run by the platform.",driverKind:"native",capabilities:["structured-result"],credentials:{required:[],anyOf:[]},supportedPlatforms:["linux"],resultProtocol:{kind:"native-runner",version:1},modelSupport:{selection:"orchestration",effort:!1},available:!0}},Qe=Object.keys(Ze),we=Object.values(Ze),di=we.filter(({driverKind:e})=>e==="external-acp").map(({id:e})=>e),Dn=we.filter(({available:e,driverKind:t})=>e&&t==="external-acp"),et=Dn.map(({id:e})=>e),$n=we.filter(({available:e})=>e),Fn=$n.map(({id:e})=>e),tt="hlix";var Hn=["chat","kanban","linear","github","api"];var nt={chat:{enabledByDefault:!0,triage:!0,kind:"native",label:"Chat"},kanban:{enabledByDefault:!0,triage:!0,kind:"native",label:"Board"},linear:{enabledByDefault:!0,triage:!0,kind:"external",label:"Linear"},github:{enabledByDefault:!0,triage:!0,kind:"external",label:"GitHub issues"},api:{enabledByDefault:!0,triage:!0,kind:"native",label:"API"}};function Un(e){return Hn.filter((t)=>nt[t].kind===e)}var ui=Un("external"),mi=Un("native");import{z as p}from"zod";var Bn=p.enum(Qe),Gn=p.enum(et),Wn=p.object({node:p.string().optional(),python:p.string().optional(),bun:p.string().optional(),playwright:p.boolean().optional()}).partial(),Yn=p.object({agents:p.array(Gn).optional(),toolchain:Wn.optional(),aptPackages:p.array(p.string()).optional(),setup:p.string().optional(),hash:p.string().optional(),imageTag:p.string().nullable().optional(),linearProjectId:p.string().optional(),linearTeamId:p.string().optional()}).partial(),Si=p.object({owner:p.string(),name:p.string(),cloneUrl:p.string(),defaultBranch:p.string()}),Kn=p.object({key:p.string(),cloneUrl:p.string().nullable(),owner:p.string().nullable(),name:p.string().nullable(),defaultBranch:p.string(),setupCommand:p.string().nullable().optional(),verifyCommand:p.string().nullable().optional()});var Vn=p.object({name:p.string(),skillSlugs:p.array(p.string()),agentSlugs:p.array(p.string())}),qn=p.object({path:p.string(),content:p.string()}),zn=p.object({vars:p.record(p.string(),p.string()).default({}),files:p.array(qn).optional(),skills:p.array(p.string()).optional(),mcpServers:p.array(p.unknown()).optional(),managedPaths:p.array(p.string().refine((e)=>e.length>0&&e===e.normalize("NFC")&&!e.startsWith("/")&&!e.includes("\\")&&!/[\u0000-\u001f\u007f]/.test(e)&&e.split("/").every((t)=>t&&t!=="."&&t!==".."),"managed path must be a canonical project-relative path")).optional()}),Xn=p.object({path:p.string(),kind:p.enum(["dotenv","credential","detected-content"]),contentBase64:p.string(),size:p.number().int().nonnegative(),sha256:p.string().regex(/^[0-9a-f]{64}$/)}),Jn=p.object({taskId:p.string(),cycleId:p.string(),threadId:p.string(),organizationId:p.string().optional(),projectId:p.string().optional(),description:p.string(),reviewFeedback:p.string().optional(),iteration:p.number().default(0),operationId:p.string().min(1).optional(),repo:Kn.nullable().default(null),verifyCommand:p.string().nullable().optional(),branch:p.string(),baseBranch:p.string(),githubToken:p.string().optional(),snapshotKey:p.string().optional(),aiGatewayUrl:p.string().optional(),secrets:p.record(p.string(),p.string()),packs:p.array(Vn),systemPrompt:p.string().optional(),timeoutSeconds:p.number().default(1800),resultToken:p.string().min(1).optional(),agent:Bn.default(tt),agentEnv:p.record(p.string(),p.string()).optional(),projectRuntime:Yn.optional(),environment:zn.optional(),protectedFiles:p.array(Xn).optional()}),vi=p.enum(["acp"]),Ei=p.enum(["builder","desktop","e2e"]),wi=p.object({batchId:p.string(),tasks:p.array(Jn).min(1).max(20)}),Zn=p.object({inputTokens:p.number(),outputTokens:p.number(),costUsd:p.number()}),_i=p.object({taskId:p.string(),token:p.string().optional(),status:p.enum(["success","failed"]),cost:Zn.optional(),model:p.string().optional(),error:p.string().optional()});import{z as R}from"zod";var Ii=R.discriminatedUnion("type",[R.object({type:R.literal("text"),text:R.string()}),R.object({type:R.literal("reasoning"),text:R.string()}),R.object({type:R.literal("tool"),toolCallId:R.string().min(1),toolName:R.string().min(1),state:R.enum(["pending","done","error"]),input:R.unknown().optional(),output:R.unknown().optional(),error:R.string().optional()})]);import{SelectList as Ci}from"@earendil-works/pi-tui";var rt=(e)=>e;function _e(e){return(t)=>t?`\x1B[${e}m${t}\x1B[0m`:t}var re={gold:{rgb:[255,204,0],cube:220},vermilion:{rgb:[230,0,23],cube:160},teal:{rgb:[54,145,119],cube:66},paper:{rgb:[229,230,232],cube:188},slate:{rgb:[151,153,157],cube:103}};function Ie(e=process.env,t=process.stdout.isTTY===!0){if(e.NO_COLOR!==void 0&&e.NO_COLOR!=="")return"none";let n=e.FORCE_COLOR!==void 0&&e.FORCE_COLOR!=="";if(!t&&!n)return"none";let r=(e.COLORTERM??"").toLowerCase();if(r==="truecolor"||r==="24bit")return"truecolor";if(/-direct\b/.test(e.TERM??""))return"truecolor";return"ansi256"}var oe=(e,t)=>{if(t==="none")return rt;if(t==="truecolor")return _e(`38;2;${e.rgb[0]};${e.rgb[1]};${e.rgb[2]}`);return _e(`38;5;${e.cube}`)};function Ce(e=Ie()){return{brand:oe(re.gold,e),muted:e==="none"?rt:_e("2"),user:oe(re.paper,e),alert:oe(re.vermilion,e),ok:oe(re.teal,e),added:oe(re.teal,e),removed:oe(re.vermilion,e)}}function se(e){return{selectedPrefix:e.brand,selectedText:e.brand,description:e.muted,scrollInfo:e.muted,noMatch:e.muted}}function Qn(e){return{borderColor:e.muted,selectList:se(e)}}function er(e,t=Ie()){let n=(r)=>t==="none"?rt:_e(r);return{heading:e.brand,link:e.ok,linkUrl:e.muted,code:e.brand,codeBlock:e.user,codeBlockBorder:e.muted,quote:e.muted,quoteBorder:e.muted,hr:e.muted,listBullet:e.brand,bold:n("1"),italic:n("3"),strikethrough:n("9"),underline:n("4")}}var Ti=12;function Ri(e){let t=/^(.*?)\(([^()]*)\)\s*$/.exec(e);if(!t)return Ee(e);let n=(t[1]??"").trim(),r=Ee(t[2]??"").slice(H.length).trim();return n?`${H} ${n} (${r})`:`${H} ${r}`}function ot(e){let t=new Set,n=[],r=(o,s)=>{if(t.has(o))return;t.add(o),n.push({id:o,label:Ri(s)})};for(let o of e.served??[])r(`${e.providerName}/${o.id}`,o.name);for(let o of e.userModelIds??[]){if(o.startsWith(`${e.providerName}/`))continue;r(o,o)}return n}function rr(e){let t=tr(e.cwd)?"project":"global";return nr({key:"model",value:e.modelId,scope:t,cwd:e.cwd,env:e.env})}function or(e){let t=e.colors??Ce(),n=e.entries.map((i)=>({value:i.id,label:i.label})),r=new Ci(n,Ti,se(t)),o=e.entries.findIndex((i)=>i.id===e.current);if(o>=0)r.setSelectedIndex(o);let s=e.tui.showOverlay(r,{width:"60%",maxHeight:"60%"}),l=()=>{s.hide(),e.tui.requestRender()};r.onSelect=(i)=>{l();let c=e.entries.find((a)=>a.id===i.value);if(c)e.onPick(c)},r.onCancel=()=>{l(),e.onCancel?.()},s.focus()}import{Markdown as ki,truncateToWidth as U,wrapTextWithAnsi as st}from"@earendil-works/pi-tui";function sr(e,t){if(e.length>600||t.length>600)return[...e.map((c)=>({kind:"del",text:c})),...t.map((c)=>({kind:"add",text:c}))];let n=e.length,r=t.length,o=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=n-1;c>=0;c-=1)for(let a=r-1;a>=0;a-=1)o[c][a]=e[c]===t[a]?o[c+1][a+1]+1:Math.max(o[c+1][a],o[c][a+1]);let s=[],l=0,i=0;while(l<n&&i<r)if(e[l]===t[i])s.push({kind:"same",text:e[l]}),l+=1,i+=1;else if(o[l+1][i]>=o[l][i+1])s.push({kind:"del",text:e[l]}),l+=1;else s.push({kind:"add",text:t[i]}),i+=1;while(l<n)s.push({kind:"del",text:e[l++]});while(i<r)s.push({kind:"add",text:t[i++]});return s}function ir(e,t,n={}){let r=n.context??2,o=sr(e.split(`
22
+ `),t.split(`
23
+ `)),s=new Set;o.forEach((a,m)=>{if(a.kind==="same")return;for(let u=m-r;u<=m+r;u+=1)if(u>=0&&u<o.length)s.add(u)});let l=[],i=0,c=()=>{if(i===0)return;l.push(` … ${i} unchanged line${i===1?"":"s"}`),i=0};return o.forEach((a,m)=>{if(!s.has(m)){i+=1;return}c(),l.push(`${a.kind==="add"?"+":a.kind==="del"?"-":" "} ${a.text}`)}),c(),l}function ar(e,t){let n=sr(e.split(`
24
+ `),t.split(`
25
+ `)),r=n.filter((s)=>s.kind==="add").length,o=n.filter((s)=>s.kind==="del").length;if(r===0&&o===0)return"";return[r>0?`+${r}`:"",o>0?`−${o}`:""].filter(Boolean).join(" ")}var Ai={user:"›",assistant:" ",tool:"⏺",command:"▸",subagent:"↳",notice:"·"},it=8;function lr(e,t,n){let r=`┌ ${e} `,o=Math.max(0,t-r.length);return n(U(`${r}${"─".repeat(o)}`,t))}var Pi=(e,t)=>t(U(`└${"─".repeat(Math.max(0,e-1))}`,e));function pe(e,t,n,r){let o=Math.max(1,t-2),s=[];for(let l of e){let i=l===""?[""]:st(l,o);for(let c of i)s.push(U(`${r("│")} ${n(c)}`,t))}return s}function Ni(e){let t=e.tool;if(!t)return"";let n=[],r=t.args??{};if(typeof r.old_string==="string"&&typeof r.new_string==="string"){let o=ar(r.old_string,r.new_string);if(o)n.push(o)}if(t.durationMs!==void 0)n.push(`${(t.durationMs/1000).toFixed(1)}s`);if(t.exitCode!==void 0&&t.exitCode!==0)n.push(`exit ${t.exitCode}`);return n.join(" · ")}function Mi(e){switch(e.tool?.state){case"running":return"⏺";case"awaiting":return"?";case"declined":return"⊘";case"error":return"✗";default:return"✓"}}function Oi(e){let t=e.tool;if(!t)return[];let n=t.args??{};if(typeof n.old_string==="string"&&typeof n.new_string==="string")return ir(n.old_string,n.new_string);let r=(t.result??"").trimEnd();return r===""?[]:r.split(`
26
+ `)}function at(e,t){let n=e-t;return`… ${n} more line${n===1?"":"s"} — ctrl-o to expand`}function cr(e,t){let{width:n,colors:r}=t;switch(e.kind){case"assistant":return dr(e.text,n,r);case"command":return ji(e,t);case"tool":return Di(e,t);case"subagent":return Fi(e,t);default:{let o=e.kind==="user"?r.user:e.error?r.alert:r.muted,s=e.error?"!":Ai[e.kind];return Li(e.text,s,n,o)}}}function dr(e,t,n){let r=Math.max(8,t-2);return new ki(e,0,0,er(n)).render(r).map((s)=>U(` ${s}`,t))}function Li(e,t,n,r){let o=Math.max(1,n-2),s=[];for(let l of e.split(`
27
+ `)){let i=l===""?[""]:st(l,o);for(let c of i){let a=s.length===0?`${t} `:" ";s.push(U(`${a}${r(c)}`,n))}}return s}function ji(e,t){let{width:n,colors:r}=t,o=e.error?r.alert:r.muted,s=e.text===""?["(no output)"]:e.text.split(`
28
+ `),l=e.expanded===!0?s:s.slice(0,it*3),i=pe(l,n,e.error?r.alert:r.user,o);return[lr(e.title??"command",n,o),...i,...l.length<s.length?pe([at(s.length,l.length)],n,r.muted,o):[],Pi(n,o)]}function Di(e,t){let{width:n,colors:r}=t,o=e.tool,s=Mi(e),l=e.error?r.alert:o?.state==="running"?r.muted:r.ok,i=Ni(e),c=`${s} ${e.text}`,a=n-c.length-i.length-1,m=i&&a>0?U(`${l(c)}${" ".repeat(a)}${r.muted(i)}`,n):U(l(c),n);if(o?.state==="running"||o?.state==="awaiting")return[m];let u=Oi(e);if(u.length===0)return[m];let f=e.expanded===!0?u:u.slice(0,it);return[m,...$i(f,n,r),...f.length<u.length?pe([at(u.length,f.length)],n,r.muted,r.muted):[]]}function $i(e,t,n){let r=Math.max(1,t-2),o=[];for(let s of e){let l=s.startsWith("+")?n.added:s.startsWith("-")?n.removed:n.muted;for(let i of s===""?[""]:st(s,r))o.push(U(`${n.muted("│")} ${l(i)}`,t))}return o}function Fi(e,t){let{width:n,colors:r}=t,o=e.subagent;if(!o)return[];let s=e.error?r.alert:r.muted,l=o.state==="running"?"↳":e.error?"✗":"✓",i=o.durationMs!==void 0?` · ${(o.durationMs/1000).toFixed(1)}s`:"",c=U(`${(e.error?r.alert:r.brand)(`${l} ${o.agentType}`)}${r.muted(`${i}${o.tools.length>0?` · ${o.tools.length} tool calls`:""}`)}`,n),a=[o.task];if(o.tools.length>0)a.push(`tools: ${[...new Set(o.tools)].join(", ")}`);if(o.state!=="running"&&o.result){let m=o.result.split(`
29
+ `),u=e.expanded===!0?m:m.slice(0,it);if(a.push("",...u),u.length<m.length)a.push(at(m.length,u.length))}return[c,...pe(a,n,r.muted,s)]}function pr(e,t){let{width:n,colors:r}=t,o=e.args??{},s=[o.command,o.path,o.pattern,o.query,o.task].find((i)=>typeof i==="string"&&i!==""),l=A(e.toolName);return[lr(`Approve ${l}`,n,r.alert),...pe(s?[s]:["(no arguments)"],n,r.user,r.alert)]}var ue="yolo";function Hi(e,t){if(t<=0)return`${Math.round(e/1000)}k`;return`${Math.round(e/t*100)}% of ${Math.round(t/1000)}k`}function Ui(e){return e>0&&e<0.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Bi=4,Gi=["cost","total_cost","costUsd"];function Te(e){let t=e?.raw;for(let n=0;n<Bi&&t&&typeof t==="object";n+=1){for(let r of Gi){let o=t[r];if(typeof o==="number"&&Number.isFinite(o)&&o>0)return o}t=t.raw}return}var Wi=(e)=>e.startsWith(H)?e:`${H} ${e}`;function Yi(e){let t=[...e.yolo?[ue]:[],e.sandbox,e.harness];if(e.mode)t.push(e.mode);if(e.model)t.push(Wi(e.model));if(e.workspace)t.push(e.workspace);if(e.branch)t.push(e.branch);if(e.context)t.push(Hi(e.context.used,e.context.total));if(e.costUsd!==void 0)t.push(Ui(e.costUsd));if(e.memory)t.push(e.memory);if(e.warning)t.push(e.warning);return t}function ur(e,t){let n=Yi(e).join(" · ");if(t===void 0||t<=0||n.length<=t)return n;return t<=1?n.slice(0,t):`${n.slice(0,t-1)}…`}var Ki="subagent",fr=()=>({entries:[],busy:!1,status:"",approval:null});function Re(e){let t=e?.content,n=t?.parts;if(!Array.isArray(n)){let r=t?.content;return typeof r==="string"?r:""}return n.filter((r)=>{let o=r;return o.type==="text"&&typeof o.text==="string"}).map((r)=>r.text).join("")}function mr(e,t){let n=t??{},r=n.path??n.command??n.pattern??n.query;return typeof r==="string"?`${A(e)} ${r}`:A(e)}function gr(e){let t=e===void 0?null:/^Exit code: (\d+)$/m.exec(e);return t?Number(t[1]):void 0}function Vi(e){if(typeof e==="string")return e;if(e===void 0||e===null)return"";let t=e.content;if(Array.isArray(t))return t.map((n)=>{let r=n;return r.type==="text"&&typeof r.text==="string"?r.text:""}).filter((n)=>n!=="").join(`
30
+ `);try{return JSON.stringify(e,null,2)}catch{return String(e)}}var qi={om_observation_start:"remembering…",om_observation_end:"",om_reflection_start:"condensing memory…",om_reflection_end:"",compaction_start:"compacting…",compaction_end:""},zi={thread_created:()=>"New conversation.",info:(e)=>typeof e.message==="string"?e.message:null};function hr(e,t){let n=(i,c)=>{let a=e.entries.findIndex((u)=>u.id===i),m=[...e.entries];if(a<0)m.push(c);else m[a]=c;return{...e,entries:m}},r=(i)=>({...e,entries:[...e.entries,i]}),o=(i)=>e.entries.find((c)=>c.id===i),s=(i)=>`tool:${String(i)}`,l=(i)=>`sub:${String(i)}`;switch(t.type){case"agent_start":return{...e,busy:!0};case"agent_end":return{...e,busy:!1,status:""};case"message_start":case"message_update":case"message_end":{let i=t.message;if(!i?.id)return e;let c=Re(i);if(!c)return e;let a=`msg:${i.id}`;if(o(a)?.text===c)return e;return n(a,{kind:i.role==="user"?"user":"assistant",id:a,text:c})}case"tool_start":{if(t.toolName===Ki)return e;let i=s(t.toolCallId),c=A(t.toolName);return n(i,{kind:"tool",id:i,text:mr(t.toolName,t.args),tool:{name:c,args:t.args,state:"running"}})}case"tool_approval_required":{let i=s(t.toolCallId),c=o(i),a={toolCallId:String(t.toolCallId),toolName:t.toolName,args:t.args},m=c?.tool?{...c,tool:{...c.tool,state:"awaiting"}}:{kind:"tool",id:i,text:mr(t.toolName,t.args),tool:{name:A(t.toolName),args:t.args,state:"awaiting"}};return{...n(i,m),approval:a}}case"tool_end":{let i=s(t.toolCallId),c=o(i);if(!c?.tool)return e;let a=t.denied===!0,m=t.isError===!0,u=Vi(t.result),f=n(i,{...c,error:m||a,tool:{...c.tool,result:u,state:a?"declined":m?"error":"done",...gr(u)!==void 0?{exitCode:gr(u)}:{}}});return e.approval?.toolCallId===String(t.toolCallId)?{...f,approval:null}:f}case"subagent_start":{let i=l(t.toolCallId);return n(i,{kind:"subagent",id:i,title:String(t.agentType),text:String(t.task??""),subagent:{agentType:String(t.agentType),task:String(t.task??""),tools:[],state:"running"}})}case"subagent_tool_start":{let i=l(t.toolCallId),c=o(i);if(!c?.subagent)return e;return n(i,{...c,subagent:{...c.subagent,tools:[...c.subagent.tools,A(t.subToolName)]}})}case"subagent_end":{let i=l(t.toolCallId),c=o(i);if(!c?.subagent)return e;let a=t.isError===!0;return n(i,{...c,error:a,subagent:{...c.subagent,state:a?"error":"done",result:String(t.result??""),...typeof t.durationMs==="number"?{durationMs:t.durationMs}:{}}})}case"error":{let i=t.error;return r({kind:"notice",id:`error:${e.entries.length}`,text:i?.message??"The turn failed.",error:!0})}default:{let i=qi[t.type];if(i!==void 0)return{...e,status:i};let c=zi[t.type]?.(t);return c===null||c===void 0?e:r({kind:"notice",id:`${t.type}:${e.entries.length}`,text:c})}}}function yr(e){return{kind:"command",id:`cmd:${e.index}`,title:`/${e.name}`,text:e.output,...e.failed?{error:!0}:{}}}import{readdirSync as Xi,readFileSync as Ji}from"node:fs";import{basename as Zi,join as Qi}from"node:path";var ea=(e)=>e.split(" ").join("-");function ta(e,t,n){let r=e.name.split(" "),o=t.trim();if(o)r.push(...o.split(/\s+/));return r.push("--cwd",n),r}var br="Project prompt";function na(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(e);if(!t)return{description:br,body:e};return{description:/^description:[ \t]*(.+)$/m.exec(t[1]??"")?.[1]?.trim()||br,body:e.slice(t[0].length).replace(/^(?:[ \t]*\r?\n)+/,"")}}function ra(e){let t=new Map;for(let n of e){let r;try{r=Xi(n)}catch{continue}for(let o of r){if(!o.endsWith(".md"))continue;try{t.set(Zi(o,".md"),na(Ji(Qi(n,o),"utf8")))}catch{continue}}}return t}function oa(e,t){let n=t.trim();if(e.includes("$ARGUMENTS"))return e.split("$ARGUMENTS").join(n);return n?`${e.trimEnd()}
31
+
32
+ ${n}`:e}function xr(e,t){return async(n,r)=>{let o="",s=(i)=>{o+=i},l=await ie([e],ta(e,n,r),{stdout:s,stderr:s,env:t});return{lines:[],output:o.trimEnd()||`exit ${l}`,...l===0?{}:{failed:!0}}}}var ke={lines:["This command needs a live session."]};async function Sr(e,t,n,r,o){let s=o.find((m)=>m.name==="config set");if(!s)return{ok:!1,message:`This build has no \`config set\`, so ${e} was not written.`};let l="",i=(m)=>{l+=m},c=await ie([s],["config","set",e,t,"--cwd",n],{stdout:i,stderr:i,env:r}),a=l.trim();if(c===0)return{ok:!0,message:a||`${e} is ${t}.`};return{ok:!1,message:[`${e} was NOT written: ${a.replace(/^error:\s*/,"")||"config set failed."}`,`To set it for every project: \`hlix config set ${e} ${t} --global\`.`].join(`
33
+ `)}}function wr(e={}){let t=e.env??process.env,n=e.shell,r=new Map,o=(a)=>r.set(a.name,a),s=e.commands??me;for(let a of s)o({name:ea(a.name),description:a.summary,handler:xr(a,t)});let l=(a,m,u)=>{let f=s.find((y)=>y.name===m);if(f)o({name:a,description:u,handler:xr(f,t)})};for(let[a,m]of ra(e.promptFiles??[])){if(r.has(a))continue;o({name:a,description:m.description,prompt:(u)=>oa(m.body,u),handler:()=>({lines:[]})})}l("config","config list","Show this folder's settings and where each came from"),l("secrets","secrets list","List this project's stored secrets, masked"),l("follow","tasks watch","Watch a task the platform is running"),o({name:"model",description:"Pick the model this session runs on",handler:()=>(n?.openModelPicker?.(),{lines:n?.openModelPicker?[]:["No model picker in this mode."]})}),o({name:"sandbox",description:"Where this session's files and commands run",handler:async(a,m)=>{let u=n?.facts;if(!u)return{lines:["Sandbox not resolved."]};let f=a.trim(),y=async(w)=>{let E=await Sr("sandbox",w,m,t,s);return{lines:[],output:[u.sandboxLine,E.ok?`${E.message} This session keeps ${u.sandbox}; restart to run in ${w}.`:E.message].join(`
34
+ `),...E.ok?{}:{failed:!0}}};if(f){if(!J.includes(f))return{lines:[`/sandbox must name one of ${J.join(", ")}.`]};return y(f)}if(!n?.openPicker)return{lines:[],output:u.sandboxLine};return n.openPicker({title:"Sandbox",current:u.sandbox,choices:J.map((w)=>({value:w,label:w,description:sa[w]})),apply:y}),{lines:[]}}}),o({name:"harness",description:"Show or change which coder does the work",handler:async(a,m)=>{let u=n?.facts;if(!u)return{lines:["Harness not resolved."]};let f=u.harnessModesBuilt?n?.session?.mode.get()??u.harness:u.harness,y=async(E)=>{let _=je({requested:E,current:f,available:u.availableHarnesses,sandbox:u.sandbox,sandboxLine:u.sandboxLine,modesBuilt:u.harnessModesBuilt});if(_.action==="mode"&&n?.session)await n.session.mode.switch({modeId:_.harness}),n.setFact?.({harness:_.harness,mode:_.harness});if(_.action==="preference"){if(!n?.setProjectHarness)return{lines:["This folder is not bound to a hlix project, so there is no project preference to write. Run `hlix init` or pass --project <id>."]};await n.setProjectHarness(_.harness),n.setFact?.({harness:_.harness})}let M=_.action==="restart"?await Sr("harness",E,m,t,s):null;return{lines:[],output:M?`${_.message}
35
+ ${M.message}`:_.message,...M&&!M.ok?{failed:!0}:{}}},w=a.trim();if(w)return y(w);if(!n?.openPicker)return{lines:[],output:`harness: ${f}`};return n.openPicker({title:"Harness",current:f,choices:B.map((E)=>({value:E,label:E,description:u.availableHarnesses.includes(E)?E==="hlix"?"Our own coder. The default.":"Installed on this machine.":"Not installed here."})),apply:y}),{lines:[]}}}),o({name:"new",description:"Start a new conversation in this folder",handler:async()=>{if(!n?.session)return ke;return await n.session.thread.create(),{lines:[]}}}),o({name:"threads",description:"List this folder's conversations, newest first",handler:async(a)=>{if(!n?.session)return ke;let m=a.trim();if(m)return await n.session.thread.switch({threadId:m}),{lines:[],output:`Switched to thread ${m}.`};let u=vr(await n.session.thread.list());if(u.length===0)return{lines:[],output:"No conversations here yet."};let f=n.session.thread.getId();return{lines:[],output:u.map((y)=>Er(y,f)).join(`
36
+ `)}}}),o({name:"resume",description:"Pick an earlier conversation in this folder and continue it",handler:async()=>{if(!n?.session)return ke;let a=vr(await n.session.thread.list());if(a.length===0)return{lines:[],output:"No conversations here yet."};let m=n.session.thread.getId();if(!n.openPicker)return{lines:[],output:a.map((u)=>Er(u,m)).join(`
37
+ `)};return n.openPicker({title:"Resume",...m?{current:m}:{},choices:a.map((u)=>({value:u.id,label:u.title?.trim()||"(untitled)",description:`${u.id} ${_r(u.updatedAt)}`})),apply:async(u)=>(await n.session?.thread.switch({threadId:u,emitEvent:!0}),{lines:[],output:`Resumed ${u}.`})}),{lines:[]}}}),o({name:"compact",description:"Condense this conversation into memory now",handler:async()=>{if(!n?.compact)return ke;return{lines:[],output:await n.compact()}}}),o({name:"log",description:"Show what this session's libraries logged",handler:()=>{if(!n?.log)return{lines:["No log in this mode."]};let a=n.log.tail(200);return{lines:[],output:a.length===0?`Nothing logged this session.
38
+ ${n.log.path}`:[...a,"",n.log.path].join(`
39
+ `)}}}),o({name:"rules",description:"Show the user and project rules this session loaded",handler:()=>{if(!n?.rules)return{lines:["Rules not resolved."]};return{lines:[],output:n.rules()}}}),o({name:"yolo",description:"Run without asking for approval — toggles",handler:(a)=>{if(!n?.yolo)return{lines:["Approvals are not resolved in this mode."]};let m=a.trim().toLowerCase(),u=m===""?!n.yolo.get():!["off","false","0","no"].includes(m);return n.yolo.set(u),n.setFact?.({yolo:u}),{lines:[],output:u?"yolo is ON — every tool runs without asking, including writes, commands and hlix calls. /yolo again to turn it off.":"yolo is off. Writes, commands and hlix calls ask again."}}}),o({name:"help",description:"List the commands this terminal knows",handler:()=>({lines:[],output:[...r.values()].map((a)=>`/${a.name.padEnd(22)} ${a.description}`).sort().join(`
40
+ `)})});let i={name:"exit",description:"Leave Hlix Code",handler:()=>({lines:[],quit:!0})};o(i),o({...i,name:"quit"});let c=r.get("standards");if(c&&n?.mcp)o({...c,handler:async(a,m)=>{let u=await c.handler(a,m),f=n.mcp?.()??[];if(f.length===0)return u;return{...u,output:[u.output??"","MCP servers (this session)",...f.map((y)=>` ${y}`)].join(`
41
+ `).trim()}}});return r}var sa={cloud:"The project's own Coding Workspace. Shared with your team.",docker:"A container on this machine, with this folder mounted.",local:"Directly on this machine."};function vr(e){return[...e].sort((t,n)=>(n.updatedAt?.getTime()??0)-(t.updatedAt?.getTime()??0))}function _r(e,t=new Date){if(!e)return"no activity";let n=Math.floor((t.getTime()-e.getTime())/60000);if(n<1)return"just now";if(n<60)return`${n}m ago`;let r=Math.floor(n/60);if(r<24)return`${r}h ago`;if(r<48)return"yesterday";return e.toISOString().slice(0,10)}var Er=(e,t)=>`${e.id===t?"›":" "} ${(e.title?.trim()||"(untitled)").padEnd(40)} ${_r(e.updatedAt)}`;function Ir(e){if(!e.startsWith("/"))return{kind:"prompt",name:"",args:e};let t=e.slice(1),n=t.indexOf(" ");return n<0?{kind:"slash",name:t,args:""}:{kind:"slash",name:t.slice(0,n),args:t.slice(n+1)}}function Cr(e,t){let n=e.args.trimStart(),r=n.indexOf(" "),o=r<0?n:n.slice(0,r);if(o==="")return e;let s=`${e.name}-${o}`;if(!t.has(s))return e;return{kind:e.kind,name:s,args:r<0?"":n.slice(r+1)}}class Rr{colors;state=fr();expanded=new Set;constructor(e){this.colors=e}render(e){return this.state.entries.flatMap((t)=>[...cr(this.expanded.has(t.id)?{...t,expanded:!0}:t,{width:e,colors:this.colors}),""])}lastCollapsible(){return[...this.state.entries].reverse().find((e)=>e.kind==="tool"||e.kind==="command"||e.kind==="subagent")}invalidate(){}}class kr{colors;text="";constructor(e){this.colors=e}render(e){return this.text===""?[]:[this.colors.muted(lt(`· ${this.text}`,e))]}invalidate(){}}class Ar{colors;facts=null;constructor(e){this.colors=e}render(e){if(!this.facts)return[];let t=ur(this.facts,e);if(this.facts.yolo!==!0||!t.startsWith(ue))return[this.colors.muted(t)];return[`${this.colors.alert(ue)}${this.colors.muted(t.slice(ue.length))}`]}invalidate(){}}class Pr{header=()=>[];body=null;open(e,t){this.header=e,this.body=t}close(){this.header=()=>[],this.body=null}render(e){if(!this.body)return[];return[...this.header(e),...this.body.render(e),""]}handleInput(e){this.body?.handleInput?.(e)}invalidate(){this.body?.invalidate()}}async function Nr(e){let t=Ce(Ie(e.env)),n=e.tui??new ca(new aa),r=new Rr(t),o=new kr(t),s=new Pr,l=new Ar(t),i={...e.facts};l.facts=i;let c=0,a=()=>n.requestRender(),m=(g)=>{r.state={...r.state,entries:[...r.state.entries,g]},a()},u=(g)=>{m({kind:"notice",id:`warn:${c++}`,text:g,error:!0})},f=(g)=>{m({kind:"notice",id:`say:${c++}`,text:g})},y=(g,b)=>{for(let x of b.lines)u(x);if(b.output===void 0)return;m(yr({name:g,output:b.output,index:c++,...b.failed?{failed:!0}:{}}))},w=new ia(n,Qn(t)),E=()=>{s.close(),n.setFocus(w),n.requestRender()},_=(g)=>{let{content:b,files:x,notes:S}=Sn(g,e.cwd);m({kind:"user",id:`you:${c++}`,text:g});for(let C of S)u(C);e.session.sendMessage({content:b,...x.length>0?{files:x}:{}}).catch((C)=>{u(C instanceof Error?C.message:String(C))})},M=(g)=>{let b=g.choices.map((S)=>({value:S.value,label:S.value===g.current?`${S.label} (current)`:S.label,...S.description?{description:S.description}:{}})),x=new Tr(b,Math.min(b.length,8),se(t));x.onSelect=(S)=>{E(),Promise.resolve(g.apply(S.value)).then((C)=>y(g.title.toLowerCase(),C)).catch((C)=>{u(`${g.title}: ${C instanceof Error?C.message:String(C)}`)})},x.onCancel=E,s.open((S)=>[t.brand(lt(g.title,S))],x),n.setFocus(s),n.requestRender()},O=(g,b)=>{let x=e.commands.get(g);if(!x){u(`Unknown command /${g}. Try /help.`);return}if(x.prompt){_(x.prompt(b));return}Promise.resolve(x.handler(b,e.cwd)).then((S)=>{if(y(g,S),S.quit)n.stop()}).catch((S)=>{u(`/${g} failed: ${S instanceof Error?S.message:String(S)}`)})},ee=()=>{if(e.models.length===0){u("No models to choose from. Run `hlix auth login`.");return}or({tui:n,entries:e.models,...i.model?{current:i.model}:{},colors:t,onPick:(g)=>{(async()=>{try{await e.session.model.switch({modelId:g.id});let b=rr({modelId:g.id,cwd:e.cwd,env:e.env});i.model=g.label,e.onModelPicked?.(g),f(`Model is ${g.label} — written to ${b}.`)}catch(b){u(`Could not switch model: ${b instanceof Error?b.message:String(b)}`)}})()},onCancel:()=>n.setFocus(w)})},P=(g,b,x)=>{e.session.respondToToolApproval({decision:b,toolCallId:g,...x?{declineContext:{reason:x}}:{}})},L=(g)=>{if(e.yolo?.get()){P(g.toolCallId,"approve");return}let b=Zt(g.toolName),x=new Tr(b.map((S)=>({value:S.value,label:S.label,description:S.description})),b.length,se(t));x.onSelect=(S)=>{if(S.value!=="decline"){E(),P(g.toolCallId,S.value);return}let C=new la({prompt:"why not? (enter to skip) ",placeholder:"reason"}),T=(v)=>{E(),P(g.toolCallId,"decline",v.trim())};C.onSubmit=T,C.onEscape=()=>T(""),s.open(()=>[],C),n.setFocus(s),n.requestRender()},x.onCancel=()=>{E(),P(g.toolCallId,"decline","The user dismissed the approval prompt.")},s.open((S)=>pr({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{width:S,colors:t}),x),n.setFocus(s),n.requestRender()};e.session.subscribe((g)=>{if(g.type==="tool_approval_required")L(g);if(g.type==="mode_changed")i.mode=g.modeId;if(g.type==="usage_update"){let x=Te(g.usage);if(i.context={used:g.usage.totalTokens,total:i.context?.total??0},x!==void 0)i.costUsd=x}let b=hr(r.state,g);if(b!==r.state)r.state=b;o.text=r.state.status,a()});let j=xn({tui:n,editor:w,commands:e.commands,basePath:e.cwd,handlers:{onSubmit:(g)=>{let b=Ir(g);if(b.kind==="slash"){let x=Cr(b,e.commands);O(x.name,x.args);return}_(g)},onCycleMode:()=>{let g=sn(e.session.mode.get());e.session.mode.switch({modeId:g}).catch(()=>{u("This session's harness has no build/plan modes. Try /harness.")})},onAbort:()=>{if(!r.state.busy)return;e.session.abort(),f("Aborted.")},onExpand:()=>{let g=r.lastCollapsible();if(!g)return;if(r.expanded.has(g.id))r.expanded.delete(g.id);else r.expanded.add(g.id);n.requestRender()},onInterruptWarning:()=>f(qe),onExit:()=>n.stop()}});for(let g of e.notices??[])f(g);if(n.addChild(new class{render(g){return[t.brand(lt(`◆ ${N}`,g)),""]}invalidate(){}}),n.addChild(r),n.addChild(o),n.addChild(s),n.addChild(w),n.addChild(l),n.setFocus(w),a(),e.commands.set("model",{name:"model",description:"Pick the model this session runs on",handler:()=>(ee(),{lines:[]})}),e.bindings)e.bindings.openPicker=M,e.bindings.openModelPicker=ee,e.bindings.setFact=(g)=>{if(g.harness!==void 0)i.harness=g.harness;if(g.mode!==void 0)i.mode=g.mode;if(g.yolo!==void 0)i.yolo=g.yolo;a()};await new Promise((g)=>{let b=n.stop.bind(n);n.stop=(x)=>{j(),b(x),g()},n.start()})}var da=new Set(["display_state_changed","tool_input_start","tool_input_delta","tool_input_end","om_status"]),pa=(e)=>!da.has(e);function ua(e){let t={type:e.type};switch(e.type){case"message_start":case"message_update":case"message_end":t.role=e.message.role,t.text=Re(e.message);break;case"tool_start":case"tool_approval_required":t.tool=e.toolName,t.toolCallId=e.toolCallId;break;case"tool_end":if(t.toolCallId=e.toolCallId,t.isError=e.isError,e.denied===!0)t.denied=!0;break;case"usage_update":{t.totalTokens=e.usage.totalTokens;let n=Te(e.usage);if(n!==void 0)t.costUsd=n;break}case"subagent_start":t.agentType=e.agentType,t.task=e.task;break;case"subagent_end":t.agentType=e.agentType,t.isError=e.isError,t.durationMs=e.durationMs;break;case"agent_end":t.reason=e.reason??"complete";break;case"error":t.message=e.error?.message??String(e.error);break;default:break}return JSON.stringify(t)}async function Mr(e){let t=e.write??((i)=>process.stdout.write(i)),n=e.writeError??((i)=>process.stderr.write(i)),r="",o=null,s="complete";await new Promise((i)=>{let c=e.session.subscribe((a)=>{if(e.json&&pa(a.type))t(`${ua(a)}
42
+ `);if(a.type==="tool_approval_required"){let m=Jt({toolName:a.toolName,yolo:e.yolo===!0});e.session.respondToToolApproval({decision:m.decision,toolCallId:a.toolCallId,...m.reason?{declineContext:{reason:m.reason}}:{}});return}if(a.type==="message_end"){if(a.message.role!=="user")r=Re(a.message);return}if(a.type==="error"){o=a.error?.message??String(a.error);return}if(a.type==="agent_end")s=a.reason??"complete",c(),i()});e.session.sendMessage({content:e.prompt}).catch((a)=>{o=a instanceof Error?a.message:String(a),c(),i()})});let l=s==="complete"&&o===null;if(!e.json){if(r)t(`${r}
43
+ `);if(o)n(`${o}
44
+ `);else if(!l)n(`the turn ended ${s}
45
+ `)}return{text:r,exitCode:l?0:1}}import{appendFileSync as ma,mkdirSync as ga}from"node:fs";import{homedir as fa}from"node:os";import{dirname as ha,join as Or}from"node:path";var ya=["log","info","warn","error","debug","trace"];function ba(e=process.env){let t=e.HLIX_CONFIG_HOME??Or(e.HOME??fa(),".hlix");return Or(t,"code","hlix-code.log")}var xa={log:"notes",info:"notes",debug:"notes",trace:"notes",warn:"warnings",error:"errors"};function Sa(e){if(typeof e==="string")return e;if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}function ct(e=process.env,t=console){let n=ba(e),r=new Set,o=[],s={notes:0,warnings:0,errors:0},l=new Map,i=(a,m)=>{let u=`${new Date().toISOString()} ${a} ${m}`;o.push(u);try{ga(ha(n),{recursive:!0}),ma(n,`${u}
46
+ `,"utf8")}catch{}};for(let a of ya)l.set(a,t[a]),t[a]=(...m)=>{let u=m.map(Sa).join(" ");if(r.has(`${a}:${u}`))return;r.add(`${a}:${u}`),s[xa[a]]+=1,i(a,u)};let c=!1;return{path:n,counts:s,note:(a)=>i("hlix",a),tail:(a)=>o.slice(Math.max(0,o.length-a)),restore:()=>{if(c)return;c=!0;for(let[a,m]of l)t[a]=m}}}function Lr(e){let t=[];if(e.counts.errors>0)t.push(`${e.counts.errors} error${e.counts.errors===1?"":"s"}`);if(e.counts.warnings>0)t.push(`${e.counts.warnings} warning${e.counts.warnings===1?"":"s"}`);if(e.counts.notes>0)t.push(`${e.counts.notes} note${e.counts.notes===1?"":"s"}`);if(t.length===0)return"";return`log: ${t.join(" · ")} from this session's libraries — /log to read them`}import{MCPClient as va}from"@mastra/mcp";var dt={tools:{},statusLines:[],summary:"",connected:[],failed:[],stop:async()=>{}};function Ea(e,t){let n={},r=[];for(let o of e){if("command"in o.config){n[o.name]={command:o.config.command,...o.config.args?{args:o.config.args}:{},...o.config.env?{env:o.config.env}:{},stderr:"ignore",cwd:t};continue}try{n[o.name]={url:new URL(o.config.url),...o.config.headers?{requestInit:{headers:o.config.headers}}:{}}}catch{r.push({name:o.name,reason:"not a valid url"})}}return{servers:n,skipped:r}}function wa(e,t){let n={};for(let r of t)n[r]=0;for(let r of e){let o=t.filter((s)=>r.startsWith(`${s}_`)).sort((s,l)=>l.length-s.length)[0];if(o)n[o]=(n[o]??0)+1}return n}var Pe=(e,t)=>`${e} ${t}${e===1?"":"s"}`;async function pt(e){if(e.servers.length===0)return dt;let{servers:t,skipped:n}=Ea(e.servers,e.cwd),r=Object.keys(t),o=e.timeoutMs??20000,s=[...n];if(r.length===0)return Ae({failed:s});let l;try{l=(e.client??((y)=>new va(y)))({id:`hlix-code:${e.cwd}`,servers:t,timeout:o})}catch(f){for(let y of r)s.push({name:y,reason:jr(f)});return Ae({failed:s})}let i={},c={};try{let f=await l.listToolsWithErrors({perServerTimeoutMs:o});i=f.tools,c=f.errors}catch(f){for(let y of r)s.push({name:y,reason:jr(f)});return await l.disconnect().catch(()=>{}),Ae({failed:s})}for(let[f,y]of Object.entries(c))s.push({name:f,reason:y});let a=wa(Object.keys(i),r),m=r.filter((f)=>!(f in c)).map((f)=>({name:f,tools:a[f]??0})),u=!1;return Ae({tools:i,connected:m,failed:s,stop:async()=>{if(u)return;u=!0,await l.disconnect().catch(()=>{})}})}function Ae(e){let t=e.connected??[],n=e.failed??[],r=e.tools??{},o=t.length===0?n.length>0?`mcp: ${Pe(n.length,"server")} unreachable`:"":`mcp: ${Pe(t.length,"server")} · ${Pe(t.reduce((s,l)=>s+l.tools,0),"tool")}${n.length>0?` · ${n.length} unreachable`:""}`;return{tools:r,connected:t,failed:n,summary:o,statusLines:_a(t,n),stop:e.stop??(async()=>{})}}var jr=(e)=>e instanceof Error?e.message:String(e);function _a(e,t){return[...e.map((n)=>`✓ ${n.name} — ${Pe(n.tools,"tool")}`),...t.map((n)=>`✗ ${n.name} — ${n.reason}`)]}var Ra="run `hlix auth login`",ka=["You are running inside Hlix Code, the terminal shell for the hlix control plane.","Every `hlix` CLI command is available to you as a tool named `hlix_<command>`,","with spaces replaced by underscores — `hlix_status`, `hlix_tasks_list`, `hlix_push`.","Use those tools instead of running `hlix` through the shell: they resolve the","folder's workspace binding and credential the same way the CLI does, and they","return the CLI's machine-readable output.","Report a non-zero exit code and its stderr to the user verbatim. Never invent a","project, task or workspace id — read one with a tool first.","","Do not create, write or modify any file the user's request did not ask for.","You do not need to probe whether you can write: if a write is refused you will","be told, with a reason. A scratch file nobody asked for is a change the user has","to notice and undo.","","This project's secrets live in the hlix secrets store, not in a file in this","folder: `hlix_secrets_list` shows them keyed by (key, source file) with every","value masked, and `hlix_secrets_set` changes one. When the user asks for a",'local env file, call `hlix_secrets_export` with `{ flags: { out: ".env" } }` —',"it writes the rendered file at mode 0600 and refuses a path git tracks. Do not","repeat an exported secret value back into the conversation."].join(`
47
+ `);function Aa(e){if(!e||e.entries.length===0)return"";let t=e.entries.length,n=new Set(e.entries.map((r)=>r.source)).size;return`secrets: ${t} ${t===1?"entry":"entries"} (${n} ${n===1?"source":"sources"})`}async function Pa(e,t){try{return await F(process.env,{cwd:e,flags:{}}).secrets.listEntries(t)}catch{return null}}function Na(e){let{values:t,positionals:n}=Ta({args:e,allowPositionals:!0,strict:!1,options:{local:{type:"boolean"},sandbox:{type:"string"},"docker-image":{type:"string"},harness:{type:"string"},project:{type:"string"},cwd:{type:"string"},print:{type:"string",short:"p"},json:{type:"boolean"},yolo:{type:"boolean"},"allow-writes":{type:"boolean"}}}),r=typeof t.sandbox==="string"?t.sandbox:t.local===!0?"local":void 0,o=typeof t.print==="string"?t.print:void 0,s=o===void 0?void 0:[o,...n].filter((l)=>l!=="").join(" ");return{...r?{sandbox:r,sandboxSource:"flag"}:{},...typeof t["docker-image"]==="string"?{dockerImage:t["docker-image"]}:{},...typeof t.harness==="string"?{harness:t.harness}:{},...typeof t.project==="string"?{project:t.project}:{},...s!==void 0?{print:s}:{},...t.json===!0?{json:!0}:{},...t.yolo===!0||t["allow-writes"]===!0?{yolo:!0}:{},cwd:Ca(typeof t.cwd==="string"?t.cwd:".")}}function Ma(e){let t=Object.keys(te),r=e.sandbox==="cloud"?t:t.filter((c)=>e.installed(c)),o=["hlix",...r],s=t.filter((c)=>!r.includes(c)),l=e.requested.harness;if(l==="hlix"||r.includes(l))return{harness:e.requested,available:o,unavailable:s,refusal:null,warning:null};let i=Le(te[l]);if(e.requested.source==="flag")return{harness:e.requested,available:o,unavailable:s,refusal:i,warning:null};return{harness:{harness:"hlix",source:"default"},available:o,unavailable:s,refusal:null,warning:`${i} Falling back to harness hlix.`}}async function Oa(e,t){try{let r=await F(process.env,{cwd:e,flags:{}}).modelConfig.resolvedProjectHarness(t);return{harness:r.harness,source:r.source}}catch{return null}}async function La(e,t){let n=t.skills&&t.skills.length>0?{skills:t.skills}:{};if(e.choice!=="cloud")return Ue(e,{cwd:t.cwd,...n});if(!t.projectId)throw new Y("invalid_usage","The cloud sandbox needs a hlix project. Run `hlix init`, pass --project <id>, or choose --sandbox docker|local.");let o=F(process.env,{cwd:t.cwd,flags:{}}).projects.workspace(t.projectId);return Ue(e,{cwd:t.cwd,projectId:t.projectId,remote:o})}var ut=".hlix";function ja(e,t,n=(r)=>{try{return Ia(r)}catch{return r}}){let r=new Set,o=[];for(let s of e.skills){if(s.scope!=="project")continue;let l=zr(t,s.path);if(l===""||l.startsWith(".."))continue;let i=n(s.path);if(r.has(i))continue;r.add(i),o.push(l)}return o}function Da(e,t){let n=[];if(e.global)n.push(["# Your user's own rules","","Written by the person you are working with, for every project they open.","Follow them unless this project's rules below say otherwise.","",e.global.content].join(`
48
+ `));if(e.project)n.push([`# This project's rules (${zr(t,e.project.path)||e.project.path})`,"","Written for whichever coding agent opens this repository. They are the","project's own rules and they take precedence over the user rules above.","",e.project.content].join(`
49
+ `));return n.join(`
50
+
51
+ `)}var $a={boot:fn,app:Nr,headless:Mr,mcp:pt,log:ct,stdio:{get stdinIsTty(){return process.stdin.isTTY===!0},get stdoutIsTty(){return process.stdout.isTTY===!0}}};function Fa(e){if(e.flag===!0)return!0;return Fr(e.configured)===!0}function Ha(e){if(e.print)return null;if(e.stdinIsTty&&e.stdoutIsTty)return null;return`${N} needs a terminal. Run \`hlix -p "<prompt>"\` for one turn without a screen, or start \`hlix\` in a terminal.`}function Ua(e,t){let n=e?.mode?.get;if(typeof n!=="function")return t;let r=n.call(e.mode);return typeof r==="string"&&r!==""?r:t}async function Gm(e,t=$a){let n=Na(e),r=Ha({print:n.print!==void 0,stdinIsTty:t.stdio?.stdinIsTty??!0,stdoutIsTty:t.stdio?.stdoutIsTty??!0});if(r)return process.stderr.write(`error: ${r}
52
+ `),2;let o=$r(n.cwd,process.env),s=n.project??o.merged.projectId,l=n.print===void 0?(t.log??ct)(process.env):null,i=Yr(n.cwd,Hr(process.env),{configDir:ut}),c=Br({cwd:n.cwd,configDir:ut,env:process.env}),a=new Fe({root:n.cwd,already:[c.project?.path,c.global?.path].filter((v)=>v!==void 0)}),m=new Ge(Fa({...n.yolo!==void 0?{flag:n.yolo}:{},...o.merged.yolo!==void 0?{configured:o.merged.yolo}:{}})),u,f,y;try{if(f=Kt({flag:n.sandbox??o.merged.sandbox,flagSource:n.sandbox?"flag":"config",projectId:s,dockerImage:n.dockerImage??o.merged.dockerImage,dockerAvailable:()=>qt()}),y=Ma({requested:ht({...n.harness?{flag:n.harness}:{},...o.merged.harness?{configured:o.merged.harness}:{},...o.sources.harness?{configSource:o.sources.harness}:{}}),sandbox:f.choice,installed:(v)=>bt(te[v].command)}),y.refusal)throw new Y("invalid_usage",y.refusal);u=await La(f,{cwd:n.cwd,projectId:s,...f.choice==="cloud"?{}:{skills:ja(i,n.cwd)}})}catch(v){return l?.restore(),process.stderr.write(`error: ${v instanceof Error?v.message:String(v)}
53
+ `),2}if(y.warning)process.stderr.write(`warning: ${y.warning}
54
+ `);if(f.choice==="cloud"){let v=s?await Oa(n.cwd,s):null;if(v&&n.harness&&n.harness!==v.harness)process.stderr.write(`warning: this project runs ${v.harness}. Run \`/harness ${n.harness}\` to make ${n.harness} the project's setting.
55
+ `);y={...y,harness:v??{harness:"unknown",source:s?"the project's setting could not be read":"no project bound"}}}let w=await Pt({cwd:n.cwd,env:process.env}),E=At({cwd:n.cwd,env:process.env,...w.served?{models:w.served.map((v)=>v.id)}:{}}),_=Nt({endpoint:E,cloud:f.choice==="cloud",...o.merged.model?{configured:o.merged.model}:{},...o.sources.model?{configuredSource:o.sources.model}:{}});if(_?.notice)process.stderr.write(`warning: ${_.notice}
56
+ `);if(!E)return l?.restore(),process.stderr.write(`error: no hlix credential for this folder — ${Ra}.
57
+ `),2;let M=fe(ye(o.merged.memoryTokens)??ge),O=Vt(f),ee=qr(i),P=Gr(c,n.cwd),L=s?Aa(await Pa(n.cwd,s)):"",j=n.print===void 0?await(t.mcp??pt)({servers:i.mcpServers,cwd:n.cwd}):dt,g=Kr(i.generatedCommands,n.cwd),b=Vr(i.instructions,n.cwd),x=Da(c,n.cwd),S=[...Ur.flatMap((v)=>[Dr(n.cwd,".claude",v),Dr(n.cwd,ut,v)]),...i.commands.map((v)=>v.path),...g?[g]:[]],C=y.harness.harness==="unknown"?"hlix":y.harness.harness,T;try{T=await t.boot({cwd:n.cwd,env:process.env,sandbox:f.choice,workspace:u,endpoint:E,model:_,harness:C,harnessFromFlag:y.harness.source==="flag",unavailableHarnesses:y.unavailable,...o.global?.providers?{providers:o.global.providers}:{},...o.merged.memoryTokens?{memoryTokens:o.merged.memoryTokens}:{},hostInstructions:[ka,...f.choice==="cloud"?[xt(y.harness.harness)]:[],...x?[x]:[],...b?[b]:[]].join(`
58
+
59
+ `),mcpTools:j.tools,projectSubagents:i.subagents,nestedRules:a,extraTools:{...wt({cwd:n.cwd}),hlix_tasks_follow:It({cwd:n.cwd}),hlix_harness:Et({sandbox:f.choice,sandboxLine:O,available:y.available,modesBuilt:!1,session:()=>null})}})}catch(v){if(l?.restore(),await j.stop(),v instanceof be)return process.stderr.write(`error: ${v.message}
60
+ `),2;return process.stderr.write(`error: ${N} could not start: ${v instanceof Error?v.message:String(v)}
61
+ `),2}try{if(n.print!==void 0)return(await t.headless({session:T.session,prompt:n.print,...n.json?{json:!0}:{},...m.get()?{yolo:!0}:{}})).exitCode;let v={session:T.session,compact:async()=>{let K=T.session.thread.getId();if(!K)return"Nothing to condense yet.";let Ne=await T.memory.omEngine;if(!Ne)return"Observational memory is not running in this session.";return(await Ne.observe({threadId:K,resourceId:E.workspaceId})).observed?"Condensed.":"Nothing new to condense."},facts:{sandbox:f.choice,sandboxLine:O,harness:String(y.harness.harness),availableHarnesses:y.available,harnessModesBuilt:T.harnessModesBuilt},...l?{log:{path:l.path,tail:l.tail}}:{},rules:()=>Wr(c,n.cwd,process.env,a.loaded()),mcp:()=>j.statusLines,yolo:{get:()=>m.get(),set:(K)=>m.set(K)},...s?{setProjectHarness:async(K)=>{await F(process.env,{cwd:n.cwd,flags:{}}).modelConfig.setProjectHarness(s,K)}}:{}},Xr=wr({env:process.env,promptFiles:S,shell:v}),mt=ot({...w.served?{served:w.served}:{},userModelIds:T.gateway.modelIds(),providerName:E.name});return await t.app({session:T.session,cwd:n.cwd,env:process.env,commands:Xr,models:mt,bindings:v,yolo:m,notices:Ba({rules:P,standards:ee,secrets:L,mcp:j.summary,subagents:T.subagentLine,subagentsSkipped:T.subagentsSkipped,log:l?Lr(l):""}),facts:{sandbox:O.replace(/^sandbox: /,""),harness:yt(y.harness),mode:Ua(T.session,Z),..._?{model:Ga(_,mt)}:{},workspace:E.workspaceId,context:{used:0,total:0},memory:Mt("",M).replace(/^ · /,""),...m.get()?{yolo:!0}:{},...w.warning?{warning:w.warning}:{}}}),0}finally{await j.stop(),await T.dispose(),l?.restore()}}function Ba(e){return[e.rules,e.standards,e.mcp,e.subagents,...e.subagentsSkipped.map((t)=>`subagent not loaded: ${t}`),e.secrets,e.log].filter((t)=>t!=="")}function Ga(e,t){return t.find((n)=>n.id===e.id)?.label??e.id}export{Ua as currentMode,Na as parseHlixCodeArgs,Ma as planHarness,Fa as resolveYolo,Da as rulesBlock,Gm as runHlixCode,Aa as secretsStatusLine,Ba as startupNotices,Ha as terminalRequirement,ja as workspaceSkillPaths};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import"./index-11raxarr.js";var s="@hlix/cli",i="0.5.0",n="SEE LICENSE IN LICENSE",a="Hlix Code and the hlix control-plane CLI.",r=["hlix","cli","agents"],l="https://hlix.ai",p="module",d="./dist/index.js",o={hlix:"./dist/index.js"},c=["dist","skills","LICENSE","THIRD_PARTY_NOTICES"],u={node:">=22.19.0"},b={access:"public"},m={build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --splitting --packages external --minify --banner '#!/usr/bin/env node'",test:'bun test --isolate src --path-ignore-patterns "**/*.integration.test.ts" --timeout 20000',typecheck:"tsc --noEmit",prepublishOnly:"bun run typecheck && bun run build && bun run test","test:integration":"NODE_ENV=test bun run ../../apps/backend/scripts/with-aimock.ts -- bun run ../../apps/backend/scripts/with-test-db.ts -- bun test --isolate --preload ../../apps/backend/test/helpers/pool-lifecycle.ts --timeout 60000 .integration.test.ts"},h={"@earendil-works/pi-tui":"0.85.1","@mastra/acp":"^0.4.1","@mastra/core":"1.66.0","@mastra/docker":"^0.7.0","@mastra/libsql":"1.22.5","@mastra/mcp":"1.17.3","@mastra/memory":"1.29.0",ignore:"7.0.8","openapi-fetch":"^0.17.0",zod:"4.5.4"},g={"@hlix/sdk":"^0.2.0","@hlix/shared":"*","@types/bun":"latest",typescript:"^7.0.2"},k={name:s,version:i,license:n,description:a,keywords:r,homepage:l,type:p,main:d,bin:o,files:c,engines:u,publishConfig:b,scripts:m,dependencies:h,devDependencies:g};export{o as bin,k as default,h as dependencies,a as description,g as devDependencies,u as engines,c as files,l as homepage,r as keywords,n as license,d as main,s as name,b as publishConfig,m as scripts,p as type,i as version};
2
+ import"./index-f303pf32.js";var s="@hlix/cli",i="0.5.1",n="SEE LICENSE IN LICENSE",a="Hlix Code and the hlix control-plane CLI.",r=["hlix","cli","agents"],l="https://hlix.ai",p="module",d="./dist/index.js",o={hlix:"./dist/index.js"},c=["dist","skills","LICENSE","THIRD_PARTY_NOTICES"],u={node:">=22.19.0"},b={access:"public"},m={build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --splitting --packages external --minify --banner '#!/usr/bin/env node'",test:'bun test --isolate src --path-ignore-patterns "**/*.integration.test.ts" --timeout 20000',typecheck:"tsc --noEmit",prepublishOnly:"bun run typecheck && bun run build && bun run test","test:integration":"NODE_ENV=test bun run ../../apps/backend/scripts/with-aimock.ts -- bun run ../../apps/backend/scripts/with-test-db.ts -- bun test --isolate --preload ../../apps/backend/test/helpers/pool-lifecycle.ts --timeout 60000 .integration.test.ts"},h={"@earendil-works/pi-tui":"0.85.1","@mastra/acp":"^0.4.1","@mastra/core":"1.66.0","@mastra/docker":"^0.7.0","@mastra/libsql":"1.22.5","@mastra/mcp":"1.17.3","@mastra/memory":"1.29.0",ignore:"7.0.8","openapi-fetch":"^0.17.0",zod:"4.5.4"},g={"@hlix/sdk":"^0.2.0","@hlix/shared":"*","@types/bun":"latest",typescript:"^7.0.2"},k={name:s,version:i,license:n,description:a,keywords:r,homepage:l,type:p,main:d,bin:o,files:c,engines:u,publishConfig:b,scripts:m,dependencies:h,devDependencies:g};export{o as bin,k as default,h as dependencies,a as description,g as devDependencies,u as engines,c as files,l as homepage,r as keywords,n as license,d as main,s as name,b as publishConfig,m as scripts,p as type,i as version};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hlix/cli",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "Hlix Code and the hlix control-plane CLI.",
6
6
  "keywords": [
@@ -36,12 +36,16 @@ them exits `workspace_mismatch` naming the ones that are, instead of storing a
36
36
  credential that 403s later. `hlix auth login` then verifies the key against a
37
37
  real call **before** writing it, so a key that does not work is never stored.
38
38
 
39
- `auth status` names the credential's **source** — the environment or the stored
40
- file — and probes it against the API. It never prints the key, not even a
41
- prefix. `auth logout` removes the credential **file** only; a key supplied
39
+ `auth status` names the credential's **source** and probes it against the API.
40
+ `--json` reports it as `credentialSource`: `"file"` for the stored credential,
41
+ `"env"` for `HLIX_API_KEY`, `"session"` for the desktop app's own session
42
+ (`HLIX_SESSION_TOKEN`), which is never stored. It never prints the key, not even
43
+ a prefix. `auth logout` removes the credential **file** only; a key supplied
42
44
  through `HLIX_API_KEY` is reported and left alone, because it belongs to the
43
- shell that set it. Removal asks for confirmation unless `--yes` is given, and
44
- refuses any path that is not a credential document this CLI wrote.
45
+ shell that set it, and so is a desktop session, which belongs to the app
46
+ (`reason: "environment"` and `reason: "session"` respectively). Removal asks for
47
+ confirmation unless `--yes` is given, and refuses any path that is not a
48
+ credential document this CLI wrote.
45
49
 
46
50
  ## Where a command points
47
51