hejaz-ai-cli 1.0.1 → 1.0.2

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 +1 -1
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -81,7 +81,7 @@ ${u}`,o=`${u||""}${o}
81
81
  `;let a=Q=>{console.log(o),Sg.exit(typeof Q=="number"?Q:2)},g=()=>{console.log(typeof e.version=="string"?e.version:A.version),Sg.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||u0(f);let C=ah(i,{exclude:["--",/^\w$/]}),p={...C};s0(C,e);for(let Q of Object.values(e.flags)){if(Array.isArray(Q.aliases))for(let R of Q.aliases)delete C[R];delete C[Q.shortFlag]}return a0(e.flags,C,f),{input:f,flags:C,unnormalizedFlags:p,pkg:A,help:o,showHelp:a,showVersion:g}},l0=(e,t={})=>{let A=n0(e,t),i=i0(A),o=ax(A,i);return Sg.title=o.pkg.bin?Object.keys(o.pkg.bin).at(0):o.pkg.name,o};import{existsSync as Bo,mkdirSync as lx,readFileSync as cx,writeFileSync as gx}from"node:fs";import{homedir as fx}from"node:os";import{join as ho}from"node:path";var vg={api_key:"",base_url:"http://localhost:8080",tenant_id:"",default_model:"gemini-3-flash-preview",timeout:30,max_retries:3},c0={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(fx(),".hejaz"),Gu=ho(oi,"config.json"),g0=ho(oi,"permissions.json"),f0=ho(oi,"mcp_servers.json"),Ex=ho(oi,"sessions");function xg(e){Bo(e)||lx(e,{recursive:!0})}function Ix(e,t){try{if(Bo(e))return JSON.parse(cx(e,"utf-8"))}catch{}return t}function _u(e,t){xg(oi),gx(e,JSON.stringify(t,null,2)+`
82
82
  `,"utf-8")}function E0(){return{...vg,...Ix(Gu,{})}}function Cx(e){_u(Gu,e)}function I0(e){let A={...E0(),...e};return Cx(A),A}function C0(){return xg(oi),xg(Ex),Bo(Gu)||_u(Gu,vg),Bo(g0)||_u(g0,c0),Bo(f0)||_u(f0,[]),E0()}var it=fe(Pe(),1);var si=fe(Pe(),1);function Bx({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:Q}=f;(0,si.useEffect)(()=>{C(d=>{if(!A||!u)return d;let S=e||"";return d.cursorOffset>S.length-1?{cursorOffset:S.length,cursorWidth:0}:d})},[e,A,u]);let R=o?Q:0,b=i?i.repeat(e.length):e,v=b,D=t?Ge.grey(t):void 0;if(u&&A){D=t.length>0?Ge.inverse(t[0])+Ge.grey(t.slice(1)):Ge.inverse(" "),v=b.length>0?"":Ge.inverse(" ");let d=0;for(let S of b)v+=d>=p-R&&d<=p?Ge.inverse(S):S,d++;b.length>0&&p===b.length&&(v+=Ge.inverse(" "))}return go((d,S)=>{if(S.upArrow||S.downArrow||S.ctrl&&d==="c"||S.tab||S.shift&&S.tab)return;if(S.return){g&&g(e);return}let P=p,T=e,X=0;S.leftArrow?u&&P--:S.rightArrow?u&&P++:S.backspace||S.delete?p>0&&(T=e.slice(0,p-1)+e.slice(p,e.length),P--):(T=e.slice(0,p)+d+e.slice(p,e.length),P+=d.length,d.length>1&&(X=d.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(he,null,t?b.length>0?v:D:v)}var B0=Bx;var jt={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 dx}from"node:crypto";var Mu=class{async*parse(t){let A=t.getReader(),i=new TextDecoder,o="",u=null,a=[];try{for(;;){let{done:g,value:f}=await A.read();if(g)break;o+=i.decode(f,{stream:!0});let C=o.split(`
83
83
  `);o=C.pop()??"";for(let p of C){let Q=p.replace(/\r$/,"");if(!Q){if(a.length>0){let R=this.flush(u,a);R&&(yield R)}u=null,a=[];continue}Q.startsWith("data:")?a.push(Q.slice(5).trimStart()):Q.startsWith("event:")&&(u=Q.slice(6).trim())}}if(a.length>0){let g=this.flush(u,a);g&&(yield g)}}finally{A.releaseLock()}}flush(t,A){let i=A.join(`
