@gencode/cli 0.0.36 → 0.0.38
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/dist/bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as e,i as t,r as n,t as r}from"./program-
|
|
2
|
+
import{a as e,i as t,r as n,t as r}from"./program-A7EVfTdv.js";function i(){globalThis.getPkgPath||(globalThis.getPkgPath=()=>`@wizard/aimax`)}i();const a=Date.now(),o=process.env.AIMAX_DATA_DIR;o&&n(o),t.info(`AIMax CLI starting (pid=${process.pid})`),r().parseAsync(process.argv).catch(e=>{t.error(`Unexpected error: ${e.message}`),process.exit(1)}).finally(()=>{let n=Date.now()-a;return t.info(`AIMax CLI exited (total uptime: ${n}ms)`),e()});export{};
|
|
@@ -2,7 +2,7 @@ import{createRequire as e}from"node:module";import{Command as t}from"commander";
|
|
|
2
2
|
`)}function C(e){process.stderr.write(e+`
|
|
3
3
|
`)}function w(e){switch(e.type){case`start`:S(`\n[start] ${e.message}`);break;case`text`:_e(e.text);break;case`stream_text_delta`:_e(e.text);break;case`bootstrap`:S(`\n[bootstrap:${e.phase}] ${e.dataDir}`);break;case`session_reset`:S(`\n[session:${e.action}] ${e.message}`);break;case`tool_start`:S(`\n[tool:${e.name}] ${JSON.stringify(e.input)}`);break;case`tool_end`:S(`[tool:${e.name}] ${e.isError?`ERROR`:`OK`} ${e.output.slice(0,200)}`);break;case`compaction`:S(`\n[compaction${e.layer?`:${e.layer}`:``}] ${e.reason}${e.strategy?` (${e.strategy})`:``}`);break;case`skill_used`:S(`\n[skill] ${e.skillName} agent=${e.agent} task=${e.taskId}`);break;case`custom`:S(`\n[plugin:${e.pluginId}] ${e.name}${e.label?` ${e.label}`:``}${e.data?` ${JSON.stringify(e.data)}`:``}`);break;case`error`:C(`\n[error] ${e.message}`);break;case`diagnostic`:break;case`subagent_spawn`:S(`\n[subagent:spawn]${e.label?` "${e.label}"`:``} ${e.task}`);break;case`subagent_complete`:S(`[subagent:${e.status}] ${e.task}`);break;case`hitl_requested`:if(S(`\n[hitl:${e.request.kind}] ${e.request.title}`),S(` prompt: ${e.request.prompt}`),S(` requestId: ${e.request.requestId}`),e.request.input.mode===`choice`)for(let t of e.request.input.choices)S(` - [${t.id}] ${t.label}`);break;case`hitl_resumed`:S(`\n[hitl:resumed] requestId=${e.requestId} action=${e.resolution.action}`);break;case`hitl_expired`:S(`\n[hitl:expired] requestId=${e.requestId} reason=${e.reason}`);break;case`hitl_cancelled`:S(`\n[hitl:cancelled] requestId=${e.requestId}${e.reason?` reason=${e.reason}`:``}`);break}}function T(e,t){if(t===`json`){S(JSON.stringify(e,null,2));return}S(`
|
|
4
4
|
`),S(`session: ${e.sessionId}`),S(`duration: ${e.durationMs}ms`),S(`tokens: input=${e.usage.input} output=${e.usage.output} total=${e.usage.total}`),e.context&&(S(`context: ${e.context.snapshotPath}`),S(`tool-results: ${e.context.toolResultsDir}`)),e.error&&C(`error: ${e.error}`)}function ve(e,t){if(t===`json`){S(JSON.stringify(e,null,2));return}if(e.length===0){S(`No sessions found.`);return}for(let t of e){let e=t.createdAt?new Date(t.createdAt).toLocaleString():`unknown`;S(`${t.id} ${e} [${t.channel}] ${t.title}`)}}function ye(e,t){if(t===`json`){S(JSON.stringify(e,null,2));return}S(`session: ${e.id}`),e.metadata&&(S(`title: ${e.metadata.title}`),S(`channel: ${e.metadata.channel}`),S(`created: ${e.metadata.createdAt}`),S(`updated: ${e.metadata.updatedAt}`)),S(`transcript: ${e.transcriptPath}`),S(`entries: ${e.transcriptEntryCount}`),S(`context: ${e.contextSnapshotPath}`),S(`session-memory: ${e.sessionMemoryPath}`),S(`collapse-log: ${e.collapseLogPath}`),S(`read-states: ${e.readStateCount}`),S(`tool-results: ${e.toolResultRefCount}`),S(`tool-results-dir: ${e.toolResultsDir}`)}function be(e,t){if(t===`json`){S(JSON.stringify(e,null,2));return}S(`session: ${e.id}`),S(`transcript: ${e.paths.transcriptPath}`),S(`context: ${e.paths.contextSnapshotPath}`),S(`session-memory: ${e.paths.sessionMemoryPath}`),S(`collapse-log: ${e.paths.collapseLogPath}`),S(`tool-results-dir: ${e.paths.toolResultsDir}`),S(`transcript-entries: ${e.transcript.length}`),S(`read-states: ${e.context.readStates.length}`),S(`tool-results: ${e.context.toolResults.length}`),S(`collapse-spans: ${e.context.compaction.collapseSpans.length}`)}function xe(e,t){if(t===`json`){S(JSON.stringify(e,null,2));return}S(`Bootstrap completed.`),S(`dataDir: ${e.dataDir}`),S(`created dirs: ${e.createdDirs.length}`),S(`created files: ${e.createdFiles.length}`),S(`skipped dirs: ${e.skippedDirs.length}`),S(`skipped files: ${e.skippedFiles.length}`)}function Se(e){e.command(`bootstrap`).description(`Initialize the data directory with required directories and templates`).requiredOption(`-d, --data-dir <path>`,`Data directory path`).option(`--output <format>`,`Output format: text (default) or json`,`text`).action(async e=>{let t=e.output===`json`?`json`:`text`;try{xe(await n(e.dataDir),t)}catch(e){C(`Error bootstrapping data directory: ${e.message}`),process.exit(1)}})}function Ce(e){return oe.sm4_encrypt_ecb(e)}function E(e){return Ce(e)}function D(e={}){let t=e.baseUrl??process.env.AIMAX_BASE_URL,n=process.env.AIMAX_AUTH_TOKEN,r=e.authToken?E(e.authToken):n?E(n):e.apiKey??process.env.AIMAX_API_KEY,i=e.model??process.env.AIMAX_MODEL,a=[];if(t||a.push(`--base-url / AIMAX_BASE_URL`),r||a.push(`--api-key / AIMAX_API_KEY`),i||a.push(`--model / AIMAX_MODEL`),a.length>0)throw Error(`Missing required LLM configuration: ${a.join(`, `)}`);return{baseUrl:t,apiKey:r,model:i,contextWindow:e.contextWindow??(process.env.AIMAX_CONTEXT_WINDOW?Number(process.env.AIMAX_CONTEXT_WINDOW):void 0),flashModel:e.flashModel??process.env.AIMAX_FLASH_MODEL}}function O(e,t){return t?g.resolve(t):g.join(e,`.aimax`,`plugins.json`)}async function k(e,t){let n=O(e,t);try{let e=await _.readFile(n,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function A(e,t,n){let r=O(e,n);await _.mkdir(g.dirname(r),{recursive:!0}),await _.writeFile(r,JSON.stringify(t,null,2),`utf-8`)}function j(e){return typeof e==`object`&&!!e}function M(e){return j(e)&&e.type===`text`&&typeof e.text==`string`&&(e.textSignature===void 0||typeof e.textSignature==`string`)}function N(e){return j(e)&&e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`}function we(e){return j(e)&&e.type===`thinking`&&typeof e.thinking==`string`&&(e.thinkingSignature===void 0||typeof e.thinkingSignature==`string`)&&(e.redacted===void 0||typeof e.redacted==`boolean`)}function Te(e){return j(e)&&e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`&&j(e.arguments)&&(e.thoughtSignature===void 0||typeof e.thoughtSignature==`string`)}function Ee(e){return typeof e==`string`||Array.isArray(e)&&e.every(e=>M(e)||N(e))}function De(e){return Array.isArray(e)&&e.every(e=>M(e)||we(e)||Te(e))}function Oe(e){return j(e)&&typeof e.input==`number`&&typeof e.output==`number`&&typeof e.cacheRead==`number`&&typeof e.cacheWrite==`number`&&typeof e.totalTokens==`number`&&j(e.cost)&&typeof e.cost.input==`number`&&typeof e.cost.output==`number`&&typeof e.cost.cacheRead==`number`&&typeof e.cost.cacheWrite==`number`&&typeof e.cost.total==`number`}function ke(e){return!j(e)||typeof e.role!=`string`?!1:e.role===`user`?Ee(e.content):e.role===`assistant`?De(e.content)&&typeof e.api==`string`&&typeof e.provider==`string`&&typeof e.model==`string`&&Oe(e.usage)&&(e.stopReason===`stop`||e.stopReason===`length`||e.stopReason===`toolUse`||e.stopReason===`error`||e.stopReason===`aborted`)&&(e.errorMessage===void 0||typeof e.errorMessage==`string`):e.role===`toolResult`?typeof e.toolCallId==`string`&&typeof e.toolName==`string`&&Array.isArray(e.content)&&e.content.every(e=>M(e)||N(e))&&typeof e.isError==`boolean`:!1}async function Ae(e){let t;try{t=await _.readFile(e,`utf-8`)}catch(e){throw Error(`Failed to read message file: ${e.message}`)}let n;try{n=JSON.parse(t)}catch(e){throw Error(`Invalid JSON in message file: ${e.message}`)}let r=Array.isArray(n)?n:[n];if(r.length===0||!r.every(e=>ke(e)))throw Error(`Message file must contain one Message object or an array of Message objects`);return r}async function je(e){if(!!e.message==!!e.fromFile)throw Error(`Exactly one of --message or --from-file must be provided`);return e.fromFile?{kind:`messages`,messages:await Ae(e.fromFile)}:{kind:`text`,message:e.message}}let P=function(e){return e.INFO=`INFO`,e.ERROR=`ERROR`,e.WARN=`WARN`,e}({}),F=null;function Me(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function Ne(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Pe(e){return g.join(e,`.aimax`)}function Fe(e){return{appLogPath:g.join(e,`app.log`),errorLogPath:g.join(e,`errors.log`)}}function Ie(e){let{appLogPath:t,errorLogPath:n}=Fe(e);v.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`pattern`,pattern:`[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%p] %m`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`pattern`,pattern:`[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%p] %m`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function Le(e,t,n){process.stderr.write(`[${Me()}] [${e}] ${t}${Ne(n)}\n`)}function I(e,t,n){let r=`${t}${Ne(n)}`;if(!F){Le(e,r);return}let i=v.getLogger();if(e===P.ERROR){i.error(r);return}if(e===P.WARN){i.warn(r);return}i.info(r)}function L(e){let t=Pe(e);F?.dataDir!==e&&(se.mkdirSync(t,{recursive:!0}),Ie(t),F={dataDir:e,logDir:t})}async function Re(){await v.shutdown()}const R={info:(e,t)=>I(P.INFO,e,t),warn:(e,t)=>I(P.WARN,e,t),error:(e,t)=>I(P.ERROR,e,t)};var z=class{startTime;name;constructor(e){this.name=e,this.startTime=Date.now()}end(){let e=Date.now()-this.startTime;return R.info(`${this.name} completed in ${e}ms`),e}},B=class{constructor(e){this.sinks=e}async send(e){await Promise.allSettled(this.sinks.map(async t=>{await t.send(e)}))}async close(){await Promise.allSettled(this.sinks.map(async e=>{await e.close()}))}},V=class{constructor(e){this.url=e}async send(e){await this.post(this.toPayload(e))}async close(){}async post(e){let t=Date.now(),n=ze(e);R.info(`sending callback event`,{callbackUrl:this.url,...n});let r=await fetch(this.url,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),i=Date.now()-t;if(!r.ok)throw R.error(`callback event failed`,{callbackUrl:this.url,httpStatus:r.status,durationMs:i,...n}),Error(`Callback failed with status ${r.status}`);R.info(`callback event delivered`,{callbackUrl:this.url,httpStatus:r.status,durationMs:i,...n})}toPayload(e){switch(e.type){case`start`:return e;case`progress`:return e;case`done`:return e;case`error`:return e;case`session_reset`:return e;case`hitl`:return e;case`title_updated`:return e;default:{let t=e;throw Error(`Unsupported callback event: ${JSON.stringify(t)}`)}}}};function ze(e){return{eventType:e.type,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,user:e.user,progressType:e.type===`progress`?e.event.type:void 0}}function Be(e,t){if(t.kind===`none`)return e;let n=new URL(e);return n.searchParams.set(`authToken`,t.token),n.toString()}function H(){let e=globalThis.WebSocket;if(!e)throw Error(`WebSocket is not available in this runtime`);return e}function Ve(e){return e?{kind:`query_token`,token:e}:{kind:`none`}}function U(e,t,n){if(typeof e.once==`function`){e.once(t,n);return}if(typeof e.addEventListener==`function`&&typeof e.removeEventListener==`function`){let r=(...i)=>{e.removeEventListener?.(t,r),n(...i)};e.addEventListener(t,r);return}throw Error(`WebSocket does not support one-time listener registration for "${t}"`)}function He(e,t,n){if(typeof e.on==`function`){e.on(t,n);return}if(typeof e.addEventListener==`function`){e.addEventListener(t,n);return}throw Error(`WebSocket does not support listener registration for "${t}"`)}var W=class{socket=null;connectPromise=null;enabled=!0;textSequence=0;constructor(e,t,n){this.url=e,this.events=t,this.authToken=n}async send(e){let t=this.toEnvelope(e);if(!(!t||!this.enabled))try{await this.ensureConnected();let e=H();if(!this.socket||this.socket.readyState!==e.OPEN)return;this.socket.send(JSON.stringify(t))}catch(e){R.warn(`websocket sink disabled after send failure`,{url:this.url,error:e instanceof Error?e.message:String(e)}),this.enabled=!1}}async sendTextDelta(e){if(!this.enabled||!this.events.has(`text`))return;this.textSequence+=1;let t={type:`text`,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,user:e.user,timestamp:new Date().toISOString(),sequence:this.textSequence,delta:e.text};try{await this.ensureConnected();let e=H();if(!this.socket||this.socket.readyState!==e.OPEN)return;this.socket.send(JSON.stringify(t))}catch(e){R.warn(`websocket sink disabled after text delta send failure`,{url:this.url,error:e instanceof Error?e.message:String(e)}),this.enabled=!1}}async close(){this.enabled=!1;let e=this.socket;if(this.socket=null,this.connectPromise=null,!e)return;let t=H();e.readyState!==t.CLOSED&&await new Promise(t=>{U(e,`close`,()=>t()),e.close()})}async ensureConnected(){if(!this.enabled)return;let e=H();if(this.socket&&this.socket.readyState===e.OPEN)return;if(this.connectPromise){await this.connectPromise;return}let t=new e(Be(this.url,Ve(this.authToken)));this.connectPromise=new Promise((e,n)=>{U(t,`open`,()=>{this.socket=t,He(t,`close`,()=>{this.socket===t&&(this.socket=null)}),e()}),U(t,`error`,e=>{n(e)})});try{await this.connectPromise}finally{this.connectPromise=null}}toEnvelope(e){let t=new Date().toISOString();switch(e.type){case`start`:return this.events.has(`start`)?{...e,timestamp:t}:null;case`done`:return this.events.has(`done`)?{...e,timestamp:t}:null;case`error`:return this.events.has(`error`)?{...e,timestamp:t}:null;case`hitl`:return this.events.has(`hitl`)?{...e,timestamp:t}:null;case`title_updated`:return this.events.has(`title_updated`)?{type:`title_updated`,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,user:e.user,timestamp:t,title:e.title}:null;case`session_reset`:return null;case`progress`:return e.event.type===`text`?this.events.has(`text`)?(this.textSequence+=1,{type:`text`,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,user:e.user,timestamp:t,sequence:this.textSequence,delta:e.event.text}):null:e.event.type===`stream_text_delta`||!this.events.has(`progress`)?null:{type:`progress`,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,user:e.user,timestamp:t,event:e.event};default:{let t=e;throw Error(`Unsupported stream event: ${JSON.stringify(t)}`)}}}};const G=[`start`,`text`,`done`,`error`,`hitl`];function Ue(e){if(!e?.trim())return new Set(G);let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean),n=new Set([`start`,`text`,`progress`,`done`,`error`,`hitl`,`title_updated`]),r=new Set;for(let e of t){if(!n.has(e))throw Error(`Invalid stream event: ${e}. Must be one of start,text,progress,done,error,hitl`);r.add(e)}return r.size>0?r:new Set(G)}function We(e){let t=e.dataDir??process.env.AIMAX_DATA_DIR;if(!t)throw Error(`Data directory must be specified via --data-dir or AIMAX_DATA_DIR`);return t}function Ge(e){return e?m(e):void 0}function Ke(e){if(!e.inputJson)throw Error(`--input-json is required for resume command`);try{let t=JSON.parse(e.inputJson);return{requestId:e.requestId,sessionId:e.sessionId,action:t.action??`submit`,values:t.values,submittedBy:t.submittedBy,idempotencyKey:t.idempotencyKey,submittedAt:t.submittedAt??new Date().toISOString()}}catch(e){throw Error(`Invalid --input-json: ${e.message}`)}}async function qe(e){let t=We(e),n=e.channel??`WEB`,r=D({baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow?Number(e.contextWindow):void 0,flashModel:e.flashModel}),i=Ke(e);return{dataDir:t,channel:n,format:e.output===`json`?`json`:`text`,timeoutMs:e.timeout?Number(e.timeout):void 0,llm:r,resolution:i}}function Je(e){let t=[],n=null;return e.callbackUrl&&t.push(new V(e.callbackUrl)),e.streamUrl&&(n=new W(e.streamUrl,Ue(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new B(t),websocketSink:n}}async function Ye(e){let{dataDir:t,sessionId:n,sessionStoreName:r,toolCallId:i,resolution:a}=e;i&&await re(t,n,e=>{let t=e.findIndex(e=>e.role===`tool_result`&&e.toolCallId===i&&e.toolName===`request_approval`);if(t===-1)return e;let n=e.slice(0,t+1);return n[t]={...n[t],content:s(a),isError:!1},n},{storeName:r})}async function Xe(e){L(We(e));let t=new z(`resume command`),n=null;try{let r=await qe(e),i=Ge(e.sessionStore);R.info(`resume command started`,{sessionId:e.sessionId,requestId:e.requestId,channel:r.channel,dataDir:r.dataDir});let a=await te(r.dataDir,e.sessionId,{storeName:i});if(!a)throw Error(`No pending HITL request found for session "${e.sessionId}"`);if(a.request.requestId!==e.requestId)throw Error(`Request ID mismatch: pending is "${a.request.requestId}", got "${e.requestId}"`);if(a.status===`expired`)throw Error(`HITL request has expired`);if(a.status===`cancelled`)throw Error(`HITL request has been cancelled`);let o=await h({dataDir:r.dataDir,sessionStoreName:i,sessionId:e.sessionId,requestId:e.requestId,resolution:r.resolution}),s=o.state;if(!s)throw Error(`Resolved HITL state was not persisted`);let c=Ze(r.resolution,s.request.kind);await Ye({dataDir:r.dataDir,sessionId:e.sessionId,sessionStoreName:i,toolCallId:s.toolContext?.toolCallId,resolution:r.resolution});let l=Je(e);n=l.sink;let u=e.sessionId,d=async t=>{if(u=t.sessionId??u,!ae(t)){if(t.type===`stream_text_delta`){r.format===`text`&&w(t),await l.websocketSink?.sendTextDelta({sessionId:u,channel:r.channel,messageId:e.messageId,user:e.user,text:t.text});return}if(r.format===`text`&&w(t),t.type===`hitl_resumed`){await n?.send({sessionId:u,channel:r.channel,messageId:e.messageId,user:e.user,type:`progress`,event:t});return}if(t.type===`start`){await n?.send({sessionId:u,channel:r.channel,messageId:e.messageId,user:e.user,type:`start`,message:t.message});return}await n?.send({sessionId:u,channel:r.channel,messageId:e.messageId,user:e.user,type:`progress`,event:t})}};await d({type:`hitl_resumed`,requestId:e.requestId,resolution:r.resolution,sessionId:e.sessionId}),`idempotentReplay`in o&&o.idempotentReplay&&(R.info(`resume command treated as idempotent replay`,{sessionId:e.sessionId,requestId:e.requestId,idempotencyKey:r.resolution.idempotencyKey}),T({sessionId:e.sessionId,text:`Resume request already processed.`,usage:{input:0,output:0,total:0},durationMs:0},r.format),t.end(),process.exit(0));let ee=e.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,f=await k(r.dataDir,ee),p;try{p=await ie({dataDir:r.dataDir,sessionStoreName:i,sessionId:e.sessionId,messageId:e.messageId,channel:r.channel,llm:r.llm,timeoutMs:r.timeoutMs,message:c,hitlResume:{request:s.request,resolution:r.resolution,checkpoint:s.checkpoint,toolContext:s.toolContext},plugins:f?{config:f,dataDir:r.dataDir,workspaceDir:g.join(r.dataDir,`workspace`),bundledDir:process.env.AIMAX_PLUGINS_BUNDLED_DIR,llmAllowlist:f.llmAllowlist}:void 0,onProgress:d})}finally{}p.error?await n?.send({sessionId:p.sessionId,channel:r.channel,messageId:e.messageId,user:e.user,type:`error`,message:p.error}):await n?.send({sessionId:p.sessionId,channel:r.channel,messageId:e.messageId,user:e.user,type:`done`,result:{text:p.text,usage:p.usage,durationMs:p.durationMs,error:p.error,paused:p.paused}}),T(p,r.format),p.error?R.error(`resume command failed: ${p.error}`):R.info(`resume command succeeded`),t.end(),process.exit(p.error?1:0)}catch(r){let i=r;n&&(i.message.includes(`expired`)&&await n.send({sessionId:e.sessionId,channel:e.channel??`WEB`,messageId:e.messageId,user:e.user,type:`progress`,event:{type:`hitl_expired`,sessionId:e.sessionId,requestId:e.requestId,reason:i.message}}),i.message.includes(`cancelled`)&&await n.send({sessionId:e.sessionId,channel:e.channel??`WEB`,messageId:e.messageId,user:e.user,type:`progress`,event:{type:`hitl_cancelled`,sessionId:e.sessionId,requestId:e.requestId,reason:i.message}}),await n.send({sessionId:e.sessionId,channel:e.channel??`WEB`,messageId:e.messageId,user:e.user,type:`error`,message:`Resume failed: ${i.message}`})),R.error(`resume command error: ${i.message}`),C(`Fatal: ${i.message}`),t.end(),process.exit(1)}finally{await n?.close()}}function Ze(e,t){return r(e,t)}function Qe(e){e.command(`resume`).description(`Resume a paused HITL session with user input`).requiredOption(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).requiredOption(`-s, --session-id <id>`,`Session ID to resume`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).requiredOption(`--request-id <id>`,`HITL request ID to resolve`).requiredOption(`--input-json <json>`,`JSON string with the resolution (action, values, etc.)`).option(`--message-id <id>`,`Message ID for correlating events`).option(`--user <id>`,`User identifier propagated to external callback and stream payloads`).option(`-c, --channel <channel>`,`Channel name (default: WEB)`,`WEB`).option(`--base-url <url>`,`LLM API base URL (overrides AIMAX_BASE_URL)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY)`).option(`--auth-token <token>`,`Auth token used to generate the API key`).option(`--model <name>`,`LLM model name (overrides AIMAX_MODEL)`).option(`--context-window <n>`,`LLM context window size`).option(`--callback-url <url>`,`HTTP callback URL for progress events`).option(`--stream-url <url>`,`WebSocket URL for streaming text events`).option(`--stream-auth-token <token>`,`Auth token for WebSocket streaming`).option(`--stream-events <list>`,`Comma-separated stream events`).option(`--timeout <ms>`,`Execution timeout in milliseconds`).option(`--output <format>`,`Output format: text (default) or json`,`text`).option(`--plugins-config <path>`,`Plugins config file path`).action(async e=>{await Xe(e)})}const $e=[`start`,`text`,`done`,`error`];function et(e){if(!e?.trim())return new Set($e);let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean),n=new Set([`start`,`text`,`progress`,`done`,`error`,`hitl`,`title_updated`]),r=new Set;for(let e of t){if(!n.has(e))throw Error(`Invalid stream event: ${e}. Must be one of start,text,progress,done,error,hitl,title_updated`);r.add(e)}return r.size>0?r:new Set($e)}function tt(e){let t=e.dataDir??process.env.AIMAX_DATA_DIR;if(!t)throw Error(`Data directory must be specified via --data-dir option or AIMAX_DATA_DIR environment variable`);return t}function nt(e){return e??`WEB`}function rt(e){return e?m(e):void 0}function it(e,t){return e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`}function at(e,t,n=78){let r=n-2,i=r-2,a=e?` ${it(e,Math.max(0,i-2))} `:``,o=e?`┌${a}${`─`.repeat(Math.max(0,r-a.length))}┐`:`┌${`─`.repeat(r)}┐`,s=`└${`─`.repeat(r)}┘`;return[o,...t.map(e=>`│ ${it(e,i).padEnd(i,` `)} │`),s].join(`
|
|
5
|
-
`)}function ot(e){return e.kind===`text`?`inline message (${e.message.length} chars)`:`message file (${e.messages.length} messages)`}function st(e,t){let n=rt(e.sessionStore)??`sessions`,r=t.timeoutMs===void 0?`default`:`${t.timeoutMs}`,i=e.callbackUrl?`enabled`:`disabled`,a=e.streamUrl?`enabled`:`disabled`,o=ot(t.input),s=t.input.kind===`text`?`inline`:e.fromFile??`file
|
|
5
|
+
`)}function ot(e){return e.kind===`text`?`inline message (${e.message.length} chars)`:`message file (${e.messages.length} messages)`}function st(e,t){let n=rt(e.sessionStore)??`sessions`,r=t.timeoutMs===void 0?`default`:`${t.timeoutMs}`,i=e.callbackUrl?`enabled`:`disabled`,a=e.streamUrl?`enabled`:`disabled`,o=ot(t.input),s=t.input.kind===`text`?`inline`:e.fromFile??`file`,c=new Date().toISOString();return{banner:at(void 0,[`AIMax CLI`,`Stateless Agent Runner`]),contextBox:at(`Run Context`,[`time : ${c}`,`channel : ${t.channel}`,`user : ${e.user??`-`}`,`sessionId : ${e.sessionId??`new`}`,`sessionStore : ${n}`,`messageId : ${e.messageId??`-`}`,`dataDir : ${t.dataDir}`,`workspace : ${g.join(t.dataDir,`workspace`)}`,`output : ${t.format}`,`callback : ${i}`,`websocket : ${a}`,`timeoutMs : ${r}`,`input : ${o}`]),logContext:{time:c,channel:t.channel,user:e.user,dataDir:t.dataDir,workspaceDir:g.join(t.dataDir,`workspace`),sessionId:e.sessionId??`new`,sessionStore:n,messageId:e.messageId,output:t.format,hasCallback:!!e.callbackUrl,hasStream:!!e.streamUrl,timeoutMs:t.timeoutMs,inputKind:t.input.kind,inputSource:s,inputSummary:o}}}async function ct(e){let t=tt(e),n=nt(e.channel),r=D({baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow?Number(e.contextWindow):void 0,flashModel:e.flashModel}),i=await je({message:e.message,fromFile:e.fromFile});return{dataDir:t,channel:n,format:e.output===`json`?`json`:`text`,timeoutMs:e.timeout?Number(e.timeout):void 0,llm:r,input:i}}function lt(e){let t=[],n=null;return e.callbackUrl&&t.push(new V(e.callbackUrl)),e.streamUrl&&(n=new W(e.streamUrl,et(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new B(t),websocketSink:n}}async function K(e,t){R.info(`dispatching external event`,Et(t)),await e.sink.send(t)}function ut(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e)){if(r===null||typeof r==`string`||typeof r==`number`||typeof r==`boolean`){t[n]=r;continue}if(r instanceof Error){t[n]=`${r.name}: ${r.message}`;continue}t[n]=JSON.stringify(r)}return t}function dt(e){let t={sessionId:e.sessionId,messageId:e.messageId,parentSessionId:e.parentSessionId,depth:e.depth,scope:e.scope,phase:e.phase,...ut(e.details)};if(e.level===`error`){R.error(e.message,t);return}if(e.level===`warn`){R.warn(e.message,t);return}R.info(e.message,t)}function ft(e,t,n,r,i){return{sink:e,websocketSink:t,channel:n,defaultMessageId:r,user:i}}function pt(){let e=new AbortController,t=()=>e.abort();return process.once(`SIGTERM`,t),process.once(`SIGINT`,t),{controller:e,cleanup:()=>{process.off(`SIGTERM`,t),process.off(`SIGINT`,t)}}}function mt(e){return{activeSessionId:e??`pending`,finalResult:null}}function ht(e,t){e.activeSessionId=t.sessionId??e.activeSessionId}function gt(e,t){return e.messageId??t}async function _t(e,t,n){if(!await c(e.dataDir)){if(await q(t,e.format,n.activeSessionId,e.dataDir,`checking`),(await a(e.dataDir)).performedBootstrap){await q(t,e.format,n.activeSessionId,e.dataDir,`initializing`),await q(t,e.format,n.activeSessionId,e.dataDir,`initialized`);return}await q(t,e.format,n.activeSessionId,e.dataDir,`ready`)}}async function q(e,t,n,r,i){let a={type:`bootstrap`,phase:i,dataDir:r};t===`text`&&w(a),await K(e,{sessionId:n,channel:e.channel,messageId:e.defaultMessageId,user:e.user,type:`progress`,event:a})}function vt(e,t,n){return async r=>{if(ht(n,r),ae(r)){dt(r);return}if(r.type===`stream_text_delta`){e.format===`text`&&w(r),await t.websocketSink?.sendTextDelta({sessionId:n.activeSessionId,channel:e.channel,messageId:gt(r,t.defaultMessageId),user:t.user,text:r.text});return}e.format===`text`&&w(r);let i=gt(r,t.defaultMessageId);if(r.type===`hitl_requested`){await K(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`hitl`,request:r.request}),await K(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`progress`,event:r});return}if(r.type===`start`){await K(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`start`,message:r.message});return}if(r.type===`session_reset`){await K(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`session_reset`,action:r.action,previousSessionId:r.previousSessionId,message:r.message});return}await K(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`progress`,event:r})}}function yt(e,t,n,r,i){let a={dataDir:t.dataDir,sessionStoreName:rt(e.sessionStore),sessionId:e.sessionId,messageId:e.messageId,channel:t.channel,llm:t.llm,timeoutMs:t.timeoutMs,abortSignal:n.signal,plugins:i?{config:i,dataDir:t.dataDir,workspaceDir:g.join(t.dataDir,`workspace`),bundledDir:process.env.AIMAX_PLUGINS_BUNDLED_DIR,llmAllowlist:i.llmAllowlist}:void 0,onProgress:r};return t.input.kind===`messages`?{...a,messages:t.input.messages}:{...a,message:t.input.message}}async function bt(e,t,n,r){if(t.activeSessionId=r.sessionId,t.finalResult=r,r.error){await K(e,{sessionId:r.sessionId,channel:e.channel,messageId:n,user:e.user,type:`error`,message:r.error});return}await K(e,{sessionId:r.sessionId,channel:e.channel,messageId:n,user:e.user,type:`done`,result:{text:r.text,usage:r.usage,durationMs:r.durationMs,error:r.error,paused:r.paused}})}async function xt(e,t,n,r){await K(e,{sessionId:t.finalResult?.sessionId??t.activeSessionId,channel:e.channel,messageId:n,user:e.user,type:`error`,message:`Fatal: ${r.message}`})}function St(e,t){let n=st(e,t);R.info([`run command started`,n.banner,n.contextBox].join(`
|
|
6
6
|
`),n.logContext),t.format===`text`&&(S(n.banner),S(``),S(n.contextBox),S(``))}function Ct(e,t,n){T(t,n),t.error?R.error(`run command failed: ${t.error}`):R.info(`run command succeeded`),e.end(),process.exit(t.error?1:0)}function wt(e,t){R.error(`run command error: ${t.message}`),C(`Fatal: ${t.message}`),e.end(),process.exit(1)}async function Tt(e){if(e.resumeRequestId||e.resumeInputJson){if(!e.sessionId||!e.resumeRequestId||!e.resumeInputJson)throw Error(`--session-id, --resume-request-id and --resume-input-json must be provided together`);await Xe({dataDir:e.dataDir,sessionId:e.sessionId,sessionStore:e.sessionStore,requestId:e.resumeRequestId,inputJson:e.resumeInputJson,channel:e.channel,baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow,flashModel:e.flashModel,callbackUrl:e.callbackUrl,streamUrl:e.streamUrl,streamAuthToken:e.streamAuthToken,streamEvents:e.streamEvents,timeout:e.timeout,output:e.output,pluginsConfig:e.pluginsConfig,messageId:e.messageId,user:e.user});return}L(tt(e));let t=new z(`run command`),{controller:n,cleanup:r}=pt(),i=null,a=e.channel??`WEB`,o=mt(e.sessionId);try{let r=await ct(e);a=r.channel,St(e,r);let s=lt(e);i=s.sink,R.info(`external sink configured`,{callbackUrl:e.callbackUrl,streamUrl:e.streamUrl,streamEvents:e.streamEvents});let c=ft(i,s.websocketSink,r.channel,e.messageId,e.user);await _t(r,c,o);let l=e.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,u=await k(r.dataDir,l),d=await ie(yt(e,r,n,vt(r,c,o),u));await bt(c,o,e.messageId,d),Ct(t,d,r.format)}catch(n){let r=n;i&&await xt(ft(i,null,a,e.messageId,e.user),o,e.messageId,r),wt(t,r)}finally{await i?.close(),r()}}function Et(e){return{eventType:e.type,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,user:e.user,progressType:e.type===`progress`?e.event.type:void 0,textLength:e.type===`done`?e.result.text.length:void 0,hasError:e.type===`error`?!0:e.type===`done`?!!e.result.error:void 0}}function Dt(e){e.command(`run`).description(`Run an agent task`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).option(`--user <id>`,`User identifier propagated to external callback and stream payloads`).option(`--message <text>`,`User message to send to the agent`).option(`--from-file <path>`,`Load structured Message JSON from a file`).option(`-s, --session-id <id>`,`Resume an existing session by ID`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).option(`--message-id <id>`,`Message ID for correlating events`).option(`-c, --channel <channel>`,`Channel name (default: WEB)`,`WEB`).option(`--base-url <url>`,`LLM API base URL (overrides AIMAX_BASE_URL)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY)`).option(`--auth-token <token>`,`Auth token used to generate the API key (highest priority)`).option(`--model <name>`,`LLM model name (overrides AIMAX_MODEL)`).option(`--context-window <n>`,`LLM context window size`).option(`--flash-model <name>`,`Flash model for lightweight tasks like title generation (overrides AIMAX_FLASH_MODEL)`).option(`--callback-url <url>`,`HTTP callback URL for progress events`).option(`--stream-url <url>`,`WebSocket URL for streaming text events`).option(`--stream-auth-token <token>`,`Auth token for WebSocket streaming`).option(`--stream-events <list>`,`Comma-separated stream events: start,text,progress,done,error`).option(`--timeout <ms>`,`Execution timeout in milliseconds (default: 600000)`).option(`--output <format>`,`Output format: text (default) or json`,`text`).option(`--plugins-config <path>`,`Plugins config file path`).option(`--resume-request-id <id>`,`Resume a pending HITL request from aimax run`).option(`--resume-input-json <json>`,`Structured HITL resume payload used with --resume-request-id`).action(async e=>{await Tt(e)})}function Ot(e){e.command(`sessions`).description(`List or inspect sessions for a data directory`).argument(`[action]`,`Action: list (default) | inspect | export`).option(`-d, --data-dir <path>`,`Data directory path`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).option(`-c, --channel <channel>`,`Filter by channel type: H5 | WEB | KLPA | TASK | CRON | EIP_ASSISTANT`).option(`-s, --session-id <id>`,`Session ID for inspect/export`).option(`--output <format>`,`Output format: text or json`).action(async(e,t,n)=>{let r=n.opts(),i=e??`list`,a=i===`export`?r.output===`text`?`text`:`json`:r.output===`json`?`json`:`text`;r.dataDir||(C(`error: required option '-d, --data-dir <path>' not specified`),process.exit(1)),r.channel&&r.channel!==`H5`&&r.channel!==`WEB`&&r.channel!==`KLPA`&&r.channel!==`TASK`&&r.channel!==`CRON`&&r.channel!==`EIP_ASSISTANT`&&(C(`Invalid channel: ${r.channel}. Must be 'H5', 'WEB', 'KLPA', 'TASK', 'CRON', or 'EIP_ASSISTANT'`),process.exit(1));try{let e=r.sessionStore?m(r.sessionStore):void 0;if(i===`list`){ve(await ee(r.dataDir,r.channel,{storeName:e}),a);return}if(r.sessionId||(C(`error: required option '-s, --session-id <id>' not specified`),process.exit(1)),i===`inspect`){ye(await u(r.dataDir,r.sessionId,{storeName:e}),a);return}if(i===`export`){be(await o(r.dataDir,r.sessionId,{storeName:e}),a);return}C(`Invalid sessions action: ${i}. Must be 'list', 'inspect', or 'export'`),process.exit(1)}catch(e){C(`${i===`inspect`?`Error inspecting session`:i===`export`?`Error exporting session`:`Error listing sessions`}: ${e.message}`),process.exit(1)}})}function kt(e,t){let n=[];return n.push(`backend: ${e.backend}`),n.push(`provider: ${e.provider}${e.model?` (${e.model})`:``}`),typeof e.files==`number`&&n.push(`files: ${e.files}`),typeof e.chunks==`number`&&n.push(`chunks: ${e.chunks}`),typeof e.dirty==`boolean`&&n.push(`dirty: ${e.dirty}`),e.dbPath&&n.push(`db: ${e.dbPath}`),e.sources?.length&&n.push(`sources: ${e.sources.join(`, `)}`),t&&(e.fts&&(n.push(`fts: enabled=${e.fts.enabled} available=${e.fts.available}`),e.fts.error&&n.push(`fts_error: ${e.fts.error}`)),e.vector&&(n.push(`vector: enabled=${e.vector.enabled} available=${e.vector.available??`unknown`}`),e.vector.dims&&n.push(`vector_dims: ${e.vector.dims}`),e.vector.loadError&&n.push(`vector_error: ${e.vector.loadError}`)),e.cache&&n.push(`cache: enabled=${e.cache.enabled} entries=${e.cache.entries??0}`)),n.join(`
|
|
7
7
|
`)}function J(e){let t=g.join(e.dataDir,`.aimax`),n=ne({providerId:e.provider,pluginId:e.providerPlugin,dataDir:e.dataDir,memoryDir:t});return n?n.provider:i({dataDir:e.dataDir,memoryDir:t},{includeSessions:e.includeSessions})}function At(e){let t=e.command(`memory`).description(`Manage semantic memory indexing and search`);t.command(`status`).description(`Show memory index status`).requiredOption(`-d, --data-dir <path>`,`Data directory path`).option(`--deep`,`Probe embedding/vector availability`).option(`--index`,`Run a refresh before reporting status`).option(`--include-sessions`,`Include session transcripts in indexing`).option(`--provider <id>`,`Memory provider id`).option(`--provider-plugin <id>`,`Memory provider plugin id`).option(`--verbose`,`Verbose output`).option(`--output <format>`,`Output format: text (default) or json`,`text`).action(async e=>{let t=e.output===`json`?`json`:`text`;try{let n=J({dataDir:e.dataDir,provider:e.provider,providerPlugin:e.providerPlugin,includeSessions:e.includeSessions});e.index&&n.sync&&await n.sync(`cli-status`);let r=n.status();e.deep&&((r.custom??={}).note=`deep probe is only supported by builtin provider`),S(t===`json`?JSON.stringify(r,null,2):kt(r,e.deep))}catch(e){C(`Error getting memory status: ${e.message}`),process.exit(1)}}),t.command(`index`).description(`Reindex memory files`).requiredOption(`-d, --data-dir <path>`,`Data directory path`).option(`--include-sessions`,`Include session transcripts in indexing`).option(`--provider <id>`,`Memory provider id`).option(`--provider-plugin <id>`,`Memory provider plugin id`).option(`--verbose`,`Verbose output`).action(async e=>{try{let t=J({dataDir:e.dataDir,provider:e.provider,providerPlugin:e.providerPlugin,includeSessions:e.includeSessions});t.sync&&await t.sync(`cli-index`),S(`Memory index refreshed.`)}catch(e){C(`Error indexing memory: ${e.message}`),process.exit(1)}}),t.command(`search [query]`).description(`Search semantic memory`).requiredOption(`-d, --data-dir <path>`,`Data directory path`).option(`--query <text>`,`Search query`).option(`--include-sessions`,`Include session transcripts in search`).option(`--provider <id>`,`Memory provider id`).option(`--provider-plugin <id>`,`Memory provider plugin id`).option(`--output <format>`,`Output format: text (default) or json`,`text`).action(async(e,t)=>{let n=t.output===`json`?`json`:`text`,r=t.query?.trim()||e?.trim();r||(C(`Query is required: provide [query] or --query <text>`),process.exit(1));try{let e=await J({dataDir:t.dataDir,provider:t.provider,providerPlugin:t.providerPlugin,includeSessions:t.includeSessions}).search(r);if(n===`json`){S(JSON.stringify(e,null,2));return}if(e.length===0){S(`No results found for: ${r}`);return}S(e.map(e=>{let t=`${e.path}:${e.startLine}-${e.endLine} (${e.score.toFixed(4)}) ${e.snippet}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
|
|
8
8
|
`))}catch(e){C(`Error searching memory: ${e.message}`),process.exit(1)}})}function jt(e){return`${e.match.accountId?`${e.match.channel}:${e.match.accountId}`:e.match.channel} -> ${e.agentId}`}function Mt(e){return async t=>{let n=await b(t),r=ue(n),i=de(n);if(x(n),e.json){console.log(JSON.stringify({agents:r,bindings:i},null,2));return}console.log(`Agents:`);for(let e of r){let n=e.default?` (default)`:``,r=e.name&&e.name!==e.id?`${e.id}${n} (${e.name})`:`${e.id}${n}`;if(console.log(` - ${r}`),e.identity?.emoji||e.identity?.name){let t=[e.identity.emoji,e.identity.name].filter(Boolean).join(` `);console.log(` Identity: ${t}`)}let a=he(t,e.id);if(console.log(` Agent dir: ${a}`),e.model){let t=typeof e.model==`string`?e.model:e.model.primary;console.log(` Model: ${t}`)}let o=i.filter(t=>t.agentId===e.id);if(o.length>0){console.log(` Routing rules:`);for(let e of o)console.log(` - ${jt(e)}`)}}}}function Nt(e,t){return async n=>{y(await b(n),fe(e))&&(console.error(`Agent "${e}" already exists.`),process.exit(1)),await ce(n,{id:e,name:t.name,model:t.model,default:t.default})||(console.error(`Agent "${e}" already exists.`),process.exit(1));let r=he(n,e);console.log(`Agent "${e}" added successfully.`),console.log(` Agent dir: ${r}`)}}function Pt(e){return async t=>{let n=y(await b(t),fe(e));n||(console.error(`Agent "${e}" not found.`),process.exit(1)),n.default===!0&&(console.error(`Cannot delete default agent "${e}".`),process.exit(1)),await pe(t,e)||(console.error(`Failed to delete agent "${e}".`),process.exit(1)),console.log(`Agent "${e}" deleted.`)}}function Ft(e){return async t=>{let n=await b(t),r=e.agent??x(n);y(n,r)||(console.error(`Agent "${r}" not found.`),process.exit(1)),(!e.bind||e.bind.length===0)&&(console.error(`Please specify --bind <channel>[:<account>]`),process.exit(1));for(let n of e.bind){let[e,...i]=n.split(`:`),a=i.join(`:`),o=[`H5`,`WEB`,`KLPA`,`TASK`,`CRON`,`EIP_ASSISTANT`];o.includes(e)||(console.error(`Invalid channel: ${e}`),console.error(`Valid channels: ${o.join(`, `)}`),process.exit(1)),await le(t,{agentId:r,match:{channel:e,accountId:a||void 0}}),console.log(`Binding added: ${n} -> ${r}`)}}}function It(e){return async t=>{let n=await b(t),r=e.agent??x(n);if(y(n,r)||(console.error(`Agent "${r}" not found.`),process.exit(1)),e.all){let e=await me(t,r,`*`);console.log(`Removed ${e} binding(s) for agent "${r}".`)}else if(e.bind&&e.bind.length>0){let n=0;for(let i of e.bind){let[e,...a]=i.split(`:`),o=await me(t,r,e,a.join(`:`)||void 0);o>0?(console.log(`Binding removed: ${i} -> ${r}`),n+=o):console.log(`No binding found: ${i} -> ${r}`)}}else console.error(`Please specify --bind <channel>[:<account>] or --all`),process.exit(1)}}function Lt(e){return async t=>{let n=de(await b(t));if(e.agent&&(n=n.filter(t=>t.agentId===e.agent)),e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(`No bindings configured.`);return}console.log(`Routing bindings:`);for(let e of n)console.log(` ${jt(e)}`)}}function Rt(e){return async t=>{let n=await b(t),r=e.agent??x(n);y(n,r)||(console.error(`Agent "${r}" not found.`),process.exit(1)),await ge(t,r,{name:e.name,emoji:e.emoji,avatar:e.avatar})||(console.error(`Failed to update identity for agent "${r}".`),process.exit(1)),console.log(`Identity updated for agent "${r}".`)}}function zt(e,t){let n=e.command(`agents`).description(`Manage agents`);n.command(`list`).description(`List all configured agents`).option(`-j, --json`,`Output as JSON`).option(`-b, --bindings`,`Show detailed binding rules`).action(async e=>{let n=t();await Mt(e)(n)}),n.command(`add <id>`).description(`Add a new agent`).option(`-n, --name <name>`,`Display name`).option(`-m, --model <model>`,`Model identifier`).option(`--default`,`Mark as default agent`).action(async(e,n)=>{let r=t();await Nt(e,n)(r)}),n.command(`delete <id>`).description(`Delete an agent`).action(async e=>{let n=t();await Pt(e)(n)}),n.command(`bind`).description(`Bind a channel to an agent`).option(`-a, --agent <id>`,`Target agent ID`).option(`-b, --bind <channel...>`,`Channel binding (e.g., WEB, KLPA:ops)`).action(async e=>{let n=t();await Ft(e)(n)}),n.command(`unbind`).description(`Unbind a channel from an agent`).option(`-a, --agent <id>`,`Target agent ID`).option(`-b, --bind <channel...>`,`Channel binding to remove`).option(`--all`,`Remove all bindings for the agent`).action(async e=>{let n=t();await It(e)(n)}),n.command(`bindings`).description(`List routing bindings`).option(`-a, --agent <id>`,`Filter by agent ID`).option(`-j, --json`,`Output as JSON`).action(async e=>{let n=t();await Lt(e)(n)}),n.command(`set-identity`).description(`Set agent identity`).option(`-a, --agent <id>`,`Target agent ID`).option(`-n, --name <name>`,`Agent name`).option(`-e, --emoji <emoji>`,`Agent emoji`).option(`--avatar <path>`,`Avatar path`).action(async e=>{let n=t();await Rt(e)(n)})}function Y(e){return g.join(e,`workspace`)}function X(){let e=process.env.AIMAX_PLUGINS_BUNDLED_DIR;return e&&e.trim()||void 0}function Bt(e){if(e.length===0){S(`No plugins discovered.`);return}for(let t of e){let e=t.status.padEnd(8,` `);S(`${t.id} ${e} ${t.origin} ${t.source}`)}}function Vt(e){S(`id: ${e.id}`),S(`status: ${e.status}`),S(`origin: ${e.origin}`),S(`source: ${e.source}`),S(`enabled: ${e.enabled}`),e.error&&S(`error: ${e.error}`),S(`tools: ${e.toolCount}`),S(`hooks: ${e.hookCount}`),e.skills.length>0&&S(`skills: ${e.skills.join(`, `)}`)}function Z(e){return Array.from(new Set((e??[]).map(e=>e.trim()).filter(Boolean)))}function Ht(e){if(e.length===0){S(`LLM allowlist is empty.`);return}for(let t of e)S(t)}function Ut(e,t){let n=e.command(`plugins`).description(`Manage AIMax plugins`),r=e=>e.option(`--plugins-config <path>`,`Plugins config file path`);r(n.command(`list`)).description(`List discovered plugins`).option(`-d, --data-dir <path>`,`Data directory path`).action(async e=>{let n=e.dataDir??t();Bt(l({config:await k(n,e.pluginsConfig),dataDir:n,workspaceDir:Y(n),bundledDir:X()}).registry.plugins)}),r(n.command(`info`)).description(`Show plugin details`).argument(`<id>`,`Plugin id`).option(`-d, --data-dir <path>`,`Data directory path`).action(async(e,n)=>{let r=n.dataDir??t(),i=l({config:await k(r,n.pluginsConfig),dataDir:r,workspaceDir:Y(r),bundledDir:X()}).registry.plugins.find(t=>t.id===e);i||(C(`Plugin not found: ${e}`),process.exit(1)),Vt(i)}),r(n.command(`enable`)).description(`Enable a plugin`).argument(`<id>`,`Plugin id`).option(`-d, --data-dir <path>`,`Data directory path`).action(async(e,n)=>{let r=n.dataDir??t(),i=await k(r,n.pluginsConfig)??{},a=p(i);l({config:i,dataDir:r,workspaceDir:Y(r),bundledDir:X()}).registry.plugins.some(t=>t.id===e)||(C(`Plugin not found: ${e}`),process.exit(1)),await A(r,{...i,entries:{...i.entries,[e]:{...i.entries?.[e]??{},enabled:!0}}},n.pluginsConfig),S(`Enabled ${e}`),a.allow.length>0&&!a.allow.includes(e)&&S(`Note: plugins.allow is set; add this plugin id to allowlist if needed.`)}),r(n.command(`disable`)).description(`Disable a plugin`).argument(`<id>`,`Plugin id`).option(`-d, --data-dir <path>`,`Data directory path`).action(async(e,n)=>{let r=n.dataDir??t(),i=await k(r,n.pluginsConfig)??{};l({config:i,dataDir:r,workspaceDir:Y(r),bundledDir:X()}).registry.plugins.some(t=>t.id===e)||(C(`Plugin not found: ${e}`),process.exit(1)),await A(r,{...i,entries:{...i.entries,[e]:{...i.entries?.[e]??{},enabled:!1}}},n.pluginsConfig),S(`Disabled ${e}`)}),r(n.command(`doctor`)).description(`Validate plugin configuration`).option(`-d, --data-dir <path>`,`Data directory path`).action(async e=>{let n=e.dataDir??t(),r=l({config:await k(n,e.pluginsConfig),dataDir:n,workspaceDir:Y(n),bundledDir:X()});if(r.diagnostics.length===0){S(`No plugin issues detected.`);return}for(let e of r.diagnostics)S(`${e.level===`error`?`ERROR`:`WARN`}${e.pluginId?` ${e.pluginId}`:``}: ${e.message}`);r.diagnostics.some(e=>e.level===`error`)&&process.exit(1)});let i=n.command(`llm-allow`).description(`Manage plugin LLM allowlist`);r(i.command(`list`)).description(`List LLM allowlist entries`).option(`-d, --data-dir <path>`,`Data directory path`).action(async e=>{Ht(Z((await k(e.dataDir??t(),e.pluginsConfig))?.llmAllowlist))}),r(i.command(`add`)).description(`Add entries to the LLM allowlist (plugin id or tool name)`).argument(`<entry...>`,`Plugin id or tool name`).option(`-d, --data-dir <path>`,`Data directory path`).action(async(e,n)=>{let r=n.dataDir??t(),i=await k(r,n.pluginsConfig)??{},a=Z([...i.llmAllowlist??[],...e]);await A(r,{...i,llmAllowlist:a},n.pluginsConfig),S(`LLM allowlist updated (${a.length} entries).`)}),r(i.command(`remove`)).description(`Remove entries from the LLM allowlist`).argument(`<entry...>`,`Plugin id or tool name`).option(`-d, --data-dir <path>`,`Data directory path`).action(async(e,n)=>{let r=n.dataDir??t(),i=await k(r,n.pluginsConfig)??{},a=new Set(e.map(e=>e.trim()).filter(Boolean)),o=Z(i.llmAllowlist).filter(e=>!a.has(e));await A(r,{...i,llmAllowlist:o},n.pluginsConfig),S(`LLM allowlist updated (${o.length} entries).`)}),r(i.command(`clear`)).description(`Clear the LLM allowlist`).option(`-d, --data-dir <path>`,`Data directory path`).action(async e=>{let n=e.dataDir??t();await A(n,{...await k(n,e.pluginsConfig)??{},llmAllowlist:[]},e.pluginsConfig),S(`LLM allowlist cleared.`)})}function Wt(e){e.command(`commands`).description(`List available slash commands for a data directory`).requiredOption(`-d, --data-dir <path>`,`Data directory path`).option(`--output <format>`,`Output format: text (default) or json`,`text`).action(async e=>{let t=e.output===`json`?`json`:`text`;try{let n=d(await f(e.dataDir,[]));if(t===`json`){S(JSON.stringify(n,null,2));return}S(`Commands`),S(` builtin: ${n.builtin.map(e=>e.name).join(` | `)}`),n.skillCommands.length>0?S(` skills: ${n.skillCommands.map(e=>e.name).join(` | `)}`):S(` skills: (none)`)}catch(e){C(`Error listing commands: ${e.message}`),process.exit(1)}})}const Gt=[`progress`,`error`,`hitl`];function Q(e){let t=e.dataDir??process.env.AIMAX_DATA_DIR;if(!t)throw Error(`Data directory must be specified via --data-dir or AIMAX_DATA_DIR`);return t}function Kt(e){if(!e?.trim())return new Set(Gt);let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean),n=new Set([`start`,`text`,`progress`,`done`,`error`,`hitl`,`title_updated`]),r=new Set;for(let e of t){if(!n.has(e))throw Error(`Invalid stream event: ${e}. Must be one of start,text,progress,done,error,hitl`);r.add(e)}return r.size>0?r:new Set(Gt)}function qt(e){return e?m(e):void 0}function Jt(e){let t=[];return e.callbackUrl&&t.push(new V(e.callbackUrl)),e.streamUrl&&t.push(new W(e.streamUrl,Kt(e.streamEvents),e.streamAuthToken)),new B(t)}async function Yt(e){L(Q(e));let t=new z(`cancel command`),n=Q(e),r=e.channel??`WEB`,i=e.output===`json`?`json`:`text`,a=Jt(e),o=qt(e.sessionStore);try{let s=await te(n,e.sessionId,{storeName:o});if(!s)throw Error(`No pending HITL request found for session "${e.sessionId}"`);let c=e.requestId??s.request.requestId;if(s.request.requestId!==c)throw Error(`Request ID mismatch: pending is "${s.request.requestId}", got "${c}"`);if(!(await h({dataDir:n,sessionStoreName:o,sessionId:e.sessionId,requestId:c,resolution:{requestId:c,sessionId:e.sessionId,action:`cancel`,submittedAt:new Date().toISOString(),submittedBy:{channel:r}}})).state)throw Error(`Failed to cancel HITL request`);let l={type:`hitl_cancelled`,sessionId:e.sessionId,requestId:c,reason:e.reason??`cancelled by operator`};i===`text`&&w(l),await a.send({type:`progress`,sessionId:e.sessionId,channel:r,messageId:e.messageId,event:l}),t.end(),process.exit(0)}catch(n){let i=n;await a.send({type:`error`,sessionId:e.sessionId,channel:r,messageId:e.messageId,message:i.message}),R.error(`cancel command error: ${i.message}`),C(`Fatal: ${i.message}`),t.end(),process.exit(1)}finally{await a.close()}}function Xt(e){e.command(`cancel`).description(`Cancel a pending HITL request`).requiredOption(`-d, --data-dir <path>`,`Data directory path`).requiredOption(`-s, --session-id <id>`,`Session ID containing the pending HITL request`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).option(`--request-id <id>`,`HITL request ID to cancel`).option(`--reason <text>`,`Human-readable cancel reason`).option(`-c, --channel <channel>`,`Channel type (default: WEB)`,`WEB`).option(`--callback-url <url>`,`HTTP callback URL for progress events`).option(`--stream-url <url>`,`WebSocket URL for streaming text events`).option(`--stream-auth-token <token>`,`Auth token for WebSocket streaming`).option(`--stream-events <list>`,`Comma-separated stream events`).option(`--message-id <id>`,`Message ID for correlating events`).option(`--output <format>`,`Output format: text (default) or json`,`text`).action(async e=>{await Yt(e)})}const Zt=e(import.meta.url)(`../package.json`);function $(){return process.env.AIMAX_DATA_DIR||process.cwd()}function Qt(){let e=new t;return e.name(`aimax`).description(`AIMax CLI — runs agent tasks in a containerized environment`).version(Zt.version),Dt(e),Qe(e),Xt(e),Ot(e),Wt(e),Se(e),At(e),zt(e,$),Ut(e,$),e}export{Re as a,R as i,$ as n,L as r,Qt as t};
|
package/dist/program.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./program-
|
|
1
|
+
import{n as e,t}from"./program-A7EVfTdv.js";export{t as createProgram,e as getDataDir};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gencode/cli",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.38",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"aimax": "./dist/bin.js"
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
"commander": "^14.0.3",
|
|
22
22
|
"gensign-node": "latest",
|
|
23
23
|
"log4js": "^6.9.1",
|
|
24
|
-
"@gencode/
|
|
25
|
-
"@gencode/
|
|
24
|
+
"@gencode/shared": "0.0.11",
|
|
25
|
+
"@gencode/agents": "0.0.39"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@types/node": "^22.0.0",
|