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