@hlix/cli 0.5.3 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ import{a as q,c as ve,d as et,e as F,f as de,g as Ie,h as ee,i as Y,j as Ke,k as lo,l as co,m as Er,n as po,o as uo,p as Gt,q as mo,r as go,s as fo,t as ho,u as yo,v as xo,w as bo,x as Se}from"./index-nz8482bb.js";import"./index-f303pf32.js";import{realpathSync as pl}from"node:fs";import{join as io,relative as So,resolve as ul}from"node:path";import{parseArgs as ml}from"node:util";import{accessSync as vo,constants as wo,statSync as Eo}from"node:fs";import{delimiter as _o,join as Io}from"node:path";import{createACPTool as Co}from"@mastra/acp";import{createTool as Ro}from"@mastra/core/tools";import{z as X}from"zod";var oe={"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 Mt(e){if(e.flag)return{harness:To(e.flag,"--harness"),source:"flag"};if(e.configured)return{harness:e.configured,source:e.configSource??"project"};return{harness:Ke,source:"default"}}function To(e,t){if(Y.includes(e))return e;throw Error(`${t} must be one of ${Y.join(", ")}; got "${e}".`)}var Ye="hlix_tasks_follow",ko=(e)=>`hlix_coder_${e.split("-").join("_")}`;function Ve(e){if(e.source==="default")return String(e.harness);let t=e.source==="flag"?"--harness":e.source;return`${e.harness} (${t})`}function Ot(e,t=process.env){return qe(e,t)!==null}function qe(e,t=process.env){if(!e)return null;if(e.includes("/"))return Pt(e)?e:null;let n=(t.PATH??"").split(_o).filter(Boolean);for(let r of n){let o=Io(r,e);if(Pt(o))return o}return null}function Pt(e){if(!e)return!1;try{if(!Eo(e).isFile())return!1;return vo(e,wo.X_OK),!0}catch{return!1}}var ze=(e)=>`harness ${e.harness} needs \`${e.command}\` on PATH. Install it with: ${e.install}`;function Ao(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 Nt=["ask_user","task_write","task_update","task_complete","task_check"],Po=(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(" "),Lt=(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. \`${Ye}\` 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
+ `),No=(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 jt(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(oe)){let s=e.active===o.harness,a=ko(o.harness);r.push({id:o.harness,name:o.label,description:`${o.label} runs on this machine over ACP and edits ${e.cwd}.`,instructions:No(o,a),availableTools:t.has(o.harness)?[...e.readTools,...Nt,Ye]:[a,...e.readTools,...Nt,Ye],...t.has(o.harness)?{}:{additionalTools:{[a]:Co({id:a,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)=>Ao(i)})}},...n,...s?{metadata:{default:!0}}:{}})}return r}function Dt(e){if(!e.fromFlag||!e.modesBuilt)return null;return e.current===e.harness?null:e.harness}function Xe(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(!Y.includes(e.requested))return n(`/harness must name one of ${Y.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}. ${Po(r)}`}}if(!t.includes(r))return n(ze(oe[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 $t(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:X.object({harness:X.string().optional().describe(`One of ${Y.join(", ")}. Omit to report the current one.`)}),outputSchema:X.object({harness:X.string(),available:X.array(X.string()),message:X.string()}),execute:async(t)=>{let n=e.session(),r=Xe({...t.harness?{requested:t.harness}:{},current:n?.mode.get()??Ke,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 Mo}from"@mastra/core/tools";import{z as M}from"zod";var Oo=(e)=>`hlix_${e.split(" ").join("_")}`,Lo=M.object({args:M.array(M.string()).optional().describe("Positional arguments that follow the command name."),flags:M.record(M.string(),M.union([M.string(),M.boolean()])).optional().describe('Options without the leading dashes, e.g. { "yes": true, "name": "api" }.')}),jo=M.object({exitCode:M.number(),stdout:M.string(),stderr:M.string()});function Do(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 $o(e,t,n,r=process.env){let o="",s="";return{exitCode:await de([e],Do(e,t,n),{stdout:(i)=>{o+=i},stderr:(i)=>{s+=i},env:r}),stdout:o,stderr:s}}function Ft(e){let t={};for(let n of e.commands??Se){let r=Oo(n.name);t[r]=Mo({id:r,description:`${n.summary}
5
+
6
+ ${n.usage}`,inputSchema:Lo,outputSchema:jo,execute:async(o)=>$o(n,o,e.cwd,e.env)})}return t}import{createTool as Fo}from"@mastra/core/tools";async function Ht(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 K}from"zod";function Ho(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:Uo(e.output)};case"error":return{event:"finish",isError:!0,result:e.message};case"done":return{event:"finish",isError:!1};default:return null}}function Uo(e){return typeof e==="object"&&e!==null&&e.status==="failed"}async function Bo(e,t){let n=[],r=[],o="streamed",s="The coder's turn ended.";for await(let a of e){if(a.type==="idle"){o="idle",s="Nothing is being coded right now. The task is not in build or test.";break}if(a.type==="error")o="error",s=a.message;if(a.type==="on_chat_model_stream")n.push(a.delta);if(a.type==="on_tool_start")r.push(a.name);let i=Ho(a);if(i)await t(i)}return{status:o,text:n.join(""),tools:r,message:s}}function Ut(e){return Fo({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:K.object({taskId:K.string().describe("The task to follow.")}),outputSchema:K.object({status:K.enum(["streamed","idle","error","unassigned"]),text:K.string(),tools:K.array(K.string()),message:K.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 Bo(r.projects.observeAgent(o.projectId,o.agentId),(s)=>Ht(n,s))}})}import{readFileSync as Go,statSync as Wt}from"node:fs";import{isAbsolute as Wo,join as Yo,relative as Ze,resolve as J}from"node:path";var Ko=["path","file","filePath","target","targetPath","dest","destination"],Je=8000,Vo=(e)=>{try{return Wt(e).isFile()}catch{return!1}},qo=(e)=>{try{return Wt(e).isDirectory()}catch{return!1}};function Bt(e,t){let n=Ze(e,t);return n!==""&&!n.startsWith("..")&&!Wo(n)}function zo(e){let t=J(e.root),n=J(t,e.touched);if(!Bt(t,n))return null;let r=qo(n)?n:J(n,"..");while(Bt(t,r)){for(let o of Gt){let s=Yo(r,o);if(Vo(s))return s}r=J(r,"..")}return null}function Xo(e,t){let n=Ze(t,e.path),r=!n||n.startsWith("..")?e.path:n;return[`Rules for ${Ze(t,J(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 Jo(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 a=Zo(s.args);if(!a)continue;let i=[];for(let c of Ko){let l=a[c];if(typeof l==="string"&&l.trim()!=="")i.push(l)}if(i.length>0)t.push({id:s.toolCallId,paths:i})}}return t}function Zo(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 Qe{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=J(e.root),this.skip=new Set((e.already??[]).map((t)=>J(t)))}loaded(){return[...this.sent.values()]}consider(e){let t=zo({touched:e,root:this.root});if(!t||this.skip.has(t)||this.sent.has(t))return null;let n;try{n=Go(t,"utf8").trim()}catch{return null}if(n==="")return null;let r={path:t,content:n.length>Je?`${n.slice(0,Je).trimEnd()}
8
+
9
+ [truncated: ${t} is longer than ${Je} characters]`:n};return this.sent.set(t,r),r}newCalls(e,t){let n=Jo(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:Xo(r,this.root),attributes:{type:"nested-rules",path:r.path}})}return e.messageList}}import{createHash as ts}from"node:crypto";import{existsSync as ns,realpathSync as rs}from"node:fs";import{basename as os,dirname as ss,join as is,resolve as zt,sep as Xt}from"node:path";import{Memory as as}from"@mastra/memory";var V="hlix",Z="default",pe=(e)=>`${V}/${e}`,Yt=(e)=>e.startsWith(`${V}/`)&&e.length>V.length+1;function Qo(e){return{name:V,url:`${e.baseUrl.replace(/\/+$/,"")}/v1/api/ai/w/${e.workspaceId}`,apiKey:e.apiKey,models:[...new Set([Z,...e.models??[]])]}}function Kt(e){let t=et({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{...Qo({baseUrl:t.baseUrl,workspaceId:t.workspaceId,apiKey:n,...e.models?{models:e.models}:{}}),workspaceId:t.workspaceId,...r?{projectId:r}:{}}}var es=3000;async function Vt(e){let t=et({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??es)})).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 qt(e){if(e.configured){let t=e.configuredSource??"config";if(!e.cloud||!e.endpoint||Yt(e.configured))return{id:e.configured,source:t};return{id:pe(Z),source:"workspace",notice:`model ${e.configured} from ${t} is not available on the cloud sandbox; using hlix default`}}return e.endpoint?{id:pe(Z),source:"workspace"}:null}function Jt(e){try{return rs(zt(e))}catch{return zt(e)}}function ls(e){let t=Jt(e),n=ve(t);if(n)return Jt(n.root);for(let r=t;;){if(ns(is(r,".git")))return r;let o=ss(r);if(o===r)return t;r=o}}var cs=(e)=>e.length>8?`${e.slice(0,8)}…`:e;function Zt(e){let t=ls(e.cwd),n=e.projectId?.trim(),r=n||ts("sha256").update(t).digest("hex").slice(0,16);return{resourceId:`${e.workspaceId}:${r}`,legacyResourceId:e.workspaceId,root:t,label:n?`project ${cs(n)}`:`folder ${os(t)}`}}var Qt=(e,t)=>typeof e==="string"&&(e===t||e.startsWith(t.endsWith(Xt)?t:`${t}${Xt}`)),en=(e,t)=>`memory: ${e.label} · ${t} thread${t===1?"":"s"}`,we=200000;function Ee(e){let t=Math.round(e*3/7);return{observationThreshold:t,reflectionThreshold:e-t}}var tn=(e,t)=>`${e} · memory: ${Math.round((t.observationThreshold+t.reflectionThreshold)/1000)}k`;function nn(e){return new as({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 Ts}from"node:child_process";import{DockerSandbox as ks}from"@mastra/docker";import{LocalFilesystem as pn,LocalSandbox as As,Workspace as un}from"@mastra/core/workspace";var ds=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,rn=/^(\s*name\s*:\s*)(.+?)\s*$/;function ps(e,t){if(!ds.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)=>rn.test(c));if(s<0)return e;let a=rn.exec(o[s]);if(!a)return e;let i=a[2].replace(/^["']|["']$/g,"").trim();if(i===t)return e;if(o[s]=`${a[1]}${t}`,!o.some((c)=>/^\s*title\s*:/.test(c)))o.push(`title: ${i}`);return`${o.join(`
12
+ `)}${e.slice(n)}`}function us(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 on(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=us(n);if(o===null)return r;let s=typeof r==="string"?r:r.toString("utf8");return ps(s,o)}};if(e.realpath)t.realpath=(n)=>e.realpath?.(n);return t}import{WORKSPACE_TOOLS as T}from"@mastra/core/workspace";var se={[T.FILESYSTEM.READ_FILE]:"view",[T.FILESYSTEM.WRITE_FILE]:"write_file",[T.FILESYSTEM.EDIT_FILE]:"edit_file",[T.FILESYSTEM.LIST_FILES]:"find_files",[T.FILESYSTEM.DELETE]:"delete_file",[T.FILESYSTEM.FILE_STAT]:"file_stat",[T.FILESYSTEM.MKDIR]:"mkdir",[T.FILESYSTEM.GREP]:"search_content",[T.FILESYSTEM.AST_EDIT]:"ast_edit",[T.SANDBOX.EXECUTE_COMMAND]:"execute_command",[T.SANDBOX.GET_PROCESS_OUTPUT]:"process_output",[T.SANDBOX.KILL_PROCESS]:"kill_process",[T.LSP.LSP_INSPECT]:"lsp_inspect"},ue=[T.FILESYSTEM.WRITE_FILE,T.FILESYSTEM.EDIT_FILE,T.FILESYSTEM.DELETE,T.FILESYSTEM.MKDIR,T.FILESYSTEM.AST_EDIT,T.SANDBOX.EXECUTE_COMMAND,T.SANDBOX.KILL_PROCESS].map((e)=>se[e]),_e=Object.values(se).filter((e)=>!ue.includes(e)),me=Object.fromEntries(Object.entries(se).map(([e,t])=>[e,{name:t}]));function O(e){return se[e]??e}import{posix as sn}from"node:path";import{DirectoryNotEmptyError as ms,DirectoryNotFoundError as gs,FileExistsError as fs,FileNotFoundError as hs,FilesystemError as ys,IsDirectoryError as xs,MastraFilesystem as bs,MastraSandbox as Ss,NotDirectoryError as vs,PermissionError as ws,Workspace as Es}from"@mastra/core/workspace";var _s=600000,Is=["recursive","overwrite","force","maxDepth","extension"];function Q(e){let t=e??{},n={};for(let r of Is)if(t[r]!==void 0)n[r]=t[r];return Object.keys(n).length>0?{options:n}:{}}var an=(e)=>e instanceof Date?e:new Date(typeof e==="string"||typeof e==="number"?e:0);function Cs(e,t,n){let r=e?.status;if(typeof r!=="number")return e;let o=e?.body,s=typeof o?.code==="string"?o.code:"",a=typeof o?.error==="string"?o.error:"",i=(c)=>a.toLowerCase().includes(c);if(r===404)return s==="ENOTDIR"||i("directory not found")?new gs(t):new hs(t);if(r===403)return new ws(t,n);if(r===409){if(s==="EEXIST"||i("already exists"))return new fs(t);if(s==="ENOTEMPTY"||i("not empty"))return new ms(t);if(s==="EISDIR"||i("is a directory"))return new xs(t);if(s==="ENOTDIR"||i("not a directory"))return new vs(t);return new ys(a||`${n} failed`,s||"ECONFLICT",t)}return e}class ln extends bs{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 sn.isAbsolute(e)?e:sn.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 Cs(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",...Q(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,...Q(t)})}async copyFile(e,t,n){await this.call({op:"copy",path:e,dest:this.resolveAbsolutePath(t),...Q(n)})}async moveFile(e,t,n){await this.call({op:"move",path:e,dest:this.resolveAbsolutePath(t),...Q(n)})}async mkdir(e,t){await this.call({op:"mkdir",path:e,...Q(t)})}async rmdir(e,t){await this.call({op:"rmdir",path:e,...Q(t)})}async readdir(e,t){return await this.call({op:"readdir",path:e,...Q(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:an(t.createdAt),modifiedAt:an(t.modifiedAt)}}}var Rs=(e)=>`'${e.split("'").join("'\\''")}'`;class cn extends Ss{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(Rs)].join(" "),o=Date.now(),s=n?.cwd??this.workingDirectory,a=await this.client.exec({command:r,...s?{cwd:s}:{},timeoutMs:n?.timeout??_s});return{success:a.exitCode===0,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,executionTimeMs:Date.now()-o,command:e,args:t}}}function dn(e,t){let n=t.root;return new Es({id:`hlix-project:${t.projectId}`,name:"Hlix Coding Workspace",filesystem:new ln(e,{root:n}),sandbox:new cn(e,{projectId:t.projectId,root:n}),tools:me})}var gn="node:22-bookworm",Ps=(e)=>`hlix-code-${e}`;function Ns(e,t){if(ee.includes(e))return e;throw new q("invalid_usage",`${t==="flag"?"--sandbox":"sandbox in .hlix/config.json"} must be one of ${ee.join(", ")}; got "${e}".`)}function fn(e){let t=(n)=>n==="docker"?{image:e.dockerImage?.trim()||gn}:{};if(e.flag){let n=e.flagSource??"flag",r=Ns(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 hn=(e)=>`sandbox: ${e.choice} (${e.reason}${e.image?`, ${e.image}`:""})`;function yn(e=3000){try{return Ts("docker",["info"],{timeout:e,stdio:"ignore"}),!0}catch{return!1}}function mn(e,t){if(!e||e.length===0)return{};return{skills:[...e],skillSource:on(t)}}async function Ms(e,t){let n=await e.environment();if(n.state==="absent")throw new q("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 q("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 tt(e,t){if(e.choice==="local"){let s=new pn({basePath:t.cwd});return new un({id:"hlix-code-local",name:"Hlix Code (this machine)",filesystem:s,...mn(t.skills,s),sandbox:new As({workingDirectory:t.cwd}),tools:me})}if(e.choice==="cloud"){if(!t.remote||!t.projectId)throw new q("invalid_usage","The cloud sandbox needs a hlix project. Run `hlix init`, pass --project <id>, or choose --sandbox docker|local.");return dn(t.remote,{projectId:t.projectId,root:await Ms(t.remote,t.projectId)})}let n="/workspace",r=e.image??gn,o=new pn({basePath:t.cwd});return new un({id:"hlix-code-docker",name:"Hlix Code (Docker)",filesystem:o,...mn(t.skills,o),tools:me,sandbox:new ks({id:Ps(r),image:r,volumes:{[t.cwd]:n},workingDirectory:n})})}import{basename as ii}from"node:path";import{AgentController as ai}from"@mastra/core/agent-controller";import{createCodingAgent as li}from"@mastra/core/coding-agent";import{createWorkspaceTools as ci}from"@mastra/core/workspace";var Os=["execute_command","kill_process"],Ls=["updateWorkingMemory","task_write","task_update","task_complete","task_check","ask_user","submit_plan"];function nt(e){let t=e in se?O(e):e;if(Os.includes(t))return"execute";if(ue.includes(t))return"edit";if(_e.includes(t)||Ls.includes(t))return"read";if(t.startsWith("hlix_"))return"other";return null}function xn(e=[]){let t=new Set(e);return(n)=>t.has(n)?"mcp":nt(n)}function js(e){return nt(e)!=="read"}var bn=[{category:"read",policy:"allow"}];function Sn(e){if(e.yolo||!js(e.toolName))return{decision:"approve"};return{decision:"decline",reason:`Hlix Code is running with -p (no terminal to ask), so ${O(e.toolName)} was not run. Report this to the user: re-run with --yolo to let this session change things.`}}class rt{on;constructor(e){this.on=e}get(){return this.on}set(e){this.on=e}}function vn(e){let t=O(e),n=nt(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 Ds,ModelRouterLanguageModel as $s}from"@mastra/core/llm";function Fs(e,t){let n=[];for(let r of e??[]){if(!r.name||!r.url||r.name===V)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 wn(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 Ds{id=`${V}-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=wn(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===V?"Hlix":t.name,url:t.url,apiKeyEnvVar:[],gateway:this.id,models:t.models.map((n)=>`${t.name}/${n}`)};return e}endpointFor(e){let t=wn(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 $s({id:`${e.providerId}/${e.modelId}`,url:t.url,apiKey:e.apiKey||t.apiKey,...e.headers?{headers:e.headers}:{}})}}function _n(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(...Fs(e.providers,e.env));return new En(t)}import{buildBasePrompt as Hs}from"@mastra/core/coding-agent";var D="Hlix Code",Us="Hlix Code",Bs="noreply@hlix.ai";function Gs(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 In(e){return e.sandbox==="cloud"?e.filesystemRoot??e.cwd:e.cwd}function Cn(e){let t=Hs({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:Gs(e.sandbox),hasSubagents:e.hasSubagents??!1,productName:D,coAuthorName:Us,coAuthorEmail:Bs});return e.hostInstructions?`${t}
13
+
14
+ ${e.hostInstructions}`:t}var te="build",Rn="plan",Ws=[te,Rn];function Tn(e,t=Ws){let n=t.indexOf(e);return t[(n+1)%t.length]??t[0]}function ot(e){let t=new Set(ue);return e.filter((n)=>!t.has(n)&&!n.startsWith("hlix_"))}function Ys(e){return[...new Set([...ot(e),"submit_plan","task_write","task_update","task_check"])]}var Ks=["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
+ `),Vs=["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 kn(e){let t=e.modelId?{defaultModelId:e.modelId}:{};return[{id:te,name:"build",description:"Read, write and run. The default.",instructions:Vs,metadata:{default:!0},...t},{id:Rn,name:"plan",description:"Read and plan; no edits, no commands.",instructions:Ks,availableTools:Ys(e.registeredTools),transitionsTo:te,...t}]}import{lstatSync as qs,mkdirSync as zs,unlinkSync as Xs}from"node:fs";import{homedir as Js}from"node:os";import{join as st}from"node:path";import{LibSQLStore as Zs}from"@mastra/libsql";function it(e=process.env){return st(e.HLIX_CONFIG_HOME??Js(),".hlix","code")}function Qs(e=process.env){return`file:${st(it(e),"threads.db")}`}var ei=["auth.json","mastra.db","mastra.db-shm","mastra.db-wal","settings.json"];function ti(e=process.env){let t=it(e);for(let n of ei){let r=st(t,n);try{if(!qs(r).isFile())continue;Xs(r)}catch{}}}function An(e=process.env){return zs(it(e),{recursive:!0}),ti(e),new Zs({id:"hlix-code",url:Qs(e)})}var Pn="explore",Nn="plan",Mn="execute",at=[`You are a subagent of ${D}. 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
+ `),ni=[at,"","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
+ `),ri=[at,"","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
+ `),oi=[at,"","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 On(e){let t=e.modelId?{defaultModelId:e.modelId}:{},n=e.registeredTools.filter((r)=>_e.includes(r));return[{id:Pn,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:ni,allowedWorkspaceTools:n,...t},{id:Nn,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:ri,...t},{id:Mn,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:oi,...t}]}var si=[Pn,Nn,Mn];function Ln(e,t){let n=[],r=[];for(let o of e){if(si.includes(o.name)){r.push(`${o.name} (reserved by ${D})`);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 jn(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 Ce extends Error{constructor(){super("No hlix credential for this folder. Run `hlix auth login`.");this.name="NoCredentialError"}}function di(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 Dn(e){if(!e.endpoint)throw new Ce;let t=e.endpoint,n=e.model?.id??pe(Z),r=_n({endpoint:t,...e.providers?{providers:e.providers}:{},env:e.env,cloud:e.sandbox==="cloud"}),o=Zt({workspaceId:t.workspaceId,cwd:e.cwd,...e.projectId?{projectId:e.projectId}:{}}),s=An(e.env),a=Ee(Ie(e.memoryTokens)??we),i=null,c=di(t,n),l=nn({storage:s,thresholds:a,observerModel:()=>i?.om.observer.resolvedModel()??c,reflectorModel:()=>i?.om.reflector.resolvedModel()??c}),g=e.workspace?await ci(e.workspace):{},u=e.mcpTools??{},f={...g,...e.extraTools??{},...u},y=Object.keys(f),_=On({registeredTools:y,modelId:n}),w=Ln(e.projectSubagents??[],n),v=[..._,...w.subagents],P=In({sandbox:e.sandbox,cwd:e.cwd,...e.workspace?.filesystem?.basePath?{filesystemRoot:e.workspace.filesystem.basePath}:{}}),L=li({id:"hlix-coder",name:D,model:c,instructions:Cn({projectPath:P,projectName:ii(e.cwd),mode:te,modelId:n,sandbox:e.sandbox,hasSubagents:v.length>0,...e.hostInstructions?{hostInstructions:e.hostInstructions}:{}}),tools:f,...e.workspace?{workspace:e.workspace}:{},...e.nestedRules?{inputProcessors:[e.nestedRules]}:{},memory:l}),j=jt({sandbox:e.sandbox,cwd:e.cwd,active:e.harness,readTools:ot(y),...e.workspace?{workspace:e.workspace}:{},...e.unavailableHarnesses?{unavailable:e.unavailableHarnesses}:{},model:n}),z=j.length>0?j:kn({registeredTools:y,modelId:n}),N=new ai({id:"hlix-code",resourceId:o.resourceId,agent:L,storage:s,memory:l,modes:z,subagents:v,tools:f,gateways:[r],omConfig:{defaultObserverModelId:n,defaultReflectorModelId:n,defaultObservationThreshold:a.observationThreshold,defaultReflectionThreshold:a.reflectionThreshold},toolCategoryResolver:xn(Object.keys(u)),...e.workspace?{workspace:e.workspace}:{}});await N.init();let k=await N.createSession({resourceId:o.resourceId,tags:{projectPath:o.root}});if(i=k,n)await k.model.switch({modelId:n});let W=Dt({fromFlag:e.harnessFromFlag===!0,harness:e.harness,modesBuilt:j.length>0,current:k.mode.get()});if(W)await k.mode.switch({modeId:W});for(let re of bn)await k.permissions.setForCategory(re);return{controller:N,session:k,gateway:r,store:s,memory:l,scope:o,harnessModesBuilt:j.length>0,subagentLine:jn(_,w.subagents),subagentsSkipped:w.skipped,dispose:async()=>{await N.destroy().catch(()=>{}),await s.close().catch(()=>{})}}}import{Editor as Ka,ProcessTerminal as Va,SelectList as Xr,Input as qa,TuiMainScreen as za,truncateToWidth as Ct}from"@earendil-works/pi-tui";import{readFileSync as pi,statSync as ui}from"node:fs";import{basename as mi,extname as gi,isAbsolute as fi,join as hi}from"node:path";import{CombinedAutocompleteProvider as yi,Key as Re,matchesKey as xi}from"@earendil-works/pi-tui";function bi(e,t=xi){if(t(e,Re.shift("tab")))return"cycle-mode";if(t(e,Re.ctrl("c")))return"interrupt";if(t(e,Re.ctrl("o")))return"expand";if(t(e,Re.escape))return"abort";return"text"}var Si=2000;class Fn{windowMs;armedAt=0;constructor(e=Si){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 vi(e){return[...e.entries()].map(([t,n])=>({name:t,description:n.description})).sort((t,n)=>t.name.localeCompare(n.name))}var lt="Press Ctrl-C again to leave Hlix Code.";class Hn extends yi{applyCompletion(e,t,n,r,o){let s=e[t]??"";if(/^\/[^\s/]*$/.test(s.slice(0,n))){let a=[...e];return a[t]=`/${r.value} ${s.slice(n)}`,{lines:a,cursorLine:t,cursorCol:r.value.length+2}}return super.applyCompletion(e,t,n,r,o)}}function wi(e=process.env){for(let t of["fd","fdfind"]){let n=qe(t,e);if(n)return n}return null}function Ei(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 Un(e){let t=new Fn;return e.editor.setAutocompleteProvider(new Hn(vi(e.commands),e.basePath,wi())),e.editor.onSubmit=(n)=>{let r=n.trim();if(!r){e.handlers.onEmptySubmit?.();return}e.editor.addToHistory(r),e.editor.setText(""),e.handlers.onSubmit(r)},e.tui.addInputListener((n)=>{switch(bi(n)){case"cycle-mode":return e.handlers.onCycleMode(),{consume:!0};case"interrupt":if(t.press()==="exit")e.handlers.onExit();else e.handlers.onInterruptWarning(lt);return{consume:!0};case"expand":return t.disarm(),e.handlers.onExpand(),{consume:!0};case"abort":if(e.editor.isShowingAutocomplete())return;if(Ei(e.tui,e.editor))return;return t.disarm(),e.handlers.onAbort(),{consume:!0};default:t.disarm();return}})}var _i={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},$n=8388608;function Bn(e,t,n=pi,r=(o)=>ui(o).size){let o=[],s=[],a=new Set;for(let i of e.matchAll(/(?:^|\s)@(\S+)/g)){let c=i[1],l=_i[gi(c).toLowerCase()];if(!l||a.has(c))continue;a.add(c);let g=fi(c)?c:hi(t,c);try{let u=r(g);if(u>$n){s.push(`@${c} is ${Math.round(u/1048576)} MB — too large to attach (limit ${$n/1048576} MB).`);continue}o.push({data:`data:${l};base64,${n(g).toString("base64")}`,mediaType:l,filename:mi(c)})}catch{s.push(`@${c} could not be read, so it was not attached.`)}}return{content:e,files:o,notes:s}}import{z as H}from"zod";var ne=H.string().trim().min(1),Ii=H.discriminatedUnion("kind",[H.object({kind:H.literal("project"),projectId:ne}).strict(),H.object({kind:H.literal("cycle"),projectId:ne,cycleId:ne}).strict(),H.object({kind:H.literal("task"),projectId:ne,taskId:ne}).strict(),H.object({kind:H.literal("agent"),projectId:ne,agentId:ne}).strict()]);import{z as d}from"zod";var Gn=["github-compare","workspace-artifact"],Te=d.enum(["added","removed","modified","renamed","copied","changed","unchanged","unknown"]),Wn=d.object({path:d.string(),previousPath:d.string().nullable(),status:Te,additions:d.number().nullable(),deletions:d.number().nullable(),patch:d.string().nullable(),patchTruncated:d.boolean()}),Yn=d.object({status:d.enum(["ahead","behind","identical","diverged","unknown"]),aheadBy:d.number().nullable(),behindBy:d.number().nullable()}),Kn=d.object({kind:d.literal("git-archive"),reviewUrl:d.string(),sizeBytes:d.number().nullable(),capturedAt:d.string().nullable()}),Vn=d.object({verdict:d.enum(["approved","rejected"]),summary:d.string().nullable(),headSha:d.string().nullable(),observedAt:d.string(),stale:d.boolean()}),Ci=d.object({taskId:d.string(),repoId:d.string().nullable(),source:d.enum(Gn),observedAt:d.string(),baseRef:d.string().nullable(),baseSha:d.string().nullable(),headRef:d.string().nullable(),headSha:d.string().nullable(),comparison:Yn,filesChanged:d.number().nullable(),additions:d.number().nullable(),deletions:d.number().nullable(),commits:d.number().nullable(),files:d.array(Wn),filesTruncated:d.boolean(),evaluator:Vn.nullable(),artifact:Kn.nullable()}),qn=["base","head"],ct=d.enum(qn),zn=["open","resolved"],dt=d.enum(zn),Xn=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(),Jn=["previews-disabled","boundary-unavailable","review-head-unavailable","no-live-preview","revision-mismatch","source-not-isolated","unsafe-source"],Zn=d.discriminatedUnion("enabled",[d.object({enabled:d.literal(!0)}),d.object({enabled:d.literal(!1),reasonCode:d.enum(Jn),reason:d.string()})]),Qn=d.string().regex(/^[0-9a-f]{40}$/i,"expected a commit sha"),er=d.object({id:d.string(),taskId:d.string(),projectId:d.string(),authorId:d.string(),headSha:d.string(),path:d.string().nullable(),side:ct.nullable(),lineStart:d.number().nullable(),lineEnd:d.number().nullable(),selectedText:d.string().nullable(),body:d.string(),resolution:dt,resolvedBy:d.string().nullable(),resolvedAt:d.string().nullable(),revisionIteration:d.number().nullable(),createdAt:d.string(),updatedAt:d.string(),stale:d.boolean()}),Ri=d.object({taskId:d.string(),headSha:d.string().nullable(),comments:d.array(er),visualContext:Zn.optional()}),Ti=d.object({headSha:Qn,body:d.string().min(1).max(1e4),path:d.string().min(1).max(1024).nullish(),side:ct.nullish(),lineStart:d.number().int().positive().nullish(),lineEnd:d.number().int().positive().nullish(),selectedText:d.string().max(1e4).nullish(),visualContext:Xn.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"})}),ki=d.object({resolution:dt}),Ai=d.object({headSha:Qn}),Pi=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 tr=h.enum(["github","workspace"]),pt=h.object({path:h.string(),previousPath:h.string().nullable(),status:Te,additions:h.number().nullable(),deletions:h.number().nullable(),binary:h.boolean()}),nr=h.object({sha:h.string(),subject:h.string(),at:h.string()}),ge=h.object({ref:h.string(),sha:h.string().nullable()}),rr=h.object({repoKey:h.string(),label:h.string(),base:ge,head:ge,files:h.array(pt),filesTruncated:h.boolean(),filesChanged:h.number(),additions:h.number(),deletions:h.number(),commits:h.array(nr),unavailable:h.enum(["repository_unreachable"]).nullable()}),or=h.object({taskId:h.string(),title:h.string(),repoKey:h.string(),files:h.array(pt),observedAt:h.string()}),Ni=h.object({projectId:h.string(),source:tr,environmentState:h.string().nullable(),observedAt:h.string(),repos:h.array(rr),inFlight:h.array(or)}),Mi=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:ge,paths:h.array(h.string()),truncated:h.boolean()}),Li=h.object({error:h.string(),environmentState:h.string()}),ji=h.object({repoKey:h.string(),path:h.string(),ref:ge,content:h.string().nullable(),truncated:h.boolean(),binary:h.boolean(),size:h.number().nullable()});var ke={"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 Di=Object.keys(ke);var $i={"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 B="◆",Fi=(()=>{let e={};for(let t of Object.keys(ke)){let n=ke[t];e[t]=n.displayName,e[$i[t]]=n.displayName,e[`${n.provider}:${t}`]=n.displayName}return e})();function Ae(e){if(!e)return e;let n=Fi[e]??e.split(/[/:]/).pop()??e;return`${B} ${n}`}var ut={"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}},mt=Object.keys(ut),Pe=Object.values(ut),Hi=Pe.filter(({driverKind:e})=>e==="external-acp").map(({id:e})=>e),sr=Pe.filter(({available:e,driverKind:t})=>e&&t==="external-acp"),gt=sr.map(({id:e})=>e),ir=Pe.filter(({available:e})=>e),ar=ir.map(({id:e})=>e),ft="hlix";var lr=["chat","kanban","linear","github","api"];var ht={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 cr(e){return lr.filter((t)=>ht[t].kind===e)}var Bi=cr("external"),Gi=cr("native");import{z as p}from"zod";var dr=p.enum(mt),pr=p.enum(gt),ur=p.object({node:p.string().optional(),python:p.string().optional(),bun:p.string().optional(),playwright:p.boolean().optional()}).partial(),mr=p.object({agents:p.array(pr).optional(),toolchain:ur.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(),Xi=p.object({owner:p.string(),name:p.string(),cloneUrl:p.string(),defaultBranch:p.string()}),gr=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 fr=p.object({name:p.string(),skillSlugs:p.array(p.string()),agentSlugs:p.array(p.string())}),hr=p.object({path:p.string(),content:p.string()}),yr=p.object({vars:p.record(p.string(),p.string()).default({}),files:p.array(hr).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()}),xr=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}$/)}),br=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:gr.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(fr),systemPrompt:p.string().optional(),timeoutSeconds:p.number().default(1800),resultToken:p.string().min(1).optional(),agent:dr.default(ft),agentEnv:p.record(p.string(),p.string()).optional(),projectRuntime:mr.optional(),environment:yr.optional(),protectedFiles:p.array(xr).optional()}),Ji=p.enum(["acp"]),Zi=p.enum(["builder","desktop","e2e"]),Qi=p.object({batchId:p.string(),tasks:p.array(br).min(1).max(20)}),Sr=p.object({inputTokens:p.number(),outputTokens:p.number(),costUsd:p.number()}),ea=p.object({taskId:p.string(),token:p.string().optional(),status:p.enum(["success","failed"]),cost:Sr.optional(),model:p.string().optional(),error:p.string().optional()});import{z as A}from"zod";var ta=A.discriminatedUnion("type",[A.object({type:A.literal("text"),text:A.string()}),A.object({type:A.literal("reasoning"),text:A.string()}),A.object({type:A.literal("tool"),toolCallId:A.string().min(1),toolName:A.string().min(1),state:A.enum(["pending","done","error"]),input:A.unknown().optional(),output:A.unknown().optional(),error:A.string().optional()})]);import{SelectList as na}from"@earendil-works/pi-tui";var yt=(e)=>e;function Ne(e){return(t)=>t?`\x1B[${e}m${t}\x1B[0m`:t}var ie={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 Me(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 ae=(e,t)=>{if(t==="none")return yt;if(t==="truecolor")return Ne(`38;2;${e.rgb[0]};${e.rgb[1]};${e.rgb[2]}`);return Ne(`38;5;${e.cube}`)};function Oe(e=Me()){return{brand:ae(ie.gold,e),muted:e==="none"?yt:Ne("2"),user:ae(ie.paper,e),alert:ae(ie.vermilion,e),ok:ae(ie.teal,e),added:ae(ie.teal,e),removed:ae(ie.vermilion,e)}}function le(e){return{selectedPrefix:e.brand,selectedText:e.brand,description:e.muted,scrollInfo:e.muted,noMatch:e.muted}}function vr(e){return{borderColor:e.muted,selectList:le(e)}}function wr(e,t=Me()){let n=(r)=>t==="none"?yt:Ne(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 ra=12;function oa(e){let t=/^(.*?)\(([^()]*)\)\s*$/.exec(e);if(!t)return Ae(e);let n=(t[1]??"").trim(),r=Ae(t[2]??"").slice(B.length).trim();return n?`${B} ${n} (${r})`:`${B} ${r}`}function xt(e){let t=new Set,n=[],r=(o,s)=>{if(t.has(o))return;t.add(o),n.push({id:o,label:oa(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 _r(e){let t=ve(e.cwd)?"project":"global";return Er({key:"model",value:e.modelId,scope:t,cwd:e.cwd,env:e.env})}function Ir(e){let t=e.colors??Oe(),n=e.entries.map((i)=>({value:i.id,label:i.label})),r=new na(n,ra,le(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%"}),a=()=>{s.hide(),e.tui.requestRender()};r.onSelect=(i)=>{a();let c=e.entries.find((l)=>l.id===i.value);if(c)e.onPick(c)},r.onCancel=()=>{a(),e.onCancel?.()},s.focus()}import{Markdown as ca,truncateToWidth as G,wrapTextWithAnsi as vt}from"@earendil-works/pi-tui";function Cr(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 l=r-1;l>=0;l-=1)o[c][l]=e[c]===t[l]?o[c+1][l+1]+1:Math.max(o[c+1][l],o[c][l+1]);let s=[],a=0,i=0;while(a<n&&i<r)if(e[a]===t[i])s.push({kind:"same",text:e[a]}),a+=1,i+=1;else if(o[a+1][i]>=o[a][i+1])s.push({kind:"del",text:e[a]}),a+=1;else s.push({kind:"add",text:t[i]}),i+=1;while(a<n)s.push({kind:"del",text:e[a++]});while(i<r)s.push({kind:"add",text:t[i++]});return s}function Rr(e,t,n={}){let r=n.context??2,o=Cr(e.split(`
21
+ `),t.split(`
22
+ `)),s=new Set;o.forEach((l,g)=>{if(l.kind==="same")return;for(let u=g-r;u<=g+r;u+=1)if(u>=0&&u<o.length)s.add(u)});let a=[],i=0,c=()=>{if(i===0)return;a.push(` … ${i} unchanged line${i===1?"":"s"}`),i=0};return o.forEach((l,g)=>{if(!s.has(g)){i+=1;return}c(),a.push(`${l.kind==="add"?"+":l.kind==="del"?"-":" "} ${l.text}`)}),c(),a}function Tr(e,t){let n=Cr(e.split(`
23
+ `),t.split(`
24
+ `)),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 sa="subagent",Pr=()=>({entries:[],busy:!1,status:"",approval:null});function Le(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 kr(e,t){let n=t??{},r=n.path??n.command??n.pattern??n.query;return typeof r==="string"?`${O(e)} ${r}`:O(e)}function Ar(e){let t=e===void 0?null:/^Exit code: (\d+)$/m.exec(e);return t?Number(t[1]):void 0}function ia(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(`
25
+ `);try{return JSON.stringify(e,null,2)}catch{return String(e)}}var aa={om_observation_start:"remembering…",om_observation_end:"",om_reflection_start:"condensing memory…",om_reflection_end:"",compaction_start:"compacting…",compaction_end:""},la={thread_created:()=>"New conversation.",info:(e)=>typeof e.message==="string"?e.message:null};function Nr(e,t){let n=(i,c)=>{let l=e.entries.findIndex((u)=>u.id===i),g=[...e.entries];if(l<0)g.push(c);else g[l]=c;return{...e,entries:g}},r=(i)=>({...e,entries:[...e.entries,i]}),o=(i)=>e.entries.find((c)=>c.id===i),s=(i)=>`tool:${String(i)}`,a=(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=Le(i);if(!c)return e;let l=`msg:${i.id}`;if(o(l)?.text===c)return e;return n(l,{kind:i.role==="user"?"user":"assistant",id:l,text:c})}case"tool_start":{if(t.toolName===sa)return e;let i=s(t.toolCallId),c=O(t.toolName);return n(i,{kind:"tool",id:i,text:kr(t.toolName,t.args),tool:{name:c,args:t.args,state:"running"}})}case"tool_approval_required":{let i=s(t.toolCallId),c=o(i),l={toolCallId:String(t.toolCallId),toolName:t.toolName,args:t.args},g=c?.tool?{...c,tool:{...c.tool,state:"awaiting"}}:{kind:"tool",id:i,text:kr(t.toolName,t.args),tool:{name:O(t.toolName),args:t.args,state:"awaiting"}};return{...n(i,g),approval:l}}case"tool_end":{let i=s(t.toolCallId),c=o(i);if(!c?.tool)return e;let l=t.denied===!0,g=t.isError===!0,u=ia(t.result),f=n(i,{...c,error:g||l,tool:{...c.tool,result:u,state:l?"declined":g?"error":"done",...Ar(u)!==void 0?{exitCode:Ar(u)}:{}}});return e.approval?.toolCallId===String(t.toolCallId)?{...f,approval:null}:f}case"subagent_start":{let i=a(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=a(t.toolCallId),c=o(i);if(!c?.subagent)return e;return n(i,{...c,subagent:{...c.subagent,tools:[...c.subagent.tools,O(t.subToolName)]}})}case"subagent_end":{let i=a(t.toolCallId),c=o(i);if(!c?.subagent)return e;let l=t.isError===!0;return n(i,{...c,error:l,subagent:{...c.subagent,state:l?"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=aa[t.type];if(i!==void 0)return{...e,status:i};let c=la[t.type]?.(t);return c===null||c===void 0?e:r({kind:"notice",id:`${t.type}:${e.entries.length}`,text:c})}}}function Mr(e){return e.replace(/\r\n/g,`
26
+ `).split(`
27
+ `).map((t)=>t.split("\r").reduce((n,r)=>r+n.slice(r.length),""))}function je(e){let t=e.state??(e.failed?"failed":"done");return{kind:"command",id:`cmd:${e.index}`,title:`/${e.name}`,text:e.output,...t==="failed"&&!e.report?{error:!0}:{},command:{state:t,elapsedMs:e.elapsedMs??0,...e.exitCode===void 0?{}:{exitCode:e.exitCode},...e.report?{report:e.report}:{}}}}var da={user:"›",assistant:" ",tool:"⏺",command:"▸",subagent:"↳",notice:"·"},fe=8,Or=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],pa=(e)=>Or[Math.floor(Math.max(0,e)/100)%Or.length],bt=(e,t)=>t?`${Math.floor(e/1000)}s`:`${(e/1000).toFixed(1)}s`;function ua(e,t){if(t.state==="running")return`${e} ${pa(t.elapsedMs)} ${bt(t.elapsedMs,!0)}`;if(t.state==="cancelled")return`${e} cancelled after ${bt(t.elapsedMs,!0)}`;let n=t.exitCode!==void 0&&t.exitCode!==0;return`${e} ${bt(t.elapsedMs,!1)}${n?` · exit ${t.exitCode}`:""}`}function St(e,t,n){let r=`┌ ${e} `,o=Math.max(0,t-r.length);return n(G(`${r}${"─".repeat(o)}`,t))}var ma=(e,t)=>t(G(`└${"─".repeat(Math.max(0,e-1))}`,e));function U(e,t,n,r){let o=Math.max(1,t-2),s=[];for(let a of e){let i=a===""?[""]:vt(a,o);for(let c of i)s.push(G(`${r("│")} ${n(c)}`,t))}return s}function ga(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=Tr(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 fa(e){switch(e.tool?.state){case"running":return"⏺";case"awaiting":return"?";case"declined":return"⊘";case"error":return"✗";default:return"✓"}}function ha(e){let t=e.tool;if(!t)return[];let n=t.args??{};if(typeof n.old_string==="string"&&typeof n.new_string==="string")return Rr(n.old_string,n.new_string);let r=(t.result??"").trimEnd();return r===""?[]:r.split(`
28
+ `)}function De(e,t){let n=e-t;return`… ${n} more line${n===1?"":"s"} — ctrl-o to expand`}function Lr(e,t){let{width:n,colors:r}=t;switch(e.kind){case"assistant":return jr(e.text,n,r);case"command":return xa(e,t);case"tool":return Sa(e,t);case"subagent":return wa(e,t);default:{let o=e.kind==="user"?r.user:e.error?r.alert:r.muted,s=e.error?"!":da[e.kind];return ya(e.text,s,n,o)}}}function jr(e,t,n){let r=Math.max(8,t-2);return new ca(e,0,0,wr(n)).render(r).map((s)=>G(` ${s}`,t))}function ya(e,t,n,r){let o=Math.max(1,n-2),s=[];for(let a of e.split(`
29
+ `)){let i=a===""?[""]:vt(a,o);for(let c of i){let l=s.length===0?`${t} `:" ";s.push(G(`${l}${r(c)}`,n))}}return s}function xa(e,t){let{width:n,colors:r}=t,o=e.command??{state:e.error?"failed":"done",elapsedMs:0},s=e.error?r.alert:r.muted,a=ua(e.title??"command",o),i=ma(n,s);if(o.report)return[St(a,n,s),...ba(e,o,t,s),i];let c=e.text===""?["(no output)"]:Mr(e.text),l=o.state==="running",g=e.expanded===!0?c:l?c.slice(-fe):c.slice(0,fe*3),u=c.length-g.length;return[St(a,n,s),...U(g,n,e.error?r.alert:r.user,s),...u>0?U([De(c.length,g.length)],n,r.muted,s):[],i]}function ba(e,t,n,r){let{width:o,colors:s}=n,a=t.report;if(!a)return[];let i=e.expanded===!0?a.rows:a.rows.slice(0,fe);return[...U([`⚠ ${a.headline}`],o,s.brand,r),...i.length>0?U(["",...i],o,s.user,r):[],...i.length<a.rows.length?U([De(a.rows.length,i.length)],o,s.muted,r):[],...a.notes.length>0?U(a.notes,o,s.muted,r):[],...a.next?U(["",`→ ${a.next}`],o,s.brand,r):[]]}function Sa(e,t){let{width:n,colors:r}=t,o=e.tool,s=fa(e),a=e.error?r.alert:o?.state==="running"?r.muted:r.ok,i=ga(e),c=`${s} ${e.text}`,l=n-c.length-i.length-1,g=i&&l>0?G(`${a(c)}${" ".repeat(l)}${r.muted(i)}`,n):G(a(c),n);if(o?.state==="running"||o?.state==="awaiting")return[g];let u=ha(e);if(u.length===0)return[g];let f=e.expanded===!0?u:u.slice(0,fe);return[g,...va(f,n,r),...f.length<u.length?U([De(u.length,f.length)],n,r.muted,r.muted):[]]}function va(e,t,n){let r=Math.max(1,t-2),o=[];for(let s of e){let a=s.startsWith("+")?n.added:s.startsWith("-")?n.removed:n.muted;for(let i of s===""?[""]:vt(s,r))o.push(G(`${n.muted("│")} ${a(i)}`,t))}return o}function wa(e,t){let{width:n,colors:r}=t,o=e.subagent;if(!o)return[];let s=e.error?r.alert:r.muted,a=o.state==="running"?"↳":e.error?"✗":"✓",i=o.durationMs!==void 0?` · ${(o.durationMs/1000).toFixed(1)}s`:"",c=G(`${(e.error?r.alert:r.brand)(`${a} ${o.agentType}`)}${r.muted(`${i}${o.tools.length>0?` · ${o.tools.length} tool calls`:""}`)}`,n),l=[o.task];if(o.tools.length>0)l.push(`tools: ${[...new Set(o.tools)].join(", ")}`);if(o.state!=="running"&&o.result){let g=o.result.split(`
30
+ `),u=e.expanded===!0?g:g.slice(0,fe);if(l.push("",...u),u.length<g.length)l.push(De(g.length,u.length))}return[c,...U(l,n,r.muted,s)]}function Dr(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!==""),a=O(e.toolName);return[St(`Approve ${a}`,n,r.alert),...U(s?[s]:["(no arguments)"],n,r.user,r.alert)]}var he="yolo";function Ea(e,t){if(t<=0)return`${Math.round(e/1000)}k`;return`${Math.round(e/t*100)}% of ${Math.round(t/1000)}k`}function _a(e){return e>0&&e<0.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Ia=4,Ca=["cost","total_cost","costUsd"];function $e(e){let t=e?.raw;for(let n=0;n<Ia&&t&&typeof t==="object";n+=1){for(let r of Ca){let o=t[r];if(typeof o==="number"&&Number.isFinite(o)&&o>0)return o}t=t.raw}return}var Ra=(e)=>e.startsWith(B)?e:`${B} ${e}`,Ta=(e)=>e.split(" (")[0];function ka(e){let t=[...e.yolo?[he]:[],e.sandbox,e.harness];if(e.mode&&e.mode!==Ta(e.harness))t.push(e.mode);if(e.model)t.push(Ra(e.model));if(e.workspace)t.push(e.workspace);if(e.branch)t.push(e.branch);if(e.context)t.push(Ea(e.context.used,e.context.total));if(e.costUsd!==void 0)t.push(_a(e.costUsd));if(e.memory)t.push(e.memory);if(e.warning)t.push(e.warning);return t}function $r(e,t){let n=ka(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)}…`}import{readdirSync as Ma,readFileSync as Oa}from"node:fs";import{basename as La,join as ja}from"node:path";var Aa={scan_blocked:{next:(e)=>`/${e} --history preserve`,needs:"history"},approval_required:{next:(e)=>`/${e} --dry-run`,needs:"dry-run"},unauthenticated:{next:()=>"/auth-login"},missing_credential:{next:()=>"/auth-login"},workspace_required:{next:()=>"/auth-login"},already_imported:{next:()=>"/push"},not_initialized:{next:()=>"/init"}},wt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Fr=(e)=>(e.split(`
31
+ `)[0]??e).replace(/:$/,"");function Pa(e){let t=e;return Array.isArray(t?.findings)&&Array.isArray(t?.blocking)}function Na(e){let t=new Map;for(let n of e)t.set(n.path,[...t.get(n.path)??[],n]);return[...t].map(([n,r])=>{let o=[...new Set(r.map((a)=>a.reason))].join(", "),s=r[0];return r.length===1?`${s.commit.slice(0,7)} · ${n} · ${o}`:`${n} ×${r.length} · ${o}`})}function Hr(e){if(e.code==="unknown")return null;let t=Aa[e.code],n=t?.needs===void 0||e.options?.includes(t.needs)!==!1,r=t&&n?t.next(e.name):null;if(e.code==="scan_blocked"&&Pa(e.details)){let{findings:a,fixtureFindings:i,blocking:c}=e.details;return{headline:a.length>0?`Import blocked — ${wt(a.length,"finding")} in Git history`:`Import blocked — ${wt(c.length,"finding")}`,rows:[...Na(a),...c.map(Fr)],notes:i>0?[`${wt(i,"finding")} look like fixtures (not blocking)`]:[],next:a.length>0?r:null}}let[o,...s]=e.message.split(`
32
+ `);return{headline:Fr(o??e.message),rows:s.filter((a)=>a.trim()!==""),notes:[],next:r}}var Kr=(e)=>e.split(" ").join("-");function Da(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 Ur="Project prompt";function $a(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(e);if(!t)return{description:Ur,body:e};return{description:/^description:[ \t]*(.+)$/m.exec(t[1]??"")?.[1]?.trim()||Ur,body:e.slice(t[0].length).replace(/^(?:[ \t]*\r?\n)+/,"")}}function Fa(e){let t=new Map;for(let n of e){let r;try{r=Ma(n)}catch{continue}for(let o of r){if(!o.endsWith(".md"))continue;try{t.set(La(o,".md"),$a(Oa(ja(n,o),"utf8")))}catch{continue}}}return t}function Ha(e,t){let n=t.trim();if(e.includes("$ARGUMENTS"))return e.split("$ARGUMENTS").join(n);return n?`${e.trimEnd()}
33
+
34
+ ${n}`:e}function Br(e,t){return async(n,r,o)=>{let s="",a=(u)=>{s+=u,o?.onOutput?.(u)},i=[],c=await de([e],Da(e,n,r),{stdout:a,stderr:a,env:t,...o?.signal?{signal:o.signal}:{},onFailure:(u)=>i.push(u)}),l=i.at(-1),g=l?Hr({name:Kr(e.name),...e.options?{options:e.options}:{},...l}):null;return{lines:[],output:s.trimEnd()||`exit ${c}`,exitCode:c,...c===0?{}:{failed:!0},...g?{report:g}:{}}}}var Fe={lines:["This command needs a live session."]};async function Gr(e,t,n,r,o){let s=o.find((g)=>g.name==="config set");if(!s)return{ok:!1,message:`This build has no \`config set\`, so ${e} was not written.`};let a="",i=(g)=>{a+=g},c=await de([s],["config","set",e,t,"--cwd",n],{stdout:i,stderr:i,env:r}),l=a.trim();if(c===0)return{ok:!0,message:l||`${e} is ${t}.`};return{ok:!1,message:[`${e} was NOT written: ${l.replace(/^error:\s*/,"")||"config set failed."}`,`To set it for every project: \`hlix config set ${e} ${t} --global\`.`].join(`
35
+ `)}}function Vr(e={}){let t=e.env??process.env,n=e.shell,r=new Map,o=(l)=>r.set(l.name,l),s=e.commands??Se;for(let l of s)o({name:Kr(l.name),description:l.summary,handler:Br(l,t)});let a=(l,g,u)=>{let f=s.find((y)=>y.name===g);if(f)o({name:l,description:u,handler:Br(f,t)})};for(let[l,g]of Fa(e.promptFiles??[])){if(r.has(l))continue;o({name:l,description:g.description,prompt:(u)=>Ha(g.body,u),handler:()=>({lines:[]})})}a("config","config list","Show this folder's settings and where each came from"),a("secrets","secrets list","List this project's stored secrets, masked"),a("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(l,g)=>{let u=n?.facts;if(!u)return{lines:["Sandbox not resolved."]};let f=l.trim(),y=async(_)=>{let w=await Gr("sandbox",_,g,t,s);return{lines:[],output:[u.sandboxLine,w.ok?`${w.message} This session keeps ${u.sandbox}; restart to run in ${_}.`:w.message].join(`
36
+ `),...w.ok?{}:{failed:!0}}};if(f){if(!ee.includes(f))return{lines:[`/sandbox must name one of ${ee.join(", ")}.`]};return y(f)}if(!n?.openPicker)return{lines:[],output:u.sandboxLine};return n.openPicker({title:"Sandbox",current:u.sandbox,choices:ee.map((_)=>({value:_,label:_,description:Ua[_]})),apply:y}),{lines:[]}}}),o({name:"harness",description:"Show or change which coder does the work (`clear` un-pins the project)",handler:async(l,g)=>{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(w)=>{let v=Xe({requested:w,current:f,available:u.availableHarnesses,sandbox:u.sandbox,sandboxLine:u.sandboxLine,modesBuilt:u.harnessModesBuilt});if(v.action==="mode"&&n?.session)await n.session.mode.switch({modeId:v.harness}),n.setFact?.({harness:v.harness,mode:v.harness});if(v.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(v.harness),n.setFact?.({harness:v.harness})}let P=v.action==="restart"?await Gr("harness",w,g,t,s):null;return{lines:[],output:P?`${v.message}
37
+ ${P.message}`:v.message,...P&&!P.ok?{failed:!0}:{}}},_=l.trim();if(_==="clear"){if(!n?.clearProjectHarness)return{lines:["This folder is not bound to a hlix project, so there is no project preference to clear. Run `hlix init` or pass --project <id>."]};let w=await n.clearProjectHarness();if(w)n.setFact?.({harness:w});return{lines:[],output:w?`Project harness preference cleared. Now: ${w}.`:"Project harness preference cleared. Run `/harness` for what runs now."}}if(_)return y(_);if(!n?.openPicker)return{lines:[],output:`harness: ${f}`};return n.openPicker({title:"Harness",current:f,choices:Y.map((w)=>({value:w,label:w,description:u.availableHarnesses.includes(w)?w==="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 Fe;return await n.session.thread.create(),{lines:[]}}}),o({name:"threads",description:"List this project's conversations, newest first",handler:async(l)=>{if(!n?.session)return Fe;let g=l.trim();if(g&&g!=="--all")return{lines:[],output:await Yr(n,g)};let u=He(await n.session.thread.list()),f=He(await It(n)),y=n.session.thread.getId();if(u.length===0&&f.length===0)return{lines:[],output:"No conversations here yet."};let _=u.map((w)=>_t(w,y));if(g==="--all")_.push(...Wr(f));else if(f.length>0)_.push(Wa(f.length));return{lines:[],output:_.join(`
38
+ `)}}}),o({name:"resume",description:"Pick an earlier conversation in this project and continue it",handler:async()=>{if(!n?.session)return Fe;let l=He(await n.session.thread.list()),g=He(await It(n));if(l.length===0&&g.length===0)return{lines:[],output:"No conversations here yet."};let u=n.session.thread.getId();if(!n.openPicker)return{lines:[],output:[...l.map((f)=>_t(f,u)),...Wr(g)].join(`
39
+ `)};return n.openPicker({title:"Resume",...u?{current:u}:{},choices:[...l.map((f)=>({value:f.id,label:f.title?.trim()||"(untitled)",description:`${f.id} ${Et(f.updatedAt)}`})),...g.map((f)=>({value:f.id,label:f.title?.trim()||"(untitled)",description:`${f.id} ${Et(f.updatedAt)} ${Ba}`}))],apply:async(f)=>({lines:[],output:await Yr(n,f)})}),{lines:[]}}}),o({name:"compact",description:"Condense this conversation into memory now",handler:async()=>{if(!n?.compact)return Fe;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 l=n.log.tail(200);return{lines:[],output:l.length===0?`Nothing logged this session.
40
+ ${n.log.path}`:[...l,"",n.log.path].join(`
41
+ `)}}}),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:(l)=>{if(!n?.yolo)return{lines:["Approvals are not resolved in this mode."]};let g=l.trim().toLowerCase(),u=g===""?!n.yolo.get():!["off","false","0","no"].includes(g);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((l)=>`/${l.name.padEnd(22)} ${l.description}`).sort().join(`
42
+ `)})});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(l,g)=>{let u=await c.handler(l,g),f=n.mcp?.()??[];if(f.length===0)return u;return{...u,output:[u.output??"","MCP servers (this session)",...f.map((y)=>` ${y}`)].join(`
43
+ `).trim()}}});return r}var Ua={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 He(e){return[...e].sort((t,n)=>(n.updatedAt?.getTime()??0)-(t.updatedAt?.getTime()??0))}function Et(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 _t=(e,t)=>`${e.id===t?"›":" "} ${(e.title?.trim()||"(untitled)").padEnd(40)} ${Et(e.updatedAt)}`,Ba="· older";function Ga(e,t){return e.filter((n)=>n.resourceId===t.legacyResourceId&&Qt(n.metadata?.projectPath,t.root))}async function It(e){if(!e.session||!e.memory)return[];return Ga(await e.session.thread.list({allResources:!0}),e.memory)}var Wa=(e)=>`${e} older thread${e===1?"":"s"} from before per-project memory — /threads --all to see them`,Wr=(e)=>e.length===0?[]:["","before per-project memory (resuming one copies it into this project):",...e.map((t)=>_t(t,null))];async function Yr(e,t){let n=e.session;if(!n)return"No session.";try{return await n.thread.switch({threadId:t,emitEvent:!0}),`Resumed ${t}.`}catch(r){let o=await Ya(e,t);if(!o)throw r;return`Resumed ${t} as ${o} — copied into this project's memory.`}}async function Ya(e,t){let n=e.session?.thread,r=e.memory;if(!n?.cloneToCurrentResource||!r)return null;let s=(await It(e)).find((i)=>i.id===t)?.metadata?.projectPath;if(typeof s!=="string")return null;return(await n.cloneToCurrentResource({threadId:t,expectedResourceId:r.legacyResourceId,expectedProjectPath:s})).id}function qr(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 zr(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 Jr{colors;state=Pr();expanded=new Set;constructor(e){this.colors=e}render(e){return this.state.entries.flatMap((t)=>[...Lr(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 Zr{colors;text="";constructor(e){this.colors=e}render(e){return this.text===""?[]:[this.colors.muted(Ct(`· ${this.text}`,e))]}invalidate(){}}class Qr{colors;facts=null;constructor(e){this.colors=e}render(e){if(!this.facts)return[];let t=$r(this.facts,e);if(this.facts.yolo!==!0||!t.startsWith(he))return[this.colors.muted(t)];return[`${this.colors.alert(he)}${this.colors.muted(t.slice(he.length))}`]}invalidate(){}}class eo{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 to(e){let t=Oe(Me(e.env)),n=e.tui??new za(new Va),r=new Jr(t),o=new Zr(t),s=new eo,a=new Qr(t),i={...e.facts};a.facts=i;let c=0,l=()=>n.requestRender(),g=(m)=>{r.state={...r.state,entries:[...r.state.entries,m]},l()},u=(m)=>{r.state={...r.state,entries:r.state.entries.map((x)=>x.id===m.id?m:x)},l()},f=(m)=>{r.state={...r.state,entries:r.state.entries.filter((x)=>x.id!==m)},l()},y=(m)=>{g({kind:"notice",id:`warn:${c++}`,text:m,error:!0})},_=(m)=>{g({kind:"notice",id:`say:${c++}`,text:m})},w=(m,x)=>{for(let b of x.lines)y(b);if(x.output===void 0)return;g(je({name:m,output:x.output,index:c++,...x.failed?{failed:!0}:{}}))},v=null,P=null,L=null,j=()=>{o.text=v?`running /${v.name} — ESC to cancel`:r.state.status},z=()=>{if(P===null)return;clearInterval(P),P=null},N=new Ka(n,vr(t)),k=()=>{s.close(),n.setFocus(N),n.requestRender()},W=(m)=>{let{content:x,files:b,notes:S}=Bn(m,e.cwd);g({kind:"user",id:`you:${c++}`,text:m});for(let R of S)y(R);e.session.sendMessage({content:x,...b.length>0?{files:b}:{}}).catch((R)=>{y(R instanceof Error?R.message:String(R))})},re=(m)=>{let x=m.choices.map((S)=>({value:S.value,label:S.value===m.current?`${S.label} (current)`:S.label,...S.description?{description:S.description}:{}})),b=new Xr(x,Math.min(x.length,8),le(t));b.onSelect=(S)=>{k(),Promise.resolve(m.apply(S.value)).then((R)=>w(m.title.toLowerCase(),R)).catch((R)=>{y(`${m.title}: ${R instanceof Error?R.message:String(R)}`)})},b.onCancel=k,s.open((S)=>[t.brand(Ct(m.title,S))],b),n.setFocus(s),n.requestRender()},ye=(m,x)=>{let b=e.commands.get(m);if(!b){y(`Unknown command /${m}. Try /help.`);return}if(b.prompt){W(b.prompt(x));return}if(v){y(`/${v.name} is still running. Press ESC to cancel it first.`);return}let S={name:m,index:c++,started:Date.now(),output:"",controller:new AbortController,cancelled:!1};v=S;let R=(I={})=>je({name:m,index:S.index,output:I.output??S.output,elapsedMs:I.elapsedMs??Date.now()-S.started,...I.state?{state:I.state}:{},...I.failed?{failed:!0}:{},...I.exitCode===void 0?{}:{exitCode:I.exitCode},...I.report?{report:I.report}:{}}),ce=()=>{if(v===S)v=null;z(),j()};g(R({output:"",state:"running",elapsedMs:0})),j(),P=setInterval(()=>{if(v===S)u(R({state:"running"}))},200),(async()=>b.handler(x,e.cwd,{onOutput:(I)=>{if(v!==S)return;S.output+=I,u(R({state:"running"}))},signal:S.controller.signal}))().then((I)=>{if(S.cancelled)return;ce();for(let be of I.lines)y(be);if(I.output===void 0){f(`cmd:${S.index}`);return}if(u(R({output:I.output,...I.failed?{failed:!0}:{},...I.exitCode===void 0?{}:{exitCode:I.exitCode},...I.report?{report:I.report}:{}})),L=I.report?.next??null,I.quit)n.stop()}).catch((I)=>{if(S.cancelled)return;ce();let be=I instanceof Error?I.message:String(I);u(R({output:be,failed:!0})),y(`/${m} failed: ${be}`)})},Ge=()=>{let m=v;if(!m)return;m.cancelled=!0,m.controller.abort(),v=null,z(),j(),u(je({name:m.name,index:m.index,output:m.output,state:"cancelled",elapsedMs:Date.now()-m.started}))},xe=()=>{if(e.models.length===0){y("No models to choose from. Run `hlix auth login`.");return}Ir({tui:n,entries:e.models,...i.model?{current:i.model}:{},colors:t,onPick:(m)=>{(async()=>{try{await e.session.model.switch({modelId:m.id});let x=_r({modelId:m.id,cwd:e.cwd,env:e.env});i.model=m.label,e.onModelPicked?.(m),_(`Model is ${m.label} — written to ${x}.`)}catch(x){y(`Could not switch model: ${x instanceof Error?x.message:String(x)}`)}})()},onCancel:()=>n.setFocus(N)})},C=(m,x,b)=>{e.session.respondToToolApproval({decision:x,toolCallId:m,...b?{declineContext:{reason:b}}:{}})},E=(m)=>{if(e.yolo?.get()){C(m.toolCallId,"approve");return}let x=vn(m.toolName),b=new Xr(x.map((S)=>({value:S.value,label:S.label,description:S.description})),x.length,le(t));b.onSelect=(S)=>{if(S.value!=="decline"){k(),C(m.toolCallId,S.value);return}let R=new qa({prompt:"why not? (enter to skip) ",placeholder:"reason"}),ce=(I)=>{k(),C(m.toolCallId,"decline",I.trim())};R.onSubmit=ce,R.onEscape=()=>ce(""),s.open(()=>[],R),n.setFocus(s),n.requestRender()},b.onCancel=()=>{k(),C(m.toolCallId,"decline","The user dismissed the approval prompt.")},s.open((S)=>Dr({toolCallId:m.toolCallId,toolName:m.toolName,args:m.args},{width:S,colors:t}),b),n.setFocus(s),n.requestRender()};e.session.subscribe((m)=>{if(m.type==="tool_approval_required")E(m);if(m.type==="mode_changed")i.mode=m.modeId;if(m.type==="usage_update"){let b=$e(m.usage);if(i.context={used:m.usage.totalTokens,total:i.context?.total??0},b!==void 0)i.costUsd=b}let x=Nr(r.state,m);if(x!==r.state)r.state=x;j(),l()});let We=Un({tui:n,editor:N,commands:e.commands,basePath:e.cwd,handlers:{onSubmit:(m)=>{L=null;let x=qr(m);if(x.kind==="slash"){let b=zr(x,e.commands);ye(b.name,b.args);return}W(m)},onCycleMode:()=>{let m=Tn(e.session.mode.get());e.session.mode.switch({modeId:m}).catch(()=>{y("This session's harness has no build/plan modes. Try /harness.")})},onAbort:()=>{if(v){Ge();return}if(!r.state.busy)return;e.session.abort(),_("Aborted.")},onEmptySubmit:()=>{if(!L)return;N.setText(L),L=null,n.requestRender()},onExpand:()=>{let m=r.lastCollapsible();if(!m)return;if(r.expanded.has(m.id))r.expanded.delete(m.id);else r.expanded.add(m.id);n.requestRender()},onInterruptWarning:()=>_(lt),onExit:()=>n.stop()}});for(let m of e.notices??[])_(m);if(n.addChild(new class{render(m){return[t.brand(Ct(`◆ ${D}`,m)),""]}invalidate(){}}),n.addChild(r),n.addChild(o),n.addChild(s),n.addChild(N),n.addChild(a),n.setFocus(N),l(),e.commands.set("model",{name:"model",description:"Pick the model this session runs on",handler:()=>(xe(),{lines:[]})}),e.bindings)e.bindings.openPicker=re,e.bindings.openModelPicker=xe,e.bindings.setFact=(m)=>{if(m.harness!==void 0)i.harness=m.harness;if(m.mode!==void 0)i.mode=m.mode;if(m.yolo!==void 0)i.yolo=m.yolo;l()};await new Promise((m)=>{let x=n.stop.bind(n);n.stop=(b)=>{We(),z(),x(b),m()},n.start()})}var Xa=new Set(["display_state_changed","tool_input_start","tool_input_delta","tool_input_end","om_status"]),Ja=(e)=>!Xa.has(e);function Za(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=Le(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=$e(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 no(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((l)=>{if(e.json&&Ja(l.type))t(`${Za(l)}
44
+ `);if(l.type==="tool_approval_required"){let g=Sn({toolName:l.toolName,yolo:e.yolo===!0});e.session.respondToToolApproval({decision:g.decision,toolCallId:l.toolCallId,...g.reason?{declineContext:{reason:g.reason}}:{}});return}if(l.type==="message_end"){if(l.message.role!=="user")r=Le(l.message);return}if(l.type==="error"){o=l.error?.message??String(l.error);return}if(l.type==="agent_end")s=l.reason??"complete",c(),i()});e.session.sendMessage({content:e.prompt}).catch((l)=>{o=l instanceof Error?l.message:String(l),c(),i()})});let a=s==="complete"&&o===null;if(!e.json){if(r)t(`${r}
45
+ `);if(o)n(`${o}
46
+ `);else if(!a)n(`the turn ended ${s}
47
+ `)}return{text:r,exitCode:a?0:1}}import{appendFileSync as Qa,mkdirSync as el}from"node:fs";import{homedir as tl}from"node:os";import{dirname as nl,join as ro}from"node:path";var rl=["log","info","warn","error","debug","trace"];function ol(e=process.env){let t=e.HLIX_CONFIG_HOME??ro(e.HOME??tl(),".hlix");return ro(t,"code","hlix-code.log")}var sl={log:"notes",info:"notes",debug:"notes",trace:"notes",warn:"warnings",error:"errors"};function il(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 Rt(e=process.env,t=console){let n=ol(e),r=new Set,o=[],s={notes:0,warnings:0,errors:0},a=new Map,i=(l,g)=>{let u=`${new Date().toISOString()} ${l} ${g}`;o.push(u);try{el(nl(n),{recursive:!0}),Qa(n,`${u}
48
+ `,"utf8")}catch{}};for(let l of rl)a.set(l,t[l]),t[l]=(...g)=>{let u=g.map(il).join(" ");if(r.has(`${l}:${u}`))return;r.add(`${l}:${u}`),s[sl[l]]+=1,i(l,u)};let c=!1;return{path:n,counts:s,note:(l)=>i("hlix",l),tail:(l)=>o.slice(Math.max(0,o.length-l)),restore:()=>{if(c)return;c=!0;for(let[l,g]of a)t[l]=g}}}function oo(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 al}from"@mastra/mcp";var Tt={tools:{},statusLines:[],summary:"",connected:[],failed:[],stop:async()=>{}};function ll(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 cl(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,a)=>a.length-s.length)[0];if(o)n[o]=(n[o]??0)+1}return n}var Be=(e,t)=>`${e} ${t}${e===1?"":"s"}`;async function kt(e){if(e.servers.length===0)return Tt;let{servers:t,skipped:n}=ll(e.servers,e.cwd),r=Object.keys(t),o=e.timeoutMs??20000,s=[...n];if(r.length===0)return Ue({failed:s});let a;try{a=(e.client??((y)=>new al(y)))({id:`hlix-code:${e.cwd}`,servers:t,timeout:o})}catch(f){for(let y of r)s.push({name:y,reason:so(f)});return Ue({failed:s})}let i={},c={};try{let f=await a.listToolsWithErrors({perServerTimeoutMs:o});i=f.tools,c=f.errors}catch(f){for(let y of r)s.push({name:y,reason:so(f)});return await a.disconnect().catch(()=>{}),Ue({failed:s})}for(let[f,y]of Object.entries(c))s.push({name:f,reason:y});let l=cl(Object.keys(i),r),g=r.filter((f)=>!(f in c)).map((f)=>({name:f,tools:l[f]??0})),u=!1;return Ue({tools:i,connected:g,failed:s,stop:async()=>{if(u)return;u=!0,await a.disconnect().catch(()=>{})}})}function Ue(e){let t=e.connected??[],n=e.failed??[],r=e.tools??{},o=t.length===0?n.length>0?`mcp: ${Be(n.length,"server")} unreachable`:"":`mcp: ${Be(t.length,"server")} · ${Be(t.reduce((s,a)=>s+a.tools,0),"tool")}${n.length>0?` · ${n.length} unreachable`:""}`;return{tools:r,connected:t,failed:n,summary:o,statusLines:dl(t,n),stop:e.stop??(async()=>{})}}var so=(e)=>e instanceof Error?e.message:String(e);function dl(e,t){return[...e.map((n)=>`✓ ${n.name} — ${Be(n.tools,"tool")}`),...t.map((n)=>`✗ ${n.name} — ${n.reason}`)]}var gl="run `hlix auth login`",fl=["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(`
49
+ `);function hl(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 yl(e,t){try{return await F(process.env,{cwd:e,flags:{}}).secrets.listEntries(t)}catch{return null}}function xl(e){let{values:t,positionals:n}=ml({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((a)=>a!=="").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:ul(typeof t.cwd==="string"?t.cwd:".")}}function bl(e){let t=Object.keys(oe),r=e.sandbox==="cloud"?t:t.filter((c)=>e.installed(c)),o=["hlix",...r],s=t.filter((c)=>!r.includes(c)),a=e.requested.harness;if(a==="hlix"||r.includes(a))return{harness:e.requested,available:o,unavailable:s,refusal:null,warning:null};let i=ze(oe[a]);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 ao(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 Sl(e,t){let n=t.skills&&t.skills.length>0?{skills:t.skills}:{};if(e.choice!=="cloud")return tt(e,{cwd:t.cwd,...n});if(!t.projectId)throw new q("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 tt(e,{cwd:t.cwd,projectId:t.projectId,remote:o})}var At=".hlix";function vl(e,t,n=(r)=>{try{return pl(r)}catch{return r}}){let r=new Set,o=[];for(let s of e.skills){if(s.scope!=="project")continue;let a=So(t,s.path);if(a===""||a.startsWith(".."))continue;let i=n(s.path);if(r.has(i))continue;r.add(i),o.push(a)}return o}function wl(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(`
50
+ `));if(e.project)n.push([`# This project's rules (${So(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(`
51
+ `));return n.join(`
52
+
53
+ `)}var El={boot:Dn,app:to,headless:no,mcp:kt,log:Rt,stdio:{get stdinIsTty(){return process.stdin.isTTY===!0},get stdoutIsTty(){return process.stdout.isTTY===!0}}};function _l(e){if(e.flag===!0)return!0;return co(e.configured)===!0}function Il(e){if(e.print)return null;if(e.stdinIsTty&&e.stdoutIsTty)return null;return`${D} needs a terminal. Run \`hlix -p "<prompt>"\` for one turn without a screen, or start \`hlix\` in a terminal.`}function Cl(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 Lg(e,t=El){let n=xl(e),r=Il({print:n.print!==void 0,stdinIsTty:t.stdio?.stdinIsTty??!0,stdoutIsTty:t.stdio?.stdoutIsTty??!0});if(r)return process.stderr.write(`error: ${r}
54
+ `),2;let o=lo(n.cwd,process.env),s=n.project??o.merged.projectId,a=n.print===void 0?(t.log??Rt)(process.env):null,i=ho(n.cwd,po(process.env),{configDir:At}),c=mo({cwd:n.cwd,configDir:At,env:process.env}),l=new Qe({root:n.cwd,already:[c.project?.path,c.global?.path].filter((E)=>E!==void 0)}),g=new rt(_l({...n.yolo!==void 0?{flag:n.yolo}:{},...o.merged.yolo!==void 0?{configured:o.merged.yolo}:{}})),u,f,y;try{if(f=fn({flag:n.sandbox??o.merged.sandbox,flagSource:n.sandbox?"flag":"config",projectId:s,dockerImage:n.dockerImage??o.merged.dockerImage,dockerAvailable:()=>yn()}),y=bl({requested:Mt({...n.harness?{flag:n.harness}:{},...o.merged.harness?{configured:o.merged.harness}:{},...o.sources.harness?{configSource:o.sources.harness}:{}}),sandbox:f.choice,installed:(E)=>Ot(oe[E].command)}),y.refusal)throw new q("invalid_usage",y.refusal);u=await Sl(f,{cwd:n.cwd,projectId:s,...f.choice==="cloud"?{}:{skills:vl(i,n.cwd)}})}catch(E){return a?.restore(),process.stderr.write(`error: ${E instanceof Error?E.message:String(E)}
55
+ `),2}if(y.warning)process.stderr.write(`warning: ${y.warning}
56
+ `);if(f.choice==="cloud"){let E=s?await ao(n.cwd,s):null;if(E&&n.harness&&n.harness!==E.harness)process.stderr.write(`warning: this project runs ${E.harness}. Run \`/harness ${n.harness}\` to make ${n.harness} the project's setting.
57
+ `);y={...y,harness:E??{harness:"unknown",source:s?"the project's setting could not be read":"no project bound"}}}let _=await Vt({cwd:n.cwd,env:process.env}),w=Kt({cwd:n.cwd,env:process.env,..._.served?{models:_.served.map((E)=>E.id)}:{}}),v=qt({endpoint:w,cloud:f.choice==="cloud",...o.merged.model?{configured:o.merged.model}:{},...o.sources.model?{configuredSource:o.sources.model}:{}});if(v?.notice)process.stderr.write(`warning: ${v.notice}
58
+ `);if(!w)return a?.restore(),process.stderr.write(`error: no hlix credential for this folder — ${gl}.
59
+ `),2;let P=Ee(Ie(o.merged.memoryTokens)??we),L=hn(f),j=bo(i),z=go(c,n.cwd),N=s?hl(await yl(n.cwd,s)):"",k=n.print===void 0?await(t.mcp??kt)({servers:i.mcpServers,cwd:n.cwd}):Tt,W=yo(i.generatedCommands,n.cwd),re=xo(i.instructions,n.cwd),ye=wl(c,n.cwd),Ge=[...uo.flatMap((E)=>[io(n.cwd,".claude",E),io(n.cwd,At,E)]),...i.commands.map((E)=>E.path),...W?[W]:[]],xe=y.harness.harness==="unknown"?"hlix":y.harness.harness,C;try{C=await t.boot({cwd:n.cwd,env:process.env,sandbox:f.choice,workspace:u,endpoint:w,...s?{projectId:s}:{},model:v,harness:xe,harnessFromFlag:y.harness.source==="flag",unavailableHarnesses:y.unavailable,...o.global?.providers?{providers:o.global.providers}:{},...o.merged.memoryTokens?{memoryTokens:o.merged.memoryTokens}:{},hostInstructions:[fl,...f.choice==="cloud"?[Lt(y.harness.harness)]:[],...ye?[ye]:[],...re?[re]:[]].join(`
60
+
61
+ `),mcpTools:k.tools,projectSubagents:i.subagents,nestedRules:l,extraTools:{...Ft({cwd:n.cwd}),hlix_tasks_follow:Ut({cwd:n.cwd}),hlix_harness:$t({sandbox:f.choice,sandboxLine:L,available:y.available,modesBuilt:!1,session:()=>null})}})}catch(E){if(a?.restore(),await k.stop(),E instanceof Ce)return process.stderr.write(`error: ${E.message}
62
+ `),2;return process.stderr.write(`error: ${D} could not start: ${E instanceof Error?E.message:String(E)}
63
+ `),2}try{if(n.print!==void 0)return(await t.headless({session:C.session,prompt:n.print,...n.json?{json:!0}:{},...g.get()?{yolo:!0}:{}})).exitCode;let E={session:C.session,compact:async()=>{let x=C.session.thread.getId();if(!x)return"Nothing to condense yet.";let b=await C.memory.omEngine;if(!b)return"Observational memory is not running in this session.";return(await b.observe({threadId:x,resourceId:C.scope.resourceId})).observed?"Condensed.":"Nothing new to condense."},facts:{sandbox:f.choice,sandboxLine:L,harness:String(y.harness.harness),availableHarnesses:y.available,harnessModesBuilt:C.harnessModesBuilt},memory:{legacyResourceId:C.scope.legacyResourceId,root:C.scope.root},...a?{log:{path:a.path,tail:a.tail}}:{},rules:()=>fo(c,n.cwd,process.env,l.loaded()),mcp:()=>k.statusLines,yolo:{get:()=>g.get(),set:(x)=>g.set(x)},...s?{setProjectHarness:async(x)=>{await F(process.env,{cwd:n.cwd,flags:{}}).modelConfig.setProjectHarness(s,x)},clearProjectHarness:async()=>{await F(process.env,{cwd:n.cwd,flags:{}}).modelConfig.clearProjectHarness(s);let b=await ao(n.cwd,s);return b?Ve(b):null}}:{}},We=Vr({env:process.env,promptFiles:Ge,shell:E}),m=xt({..._.served?{served:_.served}:{},userModelIds:C.gateway.modelIds(),providerName:w.name});return await t.app({session:C.session,cwd:n.cwd,env:process.env,commands:We,models:m,bindings:E,yolo:g,notices:Rl({rules:z,standards:j,memory:en(C.scope,(await C.session.thread.list().catch(()=>[])).length),secrets:N,mcp:k.summary,subagents:C.subagentLine,subagentsSkipped:C.subagentsSkipped,log:a?oo(a):""}),facts:{sandbox:L.replace(/^sandbox: /,""),harness:Ve(y.harness),mode:Cl(C.session,te),...v?{model:Tl(v,m)}:{},workspace:w.workspaceId,context:{used:0,total:0},memory:tn("",P).replace(/^ · /,""),...g.get()?{yolo:!0}:{},..._.warning?{warning:_.warning}:{}}}),0}finally{await k.stop(),await C.dispose(),a?.restore()}}function Rl(e){return[e.rules,e.standards,e.memory,e.mcp,e.subagents,...e.subagentsSkipped.map((t)=>`subagent not loaded: ${t}`),e.secrets,e.log].filter((t)=>t!=="")}function Tl(e,t){return t.find((n)=>n.id===e.id)?.label??e.id}export{Cl as currentMode,xl as parseHlixCodeArgs,bl as planHarness,_l as resolveYolo,wl as rulesBlock,Lg as runHlixCode,hl as secretsStatusLine,Rl as startupNotices,Il as terminalRequirement,vl as workspaceSkillPaths};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import"./index-f303pf32.js";var s="@hlix/cli",i="0.5.3",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.4",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.3",
3
+ "version": "0.5.4",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "Hlix Code and the hlix control-plane CLI.",
6
6
  "keywords": [
@@ -227,8 +227,9 @@ The default history policy aborts on possible historical secrets. Explicit
227
227
  example file (`.env.example` and its family) is never a finding, and a registry
228
228
  config such as `.npmrc` is one only when the committed blob held a real value
229
229
  rather than a `${VAR}` placeholder. A pattern matched inside a test, fixture or
230
- snapshot file is listed as a warning and does not block, so `--history preserve`
231
- is not the answer to it.
230
+ snapshot file, in documentation, on a line that defines a detector's own
231
+ pattern, or whose value spells out that it is fake, is listed as a warning and
232
+ does not block, so `--history preserve` is not the answer to it.
232
233
  Current environment values are sent only in the authenticated finalization
233
234
  request and stored encrypted; they are never placed in the Git bundle.
234
235