hejaz-ai-cli 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +7 -7
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -78,9 +78,9 @@ ${o}`),hg(A);let{description:u}=e;!u&&u!==!1&&({description:u}=A),u&&=o?Bg(`
78
78
  ${u}
79
79
  `,e.helpIndent):`
80
80
  ${u}`,o=`${u||""}${o}
81
- `;let a=D=>{console.log(o),xg.exit(typeof D=="number"?D:2)},g=()=>{console.log(typeof e.version=="string"?e.version:A.version),xg.exit(0)};i._.length===0&&e.argv.length===1&&(i.version===!0&&e.autoVersion?g():i.help===!0&&e.autoHelp&&a(0));let f=i._;delete i._,e.allowUnknownFlags||g0(f);let C=fh(i,{exclude:["--",/^\w$/]}),p={...C};c0(C,e);for(let D of Object.values(e.flags)){if(Array.isArray(D.aliases))for(let N of D.aliases)delete C[N];delete C[D.shortFlag]}return f0(e.flags,C,f),{input:f,flags:C,unnormalizedFlags:p,pkg:A,help:o,showHelp:a,showVersion:g}},E0=(e,t={})=>{let A=u0(e,t),i=a0(A),o=yx(A,i);return xg.title=o.pkg.bin?Object.keys(o.pkg.bin).at(0):o.pkg.name,o};import{existsSync as Bo,mkdirSync as wx,readFileSync as Fx,writeFileSync as Sx}from"node:fs";import{homedir as vx}from"node:os";import{join as ho}from"node:path";var Ng={api_key:"",base_url:"http://localhost:8080",tenant_id:"",default_model:"qwen3.5-plus",timeout:30,max_retries:3},I0={allowed_dirs:[],blocked_patterns:["*.env","*.key","*.pem","*.p12",".git/objects/**"],auto_approve:["read_file","glob","grep","list_dir","tree"],require_confirm:["write_file","edit_file","bash"]};var oi=ho(vx(),".hejaz"),Mu=ho(oi,"config.json"),C0=ho(oi,"permissions.json"),d0=ho(oi,"mcp_servers.json"),xx=ho(oi,"sessions");function Rg(e){Bo(e)||wx(e,{recursive:!0})}function Nx(e,t){try{if(Bo(e))return JSON.parse(Fx(e,"utf-8"))}catch{}return t}function Gu(e,t){Rg(oi),Sx(e,JSON.stringify(t,null,2)+`
82
- `,"utf-8")}function B0(){return{...Ng,...Nx(Mu,{})}}function Rx(e){Gu(Mu,e)}function h0(e){let A={...B0(),...e};return Rx(A),A}function p0(){return Rg(oi),Rg(xx),Bo(Mu)||Gu(Mu,Ng),Bo(C0)||Gu(C0,I0),Bo(d0)||Gu(d0,[]),B0()}var it=pe(Je(),1);var si=pe(Je(),1);function Lx({value:e,placeholder:t="",focus:A=!0,mask:i,highlightPastedText:o=!1,showCursor:u=!0,onChange:a,onSubmit:g}){let[f,C]=(0,si.useState)({cursorOffset:(e||"").length,cursorWidth:0}),{cursorOffset:p,cursorWidth:D}=f;(0,si.useEffect)(()=>{C(B=>{if(!A||!u)return B;let v=e||"";return B.cursorOffset>v.length-1?{cursorOffset:v.length,cursorWidth:0}:B})},[e,A,u]);let N=o?D:0,b=i?i.repeat(e.length):e,F=b,Q=t?Me.grey(t):void 0;if(u&&A){Q=t.length>0?Me.inverse(t[0])+Me.grey(t.slice(1)):Me.inverse(" "),F=b.length>0?"":Me.inverse(" ");let B=0;for(let v of b)F+=B>=p-N&&B<=p?Me.inverse(v):v,B++;b.length>0&&p===b.length&&(F+=Me.inverse(" "))}return go((B,v)=>{if(v.upArrow||v.downArrow||v.ctrl&&B==="c"||v.tab||v.shift&&v.tab)return;if(v.return){g&&g(e);return}let P=p,T=e,X=0;v.leftArrow?u&&P--:v.rightArrow?u&&P++:v.backspace||v.delete?p>0&&(T=e.slice(0,p-1)+e.slice(p,e.length),P--):(T=e.slice(0,p)+B+e.slice(p,e.length),P+=B.length,B.length>1&&(X=B.length)),p<0&&(P=0),p>e.length&&(P=e.length),C({cursorOffset:P,cursorWidth:X}),T!==e&&a(T)},{isActive:A}),si.default.createElement(Ce,null,t?b.length>0?F:Q:F)}var Q0=Lx;var bt={STARTED:"started",STATUS:"status",TEXT_DELTA:"text_delta",THINKING_DELTA:"thinking_delta",THINKING_END:"thinking_end",USAGE:"usage",FINISH:"finish",DONE:"done",ERROR:"error",CONTEXT_RETRIEVED:"context_retrieved",WEB_SEARCH_RESULTS:"web_search_results",FILE_PROCESSED:"file_processed",RAG_EVALUATION:"rag_evaluation",CACHE_METRICS:"cache_metrics",SESSION_CREATED:"session_created",SESSION_UPDATED:"session_updated",OUTPUT_WARNINGS:"output_warnings",RUN_STARTED:"run_started",RUN_FINISHED:"run_finished",RUN_ERROR:"run_error",CANCELLED:"cancelled",STEP_STARTED:"step_started",STEP_FINISHED:"step_finished",TOOL_CALL_START:"tool_call_start",TOOL_CALL_ARGS:"tool_call_args",TOOL_CALL_END:"tool_call_end",TOOL_CALL_RESULT:"tool_call_result",TOOL_ERROR:"tool_error",TOOL_CALL:"tool_call",TOOL_RESULT:"tool_result",TASK_PLANNING:"task_planning",WORKING_MEMORY_UPDATE:"working_memory_update",MEMORY_LOADED:"memory_loaded",FILE_CREATING:"file_creating",FILE_CREATED:"file_created",ARTIFACT_CREATED:"artifact_created",OUTLINE_READY:"outline_ready",SEARCH_STARTED:"search_started",SEARCH_PROGRESS:"search_progress",SEARCH_COMPLETED:"search_completed",CODE_EXECUTION_START:"code_execution_start",CODE_EXECUTION_OUTPUT:"code_execution_output",CODE_EXECUTION_RESULT:"code_execution_result",IMAGE_GENERATION_START:"image_generation_start",IMAGE_GENERATION_RESULT:"image_generation_result",DOCUMENT_GENERATION_START:"document_generation_start",DOCUMENT_GENERATION_RESULT:"document_generation_result",PHASE_STARTED:"phase_started",PHASE_COMPLETED:"phase_completed",PHASE_PROGRESS:"phase_progress",CONTEXT_BUDGET:"context_budget",CONTEXT_COMPACTED:"context_compacted",QUEUE_STATE:"queue_state",APPROVAL_REQUIRED:"approval_required",APPROVAL_RESULT:"approval_result",GATEWAY_DECISION:"gateway_decision",QUIZ_STATUS:"quiz:status",QUIZ_READY:"quiz:ready",QUIZ_ERROR:"quiz:error",SUBAGENT_STARTED:"subagent_started",SUBAGENT_STEP:"subagent_step",SUBAGENT_TEXT_DELTA:"subagent_text_delta",SUBAGENT_TOOL_START:"subagent_tool_start",SUBAGENT_TOOL_RESULT:"subagent_tool_result",SUBAGENT_FINISHED:"subagent_finished",TEXT_MESSAGE_START:"text_message_start",TEXT_MESSAGE_CONTENT:"text_message_content",TEXT_MESSAGE_END:"text_message_end",STATE_SNAPSHOT:"state_snapshot",STATE_DELTA:"state_delta",MESSAGES_SNAPSHOT:"messages_snapshot",RAW_EVENT:"raw_event",CUSTOM_EVENT:"custom_event"};import{randomUUID as kx}from"node:crypto";import{request as bx}from"node:https";import{request as _x}from"node:http";var Gx="1.0.3",Ou=class{config;constructor(t){this.config=t}getHeaders(){let t={"Content-Type":"application/json","X-API-Key":this.config.api_key,"X-Tenant-Id":this.config.tenant_id,"X-SDK-Version":`cli/${Gx}`,"X-Request-Id":kx()};return this.config.user_id&&(t["X-User-Id"]=this.config.user_id),t}baseUrl(){return this.config.base_url.replace(/\/$/,"")}async request(t,A,i){let o=`${this.baseUrl()}${A}`,u=this.getHeaders(),a=await fetch(o,{method:t,headers:u,body:i?JSON.stringify(i):void 0});if(a.ok)return a.json();let g=await a.text();throw new Error(`HTTP ${a.status}: ${g||a.statusText}`)}async*streamSSE(t,A){let i=new URL(t,this.baseUrl()),o=this.getHeaders();o.Accept="text/event-stream";let u=JSON.stringify(A);o["Content-Length"]=String(Buffer.byteLength(u));let a=i.protocol==="https:"?bx:_x,g=await new Promise((D,N)=>{let b=a(i,{method:"POST",headers:o},F=>{if(F.statusCode&&F.statusCode>=400){let Q="";F.on("data",B=>Q+=B),F.on("end",()=>N(new Error(`SSE HTTP ${F.statusCode}: ${Q||F.statusMessage}`)));return}D(F)});b.on("error",N),b.write(u),b.end()}),f="",C=null,p=[];for await(let D of g){f+=typeof D=="string"?D:D.toString("utf-8");let N=f.split(`
83
- `);f=N.pop()??"";for(let b of N){let F=b.replace(/\r$/,"");if(!F){if(p.length>0){let Q=this.flush(C,p);if(Q&&(yield Q,Q.eventType===bt.DONE))return}C=null,p=[];continue}F.startsWith("data:")?p.push(F.slice(5).trimStart()):F.startsWith("event:")&&(C=F.slice(6).trim())}}if(p.length>0){let D=this.flush(C,p);D&&(yield D)}}flush(t,A){let i=A.join(`
81
+ `;let a=D=>{console.log(o),xg.exit(typeof D=="number"?D:2)},g=()=>{console.log(typeof e.version=="string"?e.version:A.version),xg.exit(0)};i._.length===0&&e.argv.length===1&&(i.version===!0&&e.autoVersion?g():i.help===!0&&e.autoHelp&&a(0));let f=i._;delete i._,e.allowUnknownFlags||g0(f);let C=fh(i,{exclude:["--",/^\w$/]}),p={...C};c0(C,e);for(let D of Object.values(e.flags)){if(Array.isArray(D.aliases))for(let N of D.aliases)delete C[N];delete C[D.shortFlag]}return f0(e.flags,C,f),{input:f,flags:C,unnormalizedFlags:p,pkg:A,help:o,showHelp:a,showVersion:g}},E0=(e,t={})=>{let A=u0(e,t),i=a0(A),o=yx(A,i);return xg.title=o.pkg.bin?Object.keys(o.pkg.bin).at(0):o.pkg.name,o};import{existsSync as Bo,mkdirSync as wx,readFileSync as Fx,writeFileSync as Sx}from"node:fs";import{homedir as vx}from"node:os";import{join as ho}from"node:path";var Ng={api_key:"",base_url:"http://localhost:8080",tenant_id:"",default_model:"qwen3.5-plus",timeout:30,max_retries:3},I0={allowed_dirs:[],blocked_patterns:["*.env","*.key","*.pem","*.p12",".git/objects/**"],auto_approve:["read_file","glob","grep","list_dir","tree"],require_confirm:["write_file","edit_file","bash"]};var oi=ho(vx(),".hejaz"),Mu=ho(oi,"config.json"),C0=ho(oi,"permissions.json"),d0=ho(oi,"mcp_servers.json"),xx=ho(oi,"sessions");function Rg(e){Bo(e)||wx(e,{recursive:!0,mode:448})}function Nx(e,t){try{if(Bo(e))return JSON.parse(Fx(e,"utf-8"))}catch{}return t}function Gu(e,t){Rg(oi),Sx(e,JSON.stringify(t,null,2)+`
82
+ `,{encoding:"utf-8",mode:384})}function B0(){return{...Ng,...Nx(Mu,{})}}function Rx(e){Gu(Mu,e)}function h0(e){let A={...B0(),...e};return Rx(A),A}function p0(){return Rg(oi),Rg(xx),Bo(Mu)||Gu(Mu,Ng),Bo(C0)||Gu(C0,I0),Bo(d0)||Gu(d0,[]),B0()}var it=pe(Je(),1);var si=pe(Je(),1);function Lx({value:e,placeholder:t="",focus:A=!0,mask:i,highlightPastedText:o=!1,showCursor:u=!0,onChange:a,onSubmit:g}){let[f,C]=(0,si.useState)({cursorOffset:(e||"").length,cursorWidth:0}),{cursorOffset:p,cursorWidth:D}=f;(0,si.useEffect)(()=>{C(B=>{if(!A||!u)return B;let v=e||"";return B.cursorOffset>v.length-1?{cursorOffset:v.length,cursorWidth:0}:B})},[e,A,u]);let N=o?D:0,b=i?i.repeat(e.length):e,F=b,Q=t?Me.grey(t):void 0;if(u&&A){Q=t.length>0?Me.inverse(t[0])+Me.grey(t.slice(1)):Me.inverse(" "),F=b.length>0?"":Me.inverse(" ");let B=0;for(let v of b)F+=B>=p-N&&B<=p?Me.inverse(v):v,B++;b.length>0&&p===b.length&&(F+=Me.inverse(" "))}return go((B,v)=>{if(v.upArrow||v.downArrow||v.ctrl&&B==="c"||v.tab||v.shift&&v.tab)return;if(v.return){g&&g(e);return}let P=p,T=e,X=0;v.leftArrow?u&&P--:v.rightArrow?u&&P++:v.backspace||v.delete?p>0&&(T=e.slice(0,p-1)+e.slice(p,e.length),P--):(T=e.slice(0,p)+B+e.slice(p,e.length),P+=B.length,B.length>1&&(X=B.length)),p<0&&(P=0),p>e.length&&(P=e.length),C({cursorOffset:P,cursorWidth:X}),T!==e&&a(T)},{isActive:A}),si.default.createElement(Ce,null,t?b.length>0?F:Q:F)}var Q0=Lx;var bt={STARTED:"started",STATUS:"status",TEXT_DELTA:"text_delta",THINKING_DELTA:"thinking_delta",THINKING_END:"thinking_end",USAGE:"usage",FINISH:"finish",DONE:"done",ERROR:"error",CONTEXT_RETRIEVED:"context_retrieved",WEB_SEARCH_RESULTS:"web_search_results",FILE_PROCESSED:"file_processed",RAG_EVALUATION:"rag_evaluation",CACHE_METRICS:"cache_metrics",SESSION_CREATED:"session_created",SESSION_UPDATED:"session_updated",OUTPUT_WARNINGS:"output_warnings",RUN_STARTED:"run_started",RUN_FINISHED:"run_finished",RUN_ERROR:"run_error",CANCELLED:"cancelled",STEP_STARTED:"step_started",STEP_FINISHED:"step_finished",TOOL_CALL_START:"tool_call_start",TOOL_CALL_ARGS:"tool_call_args",TOOL_CALL_END:"tool_call_end",TOOL_CALL_RESULT:"tool_call_result",TOOL_ERROR:"tool_error",TOOL_CALL:"tool_call",TOOL_RESULT:"tool_result",TASK_PLANNING:"task_planning",WORKING_MEMORY_UPDATE:"working_memory_update",MEMORY_LOADED:"memory_loaded",FILE_CREATING:"file_creating",FILE_CREATED:"file_created",ARTIFACT_CREATED:"artifact_created",OUTLINE_READY:"outline_ready",SEARCH_STARTED:"search_started",SEARCH_PROGRESS:"search_progress",SEARCH_COMPLETED:"search_completed",CODE_EXECUTION_START:"code_execution_start",CODE_EXECUTION_OUTPUT:"code_execution_output",CODE_EXECUTION_RESULT:"code_execution_result",IMAGE_GENERATION_START:"image_generation_start",IMAGE_GENERATION_RESULT:"image_generation_result",DOCUMENT_GENERATION_START:"document_generation_start",DOCUMENT_GENERATION_RESULT:"document_generation_result",PHASE_STARTED:"phase_started",PHASE_COMPLETED:"phase_completed",PHASE_PROGRESS:"phase_progress",CONTEXT_BUDGET:"context_budget",CONTEXT_COMPACTED:"context_compacted",QUEUE_STATE:"queue_state",APPROVAL_REQUIRED:"approval_required",APPROVAL_RESULT:"approval_result",GATEWAY_DECISION:"gateway_decision",QUIZ_STATUS:"quiz:status",QUIZ_READY:"quiz:ready",QUIZ_ERROR:"quiz:error",SUBAGENT_STARTED:"subagent_started",SUBAGENT_STEP:"subagent_step",SUBAGENT_TEXT_DELTA:"subagent_text_delta",SUBAGENT_TOOL_START:"subagent_tool_start",SUBAGENT_TOOL_RESULT:"subagent_tool_result",SUBAGENT_FINISHED:"subagent_finished",TEXT_MESSAGE_START:"text_message_start",TEXT_MESSAGE_CONTENT:"text_message_content",TEXT_MESSAGE_END:"text_message_end",STATE_SNAPSHOT:"state_snapshot",STATE_DELTA:"state_delta",MESSAGES_SNAPSHOT:"messages_snapshot",RAW_EVENT:"raw_event",CUSTOM_EVENT:"custom_event"};import{randomUUID as kx}from"node:crypto";import{request as bx}from"node:https";import{request as _x}from"node:http";var Gx="1.0.3",Ou=class{config;constructor(t){this.config=t}getHeaders(){let t={"Content-Type":"application/json","X-API-Key":this.config.api_key,"X-Tenant-Id":this.config.tenant_id,"X-SDK-Version":`cli/${Gx}`,"X-Request-Id":kx()};return this.config.user_id&&(t["X-User-Id"]=this.config.user_id),t}baseUrl(){return this.config.base_url.replace(/\/$/,"")}async request(t,A,i){let o=`${this.baseUrl()}${A}`,u=this.getHeaders(),a=await fetch(o,{method:t,headers:u,body:i?JSON.stringify(i):void 0});if(a.ok)return a.json();let g=await a.text();throw new Error(`HTTP ${a.status}: ${g||a.statusText}`)}async*streamSSE(t,A){let i=new URL(t,this.baseUrl()),o=this.getHeaders();o.Accept="text/event-stream";let u=JSON.stringify(A);o["Content-Length"]=String(Buffer.byteLength(u));let a=i.protocol==="https:"?bx:_x,g=await new Promise((D,N)=>{let b=a(i,{method:"POST",headers:o},F=>{if(F.statusCode&&F.statusCode>=400){let Q="";F.on("data",B=>Q+=B),F.on("end",()=>N(new Error(`SSE HTTP ${F.statusCode}: ${Q||F.statusMessage}`)));return}D(F)});b.on("error",N),b.write(u),b.end()}),f="",C=null,p=[];try{for await(let D of g){f+=typeof D=="string"?D:D.toString("utf-8");let N=f.split(`
83
+ `);f=N.pop()??"";for(let b of N){let F=b.replace(/\r$/,"");if(!F){if(p.length>0){let Q=this.flush(C,p);if(Q&&(yield Q,Q.eventType===bt.DONE))return}C=null,p=[];continue}F.startsWith("data:")?p.push(F[5]===" "?F.slice(6):F.slice(5)):F.startsWith("event:")&&(C=F.slice(6).trim())}}if(p.length>0){let D=this.flush(C,p);D&&(yield D)}}finally{g.destroy()}}flush(t,A){let i=A.join(`
84
84
  `);if(i.trim()==="[DONE]")return{eventType:bt.DONE,data:{},timestamp:Date.now()/1e3};let o;try{o=JSON.parse(i)}catch{o={raw:i}}let u=t??o.event_type??o.event??"message";delete o.event_type,delete o.event;let a=o.timestamp??Date.now()/1e3;delete o.timestamp;let g=o.data!==void 0?o.data:o,f;return typeof g=="string"?f={content:g}:typeof g=="object"&&g!==null?f=g:f={value:g},{eventType:u,data:f,timestamp:Number(a)}}};function D0(e,t,A){let i={message:e,stream:t,model_id:A.modelId??"qwen3.5-plus",temperature:A.temperature??.7};return A.sessionId&&(i.session_id=A.sessionId),A.maxTokens&&(i.max_tokens=A.maxTokens),A.systemPrompt&&(i.system_prompt=A.systemPrompt),A.kbDatasetIds?.length&&(i.kb_dataset_ids=A.kbDatasetIds),A.webSearchEnabled&&(i.web_search_enabled=!0),A.executionProfile&&(i.execution_profile=A.executionProfile),A.osAgentEnabled&&(i.os_agent_enabled=!0),i}var Uu=class{client;constructor(t){this.client=t}async send(t,A={}){return this.client.request("POST","/api/v1/assistant/chat",D0(t,!1,A))}async*stream(t,A={}){yield*this.client.streamSSE("/api/v1/assistant/chat/stream",D0(t,!0,A))}};function m0(e,t){let A=e.trim();if(!A.startsWith("/"))return{handled:!1};let i=A.split(/\s+/),o=i[0].toLowerCase(),u=i.slice(1);switch(o){case"/exit":case"/quit":case"/q":return{handled:!0,action:"exit"};case"/clear":return{handled:!0,action:"clear"};case"/new":return{handled:!0,action:"new",stateUpdates:{sessionId:void 0}};case"/compact":return t.sessionId?{handled:!0,action:"compact"}:{handled:!0,output:"No active session to compact."};case"/memory":return u.length===0?{handled:!0,output:`Usage:
85
85
  /memory <note> Save a memory
86
86
  /memory list Show all memories
@@ -104,7 +104,7 @@ Examples:
104
104
  /skill enable <name> \u2014 Enable a skill
105
105
  /skill disable <name> \u2014 Disable a skill
106
106
  /skill delete <name> \u2014 Delete a skill
107
- /skill test <name> <input> \u2014 Test a skill`};case"/share":return{handled:!0,output:t.sessionId?`Share: ${t.baseUrl}/share/${t.sessionId}`:"No active session to share."};case"/export":return{handled:!0,output:"Export: /export markdown | /export json (coming soon)"};default:return{handled:!1,output:`Unknown command: ${o}
107
+ /skill test <name> <input> \u2014 Test a skill`};case"/share":return{handled:!0,output:t.sessionId?`Share: ${t.baseUrl}/share/${t.sessionId}`:"No active session to share."};case"/export":return{handled:!0,output:"Export: /export markdown | /export json (coming soon)"};default:return{handled:!0,output:`Unknown command: ${o}
108
108
  Type /help for available commands.`}}}var Mx=`
109
109
  Hejaz AI CLI Commands:
110
110
 
@@ -145,8 +145,8 @@ Hejaz AI CLI Commands:
145
145
  `.trim();import{existsSync as y0,readFileSync as Ox,writeFileSync as Ux,mkdirSync as Tx}from"node:fs";import{homedir as w0}from"node:os";import{join as F0}from"node:path";var Lg=F0(w0(),".hejaz","memories.json");function S0(){try{if(y0(Lg))return JSON.parse(Ox(Lg,"utf-8"))}catch{}return[]}function v0(e){let t=S0(),A={text:e,timestamp:new Date().toISOString()};t.push(A);let i=F0(w0(),".hejaz");return y0(i)||Tx(i,{recursive:!0}),Ux(Lg,JSON.stringify(t,null,2)+`