84
- `);if(i.trim()==="[DONE]")return{eventType:jt.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;return{eventType:u,data:typeof g=="object"&&g!==null?g:{value:g},timestamp:Number(a)}}};var hx=new Set([429,502,503,504]),px="1.0.0",Ou=class{config;sseParser=new Mu;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/${px}`,"X-Request-Id":dx()};return this.config.user_id&&(t["X-User-Id"]=this.config.user_id),t}baseUrl(){return this.config.base_url.replace(/\/$/,"")}backoffMs(t){return Math.min(500*2**(t-1),3e4)}async request(t,A,i){let o=`${this.baseUrl()}${A}`,u=this.getHeaders(),a=this.config.max_retries+1;for(let g=1;g<=a;g++){let f=new AbortController,C=setTimeout(()=>f.abort(),this.config.timeout*1e3);try{let p=await fetch(o,{method:t,headers:u,body:i?JSON.stringify(i):void 0,signal:f.signal});if(p.ok)return await p.json();if(hx.has(p.status)&&g<a){let R=p.headers.get("Retry-After"),b=R?parseFloat(R)*1e3:this.backoffMs(g);await new Promise(v=>setTimeout(v,b));continue}let Q=await p.text();throw new Error(`HTTP ${p.status}: ${Q||p.statusText}`)}catch(p){if(p.name==="AbortError"){if(g<a){await new Promise(Q=>setTimeout(Q,this.backoffMs(g)));continue}throw new Error(`Request timed out after ${this.config.timeout}s`)}if(g>=a)throw p;await new Promise(Q=>setTimeout(Q,this.backoffMs(g)))}finally{clearTimeout(C)}}}async*streamSSE(t,A){let i=`${this.baseUrl()}${t}`,o=this.getHeaders();o.Accept="text/event-stream";let u=await fetch(i,{method:"POST",headers:o,body:JSON.stringify(A)});if(!u.ok){let a=await u.text();throw new Error(`SSE HTTP ${u.status}: ${a||u.statusText}`)}if(!u.body)throw new Error("No response body for SSE stream");for await(let a of this.sseParser.parse(u.body))if(yield a,a.eventType==="done")return}};function d0(e,t,A){let i={message:e,stream:t,model_id:A.modelId??"gemini-3-flash-preview",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 h0(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"/help":return{handled:!0,output:Qx};case"/model":return u[0]?{handled:!0,output:`Model switched to: ${u[0]}`,stateUpdates:{model:u[0]}}:{handled:!0,output:`Current model: ${t.model}
84
+ `);if(i.trim()==="[DONE]")return{eventType:jt.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)}}};var hx=new Set([429,502,503,504]),px="1.0.0",Ou=class{config;sseParser=new Mu;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/${px}`,"X-Request-Id":dx()};return this.config.user_id&&(t["X-User-Id"]=this.config.user_id),t}baseUrl(){return this.config.base_url.replace(/\/$/,"")}backoffMs(t){return Math.min(500*2**(t-1),3e4)}async request(t,A,i){let o=`${this.baseUrl()}${A}`,u=this.getHeaders(),a=this.config.max_retries+1;for(let g=1;g<=a;g++){let f=new AbortController,C=setTimeout(()=>f.abort(),this.config.timeout*1e3);try{let p=await fetch(o,{method:t,headers:u,body:i?JSON.stringify(i):void 0,signal:f.signal});if(p.ok)return await p.json();if(hx.has(p.status)&&g<a){let R=p.headers.get("Retry-After"),b=R?parseFloat(R)*1e3:this.backoffMs(g);await new Promise(v=>setTimeout(v,b));continue}let Q=await p.text();throw new Error(`HTTP ${p.status}: ${Q||p.statusText}`)}catch(p){if(p.name==="AbortError"){if(g<a){await new Promise(Q=>setTimeout(Q,this.backoffMs(g)));continue}throw new Error(`Request timed out after ${this.config.timeout}s`)}if(g>=a)throw p;await new Promise(Q=>setTimeout(Q,this.backoffMs(g)))}finally{clearTimeout(C)}}}async*streamSSE(t,A){let i=`${this.baseUrl()}${t}`,o=this.getHeaders();o.Accept="text/event-stream";let u=await fetch(i,{method:"POST",headers:o,body:JSON.stringify(A)});if(!u.ok){let a=await u.text();throw new Error(`SSE HTTP ${u.status}: ${a||u.statusText}`)}if(!u.body)throw new Error("No response body for SSE stream");for await(let a of this.sseParser.parse(u.body))if(yield a,a.eventType==="done")return}};function d0(e,t,A){let i={message:e,stream:t,model_id:A.modelId??"gemini-3-flash-preview",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 h0(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"/help":return{handled:!0,output:Qx};case"/model":return u[0]?{handled:!0,output:`Model switched to: ${u[0]}`,stateUpdates:{model:u[0]}}:{handled:!0,output:`Current model: ${t.model}
85
85
  Usage: /model <model-name>`};case"/kb":if(u.length>0){let a=u.join(" ").split(",").map(g=>g.trim()).filter(Boolean);return{handled:!0,output:`Knowledge bases bound: ${a.join(", ")}`,stateUpdates:{kbDatasetIds:a}}}return{handled:!0,output:t.kbDatasetIds.length?`Current KBs: ${t.kbDatasetIds.join(", ")}
86
86
  Usage: /kb id1, id2`:`No knowledge bases bound.
87
87
  Usage: /kb islamic-knowledge, sales`};case"/session":return u[0]==="new"?{handled:!0,output:"New session started.",stateUpdates:{sessionId:void 0},action:"clear"}:{handled:!0,output:t.sessionId?`Current session: ${t.sessionId}`:"No active session (created on first message)."};case"/config":return{handled:!0,output:["Current configuration:",` Model: ${t.model}`,` Base URL: ${t.baseUrl}`,` KB: ${t.kbDatasetIds.join(", ")||"none"}`,` Session: ${t.sessionId??"none"}`,"","Edit: ~/.hejaz/config.json"].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hejaz-ai-cli",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
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": {