@gencode/cli 0.0.27 → 0.0.28

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{r as e,t}from"./program-CJPDK5S0.js";function n(){globalThis.getPkgPath||(globalThis.getPkgPath=()=>`@wizard/aimax`)}n();const r=Date.now();e.info(`AIMax CLI starting (pid=${process.pid})`),t().parseAsync(process.argv).catch(t=>{e.error(`Unexpected error: ${t.message}`),process.exit(1)}).finally(()=>{let t=Date.now()-r;e.info(`AIMax CLI exited (total uptime: ${t}ms)`)});export{};
2
+ import{r as e,t}from"./program-BcnstgMo.js";function n(){globalThis.getPkgPath||(globalThis.getPkgPath=()=>`@wizard/aimax`)}n();const r=Date.now();e.info(`AIMax CLI starting (pid=${process.pid})`),t().parseAsync(process.argv).catch(t=>{e.error(`Unexpected error: ${t.message}`),process.exit(1)}).finally(()=>{let t=Date.now()-r;e.info(`AIMax CLI exited (total uptime: ${t}ms)`)});export{};
@@ -1,7 +1,7 @@
1
1
  import{createRequire as e}from"node:module";import{Command as t}from"commander";import{bootstrapMountLayout as n,createBuiltinMemoryProvider as r,ensureBootstrapMountLayout as i,exportSession as a,hasBootstrapSentinel as o,initializePluginSystem as s,inspectSession as c,listAvailableSlashCommands as l,listSessionSummaries as u,loadPendingHitl as d,loadSkillsWithPluginDirs as ee,normalizePluginsConfig as f,resolveMemoryProvider as p,resolvePendingHitl as te,runAgent as m}from"@gencode/agents";import{isAgentDiagnosticEvent as h}from"@gencode/shared";import g from"node:path";import ne from"gensign-node";import _ from"node:fs/promises";import{addAgent as re,addBinding as ie,getAgentConfig as v,listAgents as ae,listBindings as oe,loadAgentsConfig as y,normalizeAgentId as b,removeAgent as se,removeBindings as x,resolveAgentDir as ce,resolveDefaultAgentId as S,updateAgentIdentity as le}from"@gencode/agents/config";function C(e){process.stdout.write(e)}function w(e){process.stdout.write(e+`
2
2
  `)}function T(e){process.stderr.write(e+`
3
3
  `)}function E(e){switch(e.type){case`start`:w(`\n[start] ${e.message}`);break;case`text`:C(e.text);break;case`stream_text_delta`:C(e.text);break;case`bootstrap`:w(`\n[bootstrap:${e.phase}] ${e.dataDir}`);break;case`session_reset`:w(`\n[session:${e.action}] ${e.message}`);break;case`tool_start`:w(`\n[tool:${e.name}] ${JSON.stringify(e.input)}`);break;case`tool_end`:w(`[tool:${e.name}] ${e.isError?`ERROR`:`OK`} ${e.output.slice(0,200)}`);break;case`compaction`:w(`\n[compaction${e.layer?`:${e.layer}`:``}] ${e.reason}${e.strategy?` (${e.strategy})`:``}`);break;case`skill_used`:w(`\n[skill] ${e.skillName} agent=${e.agent} task=${e.taskId}`);break;case`custom`:w(`\n[plugin:${e.pluginId}] ${e.name}${e.label?` ${e.label}`:``}${e.data?` ${JSON.stringify(e.data)}`:``}`);break;case`error`:T(`\n[error] ${e.message}`);break;case`diagnostic`:break;case`subagent_spawn`:w(`\n[subagent:spawn]${e.label?` "${e.label}"`:``} ${e.task}`);break;case`subagent_complete`:w(`[subagent:${e.status}] ${e.task}`);break;case`hitl_requested`:if(w(`\n[hitl:${e.request.kind}] ${e.request.title}`),w(` prompt: ${e.request.prompt}`),w(` requestId: ${e.request.requestId}`),e.request.input.mode===`choice`)for(let t of e.request.input.choices)w(` - [${t.id}] ${t.label}`);break;case`hitl_resumed`:w(`\n[hitl:resumed] requestId=${e.requestId} action=${e.resolution.action}`);break;case`hitl_expired`:w(`\n[hitl:expired] requestId=${e.requestId} reason=${e.reason}`);break;case`hitl_cancelled`:w(`\n[hitl:cancelled] requestId=${e.requestId}${e.reason?` reason=${e.reason}`:``}`);break}}function D(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}w(`
4
- `),w(`session: ${e.sessionId}`),w(`duration: ${e.durationMs}ms`),w(`tokens: input=${e.usage.input} output=${e.usage.output} total=${e.usage.total}`),e.context&&(w(`context: ${e.context.snapshotPath}`),w(`tool-results: ${e.context.toolResultsDir}`)),e.error&&T(`error: ${e.error}`)}function ue(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}if(e.length===0){w(`No sessions found.`);return}for(let t of e){let e=t.createdAt?new Date(t.createdAt).toLocaleString():`unknown`;w(`${t.id} ${e} [${t.channel}] ${t.title}`)}}function de(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}w(`session: ${e.id}`),e.metadata&&(w(`title: ${e.metadata.title}`),w(`channel: ${e.metadata.channel}`),w(`created: ${e.metadata.createdAt}`),w(`updated: ${e.metadata.updatedAt}`)),w(`transcript: ${e.transcriptPath}`),w(`entries: ${e.transcriptEntryCount}`),w(`context: ${e.contextSnapshotPath}`),w(`session-memory: ${e.sessionMemoryPath}`),w(`collapse-log: ${e.collapseLogPath}`),w(`read-states: ${e.readStateCount}`),w(`tool-results: ${e.toolResultRefCount}`),w(`tool-results-dir: ${e.toolResultsDir}`)}function fe(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}w(`session: ${e.id}`),w(`transcript: ${e.paths.transcriptPath}`),w(`context: ${e.paths.contextSnapshotPath}`),w(`session-memory: ${e.paths.sessionMemoryPath}`),w(`collapse-log: ${e.paths.collapseLogPath}`),w(`tool-results-dir: ${e.paths.toolResultsDir}`),w(`transcript-entries: ${e.transcript.length}`),w(`read-states: ${e.context.readStates.length}`),w(`tool-results: ${e.context.toolResults.length}`),w(`collapse-spans: ${e.context.compaction.collapseSpans.length}`)}function pe(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}w(`Bootstrap completed.`),w(`dataDir: ${e.dataDir}`),w(`created dirs: ${e.createdDirs.length}`),w(`created files: ${e.createdFiles.length}`),w(`skipped dirs: ${e.skippedDirs.length}`),w(`skipped files: ${e.skippedFiles.length}`)}function me(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{pe(await n(e.dataDir),t)}catch(e){T(`Error bootstrapping data directory: ${e.message}`),process.exit(1)}})}function he(e){return ne.sm4_encrypt_ecb(e)}function ge(e){return he(e)}function _e(e={}){let t=e.baseUrl??process.env.AIMAX_BASE_URL,n=process.env.AIMAX_AUTH_TOKEN,r=e.authToken?ge(e.authToken):n?ge(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 ve(e,t){return t?g.resolve(t):g.join(e,`.aimax`,`plugins.json`)}async function O(e,t){let n=ve(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 k(e,t,n){let r=ve(e,n);await _.mkdir(g.dirname(r),{recursive:!0}),await _.writeFile(r,JSON.stringify(t,null,2),`utf-8`)}function A(e){return typeof e==`object`&&!!e}function j(e){return A(e)&&e.type===`text`&&typeof e.text==`string`&&(e.textSignature===void 0||typeof e.textSignature==`string`)}function M(e){return A(e)&&e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`}function ye(e){return A(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 be(e){return A(e)&&e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`&&A(e.arguments)&&(e.thoughtSignature===void 0||typeof e.thoughtSignature==`string`)}function xe(e){return typeof e==`string`||Array.isArray(e)&&e.every(e=>j(e)||M(e))}function Se(e){return Array.isArray(e)&&e.every(e=>j(e)||ye(e)||be(e))}function Ce(e){return A(e)&&typeof e.input==`number`&&typeof e.output==`number`&&typeof e.cacheRead==`number`&&typeof e.cacheWrite==`number`&&typeof e.totalTokens==`number`&&A(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 we(e){return!A(e)||typeof e.role!=`string`?!1:e.role===`user`?xe(e.content):e.role===`assistant`?Se(e.content)&&typeof e.api==`string`&&typeof e.provider==`string`&&typeof e.model==`string`&&Ce(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=>j(e)||M(e))&&typeof e.isError==`boolean`:!1}async function Te(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=>we(e)))throw Error(`Message file must contain one Message object or an array of Message objects`);return r}async function Ee(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 Te(e.fromFile)}:{kind:`text`,message:e.message}}let N=function(e){return e.INFO=`INFO`,e.ERROR=`ERROR`,e.WARN=`WARN`,e}({});function De(){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 Oe(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 P(e,t,n){let r=De();process.stderr.write(`[${r}] [${e}] ${t}${Oe(n)}\n`)}const F={info:(e,t)=>P(N.INFO,e,t),warn:(e,t)=>P(N.WARN,e,t),error:(e,t)=>P(N.ERROR,e,t)};var I=class{startTime;name;constructor(e){this.name=e,this.startTime=Date.now()}end(){let e=Date.now()-this.startTime;return F.info(`${this.name} completed in ${e}ms`),e}},L=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()}))}},R=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=ke(e);F.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 F.error(`callback event failed`,{callbackUrl:this.url,httpStatus:r.status,durationMs:i,...n}),Error(`Callback failed with status ${r.status}`);F.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;default:{let t=e;throw Error(`Unsupported callback event: ${JSON.stringify(t)}`)}}}};function ke(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 Ae(e,t){if(t.kind===`none`)return e;let n=new URL(e);return n.searchParams.set(`authToken`,t.token),n.toString()}function z(){let e=globalThis.WebSocket;if(!e)throw Error(`WebSocket is not available in this runtime`);return e}function je(e){return e?{kind:`query_token`,token:e}:{kind:`none`}}function B(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 Me(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 V=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=z();if(!this.socket||this.socket.readyState!==e.OPEN)return;this.socket.send(JSON.stringify(t))}catch(e){F.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=z();if(!this.socket||this.socket.readyState!==e.OPEN)return;this.socket.send(JSON.stringify(t))}catch(e){F.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=z();e.readyState!==t.CLOSED&&await new Promise(t=>{B(e,`close`,()=>t()),e.close()})}async ensureConnected(){if(!this.enabled)return;let e=z();if(this.socket&&this.socket.readyState===e.OPEN)return;if(this.connectPromise){await this.connectPromise;return}let t=new e(Ae(this.url,je(this.authToken)));this.connectPromise=new Promise((e,n)=>{B(t,`open`,()=>{this.socket=t,Me(t,`close`,()=>{this.socket===t&&(this.socket=null)}),e()}),B(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`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 H=[`start`,`text`,`done`,`error`,`hitl`];function Ne(e){if(!e?.trim())return new Set(H);let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean),n=new Set([`start`,`text`,`progress`,`done`,`error`,`hitl`]),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(H)}function Pe(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 Fe(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 Ie(e){let t=Pe(e),n=e.channel??`WEB`,r=_e({baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow?Number(e.contextWindow):void 0,flashModel:e.flashModel}),i=Fe(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 Le(e){let t=[],n=null;return e.callbackUrl&&t.push(new R(e.callbackUrl)),e.streamUrl&&(n=new V(e.streamUrl,Ne(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new L(t),websocketSink:n}}async function U(e){let t=new I(`resume command`),n=null;try{let r=await Ie(e);F.info(`resume command started`,{sessionId:e.sessionId,requestId:e.requestId,channel:r.channel,dataDir:r.dataDir});let i=await d(r.dataDir,e.sessionId);if(!i)throw Error(`No pending HITL request found for session "${e.sessionId}"`);if(i.request.requestId!==e.requestId)throw Error(`Request ID mismatch: pending is "${i.request.requestId}", got "${e.requestId}"`);if(i.status===`expired`)throw Error(`HITL request has expired`);if(i.status===`cancelled`)throw Error(`HITL request has been cancelled`);let a=await te({dataDir:r.dataDir,sessionId:e.sessionId,requestId:e.requestId,resolution:r.resolution}),o=a.state;if(!o)throw Error(`Resolved HITL state was not persisted`);let s=Re(r.resolution,o.request.kind),c=Le(e);n=c.sink;let l=e.sessionId,u=async t=>{if(l=t.sessionId??l,!h(t)){if(t.type===`stream_text_delta`){r.format===`text`&&E(t),await c.websocketSink?.sendTextDelta({sessionId:l,channel:r.channel,messageId:e.messageId,user:e.user,text:t.text});return}if(r.format===`text`&&E(t),t.type===`hitl_resumed`){await n?.send({sessionId:l,channel:r.channel,messageId:e.messageId,user:e.user,type:`progress`,event:t});return}if(t.type===`start`){await n?.send({sessionId:l,channel:r.channel,messageId:e.messageId,user:e.user,type:`start`,message:t.message});return}await n?.send({sessionId:l,channel:r.channel,messageId:e.messageId,user:e.user,type:`progress`,event:t})}};await u({type:`hitl_resumed`,requestId:e.requestId,resolution:r.resolution,sessionId:e.sessionId}),`idempotentReplay`in a&&a.idempotentReplay&&(F.info(`resume command treated as idempotent replay`,{sessionId:e.sessionId,requestId:e.requestId,idempotencyKey:r.resolution.idempotencyKey}),D({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 O(r.dataDir,ee),p;try{p=await m({dataDir:r.dataDir,sessionId:e.sessionId,messageId:e.messageId,channel:r.channel,llm:r.llm,timeoutMs:r.timeoutMs,message:s,hitlResume:{request:o.request,resolution:r.resolution,checkpoint:o.checkpoint,toolContext:o.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:u})}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}}),D(p,r.format),p.error?F.error(`resume command failed: ${p.error}`):F.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}`})),F.error(`resume command error: ${i.message}`),T(`Fatal: ${i.message}`),t.end(),process.exit(1)}finally{await n?.close()}}function Re(e,t){let n=[];return n.push(`[HITL Resume] The user has responded to the ${t} request (${e.requestId}).`),e.action===`cancel`?(n.push(`Action: The user cancelled the request. Please acknowledge and proceed without this action.`),n.join(`
4
+ `),w(`session: ${e.sessionId}`),w(`duration: ${e.durationMs}ms`),w(`tokens: input=${e.usage.input} output=${e.usage.output} total=${e.usage.total}`),e.context&&(w(`context: ${e.context.snapshotPath}`),w(`tool-results: ${e.context.toolResultsDir}`)),e.error&&T(`error: ${e.error}`)}function ue(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}if(e.length===0){w(`No sessions found.`);return}for(let t of e){let e=t.createdAt?new Date(t.createdAt).toLocaleString():`unknown`;w(`${t.id} ${e} [${t.channel}] ${t.title}`)}}function de(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}w(`session: ${e.id}`),e.metadata&&(w(`title: ${e.metadata.title}`),w(`channel: ${e.metadata.channel}`),w(`created: ${e.metadata.createdAt}`),w(`updated: ${e.metadata.updatedAt}`)),w(`transcript: ${e.transcriptPath}`),w(`entries: ${e.transcriptEntryCount}`),w(`context: ${e.contextSnapshotPath}`),w(`session-memory: ${e.sessionMemoryPath}`),w(`collapse-log: ${e.collapseLogPath}`),w(`read-states: ${e.readStateCount}`),w(`tool-results: ${e.toolResultRefCount}`),w(`tool-results-dir: ${e.toolResultsDir}`)}function fe(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}w(`session: ${e.id}`),w(`transcript: ${e.paths.transcriptPath}`),w(`context: ${e.paths.contextSnapshotPath}`),w(`session-memory: ${e.paths.sessionMemoryPath}`),w(`collapse-log: ${e.paths.collapseLogPath}`),w(`tool-results-dir: ${e.paths.toolResultsDir}`),w(`transcript-entries: ${e.transcript.length}`),w(`read-states: ${e.context.readStates.length}`),w(`tool-results: ${e.context.toolResults.length}`),w(`collapse-spans: ${e.context.compaction.collapseSpans.length}`)}function pe(e,t){if(t===`json`){w(JSON.stringify(e,null,2));return}w(`Bootstrap completed.`),w(`dataDir: ${e.dataDir}`),w(`created dirs: ${e.createdDirs.length}`),w(`created files: ${e.createdFiles.length}`),w(`skipped dirs: ${e.skippedDirs.length}`),w(`skipped files: ${e.skippedFiles.length}`)}function me(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{pe(await n(e.dataDir),t)}catch(e){T(`Error bootstrapping data directory: ${e.message}`),process.exit(1)}})}function he(e){return ne.sm4_encrypt_ecb(e)}function ge(e){return he(e)}function _e(e={}){let t=e.baseUrl??process.env.AIMAX_BASE_URL,n=process.env.AIMAX_AUTH_TOKEN,r=e.authToken?ge(e.authToken):n?ge(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 ve(e,t){return t?g.resolve(t):g.join(e,`.aimax`,`plugins.json`)}async function O(e,t){let n=ve(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 k(e,t,n){let r=ve(e,n);await _.mkdir(g.dirname(r),{recursive:!0}),await _.writeFile(r,JSON.stringify(t,null,2),`utf-8`)}function A(e){return typeof e==`object`&&!!e}function j(e){return A(e)&&e.type===`text`&&typeof e.text==`string`&&(e.textSignature===void 0||typeof e.textSignature==`string`)}function M(e){return A(e)&&e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`}function ye(e){return A(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 be(e){return A(e)&&e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`&&A(e.arguments)&&(e.thoughtSignature===void 0||typeof e.thoughtSignature==`string`)}function xe(e){return typeof e==`string`||Array.isArray(e)&&e.every(e=>j(e)||M(e))}function Se(e){return Array.isArray(e)&&e.every(e=>j(e)||ye(e)||be(e))}function Ce(e){return A(e)&&typeof e.input==`number`&&typeof e.output==`number`&&typeof e.cacheRead==`number`&&typeof e.cacheWrite==`number`&&typeof e.totalTokens==`number`&&A(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 we(e){return!A(e)||typeof e.role!=`string`?!1:e.role===`user`?xe(e.content):e.role===`assistant`?Se(e.content)&&typeof e.api==`string`&&typeof e.provider==`string`&&typeof e.model==`string`&&Ce(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=>j(e)||M(e))&&typeof e.isError==`boolean`:!1}async function Te(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=>we(e)))throw Error(`Message file must contain one Message object or an array of Message objects`);return r}async function Ee(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 Te(e.fromFile)}:{kind:`text`,message:e.message}}let N=function(e){return e.INFO=`INFO`,e.ERROR=`ERROR`,e.WARN=`WARN`,e}({});function De(){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 Oe(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 P(e,t,n){let r=De();process.stderr.write(`[${r}] [${e}] ${t}${Oe(n)}\n`)}const F={info:(e,t)=>P(N.INFO,e,t),warn:(e,t)=>P(N.WARN,e,t),error:(e,t)=>P(N.ERROR,e,t)};var I=class{startTime;name;constructor(e){this.name=e,this.startTime=Date.now()}end(){let e=Date.now()-this.startTime;return F.info(`${this.name} completed in ${e}ms`),e}},L=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()}))}},R=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=ke(e);F.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 F.error(`callback event failed`,{callbackUrl:this.url,httpStatus:r.status,durationMs:i,...n}),Error(`Callback failed with status ${r.status}`);F.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 ke(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 Ae(e,t){if(t.kind===`none`)return e;let n=new URL(e);return n.searchParams.set(`authToken`,t.token),n.toString()}function z(){let e=globalThis.WebSocket;if(!e)throw Error(`WebSocket is not available in this runtime`);return e}function je(e){return e?{kind:`query_token`,token:e}:{kind:`none`}}function B(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 Me(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 V=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=z();if(!this.socket||this.socket.readyState!==e.OPEN)return;this.socket.send(JSON.stringify(t))}catch(e){F.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=z();if(!this.socket||this.socket.readyState!==e.OPEN)return;this.socket.send(JSON.stringify(t))}catch(e){F.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=z();e.readyState!==t.CLOSED&&await new Promise(t=>{B(e,`close`,()=>t()),e.close()})}async ensureConnected(){if(!this.enabled)return;let e=z();if(this.socket&&this.socket.readyState===e.OPEN)return;if(this.connectPromise){await this.connectPromise;return}let t=new e(Ae(this.url,je(this.authToken)));this.connectPromise=new Promise((e,n)=>{B(t,`open`,()=>{this.socket=t,Me(t,`close`,()=>{this.socket===t&&(this.socket=null)}),e()}),B(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 H=[`start`,`text`,`done`,`error`,`hitl`];function Ne(e){if(!e?.trim())return new Set(H);let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean),n=new Set([`start`,`text`,`progress`,`done`,`error`,`hitl`]),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(H)}function Pe(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 Fe(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 Ie(e){let t=Pe(e),n=e.channel??`WEB`,r=_e({baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow?Number(e.contextWindow):void 0,flashModel:e.flashModel}),i=Fe(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 Le(e){let t=[],n=null;return e.callbackUrl&&t.push(new R(e.callbackUrl)),e.streamUrl&&(n=new V(e.streamUrl,Ne(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new L(t),websocketSink:n}}async function U(e){let t=new I(`resume command`),n=null;try{let r=await Ie(e);F.info(`resume command started`,{sessionId:e.sessionId,requestId:e.requestId,channel:r.channel,dataDir:r.dataDir});let i=await d(r.dataDir,e.sessionId);if(!i)throw Error(`No pending HITL request found for session "${e.sessionId}"`);if(i.request.requestId!==e.requestId)throw Error(`Request ID mismatch: pending is "${i.request.requestId}", got "${e.requestId}"`);if(i.status===`expired`)throw Error(`HITL request has expired`);if(i.status===`cancelled`)throw Error(`HITL request has been cancelled`);let a=await te({dataDir:r.dataDir,sessionId:e.sessionId,requestId:e.requestId,resolution:r.resolution}),o=a.state;if(!o)throw Error(`Resolved HITL state was not persisted`);let s=Re(r.resolution,o.request.kind),c=Le(e);n=c.sink;let l=e.sessionId,u=async t=>{if(l=t.sessionId??l,!h(t)){if(t.type===`stream_text_delta`){r.format===`text`&&E(t),await c.websocketSink?.sendTextDelta({sessionId:l,channel:r.channel,messageId:e.messageId,user:e.user,text:t.text});return}if(r.format===`text`&&E(t),t.type===`hitl_resumed`){await n?.send({sessionId:l,channel:r.channel,messageId:e.messageId,user:e.user,type:`progress`,event:t});return}if(t.type===`start`){await n?.send({sessionId:l,channel:r.channel,messageId:e.messageId,user:e.user,type:`start`,message:t.message});return}await n?.send({sessionId:l,channel:r.channel,messageId:e.messageId,user:e.user,type:`progress`,event:t})}};await u({type:`hitl_resumed`,requestId:e.requestId,resolution:r.resolution,sessionId:e.sessionId}),`idempotentReplay`in a&&a.idempotentReplay&&(F.info(`resume command treated as idempotent replay`,{sessionId:e.sessionId,requestId:e.requestId,idempotencyKey:r.resolution.idempotencyKey}),D({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 O(r.dataDir,ee),p;try{p=await m({dataDir:r.dataDir,sessionId:e.sessionId,messageId:e.messageId,channel:r.channel,llm:r.llm,timeoutMs:r.timeoutMs,message:s,hitlResume:{request:o.request,resolution:r.resolution,checkpoint:o.checkpoint,toolContext:o.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:u})}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}}),D(p,r.format),p.error?F.error(`resume command failed: ${p.error}`):F.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}`})),F.error(`resume command error: ${i.message}`),T(`Fatal: ${i.message}`),t.end(),process.exit(1)}finally{await n?.close()}}function Re(e,t){let n=[];return n.push(`[HITL Resume] The user has responded to the ${t} request (${e.requestId}).`),e.action===`cancel`?(n.push(`Action: The user cancelled the request. Please acknowledge and proceed without this action.`),n.join(`
5
5
  `)):e.action===`timeout`?(n.push(`Action: The request timed out without a response. Apply the default timeout policy.`),n.join(`
6
6
  `)):(n.push(`Action: The user submitted a response.`),e.values?.selectedChoiceIds&&e.values.selectedChoiceIds.length>0&&n.push(`Selected choices: ${e.values.selectedChoiceIds.join(`, `)}`),e.values?.text&&n.push(`User text: ${e.values.text}`),e.values?.form&&n.push(`Form data: ${JSON.stringify(e.values.form)}`),n.join(`
7
7
  `))}function ze(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`).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 U(e)})}const W=[`start`,`text`,`done`,`error`];function Be(e){if(!e?.trim())return new Set(W);let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean),n=new Set([`start`,`text`,`progress`,`done`,`error`,`hitl`]),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(W)}function Ve(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 He(e){return e??`WEB`}async function Ue(e){let t=Ve(e),n=He(e.channel),r=_e({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 Ee({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 We(e){let t=[],n=null;return e.callbackUrl&&t.push(new R(e.callbackUrl)),e.streamUrl&&(n=new V(e.streamUrl,Be(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new L(t),websocketSink:n}}async function G(e,t){F.info(`dispatching external event`,at(t)),await e.sink.send(t)}function Ge(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 Ke(e){let t={sessionId:e.sessionId,messageId:e.messageId,parentSessionId:e.parentSessionId,depth:e.depth,scope:e.scope,phase:e.phase,...Ge(e.details)};if(e.level===`error`){F.error(e.message,t);return}if(e.level===`warn`){F.warn(e.message,t);return}F.info(e.message,t)}function K(e,t,n,r,i){return{sink:e,websocketSink:t,channel:n,defaultMessageId:r,user:i}}function qe(){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 Je(e){return{activeSessionId:e??`pending`,finalResult:null}}function Ye(e,t){e.activeSessionId=t.sessionId??e.activeSessionId}function q(e,t){return e.messageId??t}async function Xe(e,t,n){if(!await o(e.dataDir)){if(await J(t,e.format,n.activeSessionId,e.dataDir,`checking`),(await i(e.dataDir)).performedBootstrap){await J(t,e.format,n.activeSessionId,e.dataDir,`initializing`),await J(t,e.format,n.activeSessionId,e.dataDir,`initialized`);return}await J(t,e.format,n.activeSessionId,e.dataDir,`ready`)}}async function J(e,t,n,r,i){let a={type:`bootstrap`,phase:i,dataDir:r};t===`text`&&E(a),await G(e,{sessionId:n,channel:e.channel,messageId:e.defaultMessageId,user:e.user,type:`progress`,event:a})}function Ze(e,t,n){return async r=>{if(Ye(n,r),h(r)){Ke(r);return}if(r.type===`stream_text_delta`){e.format===`text`&&E(r),await t.websocketSink?.sendTextDelta({sessionId:n.activeSessionId,channel:e.channel,messageId:q(r,t.defaultMessageId),user:t.user,text:r.text});return}e.format===`text`&&E(r);let i=q(r,t.defaultMessageId);if(r.type===`hitl_requested`){await G(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`hitl`,request:r.request}),await G(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`progress`,event:r});return}if(r.type===`start`){await G(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`start`,message:r.message});return}if(r.type===`session_reset`){await G(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 G(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:i,user:t.user,type:`progress`,event:r})}}function Qe(e,t,n,r,i){let a={dataDir:t.dataDir,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 $e(e,t,n,r){if(t.activeSessionId=r.sessionId,t.finalResult=r,r.error){await G(e,{sessionId:r.sessionId,channel:e.channel,messageId:n,user:e.user,type:`error`,message:r.error});return}await G(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 et(e,t,n,r){await G(e,{sessionId:t.finalResult?.sessionId??t.activeSessionId,channel:e.channel,messageId:n,user:e.user,type:`error`,message:`Fatal: ${r.message}`})}function tt(e,t){F.info(`run command started`,{channel:t.channel,dataDir:t.dataDir,sessionId:e.sessionId??`new`,messageId:e.messageId,output:t.format,hasCallback:!!e.callbackUrl,hasStream:!!e.streamUrl})}function nt(e,t,n){D(t,n),t.error?F.error(`run command failed: ${t.error}`):F.info(`run command succeeded`),e.end(),process.exit(t.error?1:0)}function rt(e,t){F.error(`run command error: ${t.message}`),T(`Fatal: ${t.message}`),e.end(),process.exit(1)}async function it(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 U({dataDir:e.dataDir,sessionId:e.sessionId,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}let t=new I(`run command`),{controller:n,cleanup:r}=qe(),i=null,a=e.channel??`WEB`,o=Je(e.sessionId);try{let r=await Ue(e);a=r.channel,tt(e,r);let s=We(e);i=s.sink,F.info(`external sink configured`,{callbackUrl:e.callbackUrl,streamUrl:e.streamUrl,streamEvents:e.streamEvents});let c=K(i,s.websocketSink,r.channel,e.messageId,e.user);await Xe(r,c,o);let l=e.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,u=await O(r.dataDir,l),d=await m(Qe(e,r,n,Ze(r,c,o),u));await $e(c,o,e.messageId,d),nt(t,d,r.format)}catch(n){let r=n;i&&await et(K(i,null,a,e.messageId,e.user),o,e.messageId,r),rt(t,r)}finally{await i?.close(),r()}}function at(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 ot(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(`--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 it(e)})}function st(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(`-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`,o=i===`export`?r.output===`text`?`text`:`json`:r.output===`json`?`json`:`text`;r.dataDir||(T(`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`&&(T(`Invalid channel: ${r.channel}. Must be 'H5', 'WEB', 'KLPA', 'TASK', 'CRON', or 'EIP_ASSISTANT'`),process.exit(1));try{if(i===`list`){ue(await u(r.dataDir,r.channel),o);return}if(r.sessionId||(T(`error: required option '-s, --session-id <id>' not specified`),process.exit(1)),i===`inspect`){de(await c(r.dataDir,r.sessionId),o);return}if(i===`export`){fe(await a(r.dataDir,r.sessionId),o);return}T(`Invalid sessions action: ${i}. Must be 'list', 'inspect', or 'export'`),process.exit(1)}catch(e){T(`${i===`inspect`?`Error inspecting session`:i===`export`?`Error exporting session`:`Error listing sessions`}: ${e.message}`),process.exit(1)}})}function ct(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(`
package/dist/program.js CHANGED
@@ -1 +1 @@
1
- import{n as e,t}from"./program-CJPDK5S0.js";export{t as createProgram,e as getDataDir};
1
+ import{n as e,t}from"./program-BcnstgMo.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.27",
3
+ "version": "0.0.28",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "aimax": "./dist/bin.js"
@@ -20,8 +20,8 @@
20
20
  "dependencies": {
21
21
  "commander": "^14.0.3",
22
22
  "gensign-node": "latest",
23
- "@gencode/agents": "0.0.28",
24
- "@gencode/shared": "0.0.9"
23
+ "@gencode/agents": "0.0.29",
24
+ "@gencode/shared": "0.0.10"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/node": "^22.0.0",