146
146
  `,"utf-8"),A}function x0(){let e=S0();return e.length===0?`No memories saved yet.
147
147
  Usage: /memory <note>`:e.map((t,A)=>` ${A+1}. ${t.text} (${t.timestamp.slice(0,10)})`).join(`
148
- `)}import{spawn as Px}from"node:child_process";import{createInterface as Hx}from"node:readline";var Tu=class e{config;process=null;rl=null;requestId=0;initialized=!1;pending=new Map;tools=[];static PROTOCOL_VERSION="2025-11-25";static CLIENT_INFO={name:"hejaz-ai-cli",version:"1.0.0"};constructor(t){this.config=t}async connect(){let t={...process.env,...this.config.env};this.process=Px(this.config.command,this.config.args,{stdio:["pipe","pipe","pipe"],env:t}),this.rl=Hx({input:this.process.stdout}),this.rl.on("line",i=>this.handleLine(i)),this.process.on("error",i=>{this.rejectAll(new Error(`MCP server ${this.config.name} error: ${i.message}`))}),this.process.on("exit",i=>{this.rejectAll(new Error(`MCP server ${this.config.name} exited with code ${i}`))}),await this.jsonrpc("initialize",{protocolVersion:e.PROTOCOL_VERSION,capabilities:{tools:{}},clientInfo:e.CLIENT_INFO}),this.notify("notifications/initialized"),this.initialized=!0;let A=await this.jsonrpc("tools/list",{});return this.tools=(A.tools??[]).map(i=>({name:i.name,description:i.description??"",inputSchema:i.inputSchema??{},serverName:this.config.name})),this.tools}async callTool(t,A){if(!this.initialized)throw new Error("MCP client not connected");return this.jsonrpc("tools/call",{name:t,arguments:A})}async close(){this.rl?.close(),this.rl=null,this.process&&this.process.exitCode===null&&(this.process.kill("SIGTERM"),await new Promise(t=>{let A=setTimeout(()=>{this.process?.kill("SIGKILL"),t()},5e3);this.process.on("exit",()=>{clearTimeout(A),t()})})),this.rejectAll(new Error("MCP client closed")),this.initialized=!1}handleLine(t){let A=t.trim();if(!A)return;let i;try{i=JSON.parse(A)}catch{return}let o=i.id;if(o!=null&&this.pending.has(o)){let{resolve:u,reject:a}=this.pending.get(o);this.pending.delete(o),i.error?a(new Error(i.error.message??"MCP error")):u(i.result??{})}}jsonrpc(t,A){return new Promise((i,o)=>{let u=++this.requestId;this.pending.set(u,{resolve:i,reject:o});let a=JSON.stringify({jsonrpc:"2.0",id:u,method:t,params:A})+`
149
- `;this.process.stdin.write(a,g=>{g&&(this.pending.delete(u),o(g))}),setTimeout(()=>{this.pending.has(u)&&(this.pending.delete(u),o(new Error(`MCP ${this.config.name}: ${t} timed out (30s)`)))},3e4)})}notify(t,A){let i=JSON.stringify({jsonrpc:"2.0",method:t,params:A??{}})+`
148
+ `)}import{spawn as Px}from"node:child_process";import{createInterface as Hx}from"node:readline";var Tu=class e{config;process=null;rl=null;requestId=0;initialized=!1;pending=new Map;tools=[];static PROTOCOL_VERSION="2025-11-25";static CLIENT_INFO={name:"hejaz-ai-cli",version:"1.0.0"};constructor(t){this.config=t}async connect(){let t={...process.env,...this.config.env};this.process=Px(this.config.command,this.config.args,{stdio:["pipe","pipe","pipe"],env:t}),this.rl=Hx({input:this.process.stdout}),this.rl.on("line",i=>this.handleLine(i)),this.process.on("error",i=>{this.rejectAll(new Error(`MCP server ${this.config.name} error: ${i.message}`))}),this.process.on("exit",i=>{this.rejectAll(new Error(`MCP server ${this.config.name} exited with code ${i}`))}),await this.jsonrpc("initialize",{protocolVersion:e.PROTOCOL_VERSION,capabilities:{tools:{}},clientInfo:e.CLIENT_INFO}),this.notify("notifications/initialized"),this.initialized=!0;let A=await this.jsonrpc("tools/list",{});return this.tools=(A.tools??[]).map(i=>({name:i.name,description:i.description??"",inputSchema:i.inputSchema??{},serverName:this.config.name})),this.tools}async callTool(t,A){if(!this.initialized)throw new Error("MCP client not connected");return this.jsonrpc("tools/call",{name:t,arguments:A})}async close(){this.rl?.close(),this.rl=null,this.process&&this.process.exitCode===null&&(this.process.kill("SIGTERM"),await new Promise(t=>{let A=setTimeout(()=>{this.process?.kill("SIGKILL"),t()},5e3);this.process.on("exit",()=>{clearTimeout(A),t()})})),this.rejectAll(new Error("MCP client closed")),this.initialized=!1}handleLine(t){let A=t.trim();if(!A)return;let i;try{i=JSON.parse(A)}catch{return}let o=i.id;if(o!=null&&this.pending.has(o)){let{resolve:u,reject:a}=this.pending.get(o);this.pending.delete(o),i.error?a(new Error(i.error.message??"MCP error")):u(i.result??{})}}jsonrpc(t,A){return new Promise((i,o)=>{if(!this.process?.stdin?.writable){o(new Error(`MCP ${this.config.name}: process not available`));return}let u=++this.requestId;this.pending.set(u,{resolve:i,reject:o});let a=JSON.stringify({jsonrpc:"2.0",id:u,method:t,params:A})+`
149
+ `;this.process.stdin.write(a,p=>{p&&(this.pending.delete(u),o(p))});let g=setTimeout(()=>{this.pending.has(u)&&(this.pending.delete(u),o(new Error(`MCP ${this.config.name}: ${t} timed out (30s)`)))},3e4),f=i,C=o;this.pending.set(u,{resolve:p=>{clearTimeout(g),f(p)},reject:p=>{clearTimeout(g),C(p)}})})}notify(t,A){let i=JSON.stringify({jsonrpc:"2.0",method:t,params:A??{}})+`
150
150
  `;this.process?.stdin?.write(i)}rejectAll(t){for(let{reject:A}of this.pending.values())A(t);this.pending.clear()}};var Pu=class e{clients=new Map;tools=new Map;async connect(t,A,i,o){this.clients.has(t)&&await this.disconnect(t);let u={name:t,command:A,args:i,env:o},a=new Tu(u),g=await a.connect();this.clients.set(t,a);for(let f of g){let C=e.qualify(t,f.name);this.tools.set(C,{client:a,tool:f})}return g}async callTool(t,A){let i=this.tools.get(t);if(!i)throw new Error(`Unknown MCP tool: ${t}`);return i.client.callTool(i.tool.name,A)}listTools(){return Array.from(this.tools.entries()).map(([t,{tool:A}])=>({name:t,description:A.description,server:A.serverName,inputSchema:A.inputSchema}))}async disconnect(t){if(t){let A=this.clients.get(t);if(A){await A.close(),this.clients.delete(t);for(let[i,o]of this.tools)o.client===A&&this.tools.delete(i)}}else{for(let A of this.clients.values())await A.close();this.clients.clear(),this.tools.clear()}}get servers(){return Array.from(this.clients.keys())}isConnected(t){return this.clients.has(t)}isMCPTool(t){return this.tools.has(t)}static qualify(t,A){return`mcp_${t}__${A}`}};import{readFileSync as Jx,existsSync as Kx}from"node:fs";function Wx(e,t,A,i){return`---
