@hlix/cli 0.5.5 → 0.5.6

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,67 @@
1
+ #!/usr/bin/env node
2
+ import{e,t,n,o,s,l,i,r,h,d,y,u,c,w,p,m,v,g,f,b,S,x,a}from"./index-8g4x8tv8.js";import{realpathSync as fl}from"node:fs";import{join as wo,relative as _o,resolve as hl}from"node:path";import{parseArgs as yl}from"node:util";import{accessSync as Co,constants as Ro,statSync as To}from"node:fs";import{delimiter as ko,join as Ao}from"node:path";import{createACPTool as Po}from"@mastra/acp";import{createTool as No}from"@mastra/core/tools";import{z as ye}from"zod";var Ie={"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 qt(E){if(E.flag)return{harness:Mo(E.flag,"--harness"),source:"flag"};if(E.configured)return{harness:E.configured,source:E.configSource??"project"};return{harness:h,source:"default"}}function Mo(E,_){if(r.includes(E))return E;throw Error(`${_} must be one of ${r.join(", ")}; got "${E}".`)}var lt="hlix_tasks_follow",Oo=(E)=>`hlix_coder_${E.split("-").join("_")}`;function ct(E){if(E.source==="default")return String(E.harness);let _=E.source==="flag"?"--harness":E.source;return`${E.harness} (${_})`}function zt(E,_=process.env){return dt(E,_)!==null}function dt(E,_=process.env){if(!E)return null;if(E.includes("/"))return Kt(E)?E:null;let I=(_.PATH??"").split(ko).filter(Boolean);for(let C of I){let R=Ao(C,E);if(Kt(R))return R}return null}function Kt(E){if(!E)return!1;try{if(!To(E).isFile())return!1;return Co(E,Ro.X_OK),!0}catch{return!1}}var pt=(E)=>`harness ${E.harness} needs \`${E.command}\` on PATH. Install it with: ${E.install}`;function Lo(E){let _=E.options??[],I=_.find((C)=>C.kind==="allow_once")??_.find((C)=>C.kind==="reject_once");if(!I)return{outcome:{outcome:"cancelled"}};return{outcome:{outcome:"selected",optionId:I.optionId}}}var Vt=["ask_user","task_write","task_update","task_complete","task_check"],jo=(E)=>[`harness ${E} runs in the project's Coding Workspace, not on this machine.`,"Start work with `hlix cycles create`, find the tasks it plans with","`hlix tasks list`, and watch one live with `/follow <task-id>`.","Nothing runs on this machine, so a local coder binary is not used."].join(" "),Xt=(E)=>[E==="unknown"?"This project's harness could not be read from the server. Do NOT guess which coder it runs — say so, and offer to check with the `hlix_harness` tool.":`This project's harness is ${E}: the platform runs ${E} for the coding work it executes, in the project's Coding Workspace.`,"Change it with the `hlix_harness` tool, which writes the project's setting.","","To do coding work here, dispatch it and then watch it:","1. `hlix_cycles_create` with the project id, a title and a description. That"," is what STARTS work — it enters the project's loop, which plans the cycle,"," creates its tasks and starts the coder. It returns no cycle id.","2. `hlix_tasks_list` with that project to find the tasks planning produced.",`3. \`${lt}\` 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
+ `),Do=(E,_)=>[`The user chose the ${E.label} harness. Do not edit files or run commands`,`yourself. Hand the whole task to \`${_}\` 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 _=new Set(E.unavailable??[]),I=E.model?{defaultModelId:E.model}:{},C=[{id:"hlix",name:"Hlix",description:"The hlix agent codes here, with the full toolset.",...I}];for(let R of Object.values(Ie)){let T=E.active===R.harness,A=Oo(R.harness);C.push({id:R.harness,name:R.label,description:`${R.label} runs on this machine over ACP and edits ${E.cwd}.`,instructions:Do(R,A),availableTools:_.has(R.harness)?[...E.readTools,...Vt,lt]:[A,...E.readTools,...Vt,lt],..._.has(R.harness)?{}:{additionalTools:{[A]:Po({id:A,description:`Run a coding task with ${R.label}. Give it one natural-language brief; it reads and writes the working directory and returns its final output.`,command:R.command,args:R.args,cwd:E.cwd,...R.env?{env:R.env}:{},...E.workspace?{workspace:E.workspace}:{},onPermissionRequest:async(k)=>Lo(k)})}},...I,...T?{metadata:{default:!0}}:{}})}return C}function Zt(E){if(!E.fromFlag||!E.modesBuilt)return null;return E.current===E.harness?null:E.harness}function ut(E){let _=[...E.available],I=(R,T="none")=>({harness:E.current,available:_,action:T,message:R});if(!E.requested)return I(`harness: ${E.current}. Available here: ${_.join(", ")}.`);if(!r.includes(E.requested))return I(`/harness must name one of ${r.join(", ")}; got "${E.requested}".`);let C=E.requested;if(E.sandbox==="cloud"){let R=`${E.sandboxLine} · harness: ${C} (project preference)`;return{harness:C,available:_,action:"preference",message:C==="hlix"?R:`${R}. ${jo(C)}`}}if(!_.includes(C))return I(pt(Ie[C]));if(!E.modesBuilt)return I(`This session runs the hlix coder, so there is no ${C} mode to switch to. The choice is saved; restart with \`hlix\` to run on ${C}.`,"restart");return{harness:C,available:_,action:"mode",message:`${E.sandboxLine} · harness: ${C}`}}function Qt(E){return No({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:ye.object({harness:ye.string().optional().describe(`One of ${r.join(", ")}. Omit to report the current one.`)}),outputSchema:ye.object({harness:ye.string(),available:ye.array(ye.string()),message:ye.string()}),execute:async(_)=>{let I=E.session(),C=ut({..._.harness?{requested:_.harness}:{},current:I?.mode.get()??h,available:E.available,sandbox:E.sandbox,sandboxLine:E.sandboxLine,modesBuilt:E.modesBuilt}),R={harness:C.harness,available:C.available,message:C.message};if(C.action==="mode"&&I)return await I.mode.switch({modeId:C.harness}),R;if(C.action==="preference"){if(!E.setProjectHarness)return{...R,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(C.harness)}return R}})}import{createTool as $o}from"@mastra/core/tools";import{z as re}from"zod";var Fo=(E)=>`hlix_${E.split(" ").join("_")}`,Ho=re.object({args:re.array(re.string()).optional().describe("Positional arguments that follow the command name."),flags:re.record(re.string(),re.union([re.string(),re.boolean()])).optional().describe('Options without the leading dashes, e.g. { "yes": true, "name": "api" }.')}),Uo=re.object({exitCode:re.number(),stdout:re.string(),stderr:re.string()});function Bo(E,_,I){let C=E.name.split(" ").concat(_.args??[]);for(let[R,T]of Object.entries(_.flags??{})){if(T===!1)continue;if(C.push(`--${R}`),typeof T==="string")C.push(T)}if(!_.flags?.cwd)C.push("--cwd",I);if(E.supportsJson&&!_.flags?.json)C.push("--json");return C}async function Go(E,_,I,C=process.env){let R="",T="";return{exitCode:await s([E],Bo(E,_,I),{stdout:(k)=>{R+=k},stderr:(k)=>{T+=k},env:C}),stdout:R,stderr:T}}function en(E){let _={};for(let I of E.commands??a){let C=Fo(I.name);_[C]=$o({id:C,description:`${I.summary}
5
+
6
+ ${I.usage}`,inputSchema:Ho,outputSchema:Uo,execute:async(R)=>Go(I,R,E.cwd,E.env)})}return _}import{createTool as Wo}from"@mastra/core/tools";async function tn(E,_){let I=E?.agent?.toolCallId;if(!I)return;let C={type:"data-hlix-tool-progress",data:{toolCallId:I,progress:_},transient:!0},R=E?.agent?.outputWriter;if(R){await R(C);return}await E?.writer?.custom?.(C)}import{z as ge}from"zod";function Yo(E){switch(E.type){case"on_chat_model_stream":return E.delta?{event:"text",text:E.delta}:null;case"reasoning":return E.delta?{event:"text",text:E.delta}:null;case"on_tool_start":return{event:"tool_start",toolName:E.name,args:E.input};case"on_tool_end":return{event:"tool_end",toolName:E.name,result:E.output,isError:Ko(E.output)};case"error":return{event:"finish",isError:!0,result:E.message};case"done":return{event:"finish",isError:!1};default:return null}}function Ko(E){return typeof E==="object"&&E!==null&&E.status==="failed"}async function Vo(E,_){let I=[],C=[],R="streamed",T="The coder's turn ended.";for await(let A of E){if(A.type==="idle"){R="idle",T="Nothing is being coded right now. The task is not in build or test.";break}if(A.type==="error")R="error",T=A.message;if(A.type==="on_chat_model_stream")I.push(A.delta);if(A.type==="on_tool_start")C.push(A.name);let k=Yo(A);if(k)await _(k)}return{status:R,text:I.join(""),tools:C,message:T}}function nn(E){return Wo({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:ge.object({taskId:ge.string().describe("The task to follow.")}),outputSchema:ge.object({status:ge.enum(["streamed","idle","error","unassigned"]),text:ge.string(),tools:ge.array(ge.string()),message:ge.string()}),execute:async(_,I)=>{let C=o(E.env??process.env,{cwd:E.cwd,flags:{}}),R=await C.tasks.get(_.taskId);if(!R.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 Vo(C.projects.observeAgent(R.projectId,R.agentId),(T)=>tn(I,T))}})}import{readFileSync as qo,statSync as on}from"node:fs";import{isAbsolute as zo,join as Xo,relative as gt,resolve as xe}from"node:path";var Jo=["path","file","filePath","target","targetPath","dest","destination"],mt=8000,Zo=(E)=>{try{return on(E).isFile()}catch{return!1}},Qo=(E)=>{try{return on(E).isDirectory()}catch{return!1}};function rn(E,_){let I=gt(E,_);return I!==""&&!I.startsWith("..")&&!zo(I)}function es(E){let _=xe(E.root),I=xe(_,E.touched);if(!rn(_,I))return null;let C=Qo(I)?I:xe(I,"..");while(rn(_,C)){for(let R of p){let T=Xo(C,R);if(Zo(T))return T}C=xe(C,"..")}return null}function ts(E,_){let I=gt(_,E.path),C=!I||I.startsWith("..")?E.path:I;return[`Rules for ${gt(_,xe(E.path,".."))||"."}/ (${C})`,"","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 ns(E){let _=[];for(let I of E){let C=I.content?.parts;if(!Array.isArray(C))continue;for(let R of C){if(R.type!=="tool-invocation")continue;let T=R.toolInvocation;if(!T||T.state!=="result")continue;if(typeof T.toolCallId!=="string"||T.toolCallId==="")continue;let A=rs(T.args);if(!A)continue;let k=[];for(let P of Jo){let N=A[P];if(typeof N==="string"&&N.trim()!=="")k.push(N)}if(k.length>0)_.push({id:T.toolCallId,paths:k})}}return _}function rs(E){if(typeof E==="object"&&E!==null)return E;if(typeof E!=="string")return null;try{let _=JSON.parse(E);return typeof _==="object"&&_!==null?_:null}catch{return null}}class ft{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=xe(E.root),this.skip=new Set((E.already??[]).map((_)=>xe(_)))}loaded(){return[...this.sent.values()]}consider(E){let _=es({touched:E,root:this.root});if(!_||this.skip.has(_)||this.sent.has(_))return null;let I;try{I=qo(_,"utf8").trim()}catch{return null}if(I==="")return null;let C={path:_,content:I.length>mt?`${I.slice(0,mt).trimEnd()}
8
+
9
+ [truncated: ${_} is longer than ${mt} characters]`:I};return this.sent.set(_,C),C}newCalls(E,_){let I=ns(E.get.all.db()).filter((C)=>!this.seenCalls.has(C.id));for(let C of I)this.seenCalls.add(C.id);return _===0?[]:I}async processInputStep(E){for(let _ of this.newCalls(E.messageList,E.stepNumber))for(let I of _.paths){let C=this.consider(I);if(!C)continue;await E.sendSignal?.({type:"reactive",tagName:"system-reminder",contents:ts(C,this.root),attributes:{type:"nested-rules",path:C.path}})}return E.messageList}}import{createHash as is}from"node:crypto";import{existsSync as as,realpathSync as ls}from"node:fs";import{basename as cs,dirname as ds,join as ps,resolve as dn,sep as pn}from"node:path";import{Memory as us}from"@mastra/memory";var fe="hlix",be="default",Pe=(E)=>`${fe}/${E}`,sn=(E)=>E.startsWith(`${fe}/`)&&E.length>fe.length+1;function os(E){return{name:fe,url:`${E.baseUrl.replace(/\/+$/,"")}/v1/api/ai/w/${E.workspaceId}`,apiKey:E.apiKey,models:[...new Set([be,...E.models??[]])]}}function an(E){let _=n({env:E.env,flags:{},cwd:E.cwd});if(_.conflict||!_.credential||!_.workspaceId)return null;let I=_.credential.sessionToken||_.credential.apiKey;if(!I)return null;let C=_.binding?.config.projectId;return{...os({baseUrl:_.baseUrl,workspaceId:_.workspaceId,apiKey:I,...E.models?{models:E.models}:{}}),workspaceId:_.workspaceId,...C?{projectId:C}:{}}}var ss=3000;async function ln(E){let _=n({env:E.env,flags:{},cwd:E.cwd});if(_.conflict||!_.credential||!_.workspaceId)return{};try{return{served:(await o(E.env,{cwd:E.cwd,flags:{}}).ai.models(_.workspaceId,{signal:AbortSignal.timeout(E.timeoutMs??ss)})).models.map((C)=>({id:C.id,name:C.name}))}}catch(I){return{warning:`could not read your workspace's models (${I instanceof Error?I.message:String(I)}). Offering the workspace default only.`}}}function cn(E){if(E.configured){let _=E.configuredSource??"config";if(!E.cloud||!E.endpoint||sn(E.configured))return{id:E.configured,source:_};return{id:Pe(be),source:"workspace",notice:`model ${E.configured} from ${_} is not available on the cloud sandbox; using hlix default`}}return E.endpoint?{id:Pe(be),source:"workspace"}:null}function un(E){try{return ls(dn(E))}catch{return dn(E)}}function ms(E){let _=un(E),I=t(_);if(I)return un(I.root);for(let C=_;;){if(as(ps(C,".git")))return C;let R=ds(C);if(R===C)return _;C=R}}var gs=(E)=>E.length>8?`${E.slice(0,8)}…`:E;function mn(E){let _=ms(E.cwd),I=E.projectId?.trim(),C=I||is("sha256").update(_).digest("hex").slice(0,16);return{resourceId:`${E.workspaceId}:${C}`,legacyResourceId:E.workspaceId,root:_,label:I?`project ${gs(I)}`:`folder ${cs(_)}`}}var gn=(E,_)=>typeof E==="string"&&(E===_||E.startsWith(_.endsWith(pn)?_:`${_}${pn}`)),fn=(E,_)=>`memory: ${E.label} · ${_} thread${_===1?"":"s"}`,Ue=200000;function Be(E){let _=Math.round(E*3/7);return{observationThreshold:_,reflectionThreshold:E-_}}var hn=(E,_)=>`${E} · memory: ${Math.round((_.observationThreshold+_.reflectionThreshold)/1000)}k`;function yn(E){return new us({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 Ms}from"node:child_process";import{DockerSandbox as Os}from"@mastra/docker";import{LocalFilesystem as In,LocalSandbox as Ls,Workspace as Cn}from"@mastra/core/workspace";var fs=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,xn=/^(\s*name\s*:\s*)(.+?)\s*$/;function hs(E,_){if(!fs.test(_))return E;let I=E.indexOf(`
10
+ ---`,3);if(!E.startsWith("---")||I<0)return E;let R=E.slice(0,I).split(`
11
+ `),T=R.findIndex((P)=>xn.test(P));if(T<0)return E;let A=xn.exec(R[T]);if(!A)return E;let k=A[2].replace(/^["']|["']$/g,"").trim();if(k===_)return E;if(R[T]=`${A[1]}${_}`,!R.some((P)=>/^\s*title\s*:/.test(P)))R.push(`title: ${k}`);return`${R.join(`
12
+ `)}${E.slice(I)}`}function ys(E){let _=E.split("/").filter((I)=>I!=="");if(_.length<2||_[_.length-1]!=="SKILL.md")return null;return _[_.length-2]}function bn(E){let _={exists:(I)=>E.exists(I),stat:(I)=>E.stat(I),readdir:(I)=>E.readdir(I),readFile:async(I)=>{let C=await E.readFile(I),R=ys(I);if(R===null)return C;let T=typeof C==="string"?C:C.toString("utf8");return hs(T,R)}};if(E.realpath)_.realpath=(I)=>E.realpath?.(I);return _}import{WORKSPACE_TOOLS as J}from"@mastra/core/workspace";var Ce={[J.FILESYSTEM.READ_FILE]:"view",[J.FILESYSTEM.WRITE_FILE]:"write_file",[J.FILESYSTEM.EDIT_FILE]:"edit_file",[J.FILESYSTEM.LIST_FILES]:"find_files",[J.FILESYSTEM.DELETE]:"delete_file",[J.FILESYSTEM.FILE_STAT]:"file_stat",[J.FILESYSTEM.MKDIR]:"mkdir",[J.FILESYSTEM.GREP]:"search_content",[J.FILESYSTEM.AST_EDIT]:"ast_edit",[J.SANDBOX.EXECUTE_COMMAND]:"execute_command",[J.SANDBOX.GET_PROCESS_OUTPUT]:"process_output",[J.SANDBOX.KILL_PROCESS]:"kill_process",[J.LSP.LSP_INSPECT]:"lsp_inspect"},Ne=[J.FILESYSTEM.WRITE_FILE,J.FILESYSTEM.EDIT_FILE,J.FILESYSTEM.DELETE,J.FILESYSTEM.MKDIR,J.FILESYSTEM.AST_EDIT,J.SANDBOX.EXECUTE_COMMAND,J.SANDBOX.KILL_PROCESS].map((E)=>Ce[E]),Ge=Object.values(Ce).filter((E)=>!Ne.includes(E)),Me=Object.fromEntries(Object.entries(Ce).map(([E,_])=>[E,{name:_}]));function oe(E){return Ce[E]??E}import{posix as Sn}from"node:path";import{DirectoryNotEmptyError as xs,DirectoryNotFoundError as bs,FileExistsError as Ss,FileNotFoundError as vs,FilesystemError as ws,IsDirectoryError as Es,MastraFilesystem as _s,MastraSandbox as Is,NotDirectoryError as Cs,PermissionError as Rs,Workspace as Ts}from"@mastra/core/workspace";var ks=600000,As=["recursive","overwrite","force","maxDepth","extension"];function Se(E){let _=E??{},I={};for(let C of As)if(_[C]!==void 0)I[C]=_[C];return Object.keys(I).length>0?{options:I}:{}}var vn=(E)=>E instanceof Date?E:new Date(typeof E==="string"||typeof E==="number"?E:0);function Ps(E,_,I){let C=E?.status;if(typeof C!=="number")return E;let R=E?.body,T=typeof R?.code==="string"?R.code:"",A=typeof R?.error==="string"?R.error:"",k=(P)=>A.toLowerCase().includes(P);if(C===404)return T==="ENOTDIR"||k("directory not found")?new bs(_):new vs(_);if(C===403)return new Rs(_,I);if(C===409){if(T==="EEXIST"||k("already exists"))return new Ss(_);if(T==="ENOTEMPTY"||k("not empty"))return new xs(_);if(T==="EISDIR"||k("is a directory"))return new Es(_);if(T==="ENOTDIR"||k("not a directory"))return new Cs(_);return new ws(A||`${I} failed`,T||"ECONFLICT",_)}return E}class wn extends _s{id;name="RemoteFilesystem";provider="hlix-coding-workspace";basePath;status="ready";client;constructor(E,_){super({name:"RemoteFilesystem"});this.client=E,this.basePath=_.root,this.id=_.id??`hlix-remote-fs:${_.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 _=this.resolveAbsolutePath(E.path);try{let{result:I}=await this.client.fs({...E,encoding:E.encoding??"utf8",path:_});return I}catch(I){throw Ps(I,_,E.op)}}async readFile(E,_){let C=await this.call({op:"read",path:E,encoding:"base64"}),R=Buffer.from(C.content,C.encoding);return _?.encoding?R.toString(_.encoding):R}async writeFile(E,_,I){await this.call({op:"write",path:E,content:Buffer.from(_).toString("base64"),encoding:"base64",...Se(I)})}async appendFile(E,_){await this.call({op:"append",path:E,content:Buffer.from(_).toString("base64"),encoding:"base64"})}async deleteFile(E,_){await this.call({op:"delete",path:E,...Se(_)})}async copyFile(E,_,I){await this.call({op:"copy",path:E,dest:this.resolveAbsolutePath(_),...Se(I)})}async moveFile(E,_,I){await this.call({op:"move",path:E,dest:this.resolveAbsolutePath(_),...Se(I)})}async mkdir(E,_){await this.call({op:"mkdir",path:E,...Se(_)})}async rmdir(E,_){await this.call({op:"rmdir",path:E,...Se(_)})}async readdir(E,_){return await this.call({op:"readdir",path:E,...Se(_)})??[]}async exists(E){return await this.call({op:"exists",path:E})===!0}async stat(E){let _=await this.call({op:"stat",path:E});return{..._,createdAt:vn(_.createdAt),modifiedAt:vn(_.modifiedAt)}}}var Ns=(E)=>`'${E.split("'").join("'\\''")}'`;class En extends Is{id;name="RemoteSandbox";provider="hlix-coding-workspace";status="ready";client;constructor(E,_){super({name:"RemoteSandbox"});if(this.client=E,this.id=`hlix-remote-sandbox:${_.projectId}`,_.root)this.setWorkingDirectory(_.root)}async start(){}getInfo(){return{id:this.id,name:this.name,provider:this.provider,status:this.status,createdAt:new Date(0)}}async executeCommand(E,_=[],I){let C=[E,..._.map(Ns)].join(" "),R=Date.now(),T=I?.cwd??this.workingDirectory,A=await this.client.exec({command:C,...T?{cwd:T}:{},timeoutMs:I?.timeout??ks});return{success:A.exitCode===0,exitCode:A.exitCode,stdout:A.stdout,stderr:A.stderr,executionTimeMs:Date.now()-R,command:E,args:_}}}function _n(E,_){let I=_.root;return new Ts({id:`hlix-project:${_.projectId}`,name:"Hlix Coding Workspace",filesystem:new wn(E,{root:I}),sandbox:new En(E,{projectId:_.projectId,root:I}),tools:Me})}var Tn="node:22-bookworm",js=(E)=>`hlix-code-${E}`;function Ds(E,_){if(i.includes(E))return E;throw new e("invalid_usage",`${_==="flag"?"--sandbox":"sandbox in .hlix/config.json"} must be one of ${i.join(", ")}; got "${E}".`)}function kn(E){let _=(I)=>I==="docker"?{image:E.dockerImage?.trim()||Tn}:{};if(E.flag){let I=E.flagSource??"flag",C=Ds(E.flag,I);return{choice:C,reason:I==="flag"?`--sandbox ${E.flag}`:"config",..._(C)}}if(E.projectId)return{choice:"cloud",reason:`project ${E.projectId}`};if(E.dockerAvailable())return{choice:"docker",reason:"auto",..._("docker")};return{choice:"local",reason:"auto"}}var An=(E)=>`sandbox: ${E.choice} (${E.reason}${E.image?`, ${E.image}`:""})`;function Pn(E=3000){try{return Ms("docker",["info"],{timeout:E,stdio:"ignore"}),!0}catch{return!1}}function Rn(E,_){if(!E||E.length===0)return{};return{skills:[...E],skillSource:bn(_)}}async function $s(E,_){let I=await E.environment();if(I.state==="absent")throw new e("not_found",`Project ${_} has no Coding Workspace yet, so there is nothing to code in. Push the folder's files with \`hlix push\` (or \`hlix import\` in a folder that is not bound yet), or run a task in the project, to build one.`);if(!I.repoDir)throw new e("not_found",`This workspace's server did not say where project ${_}'s repository is. Update the server, or run with --sandbox docker|local.`);return I.repoDir}async function ht(E,_){if(E.choice==="local"){let T=new In({basePath:_.cwd});return new Cn({id:"hlix-code-local",name:"Hlix Code (this machine)",filesystem:T,...Rn(_.skills,T),sandbox:new Ls({workingDirectory:_.cwd}),tools:Me})}if(E.choice==="cloud"){if(!_.remote||!_.projectId)throw new e("invalid_usage","The cloud sandbox needs a hlix project. Run `hlix init`, pass --project <id>, or choose --sandbox docker|local.");return _n(_.remote,{projectId:_.projectId,root:await $s(_.remote,_.projectId)})}let I="/workspace",C=E.image??Tn,R=new In({basePath:_.cwd});return new Cn({id:"hlix-code-docker",name:"Hlix Code (Docker)",filesystem:R,...Rn(_.skills,R),tools:Me,sandbox:new Os({id:js(C),image:C,volumes:{[_.cwd]:I},workingDirectory:I})})}import{basename as pi}from"node:path";import{AgentController as ui}from"@mastra/core/agent-controller";import{createCodingAgent as mi}from"@mastra/core/coding-agent";import{createWorkspaceTools as gi}from"@mastra/core/workspace";var Fs=["execute_command","kill_process"],Hs=["updateWorkingMemory","task_write","task_update","task_complete","task_check","ask_user","submit_plan"];function yt(E){let _=E in Ce?oe(E):E;if(Fs.includes(_))return"execute";if(Ne.includes(_))return"edit";if(Ge.includes(_)||Hs.includes(_))return"read";if(_.startsWith("hlix_"))return"other";return null}function Nn(E=[]){let _=new Set(E);return(I)=>_.has(I)?"mcp":yt(I)}function Us(E){return yt(E)!=="read"}var Mn=[{category:"read",policy:"allow"}];function On(E){if(E.yolo||!Us(E.toolName))return{decision:"approve"};return{decision:"decline",reason:`Hlix Code is running with -p (no terminal to ask), so ${oe(E.toolName)} was not run. Report this to the user: re-run with --yolo to let this session change things.`}}class xt{on;constructor(E){this.on=E}get(){return this.on}set(E){this.on=E}}function Ln(E){let _=oe(E),I=yt(E)??"other";return[{value:"approve",label:"Allow once",description:`Run ${_} 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 ${I} tool for the rest of this session`}]}import{MastraModelGateway as Bs,ModelRouterLanguageModel as Gs}from"@mastra/core/llm";function Ws(E,_){let I=[];for(let C of E??[]){if(!C.name||!C.url||C.name===fe)continue;let R=C.apiKeyEnv?_[C.apiKeyEnv]:C.apiKey;if(C.apiKeyEnv&&!R)continue;I.push({name:C.name,url:C.url.replace(/\/+$/,""),apiKey:R??"",models:C.models??[]})}return I}function jn(E){let _=E.indexOf("/");if(_<=0||_===E.length-1)return null;return{provider:E.slice(0,_),model:E.slice(_+1)}}class Dn extends Bs{id=`${fe}-gateway`;name="Hlix";byProvider;constructor(E){super();this.byProvider=new Map(E.map((_)=>[_.name,_]))}modelIds(){return[...this.byProvider.values()].flatMap((E)=>E.models.map((_)=>`${E.name}/${_}`))}handlesModel(E){let _=jn(E);return _!==null&&this.byProvider.has(_.provider)}shouldEnable(){return this.byProvider.size>0}async fetchProviders(){let E={};for(let _ of this.byProvider.values())E[_.name]={name:_.name===fe?"Hlix":_.name,url:_.url,apiKeyEnvVar:[],gateway:this.id,models:_.models.map((I)=>`${_.name}/${I}`)};return E}endpointFor(E){let _=jn(E);return _?this.byProvider.get(_.provider):void 0}async buildUrl(E){return this.endpointFor(E)?.url}async getApiKey(E){let _=this.endpointFor(E);if(!_)throw Error(`Hlix Code cannot resolve the model "${E}". Run /model to pick one this workspace serves.`);return _.apiKey}resolveLanguageModel(E){let _=this.byProvider.get(E.providerId);if(!_)throw Error(`Hlix Code has no endpoint for provider "${E.providerId}".`);return new Gs({id:`${E.providerId}/${E.modelId}`,url:_.url,apiKey:E.apiKey||_.apiKey,...E.headers?{headers:E.headers}:{}})}}function $n(E){let _=[];if(E.endpoint)_.push({name:E.endpoint.name,url:E.endpoint.url,apiKey:E.endpoint.apiKey,models:E.endpoint.models});if(!E.cloud)_.push(...Ws(E.providers,E.env));return new Dn(_)}import{buildBasePrompt as Ys}from"@mastra/core/coding-agent";var ae="Hlix Code",Ks="Hlix Code",Vs="noreply@hlix.ai";function qs(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 Fn(E){return E.sandbox==="cloud"?E.filesystemRoot??E.cwd:E.cwd}function Hn(E){let _=Ys({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:qs(E.sandbox),hasSubagents:E.hasSubagents??!1,productName:ae,coAuthorName:Ks,coAuthorEmail:Vs});return E.hostInstructions?`${_}
13
+
14
+ ${E.hostInstructions}`:_}var ve="build",Un="plan",zs=[ve,Un];function Bn(E,_=zs){let I=_.indexOf(E);return _[(I+1)%_.length]??_[0]}function bt(E){let _=new Set(Ne);return E.filter((I)=>!_.has(I)&&!I.startsWith("hlix_"))}function Xs(E){return[...new Set([...bt(E),"submit_plan","task_write","task_update","task_check"])]}var Js=["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
+ `),Zs=["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 Gn(E){let _=E.modelId?{defaultModelId:E.modelId}:{};return[{id:ve,name:"build",description:"Read, write and run. The default.",instructions:Zs,metadata:{default:!0},..._},{id:Un,name:"plan",description:"Read and plan; no edits, no commands.",instructions:Js,availableTools:Xs(E.registeredTools),transitionsTo:ve,..._}]}import{lstatSync as Qs,mkdirSync as ei,unlinkSync as ti}from"node:fs";import{homedir as ni}from"node:os";import{join as St}from"node:path";import{LibSQLStore as ri}from"@mastra/libsql";function vt(E=process.env){return St(E.HLIX_CONFIG_HOME??ni(),".hlix","code")}function oi(E=process.env){return`file:${St(vt(E),"threads.db")}`}var si=["auth.json","mastra.db","mastra.db-shm","mastra.db-wal","settings.json"];function ii(E=process.env){let _=vt(E);for(let I of si){let C=St(_,I);try{if(!Qs(C).isFile())continue;ti(C)}catch{}}}function Wn(E=process.env){return ei(vt(E),{recursive:!0}),ii(E),new ri({id:"hlix-code",url:oi(E)})}var Yn="explore",Kn="plan",Vn="execute",wt=[`You are a subagent of ${ae}. 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
+ `),ai=[wt,"","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
+ `),li=[wt,"","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
+ `),ci=[wt,"","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 qn(E){let _=E.modelId?{defaultModelId:E.modelId}:{},I=E.registeredTools.filter((C)=>Ge.includes(C));return[{id:Yn,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:ai,allowedWorkspaceTools:I,..._},{id:Kn,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:li,..._},{id:Vn,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:ci,..._}]}var di=[Yn,Kn,Vn];function zn(E,_){let I=[],C=[];for(let R of E){if(di.includes(R.name)){C.push(`${R.name} (reserved by ${ae})`);continue}I.push({id:R.name,name:R.name,description:R.description||`The ${R.name} agent defined by this project.`,instructions:R.instructions,..._?{defaultModelId:_}:{}})}return{subagents:I,skipped:C}}function Xn(E,_){if(E.length===0&&_.length===0)return"";let I=E.map((C)=>C.id).join(", ");if(_.length===0)return`subagents: ${I}`;return`subagents: ${I} + ${_.length} from this project`}class We extends Error{constructor(){super("No hlix credential for this folder. Run `hlix auth login`.");this.name="NoCredentialError"}}function fi(E,_){let I=_.startsWith(`${E.name}/`)?_.slice(E.name.length+1):be;return{id:`${E.name}/${I}`,url:E.url,apiKey:E.apiKey}}async function Jn(E){if(!E.endpoint)throw new We;let _=E.endpoint,I=E.model?.id??Pe(be),C=$n({endpoint:_,...E.providers?{providers:E.providers}:{},env:E.env,cloud:E.sandbox==="cloud"}),R=mn({workspaceId:_.workspaceId,cwd:E.cwd,...E.projectId?{projectId:E.projectId}:{}}),T=Wn(E.env),A=Be(l(E.memoryTokens)??Ue),k=null,P=fi(_,I),N=yn({storage:T,thresholds:A,observerModel:()=>k?.om.observer.resolvedModel()??P,reflectorModel:()=>k?.om.reflector.resolvedModel()??P}),M=E.workspace?await gi(E.workspace):{},O=E.mcpTools??{},F={...M,...E.extraTools??{},...O},U=Object.keys(F),q=qn({registeredTools:U,modelId:I}),K=zn(E.projectSubagents??[],I),Y=[...q,...K.subagents],te=Fn({sandbox:E.sandbox,cwd:E.cwd,...E.workspace?.filesystem?.basePath?{filesystemRoot:E.workspace.filesystem.basePath}:{}}),se=mi({id:"hlix-coder",name:ae,model:P,instructions:Hn({projectPath:te,projectName:pi(E.cwd),mode:ve,modelId:I,sandbox:E.sandbox,hasSubagents:Y.length>0,...E.hostInstructions?{hostInstructions:E.hostInstructions}:{}}),tools:F,...E.workspace?{workspace:E.workspace}:{},...E.nestedRules?{inputProcessors:[E.nestedRules]}:{},memory:N}),ie=Jt({sandbox:E.sandbox,cwd:E.cwd,active:E.harness,readTools:bt(U),...E.workspace?{workspace:E.workspace}:{},...E.unavailableHarnesses?{unavailable:E.unavailableHarnesses}:{},model:I}),he=ie.length>0?ie:Gn({registeredTools:U,modelId:I}),ne=new ui({id:"hlix-code",resourceId:R.resourceId,agent:se,storage:T,memory:N,modes:he,subagents:Y,tools:F,gateways:[C],omConfig:{defaultObserverModelId:I,defaultReflectorModelId:I,defaultObservationThreshold:A.observationThreshold,defaultReflectionThreshold:A.reflectionThreshold},toolCategoryResolver:Nn(Object.keys(O)),...E.workspace?{workspace:E.workspace}:{}});await ne.init();let Q=await ne.createSession({resourceId:R.resourceId,tags:{projectPath:R.root}});if(k=Q,I)await Q.model.switch({modelId:I});let me=Zt({fromFlag:E.harnessFromFlag===!0,harness:E.harness,modesBuilt:ie.length>0,current:Q.mode.get()});if(me)await Q.mode.switch({modeId:me});for(let Ee of Mn)await Q.permissions.setForCategory(Ee);return{controller:ne,session:Q,gateway:C,store:T,memory:N,scope:R,harnessModesBuilt:ie.length>0,subagentLine:Xn(q,K.subagents),subagentsSkipped:K.skipped,dispose:async()=>{await ne.destroy().catch(()=>{}),await T.close().catch(()=>{})}}}import{Editor as Xa,ProcessTerminal as Ja,SelectList as po,Input as Za,TuiMainScreen as Qa,truncateToWidth as Ut}from"@earendil-works/pi-tui";import{readFileSync as hi,statSync as yi}from"node:fs";import{basename as xi,extname as bi,isAbsolute as Si,join as vi}from"node:path";import{CombinedAutocompleteProvider as wi,Key as Ye,matchesKey as Ei}from"@earendil-works/pi-tui";function _i(E,_=Ei){if(_(E,Ye.shift("tab")))return"cycle-mode";if(_(E,Ye.ctrl("c")))return"interrupt";if(_(E,Ye.ctrl("o")))return"expand";if(_(E,Ye.escape))return"abort";return"text"}var Ii=2000;class Qn{windowMs;armedAt=0;constructor(E=Ii){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 Ci(E){return[...E.entries()].map(([_,I])=>({name:_,description:I.description})).sort((_,I)=>_.name.localeCompare(I.name))}var Et="Press Ctrl-C again to leave Hlix Code.";class er extends wi{applyCompletion(E,_,I,C,R){let T=E[_]??"";if(/^\/[^\s/]*$/.test(T.slice(0,I))){let A=[...E];return A[_]=`/${C.value} ${T.slice(I)}`,{lines:A,cursorLine:_,cursorCol:C.value.length+2}}return super.applyCompletion(E,_,I,C,R)}}function Ri(E=process.env){for(let _ of["fd","fdfind"]){let I=dt(_,E);if(I)return I}return null}function Ti(E,_){let I=E.getFocusedComponent;if(typeof I!=="function")return!1;let C=I.call(E);return C!==void 0&&C!==null&&C!==_}function tr(E){let _=new Qn;return E.editor.setAutocompleteProvider(new er(Ci(E.commands),E.basePath,Ri())),E.editor.onSubmit=(I)=>{let C=I.trim();if(!C){E.handlers.onEmptySubmit?.();return}E.editor.addToHistory(C),E.editor.setText(""),E.handlers.onSubmit(C)},E.tui.addInputListener((I)=>{switch(_i(I)){case"cycle-mode":return E.handlers.onCycleMode(),{consume:!0};case"interrupt":if(_.press()==="exit")E.handlers.onExit();else E.handlers.onInterruptWarning(Et);return{consume:!0};case"expand":return _.disarm(),E.handlers.onExpand(),{consume:!0};case"abort":if(E.editor.isShowingAutocomplete())return;if(Ti(E.tui,E.editor))return;return _.disarm(),E.handlers.onAbort(),{consume:!0};default:_.disarm();return}})}var ki={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Zn=8388608;function nr(E,_,I=hi,C=(R)=>yi(R).size){let R=[],T=[],A=new Set;for(let k of E.matchAll(/(?:^|\s)@(\S+)/g)){let P=k[1],N=ki[bi(P).toLowerCase()];if(!N||A.has(P))continue;A.add(P);let M=Si(P)?P:vi(_,P);try{let O=C(M);if(O>Zn){T.push(`@${P} is ${Math.round(O/1048576)} MB — too large to attach (limit ${Zn/1048576} MB).`);continue}R.push({data:`data:${N};base64,${I(M).toString("base64")}`,mediaType:N,filename:xi(P)})}catch{T.push(`@${P} could not be read, so it was not attached.`)}}return{content:E,files:R,notes:T}}import{z as ce}from"zod";var we=ce.string().trim().min(1),Ai=ce.discriminatedUnion("kind",[ce.object({kind:ce.literal("project"),projectId:we}).strict(),ce.object({kind:ce.literal("cycle"),projectId:we,cycleId:we}).strict(),ce.object({kind:ce.literal("task"),projectId:we,taskId:we}).strict(),ce.object({kind:ce.literal("agent"),projectId:we,agentId:we}).strict()]);import{z as L}from"zod";var rr=["github-compare","workspace-artifact"],Ke=L.enum(["added","removed","modified","renamed","copied","changed","unchanged","unknown"]),or=L.object({path:L.string(),previousPath:L.string().nullable(),status:Ke,additions:L.number().nullable(),deletions:L.number().nullable(),patch:L.string().nullable(),patchTruncated:L.boolean()}),sr=L.object({status:L.enum(["ahead","behind","identical","diverged","unknown"]),aheadBy:L.number().nullable(),behindBy:L.number().nullable()}),ir=L.object({kind:L.literal("git-archive"),reviewUrl:L.string(),sizeBytes:L.number().nullable(),capturedAt:L.string().nullable()}),ar=L.object({verdict:L.enum(["approved","rejected"]),summary:L.string().nullable(),headSha:L.string().nullable(),observedAt:L.string(),stale:L.boolean()}),Pi=L.object({taskId:L.string(),repoId:L.string().nullable(),source:L.enum(rr),observedAt:L.string(),baseRef:L.string().nullable(),baseSha:L.string().nullable(),headRef:L.string().nullable(),headSha:L.string().nullable(),comparison:sr,filesChanged:L.number().nullable(),additions:L.number().nullable(),deletions:L.number().nullable(),commits:L.number().nullable(),files:L.array(or),filesTruncated:L.boolean(),evaluator:ar.nullable(),artifact:ir.nullable()}),lr=["base","head"],_t=L.enum(lr),cr=["open","resolved"],It=L.enum(cr),dr=L.object({pagePath:L.string().min(1).max(2048).regex(/^\/(?!\/)/,"expected a same-origin absolute path").refine((E)=>!/[?#\\]/.test(E),"query, fragment, and backslash are not allowed"),selector:L.string().min(1).max(512),viewport:L.object({width:L.number().int().min(320).max(1920),height:L.number().int().min(320).max(1200),deviceScaleFactor:L.literal(1)}).strict()}).strict(),pr=["previews-disabled","boundary-unavailable","review-head-unavailable","no-live-preview","revision-mismatch","source-not-isolated","unsafe-source"],ur=L.discriminatedUnion("enabled",[L.object({enabled:L.literal(!0)}),L.object({enabled:L.literal(!1),reasonCode:L.enum(pr),reason:L.string()})]),mr=L.string().regex(/^[0-9a-f]{40}$/i,"expected a commit sha"),gr=L.object({id:L.string(),taskId:L.string(),projectId:L.string(),authorId:L.string(),headSha:L.string(),path:L.string().nullable(),side:_t.nullable(),lineStart:L.number().nullable(),lineEnd:L.number().nullable(),selectedText:L.string().nullable(),body:L.string(),resolution:It,resolvedBy:L.string().nullable(),resolvedAt:L.string().nullable(),revisionIteration:L.number().nullable(),createdAt:L.string(),updatedAt:L.string(),stale:L.boolean()}),Ni=L.object({taskId:L.string(),headSha:L.string().nullable(),comments:L.array(gr),visualContext:ur.optional()}),Mi=L.object({headSha:mr,body:L.string().min(1).max(1e4),path:L.string().min(1).max(1024).nullish(),side:_t.nullish(),lineStart:L.number().int().positive().nullish(),lineEnd:L.number().int().positive().nullish(),selectedText:L.string().max(1e4).nullish(),visualContext:dr.optional()}).superRefine((E,_)=>{if(E.lineStart!=null&&(E.path==null||E.side==null))_.addIssue({code:L.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))_.addIssue({code:L.ZodIssueCode.custom,path:["lineEnd"],message:"lineEnd must be >= lineStart"});if(E.side!=null&&E.path==null)_.addIssue({code:L.ZodIssueCode.custom,path:["side"],message:"a side needs a path"})}),Oi=L.object({resolution:It}),Li=L.object({headSha:mr}),ji=L.object({taskId:L.string(),cycleId:L.string(),headSha:L.string(),commentIds:L.array(L.string()),staleSkipped:L.number(),feedback:L.string(),iteration:L.number(),started:L.boolean(),reason:L.string().nullable()});import{z as H}from"zod";var fr=H.enum(["github","workspace"]),Ct=H.object({path:H.string(),previousPath:H.string().nullable(),status:Ke,additions:H.number().nullable(),deletions:H.number().nullable(),binary:H.boolean()}),hr=H.object({sha:H.string(),subject:H.string(),at:H.string()}),Oe=H.object({ref:H.string(),sha:H.string().nullable()}),yr=H.object({repoKey:H.string(),label:H.string(),base:Oe,head:Oe,files:H.array(Ct),filesTruncated:H.boolean(),filesChanged:H.number(),additions:H.number(),deletions:H.number(),commits:H.array(hr),unavailable:H.enum(["repository_unreachable"]).nullable()}),xr=H.object({taskId:H.string(),title:H.string(),repoKey:H.string(),files:H.array(Ct),observedAt:H.string()}),Di=H.object({projectId:H.string(),source:fr,environmentState:H.string().nullable(),observedAt:H.string(),repos:H.array(yr),inFlight:H.array(xr)}),$i=H.object({repoKey:H.string(),path:H.string(),patch:H.string().nullable(),patchTruncated:H.boolean(),binary:H.boolean()}),Fi=H.object({repoKey:H.string(),ref:Oe,paths:H.array(H.string()),truncated:H.boolean()}),Hi=H.object({error:H.string(),environmentState:H.string()}),Ui=H.object({repoKey:H.string(),path:H.string(),ref:Oe,content:H.string().nullable(),truncated:H.boolean(),binary:H.boolean(),size:H.number().nullable(),data:H.string().nullable(),mediaType:H.string().nullable()});var Ve={"claude-opus-4-8":{provider:"anthropic",contextWindow:1e6,displayName:"Opus 4.8",tier:"frontier"},"claude-sonnet-5":{provider:"anthropic",contextWindow:1e6,displayName:"Sonnet 5",tier:"primary"},"claude-opus-4-7":{provider:"anthropic",contextWindow:200000,displayName:"Opus 4.7",tier:"frontier",picker:!1},"claude-opus-4-6":{provider:"anthropic",contextWindow:200000,displayName:"Opus 4.6",tier:"frontier",picker:!1},"claude-sonnet-4-6":{provider:"anthropic",contextWindow:200000,displayName:"Sonnet 4.6",tier:"primary",picker:!1},"claude-sonnet-4-5-20250929":{provider:"anthropic",contextWindow:200000,displayName:"Sonnet 4.5",tier:"primary",picker:!1},"claude-haiku-4-5":{provider:"anthropic",contextWindow:200000,displayName:"Haiku 4.5",tier:"fast"},"gpt-5.6-sol":{provider:"openai",contextWindow:1050000,displayName:"GPT-5.6 Sol",tier:"frontier"},"gpt-5.6-terra":{provider:"openai",contextWindow:1050000,displayName:"GPT-5.6 Terra",tier:"primary"},"gpt-5.6-luna":{provider:"openai",contextWindow:1050000,displayName:"GPT-5.6 Luna",tier:"fast"},"gpt-5.5":{provider:"openai",contextWindow:400000,displayName:"GPT-5.5",tier:"frontier",picker:!1},"gpt-5":{provider:"openai",contextWindow:256000,displayName:"GPT-5",tier:"frontier",picker:!1},"gpt-5-mini":{provider:"openai",contextWindow:128000,displayName:"GPT-5 Mini",tier:"fast",picker:!1},"gpt-4.1-mini":{provider:"openai",contextWindow:128000,displayName:"GPT-4.1 Mini",tier:"fast",picker:!1},"gemini-3.8-flash":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini 3.8 Flash",tier:"fast"},"gemini-3.6-flash":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini 3.6 Flash",tier:"fast",picker:!1},"gemini-3.5-flash":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini 3.5 Flash",tier:"fast",picker:!1},"gemini-2.5-pro":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini 2.5 Pro",tier:"primary",picker:!1},"gemini-embedding-2":{provider:"google_genai",contextWindow:8192,displayName:"Gemini Embedding 2",tier:"embedding",picker:!1},"grok-4.5":{provider:"openrouter",contextWindow:500000,displayName:"Grok 4.5",tier:"frontier"},"kimi-k3":{provider:"openrouter",contextWindow:1048576,displayName:"Kimi K3",tier:"primary"},"deepseek-v4-pro":{provider:"openrouter",contextWindow:1048576,displayName:"DeepSeek V4 Pro",tier:"primary"},"glm-5.3":{provider:"openrouter",contextWindow:1048576,displayName:"GLM 5.3",tier:"primary"},"qwen3.8-max":{provider:"openrouter",contextWindow:1e6,displayName:"Qwen 3.8 Max",tier:"primary"},auto:{provider:"openrouter",contextWindow:2000000,displayName:"Auto",tier:"primary"},"pareto-code":{provider:"openrouter",contextWindow:2000000,displayName:"Auto for coding",tier:"primary"},"opus-latest":{provider:"anthropic",contextWindow:1e6,displayName:"Claude Opus (Latest)",tier:"frontier"},"sonnet-latest":{provider:"anthropic",contextWindow:1e6,displayName:"Claude Sonnet (Latest)",tier:"primary"},"gemini-flash-latest":{provider:"google_genai",contextWindow:1048576,displayName:"Gemini Flash (Latest)",tier:"fast"},"gpt-latest":{provider:"openai",contextWindow:1050000,displayName:"GPT (Latest)",tier:"frontier"},"whisper-1":{provider:"openrouter",contextWindow:0,displayName:"Whisper 1 (Speech-to-Text)",tier:"media",picker:!1},"voxtral-mini-tts":{provider:"openrouter",contextWindow:4096,displayName:"Voxtral Mini TTS (Text-to-Speech)",tier:"media",picker:!1},"seedream-4-5":{provider:"openrouter",contextWindow:4096,displayName:"Seedream 4.5 (Image)",tier:"media",picker:!1},"veo-3-1":{provider:"openrouter",contextWindow:0,displayName:"Veo 3.1 (Video)",tier:"media",picker:!1}};var Bi=Object.keys(Ve);var Gi={"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 pe="◆",Wi=(()=>{let E={};for(let _ of Object.keys(Ve)){let I=Ve[_];E[_]=I.displayName,E[Gi[_]]=I.displayName,E[`${I.provider}:${_}`]=I.displayName}return E})();function qe(E){if(!E)return E;let I=Wi[E]??E.split(/[/:]/).pop()??E;return`${pe} ${I}`}var Rt={"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}},Tt=Object.keys(Rt),ze=Object.values(Rt),Yi=ze.filter(({driverKind:E})=>E==="external-acp").map(({id:E})=>E),br=ze.filter(({available:E,driverKind:_})=>E&&_==="external-acp"),kt=br.map(({id:E})=>E),Sr=ze.filter(({available:E})=>E),vr=Sr.map(({id:E})=>E),At="hlix";var wr=["chat","kanban","linear","github","api"];var Pt={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 Er(E){return wr.filter((_)=>Pt[_].kind===E)}var Vi=Er("external"),qi=Er("native");import{z as j}from"zod";var _r=j.enum(Tt),Ir=j.enum(kt),Cr=j.object({node:j.string().optional(),python:j.string().optional(),bun:j.string().optional(),playwright:j.boolean().optional()}).partial(),Rr=j.object({agents:j.array(Ir).optional(),toolchain:Cr.optional(),aptPackages:j.array(j.string()).optional(),setup:j.string().optional(),hash:j.string().optional(),imageTag:j.string().nullable().optional(),linearProjectId:j.string().optional(),linearTeamId:j.string().optional()}).partial(),ta=j.object({owner:j.string(),name:j.string(),cloneUrl:j.string(),defaultBranch:j.string()}),Tr=j.object({key:j.string(),cloneUrl:j.string().nullable(),owner:j.string().nullable(),name:j.string().nullable(),defaultBranch:j.string(),setupCommand:j.string().nullable().optional(),verifyCommand:j.string().nullable().optional()});var kr=j.object({name:j.string(),skillSlugs:j.array(j.string()),agentSlugs:j.array(j.string())}),Ar=j.object({path:j.string(),content:j.string()}),Pr=j.object({vars:j.record(j.string(),j.string()).default({}),files:j.array(Ar).optional(),skills:j.array(j.string()).optional(),mcpServers:j.array(j.unknown()).optional(),managedPaths:j.array(j.string().refine((E)=>E.length>0&&E===E.normalize("NFC")&&!E.startsWith("/")&&!E.includes("\\")&&!/[\u0000-\u001f\u007f]/.test(E)&&E.split("/").every((_)=>_&&_!=="."&&_!==".."),"managed path must be a canonical project-relative path")).optional()}),Nr=j.object({path:j.string(),kind:j.enum(["dotenv","credential","detected-content"]),contentBase64:j.string(),size:j.number().int().nonnegative(),sha256:j.string().regex(/^[0-9a-f]{64}$/)}),Mr=j.object({taskId:j.string(),cycleId:j.string(),threadId:j.string(),organizationId:j.string().optional(),projectId:j.string().optional(),description:j.string(),reviewFeedback:j.string().optional(),iteration:j.number().default(0),operationId:j.string().min(1).optional(),repo:Tr.nullable().default(null),verifyCommand:j.string().nullable().optional(),branch:j.string(),baseBranch:j.string(),githubToken:j.string().optional(),snapshotKey:j.string().optional(),aiGatewayUrl:j.string().optional(),secrets:j.record(j.string(),j.string()),packs:j.array(kr),systemPrompt:j.string().optional(),timeoutSeconds:j.number().default(1800),resultToken:j.string().min(1).optional(),agent:_r.default(At),agentEnv:j.record(j.string(),j.string()).optional(),projectRuntime:Rr.optional(),environment:Pr.optional(),protectedFiles:j.array(Nr).optional()}),na=j.enum(["acp"]),ra=j.enum(["builder","desktop","e2e"]),oa=j.object({batchId:j.string(),tasks:j.array(Mr).min(1).max(20)}),Or=j.object({inputTokens:j.number(),outputTokens:j.number(),costUsd:j.number()}),sa=j.object({taskId:j.string(),token:j.string().optional(),status:j.enum(["success","failed"]),cost:Or.optional(),model:j.string().optional(),error:j.string().optional()});import{z as ee}from"zod";var ia=ee.discriminatedUnion("type",[ee.object({type:ee.literal("text"),text:ee.string()}),ee.object({type:ee.literal("reasoning"),text:ee.string()}),ee.object({type:ee.literal("tool"),toolCallId:ee.string().min(1),toolName:ee.string().min(1),state:ee.enum(["pending","done","error"]),input:ee.unknown().optional(),output:ee.unknown().optional(),error:ee.string().optional()})]);function aa(E){let _=/^(.*?)\(([^()]*)\)\s*$/.exec(E);if(!_)return qe(E);let I=(_[1]??"").trim(),C=qe(_[2]??"").slice(pe.length).trim();return I?`${pe} ${I} (${C})`:`${pe} ${C}`}function Nt(E){let _=new Set,I=[],C=(R,T)=>{if(_.has(R))return;_.add(R),I.push({id:R,label:aa(T)})};for(let R of E.served??[])C(`${E.providerName}/${R.id}`,R.name);for(let R of E.userModelIds??[]){if(R.startsWith(`${E.providerName}/`))continue;C(R,R)}return I}function Lr(E){let _=t(E.cwd)?"project":"global";return u({key:"model",value:E.modelId,scope:_,cwd:E.cwd,env:E.env})}import{Markdown as ua,truncateToWidth as ue,wrapTextWithAnsi as jt}from"@earendil-works/pi-tui";function jr(E,_){if(E.length>600||_.length>600)return[...E.map((P)=>({kind:"del",text:P})),..._.map((P)=>({kind:"add",text:P}))];let I=E.length,C=_.length,R=Array.from({length:I+1},()=>Array(C+1).fill(0));for(let P=I-1;P>=0;P-=1)for(let N=C-1;N>=0;N-=1)R[P][N]=E[P]===_[N]?R[P+1][N+1]+1:Math.max(R[P+1][N],R[P][N+1]);let T=[],A=0,k=0;while(A<I&&k<C)if(E[A]===_[k])T.push({kind:"same",text:E[A]}),A+=1,k+=1;else if(R[A+1][k]>=R[A][k+1])T.push({kind:"del",text:E[A]}),A+=1;else T.push({kind:"add",text:_[k]}),k+=1;while(A<I)T.push({kind:"del",text:E[A++]});while(k<C)T.push({kind:"add",text:_[k++]});return T}function Dr(E,_,I={}){let C=I.context??2,R=jr(E.split(`
21
+ `),_.split(`
22
+ `)),T=new Set;R.forEach((N,M)=>{if(N.kind==="same")return;for(let O=M-C;O<=M+C;O+=1)if(O>=0&&O<R.length)T.add(O)});let A=[],k=0,P=()=>{if(k===0)return;A.push(` … ${k} unchanged line${k===1?"":"s"}`),k=0};return R.forEach((N,M)=>{if(!T.has(M)){k+=1;return}P(),A.push(`${N.kind==="add"?"+":N.kind==="del"?"-":" "} ${N.text}`)}),P(),A}function $r(E,_){let I=jr(E.split(`
23
+ `),_.split(`
24
+ `)),C=I.filter((T)=>T.kind==="add").length,R=I.filter((T)=>T.kind==="del").length;if(C===0&&R===0)return"";return[C>0?`+${C}`:"",R>0?`−${R}`:""].filter(Boolean).join(" ")}var Mt=(E)=>E;function Xe(E){return(_)=>_?`\x1B[${E}m${_}\x1B[0m`:_}var Re={gold:{rgb:[255,204,0],cube:220},vermilion:{rgb:[230,0,23],cube:160},teal:{rgb:[54,145,119],cube:66},paper:{rgb:[229,230,232],cube:188},slate:{rgb:[151,153,157],cube:103}};function Je(E=process.env,_=process.stdout.isTTY===!0){if(E.NO_COLOR!==void 0&&E.NO_COLOR!=="")return"none";let I=E.FORCE_COLOR!==void 0&&E.FORCE_COLOR!=="";if(!_&&!I)return"none";let C=(E.COLORTERM??"").toLowerCase();if(C==="truecolor"||C==="24bit")return"truecolor";if(/-direct\b/.test(E.TERM??""))return"truecolor";return"ansi256"}var Te=(E,_)=>{if(_==="none")return Mt;if(_==="truecolor")return Xe(`38;2;${E.rgb[0]};${E.rgb[1]};${E.rgb[2]}`);return Xe(`38;5;${E.cube}`)};function Fr(E=Je()){return{brand:Te(Re.gold,E),muted:E==="none"?Mt:Xe("2"),user:Te(Re.paper,E),alert:Te(Re.vermilion,E),ok:Te(Re.teal,E),added:Te(Re.teal,E),removed:Te(Re.vermilion,E)}}function Ze(E){return{selectedPrefix:E.brand,selectedText:E.brand,description:E.muted,scrollInfo:E.muted,noMatch:E.muted}}function Hr(E){return{borderColor:E.muted,selectList:Ze(E)}}function Ur(E,_=Je()){let I=(C)=>_==="none"?Mt:Xe(C);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:I("1"),italic:I("3"),strikethrough:I("9"),underline:I("4")}}var la="subagent",Wr=()=>({entries:[],busy:!1,status:"",approval:null});function Qe(E){let _=E?.content,I=_?.parts;if(!Array.isArray(I)){let C=_?.content;return typeof C==="string"?C:""}return I.filter((C)=>{let R=C;return R.type==="text"&&typeof R.text==="string"}).map((C)=>C.text).join("")}function Br(E,_){let I=_??{},C=I.path??I.command??I.pattern??I.query;return typeof C==="string"?`${oe(E)} ${C}`:oe(E)}function Gr(E){let _=E===void 0?null:/^Exit code: (\d+)$/m.exec(E);return _?Number(_[1]):void 0}function ca(E){if(typeof E==="string")return E;if(E===void 0||E===null)return"";let _=E.content;if(Array.isArray(_))return _.map((I)=>{let C=I;return C.type==="text"&&typeof C.text==="string"?C.text:""}).filter((I)=>I!=="").join(`
25
+ `);try{return JSON.stringify(E,null,2)}catch{return String(E)}}var da={om_observation_start:"remembering…",om_observation_end:"",om_reflection_start:"condensing memory…",om_reflection_end:"",compaction_start:"compacting…",compaction_end:""},pa={thread_created:()=>"New conversation.",info:(E)=>typeof E.message==="string"?E.message:null};function Yr(E,_){let I=(k,P)=>{let N=E.entries.findIndex((O)=>O.id===k),M=[...E.entries];if(N<0)M.push(P);else M[N]=P;return{...E,entries:M}},C=(k)=>({...E,entries:[...E.entries,k]}),R=(k)=>E.entries.find((P)=>P.id===k),T=(k)=>`tool:${String(k)}`,A=(k)=>`sub:${String(k)}`;switch(_.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 k=_.message;if(!k?.id)return E;let P=Qe(k);if(!P)return E;let N=`msg:${k.id}`;if(R(N)?.text===P)return E;return I(N,{kind:k.role==="user"?"user":"assistant",id:N,text:P})}case"tool_start":{if(_.toolName===la)return E;let k=T(_.toolCallId),P=oe(_.toolName);return I(k,{kind:"tool",id:k,text:Br(_.toolName,_.args),tool:{name:P,args:_.args,state:"running"}})}case"tool_approval_required":{let k=T(_.toolCallId),P=R(k),N={toolCallId:String(_.toolCallId),toolName:_.toolName,args:_.args},M=P?.tool?{...P,tool:{...P.tool,state:"awaiting"}}:{kind:"tool",id:k,text:Br(_.toolName,_.args),tool:{name:oe(_.toolName),args:_.args,state:"awaiting"}};return{...I(k,M),approval:N}}case"tool_end":{let k=T(_.toolCallId),P=R(k);if(!P?.tool)return E;let N=_.denied===!0,M=_.isError===!0,O=ca(_.result),F=I(k,{...P,error:M||N,tool:{...P.tool,result:O,state:N?"declined":M?"error":"done",...Gr(O)!==void 0?{exitCode:Gr(O)}:{}}});return E.approval?.toolCallId===String(_.toolCallId)?{...F,approval:null}:F}case"subagent_start":{let k=A(_.toolCallId);return I(k,{kind:"subagent",id:k,title:String(_.agentType),text:String(_.task??""),subagent:{agentType:String(_.agentType),task:String(_.task??""),tools:[],state:"running"}})}case"subagent_tool_start":{let k=A(_.toolCallId),P=R(k);if(!P?.subagent)return E;return I(k,{...P,subagent:{...P.subagent,tools:[...P.subagent.tools,oe(_.subToolName)]}})}case"subagent_end":{let k=A(_.toolCallId),P=R(k);if(!P?.subagent)return E;let N=_.isError===!0;return I(k,{...P,error:N,subagent:{...P.subagent,state:N?"error":"done",result:String(_.result??""),...typeof _.durationMs==="number"?{durationMs:_.durationMs}:{}}})}case"error":{let k=_.error;return C({kind:"notice",id:`error:${E.entries.length}`,text:k?.message??"The turn failed.",error:!0})}default:{let k=da[_.type];if(k!==void 0)return{...E,status:k};let P=pa[_.type]?.(_);return P===null||P===void 0?E:C({kind:"notice",id:`${_.type}:${E.entries.length}`,text:P})}}}function Kr(E){return E.replace(/\r\n/g,`
26
+ `).split(`
27
+ `).map((_)=>_.split("\r").reduce((I,C)=>C+I.slice(C.length),""))}function et(E){let _=E.state??(E.failed?"failed":"done");return{kind:"command",id:`cmd:${E.index}`,title:`/${E.name}`,text:E.output,..._==="failed"&&!E.report?{error:!0}:{},command:{state:_,elapsedMs:E.elapsedMs??0,...E.exitCode===void 0?{}:{exitCode:E.exitCode},...E.report?{report:E.report}:{}}}}var ma={user:"›",assistant:" ",tool:"⏺",command:"▸",subagent:"↳",notice:"·"},Le=8,Vr=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],ga=(E)=>Vr[Math.floor(Math.max(0,E)/100)%Vr.length],Ot=(E,_)=>_?`${Math.floor(E/1000)}s`:`${(E/1000).toFixed(1)}s`;function fa(E,_){if(_.state==="running")return`${E} ${ga(_.elapsedMs)} ${Ot(_.elapsedMs,!0)}`;if(_.state==="cancelled")return`${E} cancelled after ${Ot(_.elapsedMs,!0)}`;let I=_.exitCode!==void 0&&_.exitCode!==0;return`${E} ${Ot(_.elapsedMs,!1)}${I?` · exit ${_.exitCode}`:""}`}function Lt(E,_,I){let C=`┌ ${E} `,R=Math.max(0,_-C.length);return I(ue(`${C}${"─".repeat(R)}`,_))}var ha=(E,_)=>_(ue(`└${"─".repeat(Math.max(0,E-1))}`,E));function de(E,_,I,C){let R=Math.max(1,_-2),T=[];for(let A of E){let k=A===""?[""]:jt(A,R);for(let P of k)T.push(ue(`${C("│")} ${I(P)}`,_))}return T}function ya(E){let _=E.tool;if(!_)return"";let I=[],C=_.args??{};if(typeof C.old_string==="string"&&typeof C.new_string==="string"){let R=$r(C.old_string,C.new_string);if(R)I.push(R)}if(_.durationMs!==void 0)I.push(`${(_.durationMs/1000).toFixed(1)}s`);if(_.exitCode!==void 0&&_.exitCode!==0)I.push(`exit ${_.exitCode}`);return I.join(" · ")}function xa(E){switch(E.tool?.state){case"running":return"⏺";case"awaiting":return"?";case"declined":return"⊘";case"error":return"✗";default:return"✓"}}function ba(E){let _=E.tool;if(!_)return[];let I=_.args??{};if(typeof I.old_string==="string"&&typeof I.new_string==="string")return Dr(I.old_string,I.new_string);let C=(_.result??"").trimEnd();return C===""?[]:C.split(`
28
+ `)}function tt(E,_){let I=E-_;return`… ${I} more line${I===1?"":"s"} — ctrl-o to expand`}function qr(E,_){let{width:I,colors:C}=_;switch(E.kind){case"assistant":return zr(E.text,I,C);case"command":return va(E,_);case"tool":return Ea(E,_);case"subagent":return Ia(E,_);default:{let R=E.kind==="user"?C.user:E.error?C.alert:C.muted,T=E.error?"!":ma[E.kind];return Sa(E.text,T,I,R)}}}function zr(E,_,I){let C=Math.max(8,_-2);return new ua(E,0,0,Ur(I)).render(C).map((T)=>ue(` ${T}`,_))}function Sa(E,_,I,C){let R=Math.max(1,I-2),T=[];for(let A of E.split(`
29
+ `)){let k=A===""?[""]:jt(A,R);for(let P of k){let N=T.length===0?`${_} `:" ";T.push(ue(`${N}${C(P)}`,I))}}return T}function va(E,_){let{width:I,colors:C}=_,R=E.command??{state:E.error?"failed":"done",elapsedMs:0},T=E.error?C.alert:C.muted,A=fa(E.title??"command",R),k=ha(I,T);if(R.report)return[Lt(A,I,T),...wa(E,R,_,T),k];let P=E.text===""?["(no output)"]:Kr(E.text),N=R.state==="running",M=E.expanded===!0?P:N?P.slice(-Le):P.slice(0,Le*3),O=P.length-M.length;return[Lt(A,I,T),...de(M,I,E.error?C.alert:C.user,T),...O>0?de([tt(P.length,M.length)],I,C.muted,T):[],k]}function wa(E,_,I,C){let{width:R,colors:T}=I,A=_.report;if(!A)return[];let k=E.expanded===!0?A.rows:A.rows.slice(0,Le);return[...de([`⚠ ${A.headline}`],R,T.brand,C),...k.length>0?de(["",...k],R,T.user,C):[],...k.length<A.rows.length?de([tt(A.rows.length,k.length)],R,T.muted,C):[],...A.notes.length>0?de(A.notes,R,T.muted,C):[],...A.next?de(["",`→ ${A.next}`],R,T.brand,C):[]]}function Ea(E,_){let{width:I,colors:C}=_,R=E.tool,T=xa(E),A=E.error?C.alert:R?.state==="running"?C.muted:C.ok,k=ya(E),P=`${T} ${E.text}`,N=I-P.length-k.length-1,M=k&&N>0?ue(`${A(P)}${" ".repeat(N)}${C.muted(k)}`,I):ue(A(P),I);if(R?.state==="running"||R?.state==="awaiting")return[M];let O=ba(E);if(O.length===0)return[M];let F=E.expanded===!0?O:O.slice(0,Le);return[M,..._a(F,I,C),...F.length<O.length?de([tt(O.length,F.length)],I,C.muted,C.muted):[]]}function _a(E,_,I){let C=Math.max(1,_-2),R=[];for(let T of E){let A=T.startsWith("+")?I.added:T.startsWith("-")?I.removed:I.muted;for(let k of T===""?[""]:jt(T,C))R.push(ue(`${I.muted("│")} ${A(k)}`,_))}return R}function Ia(E,_){let{width:I,colors:C}=_,R=E.subagent;if(!R)return[];let T=E.error?C.alert:C.muted,A=R.state==="running"?"↳":E.error?"✗":"✓",k=R.durationMs!==void 0?` · ${(R.durationMs/1000).toFixed(1)}s`:"",P=ue(`${(E.error?C.alert:C.brand)(`${A} ${R.agentType}`)}${C.muted(`${k}${R.tools.length>0?` · ${R.tools.length} tool calls`:""}`)}`,I),N=[R.task];if(R.tools.length>0)N.push(`tools: ${[...new Set(R.tools)].join(", ")}`);if(R.state!=="running"&&R.result){let M=R.result.split(`
30
+ `),O=E.expanded===!0?M:M.slice(0,Le);if(N.push("",...O),O.length<M.length)N.push(tt(M.length,O.length))}return[P,...de(N,I,C.muted,T)]}function Xr(E,_){let{width:I,colors:C}=_,R=E.args??{},T=[R.command,R.path,R.pattern,R.query,R.task,R.name,R.skill].find((k)=>typeof k==="string"&&k!==""),A=oe(E.toolName);return[Lt(`Approve ${A}`,I,C.alert),...de(T?[T]:["(no arguments)"],I,C.user,C.alert)]}var je="yolo";function Ca(E,_){if(_<=0)return`${Math.round(E/1000)}k`;return`${Math.round(E/_*100)}% of ${Math.round(_/1000)}k`}function Ra(E){return E>0&&E<0.01?`$${E.toFixed(4)}`:`$${E.toFixed(2)}`}var Ta=4,ka=["cost","total_cost","costUsd"];function nt(E){let _=E?.raw;for(let I=0;I<Ta&&_&&typeof _==="object";I+=1){for(let C of ka){let R=_[C];if(typeof R==="number"&&Number.isFinite(R)&&R>0)return R}_=_.raw}return}var Aa=(E)=>E.startsWith(pe)?E:`${pe} ${E}`,Pa=(E)=>E.split(" (")[0];function Na(E){let _=[...E.yolo?[je]:[],E.sandbox,E.harness];if(E.mode&&E.mode!==Pa(E.harness))_.push(E.mode);if(E.model)_.push(Aa(E.model));if(E.workspace)_.push(E.workspace);if(E.branch)_.push(E.branch);if(E.context)_.push(Ca(E.context.used,E.context.total));if(E.costUsd!==void 0)_.push(Ra(E.costUsd));if(E.memory)_.push(E.memory);if(E.warning)_.push(E.warning);return _}function Jr(E,_){let I=Na(E).join(" · ");if(_===void 0||_<=0||I.length<=_)return I;return _<=1?I.slice(0,_):`${I.slice(0,_-1)}…`}import{readdirSync as ja,readFileSync as Da}from"node:fs";import{basename as $a,join as Fa}from"node:path";var Ma={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"}},Dt=(E,_)=>`${E} ${_}${E===1?"":"s"}`,Zr=(E)=>(E.split(`
31
+ `)[0]??E).replace(/:$/,"");function Oa(E){let _=E;return Array.isArray(_?.findings)&&Array.isArray(_?.blocking)}function La(E){let _=new Map;for(let I of E)_.set(I.path,[..._.get(I.path)??[],I]);return[..._].map(([I,C])=>{let R=[...new Set(C.map((A)=>A.reason))].join(", "),T=C[0];return C.length===1?`${T.commit.slice(0,7)} · ${I} · ${R}`:`${I} ×${C.length} · ${R}`})}function Qr(E){if(E.code==="unknown")return null;let _=Ma[E.code],I=_?.needs===void 0||E.options?.includes(_.needs)!==!1,C=_&&I?_.next(E.name):null;if(E.code==="scan_blocked"&&Oa(E.details)){let{findings:A,fixtureFindings:k,blocking:P}=E.details;return{headline:A.length>0?`Import blocked — ${Dt(A.length,"finding")} in Git history`:`Import blocked — ${Dt(P.length,"finding")}`,rows:[...La(A),...P.map(Zr)],notes:k>0?[`${Dt(k,"finding")} look like fixtures (not blocking)`]:[],next:A.length>0?C:null}}let[R,...T]=E.message.split(`
32
+ `);return{headline:Zr(R??E.message),rows:T.filter((A)=>A.trim()!==""),notes:[],next:C}}var io=(E)=>E.split(" ").join("-");function Ha(E,_,I){let C=E.name.split(" "),R=_.trim();if(R)C.push(...R.split(/\s+/));return C.push("--cwd",I),C}var eo="Project prompt";function Ua(E){let _=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(E);if(!_)return{description:eo,body:E};return{description:/^description:[ \t]*(.+)$/m.exec(_[1]??"")?.[1]?.trim()||eo,body:E.slice(_[0].length).replace(/^(?:[ \t]*\r?\n)+/,"")}}function Ba(E){let _=new Map;for(let I of E){let C;try{C=ja(I)}catch{continue}for(let R of C){if(!R.endsWith(".md"))continue;try{_.set($a(R,".md"),Ua(Da(Fa(I,R),"utf8")))}catch{continue}}}return _}function Ga(E,_){let I=_.trim();if(E.includes("$ARGUMENTS"))return E.split("$ARGUMENTS").join(I);return I?`${E.trimEnd()}
33
+
34
+ ${I}`:E}function to(E,_){return async(I,C,R)=>{let T="",A=(O)=>{T+=O,R?.onOutput?.(O)},k=[],P=await s([E],Ha(E,I,C),{stdout:A,stderr:A,env:_,...R?.signal?{signal:R.signal}:{},onFailure:(O)=>k.push(O)}),N=k.at(-1),M=N?Qr({name:io(E.name),...E.options?{options:E.options}:{},...N}):null;return{lines:[],output:T.trimEnd()||`exit ${P}`,exitCode:P,...P===0?{}:{failed:!0},...M?{report:M}:{}}}}var rt={lines:["This command needs a live session."]};async function no(E,_,I,C,R){let T=R.find((M)=>M.name==="config set");if(!T)return{ok:!1,message:`This build has no \`config set\`, so ${E} was not written.`};let A="",k=(M)=>{A+=M},P=await s([T],["config","set",E,_,"--cwd",I],{stdout:k,stderr:k,env:C}),N=A.trim();if(P===0)return{ok:!0,message:N||`${E} is ${_}.`};return{ok:!1,message:[`${E} was NOT written: ${N.replace(/^error:\s*/,"")||"config set failed."}`,`To set it for every project: \`hlix config set ${E} ${_} --global\`.`].join(`
35
+ `)}}function ao(E={}){let _=E.env??process.env,I=E.shell,C=new Map,R=(N)=>C.set(N.name,N),T=E.commands??a;for(let N of T)R({name:io(N.name),description:N.summary,handler:to(N,_)});let A=(N,M,O)=>{let F=T.find((U)=>U.name===M);if(F)R({name:N,description:O,handler:to(F,_)})};for(let[N,M]of Ba(E.promptFiles??[])){if(C.has(N))continue;R({name:N,description:M.description,prompt:(O)=>Ga(M.body,O),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"),R({name:"model",description:"Pick the model this session runs on",handler:()=>(I?.openModelPicker?.(),{lines:I?.openModelPicker?[]:["No model picker in this mode."]})}),R({name:"sandbox",description:"Where this session's files and commands run",handler:async(N,M)=>{let O=I?.facts;if(!O)return{lines:["Sandbox not resolved."]};let F=N.trim(),U=async(q)=>{let K=await no("sandbox",q,M,_,T);return{lines:[],output:[O.sandboxLine,K.ok?`${K.message} This session keeps ${O.sandbox}; restart to run in ${q}.`:K.message].join(`
36
+ `),...K.ok?{}:{failed:!0}}};if(F){if(!i.includes(F))return{lines:[`/sandbox must name one of ${i.join(", ")}.`]};return U(F)}if(!I?.openPicker)return{lines:[],output:O.sandboxLine};return I.openPicker({title:"Sandbox",current:O.sandbox,choices:i.map((q)=>({value:q,label:q,description:Wa[q]})),apply:U}),{lines:[]}}}),R({name:"harness",description:"Show or change which coder does the work (`clear` un-pins the project)",handler:async(N,M)=>{let O=I?.facts;if(!O)return{lines:["Harness not resolved."]};let F=O.harnessModesBuilt?I?.session?.mode.get()??O.harness:O.harness,U=async(K)=>{let Y=ut({requested:K,current:F,available:O.availableHarnesses,sandbox:O.sandbox,sandboxLine:O.sandboxLine,modesBuilt:O.harnessModesBuilt});if(Y.action==="mode"&&I?.session)await I.session.mode.switch({modeId:Y.harness}),I.setFact?.({harness:Y.harness,mode:Y.harness});if(Y.action==="preference"){if(!I?.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 I.setProjectHarness(Y.harness),I.setFact?.({harness:Y.harness})}let te=Y.action==="restart"?await no("harness",K,M,_,T):null;return{lines:[],output:te?`${Y.message}
37
+ ${te.message}`:Y.message,...te&&!te.ok?{failed:!0}:{}}},q=N.trim();if(q==="clear"){if(!I?.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 K=await I.clearProjectHarness();if(K)I.setFact?.({harness:K});return{lines:[],output:K?`Project harness preference cleared. Now: ${K}.`:"Project harness preference cleared. Run `/harness` for what runs now."}}if(q)return U(q);if(!I?.openPicker)return{lines:[],output:`harness: ${F}`};return I.openPicker({title:"Harness",current:F,choices:r.map((K)=>({value:K,label:K,description:O.availableHarnesses.includes(K)?K==="hlix"?"Our own coder. The default.":"Installed on this machine.":"Not installed here."})),apply:U}),{lines:[]}}}),R({name:"new",description:"Start a new conversation in this folder",handler:async()=>{if(!I?.session)return rt;return await I.session.thread.create(),{lines:[]}}}),R({name:"threads",description:"List this project's conversations, newest first",handler:async(N)=>{if(!I?.session)return rt;let M=N.trim();if(M&&M!=="--all")return{lines:[],output:await oo(I,M)};let O=ot(await I.session.thread.list()),F=ot(await Ht(I)),U=I.session.thread.getId();if(O.length===0&&F.length===0)return{lines:[],output:"No conversations here yet."};let q=O.map((K)=>Ft(K,U));if(M==="--all")q.push(...ro(F));else if(F.length>0)q.push(Va(F.length));return{lines:[],output:q.join(`
38
+ `)}}}),R({name:"resume",description:"Pick an earlier conversation in this project and continue it",handler:async()=>{if(!I?.session)return rt;let N=ot(await I.session.thread.list()),M=ot(await Ht(I));if(N.length===0&&M.length===0)return{lines:[],output:"No conversations here yet."};let O=I.session.thread.getId();if(!I.openPicker)return{lines:[],output:[...N.map((F)=>Ft(F,O)),...ro(M)].join(`
39
+ `)};return I.openPicker({title:"Resume",...O?{current:O}:{},choices:[...N.map((F)=>({value:F.id,label:F.title?.trim()||"(untitled)",description:`${F.id} ${$t(F.updatedAt)}`})),...M.map((F)=>({value:F.id,label:F.title?.trim()||"(untitled)",description:`${F.id} ${$t(F.updatedAt)} ${Ya}`}))],apply:async(F)=>({lines:[],output:await oo(I,F)})}),{lines:[]}}}),R({name:"compact",description:"Condense this conversation into memory now",handler:async()=>{if(!I?.compact)return rt;return{lines:[],output:await I.compact()}}}),R({name:"log",description:"Show what this session's libraries logged",handler:()=>{if(!I?.log)return{lines:["No log in this mode."]};let N=I.log.tail(200);return{lines:[],output:N.length===0?`Nothing logged this session.
40
+ ${I.log.path}`:[...N,"",I.log.path].join(`
41
+ `)}}}),R({name:"rules",description:"Show the user and project rules this session loaded",handler:()=>{if(!I?.rules)return{lines:["Rules not resolved."]};return{lines:[],output:I.rules()}}}),R({name:"yolo",description:"Run without asking for approval — toggles",handler:(N)=>{if(!I?.yolo)return{lines:["Approvals are not resolved in this mode."]};let M=N.trim().toLowerCase(),O=M===""?!I.yolo.get():!["off","false","0","no"].includes(M);return I.yolo.set(O),I.setFact?.({yolo:O}),{lines:[],output:O?"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."}}}),R({name:"help",description:"List the commands this terminal knows",handler:()=>({lines:[],output:[...C.values()].map((N)=>`/${N.name.padEnd(22)} ${N.description}`).sort().join(`
42
+ `)})});let k={name:"exit",description:"Leave Hlix Code",handler:()=>({lines:[],quit:!0})};R(k),R({...k,name:"quit"});let P=C.get("standards");if(P&&I?.mcp)R({...P,handler:async(N,M)=>{let O=await P.handler(N,M),F=I.mcp?.()??[];if(F.length===0)return O;return{...O,output:[O.output??"","MCP servers (this session)",...F.map((U)=>` ${U}`)].join(`
43
+ `).trim()}}});return C}var Wa={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 ot(E){return[...E].sort((_,I)=>(I.updatedAt?.getTime()??0)-(_.updatedAt?.getTime()??0))}function $t(E,_=new Date){if(!E)return"no activity";let I=Math.floor((_.getTime()-E.getTime())/60000);if(I<1)return"just now";if(I<60)return`${I}m ago`;let C=Math.floor(I/60);if(C<24)return`${C}h ago`;if(C<48)return"yesterday";return E.toISOString().slice(0,10)}var Ft=(E,_)=>`${E.id===_?"›":" "} ${(E.title?.trim()||"(untitled)").padEnd(40)} ${$t(E.updatedAt)}`,Ya="· older";function Ka(E,_){return E.filter((I)=>I.resourceId===_.legacyResourceId&&gn(I.metadata?.projectPath,_.root))}async function Ht(E){if(!E.session||!E.memory)return[];return Ka(await E.session.thread.list({allResources:!0}),E.memory)}var Va=(E)=>`${E} older thread${E===1?"":"s"} from before per-project memory — /threads --all to see them`,ro=(E)=>E.length===0?[]:["","before per-project memory (resuming one copies it into this project):",...E.map((_)=>Ft(_,null))];async function oo(E,_){let I=E.session;if(!I)return"No session.";try{return await I.thread.switch({threadId:_,emitEvent:!0}),`Resumed ${await qa(E,_)}.
44
+ ${await so(E)}`}catch(C){let R=await za(E,_);if(!R)throw C;return`Resumed ${_} as ${R} — copied into this project's memory.
45
+ ${await so(E)}`}}async function qa(E,_){let C=(await E.session?.thread.list())?.find((R)=>R.id===_)?.title?.trim();return C?`"${C}"`:_}async function so(E,_=6){let I=E.session;if(!I)return"";let R=(await I.thread.listActiveMessages()).filter((k)=>k.role==="user"||k.role==="signal"||k.role==="assistant").map((k)=>({who:k.role==="assistant"?"hlix":"you",text:(k.content?.parts??[]).filter((P)=>P.type==="text"&&typeof P.text==="string").map((P)=>P.text).join(" ").replace(/\s+/g," ").trim()})).filter((k)=>k.text!=="");if(R.length===0)return"No turns in this conversation yet.";let T=R.slice(-_),A=T.map((k)=>`${k.who.padEnd(4)} ${k.text.length>110?`${k.text.slice(0,109)}…`:k.text}`);if(R.length>T.length)A.unshift(`… ${R.length-T.length} earlier turn${R.length-T.length===1?"":"s"}`);return A.join(`
46
+ `)}async function za(E,_){let I=E.session?.thread,C=E.memory;if(!I?.cloneToCurrentResource||!C)return null;let T=(await Ht(E)).find((k)=>k.id===_)?.metadata?.projectPath;if(typeof T!=="string")return null;return(await I.cloneToCurrentResource({threadId:_,expectedResourceId:C.legacyResourceId,expectedProjectPath:T})).id}function lo(E){if(!E.startsWith("/"))return{kind:"prompt",name:"",args:E};let _=E.slice(1),I=_.indexOf(" ");return I<0?{kind:"slash",name:_,args:""}:{kind:"slash",name:_.slice(0,I),args:_.slice(I+1)}}function co(E,_){let I=E.args.trimStart(),C=I.indexOf(" "),R=C<0?I:I.slice(0,C);if(R==="")return E;let T=`${E.name}-${R}`;if(!_.has(T))return E;return{kind:E.kind,name:T,args:C<0?"":I.slice(C+1)}}class uo{colors;state=Wr();expanded=new Set;constructor(E){this.colors=E}render(E){return this.state.entries.flatMap((_)=>[...qr(this.expanded.has(_.id)?{..._,expanded:!0}:_,{width:E,colors:this.colors}),""])}lastCollapsible(){return[...this.state.entries].reverse().find((E)=>E.kind==="tool"||E.kind==="command"||E.kind==="subagent")}invalidate(){}}class mo{colors;text="";constructor(E){this.colors=E}render(E){return this.text===""?[]:[this.colors.muted(Ut(`· ${this.text}`,E))]}invalidate(){}}class go{colors;facts=null;constructor(E){this.colors=E}render(E){if(!this.facts)return[];let _=Jr(this.facts,E);if(this.facts.yolo!==!0||!_.startsWith(je))return[this.colors.muted(_)];return[`${this.colors.alert(je)}${this.colors.muted(_.slice(je.length))}`]}invalidate(){}}class fo{header=()=>[];body=null;open(E,_){this.header=E,this.body=_}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 ho(E){let _=Fr(Je(E.env)),I=E.tui??new Qa(new Ja),C=new uo(_),R=new mo(_),T=new fo,A=new go(_),k={...E.facts};A.facts=k;let P=0,N=()=>I.requestRender(),M=(D)=>{C.state={...C.state,entries:[...C.state.entries,D]},N()},O=(D)=>{let B=C.state.entries.some((G)=>G.id===D.id);C.state={...C.state,entries:B?C.state.entries.map((G)=>G.id===D.id?D:G):[...C.state.entries,D]},N()},F=(D)=>{C.state={...C.state,entries:C.state.entries.filter((B)=>B.id!==D)},N()},U=(D)=>{M({kind:"notice",id:`warn:${P++}`,text:D,error:!0})},q=(D)=>{M({kind:"notice",id:`say:${P++}`,text:D})},K=(D,B)=>{for(let G of B.lines)U(G);if(B.output===void 0)return;M(et({name:D,output:B.output,index:P++,...B.failed?{failed:!0}:{}}))},Y=null,te=null,se=null,ie=()=>{R.text=Y?`running /${Y.name} — ESC to cancel`:C.state.status},he=()=>{if(te===null)return;clearInterval(te),te=null},ne=new Xa(I,Hr(_)),Q=()=>{T.close(),I.setFocus(ne),I.requestRender()},me=new Set,Ee=async(D)=>{let B=E.session.thread.getId();if(!B||me.has(B))return;if(me.add(B),(await E.session.thread.list()).find((X)=>X.id===B)?.title?.trim())return;let W=D.replace(/\s+/g," ").trim().slice(0,60);if(W)await E.session.thread.rename({title:W})},ke=(D)=>{let{content:B,files:G,notes:W}=nr(D,E.cwd);M({kind:"user",id:`you:${P++}`,text:D});for(let X of W)U(X);Ee(D).catch(()=>{}),E.session.sendMessage({content:B,...G.length>0?{files:G}:{}}).catch((X)=>{U(X instanceof Error?X.message:String(X))})},De=(D)=>{let B=D.choices.map((W)=>({value:W.value,label:W.value===D.current?`${W.label} (current)`:W.label,...W.description?{description:W.description}:{}})),G=new po(B,Math.min(B.length,8),Ze(_));G.onSelect=(W)=>{Q(),Promise.resolve(D.apply(W.value)).then((X)=>K(D.title.toLowerCase(),X)).catch((X)=>{U(`${D.title}: ${X instanceof Error?X.message:String(X)}`)})},G.onCancel=Q,T.open((W)=>[_.brand(Ut(D.title,W))],G),I.setFocus(T),I.requestRender()},at=(D,B)=>{let G=E.commands.get(D);if(!G){U(`Unknown command /${D}. Try /help.`);return}if(G.prompt){ke(G.prompt(B));return}if(Y){U(`/${Y.name} is still running. Press ESC to cancel it first.`);return}let W={name:D,index:P++,started:Date.now(),output:"",controller:new AbortController,cancelled:!1};Y=W;let X=(z={})=>et({name:D,index:W.index,output:z.output??W.output,elapsedMs:z.elapsedMs??Date.now()-W.started,...z.state?{state:z.state}:{},...z.failed?{failed:!0}:{},...z.exitCode===void 0?{}:{exitCode:z.exitCode},...z.report?{report:z.report}:{}}),Ae=()=>{if(Y===W)Y=null;he(),ie()},Fe=!1,Io=()=>{if(Fe||Y!==W)return;Fe=!0,M(X({output:"",state:"running",elapsedMs:0})),ie(),te=setInterval(()=>{if(Y===W)O(X({state:"running"}))},200)};(async()=>G.handler(B,E.cwd,{onOutput:(z)=>{if(Y!==W)return;W.output+=z,O(X({state:"running"}))},signal:W.controller.signal}))().then((z)=>{if(W.cancelled)return;Ae();for(let He of z.lines)U(He);if(z.quit)I.stop();if(z.output===void 0){F(`cmd:${W.index}`);return}O(X({output:z.output,...z.failed?{failed:!0}:{},...z.exitCode===void 0?{}:{exitCode:z.exitCode},...z.report?{report:z.report}:{}})),se=z.report?.next??null}).catch((z)=>{if(W.cancelled)return;Ae();let He=z instanceof Error?z.message:String(z);O(X({output:He,failed:!0})),U(`/${D} failed: ${He}`)}),queueMicrotask(Io)},Z=()=>{let D=Y;if(!D)return;D.cancelled=!0,D.controller.abort(),Y=null,he(),ie(),O(et({name:D.name,index:D.index,output:D.output,state:"cancelled",elapsedMs:Date.now()-D.started}))},V=()=>{if(E.models.length===0){U("No models to choose from. Run `hlix auth login`.");return}let D=E.models.find((B)=>B.label===k.model)?.id;De({title:"Model",...D?{current:D}:{},choices:E.models.map((B)=>({value:B.id,label:B.label})),apply:async(B)=>{let G=E.models.find((X)=>X.id===B);if(!G)return{lines:[],output:`Unknown model ${B}.`,failed:!0};await E.session.model.switch({modelId:G.id});let W=Lr({modelId:G.id,cwd:E.cwd,env:E.env});return k.model=G.label,E.onModelPicked?.(G),{lines:[],output:`Model is ${G.label} — written to ${W}.`}}})},_e=(D,B,G)=>{E.session.respondToToolApproval({decision:B,toolCallId:D,...G?{declineContext:{reason:G}}:{}})},$e=(D)=>{if(E.yolo?.get()){_e(D.toolCallId,"approve");return}let B=Ln(D.toolName),G=new po(B.map((W)=>({value:W.value,label:W.label,description:W.description})),B.length,Ze(_));G.onSelect=(W)=>{if(W.value!=="decline"){Q(),_e(D.toolCallId,W.value);return}let X=new Za({prompt:"why not? (enter to skip) ",placeholder:"reason"}),Ae=(Fe)=>{Q(),_e(D.toolCallId,"decline",Fe.trim())};X.onSubmit=Ae,X.onEscape=()=>Ae(""),T.open(()=>[],X),I.setFocus(T),I.requestRender()},G.onCancel=()=>{Q(),_e(D.toolCallId,"decline","The user dismissed the approval prompt.")},T.open((W)=>Xr({toolCallId:D.toolCallId,toolName:D.toolName,args:D.args},{width:W,colors:_}),G),I.setFocus(T),I.requestRender()};E.session.subscribe((D)=>{if(D.type==="tool_approval_required")$e(D);if(D.type==="mode_changed")k.mode=D.modeId;if(D.type==="usage_update"){let G=nt(D.usage);if(k.context={used:D.usage.totalTokens,total:k.context?.total??0},G!==void 0)k.costUsd=G}let B=Yr(C.state,D);if(B!==C.state)C.state=B;ie(),N()});let le=tr({tui:I,editor:ne,commands:E.commands,basePath:E.cwd,handlers:{onSubmit:(D)=>{se=null;let B=lo(D);if(B.kind==="slash"){let G=co(B,E.commands);at(G.name,G.args);return}ke(D)},onCycleMode:()=>{let D=Bn(E.session.mode.get());E.session.mode.switch({modeId:D}).catch(()=>{U("This session's harness has no build/plan modes. Try /harness.")})},onAbort:()=>{if(Y){Z();return}if(!C.state.busy)return;E.session.abort(),q("Aborted.")},onEmptySubmit:()=>{if(!se)return;ne.setText(se),se=null,I.requestRender()},onExpand:()=>{let D=C.lastCollapsible();if(!D)return;if(C.expanded.has(D.id))C.expanded.delete(D.id);else C.expanded.add(D.id);I.requestRender()},onInterruptWarning:()=>q(Et),onExit:()=>I.stop()}});for(let D of E.notices??[])q(D);if(I.addChild(new class{render(D){return[_.brand(Ut(`◆ ${ae}`,D)),""]}invalidate(){}}),I.addChild(C),I.addChild(R),I.addChild(T),I.addChild(ne),I.addChild(A),I.setFocus(ne),N(),E.commands.set("model",{name:"model",description:"Pick the model this session runs on",handler:()=>(V(),{lines:[]})}),E.bindings)E.bindings.openPicker=De,E.bindings.openModelPicker=V,E.bindings.setFact=(D)=>{if(D.harness!==void 0)k.harness=D.harness;if(D.mode!==void 0)k.mode=D.mode;if(D.yolo!==void 0)k.yolo=D.yolo;N()};await new Promise((D)=>{let B=I.stop.bind(I);I.stop=(G)=>{le(),he(),B(G),D()},I.start()})}var el=new Set(["display_state_changed","tool_input_start","tool_input_delta","tool_input_end","om_status"]),tl=(E)=>!el.has(E);function yo(E){let _={type:E.type};switch(E.type){case"message_start":case"message_update":case"message_end":_.role=E.message.role,_.text=Qe(E.message);break;case"tool_start":case"tool_approval_required":_.tool=E.toolName,_.toolCallId=E.toolCallId;break;case"tool_end":if(_.toolCallId=E.toolCallId,_.isError=E.isError,E.denied===!0)_.denied=!0;break;case"usage_update":{_.totalTokens=E.usage.totalTokens;let I=nt(E.usage);if(I!==void 0)_.costUsd=I;break}case"subagent_start":_.agentType=E.agentType,_.task=E.task;break;case"subagent_end":_.agentType=E.agentType,_.isError=E.isError,_.durationMs=E.durationMs;break;case"agent_end":_.reason=E.reason??"complete";break;case"error":_.message=E.error?.message??String(E.error);break;default:break}return JSON.stringify(_)}async function nl(E,_){try{let I=E.thread,C=I?.getId?.();if(!C||!I?.list||!I.rename)return;if((await I.list()).find((A)=>A.id===C)?.title?.trim())return;let T=_.replace(/\s+/g," ").trim().slice(0,60);if(T)await I.rename({title:T})}catch{}}async function xo(E){let _=E.write??((P)=>process.stdout.write(P)),I=E.writeError??((P)=>process.stderr.write(P)),C="",R=null,T="complete",A=new Set;await new Promise((P)=>{let N=E.session.subscribe((M)=>{if(E.json&&tl(M.type)){let O="message"in M?M.message.id:void 0;if(O&&M.type==="message_update"&&!A.has(O))A.add(O),_(`${yo({...M,type:"message_start"})}
47
+ `);if(O&&M.type==="message_start"){if(A.has(O))return;A.add(O)}_(`${yo(M)}
48
+ `)}if(M.type==="tool_approval_required"){let O=On({toolName:M.toolName,yolo:E.yolo===!0});E.session.respondToToolApproval({decision:O.decision,toolCallId:M.toolCallId,...O.reason?{declineContext:{reason:O.reason}}:{}});return}if(M.type==="message_end"){if(M.message.role!=="user")C=Qe(M.message);return}if(M.type==="error"){R=M.error?.message??String(M.error);return}if(M.type==="agent_end")T=M.reason??"complete",N(),P()});nl(E.session,E.prompt),E.session.sendMessage({content:E.prompt}).catch((M)=>{R=M instanceof Error?M.message:String(M),N(),P()})});let k=T==="complete"&&R===null;if(!E.json){if(C)_(`${C}
49
+ `);if(R)I(`${R}
50
+ `);else if(!k)I(`the turn ended ${T}
51
+ `)}return{text:C,exitCode:k?0:1}}import{appendFileSync as rl,mkdirSync as ol}from"node:fs";import{homedir as sl}from"node:os";import{dirname as il,join as bo}from"node:path";var al=["log","info","warn","error","debug","trace"];function ll(E=process.env){let _=E.HLIX_CONFIG_HOME??bo(E.HOME??sl(),".hlix");return bo(_,"code","hlix-code.log")}var cl={log:"notes",info:"notes",debug:"notes",trace:"notes",warn:"warnings",error:"errors"};function dl(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 Bt(E=process.env,_=console){let I=ll(E),C=new Set,R=[],T={notes:0,warnings:0,errors:0},A=new Map,k=(N,M)=>{let O=`${new Date().toISOString()} ${N} ${M}`;R.push(O);try{ol(il(I),{recursive:!0}),rl(I,`${O}
52
+ `,"utf8")}catch{}};for(let N of al)A.set(N,_[N]),_[N]=(...M)=>{let O=M.map(dl).join(" ");if(C.has(`${N}:${O}`))return;C.add(`${N}:${O}`),T[cl[N]]+=1,k(N,O)};let P=!1;return{path:I,counts:T,note:(N)=>k("hlix",N),tail:(N)=>R.slice(Math.max(0,R.length-N)),restore:()=>{if(P)return;P=!0;for(let[N,M]of A)_[N]=M}}}function So(E){let _=[];if(E.counts.errors>0)_.push(`${E.counts.errors} error${E.counts.errors===1?"":"s"}`);if(E.counts.warnings>0)_.push(`${E.counts.warnings} warning${E.counts.warnings===1?"":"s"}`);if(E.counts.notes>0)_.push(`${E.counts.notes} note${E.counts.notes===1?"":"s"}`);if(_.length===0)return"";return`log: ${_.join(" · ")} from this session's libraries — /log to read them`}import{MCPClient as pl}from"@mastra/mcp";var Gt={tools:{},statusLines:[],summary:"",connected:[],failed:[],stop:async()=>{}};function ul(E,_){let I={},C=[];for(let R of E){if("command"in R.config){I[R.name]={command:R.config.command,...R.config.args?{args:R.config.args}:{},...R.config.env?{env:R.config.env}:{},stderr:"ignore",cwd:_};continue}try{I[R.name]={url:new URL(R.config.url),...R.config.headers?{requestInit:{headers:R.config.headers}}:{}}}catch{C.push({name:R.name,reason:"not a valid url"})}}return{servers:I,skipped:C}}function ml(E,_){let I={};for(let C of _)I[C]=0;for(let C of E){let R=_.filter((T)=>C.startsWith(`${T}_`)).sort((T,A)=>A.length-T.length)[0];if(R)I[R]=(I[R]??0)+1}return I}var it=(E,_)=>`${E} ${_}${E===1?"":"s"}`;async function Wt(E){if(E.servers.length===0)return Gt;let{servers:_,skipped:I}=ul(E.servers,E.cwd),C=Object.keys(_),R=E.timeoutMs??20000,T=[...I];if(C.length===0)return st({failed:T});let A;try{A=(E.client??((U)=>new pl(U)))({id:`hlix-code:${E.cwd}`,servers:_,timeout:R})}catch(F){for(let U of C)T.push({name:U,reason:vo(F)});return st({failed:T})}let k={},P={};try{let F=await A.listToolsWithErrors({perServerTimeoutMs:R});k=F.tools,P=F.errors}catch(F){for(let U of C)T.push({name:U,reason:vo(F)});return await A.disconnect().catch(()=>{}),st({failed:T})}for(let[F,U]of Object.entries(P))T.push({name:F,reason:U});let N=ml(Object.keys(k),C),M=C.filter((F)=>!(F in P)).map((F)=>({name:F,tools:N[F]??0})),O=!1;return st({tools:k,connected:M,failed:T,stop:async()=>{if(O)return;O=!0,await A.disconnect().catch(()=>{})}})}function st(E){let _=E.connected??[],I=E.failed??[],C=E.tools??{},R=_.length===0?I.length>0?`mcp: ${it(I.length,"server")} unreachable`:"":`mcp: ${it(_.length,"server")} · ${it(_.reduce((T,A)=>T+A.tools,0),"tool")}${I.length>0?` · ${I.length} unreachable`:""}`;return{tools:C,connected:_,failed:I,summary:R,statusLines:gl(_,I),stop:E.stop??(async()=>{})}}var vo=(E)=>E instanceof Error?E.message:String(E);function gl(E,_){return[...E.map((I)=>`✓ ${I.name} — ${it(I.tools,"tool")}`),..._.map((I)=>`✗ ${I.name} — ${I.reason}`)]}var xl="run `hlix auth login`",bl=["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(`
53
+ `);function Sl(E){if(!E||E.entries.length===0)return"";let _=E.entries.length,I=new Set(E.entries.map((C)=>C.source)).size;return`secrets: ${_} ${_===1?"entry":"entries"} (${I} ${I===1?"source":"sources"})`}async function vl(E,_){try{return await o(process.env,{cwd:E,flags:{}}).secrets.listEntries(_)}catch{return null}}function wl(E){let{values:_,positionals:I}=yl({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"}}}),C=typeof _.sandbox==="string"?_.sandbox:_.local===!0?"local":void 0,R=typeof _.print==="string"?_.print:void 0,T=R===void 0?void 0:[R,...I].filter((A)=>A!=="").join(" ");return{...C?{sandbox:C,sandboxSource:"flag"}:{},...typeof _["docker-image"]==="string"?{dockerImage:_["docker-image"]}:{},...typeof _.harness==="string"?{harness:_.harness}:{},...typeof _.project==="string"?{project:_.project}:{},...T!==void 0?{print:T}:{},..._.json===!0?{json:!0}:{},..._.yolo===!0||_["allow-writes"]===!0?{yolo:!0}:{},cwd:hl(typeof _.cwd==="string"?_.cwd:".")}}function El(E){let _=Object.keys(Ie),C=E.sandbox==="cloud"?_:_.filter((P)=>E.installed(P)),R=["hlix",...C],T=_.filter((P)=>!C.includes(P)),A=E.requested.harness;if(A==="hlix"||C.includes(A))return{harness:E.requested,available:R,unavailable:T,refusal:null,warning:null};let k=pt(Ie[A]);if(E.requested.source==="flag")return{harness:E.requested,available:R,unavailable:T,refusal:k,warning:null};return{harness:{harness:"hlix",source:"default"},available:R,unavailable:T,refusal:null,warning:`${k} Falling back to harness hlix.`}}async function Eo(E,_){try{let C=await o(process.env,{cwd:E,flags:{}}).modelConfig.resolvedProjectHarness(_);return{harness:C.harness,source:C.source}}catch{return null}}async function _l(E,_){let I=_.skills&&_.skills.length>0?{skills:_.skills}:{};if(E.choice!=="cloud")return ht(E,{cwd:_.cwd,...I});if(!_.projectId)throw new e("invalid_usage","The cloud sandbox needs a hlix project. Run `hlix init`, pass --project <id>, or choose --sandbox docker|local.");let R=o(process.env,{cwd:_.cwd,flags:{}}).projects.workspace(_.projectId);return ht(E,{cwd:_.cwd,projectId:_.projectId,remote:R})}var Yt=".hlix";function Il(E,_,I=(C)=>{try{return fl(C)}catch{return C}}){let C=new Set,R=[];for(let T of E.skills){if(T.scope!=="project")continue;let A=_o(_,T.path);if(A===""||A.startsWith(".."))continue;let k=I(T.path);if(C.has(k))continue;C.add(k),R.push(A)}return R}function Cl(E,_){let I=[];if(E.global)I.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(`
54
+ `));if(E.project)I.push([`# This project's rules (${_o(_,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(`
55
+ `));return I.join(`
56
+
57
+ `)}var Rl={boot:Jn,app:ho,headless:xo,mcp:Wt,log:Bt,stdio:{get stdinIsTty(){return process.stdin.isTTY===!0},get stdoutIsTty(){return process.stdout.isTTY===!0}}};function Tl(E){if(E.flag===!0)return!0;return y(E.configured)===!0}function kl(E){if(E.print)return null;if(E.stdinIsTty&&E.stdoutIsTty)return null;return`${ae} needs a terminal. Run \`hlix -p "<prompt>"\` for one turn without a screen, or start \`hlix\` in a terminal.`}function Al(E,_){let I=E?.mode?.get;if(typeof I!=="function")return _;let C=I.call(E.mode);return typeof C==="string"&&C!==""?C:_}async function $g(E,_=Rl){let I=wl(E),C=kl({print:I.print!==void 0,stdinIsTty:_.stdio?.stdinIsTty??!0,stdoutIsTty:_.stdio?.stdoutIsTty??!0});if(C)return process.stderr.write(`error: ${C}
58
+ `),2;let R=d(I.cwd,process.env),T=I.project??R.merged.projectId,A=I.print===void 0?(_.log??Bt)(process.env):null,k=f(I.cwd,c(process.env),{configDir:Yt}),P=m({cwd:I.cwd,configDir:Yt,env:process.env}),N=new ft({root:I.cwd,already:[P.project?.path,P.global?.path].filter((V)=>V!==void 0)}),M=new xt(Tl({...I.yolo!==void 0?{flag:I.yolo}:{},...R.merged.yolo!==void 0?{configured:R.merged.yolo}:{}})),O,F,U;try{if(F=kn({flag:I.sandbox??R.merged.sandbox,flagSource:I.sandbox?"flag":"config",projectId:T,dockerImage:I.dockerImage??R.merged.dockerImage,dockerAvailable:()=>Pn()}),U=El({requested:qt({...I.harness?{flag:I.harness}:{},...R.merged.harness?{configured:R.merged.harness}:{},...R.sources.harness?{configSource:R.sources.harness}:{}}),sandbox:F.choice,installed:(V)=>zt(Ie[V].command)}),U.refusal)throw new e("invalid_usage",U.refusal);O=await _l(F,{cwd:I.cwd,projectId:T,...F.choice==="cloud"?{}:{skills:Il(k,I.cwd)}})}catch(V){return A?.restore(),process.stderr.write(`error: ${V instanceof Error?V.message:String(V)}
59
+ `),2}if(U.warning)process.stderr.write(`warning: ${U.warning}
60
+ `);if(F.choice==="cloud"){let V=T?await Eo(I.cwd,T):null;if(V&&I.harness&&I.harness!==V.harness)process.stderr.write(`warning: this project runs ${V.harness}. Run \`/harness ${I.harness}\` to make ${I.harness} the project's setting.
61
+ `);U={...U,harness:V??{harness:"unknown",source:T?"the project's setting could not be read":"no project bound"}}}let q=await ln({cwd:I.cwd,env:process.env}),K=an({cwd:I.cwd,env:process.env,...q.served?{models:q.served.map((V)=>V.id)}:{}}),Y=cn({endpoint:K,cloud:F.choice==="cloud",...R.merged.model?{configured:R.merged.model}:{},...R.sources.model?{configuredSource:R.sources.model}:{}});if(Y?.notice)process.stderr.write(`warning: ${Y.notice}
62
+ `);if(!K)return A?.restore(),process.stderr.write(`error: no hlix credential for this folder — ${xl}.
63
+ `),2;let te=Be(l(R.merged.memoryTokens)??Ue),se=An(F),ie=x(k),he=v(P,I.cwd),ne=T?Sl(await vl(I.cwd,T)):"",Q=I.print===void 0?await(_.mcp??Wt)({servers:k.mcpServers,cwd:I.cwd}):Gt,me=b(k.generatedCommands,I.cwd),Ee=S(k.instructions,I.cwd),ke=Cl(P,I.cwd),De=[...w.flatMap((V)=>[wo(I.cwd,".claude",V),wo(I.cwd,Yt,V)]),...k.commands.map((V)=>V.path),...me?[me]:[]],at=U.harness.harness==="unknown"?"hlix":U.harness.harness,Z;try{Z=await _.boot({cwd:I.cwd,env:process.env,sandbox:F.choice,workspace:O,endpoint:K,...T?{projectId:T}:{},model:Y,harness:at,harnessFromFlag:U.harness.source==="flag",unavailableHarnesses:U.unavailable,...R.global?.providers?{providers:R.global.providers}:{},...R.merged.memoryTokens?{memoryTokens:R.merged.memoryTokens}:{},hostInstructions:[bl,...F.choice==="cloud"?[Xt(U.harness.harness)]:[],...ke?[ke]:[],...Ee?[Ee]:[]].join(`
64
+
65
+ `),mcpTools:Q.tools,projectSubagents:k.subagents,nestedRules:N,extraTools:{...en({cwd:I.cwd}),hlix_tasks_follow:nn({cwd:I.cwd}),hlix_harness:Qt({sandbox:F.choice,sandboxLine:se,available:U.available,modesBuilt:!1,session:()=>null})}})}catch(V){if(A?.restore(),await Q.stop(),V instanceof We)return process.stderr.write(`error: ${V.message}
66
+ `),2;return process.stderr.write(`error: ${ae} could not start: ${V instanceof Error?V.message:String(V)}
67
+ `),2}try{if(I.print!==void 0)return(await _.headless({session:Z.session,prompt:I.print,...I.json?{json:!0}:{},...M.get()?{yolo:!0}:{}})).exitCode;let V={session:Z.session,compact:async()=>{let le=Z.session.thread.getId();if(!le)return"Nothing to condense yet.";let D=await Z.memory.omEngine;if(!D)return"Observational memory is not running in this session.";return(await D.observe({threadId:le,resourceId:Z.scope.resourceId})).observed?"Condensed.":"Nothing new to condense."},facts:{sandbox:F.choice,sandboxLine:se,harness:String(U.harness.harness),availableHarnesses:U.available,harnessModesBuilt:Z.harnessModesBuilt},memory:{legacyResourceId:Z.scope.legacyResourceId,root:Z.scope.root},...A?{log:{path:A.path,tail:A.tail}}:{},rules:()=>g(P,I.cwd,process.env,N.loaded()),mcp:()=>Q.statusLines,yolo:{get:()=>M.get(),set:(le)=>M.set(le)},...T?{setProjectHarness:async(le)=>{await o(process.env,{cwd:I.cwd,flags:{}}).modelConfig.setProjectHarness(T,le)},clearProjectHarness:async()=>{await o(process.env,{cwd:I.cwd,flags:{}}).modelConfig.clearProjectHarness(T);let D=await Eo(I.cwd,T);return D?ct(D):null}}:{}},_e=ao({env:process.env,promptFiles:De,shell:V}),$e=Nt({...q.served?{served:q.served}:{},userModelIds:Z.gateway.modelIds(),providerName:K.name});return await _.app({session:Z.session,cwd:I.cwd,env:process.env,commands:_e,models:$e,bindings:V,yolo:M,notices:Pl({rules:he,standards:ie,memory:fn(Z.scope,(await Z.session.thread.list().catch(()=>[])).length),secrets:ne,mcp:Q.summary,subagents:Z.subagentLine,subagentsSkipped:Z.subagentsSkipped,log:A?So(A):""}),facts:{sandbox:se.replace(/^sandbox: /,""),harness:ct(U.harness),mode:Al(Z.session,ve),...Y?{model:Nl(Y,$e)}:{},workspace:K.workspaceId,context:{used:0,total:0},memory:hn("",te).replace(/^ · /,""),...M.get()?{yolo:!0}:{},...q.warning?{warning:q.warning}:{}}}),0}finally{await Q.stop(),await Z.dispose(),A?.restore()}}function Pl(E){return[E.rules,E.standards,E.memory,E.mcp,E.subagents,...E.subagentsSkipped.map((_)=>`subagent not loaded: ${_}`),E.secrets,E.log].filter((_)=>_!=="")}function Nl(E,_){return _.find((I)=>I.id===E.id)?.label??E.id}export{$g as runHlixCode};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var s="@hlix/cli",i="0.5.5",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
+ var s="@hlix/cli",i="0.5.6",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.5",
3
+ "version": "0.5.6",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "Hlix Code and the hlix control-plane CLI.",
6
6
  "keywords": [
@@ -253,6 +253,16 @@ never a shell.
253
253
  pushes; if only cloud changed it pulls; if both changed it exits with
254
254
  `conflict`.
255
255
 
256
+ A folder bound with `hlix init --project <id>` has no local base revision. If
257
+ the project already has cloud files, `hlix pull` brings them down and becomes
258
+ that base. If it has none — a project created in the dashboard — `hlix push`
259
+ (or `hlix sync`) uploads the folder as revision 1 and builds the project's
260
+ Coding Workspace from it. Only a project with no revision at all can be
261
+ bootstrapped that way: a second bootstrap push exits `conflict`, and so does a
262
+ folder with no base whose project does have a revision (pull first). `hlix
263
+ pull` on a project with no cloud files exits `not_found` and names the way
264
+ forward.
265
+
256
266
  `push`, `pull` and `sync` accept `--dry-run`: it prints the divergence — each
257
267
  side's generation, and how many files are local-only, cloud-only or differing —
258
268
  takes no action, and reports the verdict the real command would reach. A dry run