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