151
151
  name: ${e}
152
152
  title: "${t}"
@@ -194,7 +194,7 @@ ${Ee}`);break}}}catch(K){Ae(`Skill error: ${K.message}`)}g(!1),Q("");return}if(t
194
194
  ${$e}
195
195
 
196
196
  Bind with: /kb <id1>, <id2>`:"No knowledge bases found.")}catch(K){Ae(`Failed to fetch KBs: ${K.message}`)}g(!1),Q("");return}te.stateUpdates&&("model"in te.stateUpdates&&ae(te.stateUpdates.model),"kbDatasetIds"in te.stateUpdates&&Ne(te.stateUpdates.kbDatasetIds),"sessionId"in te.stateUpdates&&T(te.stateUpdates.sessionId)),te.output&&Ae(te.output);return}}function Ae(te){i(K=>[...K,{role:"system",content:te}])}i(te=>[...te,{role:"user",content:le}]),g(!0),C(""),D([]),b([]),Q("Thinking..."),Ge.current="",Te.current=[],de.current=[];try{for await(let te of CA.stream(le,{sessionId:P,modelId:X,kbDatasetIds:ye.length>0?ye:void 0,webSearchEnabled:!0}))Rt(te)}catch(te){let K=`Error: ${te.message}`;Ge.current+=(Ge.current?`
197
- `:"")+K,C(Ge.current)}let Qe=Ge.current,Et=Te.current,ct=de.current;Qe||Et.length||ct.length?i(te=>[...te,{role:"assistant",content:Qe,tools:Et.length>0?Et:void 0,agents:ct.length>0?ct:void 0}]):i(te=>[...te,{role:"system",content:"No response received. Check API key and base URL."}]),g(!1),C(""),D([]),b([]),Q("")},[a,X,ye,P,e.base_url,CA,t,kA,Rt]);return go((ue,le)=>{if(le.ctrl&&ue==="c"){t();return}if(B){if(ue==="y"||ue==="Y"){let{resolve:Ae}=B;v(null),Ae(!0)}else if(ue==="n"||ue==="N"||le.escape){let{resolve:Ae}=B;v(null),Ae(!1)}}}),(0,fe.jsxs)(Ue,{flexDirection:"column",padding:1,children:[(0,fe.jsxs)(Ue,{marginBottom:1,children:[(0,fe.jsx)(Ce,{bold:!0,color:"cyan",children:"Hejaz AI CLI v1.3.0"}),(0,fe.jsxs)(Ce,{color:"gray",children:[" ","| ",X,ye.length>0?` | KB: ${ye.join(", ")}`:"",P?` | ${P.slice(0,8)}...`:""]})]}),A.map((ue,le)=>(0,fe.jsx)(Vx,{message:ue},le)),a&&(0,fe.jsxs)(Ue,{flexDirection:"column",marginTop:1,children:[N.map((ue,le)=>(0,fe.jsx)(T0,{agent:ue},le)),p.map((ue,le)=>(0,fe.jsx)(U0,{tool:ue},le)),F&&!f&&(0,fe.jsx)(Ue,{marginLeft:2,children:(0,fe.jsx)(Ce,{color:"gray",children:F})}),f&&(0,fe.jsxs)(Ue,{children:[(0,fe.jsxs)(Ce,{color:"cyan",bold:!0,children:["AI:"," "]}),(0,fe.jsx)(Ce,{wrap:"wrap",children:f})]})]}),B&&(0,fe.jsxs)(Ue,{flexDirection:"column",marginTop:1,borderStyle:"round",borderColor:"yellow",paddingX:1,children:[(0,fe.jsx)(Ce,{color:"yellow",bold:!0,children:"Permission Required"}),(0,fe.jsx)(Ce,{color:"white",children:B.summary}),(0,fe.jsxs)(Ue,{marginTop:1,children:[(0,fe.jsx)(Ce,{color:"green",bold:!0,children:"[y]"}),(0,fe.jsx)(Ce,{children:" Approve "}),(0,fe.jsx)(Ce,{color:"red",bold:!0,children:"[n]"}),(0,fe.jsx)(Ce,{children:" Deny"})]})]}),(0,fe.jsxs)(Ue,{marginTop:1,children:[(0,fe.jsxs)(Ce,{color:"green",bold:!0,children:[">"," "]}),a?(0,fe.jsx)(Ce,{color:"gray",children:B?"Waiting for permission...":"Processing..."}):(0,fe.jsx)(Q0,{value:o,onChange:u,onSubmit:jt,placeholder:"Type a message or /help..."})]})]})}function Vx({message:e}){let{role:t,content:A,tools:i,agents:o}=e;return(0,fe.jsxs)(Ue,{flexDirection:"column",marginBottom:1,children:[(0,fe.jsxs)(Ue,{children:[t==="user"&&(0,fe.jsxs)(Ce,{color:"blue",bold:!0,children:["You:"," "]}),t==="assistant"&&(0,fe.jsxs)(Ce,{color:"cyan",bold:!0,children:["AI:"," "]}),t==="system"&&(0,fe.jsxs)(Ce,{color:"yellow",bold:!0,children:["System:"," "]}),(0,fe.jsx)(Ce,{wrap:"wrap",children:A})]}),o?.map((u,a)=>(0,fe.jsx)(T0,{agent:u,compact:!0},a)),i?.map((u,a)=>(0,fe.jsx)(U0,{tool:u,compact:!0},a))]})}function U0({tool:e,compact:t}){let A=e.status==="running"?"...":e.status==="done"?"v":e.status==="denied"?"x":"!",i=e.status==="running"?"yellow":e.status==="done"?"green":"red";return(0,fe.jsxs)(Ue,{marginLeft:t?4:2,children:[(0,fe.jsxs)(Ce,{color:i,children:[A," ",e.name]}),e.durationMs!==void 0&&(0,fe.jsxs)(Ce,{color:"gray",children:[" (",e.durationMs,"ms)"]}),e.result&&!t&&(0,fe.jsxs)(Ce,{color:"gray",children:[" \u2014 ",Qo(e.result,60)]})]})}var Zx={explore:"Search",task:"Task",plan:"Plan"};function T0({agent:e,compact:t}){let A=Zx[e.type]??e.type,i=e.status==="running"?"...":e.status==="done"?"v":"x",o=e.status==="running"?"yellow":e.status==="done"?"green":"red";return(0,fe.jsxs)(Ue,{flexDirection:"column",marginLeft:t?4:2,marginBottom:t?0:1,children:[(0,fe.jsxs)(Ue,{children:[(0,fe.jsxs)(Ce,{color:o,children:[i," "]}),(0,fe.jsx)(Ce,{color:"magenta",bold:!0,children:A}),e.description&&(0,fe.jsxs)(Ce,{color:"gray",children:[" ",e.description]}),e.durationMs!==void 0&&(0,fe.jsxs)(Ce,{color:"gray",children:[" (",(e.durationMs/1e3).toFixed(1),"s)"]})]}),!t&&e.tools.map((u,a)=>(0,fe.jsxs)(Ue,{marginLeft:4,children:[(0,fe.jsxs)(Ce,{color:u.status==="running"?"yellow":u.status==="done"?"green":"red",children:[u.status==="running"?"...":u.status==="done"?"v":"x"," ",u.name]}),u.summary&&(0,fe.jsxs)(Ce,{color:"gray",children:[" \u2014 ",Qo(u.summary,50)]})]},a)),t&&e.resultSummary&&(0,fe.jsx)(Ue,{marginLeft:4,children:(0,fe.jsx)(Ce,{color:"gray",children:Qo(e.resultSummary,80)})}),!t&&e.status==="running"&&e.streamingText&&(0,fe.jsx)(Ue,{marginLeft:4,children:(0,fe.jsx)(Ce,{color:"gray",children:Qo(e.streamingText,200)})})]})}function Qo(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}var P0=pe(po(),1),Zt=E0(`
197
+ `:"")+K,C(Ge.current)}let Qe=Ge.current,Et=Te.current,ct=de.current;Qe||Et.length||ct.length?i(te=>[...te,{role:"assistant",content:Qe,tools:Et.length>0?Et:void 0,agents:ct.length>0?ct:void 0}]):i(te=>[...te,{role:"system",content:"No response received. Check API key and base URL."}]),g(!1),C(""),D([]),b([]),Q("")},[a,X,ye,P,e.base_url,CA,t,kA,Rt]);return go((ue,le)=>{if(le.ctrl&&ue==="c"){t();return}if(B){if(ue==="y"||ue==="Y"){let{resolve:Ae}=B;v(null),Ae(!0)}else if(ue==="n"||ue==="N"||le.escape){let{resolve:Ae}=B;v(null),Ae(!1)}}}),(0,fe.jsxs)(Ue,{flexDirection:"column",padding:1,children:[(0,fe.jsxs)(Ue,{marginBottom:1,children:[(0,fe.jsx)(Ce,{bold:!0,color:"cyan",children:"Hejaz AI CLI v1.3.1"}),(0,fe.jsxs)(Ce,{color:"gray",children:[" ","| ",X,ye.length>0?` | KB: ${ye.join(", ")}`:"",P?` | ${P.slice(0,8)}...`:""]})]}),A.map((ue,le)=>(0,fe.jsx)(Vx,{message:ue},le)),a&&(0,fe.jsxs)(Ue,{flexDirection:"column",marginTop:1,children:[N.map((ue,le)=>(0,fe.jsx)(T0,{agent:ue},le)),p.map((ue,le)=>(0,fe.jsx)(U0,{tool:ue},le)),F&&!f&&(0,fe.jsx)(Ue,{marginLeft:2,children:(0,fe.jsx)(Ce,{color:"gray",children:F})}),f&&(0,fe.jsxs)(Ue,{children:[(0,fe.jsxs)(Ce,{color:"cyan",bold:!0,children:["AI:"," "]}),(0,fe.jsx)(Ce,{wrap:"wrap",children:f})]})]}),B&&(0,fe.jsxs)(Ue,{flexDirection:"column",marginTop:1,borderStyle:"round",borderColor:"yellow",paddingX:1,children:[(0,fe.jsx)(Ce,{color:"yellow",bold:!0,children:"Permission Required"}),(0,fe.jsx)(Ce,{color:"white",children:B.summary}),(0,fe.jsxs)(Ue,{marginTop:1,children:[(0,fe.jsx)(Ce,{color:"green",bold:!0,children:"[y]"}),(0,fe.jsx)(Ce,{children:" Approve "}),(0,fe.jsx)(Ce,{color:"red",bold:!0,children:"[n]"}),(0,fe.jsx)(Ce,{children:" Deny"})]})]}),(0,fe.jsxs)(Ue,{marginTop:1,children:[(0,fe.jsxs)(Ce,{color:"green",bold:!0,children:[">"," "]}),a?(0,fe.jsx)(Ce,{color:"gray",children:B?"Waiting for permission...":"Processing..."}):(0,fe.jsx)(Q0,{value:o,onChange:u,onSubmit:jt,placeholder:"Type a message or /help..."})]})]})}function Vx({message:e}){let{role:t,content:A,tools:i,agents:o}=e;return(0,fe.jsxs)(Ue,{flexDirection:"column",marginBottom:1,children:[(0,fe.jsxs)(Ue,{children:[t==="user"&&(0,fe.jsxs)(Ce,{color:"blue",bold:!0,children:["You:"," "]}),t==="assistant"&&(0,fe.jsxs)(Ce,{color:"cyan",bold:!0,children:["AI:"," "]}),t==="system"&&(0,fe.jsxs)(Ce,{color:"yellow",bold:!0,children:["System:"," "]}),(0,fe.jsx)(Ce,{wrap:"wrap",children:A})]}),o?.map((u,a)=>(0,fe.jsx)(T0,{agent:u,compact:!0},a)),i?.map((u,a)=>(0,fe.jsx)(U0,{tool:u,compact:!0},a))]})}function U0({tool:e,compact:t}){let A=e.status==="running"?"...":e.status==="done"?"v":e.status==="denied"?"x":"!",i=e.status==="running"?"yellow":e.status==="done"?"green":"red";return(0,fe.jsxs)(Ue,{marginLeft:t?4:2,children:[(0,fe.jsxs)(Ce,{color:i,children:[A," ",e.name]}),e.durationMs!==void 0&&(0,fe.jsxs)(Ce,{color:"gray",children:[" (",e.durationMs,"ms)"]}),e.result&&!t&&(0,fe.jsxs)(Ce,{color:"gray",children:[" \u2014 ",Qo(e.result,60)]})]})}var Zx={explore:"Search",task:"Task",plan:"Plan"};function T0({agent:e,compact:t}){let A=Zx[e.type]??e.type,i=e.status==="running"?"...":e.status==="done"?"v":"x",o=e.status==="running"?"yellow":e.status==="done"?"green":"red";return(0,fe.jsxs)(Ue,{flexDirection:"column",marginLeft:t?4:2,marginBottom:t?0:1,children:[(0,fe.jsxs)(Ue,{children:[(0,fe.jsxs)(Ce,{color:o,children:[i," "]}),(0,fe.jsx)(Ce,{color:"magenta",bold:!0,children:A}),e.description&&(0,fe.jsxs)(Ce,{color:"gray",children:[" ",e.description]}),e.durationMs!==void 0&&(0,fe.jsxs)(Ce,{color:"gray",children:[" (",(e.durationMs/1e3).toFixed(1),"s)"]})]}),!t&&e.tools.map((u,a)=>(0,fe.jsxs)(Ue,{marginLeft:4,children:[(0,fe.jsxs)(Ce,{color:u.status==="running"?"yellow":u.status==="done"?"green":"red",children:[u.status==="running"?"...":u.status==="done"?"v":"x"," ",u.name]}),u.summary&&(0,fe.jsxs)(Ce,{color:"gray",children:[" \u2014 ",Qo(u.summary,50)]})]},a)),t&&e.resultSummary&&(0,fe.jsx)(Ue,{marginLeft:4,children:(0,fe.jsx)(Ce,{color:"gray",children:Qo(e.resultSummary,80)})}),!t&&e.status==="running"&&e.streamingText&&(0,fe.jsx)(Ue,{marginLeft:4,children:(0,fe.jsx)(Ce,{color:"gray",children:Qo(e.streamingText,200)})})]})}function Qo(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}var P0=pe(po(),1),Zt=E0(`
198
198
  Usage
199
199
  $ hejaz [options]
200
200
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hejaz-ai-cli",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Hejaz AI CLI — Claude Code-like terminal AI assistant with OS Agent, MCP, and knowledge base integration",
5
5
  "type": "module",
6
6
  "bin": {