@gencode/cli 0.18.0 → 0.18.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/dist/bin.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-DpUbtUIV.js → program-1RuLgLYv.js} +2 -2
- package/dist/program.js +1 -1
- package/dist/{run-Bxgv6pqW.js → run-DgS7vRrF.js} +4 -4
- package/dist/{run-CIp69zrd.d.ts → run-xTw5VXAH.d.ts} +1 -0
- package/dist/run.d.ts +1 -1
- package/dist/run.js +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# @gencode/cli
|
|
2
2
|
|
|
3
|
+
## 0.18.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 875ff97: `aimax run` 的文本启动日志现在会在 Run Context 中按参数名显示 `team` 和 `parentSessionId`,便于排查团队运行与父会话关联。
|
|
8
|
+
- f943d95: 使用 `aimax run --channel CRON --parent-session-id <主会话ID>` 启动的定时任务,在继续把完整执行记录保存到 `.aimax/crons/<执行会话ID>/` 的同时,会在成功或失败终态把一条最终结论追加到 `.aimax/sessions/<主会话ID>/transcript.jsonl`。同一执行会话只追加一次;来源主会话不存在时任务会明确失败,避免创建无法展示的空壳会话。
|
|
9
|
+
- e8238b3: 新增显式最终产物登记:每个新的 root run 都应调用且只调用一次 `record_artifacts`,将已校验的文件或 URL 累计写入 Session 的 `artifacts.json` V2;没有产物时传入 `{ "artifacts": [] }`,历史轮次的调用不计入当前轮。漏调不会触发运行时终态门禁,也不会阻止运行成功结束;工具调用后的持久化失败仍会使运行失败。`--artifacts-url-whitelist` 按 hostname 限制 URL,未配置时允许全部域名。文件工具审计迁移到独立的 `changes.json` V1。运行结果、回调、WebSocket done 和 transcript 不再返回或推断 artifacts;Claude Code、Codex、OpenCode 与 Pi 通过各自运行时工具桥接登记,ACP 暂不支持。
|
|
10
|
+
- 0521d16: fix: edit_file tool supports files with mixed line endings
|
|
11
|
+
|
|
12
|
+
Fix edit_file tool failing with "old_string not found" when file uses CRLF (`\r\n`) line endings but the model returns `old_string` with LF (`\n`) line endings.
|
|
13
|
+
|
|
14
|
+
The tool now normalizes line endings automatically, ensuring it works correctly with both Windows and Unix formatted files.
|
|
15
|
+
|
|
16
|
+
- b7e60a9: 工具执行完成后,`tool_end.details` 现在会作为结构化 JSON 数据通过 callback/websocket 提供给 UI,并写入 `.aimax/sessions/<sessionId>/transcript.jsonl` 的 `tool_result.details`,便于页面展示、会话回放与审计。结构化 `tool_end.output` 不再重复包含顶层 `details`;该字段在当前轮和历史恢复的模型请求边界也会被移除,模型仍只接收工具的 `content`。
|
|
17
|
+
- Updated dependencies [f943d95]
|
|
18
|
+
- Updated dependencies [e8238b3]
|
|
19
|
+
- Updated dependencies [0521d16]
|
|
20
|
+
- Updated dependencies [b7e60a9]
|
|
21
|
+
- @gencode/agents@0.21.2
|
|
22
|
+
- @gencode/shared@0.7.2
|
|
23
|
+
|
|
24
|
+
## 0.18.1
|
|
25
|
+
|
|
26
|
+
### Patch Changes
|
|
27
|
+
|
|
28
|
+
- 0f9d5da: Agent Team 的协调提示词现使用英文,并要求协调 Agent 将成员职责可覆盖的实质性工作优先委派给团队成员;运行时会在 SubAgent 工具中提示精确成员选择和并行/串行协作方式。直接完成仅适用于简单答复、没有匹配成员或委派不可用的情况。
|
|
29
|
+
- c562e03: CRON 定时任务现在支持通过 `--parent-session-id <主会话ID>` 关联来源会话。调度器省略 `--session-id` 后,每次触发都会在 `.aimax/crons/<执行会话ID>/` 创建独立 transcript 和日志;callback 与 websocket 的 `sessionId` 表示本次执行,`parentSessionId` 表示来源主会话。生产调度配置需停止把主会话 ID 作为 `--session-id` 传入。
|
|
30
|
+
- Updated dependencies [0f9d5da]
|
|
31
|
+
- Updated dependencies [c562e03]
|
|
32
|
+
- @gencode/agents@0.21.1
|
|
33
|
+
- @gencode/shared@0.7.1
|
|
34
|
+
|
|
3
35
|
## 0.18.0
|
|
4
36
|
|
|
5
37
|
### Minor Changes
|
package/dist/bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import"./pkg-path-D6anqptM.js";import{b as e,x as t,y as n}from"./run-
|
|
2
|
+
import"./pkg-path-D6anqptM.js";import{b as e,x as t,y as n}from"./run-DgS7vRrF.js";import{t as r}from"./program-1RuLgLYv.js";function i(e){return e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e)}function a(e){let t=e.shutdownTimeoutMs??2e3,n=!1,r=(r,a)=>{if(e.logError(`Fatal ${r}: ${i(a)}`),n)return;n=!0;let o=setTimeout(()=>e.exit(1),t);typeof o.unref==`function`&&o.unref(),Promise.resolve().then(()=>e.shutdown()).catch(()=>{}).finally(()=>{clearTimeout(o),e.exit(1)})};e.proc.on(`uncaughtException`,e=>r(`uncaughtException`,e)),e.proc.on(`unhandledRejection`,e=>r(`unhandledRejection`,e))}const o=Date.now(),s=process.env.AIMAX_DATA_DIR,c=process.argv.includes(`run`)&&process.argv.includes(`--encrypt-sessions`),l=process.argv.includes(`run`)||process.argv.includes(`resume`);function u(e){for(let t=0;t<e.length;t++){let n=e[t];if(n===`--message-id`||n===`--messageId`)return e[t+1];if(n?.startsWith(`--message-id=`))return n.slice(13);if(n?.startsWith(`--messageId=`))return n.slice(12)}}s&&!c&&!l&&n(s,{messageId:u(process.argv)}),a({proc:process,logError:t=>e.error(t),shutdown:t,exit:e=>process.exit(e)}),e.info(`AIMax CLI starting (pid=${process.pid})`,{dataDir:s,encryptedRun:c,loggerDeferred:!!(s&&(c||l))}),r().parseAsync(process.argv).catch(t=>{e.error(`Unexpected error: ${t.message}`),process.exit(1)}).finally(()=>{let n=Date.now()-o;return e.info(`AIMax CLI exited (total uptime: ${n}ms)`),t()});export{};
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./pkg-path-D6anqptM.js";import{t as e}from"./run-
|
|
1
|
+
import"./pkg-path-D6anqptM.js";import{t as e}from"./run-DgS7vRrF.js";import{n as t,t as n}from"./program-1RuLgLYv.js";export{n as createProgram,e as executeRun,t as getDataDir};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{_ as e,a as t,b as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as ee,p as te,r as ne,s as f,u as p,v as m,y as h}from"./run-
|
|
1
|
+
import{_ as e,a as t,b as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as ee,p as te,r as ne,s as f,u as p,v as m,y as h}from"./run-DgS7vRrF.js";import{createRequire as re}from"node:module";import{Command as ie}from"commander";import{bootstrapMountLayout as ae,buildAimaxGoalCliHelpExtra as oe,deleteGoal as se,exportSession as ce,generateModelResponse as le,initializePluginSystem as g,inspectSession as ue,listAvailableSlashCommands as de,listSessionSummaries as fe,loadPendingHitl as pe,loadSessionExportSnapshots as me,loadSkillsWithPluginDirs as he,loadTranscript as ge,normalizePluginsConfig as _e,normalizeSessionStoreName as _,readGoal as v,resolveGoalObjective as ve,resolveMemoryProviderOrDefault as ye,resolvePendingHitl as be,runAgent as xe,sessionsDir as Se,transcriptPath as Ce,updateGoal as y,writeGoal as we}from"@gencode/agents";import{existsSync as b,mkdirSync as x,readFileSync as S,statSync as Te,writeFileSync as C}from"node:fs";import w,{basename as T,dirname as E,isAbsolute as D,join as O,relative as k,resolve as A}from"node:path";import j from"node:fs/promises";import{fileURLToPath as Ee}from"node:url";import{addAgent as De,addBinding as Oe,getAgentConfig as M,listAgents as ke,listBindings as N,loadAgentsConfig as P,normalizeAgentId as F,removeAgent as Ae,removeBindings as I,resolveAgentDir as je,resolveDefaultAgentId as L,updateAgentIdentity as Me}from"@gencode/agents/config";import{createHash as Ne,randomUUID as R}from"node:crypto";function Pe(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`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).action(async e=>{let t=e.output===`json`?`json`:`text`;try{i(await p(e.dataDir,e,async()=>ae(e.dataDir)),t)}catch(e){o(`Error bootstrapping data directory: ${e.message}`),process.exit(1)}})}function Fe(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`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).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||(o(`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`&&(o(`Invalid channel: ${r.channel}. Must be 'H5', 'WEB', 'KLPA', 'TASK', 'CRON', or 'EIP_ASSISTANT'`),process.exit(1));try{await p(r.dataDir,r,async()=>{let e=r.sessionStore?_(r.sessionStore):void 0;if(i===`list`){s(await fe(r.dataDir,r.channel,{storeName:e}),a);return}if(r.sessionId||(o(`error: required option '-s, --session-id <id>' not specified`),process.exit(1)),i===`inspect`){u(await ue(r.dataDir,r.sessionId,{storeName:e}),a);return}if(i===`export`){te(await ce(r.dataDir,r.sessionId,{storeName:e}),a);return}o(`Invalid sessions action: ${i}. Must be 'list', 'inspect', or 'export'`),process.exit(1)})}catch(e){o(`${i===`inspect`?`Error inspecting session`:i===`export`?`Error exporting session`:`Error listing sessions`}: ${e.message}`),process.exit(1)}})}function Ie(e){return w.join(e,`workspace`)}function Le(){let e=process.env.AIMAX_PLUGINS_BUNDLED_DIR;return e&&e.trim()||void 0}function Re(e,t){let n=[];n.push(`backend: ${e.backend}`),n.push(`provider: ${e.provider}${e.model?` (${e.model})`:``}`);let r=typeof e.custom?.providerSource==`string`?e.custom.providerSource:void 0,i=typeof e.custom?.providerId==`string`?e.custom.providerId:void 0,a=typeof e.custom?.pluginId==`string`?e.custom.pluginId:void 0;r&&n.push(`provider_source: ${r}`),i&&n.push(`provider_id: ${i}`),a&&n.push(`plugin_id: ${a}`),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}`));let o=Array.isArray(e.custom?.cliWarnings)?e.custom.cliWarnings.filter(e=>typeof e==`string`&&e.length>0):[];for(let e of o)n.push(`warning: ${e}`);return n.join(`
|
|
2
2
|
`)}function ze(e){let t=e.level===`error`?`plugin error`:`plugin warning`;return e.pluginId?`${t} (${e.pluginId}): ${e.message}`:`${t}: ${e.message}`}function Be(e){if(!e||e===`cli`)return`cli`;if(e===`cron`)return`cron`;throw Error(`Unsupported dream trigger: ${e}. Expected "cli" or "cron".`)}async function Ve(e){let t=[],n;try{n=await f(e.dataDir,e.pluginsConfig)}catch(e){t.push(`failed to load plugins config: ${e.message}`)}if(!e.shouldInitialize&&!n)return{warnings:t};try{let r=g({config:n,dataDir:e.dataDir,workspaceDir:Ie(e.dataDir),bundledDir:Le()});return t.push(...r.diagnostics.map(ze)),{pluginSystem:r,warnings:t}}catch(e){return t.push(`failed to initialize plugin system: ${e.message}`),{warnings:t}}}async function z(e){let t=w.join(e.dataDir,`.aimax`),{pluginSystem:n,warnings:r}=await Ve({dataDir:e.dataDir,pluginsConfig:e.pluginsConfig,shouldInitialize:!!(e.requirePluginSystem||e.provider||e.providerPlugin)}),i=n?.normalizedConfig.slots.memory,a=e.providerPlugin?.trim()||(e.provider?void 0:i),o=ye({providerId:e.provider,pluginId:a,dataDir:e.dataDir,memoryDir:t,includeSessions:e.includeSessions});return o.providerSource===`plugin`?{provider:o.provider,providerId:o.providerId,pluginId:o.pluginId,providerOrigin:`plugin`,warnings:r,pluginSystem:n}:((a||e.provider)&&r.push(`requested memory provider was not resolved; falling back to builtin provider`),{provider:o.provider,providerId:`builtin`,providerOrigin:`builtin`,warnings:r,pluginSystem:n})}function He(e,t,n){let r={...e.custom??{},providerSource:t.providerOrigin,providerId:t.providerId,pluginId:t.pluginId,cliWarnings:t.warnings},i={...e,custom:r};return n&&t.providerOrigin===`plugin`?i.custom={...r,note:`deep probe details are provider-defined for plugin memory providers`}:n&&(i.custom={...r,note:`deep probe is only supported by builtin provider`}),i}function Ue(t){let n=t.command(`memory`).description(`Manage semantic memory indexing and search`),r=e=>e.option(`--plugins-config <path>`,`Plugins config file path`);r(n.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`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).action(async t=>{let n=t.output===`json`?`json`:`text`;try{await p(t.dataDir,t,async()=>{let r=await z({dataDir:t.dataDir,provider:t.provider,providerPlugin:t.providerPlugin,pluginsConfig:t.pluginsConfig,includeSessions:t.includeSessions});t.index&&r.provider.sync&&await r.provider.sync(`cli-status`);let i=He(r.provider.status(),r,t.deep);e(n===`json`?JSON.stringify(i,null,2):Re(i,t.deep))})}catch(e){o(`Error getting memory status: ${e.message}`),process.exit(1)}}),r(n.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(`--rebuild`,`Force full rebuild from Markdown source`).option(`--verbose`,`Verbose output`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).action(async t=>{try{await p(t.dataDir,t,async()=>{let n=await z({dataDir:t.dataDir,provider:t.provider,providerPlugin:t.providerPlugin,pluginsConfig:t.pluginsConfig,includeSessions:t.includeSessions}),r;if(n.provider.sync&&(await n.provider.sync(t.rebuild?`cli-rebuild`:`cli-index`),r=n.provider.status().custom?.lastRebuildSummary),n.warnings.length>0)for(let e of n.warnings)o(`Warning: ${e}`);t.verbose&&r&&e(JSON.stringify(r,null,2)),e(t.rebuild?`Memory index rebuilt.`:`Memory index refreshed.`)})}catch(e){o(`Error indexing memory: ${e.message}`),process.exit(1)}}),r(n.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`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).action(async(t,n)=>{let r=n.output===`json`?`json`:`text`,i=n.query?.trim()||t?.trim();i||(o(`Query is required: provide [query] or --query <text>`),process.exit(1));try{await p(n.dataDir,n,async()=>{let t=await(await z({dataDir:n.dataDir,provider:n.provider,providerPlugin:n.providerPlugin,pluginsConfig:n.pluginsConfig,includeSessions:n.includeSessions})).provider.search(i);if(r===`json`){e(JSON.stringify(t,null,2));return}if(t.length===0){e(`No results found for: ${i}`);return}e(t.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(`
|
|
3
3
|
`))})}catch(e){o(`Error searching memory: ${e.message}`),process.exit(1)}}),r(n.command(`dream`)).description(`Trigger Dream Gate host hook for memory plugins`).requiredOption(`-d, --data-dir <path>`,`Data directory path`).option(`--provider <id>`,`Memory provider id`).option(`--provider-plugin <id>`,`Memory provider plugin id`).option(`--trigger <mode>`,`Dream Gate trigger mode: cli (default) or cron`,`cli`).option(`--dry-run`,`Return hook results without plugin-side mutation`).option(`--output <format>`,`Output format: text (default) or json`,`text`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).action(async t=>{let n=t.output===`json`?`json`:`text`;try{await p(t.dataDir,t,async()=>{let r=Be(t.trigger),i=await z({dataDir:t.dataDir,provider:t.provider,providerPlugin:t.providerPlugin,pluginsConfig:t.pluginsConfig,requirePluginSystem:!0}),a=i.pluginSystem?await i.pluginSystem.registry.hooks.dispatch(`dream_gate`,{dataDir:t.dataDir,memoryDir:w.join(t.dataDir,`.aimax`),providerId:i.providerId,pluginId:i.pluginId,trigger:r,dryRun:!!t.dryRun},{workspaceDir:Ie(t.dataDir)}):[],o={ok:!0,trigger:r,providerSource:i.providerOrigin,providerId:i.providerId,pluginId:i.pluginId,resultCount:a.length,results:a,warnings:i.warnings};if(n===`json`){e(JSON.stringify(o,null,2));return}e(`trigger: ${o.trigger}`),e(`provider_source: ${o.providerSource}`),e(`provider_id: ${o.providerId}`),o.pluginId&&e(`plugin_id: ${o.pluginId}`),e(`result_count: ${o.resultCount}`),o.results.length===0?e(`note: no dream_gate hook registered`):e(`results: ${JSON.stringify(o.results)}`);for(let t of o.warnings)e(`warning: ${t}`)})}catch(e){o(`Error running dream gate: ${e.message}`),process.exit(1)}})}function We(e){return`${e.match.accountId?`${e.match.channel}:${e.match.accountId}`:e.match.channel} -> ${e.agentId}`}function Ge(e){return async t=>{let n=await P(t),r=ke(n),i=N(n);if(L(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=je(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(` - ${We(e)}`)}}}}function Ke(e,t){return async n=>{M(await P(n),F(e))&&(console.error(`Agent "${e}" already exists.`),process.exit(1)),await De(n,{id:e,name:t.name,model:t.model,default:t.default})||(console.error(`Agent "${e}" already exists.`),process.exit(1));let r=je(n,e);console.log(`Agent "${e}" added successfully.`),console.log(` Agent dir: ${r}`)}}function qe(e){return async t=>{let n=M(await P(t),F(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 Ae(t,e)||(console.error(`Failed to delete agent "${e}".`),process.exit(1)),console.log(`Agent "${e}" deleted.`)}}function Je(e){return async t=>{let n=await P(t),r=e.agent??L(n);M(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 Oe(t,{agentId:r,match:{channel:e,accountId:a||void 0}}),console.log(`Binding added: ${n} -> ${r}`)}}}function Ye(e){return async t=>{let n=await P(t),r=e.agent??L(n);if(M(n,r)||(console.error(`Agent "${r}" not found.`),process.exit(1)),e.all){let e=await I(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 I(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 Xe(e){return async t=>{let n=N(await P(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(` ${We(e)}`)}}function Ze(e){return async t=>{let n=await P(t),r=e.agent??L(n);M(n,r)||(console.error(`Agent "${r}" not found.`),process.exit(1)),await Me(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 Qe(e,t){let n=e.command(`agents`).description(`Manage agents`),r=e=>e.option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`);r(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 p(n,e,async()=>{await Ge(e)(n)})}),r(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 p(r,n,async()=>{await Ke(e,n)(r)})}),r(n.command(`delete <id>`).description(`Delete an agent`)).action(async(e,n)=>{let r=t();await p(r,n,async()=>{await qe(e)(r)})}),r(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 p(n,e,async()=>{await Je(e)(n)})}),r(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 p(n,e,async()=>{await Ye(e)(n)})}),r(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 p(n,e,async()=>{await Xe(e)(n)})}),r(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 p(n,e,async()=>{await Ze(e)(n)})})}function B(e){return w.join(e,`workspace`)}function V(){let e=process.env.AIMAX_PLUGINS_BUNDLED_DIR;return e&&e.trim()||void 0}function $e(t){if(t.length===0){e(`No plugins discovered.`);return}for(let n of t){let t=n.status.padEnd(8,` `);e(`${n.id} ${t} ${n.origin} ${n.source}`)}}function et(t){e(`id: ${t.id}`),e(`status: ${t.status}`),e(`origin: ${t.origin}`),e(`source: ${t.source}`),e(`enabled: ${t.enabled}`),t.error&&e(`error: ${t.error}`),e(`tools: ${t.toolCount}`),e(`hooks: ${t.hookCount}`),t.skills.length>0&&e(`skills: ${t.skills.join(`, `)}`)}function H(e){return Array.from(new Set((e??[]).map(e=>e.trim()).filter(Boolean)))}function tt(t){if(t.length===0){e(`LLM allowlist is empty.`);return}for(let n of t)e(n)}function nt(t,n){let i=t.command(`plugins`).description(`Manage AIMax plugins`),a=e=>e.option(`--plugins-config <path>`,`Plugins config file path`),s=e=>e.option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`);s(a(i.command(`list`))).description(`List discovered plugins`).option(`-d, --data-dir <path>`,`Data directory path`).action(async e=>{let t=e.dataDir??n();await p(t,e,async()=>{$e(g({config:await f(t,e.pluginsConfig),dataDir:t,workspaceDir:B(t),bundledDir:V()}).registry.plugins)})}),s(a(i.command(`info`))).description(`Show plugin details`).argument(`<id>`,`Plugin id`).option(`-d, --data-dir <path>`,`Data directory path`).action(async(e,t)=>{let r=t.dataDir??n();await p(r,t,async()=>{let n=g({config:await f(r,t.pluginsConfig),dataDir:r,workspaceDir:B(r),bundledDir:V()}).registry.plugins.find(t=>t.id===e);n||(o(`Plugin not found: ${e}`),process.exit(1)),et(n)})}),s(a(i.command(`enable`))).description(`Enable a plugin`).argument(`<id>`,`Plugin id`).option(`-d, --data-dir <path>`,`Data directory path`).action(async(t,i)=>{let a=i.dataDir??n();await p(a,i,async()=>{let n=await f(a,i.pluginsConfig)??{},s=_e(n);g({config:n,dataDir:a,workspaceDir:B(a),bundledDir:V()}).registry.plugins.some(e=>e.id===t)||(o(`Plugin not found: ${t}`),process.exit(1)),await r(a,{...n,entries:{...n.entries,[t]:{...n.entries?.[t]??{},enabled:!0}}},i.pluginsConfig),e(`Enabled ${t}`),s.allow.length>0&&!s.allow.includes(t)&&e(`Note: plugins.allow is set; add this plugin id to allowlist if needed.`)})}),s(a(i.command(`disable`))).description(`Disable a plugin`).argument(`<id>`,`Plugin id`).option(`-d, --data-dir <path>`,`Data directory path`).action(async(t,i)=>{let a=i.dataDir??n();await p(a,i,async()=>{let n=await f(a,i.pluginsConfig)??{};g({config:n,dataDir:a,workspaceDir:B(a),bundledDir:V()}).registry.plugins.some(e=>e.id===t)||(o(`Plugin not found: ${t}`),process.exit(1)),await r(a,{...n,entries:{...n.entries,[t]:{...n.entries?.[t]??{},enabled:!1}}},i.pluginsConfig),e(`Disabled ${t}`)})}),s(a(i.command(`doctor`))).description(`Validate plugin configuration`).option(`-d, --data-dir <path>`,`Data directory path`).action(async t=>{let r=t.dataDir??n();await p(r,t,async()=>{let n=g({config:await f(r,t.pluginsConfig),dataDir:r,workspaceDir:B(r),bundledDir:V()});if(n.diagnostics.length===0){e(`No plugin issues detected.`);return}for(let t of n.diagnostics)e(`${t.level===`error`?`ERROR`:`WARN`}${t.pluginId?` ${t.pluginId}`:``}: ${t.message}`);n.diagnostics.some(e=>e.level===`error`)&&process.exit(1)})});let c=i.command(`llm-allow`).description(`Manage plugin LLM allowlist`);s(a(c.command(`list`))).description(`List LLM allowlist entries`).option(`-d, --data-dir <path>`,`Data directory path`).action(async e=>{let t=e.dataDir??n();await p(t,e,async()=>{tt(H((await f(t,e.pluginsConfig))?.llmAllowlist))})}),s(a(c.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(t,i)=>{let a=i.dataDir??n();await p(a,i,async()=>{let n=await f(a,i.pluginsConfig)??{},o=H([...n.llmAllowlist??[],...t]);await r(a,{...n,llmAllowlist:o},i.pluginsConfig),e(`LLM allowlist updated (${o.length} entries).`)})}),s(a(c.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(t,i)=>{let a=i.dataDir??n();await p(a,i,async()=>{let n=await f(a,i.pluginsConfig)??{},o=new Set(t.map(e=>e.trim()).filter(Boolean)),s=H(n.llmAllowlist).filter(e=>!o.has(e));await r(a,{...n,llmAllowlist:s},i.pluginsConfig),e(`LLM allowlist updated (${s.length} entries).`)})}),s(a(c.command(`clear`))).description(`Clear the LLM allowlist`).option(`-d, --data-dir <path>`,`Data directory path`).action(async t=>{let i=t.dataDir??n();await p(i,t,async()=>{await r(i,{...await f(i,t.pluginsConfig)??{},llmAllowlist:[]},t.pluginsConfig),e(`LLM allowlist cleared.`)})})}function rt(t){t.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`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).action(async t=>{let n=t.output===`json`?`json`:`text`;try{await p(t.dataDir,t,async()=>{let r=de(await he(t.dataDir,[]));if(n===`json`){e(JSON.stringify(r,null,2));return}e(`Commands`),e(` builtin: ${r.builtin.map(e=>e.name).join(` | `)}`),r.skillCommands.length>0?e(` skills: ${r.skillCommands.map(e=>e.name).join(` | `)}`):e(` skills: (none)`)})}catch(e){o(`Error listing commands: ${e.message}`),process.exit(1)}})}function U(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 W(e){if(!e.sessionId)throw Error(`Session ID is required (--session-id or -s)`);return e.sessionId}function G(e){return e?_(e):void 0}async function it(e){let t={storeName:e.sessionStoreName},n=e.objective.trim(),r=await v(e.dataDir,e.sessionId,t);if(!r||(await ve(e.dataDir,e.sessionId,r,t)).trim()!==n)return we(e.dataDir,e.sessionId,{goalId:R(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:`cli`});if(r.status===`complete`)return r;let i={};return r.status===`paused`&&(i.status=`active`),e.tokenBudget!==void 0&&e.tokenBudget!==r.tokenBudget&&(i.tokenBudget=e.tokenBudget),Object.keys(i).length===0?r:await y(e.dataDir,e.sessionId,i,{...t,eventSource:`cli`})}async function at(t,n){let r=U(n),i=W(n),a=G(n.sessionStore),s=t.trim();s||(o(`error: objective cannot be empty`),process.exit(1));let c=n.tokenBudget===void 0||n.tokenBudget===`0`||n.tokenBudget===``?null:Number(n.tokenBudget);c!==null&&(Number.isNaN(c)||c<=0)&&(o(`error: --token-budget must be a positive integer, or 0 for unlimited`),process.exit(1));let l=await it({dataDir:r,sessionId:i,sessionStoreName:a,objective:s,tokenBudget:c});e(JSON.stringify({goal:l},null,2))}async function ot(t){let n=U(t),r=W(t),i=G(t.sessionStore),a=await v(n,r,{storeName:i});if(!a){e(JSON.stringify({goal:null},null,2));return}let o=await ve(n,r,a,{storeName:i});e(JSON.stringify({goal:{...a,objective:o}},null,2))}async function st(t){let n=U(t),r=W(t),i=G(t.sessionStore),a=await v(n,r,{storeName:i});a||(o(`error: no goal exists for this session`),process.exit(1)),a.status===`complete`&&(o(`error: cannot pause a completed goal`),process.exit(1));let s=await y(n,r,{status:`paused`},{storeName:i,eventSource:`cli`});e(JSON.stringify({goal:s},null,2))}async function ct(t){let n=U(t),r=W(t),i=G(t.sessionStore),a=await v(n,r,{storeName:i});if(a||(o(`error: no goal exists for this session`),process.exit(1)),a.status===`complete`&&(o(`error: cannot resume a completed goal`),process.exit(1)),a.status===`budget_limited`&&(o(`error: cannot resume a budget-limited goal; clear or replace it instead`),process.exit(1)),a.status===`active`){e(JSON.stringify({goal:a},null,2));return}let s=await y(n,r,{status:`active`},{storeName:i,eventSource:`cli`});e(JSON.stringify({goal:s},null,2))}async function lt(t){let n=await se(U(t),W(t),{storeName:G(t.sessionStore),eventSource:`cli`});e(JSON.stringify({cleared:n},null,2))}function ut(e){let t=e.command(`goal`).description(`Manage thread goals for a session`).addHelpText(`after`,oe());t.command(`set <objective>`).description(`Set or replace the thread goal (creates new goalId)`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).requiredOption(`-s, --session-id <id>`,`Session ID`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).option(`--token-budget <n>`,`Optional token budget (positive integer, or 0 for unlimited)`).action(async(e,t)=>{try{await at(e,t)}catch(e){o(`error: ${e.message}`),process.exit(1)}}),t.command(`get`).description(`Get the current goal as JSON`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).requiredOption(`-s, --session-id <id>`,`Session ID`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).action(async e=>{try{await ot(e)}catch(e){o(`error: ${e.message}`),process.exit(1)}}),t.command(`pause`).description(`Pause the current goal`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).requiredOption(`-s, --session-id <id>`,`Session ID`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).action(async e=>{try{await st(e)}catch(e){o(`error: ${e.message}`),process.exit(1)}}),t.command(`resume`).description(`Resume a paused goal`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).requiredOption(`-s, --session-id <id>`,`Session ID`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).action(async e=>{try{await ct(e)}catch(e){o(`error: ${e.message}`),process.exit(1)}}),t.command(`clear`).description(`Clear the current goal`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).requiredOption(`-s, --session-id <id>`,`Session ID`).option(`--session-store <name>`,`Session store directory under .aimax (default: sessions)`).action(async e=>{try{await lt(e)}catch(e){o(`error: ${e.message}`),process.exit(1)}})}const dt=[`progress`,`error`,`hitl`];function ft(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 pt(e){if(!e?.trim())return new Set(dt);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(dt)}function mt(e){return e?_(e):void 0}function ht(e){let n=[];return e.callbackUrl&&n.push(new t(e.callbackUrl)),e.streamUrl&&n.push(new c(e.streamUrl,pt(e.streamEvents),e.streamAuthToken)),new ee(n)}async function gt(e){let t=ft(e);await p(t,e,async()=>{h(t,{messageId:e.messageId});let r=new m(`cancel command`),i=e.channel??`WEB`,s=e.output===`json`?`json`:`text`,c=ht(e),l=mt(e.sessionStore);try{let n=await pe(t,e.sessionId,{storeName:l});if(!n)throw Error(`No pending HITL request found for session "${e.sessionId}"`);let o=e.requestId??n.request.requestId;if(n.request.requestId!==o)throw Error(`Request ID mismatch: pending is "${n.request.requestId}", got "${o}"`);if(!(await be({dataDir:t,sessionStoreName:l,sessionId:e.sessionId,requestId:o,resolution:{requestId:o,sessionId:e.sessionId,action:`cancel`,submittedAt:new Date().toISOString(),submittedBy:{channel:i}}})).state)throw Error(`Failed to cancel HITL request`);let u={type:`hitl_cancelled`,sessionId:e.sessionId,requestId:o,reason:e.reason??`cancelled by operator`};s===`text`&&a(u),await c.send({type:`progress`,sessionId:e.sessionId,channel:i,messageId:e.messageId,event:u}),r.end(),process.exit(0)}catch(t){let a=t;await c.send({type:`error`,sessionId:e.sessionId,channel:i,messageId:e.messageId,message:a.message}),n.error(`cancel command error: ${a.message}`),o(`Fatal: ${a.message}`),r.end(),process.exit(1)}finally{await c.close()}})}function _t(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`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).action(async e=>{await gt(e)})}function vt(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 yt(e){return e.query?.trim()||void 0}function bt(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw Error(`--timeout must be a positive number of milliseconds`);return t}function xt(e){if(!e)return;let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Error(`--max-tokens must be a positive integer`);return t}async function St(e){if(e.filePath){if(!w.isAbsolute(e.filePath))throw Error(`--file-path must be an absolute path`);try{await j.access(e.filePath)}catch(e){throw Error(`Failed to access --file-path: ${e.message}`)}return{source:`file`,filePath:e.filePath}}let t=e.content;if(!t||!t.trim())throw Error(`Either --file-path or --content must be provided`);return{source:`content`,content:t}}async function Ct(t){let r=null;try{let i=vt(t);h(i,{messageId:t.messageId}),r=new m(`summarize command`);let a=yt(t),o=await St(t),s=l({apiFormat:t.apiFormat,baseUrl:t.baseUrl,apiKey:t.apiKey,model:t.model,contextWindow:2e5}),c=bt(t.timeout),u=xt(t.maxTokens);n.info(`summarize command started`,{dataDir:i,source:o.source,filePath:o.source===`file`?o.filePath:void 0,queryLength:a?.length,contentLength:o.source===`content`?o.content.length:void 0,timeoutMs:c,maxTokens:u});let d=await xe({dataDir:i,channel:`WEB`,messageId:t.messageId,message:wt(o,a),llm:{...s,maxTokens:u},timeoutMs:c});e(d.text.trim()),n.info(`summarize command succeeded`,{source:o.source,summaryLength:d.text.length,durationMs:d.durationMs}),r.end()}catch(e){n.error(`summarize command error: ${e.message}`),o(`Fatal: ${e.message}`),r?.end(),process.exit(1)}}function wt(e,t){return e.source===`file`?[t?`Summarize exactly one file for the query below.`:`Summarize exactly one file.`,`Read only the absolute file path provided here. Do not search, browse, read other files, execute commands, modify files, or perform any other processing.`,`Return only the summary text.`,``,...t?[`Query:\n${t}`,``]:[],`Input source: file`,`File path: ${e.filePath}`].join(`
|
|
4
4
|
`):[t?`Summarize the provided content for the query below.`:`Summarize the provided content.`,t?`Use only the provided content and query. Do not search, browse, read files, execute commands, modify files, or perform any other processing.`:`Use only the provided content. Do not search, browse, read files, execute commands, modify files, or perform any other processing.`,`Return only the summary text.`,``,...t?[`Query:\n${t}`,``]:[],`Input source: content`,`Source content:`,`<source>`,e.content,`</source>`].join(`
|
|
5
|
-
`)}function Tt(e){e.command(`summarize`).description(`Summarize one absolute file path or inline content`).option(`--file-path <path>`,`Absolute file path to summarize`).option(`--content <text>`,`Inline text content to summarize when --file-path is not provided`).option(`--query <text>`,`Optional search target or current description to focus the summary`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).option(`--base-url <url>`,`LLM API base URL (overrides AIMAX_BASE_URL)`).option(`--api-format <format>`,`LLM API format: openai-completions or anthropic-messages (overrides AIMAX_API_FORMAT)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY / AIMAX_LLM_API_KEY)`).option(`--model <name>`,`LLM model name (overrides AIMAX_MODEL)`).option(`--timeout <ms>`,`Execution timeout in milliseconds`).option(`--max-tokens <number>`,`Maximum number of tokens for model output`).option(`--message-id <id>`,`Message ID for log correlation`).action(async e=>{await Ct(e)})}function Et(e){let t=e.input?.trim();if(!t)throw Error(`--input must be provided`);return t}function Dt(e){return e.system?.trim()||void 0}function Ot(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw Error(`--timeout must be a positive number of milliseconds`);return t}function kt(e){if(!e)return;let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Error(`--max-tokens must be a positive integer`);return t}async function At(t){let r=null;try{let i=t.dataDir??process.env.AIMAX_DATA_DIR;i&&h(i,{messageId:t.messageId}),r=new m(`generate command`);let a=Et(t),o=Dt(t),s=l({apiFormat:t.apiFormat,baseUrl:t.baseUrl,apiKey:t.apiKey,model:t.model,contextWindow:2e5}),c=Ot(t.timeout),u=kt(t.maxTokens);n.info(`generate command started`,{dataDir:i,inputLength:a.length,systemLength:o?.length,timeoutMs:c,maxTokens:u});let d=await le({llm:{...s,maxTokens:u},input:a,system:o,timeoutMs:c});e(d.text.trim()),n.info(`generate command succeeded`,{outputLength:d.text.length,durationMs:d.durationMs}),r.end()}catch(e){n.error(`generate command error: ${e.message}`),o(`Fatal: ${e.message}`),r?.end(),process.exit(1)}}function jt(e){e.command(`generate`).description(`Send one input to the model and print one response without running the agent loop`).option(`--input <text>`,`Input text to send to the model`).option(`--system <text>`,`Optional system instruction for this single model call`).option(`-d, --data-dir <path>`,`Optional data directory for CLI logs (overrides AIMAX_DATA_DIR)`).option(`--base-url <url>`,`LLM API base URL (overrides AIMAX_BASE_URL)`).option(`--api-format <format>`,`LLM API format: openai-completions or anthropic-messages (overrides AIMAX_API_FORMAT)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY / AIMAX_LLM_API_KEY)`).option(`--model <name>`,`LLM model name (overrides AIMAX_MODEL)`).option(`--timeout <ms>`,`Execution timeout in milliseconds`).option(`--max-tokens <number>`,`Maximum number of tokens for model output`).option(`--message-id <id>`,`Message ID for log correlation`).action(async e=>{await At(e)})}const Mt={accent:`#8abeb7`,border:`#5f87ff`,borderAccent:`#00d7ff`,borderMuted:`#505050`,success:`#b5bd68`,error:`#cc6666`,warning:`#ffff00`,muted:`#808080`,dim:`#666666`,text:`#d4d4d4`,thinkingText:`#808080`,selectedBg:`#3a3a4a`,userMessageBg:`#343541`,userMessageText:`#d4d4d4`,customMessageBg:`#2d2838`,customMessageText:`#d4d4d4`,customMessageLabel:`#9575cd`,toolPendingBg:`#282832`,toolSuccessBg:`#283228`,toolErrorBg:`#3c2828`,toolTitle:`#d4d4d4`,toolOutput:`#808080`,mdHeading:`#f0c674`,mdLink:`#81a2be`,mdLinkUrl:`#666666`,mdCode:`#8abeb7`,mdCodeBlock:`#b5bd68`,mdCodeBlockBorder:`#808080`,mdQuote:`#808080`,mdQuoteBorder:`#808080`,mdHr:`#808080`,mdListBullet:`#8abeb7`,toolDiffAdded:`#b5bd68`,toolDiffRemoved:`#cc6666`,toolDiffContext:`#808080`,syntaxComment:`#6A9955`,syntaxKeyword:`#569CD6`,syntaxFunction:`#DCDCAA`,syntaxVariable:`#9CDCFE`,syntaxString:`#CE9178`,syntaxNumber:`#B5CEA8`,syntaxType:`#4EC9B0`,syntaxOperator:`#D4D4D4`,syntaxPunctuation:`#D4D4D4`,thinkingOff:`#505050`,thinkingMinimal:`#6e6e6e`,thinkingLow:`#5f87af`,thinkingMedium:`#81a2be`,thinkingHigh:`#b294bb`,thinkingXhigh:`#d183e8`,bashMode:`#b5bd68`},Nt=`#18181e`,Pt=`#1e1e24`,Ft=`#3c3728`;function It(e){if(!e||typeof e!=`object`)return!1;let t=e.role;return t===`user`||t===`assistant`||t===`tool_result`||t===`compaction`}function K(e){return!e||typeof e!=`object`?!1:typeof e.type==`string`}function q(e){return{type:`text`,text:e}}function Lt(e){return{type:`thinking`,thinking:e}}function Rt(e,t){let n=e.timestamp,r=typeof n==`string`&&n?n:e.content;return`${e.role}\0${r}\0${t}`}function zt(e,t,n){let r=Rt(e,t);for(let e=0;e<100;e++){let t=Ne(`sha256`).update(`${r}\0${e}`).digest(`hex`).slice(0,8);if(!n.has(t))return n.add(t),t}let i=Ne(`sha256`).update(`${r}\0fallback`).digest(`hex`);return n.add(i),i}function Bt(e,t){let n=new Set,r=null,i=[],a={type:`session`,version:3,id:t?.sessionId??R(),timestamp:e.find(e=>e.timestamp)?.timestamp??new Date().toISOString(),cwd:t?.cwd??process.cwd()};for(let[t,a]of e.entries()){let e=zt(a,t,n),o={id:e,parentId:r,timestamp:a.timestamp};if(a.role===`user`)i.push({type:`message`,...o,message:{role:`user`,content:[q(a.content)]}});else if(a.role===`assistant`){let e=[];a.thinking?.trim()&&e.push(Lt(a.thinking.trim())),a.content.trim()&&e.push(q(a.content));for(let t of a.toolCalls??[])e.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});a.errorMessage&&e.push(q(a.errorMessage)),i.push({type:`message`,...o,message:{role:`assistant`,content:e,...a.stopReason?{stopReason:a.stopReason}:{}}})}else if(a.role===`tool_result`){let e=a.content;a.toolResultRef?.preview&&!e.includes(a.toolResultRef.preview)&&(e=`${e}\n\nPreview:\n${a.toolResultRef.preview}`),a.toolResultRef?.storagePath&&(e=`${e}\n\n[Full output: ${a.toolResultRef.storagePath}]`),i.push({type:`message`,...o,message:{role:`toolResult`,toolCallId:a.toolCallId,toolName:a.toolName,content:[q(e)],isError:a.isError}})}else a.role===`compaction`&&i.push({type:`compaction`,...o,summary:a.content,firstKeptEntryId:r??e,tokensBefore:0});r=e}return{header:a,entries:i,leafId:r}}function Vt(e,t){let n=e.trim().split(`
|
|
5
|
+
`)}function Tt(e){e.command(`summarize`).description(`Summarize one absolute file path or inline content`).option(`--file-path <path>`,`Absolute file path to summarize`).option(`--content <text>`,`Inline text content to summarize when --file-path is not provided`).option(`--query <text>`,`Optional search target or current description to focus the summary`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).option(`--base-url <url>`,`LLM API base URL (overrides AIMAX_BASE_URL)`).option(`--api-format <format>`,`LLM API format: openai-completions or anthropic-messages (overrides AIMAX_API_FORMAT)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY / AIMAX_LLM_API_KEY)`).option(`--model <name>`,`LLM model name (overrides AIMAX_MODEL)`).option(`--timeout <ms>`,`Execution timeout in milliseconds`).option(`--max-tokens <number>`,`Maximum number of tokens for model output`).option(`--message-id <id>`,`Message ID for log correlation`).action(async e=>{await Ct(e)})}function Et(e){let t=e.input?.trim();if(!t)throw Error(`--input must be provided`);return t}function Dt(e){return e.system?.trim()||void 0}function Ot(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw Error(`--timeout must be a positive number of milliseconds`);return t}function kt(e){if(!e)return;let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Error(`--max-tokens must be a positive integer`);return t}async function At(t){let r=null;try{let i=t.dataDir??process.env.AIMAX_DATA_DIR;i&&h(i,{messageId:t.messageId}),r=new m(`generate command`);let a=Et(t),o=Dt(t),s=l({apiFormat:t.apiFormat,baseUrl:t.baseUrl,apiKey:t.apiKey,model:t.model,contextWindow:2e5}),c=Ot(t.timeout),u=kt(t.maxTokens);n.info(`generate command started`,{dataDir:i,inputLength:a.length,systemLength:o?.length,timeoutMs:c,maxTokens:u});let d=await le({llm:{...s,maxTokens:u},input:a,system:o,timeoutMs:c});e(d.text.trim()),n.info(`generate command succeeded`,{outputLength:d.text.length,durationMs:d.durationMs}),r.end()}catch(e){n.error(`generate command error: ${e.message}`),o(`Fatal: ${e.message}`),r?.end(),process.exit(1)}}function jt(e){e.command(`generate`).description(`Send one input to the model and print one response without running the agent loop`).option(`--input <text>`,`Input text to send to the model`).option(`--system <text>`,`Optional system instruction for this single model call`).option(`-d, --data-dir <path>`,`Optional data directory for CLI logs (overrides AIMAX_DATA_DIR)`).option(`--base-url <url>`,`LLM API base URL (overrides AIMAX_BASE_URL)`).option(`--api-format <format>`,`LLM API format: openai-completions or anthropic-messages (overrides AIMAX_API_FORMAT)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY / AIMAX_LLM_API_KEY)`).option(`--model <name>`,`LLM model name (overrides AIMAX_MODEL)`).option(`--timeout <ms>`,`Execution timeout in milliseconds`).option(`--max-tokens <number>`,`Maximum number of tokens for model output`).option(`--message-id <id>`,`Message ID for log correlation`).action(async e=>{await At(e)})}const Mt={accent:`#8abeb7`,border:`#5f87ff`,borderAccent:`#00d7ff`,borderMuted:`#505050`,success:`#b5bd68`,error:`#cc6666`,warning:`#ffff00`,muted:`#808080`,dim:`#666666`,text:`#d4d4d4`,thinkingText:`#808080`,selectedBg:`#3a3a4a`,userMessageBg:`#343541`,userMessageText:`#d4d4d4`,customMessageBg:`#2d2838`,customMessageText:`#d4d4d4`,customMessageLabel:`#9575cd`,toolPendingBg:`#282832`,toolSuccessBg:`#283228`,toolErrorBg:`#3c2828`,toolTitle:`#d4d4d4`,toolOutput:`#808080`,mdHeading:`#f0c674`,mdLink:`#81a2be`,mdLinkUrl:`#666666`,mdCode:`#8abeb7`,mdCodeBlock:`#b5bd68`,mdCodeBlockBorder:`#808080`,mdQuote:`#808080`,mdQuoteBorder:`#808080`,mdHr:`#808080`,mdListBullet:`#8abeb7`,toolDiffAdded:`#b5bd68`,toolDiffRemoved:`#cc6666`,toolDiffContext:`#808080`,syntaxComment:`#6A9955`,syntaxKeyword:`#569CD6`,syntaxFunction:`#DCDCAA`,syntaxVariable:`#9CDCFE`,syntaxString:`#CE9178`,syntaxNumber:`#B5CEA8`,syntaxType:`#4EC9B0`,syntaxOperator:`#D4D4D4`,syntaxPunctuation:`#D4D4D4`,thinkingOff:`#505050`,thinkingMinimal:`#6e6e6e`,thinkingLow:`#5f87af`,thinkingMedium:`#81a2be`,thinkingHigh:`#b294bb`,thinkingXhigh:`#d183e8`,bashMode:`#b5bd68`},Nt=`#18181e`,Pt=`#1e1e24`,Ft=`#3c3728`;function It(e){if(!e||typeof e!=`object`)return!1;let t=e.role;return t===`user`||t===`assistant`||t===`tool_result`||t===`compaction`}function K(e){return!e||typeof e!=`object`?!1:typeof e.type==`string`}function q(e){return{type:`text`,text:e}}function Lt(e){return{type:`thinking`,thinking:e}}function Rt(e,t){let n=e.timestamp,r=typeof n==`string`&&n?n:e.content;return`${e.role}\0${r}\0${t}`}function zt(e,t,n){let r=Rt(e,t);for(let e=0;e<100;e++){let t=Ne(`sha256`).update(`${r}\0${e}`).digest(`hex`).slice(0,8);if(!n.has(t))return n.add(t),t}let i=Ne(`sha256`).update(`${r}\0fallback`).digest(`hex`);return n.add(i),i}function Bt(e,t){let n=new Set,r=null,i=[],a={type:`session`,version:3,id:t?.sessionId??R(),timestamp:e.find(e=>e.timestamp)?.timestamp??new Date().toISOString(),cwd:t?.cwd??process.cwd()};for(let[t,a]of e.entries()){let e=zt(a,t,n),o={id:e,parentId:r,timestamp:a.timestamp};if(a.role===`user`)i.push({type:`message`,...o,message:{role:`user`,content:[q(a.content)]}});else if(a.role===`assistant`){let e=[];a.thinking?.trim()&&e.push(Lt(a.thinking.trim())),a.content.trim()&&e.push(q(a.content));for(let t of a.toolCalls??[])e.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});a.errorMessage&&e.push(q(a.errorMessage)),i.push({type:`message`,...o,message:{role:`assistant`,content:e,...a.stopReason?{stopReason:a.stopReason}:{}}})}else if(a.role===`tool_result`){let e=a.content;a.toolResultRef?.preview&&!e.includes(a.toolResultRef.preview)&&(e=`${e}\n\nPreview:\n${a.toolResultRef.preview}`),a.toolResultRef?.storagePath&&(e=`${e}\n\n[Full output: ${a.toolResultRef.storagePath}]`),i.push({type:`message`,...o,message:{role:`toolResult`,toolCallId:a.toolCallId,toolName:a.toolName,content:[q(e)],isError:a.isError,...a.details===void 0?{}:{details:a.details}}})}else a.role===`compaction`&&i.push({type:`compaction`,...o,summary:a.content,firstKeptEntryId:r??e,tokensBefore:0});r=e}return{header:a,entries:i,leafId:r}}function Vt(e,t){let n=e.trim().split(`
|
|
6
6
|
`).filter(e=>e.trim()),r=[],i=0;for(let e of n)try{r.push(JSON.parse(e))}catch{i+=1}if(r.length===0)return{data:Bt([],t),skippedLines:i};let a=r[0];if(K(a)&&a.type===`session`){let e=a,t=r.slice(1).filter(K);return{data:{header:e,entries:t,leafId:t.length>0?t[t.length-1].id:null},skippedLines:i}}if(r.every(K)){let e=r;return{data:{header:{type:`session`,version:3,id:t?.sessionId??R(),timestamp:e[0]?.timestamp??new Date().toISOString(),cwd:t?.cwd??process.cwd()},entries:e,leafId:e.length>0?e[e.length-1].id:null},skippedLines:i}}return{data:Bt(r.filter(It),t),skippedLines:i}}function Ht(e){let t=e;for(;t!==E(t);){if(b(O(t,`package.json`)))return t;t=E(t)}throw Error(`Could not find @gencode/cli package root`)}function Ut(){let e=Ht(E(Ee(import.meta.url))),t=[O(e,`dist`,`export-html`),O(e,`src`,`export-html`)];for(let e of t)if(b(O(e,`template.html`)))return e;throw Error(`export-html template directory not found under ${e}`)}function Wt(e){let t=w.resolve(e),n=`${w.sep}.aimax${w.sep}`,r=t.indexOf(n);if(!(r<0))return t.slice(0,r)}function Gt(e){let t=w.dirname(w.resolve(e));return w.basename(t)}async function Kt(e){let t=e.dataDir??(e.transcriptPath?Wt(e.transcriptPath):void 0),n=e.sessionId??(e.transcriptPath?Gt(e.transcriptPath):void 0);return!t||!n?{}:me(t,n,e.sessionPathOptions)}const qt=new Map;function J(e){let t=qt.get(e);if(t!==void 0)return t;let n=S(O(Ut(),e),`utf-8`);return qt.set(e,n),n}function Jt(){let e=[];for(let[t,n]of Object.entries(Mt))e.push(`--${t}: ${n};`);return e.push(`--exportPageBg: ${Nt};`),e.push(`--exportCardBg: ${Pt};`),e.push(`--exportInfoBg: ${Ft};`),e.join(`
|
|
7
7
|
`)}function Y(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&`;case`<`:return`<`;case`>`:return`>`;case`"`:return`"`;case`'`:return`'`;default:return e}})}function Yt(e){let t=J(`template.html`),n=J(`template.css`),r=J(`template.js`),i=Buffer.from(JSON.stringify(e)).toString(`base64`),a=n.replace(`{{THEME_VARS}}`,Jt()).replace(`{{BODY_BG}}`,Nt).replace(`{{CONTAINER_BG}}`,Pt).replace(`{{INFO_BG}}`,Ft);return t.replace(`{{CSS}}`,a).replace(`{{JS}}`,r).replace(`{{SESSION_DATA}}`,i)}function Xt(e,t){return t||`aimax-session-${T(e,`.jsonl`)}.html`}function Zt(e,t){return`Skipped ${t} malformed JSONL line(s) while exporting ${e}`}function Qt(e){for(let t of e)console.warn(t)}function X(e){return e.replace(/\\/g,`/`)}function $t(e){return e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`)}function en(e){let t=X(e),n=`^`;for(let e=0;e<t.length;e+=1){let r=t[e],i=t[e+1];if(r===`*`){i===`*`?t[e+2]===`/`?(n+=`(?:.*\\/)?`,e+=2):(n+=`.*`,e+=1):n+=`[^/]*`;continue}if(r===`?`){n+=`[^/]`;continue}n+=$t(r)}return n+=`$`,new RegExp(n)}function tn(e){return/[*?[]/.test(e)}function nn(e,t){let n=X(D(e)?A(e):A(t,e)).split(`/`),r=[];for(let e of n){if(tn(e))break;r.push(e)}return A(r.join(`/`)||`/`)}async function Z(e){let t;try{t=await j.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let n=[];for(let r of t){let t=O(e,r.name);if(r.isDirectory()){n.push(...await Z(t));continue}r.isFile()&&n.push(t)}return n}async function rn(e,t,n){let r=[];for await(let i of e(t,{cwd:n}))r.push(i);return r}async function an(e,t){let n=A(t),r=D(e),i=en(X(r?A(e):e));return(await Z(nn(e,n))).map(e=>({file:e,candidate:X(r?A(e):k(n,e))})).filter(({candidate:e})=>i.test(e)).map(({file:e})=>r?A(e):X(k(n,e)))}async function on(e,t){let n=j.glob;return typeof n==`function`?rn(n,e,t):an(e,t)}async function sn(e,t){if(t.options?.includeSnapshots===!1)return e;let n=await Kt({dataDir:t.options?.dataDir,sessionId:t.options?.sessionId??e.header.id,transcriptPath:t.inputLabel,sessionPathOptions:t.options?.sessionPathOptions});return n.tools?.length?{...e,tools:n.tools}:e}async function cn(e,t,n){let r=Vt(e,{sessionId:n?.sessionId,cwd:n?.cwd}),i=r.skippedLines>0?[Zt(t,r.skippedLines)]:[],a=r.data;a=await sn(a,{inputLabel:t,options:n});let o=Yt(a),s=Xt(t,n?.outputPath);return C(s,o,`utf8`),{outputPath:s,warnings:i}}async function ln(e,t){if(!b(e))throw Error(`File not found: ${e}`);return cn(S(e,`utf-8`),e,t)}async function un(e,t){let n=await ln(e,t);return Qt(n.warnings),n.outputPath}async function dn(e,t,n){let r=Ce(e,t,n);if(!b(r))throw Error(`Transcript not found: ${r}`);if((await ge(e,t,n)).length===0&&!S(r,`utf-8`).trim())throw Error(`Nothing to export yet - transcript is empty`);let i=S(r,`utf-8`),{outputPath:a,sessionId:o,cwd:s,dataDir:c,includeSnapshots:l,...u}=n??{};return cn(i,r,{outputPath:n?.outputPath,sessionId:t,cwd:n?.cwd,dataDir:e,sessionPathOptions:u,includeSnapshots:n?.includeSnapshots})}async function fn(e,t,n){let r=await dn(e,t,n);return Qt(r.warnings),r.outputPath}function pn(e,t){let n=t.map(t=>{let n=b(O(e,t.fileName))?Te(O(e,t.fileName)):void 0,r=n?`${Math.round(n.size/1024)} KB`:``,i=t.sourcePath?`<span class="muted">${Y(t.sourcePath)}</span>`:``;return`<tr><td><a href="${Y(t.fileName)}">${Y(t.sessionId)}</a></td><td>${r}</td><td>${i}</td></tr>`}).join(`
|
|
8
8
|
`),r=`<!DOCTYPE html>
|
package/dist/program.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./run-
|
|
1
|
+
import"./run-DgS7vRrF.js";import{n as e,t}from"./program-1RuLgLYv.js";export{t as createProgram,e as getDataDir};
|
|
@@ -4,8 +4,8 @@ import{GoalConflictError as e,applyCliGoalBeforeRun as t,buildResumeNarration as
|
|
|
4
4
|
`),N(`session: ${e.sessionId}`),N(`duration: ${e.durationMs}ms`),N(`tokens: input=${e.usage.input} output=${e.usage.output} total=${e.usage.total}`),e.context&&(N(`context: ${e.context.snapshotPath}`),N(`tool-results: ${e.context.toolResultsDir}`)),e.error&&P(`error: ${e.error}`)}function je(e,t){if(t===`json`){N(JSON.stringify(e,null,2));return}if(e.length===0){N(`No sessions found.`);return}for(let t of e){let e=t.createdAt?new Date(t.createdAt).toLocaleString():`unknown`,n=t.goalStatus?` [GOAL:${t.goalStatus}]`:` [GOAL:—]`;N(`${t.id} ${e} [${t.channel}]${n} ${t.title}`)}}function Me(e,t){if(t===`json`){N(JSON.stringify(e,null,2));return}N(`session: ${e.id}`),e.metadata&&(N(`title: ${e.metadata.title}`),N(`channel: ${e.metadata.channel}`),N(`created: ${e.metadata.createdAt}`),N(`updated: ${e.metadata.updatedAt}`)),N(`transcript: ${e.transcriptPath}`),N(`entries: ${e.transcriptEntryCount}`),N(`context: ${e.contextSnapshotPath}`),N(`session-memory: ${e.sessionMemoryPath}`),N(`collapse-log: ${e.collapseLogPath}`),N(`read-states: ${e.readStateCount}`),N(`tool-results: ${e.toolResultRefCount}`),N(`tool-results-dir: ${e.toolResultsDir}`)}function Ne(e,t){if(t===`json`){N(JSON.stringify(e,null,2));return}N(`session: ${e.id}`),N(`transcript: ${e.paths.transcriptPath}`),N(`context: ${e.paths.contextSnapshotPath}`),N(`session-memory: ${e.paths.sessionMemoryPath}`),N(`collapse-log: ${e.paths.collapseLogPath}`),N(`tool-results-dir: ${e.paths.toolResultsDir}`),N(`transcript-entries: ${e.transcript.length}`),N(`read-states: ${e.context.readStates.length}`),N(`tool-results: ${e.context.toolResults.length}`),N(`collapse-spans: ${e.context.compaction.collapseSpans.length}`)}function Pe(e,t){if(t===`json`){N(JSON.stringify(e,null,2));return}N(`Bootstrap completed.`),N(`dataDir: ${e.dataDir}`),N(`created dirs: ${e.createdDirs.length}`),N(`created files: ${e.createdFiles.length}`),N(`skipped dirs: ${e.skippedDirs.length}`),N(`skipped files: ${e.skippedFiles.length}`)}const Fe=`.aimax`,Ie=`${Fe}.pre-gocryptfs.`,Le=[`app.log`,`errors.log`],Re=[`logs`],ze=[`fusermount3`,`fusermount`,`umount`],Be=[{command:`fusermount3`,args:[`-u`],label:`fusermount3 -u`},{command:`fusermount3`,args:[`-uz`],label:`fusermount3 -uz`},{command:`fusermount`,args:[`-u`],label:`fusermount -u`},{command:`fusermount`,args:[`-uz`],label:`fusermount -uz`},{command:`umount`,args:[],label:`umount`},{command:`umount`,args:[`-l`],label:`umount -l`}];function Ve(e){return C.join(e,`.aimax.enc`)}function He(e){return C.join(e,Fe)}function Ue(e){return C.join(e,`${Ie}${process.pid}.${Date.now()}`)}function We(e){return C.join(e,`${Fe}.plaintext-restore.${process.pid}.${Date.now()}`)}function Ge(e){return e.replace(/\\([0-7]{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}async function L(e){try{let t=await Je.read(),n=C.resolve(e);for(let e of t.split(`
|
|
5
5
|
`)){if(!e.trim())continue;let t=e.split(` `);if(t.length>=5&&C.resolve(Ge(t[4]??``))===n)return!0}return!1}catch{return!1}}function Ke(e){try{let t=S.readFileSync(`/proc/self/mountinfo`,`utf-8`),n=C.resolve(e);for(let e of t.split(`
|
|
6
6
|
`)){if(!e.trim())continue;let t=e.split(` `);if(t.length>=5&&C.resolve(Ge(t[4]??``))===n)return!0}return!1}catch{return!1}}async function qe(){return await T.readFile(`/proc/self/mountinfo`,`utf-8`)}const Je={read:qe};async function R(e){try{return await T.stat(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function z(e){await T.mkdir(e,{recursive:!0})}async function Ye(e){if(await z(e),(await T.readdir(e)).length>0)throw Error(`Refusing to mount encrypted .aimax over non-empty directory: ${e}. Clear stale plaintext files or disable --encrypt-sessions for this run.`)}async function Xe(e){return await R(e)?(await T.readdir(e)).length===0:!0}async function B(e){if(await R(e))return(await T.readdir(e)).length}async function Ze(e){let t;try{t=await T.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return{exists:!1,entryCount:void 0,isEmpty:!0,containsUserData:!1};throw e}let n=!1;for(let e of t)if(!(e.isDirectory()&&Re.includes(e.name))&&!(e.isFile()&&Le.some(t=>e.name.startsWith(t)))){n=!0;break}return{exists:!0,entryCount:t.length,isEmpty:t.length===0,containsUserData:n}}async function Qe(e){let t=await T.readdir(e,{withFileTypes:!0});for(let n of t){if(n.isDirectory()&&Re.includes(n.name)){await T.rm(C.join(e,n.name),{recursive:!0,force:!0}).catch(()=>{});continue}n.isFile()&&Le.some(e=>n.name.startsWith(e))&&await T.rm(C.join(e,n.name),{force:!0}).catch(()=>{})}}async function $e(e){if(!await R(C.join(e,`gocryptfs.conf`)))throw Error(`Encrypted .aimax directory exists but is not initialized: ${e}. Remove the incomplete .aimax.enc directory or restore it from backup before retrying --encrypt-sessions.`)}async function et(e){return(await T.readdir(e,{withFileTypes:!0})).filter(e=>e.isDirectory()&&e.name.startsWith(Ie)).map(t=>C.join(e,t.name)).sort()}async function V(e,t){if(!await R(t))return null;let n=Ue(e);return M.info(`--encrypt-sessions moving plaintext .aimax aside before migration`,{plainDir:t,backupDir:n}),await T.rename(t,n),n}async function H(e,t,n){M.info(`--encrypt-sessions copying plaintext backup into encrypted mount`,{backupDir:e,plainDir:t,force:n}),await T.cp(e,t,{recursive:!0,force:n})}async function tt(e,t){if(e.length===0)return[];await z(t);let n=[];for(let r of e)await R(r)&&(await H(r,t,!0),await T.rm(r,{recursive:!0,force:!0}),M.info(`--encrypt-sessions restored interrupted plaintext backup after failed migration`,{backupDir:r,plainDir:t}),n.push(r));return n}async function nt(e){let t=Date.now(),n=Ve(e),r=He(e),i=await R(n);if(!i)return;let a=i&&await R(C.join(n,`gocryptfs.conf`)),o=await Ze(r),s=o.exists?await L(r):!1;if(M.info(`plaintext .aimax restore check for disabled --encrypt-sessions`,{dataDir:e,encryptedDir:n,plainDir:r,encryptedDirExists:i,encryptedDirInitialized:a,plainDirExists:o.exists,plainDirMountPoint:s,plainDirEntryCount:o.entryCount,probeDurationMs:Date.now()-t}),!a){M.warn(`plaintext .aimax restore skipped because .aimax.enc is not initialized`,{encryptedDir:n,plainDir:r}),await z(r);return}if(s){M.warn(`plaintext .aimax restore skipped because .aimax is already a mount point`,{plainDir:r,encryptedDir:n});return}if(o.containsUserData){M.info(`plaintext .aimax restore skipped because plaintext .aimax already contains data`,{plainDir:r,encryptedDir:n,plainDirEntryCount:o.entryCount,probeDurationMs:Date.now()-t});return}o.isEmpty||(M.info(`plaintext .aimax clearing ephemeral files before restore`,{plainDir:r,encryptedDir:n,plainDirEntryCount:o.entryCount}),await Qe(r));try{await at()}catch(e){M.warn(`plaintext .aimax restore unavailable; continuing with plaintext .aimax`,{error:e instanceof Error?e.message:String(e),plainDir:r,encryptedDir:n}),await z(r);return}let c=We(e),l=!1;try{await Ye(r),await ot(n,r),l=!0,await T.rm(c,{recursive:!0,force:!0}),await z(c),await T.cp(r,c,{recursive:!0,force:!0}),M.info(`plaintext .aimax restore copied encrypted history to staging directory`,{plainDir:r,encryptedDir:n,restoreDir:c,restoredEntryCount:await B(c)}),await U(r),l=!1,await T.rm(r,{recursive:!0,force:!0}),await T.rename(c,r),M.info(`plaintext .aimax restore completed for disabled --encrypt-sessions`,{plainDir:r,encryptedDir:n})}catch(e){l&&await U(r).catch(e=>{M.warn(`plaintext .aimax restore failed to unmount during rollback`,{error:e instanceof Error?e.message:String(e),plainDir:r,encryptedDir:n})}),await T.rm(c,{recursive:!0,force:!0}).catch(()=>{}),await z(r).catch(()=>{}),M.warn(`plaintext .aimax restore failed; continuing with existing plaintext .aimax`,{error:e instanceof Error?e.message:String(e),plainDir:r,encryptedDir:n})}}async function rt(e){let t=C.join(E.tmpdir(),`aimax-gocryptfs-pass.${process.pid}.${Date.now()}`);await T.writeFile(t,`wizard_aimax@2026
|
|
7
|
-
`,{mode:384});try{return await e(t)}finally{await T.rm(t,{force:!0})}}async function it(e){let t=e.includes(`-init`)?`init`:`mount`;M.info(`--encrypt-sessions starting gocryptfs ${t}`);try{await ft(`gocryptfs`,e),M.info(`--encrypt-sessions completed gocryptfs ${t}`)}catch(n){let r=n instanceof Error?n.message:String(n);throw M.warn(`--encrypt-sessions failed gocryptfs ${t}`,{error:r}),Error(`gocryptfs ${e.join(` `)} failed: ${r}`)}}async function at(){M.info(`--encrypt-sessions checking encryption dependencies`),await mt(`gocryptfs`,`required for --encrypt-sessions`),M.info(`--encrypt-sessions dependency available`,{command:`gocryptfs`});for(let e of ze)if(await pt(e)){M.info(`--encrypt-sessions unmount dependency available`,{command:e});return}throw Error(`--encrypt-sessions requires one of ${ze.join(`, `)} to be installed for secure unmount cleanup.`)}async function ot(e,t){M.info(`--encrypt-sessions mounting encrypted .aimax`,{encryptedDir:e,plainDir:t}),await rt(async n=>{await it([`-q`,`-passfile`,n,e,t])})}async function st(e){M.info(`--encrypt-sessions initializing encrypted .aimax directory`,{encryptedDir:e}),await rt(async t=>{await it([`-q`,`-init`,`-passfile`,t,e])})}async function U(e){let t=[];M.info(`--encrypt-sessions unmounting encrypted .aimax`,{plainDir:e});for(let n of Be)try{if(M.info(`--encrypt-sessions attempting encrypted .aimax unmount`,{command:n.label,plainDir:e}),await ft(n.command,[...n.args,e]),!await L(e)){M.info(`--encrypt-sessions unmounted encrypted .aimax`,{command:n.label,plainDir:e});return}let r=`${n.label} returned success but ${e} is still mounted`;t.push(r),M.warn(`--encrypt-sessions unmount command returned success but mountpoint remains`,{command:n.label,plainDir:e})}catch(r){let i=ht(n.label,r);t.push(i),M.warn(`--encrypt-sessions unmount attempt failed`,{command:n.label,plainDir:e,error:r instanceof Error?r.message:String(r)})}throw Error(`Failed to unmount ${e}: ${t.join(`; `)}`)}function ct(e){for(let t of Be)try{if(ne(t.command,[...t.args,e],{stdio:`ignore`}),!Ke(e))return}catch{}}function lt(e){let t=!1,n=()=>{t||(t=!0,ct(e))},r=()=>n(),i=()=>{n(),process.exit(130)},a=()=>{n(),process.exit(143)};return process.once(`exit`,r),process.once(`SIGINT`,i),process.once(`SIGTERM`,a),{release(){process.removeListener(`exit`,r),process.removeListener(`SIGINT`,i),process.removeListener(`SIGTERM`,a)}}}async function ut(e){let t=Ve(e),n=He(e),r=await R(n),i=await R(t),a=i&&await R(C.join(t,`gocryptfs.conf`)),o=r?await L(n):!1;M.info(`--encrypt-sessions preparing encrypted .aimax mount`,{dataDir:e,encryptedDir:t,plainDir:n,plainDirExists:r,encryptedDirExists:i,encryptedDirInitialized:a,plainDirMountPoint:o,plainDirEntryCount:await B(n),encryptedDirEntryCount:await B(t)});let s=()=>({mounted:!1,plainDir:n,encryptedDir:t,async cleanup(){}});try{await at()}catch(e){return M.warn(`--encrypt-sessions is unavailable; continuing with plaintext .aimax`,{error:e instanceof Error?e.message:String(e)}),await z(n),s()}if(await L(n))return M.warn(`--encrypt-sessions found existing .aimax mount; continuing without taking ownership`,{plainDir:n}),s();let c=null,l=[],u=null,d=null,f=!1;try{if(l=await et(e),l.length>0&&M.warn(`--encrypt-sessions found interrupted pre-gocryptfs migration backups`,{count:l.length}),!await R(t))if(M.info(`--encrypt-sessions encrypted .aimax directory does not exist; starting first-time migration`,{encryptedDir:t,plainDir:n,resumedBackupCount:l.length}),l.length>0?u=await V(e,n):c=await V(e,n),await z(t),await st(t),await z(n),await ot(t,n),f=!0,d=lt(n),M.info(`--encrypt-sessions mounted encrypted .aimax`,{plainDir:n,encryptedDir:t}),l.length>0){for(let e of l)await H(e,n,!0);u&&=(await H(u,n,!1),await T.rm(u,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed residual plaintext backup after migration`,{backupDir:u}),null);for(let e of l)await T.rm(e,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed resumed plaintext migration backup`,{backupDir:e});l=[]}else c&&=(await H(c,n,!0),await T.rm(c,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed plaintext migration backup`,{backupDir:c}),null);else if(M.info(`--encrypt-sessions encrypted .aimax directory exists; mounting existing encrypted data`,{encryptedDir:t,plainDir:n,resumedBackupCount:l.length,plainDirEntryCount:await B(n)}),await $e(t),l.length>0?u=await V(e,n):await Xe(n)||(c=await V(e,n)),await Ye(n),await ot(t,n),f=!0,d=lt(n),M.info(`--encrypt-sessions mounted encrypted .aimax`,{plainDir:n,encryptedDir:t}),l.length>0){for(let e of l)await H(e,n,!0);u&&=(await H(u,n,!1),await T.rm(u,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed residual plaintext backup after migration`,{backupDir:u}),null);for(let e of l)await T.rm(e,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed resumed plaintext migration backup`,{backupDir:e});l=[]}else c&&=(await H(c,n,!0),await T.rm(c,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed plaintext migration backup`,{backupDir:c}),null);return M.info(`--encrypt-sessions prepared encrypted .aimax mount result`,{mounted:f,plainDir:n,encryptedDir:t,plainDirMountPoint:await L(n),plainDirEntryCount:await B(n),encryptedDirEntryCount:await B(t)}),{mounted:f,plainDir:n,encryptedDir:t,async cleanup(){if(d?.release(),!f){M.info(`--encrypt-sessions cleanup skipped because encrypted .aimax is not mounted`,{plainDir:n,encryptedDir:t});return}f=!1,M.info(`--encrypt-sessions cleanup started`,{plainDir:n,encryptedDir:t});try{await U(n),M.info(`--encrypt-sessions cleanup completed`,{plainDir:n,encryptedDir:t})}catch(e){M.warn(`--encrypt-sessions failed to unmount encrypted .aimax; continuing shutdown`,{error:e instanceof Error?e.message:String(e)})}}}}catch(e){d?.release(),f&&await U(n).catch(e=>{M.warn(`--encrypt-sessions failed to unmount during mount rollback`,{error:e instanceof Error?e.message:String(e),plainDir:n,encryptedDir:t})}),c&&await R(c)&&await Xe(n)&&(await T.rm(n,{recursive:!0,force:!0}).catch(()=>{}),await T.rename(c,n).catch(()=>{}),M.info(`--encrypt-sessions restored plaintext backup after failed migration`,{backupDir:c,plainDir:n})),u&&await R(u)&&await Xe(n)&&(await T.rm(n,{recursive:!0,force:!0}).catch(()=>{}),await T.rename(u,n).catch(()=>{}),M.info(`--encrypt-sessions restored residual plaintext backup after failed migration`,{backupDir:u,plainDir:n}));let r=await tt(l,n).catch(e=>(M.warn(`--encrypt-sessions failed to restore interrupted plaintext backups after failed migration`,{error:e instanceof Error?e.message:String(e),plainDir:n,backupCount:l.length}),[]));return l=l.filter(e=>!r.includes(e)),M.warn(`--encrypt-sessions failed; continuing with plaintext .aimax`,{error:e instanceof Error?e.message:String(e),mountedBeforeFailure:f,plainDir:n,encryptedDir:t,backupDir:c,residualPlainBackupDir:u,resumedBackupCount:l.length}),await z(n),s()}}async function dt(e,t,n){if(!t.encryptSessions)return await nt(e),n();M.info(`--encrypt-sessions wrapper starting encrypted .aimax preparation`,{dataDir:e});let r=await ut(e);M.info(`--encrypt-sessions wrapper prepared encrypted .aimax state`,{dataDir:e,mounted:r.mounted,plainDir:r.plainDir,encryptedDir:r.encryptedDir});try{return M.info(`--encrypt-sessions wrapper entering protected operation`,{dataDir:e,mounted:r.mounted}),await n(r)}finally{M.info(`--encrypt-sessions wrapper starting cleanup`,{dataDir:e,mounted:r.mounted,plainDir:r.plainDir,encryptedDir:r.encryptedDir}),await r.cleanup(),M.info(`--encrypt-sessions wrapper finished cleanup`,{dataDir:e,mounted:r.mounted,plainDir:r.plainDir,encryptedDir:r.encryptedDir})}}async function ft(e,t){await new Promise((n,r)=>{te(e,t,{encoding:`utf-8`},e=>{if(e){r(e);return}n()})})}async function pt(e){try{return await ft(`sh`,[`-c`,`command -v "${e}" >/dev/null 2>&1`]),!0}catch{return!1}}async function mt(e,t){if(!await pt(e))throw Error(`--encrypt-sessions requires ${e}: ${t}.`)}function ht(e,t){return`${e} failed: ${t instanceof Error?t.message:String(t)}`}function gt(e){return re.sm4_encrypt_ecb(e)}function _t(e){return gt(e)}const vt=[`minimal`,`low`,`medium`,`high`,`xhigh`];function yt(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(vt.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of ${vt.join(`, `)}.`)}}function W(e,t){if(e===void 0)return;let n=e.trim();if(!n)return;let r=Number(n);if(!Number.isFinite(r))throw Error(`Invalid ${t}: ${e}. Must be a number.`);return r}function bt(e,t){let n=W(e,t);if(n!==void 0){if(!Number.isInteger(n))throw Error(`Invalid ${t}: ${e}. Must be an integer.`);return n}}function xt(e,t){if(e!==void 0){if(e<0||e>2)throw Error(`Invalid ${t}: ${e}. Must be between 0 and 2.`);return e}}function St(e,t){if(e!==void 0){if(e<0||e>1)throw Error(`Invalid ${t}: ${e}. Must be between 0 and 1.`);return e}}function Ct(e,t){if(e!==void 0){if(e<=0)throw Error(`Invalid ${t}: ${e}. Must be a positive integer.`);return e}}function wt(e={}){let t=Tt(e.apiFormat??process.env.AIMAX_API_FORMAT),n=e.baseUrl??process.env.AIMAX_BASE_URL,r=process.env.AIMAX_AUTH_TOKEN,i=process.env.AIMAX_API_KEY??process.env.AIMAX_LLM_API_KEY,a=e.authToken?_t(e.authToken):r?_t(r):e.apiKey??i,o=e.model??process.env.AIMAX_MODEL,s=[];if(n||s.push(`--base-url / AIMAX_BASE_URL`),a||s.push(`--api-key / AIMAX_API_KEY / AIMAX_LLM_API_KEY`),o||s.push(`--model / AIMAX_MODEL`),s.length>0)throw Error(`Missing required LLM configuration: ${s.join(`, `)}`);return{apiFormat:t,baseUrl:n,apiKey:a,model:o,contextWindow:e.contextWindow??(process.env.AIMAX_CONTEXT_WINDOW?Number(process.env.AIMAX_CONTEXT_WINDOW):void 0),flashModel:e.flashModel??process.env.AIMAX_FLASH_MODEL,thinking:e.thinking===void 0?yt(process.env.AIMAX_THINKING,`AIMAX_THINKING`):yt(e.thinking,`--thinking`),temperature:e.temperature===void 0?xt(W(process.env.AIMAX_TEMPERATURE,`AIMAX_TEMPERATURE`),`AIMAX_TEMPERATURE`):xt(e.temperature,`--temperature`),topK:e.topK===void 0?Ct(bt(process.env.AIMAX_TOP_K,`AIMAX_TOP_K`),`AIMAX_TOP_K`):Ct(e.topK,`--top-k`),topP:e.topP===void 0?St(W(process.env.AIMAX_TOP_P,`AIMAX_TOP_P`),`AIMAX_TOP_P`):St(e.topP,`--top-p`)}}function Tt(e){if(!e||e===`openai-completions`||e===`anthropic-messages`)return e;throw Error(`Unsupported LLM API format: ${e}`)}const Et=[`off`,`fallback`];function Dt(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if([`true`,`1`,`yes`,`on`].includes(n))return!0;if([`false`,`0`,`no`,`off`].includes(n))return!1;throw Error(`Invalid ${t}: ${e}. Must be true or false.`)}}function Ot(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(Et.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of ${Et.join(`, `)}.`)}}function kt(){return[`AIMAX_MEMORY_KC_ENABLED`,`AIMAX_MEMORY_KC_BASE_URL`,`AIMAX_MEMORY_KC_BASE_PATH`,`AIMAX_MEMORY_KC_AUTH_TOKEN`,`AIMAX_MEMORY_KC_SEARCH_MODE`,`AIMAX_MEMORY_KC_TOP_K`,`AIMAX_MEMORY_KC_SCORE_THRESHOLD`,`AIMAX_MEMORY_KC_TIMEOUT_MS`,`AIMAX_MEMORY_KC_SYNC_ENABLED`].some(e=>process.env[e]!==void 0)}function At(e){return Object.values(e).some(e=>e!==void 0)}function jt(e={}){if(!(!At(e)&&!kt()))return{knowledgeController:{enabled:e.kcEnabled??Dt(process.env.AIMAX_MEMORY_KC_ENABLED,`AIMAX_MEMORY_KC_ENABLED`),baseUrl:e.kcBaseUrl??process.env.AIMAX_MEMORY_KC_BASE_URL,basePath:e.kcBasePath??process.env.AIMAX_MEMORY_KC_BASE_PATH,authToken:e.kcAuthToken??process.env.AIMAX_MEMORY_KC_AUTH_TOKEN,searchMode:e.kcSearchMode===void 0?Ot(process.env.AIMAX_MEMORY_KC_SEARCH_MODE,`AIMAX_MEMORY_KC_SEARCH_MODE`)??`off`:Ot(e.kcSearchMode,`kcSearchMode`),topK:e.kcTopK??W(process.env.AIMAX_MEMORY_KC_TOP_K,`AIMAX_MEMORY_KC_TOP_K`),scoreThreshold:e.kcScoreThreshold??W(process.env.AIMAX_MEMORY_KC_SCORE_THRESHOLD,`AIMAX_MEMORY_KC_SCORE_THRESHOLD`),timeoutMs:e.kcTimeoutMs??W(process.env.AIMAX_MEMORY_KC_TIMEOUT_MS,`AIMAX_MEMORY_KC_TIMEOUT_MS`),syncEnabled:e.kcSyncEnabled??Dt(process.env.AIMAX_MEMORY_KC_SYNC_ENABLED,`AIMAX_MEMORY_KC_SYNC_ENABLED`)}}}function Mt(e,t){return t?C.resolve(t):C.join(e,`.aimax`,`plugins.json`)}async function G(e,t){let n=Mt(e,t);try{let e=await T.readFile(n,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Nt(e,t,n){let r=Mt(e,n);await T.mkdir(C.dirname(r),{recursive:!0}),await T.writeFile(r,JSON.stringify(t,null,2),`utf-8`)}function K(e){return typeof e==`object`&&!!e}function Pt(e){return K(e)&&e.type===`text`&&typeof e.text==`string`&&(e.textSignature===void 0||typeof e.textSignature==`string`)}function Ft(e){return K(e)&&e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`}function It(e){return K(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 Lt(e){return K(e)&&e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`&&K(e.arguments)&&(e.thoughtSignature===void 0||typeof e.thoughtSignature==`string`)}function Rt(e){return typeof e==`string`||Array.isArray(e)&&e.every(e=>Pt(e)||Ft(e))}function zt(e){return Array.isArray(e)&&e.every(e=>Pt(e)||It(e)||Lt(e))}function Bt(e){return K(e)&&typeof e.input==`number`&&typeof e.output==`number`&&typeof e.cacheRead==`number`&&typeof e.cacheWrite==`number`&&typeof e.totalTokens==`number`&&K(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 Vt(e){return!K(e)||typeof e.role!=`string`?!1:e.role===`user`?Rt(e.content):e.role===`assistant`?zt(e.content)&&typeof e.api==`string`&&typeof e.provider==`string`&&typeof e.model==`string`&&Bt(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=>Pt(e)||Ft(e))&&typeof e.isError==`boolean`:!1}async function Ht(e){let t;try{t=await T.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}`)}return Ut(n,`Message file`)}function Ut(e,t=`Messages input`){let n=Array.isArray(e)?e:[e];if(n.length===0||!n.every(e=>Vt(e)))throw Error(`${t} must contain one Message object or an array of Message objects`);return n}async function Wt(e){if([!!e.message,!!e.fromFile,e.messages!==void 0].filter(Boolean).length!==1)throw Error(`Exactly one of --message, --from-file, or messages must be provided`);return e.fromFile?{kind:`messages`,messages:await Ht(e.fromFile),source:`file`}:e.messages===void 0?{kind:`text`,message:e.message}:{kind:`messages`,messages:Ut(e.messages),source:`inline`}}var Gt=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()}))}},Kt=class{deliveryQueue=Promise.resolve();constructor(e){this.url=e}async send(e){this.enqueue(this.toPayload(e))}async close(){await this.deliveryQueue}enqueue(e){let t=this.deliveryQueue.then(async()=>{await this.post(e)},async()=>{await this.post(e)});return this.deliveryQueue=t.catch(()=>{}),t}async post(e){let t=Date.now(),n=qt(e);M.info(`sending callback event`,{callbackUrl:this.url,...n});let r=new AbortController,i=!1,a=setTimeout(()=>{i=!0,r.abort()},5e3);try{let a=await fetch(this.url,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:r.signal}),o=Date.now()-t;if(!a.ok){M.error(`callback event failed`,{callbackUrl:this.url,httpStatus:a.status,durationMs:o,timedOut:i,...n});return}M.info(`callback event delivered`,{callbackUrl:this.url,httpStatus:a.status,durationMs:o,...n})}catch(e){let r=Date.now()-t;M.error(`callback event failed`,{callbackUrl:this.url,error:e instanceof Error?e.message:String(e),durationMs:r,timedOut:i,...n})}finally{clearTimeout(a)}}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 qt(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 Jt(e,t){if(t.kind===`none`)return e;let n=new URL(e);return n.searchParams.set(`authToken`,t.token),n.toString()}const Yt=5e3,Xt=5e3,Zt=6e4;function q(){let e=globalThis.WebSocket;if(!e)throw Error(`WebSocket is not available in this runtime`);return e}function Qt(e){return e?{kind:`query_token`,token:e}:{kind:`none`}}function $t(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 en(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 tn=class{socket=null;connectPromise=null;heartbeatTimer=null;lastSentAt=0;heartbeatMessageId;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.sendPayload(JSON.stringify(t)),this.heartbeatMessageId=t.messageId}catch(e){M.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.sendPayload(JSON.stringify(t)),this.heartbeatMessageId=t.messageId}catch(e){M.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,this.stopHeartbeat();let e=this.socket;if(this.socket=null,this.connectPromise=null,!e)return;let t=q();if(e.readyState!==t.CLOSED)try{await nn(new Promise(t=>{$t(e,`close`,()=>t()),e.close()}),Xt,`WebSocket close timed out after ${Xt}ms`)}catch(e){M.warn(`websocket sink close timed out`,{url:this.url,error:e instanceof Error?e.message:String(e)})}}async ensureConnected(){if(!this.enabled)return;let e=q();if(this.socket&&this.socket.readyState===e.OPEN)return;if(this.connectPromise){await this.connectPromise;return}let t=new e(Jt(this.url,Qt(this.authToken)));this.connectPromise=new Promise((e,n)=>{$t(t,`open`,()=>{this.socket=t,this.markSent(),en(t,`close`,()=>{this.socket===t&&(this.socket=null),this.stopHeartbeat()}),e()}),$t(t,`error`,e=>{n(e)})});try{await this.connectPromise}finally{this.connectPromise=null}}async sendPayload(e){await nn(this.ensureConnected(),Yt,`WebSocket connection timed out after ${Yt}ms`);let t=q();!this.socket||this.socket.readyState!==t.OPEN||(this.socket.send(e),this.markSent())}markSent(){this.lastSentAt=Date.now(),this.scheduleHeartbeat()}scheduleHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setTimeout(()=>{this.sendHeartbeatIfIdle()},Zt)}stopHeartbeat(){this.heartbeatTimer&&=(clearTimeout(this.heartbeatTimer),null)}async sendHeartbeatIfIdle(){if(!this.enabled)return;let e=q();if(!(!this.socket||this.socket.readyState!==e.OPEN)&&!(Date.now()-this.lastSentAt<Zt)&&this.heartbeatMessageId)try{let e={type:`ping`,messageId:this.heartbeatMessageId};this.socket.send(JSON.stringify(e)),this.markSent()}catch(e){M.warn(`websocket sink disabled after heartbeat send failure`,{url:this.url,error:e instanceof Error?e.message:String(e)}),this.enabled=!1,this.stopHeartbeat()}}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)}`)}}}};function nn(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>i(Error(n)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}function rn(e){let t=e.trim();if(!t)throw Error(`Goal objective cannot be empty`);return t}function an(e,t){if(t.action===`unchanged`)return null;if(t.action===`created`||t.action===`replaced`)return t.action;if(e?.status!==t.goal.status)switch(t.goal.status){case`active`:return e?.status===`paused`?`resumed`:`updated`;case`paused`:return`paused`;case`complete`:return`completed`;case`budget_limited`:return`budget_limited`;default:return`updated`}return`updated`}function on(e){let t=an(e.before,e.result);return t?{type:`goal_updated`,sessionId:e.sessionId,action:t,goalId:e.result.goal.goalId,goalStatus:e.result.goal.status}:null}function sn(e){let t=e?.packageRoot??cn(),n=C.join(t,`models`),r=C.join(n,...`Xenova/bge-small-zh-v1.5`.split(`/`));if(S.existsSync(C.join(r,`config.json`)))return n}function cn(){let e=C.dirname(ie(import.meta.url));return C.basename(e)===`src`||C.basename(e)===`dist`?C.resolve(e,`..`):e}function ln(e){return{text:e.text,usage:e.usage,durationMs:e.durationMs,...e.error?{error:e.error}:{},...e.paused?{paused:e.paused}:{},...e.uiToolPending?{uiToolPending:e.uiToolPending}:{},...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{}}}function un(e){if(!e?.trim())return;let t=new Set,n=[];for(let r of e.split(`,`)){let e=r.trim();if(!e)continue;let i=dn(e);if(!i)throw Error(`Invalid --artifacts-url-whitelist entry: ${e}. Expected a domain or URL with a valid hostname.`);t.has(i)||(t.add(i),n.push(i))}return n.length>0?n:void 0}function dn(e){try{let t=/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`http://${e}`,n=new URL(t);return n.username||n.password?null:n.hostname.trim().toLowerCase()||null}catch{return null}}const fn=[`start`,`text`,`done`,`error`,`hitl`],pn=[`off`,`gate`,`dry_run`,`write`];function mn(e){if(!e?.trim())return new Set(fn);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(fn)}function hn(e){if(e.disableTopicSegmentation===!0||process.env.AIMAX_DISABLE_TOPIC_SEGMENTATION===`true`)return{enabled:!1};let t=sn();return t?{embeddingModelDir:t}:void 0}function gn(e){return e.disableTitle===!0||process.env.AIMAX_DISABLE_TITLE===`true`?{enabled:!1}:void 0}function _n(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 vn(e){return e?.trim()||void 0}function J(e){return e?.trim()||void 0}function yn(e){let t=(e.systemAgentsDir??process.env.AIMAX_SYSTEM_AGENTS_DIR)?.trim();if(t){if(!C.isAbsolute(t)){let n=e.systemAgentsDir===void 0?`AIMAX_SYSTEM_AGENTS_DIR`:`--system-agents-dir`;throw Error(`Invalid ${n}: ${t}. Path must be absolute.`)}return t}}function bn(e){let t=(e.systemAgentTeamsDir??process.env.AIMAX_SYSTEM_AGENT_TEAMS_DIR)?.trim();if(t){if(!C.isAbsolute(t)){let n=e.systemAgentTeamsDir===void 0?`AIMAX_SYSTEM_AGENT_TEAMS_DIR`:`--system-agent-teams-dir`;throw Error(`Invalid ${n}: ${t}. Path must be absolute.`)}return t}}function xn(e){return e?f(e):void 0}function Sn(e){if(!e?.trim())return[];let t=e.split(`,`).map(e=>e.trim()).filter(Boolean),n=new Set,r=[];for(let e of t){if(!C.isAbsolute(e))throw Error(`Invalid --skillsLoadPaths entry: ${e}. Each path must be absolute.`);n.has(e)||(n.add(e),r.push(e))}return r}function Cn(e){if(!e?.trim())return[];let t=e.split(`,`).map(e=>e.trim()).filter(Boolean),n=new Set,r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}function wn(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if([`true`,`1`,`yes`,`on`].includes(n))return!0;if([`false`,`0`,`no`,`off`].includes(n))return!1;throw Error(`Invalid ${t}: ${e}. Must be true or false.`)}}function Tn(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(pn.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of off,gate,dry_run,write.`)}}function En(e){let t=e.autoSkillsLoadEnabled===void 0?wn(process.env.AIMAX_AUTO_SKILLS_LOAD_ENABLED,`AIMAX_AUTO_SKILLS_LOAD_ENABLED`):wn(e.autoSkillsLoadEnabled,`--auto-skills-load-enabled`),n=e.autoSkillsReviewMode===void 0?Tn(process.env.AIMAX_AUTO_SKILLS_REVIEW_MODE,`AIMAX_AUTO_SKILLS_REVIEW_MODE`):Tn(e.autoSkillsReviewMode,`--auto-skills-review-mode`),r={};return t!==void 0&&(r.load={enabled:t}),n!==void 0&&(r.review={mode:n}),r.load||r.review?r:void 0}function Dn(e,t){if(e.inputText&&t){let n=ee(e.inputText,t);return n.submittedBy={userId:e.user,channel:e.channel??`IM`},n}if(!e.inputJson&&!e.inputText)throw Error(`Either --input-json or --input-text must be provided for the 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}`)}}function On(e,t){if(!e.inputJson)throw Error(`UI tool resume requires --input-json`);try{let n=JSON.parse(e.inputJson),r=n&&typeof n==`object`&&`values`in n&&n.values&&typeof n.values==`object`&&!Array.isArray(n.values)?n.values:n;return{requestId:t.request.requestId,sessionId:t.sessionId,toolCallId:t.request.toolCallId,toolName:t.request.toolName,values:r,submittedAt:new Date().toISOString()}}catch(e){throw Error(`Invalid --input-json: ${e.message}`)}}async function kn(e){let t=await d(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions});for(let n=t.length-1;n>=0;--n){let r=t[n];if(r?.role!==`assistant`||!Array.isArray(r.toolCalls))continue;let i=r.toolCalls.find(t=>t.id===e.toolCallId&&t.name===e.toolName);if(i)return i.arguments}}async function An(e){let t=_n(e),n=e.channel??`WEB`,r=wt({apiFormat:e.apiFormat,baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow?Number(e.contextWindow):void 0,flashModel:e.flashModel,thinking:e.thinking});return{dataDir:t,systemAgentsDir:yn(e),systemAgentTeamsDir:bn(e),channel:n,format:e.output===`json`?`json`:`text`,timeoutMs:e.timeout?Number(e.timeout):void 0,llm:r,skillsLoadPaths:Sn(e.skillsLoadPaths),workdirAllowlist:Cn(e.workdirAllowlist),artifactsUrlWhitelist:un(e.artifactsUrlWhitelist),autoSkills:En(e)}}function jn(e){let t=[],n=null;return e.callbackUrl&&t.push(new Kt(e.callbackUrl)),e.streamUrl&&(n=new tn(e.streamUrl,mn(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new Gt(t),websocketSink:n}}async function Mn(e){let{dataDir:t,sessionId:n,sessionStoreName:r,toolCallId:i,toolName:c,resolution:l,encryptSessions:u}=e;if(!i||!c||!b(c))return;let d=(e,t)=>{switch(e){case`request_approval`:return a(t);case`clarify`:return o(t);case`request_review`:return s(t);default:return JSON.stringify({action:t.action,values:t.values})}};await g(t,n,e=>{let t=e.findIndex(e=>e.role===`tool_result`&&e.toolCallId===i&&e.toolName===c);if(t===-1)return e;let n=e.slice(0,t+1);return n[t]={...n[t],content:d(c,l),isError:!1},n},{storeName:r,encryptSessions:u})}async function Nn(e){let{dataDir:t,sessionId:n,sessionStoreName:r,result:i,encryptSessions:a}=e;await g(t,n,e=>{let t=e.findIndex(e=>e.role===`assistant`&&Array.isArray(e.toolCalls)&&e.toolCalls.some(e=>e.id===i.toolCallId&&e.name===i.toolName));if(t===-1)return e;let n=e.slice(0,t+1);return n.push({role:`tool_result`,toolCallId:i.toolCallId,toolName:i.toolName,content:JSON.stringify({submitted:!0,values:i.values}),isError:!1,timestamp:i.submittedAt}),n},{storeName:r,encryptSessions:a})}function Pn(){let e=jt();return e?{core:e}:void 0}async function Fn(n){let i=_n(n);await dt(i,n,async()=>{ye(i,{messageId:n.messageId,sessionId:n.sessionId,sessionStoreName:xn(n.sessionStore)});let a=new we(`resume command`),o=null;try{let i=await An(n),s=xn(n.sessionStore),c=null;if(n.goal||n.goalFile){let r;r=n.goalFile?await T.readFile(n.goalFile,`utf-8`):n.goal;let a=rn(r),o=n.tokenBudget===void 0?void 0:n.tokenBudget===`0`||n.tokenBudget===``?null:Number(n.tokenBudget);o!=null&&(Number.isNaN(o)||o<=0)&&(P(`error: --token-budget must be a positive integer, or 0 for unlimited`),process.exit(1));try{let e=await p(i.dataDir,n.sessionId,{storeName:s}),r=await t({dataDir:i.dataDir,sessionId:n.sessionId,objective:a,tokenBudget:o,force:n.force,storeName:s});c=on({sessionId:n.sessionId,before:e,result:r})}catch(t){throw t instanceof e&&(P(t.message),P(`Existing: ${t.existingObjectivePreview}`),process.exit(2)),t}}M.info(`resume command started`,{sessionId:n.sessionId,requestId:n.requestId,channel:i.channel,dataDir:i.dataDir});let d=await l(i.dataDir,n.sessionId,{storeName:s,encryptSessions:n.encryptSessions}),f=d?null:await u(i.dataDir,n.sessionId,{storeName:s,encryptSessions:n.encryptSessions});if(!d&&!f)throw Error(`No pending HITL or UI tool request found for session "${n.sessionId}"`);if(d){if(d.request.requestId!==n.requestId)throw Error(`Request ID mismatch: pending is "${d.request.requestId}", got "${n.requestId}"`);if(d.status===`expired`)throw Error(`HITL request has expired`);if(d.status===`cancelled`)throw Error(`HITL request has been cancelled`)}else if(f){if(f.request.requestId!==n.requestId)throw Error(`Request ID mismatch: pending is "${f.request.requestId}", got "${n.requestId}"`);if(f.status!==`pending`)throw Error(`UI tool request is already "${f.status}", cannot resume`)}if(d){let e=Dn(n,d.request),t=await m({dataDir:i.dataDir,sessionStoreName:s,sessionId:n.sessionId,requestId:n.requestId,resolution:e}),r=t.state;if(!r)throw Error(`Resolved HITL state was not persisted`);let l=In(e,r.request.kind);await Mn({dataDir:i.dataDir,sessionId:n.sessionId,sessionStoreName:s,toolCallId:r.toolContext?.toolCallId,toolName:r.toolContext?.toolName,resolution:e,encryptSessions:n.encryptSessions});let u=jn(n);o=u.sink;let f=n.sessionId,p=async e=>{if(f=e.sessionId??f,!y(e)){if(e.type===`stream_text_delta`){i.format===`text`&&F(e),await u.websocketSink?.sendTextDelta({sessionId:f,channel:i.channel,messageId:n.messageId,user:n.user,text:e.text});return}i.format===`text`&&F(e),await o?.send({sessionId:f,channel:i.channel,messageId:n.messageId,user:n.user,type:`progress`,event:e})}};c&&await p(c),await p({type:`hitl_resumed`,requestId:n.requestId,resolution:e,sessionId:n.sessionId}),`idempotentReplay`in t&&t.idempotentReplay&&(M.info(`resume command treated as idempotent replay`,{sessionId:n.sessionId,requestId:n.requestId,idempotencyKey:e.idempotencyKey}),I({sessionId:n.sessionId,text:`Resume request already processed.`,usage:{input:0,output:0,total:0},durationMs:0},i.format),a.end(),process.exit(0));let h=n.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,g=await G(i.dataDir,h),v;try{v=await _({dataDir:i.dataDir,projectDir:vn(n.projectDir),systemAgentsDir:i.systemAgentsDir,systemAgentTeamsDir:i.systemAgentTeamsDir,agentPolicy:J(n.team)?{requestedTeamName:J(n.team)}:void 0,sessionStoreName:s,sessionId:n.sessionId,messageId:n.messageId,channel:i.channel,llm:i.llm,skillsLoadPaths:i.skillsLoadPaths,workdirAllowlist:i.workdirAllowlist,artifactsUrlWhitelist:i.artifactsUrlWhitelist,autoSkills:i.autoSkills,timeoutMs:i.timeoutMs,message:l,encryptSessions:n.encryptSessions??!1,topicSegmentation:hn(n),titleGeneration:gn(n),memory:Pn(),hitlResume:{request:r.request,resolution:e,checkpoint:r.checkpoint,toolContext:r.toolContext},plugins:g?{config:g,dataDir:i.dataDir,workspaceDir:C.join(i.dataDir,`workspace`),bundledDir:process.env.AIMAX_PLUGINS_BUNDLED_DIR,llmAllowlist:g.llmAllowlist}:void 0,onProgress:p,onLog:xe})}finally{}v.error?await o?.send({sessionId:v.sessionId,channel:i.channel,messageId:n.messageId,user:n.user,type:`error`,message:v.error}):await o?.send({sessionId:v.sessionId,channel:i.channel,messageId:n.messageId,user:n.user,type:`done`,result:ln(v)}),I(v,i.format),v.error?M.error(`resume command failed: ${v.error}`):M.info(`resume command succeeded`),a.end(),process.exit(v.error?1:0)}let g=On(n,f);if(!await h(i.dataDir,n.sessionId,n.requestId,g,{storeName:s,encryptSessions:n.encryptSessions}))throw Error(`UI tool resume validation failed`);await Nn({dataDir:i.dataDir,sessionId:n.sessionId,sessionStoreName:s,result:g,encryptSessions:n.encryptSessions}),await r(i.dataDir,n.sessionId,{storeName:s,encryptSessions:n.encryptSessions});let v=jn(n);o=v.sink;let b=n.sessionId,x=async e=>{if(b=e.sessionId??b,!y(e)){if(e.type===`stream_text_delta`){i.format===`text`&&F(e),await v.websocketSink?.sendTextDelta({sessionId:b,channel:i.channel,messageId:n.messageId,user:n.user,text:e.text});return}if(i.format===`text`&&F(e),e.type===`start`){await o?.send({sessionId:b,channel:i.channel,messageId:n.messageId,user:n.user,type:`start`,message:e.message});return}await o?.send({sessionId:b,channel:i.channel,messageId:n.messageId,user:n.user,type:`progress`,event:e})}},ee=await kn({dataDir:i.dataDir,sessionId:n.sessionId,sessionStoreName:s,toolCallId:g.toolCallId,toolName:g.toolName,encryptSessions:n.encryptSessions});c&&await x(c),await x({type:`tool_end`,sessionId:n.sessionId,toolCallId:g.toolCallId,name:g.toolName,input:ee,output:JSON.stringify({submitted:!0,values:g.values}),isError:!1});let S=n.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,w=await G(i.dataDir,S),E=await _({dataDir:i.dataDir,projectDir:vn(n.projectDir),systemAgentsDir:i.systemAgentsDir,systemAgentTeamsDir:i.systemAgentTeamsDir,agentPolicy:J(n.team)?{requestedTeamName:J(n.team)}:void 0,sessionStoreName:s,sessionId:n.sessionId,messageId:n.messageId,channel:i.channel,llm:i.llm,skillsLoadPaths:i.skillsLoadPaths,workdirAllowlist:i.workdirAllowlist,artifactsUrlWhitelist:i.artifactsUrlWhitelist,autoSkills:i.autoSkills,timeoutMs:i.timeoutMs,message:`[UI_TOOL_RESUME]
|
|
7
|
+
`,{mode:384});try{return await e(t)}finally{await T.rm(t,{force:!0})}}async function it(e){let t=e.includes(`-init`)?`init`:`mount`;M.info(`--encrypt-sessions starting gocryptfs ${t}`);try{await ft(`gocryptfs`,e),M.info(`--encrypt-sessions completed gocryptfs ${t}`)}catch(n){let r=n instanceof Error?n.message:String(n);throw M.warn(`--encrypt-sessions failed gocryptfs ${t}`,{error:r}),Error(`gocryptfs ${e.join(` `)} failed: ${r}`)}}async function at(){M.info(`--encrypt-sessions checking encryption dependencies`),await mt(`gocryptfs`,`required for --encrypt-sessions`),M.info(`--encrypt-sessions dependency available`,{command:`gocryptfs`});for(let e of ze)if(await pt(e)){M.info(`--encrypt-sessions unmount dependency available`,{command:e});return}throw Error(`--encrypt-sessions requires one of ${ze.join(`, `)} to be installed for secure unmount cleanup.`)}async function ot(e,t){M.info(`--encrypt-sessions mounting encrypted .aimax`,{encryptedDir:e,plainDir:t}),await rt(async n=>{await it([`-q`,`-passfile`,n,e,t])})}async function st(e){M.info(`--encrypt-sessions initializing encrypted .aimax directory`,{encryptedDir:e}),await rt(async t=>{await it([`-q`,`-init`,`-passfile`,t,e])})}async function U(e){let t=[];M.info(`--encrypt-sessions unmounting encrypted .aimax`,{plainDir:e});for(let n of Be)try{if(M.info(`--encrypt-sessions attempting encrypted .aimax unmount`,{command:n.label,plainDir:e}),await ft(n.command,[...n.args,e]),!await L(e)){M.info(`--encrypt-sessions unmounted encrypted .aimax`,{command:n.label,plainDir:e});return}let r=`${n.label} returned success but ${e} is still mounted`;t.push(r),M.warn(`--encrypt-sessions unmount command returned success but mountpoint remains`,{command:n.label,plainDir:e})}catch(r){let i=ht(n.label,r);t.push(i),M.warn(`--encrypt-sessions unmount attempt failed`,{command:n.label,plainDir:e,error:r instanceof Error?r.message:String(r)})}throw Error(`Failed to unmount ${e}: ${t.join(`; `)}`)}function ct(e){for(let t of Be)try{if(ne(t.command,[...t.args,e],{stdio:`ignore`}),!Ke(e))return}catch{}}function lt(e){let t=!1,n=()=>{t||(t=!0,ct(e))},r=()=>n(),i=()=>{n(),process.exit(130)},a=()=>{n(),process.exit(143)};return process.once(`exit`,r),process.once(`SIGINT`,i),process.once(`SIGTERM`,a),{release(){process.removeListener(`exit`,r),process.removeListener(`SIGINT`,i),process.removeListener(`SIGTERM`,a)}}}async function ut(e){let t=Ve(e),n=He(e),r=await R(n),i=await R(t),a=i&&await R(C.join(t,`gocryptfs.conf`)),o=r?await L(n):!1;M.info(`--encrypt-sessions preparing encrypted .aimax mount`,{dataDir:e,encryptedDir:t,plainDir:n,plainDirExists:r,encryptedDirExists:i,encryptedDirInitialized:a,plainDirMountPoint:o,plainDirEntryCount:await B(n),encryptedDirEntryCount:await B(t)});let s=()=>({mounted:!1,plainDir:n,encryptedDir:t,async cleanup(){}});try{await at()}catch(e){return M.warn(`--encrypt-sessions is unavailable; continuing with plaintext .aimax`,{error:e instanceof Error?e.message:String(e)}),await z(n),s()}if(await L(n))return M.warn(`--encrypt-sessions found existing .aimax mount; continuing without taking ownership`,{plainDir:n}),s();let c=null,l=[],u=null,d=null,f=!1;try{if(l=await et(e),l.length>0&&M.warn(`--encrypt-sessions found interrupted pre-gocryptfs migration backups`,{count:l.length}),!await R(t))if(M.info(`--encrypt-sessions encrypted .aimax directory does not exist; starting first-time migration`,{encryptedDir:t,plainDir:n,resumedBackupCount:l.length}),l.length>0?u=await V(e,n):c=await V(e,n),await z(t),await st(t),await z(n),await ot(t,n),f=!0,d=lt(n),M.info(`--encrypt-sessions mounted encrypted .aimax`,{plainDir:n,encryptedDir:t}),l.length>0){for(let e of l)await H(e,n,!0);u&&=(await H(u,n,!1),await T.rm(u,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed residual plaintext backup after migration`,{backupDir:u}),null);for(let e of l)await T.rm(e,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed resumed plaintext migration backup`,{backupDir:e});l=[]}else c&&=(await H(c,n,!0),await T.rm(c,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed plaintext migration backup`,{backupDir:c}),null);else if(M.info(`--encrypt-sessions encrypted .aimax directory exists; mounting existing encrypted data`,{encryptedDir:t,plainDir:n,resumedBackupCount:l.length,plainDirEntryCount:await B(n)}),await $e(t),l.length>0?u=await V(e,n):await Xe(n)||(c=await V(e,n)),await Ye(n),await ot(t,n),f=!0,d=lt(n),M.info(`--encrypt-sessions mounted encrypted .aimax`,{plainDir:n,encryptedDir:t}),l.length>0){for(let e of l)await H(e,n,!0);u&&=(await H(u,n,!1),await T.rm(u,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed residual plaintext backup after migration`,{backupDir:u}),null);for(let e of l)await T.rm(e,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed resumed plaintext migration backup`,{backupDir:e});l=[]}else c&&=(await H(c,n,!0),await T.rm(c,{recursive:!0,force:!0}),M.info(`--encrypt-sessions removed plaintext migration backup`,{backupDir:c}),null);return M.info(`--encrypt-sessions prepared encrypted .aimax mount result`,{mounted:f,plainDir:n,encryptedDir:t,plainDirMountPoint:await L(n),plainDirEntryCount:await B(n),encryptedDirEntryCount:await B(t)}),{mounted:f,plainDir:n,encryptedDir:t,async cleanup(){if(d?.release(),!f){M.info(`--encrypt-sessions cleanup skipped because encrypted .aimax is not mounted`,{plainDir:n,encryptedDir:t});return}f=!1,M.info(`--encrypt-sessions cleanup started`,{plainDir:n,encryptedDir:t});try{await U(n),M.info(`--encrypt-sessions cleanup completed`,{plainDir:n,encryptedDir:t})}catch(e){M.warn(`--encrypt-sessions failed to unmount encrypted .aimax; continuing shutdown`,{error:e instanceof Error?e.message:String(e)})}}}}catch(e){d?.release(),f&&await U(n).catch(e=>{M.warn(`--encrypt-sessions failed to unmount during mount rollback`,{error:e instanceof Error?e.message:String(e),plainDir:n,encryptedDir:t})}),c&&await R(c)&&await Xe(n)&&(await T.rm(n,{recursive:!0,force:!0}).catch(()=>{}),await T.rename(c,n).catch(()=>{}),M.info(`--encrypt-sessions restored plaintext backup after failed migration`,{backupDir:c,plainDir:n})),u&&await R(u)&&await Xe(n)&&(await T.rm(n,{recursive:!0,force:!0}).catch(()=>{}),await T.rename(u,n).catch(()=>{}),M.info(`--encrypt-sessions restored residual plaintext backup after failed migration`,{backupDir:u,plainDir:n}));let r=await tt(l,n).catch(e=>(M.warn(`--encrypt-sessions failed to restore interrupted plaintext backups after failed migration`,{error:e instanceof Error?e.message:String(e),plainDir:n,backupCount:l.length}),[]));return l=l.filter(e=>!r.includes(e)),M.warn(`--encrypt-sessions failed; continuing with plaintext .aimax`,{error:e instanceof Error?e.message:String(e),mountedBeforeFailure:f,plainDir:n,encryptedDir:t,backupDir:c,residualPlainBackupDir:u,resumedBackupCount:l.length}),await z(n),s()}}async function dt(e,t,n){if(!t.encryptSessions)return await nt(e),n();M.info(`--encrypt-sessions wrapper starting encrypted .aimax preparation`,{dataDir:e});let r=await ut(e);M.info(`--encrypt-sessions wrapper prepared encrypted .aimax state`,{dataDir:e,mounted:r.mounted,plainDir:r.plainDir,encryptedDir:r.encryptedDir});try{return M.info(`--encrypt-sessions wrapper entering protected operation`,{dataDir:e,mounted:r.mounted}),await n(r)}finally{M.info(`--encrypt-sessions wrapper starting cleanup`,{dataDir:e,mounted:r.mounted,plainDir:r.plainDir,encryptedDir:r.encryptedDir}),await r.cleanup(),M.info(`--encrypt-sessions wrapper finished cleanup`,{dataDir:e,mounted:r.mounted,plainDir:r.plainDir,encryptedDir:r.encryptedDir})}}async function ft(e,t){await new Promise((n,r)=>{te(e,t,{encoding:`utf-8`},e=>{if(e){r(e);return}n()})})}async function pt(e){try{return await ft(`sh`,[`-c`,`command -v "${e}" >/dev/null 2>&1`]),!0}catch{return!1}}async function mt(e,t){if(!await pt(e))throw Error(`--encrypt-sessions requires ${e}: ${t}.`)}function ht(e,t){return`${e} failed: ${t instanceof Error?t.message:String(t)}`}function gt(e){return re.sm4_encrypt_ecb(e)}function _t(e){return gt(e)}const vt=[`minimal`,`low`,`medium`,`high`,`xhigh`];function yt(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(vt.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of ${vt.join(`, `)}.`)}}function W(e,t){if(e===void 0)return;let n=e.trim();if(!n)return;let r=Number(n);if(!Number.isFinite(r))throw Error(`Invalid ${t}: ${e}. Must be a number.`);return r}function bt(e,t){let n=W(e,t);if(n!==void 0){if(!Number.isInteger(n))throw Error(`Invalid ${t}: ${e}. Must be an integer.`);return n}}function xt(e,t){if(e!==void 0){if(e<0||e>2)throw Error(`Invalid ${t}: ${e}. Must be between 0 and 2.`);return e}}function St(e,t){if(e!==void 0){if(e<0||e>1)throw Error(`Invalid ${t}: ${e}. Must be between 0 and 1.`);return e}}function Ct(e,t){if(e!==void 0){if(e<=0)throw Error(`Invalid ${t}: ${e}. Must be a positive integer.`);return e}}function wt(e={}){let t=Tt(e.apiFormat??process.env.AIMAX_API_FORMAT),n=e.baseUrl??process.env.AIMAX_BASE_URL,r=process.env.AIMAX_AUTH_TOKEN,i=process.env.AIMAX_API_KEY??process.env.AIMAX_LLM_API_KEY,a=e.authToken?_t(e.authToken):r?_t(r):e.apiKey??i,o=e.model??process.env.AIMAX_MODEL,s=[];if(n||s.push(`--base-url / AIMAX_BASE_URL`),a||s.push(`--api-key / AIMAX_API_KEY / AIMAX_LLM_API_KEY`),o||s.push(`--model / AIMAX_MODEL`),s.length>0)throw Error(`Missing required LLM configuration: ${s.join(`, `)}`);return{apiFormat:t,baseUrl:n,apiKey:a,model:o,contextWindow:e.contextWindow??(process.env.AIMAX_CONTEXT_WINDOW?Number(process.env.AIMAX_CONTEXT_WINDOW):void 0),flashModel:e.flashModel??process.env.AIMAX_FLASH_MODEL,thinking:e.thinking===void 0?yt(process.env.AIMAX_THINKING,`AIMAX_THINKING`):yt(e.thinking,`--thinking`),temperature:e.temperature===void 0?xt(W(process.env.AIMAX_TEMPERATURE,`AIMAX_TEMPERATURE`),`AIMAX_TEMPERATURE`):xt(e.temperature,`--temperature`),topK:e.topK===void 0?Ct(bt(process.env.AIMAX_TOP_K,`AIMAX_TOP_K`),`AIMAX_TOP_K`):Ct(e.topK,`--top-k`),topP:e.topP===void 0?St(W(process.env.AIMAX_TOP_P,`AIMAX_TOP_P`),`AIMAX_TOP_P`):St(e.topP,`--top-p`)}}function Tt(e){if(!e||e===`openai-completions`||e===`anthropic-messages`)return e;throw Error(`Unsupported LLM API format: ${e}`)}const Et=[`off`,`fallback`];function Dt(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if([`true`,`1`,`yes`,`on`].includes(n))return!0;if([`false`,`0`,`no`,`off`].includes(n))return!1;throw Error(`Invalid ${t}: ${e}. Must be true or false.`)}}function Ot(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(Et.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of ${Et.join(`, `)}.`)}}function kt(){return[`AIMAX_MEMORY_KC_ENABLED`,`AIMAX_MEMORY_KC_BASE_URL`,`AIMAX_MEMORY_KC_BASE_PATH`,`AIMAX_MEMORY_KC_AUTH_TOKEN`,`AIMAX_MEMORY_KC_SEARCH_MODE`,`AIMAX_MEMORY_KC_TOP_K`,`AIMAX_MEMORY_KC_SCORE_THRESHOLD`,`AIMAX_MEMORY_KC_TIMEOUT_MS`,`AIMAX_MEMORY_KC_SYNC_ENABLED`].some(e=>process.env[e]!==void 0)}function At(e){return Object.values(e).some(e=>e!==void 0)}function jt(e={}){if(!(!At(e)&&!kt()))return{knowledgeController:{enabled:e.kcEnabled??Dt(process.env.AIMAX_MEMORY_KC_ENABLED,`AIMAX_MEMORY_KC_ENABLED`),baseUrl:e.kcBaseUrl??process.env.AIMAX_MEMORY_KC_BASE_URL,basePath:e.kcBasePath??process.env.AIMAX_MEMORY_KC_BASE_PATH,authToken:e.kcAuthToken??process.env.AIMAX_MEMORY_KC_AUTH_TOKEN,searchMode:e.kcSearchMode===void 0?Ot(process.env.AIMAX_MEMORY_KC_SEARCH_MODE,`AIMAX_MEMORY_KC_SEARCH_MODE`)??`off`:Ot(e.kcSearchMode,`kcSearchMode`),topK:e.kcTopK??W(process.env.AIMAX_MEMORY_KC_TOP_K,`AIMAX_MEMORY_KC_TOP_K`),scoreThreshold:e.kcScoreThreshold??W(process.env.AIMAX_MEMORY_KC_SCORE_THRESHOLD,`AIMAX_MEMORY_KC_SCORE_THRESHOLD`),timeoutMs:e.kcTimeoutMs??W(process.env.AIMAX_MEMORY_KC_TIMEOUT_MS,`AIMAX_MEMORY_KC_TIMEOUT_MS`),syncEnabled:e.kcSyncEnabled??Dt(process.env.AIMAX_MEMORY_KC_SYNC_ENABLED,`AIMAX_MEMORY_KC_SYNC_ENABLED`)}}}function Mt(e,t){return t?C.resolve(t):C.join(e,`.aimax`,`plugins.json`)}async function G(e,t){let n=Mt(e,t);try{let e=await T.readFile(n,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Nt(e,t,n){let r=Mt(e,n);await T.mkdir(C.dirname(r),{recursive:!0}),await T.writeFile(r,JSON.stringify(t,null,2),`utf-8`)}function K(e){return typeof e==`object`&&!!e}function Pt(e){return K(e)&&e.type===`text`&&typeof e.text==`string`&&(e.textSignature===void 0||typeof e.textSignature==`string`)}function Ft(e){return K(e)&&e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`}function It(e){return K(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 Lt(e){return K(e)&&e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`&&K(e.arguments)&&(e.thoughtSignature===void 0||typeof e.thoughtSignature==`string`)}function Rt(e){return typeof e==`string`||Array.isArray(e)&&e.every(e=>Pt(e)||Ft(e))}function zt(e){return Array.isArray(e)&&e.every(e=>Pt(e)||It(e)||Lt(e))}function Bt(e){return K(e)&&typeof e.input==`number`&&typeof e.output==`number`&&typeof e.cacheRead==`number`&&typeof e.cacheWrite==`number`&&typeof e.totalTokens==`number`&&K(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 Vt(e){return!K(e)||typeof e.role!=`string`?!1:e.role===`user`?Rt(e.content):e.role===`assistant`?zt(e.content)&&typeof e.api==`string`&&typeof e.provider==`string`&&typeof e.model==`string`&&Bt(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=>Pt(e)||Ft(e))&&typeof e.isError==`boolean`:!1}async function Ht(e){let t;try{t=await T.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}`)}return Ut(n,`Message file`)}function Ut(e,t=`Messages input`){let n=Array.isArray(e)?e:[e];if(n.length===0||!n.every(e=>Vt(e)))throw Error(`${t} must contain one Message object or an array of Message objects`);return n}async function Wt(e){if([!!e.message,!!e.fromFile,e.messages!==void 0].filter(Boolean).length!==1)throw Error(`Exactly one of --message, --from-file, or messages must be provided`);return e.fromFile?{kind:`messages`,messages:await Ht(e.fromFile),source:`file`}:e.messages===void 0?{kind:`text`,message:e.message}:{kind:`messages`,messages:Ut(e.messages),source:`inline`}}var Gt=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()}))}},Kt=class{deliveryQueue=Promise.resolve();constructor(e){this.url=e}async send(e){this.enqueue(this.toPayload(e))}async close(){await this.deliveryQueue}enqueue(e){let t=this.deliveryQueue.then(async()=>{await this.post(e)},async()=>{await this.post(e)});return this.deliveryQueue=t.catch(()=>{}),t}async post(e){let t=Date.now(),n=qt(e);M.info(`sending callback event`,{callbackUrl:this.url,...n});let r=new AbortController,i=!1,a=setTimeout(()=>{i=!0,r.abort()},5e3);try{let a=await fetch(this.url,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:r.signal}),o=Date.now()-t;if(!a.ok){M.error(`callback event failed`,{callbackUrl:this.url,httpStatus:a.status,durationMs:o,timedOut:i,...n});return}M.info(`callback event delivered`,{callbackUrl:this.url,httpStatus:a.status,durationMs:o,...n})}catch(e){let r=Date.now()-t;M.error(`callback event failed`,{callbackUrl:this.url,error:e instanceof Error?e.message:String(e),durationMs:r,timedOut:i,...n})}finally{clearTimeout(a)}}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 qt(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 Jt(e,t){if(t.kind===`none`)return e;let n=new URL(e);return n.searchParams.set(`authToken`,t.token),n.toString()}const Yt=5e3,Xt=5e3,Zt=6e4;function q(){let e=globalThis.WebSocket;if(!e)throw Error(`WebSocket is not available in this runtime`);return e}function Qt(e){return e?{kind:`query_token`,token:e}:{kind:`none`}}function $t(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 en(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 tn=class{socket=null;connectPromise=null;heartbeatTimer=null;lastSentAt=0;heartbeatMessageId;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.sendPayload(JSON.stringify(t)),this.heartbeatMessageId=t.messageId}catch(e){M.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,parentSessionId:e.parentSessionId,messageId:e.messageId,channel:e.channel,user:e.user,timestamp:new Date().toISOString(),sequence:this.textSequence,delta:e.text};try{await this.sendPayload(JSON.stringify(t)),this.heartbeatMessageId=t.messageId}catch(e){M.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,this.stopHeartbeat();let e=this.socket;if(this.socket=null,this.connectPromise=null,!e)return;let t=q();if(e.readyState!==t.CLOSED)try{await nn(new Promise(t=>{$t(e,`close`,()=>t()),e.close()}),Xt,`WebSocket close timed out after ${Xt}ms`)}catch(e){M.warn(`websocket sink close timed out`,{url:this.url,error:e instanceof Error?e.message:String(e)})}}async ensureConnected(){if(!this.enabled)return;let e=q();if(this.socket&&this.socket.readyState===e.OPEN)return;if(this.connectPromise){await this.connectPromise;return}let t=new e(Jt(this.url,Qt(this.authToken)));this.connectPromise=new Promise((e,n)=>{$t(t,`open`,()=>{this.socket=t,this.markSent(),en(t,`close`,()=>{this.socket===t&&(this.socket=null),this.stopHeartbeat()}),e()}),$t(t,`error`,e=>{n(e)})});try{await this.connectPromise}finally{this.connectPromise=null}}async sendPayload(e){await nn(this.ensureConnected(),Yt,`WebSocket connection timed out after ${Yt}ms`);let t=q();!this.socket||this.socket.readyState!==t.OPEN||(this.socket.send(e),this.markSent())}markSent(){this.lastSentAt=Date.now(),this.scheduleHeartbeat()}scheduleHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setTimeout(()=>{this.sendHeartbeatIfIdle()},Zt)}stopHeartbeat(){this.heartbeatTimer&&=(clearTimeout(this.heartbeatTimer),null)}async sendHeartbeatIfIdle(){if(!this.enabled)return;let e=q();if(!(!this.socket||this.socket.readyState!==e.OPEN)&&!(Date.now()-this.lastSentAt<Zt)&&this.heartbeatMessageId)try{let e={type:`ping`,messageId:this.heartbeatMessageId};this.socket.send(JSON.stringify(e)),this.markSent()}catch(e){M.warn(`websocket sink disabled after heartbeat send failure`,{url:this.url,error:e instanceof Error?e.message:String(e)}),this.enabled=!1,this.stopHeartbeat()}}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)}`)}}}};function nn(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>i(Error(n)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}function rn(e){let t=e.trim();if(!t)throw Error(`Goal objective cannot be empty`);return t}function an(e,t){if(t.action===`unchanged`)return null;if(t.action===`created`||t.action===`replaced`)return t.action;if(e?.status!==t.goal.status)switch(t.goal.status){case`active`:return e?.status===`paused`?`resumed`:`updated`;case`paused`:return`paused`;case`complete`:return`completed`;case`budget_limited`:return`budget_limited`;default:return`updated`}return`updated`}function on(e){let t=an(e.before,e.result);return t?{type:`goal_updated`,sessionId:e.sessionId,action:t,goalId:e.result.goal.goalId,goalStatus:e.result.goal.status}:null}function sn(e){let t=e?.packageRoot??cn(),n=C.join(t,`models`),r=C.join(n,...`Xenova/bge-small-zh-v1.5`.split(`/`));if(S.existsSync(C.join(r,`config.json`)))return n}function cn(){let e=C.dirname(ie(import.meta.url));return C.basename(e)===`src`||C.basename(e)===`dist`?C.resolve(e,`..`):e}function ln(e){return{text:e.text,usage:e.usage,durationMs:e.durationMs,...e.error?{error:e.error}:{},...e.paused?{paused:e.paused}:{},...e.uiToolPending?{uiToolPending:e.uiToolPending}:{}}}function un(e){if(!e?.trim())return;let t=new Set,n=[];for(let r of e.split(`,`)){let e=r.trim();if(!e)continue;let i=dn(e);if(!i)throw Error(`Invalid --artifacts-url-whitelist entry: ${e}. Expected a domain or URL with a valid hostname.`);t.has(i)||(t.add(i),n.push(i))}return n.length>0?n:void 0}function dn(e){try{let t=/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`http://${e}`,n=new URL(t);return n.username||n.password?null:n.hostname.trim().toLowerCase()||null}catch{return null}}const fn=[`start`,`text`,`done`,`error`,`hitl`],pn=[`off`,`gate`,`dry_run`,`write`];function mn(e){if(!e?.trim())return new Set(fn);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(fn)}function hn(e){if(e.disableTopicSegmentation===!0||process.env.AIMAX_DISABLE_TOPIC_SEGMENTATION===`true`)return{enabled:!1};let t=sn();return t?{embeddingModelDir:t}:void 0}function gn(e){return e.disableTitle===!0||process.env.AIMAX_DISABLE_TITLE===`true`?{enabled:!1}:void 0}function _n(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 vn(e){return e?.trim()||void 0}function J(e){return e?.trim()||void 0}function yn(e){let t=(e.systemAgentsDir??process.env.AIMAX_SYSTEM_AGENTS_DIR)?.trim();if(t){if(!C.isAbsolute(t)){let n=e.systemAgentsDir===void 0?`AIMAX_SYSTEM_AGENTS_DIR`:`--system-agents-dir`;throw Error(`Invalid ${n}: ${t}. Path must be absolute.`)}return t}}function bn(e){let t=(e.systemAgentTeamsDir??process.env.AIMAX_SYSTEM_AGENT_TEAMS_DIR)?.trim();if(t){if(!C.isAbsolute(t)){let n=e.systemAgentTeamsDir===void 0?`AIMAX_SYSTEM_AGENT_TEAMS_DIR`:`--system-agent-teams-dir`;throw Error(`Invalid ${n}: ${t}. Path must be absolute.`)}return t}}function xn(e){return e?f(e):void 0}function Sn(e){if(!e?.trim())return[];let t=e.split(`,`).map(e=>e.trim()).filter(Boolean),n=new Set,r=[];for(let e of t){if(!C.isAbsolute(e))throw Error(`Invalid --skillsLoadPaths entry: ${e}. Each path must be absolute.`);n.has(e)||(n.add(e),r.push(e))}return r}function Cn(e){if(!e?.trim())return[];let t=e.split(`,`).map(e=>e.trim()).filter(Boolean),n=new Set,r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}function wn(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if([`true`,`1`,`yes`,`on`].includes(n))return!0;if([`false`,`0`,`no`,`off`].includes(n))return!1;throw Error(`Invalid ${t}: ${e}. Must be true or false.`)}}function Tn(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(pn.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of off,gate,dry_run,write.`)}}function En(e){let t=e.autoSkillsLoadEnabled===void 0?wn(process.env.AIMAX_AUTO_SKILLS_LOAD_ENABLED,`AIMAX_AUTO_SKILLS_LOAD_ENABLED`):wn(e.autoSkillsLoadEnabled,`--auto-skills-load-enabled`),n=e.autoSkillsReviewMode===void 0?Tn(process.env.AIMAX_AUTO_SKILLS_REVIEW_MODE,`AIMAX_AUTO_SKILLS_REVIEW_MODE`):Tn(e.autoSkillsReviewMode,`--auto-skills-review-mode`),r={};return t!==void 0&&(r.load={enabled:t}),n!==void 0&&(r.review={mode:n}),r.load||r.review?r:void 0}function Dn(e,t){if(e.inputText&&t){let n=ee(e.inputText,t);return n.submittedBy={userId:e.user,channel:e.channel??`IM`},n}if(!e.inputJson&&!e.inputText)throw Error(`Either --input-json or --input-text must be provided for the 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}`)}}function On(e,t){if(!e.inputJson)throw Error(`UI tool resume requires --input-json`);try{let n=JSON.parse(e.inputJson),r=n&&typeof n==`object`&&`values`in n&&n.values&&typeof n.values==`object`&&!Array.isArray(n.values)?n.values:n;return{requestId:t.request.requestId,sessionId:t.sessionId,toolCallId:t.request.toolCallId,toolName:t.request.toolName,values:r,submittedAt:new Date().toISOString()}}catch(e){throw Error(`Invalid --input-json: ${e.message}`)}}async function kn(e){let t=await d(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions});for(let n=t.length-1;n>=0;--n){let r=t[n];if(r?.role!==`assistant`||!Array.isArray(r.toolCalls))continue;let i=r.toolCalls.find(t=>t.id===e.toolCallId&&t.name===e.toolName);if(i)return i.arguments}}async function An(e){let t=_n(e),n=e.channel??`WEB`,r=wt({apiFormat:e.apiFormat,baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow?Number(e.contextWindow):void 0,flashModel:e.flashModel,thinking:e.thinking});return{dataDir:t,systemAgentsDir:yn(e),systemAgentTeamsDir:bn(e),channel:n,format:e.output===`json`?`json`:`text`,timeoutMs:e.timeout?Number(e.timeout):void 0,llm:r,skillsLoadPaths:Sn(e.skillsLoadPaths),workdirAllowlist:Cn(e.workdirAllowlist),artifactsUrlWhitelist:un(e.artifactsUrlWhitelist),autoSkills:En(e)}}function jn(e){let t=[],n=null;return e.callbackUrl&&t.push(new Kt(e.callbackUrl)),e.streamUrl&&(n=new tn(e.streamUrl,mn(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new Gt(t),websocketSink:n}}async function Mn(e){let{dataDir:t,sessionId:n,sessionStoreName:r,toolCallId:i,toolName:c,resolution:l,encryptSessions:u}=e;if(!i||!c||!b(c))return;let d=(e,t)=>{switch(e){case`request_approval`:return a(t);case`clarify`:return o(t);case`request_review`:return s(t);default:return JSON.stringify({action:t.action,values:t.values})}};await g(t,n,e=>{let t=e.findIndex(e=>e.role===`tool_result`&&e.toolCallId===i&&e.toolName===c);if(t===-1)return e;let n=e.slice(0,t+1);return n[t]={...n[t],content:d(c,l),isError:!1},n},{storeName:r,encryptSessions:u})}async function Nn(e){let{dataDir:t,sessionId:n,sessionStoreName:r,result:i,encryptSessions:a}=e;await g(t,n,e=>{let t=e.findIndex(e=>e.role===`assistant`&&Array.isArray(e.toolCalls)&&e.toolCalls.some(e=>e.id===i.toolCallId&&e.name===i.toolName));if(t===-1)return e;let n=e.slice(0,t+1);return n.push({role:`tool_result`,toolCallId:i.toolCallId,toolName:i.toolName,content:JSON.stringify({submitted:!0,values:i.values}),isError:!1,timestamp:i.submittedAt}),n},{storeName:r,encryptSessions:a})}function Pn(){let e=jt();return e?{core:e}:void 0}async function Fn(n){let i=_n(n);await dt(i,n,async()=>{ye(i,{messageId:n.messageId,sessionId:n.sessionId,sessionStoreName:xn(n.sessionStore)});let a=new we(`resume command`),o=null;try{let i=await An(n),s=xn(n.sessionStore),c=null;if(n.goal||n.goalFile){let r;r=n.goalFile?await T.readFile(n.goalFile,`utf-8`):n.goal;let a=rn(r),o=n.tokenBudget===void 0?void 0:n.tokenBudget===`0`||n.tokenBudget===``?null:Number(n.tokenBudget);o!=null&&(Number.isNaN(o)||o<=0)&&(P(`error: --token-budget must be a positive integer, or 0 for unlimited`),process.exit(1));try{let e=await p(i.dataDir,n.sessionId,{storeName:s}),r=await t({dataDir:i.dataDir,sessionId:n.sessionId,objective:a,tokenBudget:o,force:n.force,storeName:s});c=on({sessionId:n.sessionId,before:e,result:r})}catch(t){throw t instanceof e&&(P(t.message),P(`Existing: ${t.existingObjectivePreview}`),process.exit(2)),t}}M.info(`resume command started`,{sessionId:n.sessionId,requestId:n.requestId,channel:i.channel,dataDir:i.dataDir});let d=await l(i.dataDir,n.sessionId,{storeName:s,encryptSessions:n.encryptSessions}),f=d?null:await u(i.dataDir,n.sessionId,{storeName:s,encryptSessions:n.encryptSessions});if(!d&&!f)throw Error(`No pending HITL or UI tool request found for session "${n.sessionId}"`);if(d){if(d.request.requestId!==n.requestId)throw Error(`Request ID mismatch: pending is "${d.request.requestId}", got "${n.requestId}"`);if(d.status===`expired`)throw Error(`HITL request has expired`);if(d.status===`cancelled`)throw Error(`HITL request has been cancelled`)}else if(f){if(f.request.requestId!==n.requestId)throw Error(`Request ID mismatch: pending is "${f.request.requestId}", got "${n.requestId}"`);if(f.status!==`pending`)throw Error(`UI tool request is already "${f.status}", cannot resume`)}if(d){let e=Dn(n,d.request),t=await m({dataDir:i.dataDir,sessionStoreName:s,sessionId:n.sessionId,requestId:n.requestId,resolution:e}),r=t.state;if(!r)throw Error(`Resolved HITL state was not persisted`);let l=In(e,r.request.kind);await Mn({dataDir:i.dataDir,sessionId:n.sessionId,sessionStoreName:s,toolCallId:r.toolContext?.toolCallId,toolName:r.toolContext?.toolName,resolution:e,encryptSessions:n.encryptSessions});let u=jn(n);o=u.sink;let f=n.sessionId,p=async e=>{if(f=e.sessionId??f,!y(e)){if(e.type===`stream_text_delta`){i.format===`text`&&F(e),await u.websocketSink?.sendTextDelta({sessionId:f,channel:i.channel,messageId:n.messageId,user:n.user,text:e.text});return}i.format===`text`&&F(e),await o?.send({sessionId:f,channel:i.channel,messageId:n.messageId,user:n.user,type:`progress`,event:e})}};c&&await p(c),await p({type:`hitl_resumed`,requestId:n.requestId,resolution:e,sessionId:n.sessionId}),`idempotentReplay`in t&&t.idempotentReplay&&(M.info(`resume command treated as idempotent replay`,{sessionId:n.sessionId,requestId:n.requestId,idempotencyKey:e.idempotencyKey}),I({sessionId:n.sessionId,text:`Resume request already processed.`,usage:{input:0,output:0,total:0},durationMs:0},i.format),a.end(),process.exit(0));let h=n.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,g=await G(i.dataDir,h),v;try{v=await _({dataDir:i.dataDir,projectDir:vn(n.projectDir),systemAgentsDir:i.systemAgentsDir,systemAgentTeamsDir:i.systemAgentTeamsDir,agentPolicy:J(n.team)?{requestedTeamName:J(n.team)}:void 0,sessionStoreName:s,sessionId:n.sessionId,messageId:n.messageId,channel:i.channel,llm:i.llm,skillsLoadPaths:i.skillsLoadPaths,workdirAllowlist:i.workdirAllowlist,artifactsUrlWhitelist:i.artifactsUrlWhitelist,autoSkills:i.autoSkills,timeoutMs:i.timeoutMs,message:l,encryptSessions:n.encryptSessions??!1,topicSegmentation:hn(n),titleGeneration:gn(n),memory:Pn(),hitlResume:{request:r.request,resolution:e,checkpoint:r.checkpoint,toolContext:r.toolContext},plugins:g?{config:g,dataDir:i.dataDir,workspaceDir:C.join(i.dataDir,`workspace`),bundledDir:process.env.AIMAX_PLUGINS_BUNDLED_DIR,llmAllowlist:g.llmAllowlist}:void 0,onProgress:p,onLog:xe})}finally{}v.error?await o?.send({sessionId:v.sessionId,channel:i.channel,messageId:n.messageId,user:n.user,type:`error`,message:v.error}):await o?.send({sessionId:v.sessionId,channel:i.channel,messageId:n.messageId,user:n.user,type:`done`,result:ln(v)}),I(v,i.format),v.error?M.error(`resume command failed: ${v.error}`):M.info(`resume command succeeded`),a.end(),process.exit(v.error?1:0)}let g=On(n,f);if(!await h(i.dataDir,n.sessionId,n.requestId,g,{storeName:s,encryptSessions:n.encryptSessions}))throw Error(`UI tool resume validation failed`);await Nn({dataDir:i.dataDir,sessionId:n.sessionId,sessionStoreName:s,result:g,encryptSessions:n.encryptSessions}),await r(i.dataDir,n.sessionId,{storeName:s,encryptSessions:n.encryptSessions});let v=jn(n);o=v.sink;let b=n.sessionId,x=async e=>{if(b=e.sessionId??b,!y(e)){if(e.type===`stream_text_delta`){i.format===`text`&&F(e),await v.websocketSink?.sendTextDelta({sessionId:b,channel:i.channel,messageId:n.messageId,user:n.user,text:e.text});return}if(i.format===`text`&&F(e),e.type===`start`){await o?.send({sessionId:b,channel:i.channel,messageId:n.messageId,user:n.user,type:`start`,message:e.message});return}await o?.send({sessionId:b,channel:i.channel,messageId:n.messageId,user:n.user,type:`progress`,event:e})}},ee=await kn({dataDir:i.dataDir,sessionId:n.sessionId,sessionStoreName:s,toolCallId:g.toolCallId,toolName:g.toolName,encryptSessions:n.encryptSessions});c&&await x(c),await x({type:`tool_end`,sessionId:n.sessionId,toolCallId:g.toolCallId,name:g.toolName,input:ee,output:JSON.stringify({submitted:!0,values:g.values}),isError:!1});let S=n.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,w=await G(i.dataDir,S),E=await _({dataDir:i.dataDir,projectDir:vn(n.projectDir),systemAgentsDir:i.systemAgentsDir,systemAgentTeamsDir:i.systemAgentTeamsDir,agentPolicy:J(n.team)?{requestedTeamName:J(n.team)}:void 0,sessionStoreName:s,sessionId:n.sessionId,messageId:n.messageId,channel:i.channel,llm:i.llm,skillsLoadPaths:i.skillsLoadPaths,workdirAllowlist:i.workdirAllowlist,artifactsUrlWhitelist:i.artifactsUrlWhitelist,autoSkills:i.autoSkills,timeoutMs:i.timeoutMs,message:`[UI_TOOL_RESUME]
|
|
8
8
|
The pending UI tool result has been written into the transcript. Continue from the latest tool result without repeating the same form request.`,encryptSessions:n.encryptSessions??!1,topicSegmentation:hn(n),titleGeneration:gn(n),memory:Pn(),uiToolResume:g,plugins:w?{config:w,dataDir:i.dataDir,workspaceDir:C.join(i.dataDir,`workspace`),bundledDir:process.env.AIMAX_PLUGINS_BUNDLED_DIR,llmAllowlist:w.llmAllowlist}:void 0,onProgress:x,onLog:xe});E.error?await o?.send({sessionId:E.sessionId,channel:i.channel,messageId:n.messageId,user:n.user,type:`error`,message:E.error}):await o?.send({sessionId:E.sessionId,channel:i.channel,messageId:n.messageId,user:n.user,type:`done`,result:ln(E)}),I(E,i.format),E.error?M.error(`resume command failed: ${E.error}`):M.info(`resume command succeeded`),a.end(),process.exit(E.error?1:0)}catch(e){let t=e;o&&(t.message.includes(`expired`)&&await o.send({sessionId:n.sessionId,channel:n.channel??`WEB`,messageId:n.messageId,user:n.user,type:`progress`,event:{type:`hitl_expired`,sessionId:n.sessionId,requestId:n.requestId,reason:t.message}}),t.message.includes(`cancelled`)&&await o.send({sessionId:n.sessionId,channel:n.channel??`WEB`,messageId:n.messageId,user:n.user,type:`progress`,event:{type:`hitl_cancelled`,sessionId:n.sessionId,requestId:n.requestId,reason:t.message}}),await o.send({sessionId:n.sessionId,channel:n.channel??`WEB`,messageId:n.messageId,user:n.user,type:`error`,message:`Resume failed: ${t.message}`})),M.error(`resume command error: ${t.message}`),P(`Fatal: ${t.message}`),a.end(),process.exit(1)}})}function In(e,t){return n(e,t)}function Ln(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)`).option(`--project-dir <path>`,`Current project directory used as the default cwd context`).option(`--system-agents-dir <path>`,`System agent definition directory (overrides AIMAX_SYSTEM_AGENTS_DIR, default: /aimax/agents)`).option(`--system-agent-teams-dir <path>`,`System Agent team definition directory (overrides AIMAX_SYSTEM_AGENT_TEAMS_DIR, default: /aimax/agent-teams)`).option(`--team <name>`,`Agent team name to resume with its configured coordinator`).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`).option(`--input-json <json>`,`JSON string with the resolution (action, values, etc.)`).option(`--input-text <text>`,`Plain text response for IM channels without rich UI (e.g. '同意', '拒绝')`).option(`--skillsLoadPaths <paths>`,`Comma-separated absolute skill load paths`).option(`--workdir-allowlist <paths>`,`Comma-separated additional roots allowed as cwd for exec-style tools`).option(`--auto-skills-load-enabled <boolean>`,`Enable learned auto-skill loading for the main agent (overrides AIMAX_AUTO_SKILLS_LOAD_ENABLED)`).option(`--auto-skills-review-mode <mode>`,`Auto-skill review mode: off, gate, dry_run, or write (overrides AIMAX_AUTO_SKILLS_REVIEW_MODE)`).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-format <format>`,`LLM API format: openai-completions or anthropic-messages (overrides AIMAX_API_FORMAT)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY / AIMAX_LLM_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(`--thinking <level>`,`Explicit thinking level: minimal, low, medium, high, or xhigh (overrides AIMAX_THINKING)`).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`).option(`--goal <text>`,`Set or replace the thread goal objective before resuming`).option(`--goal-file <path>`,`Read goal objective from a file`).option(`--token-budget <n>`,`Token budget for the goal (positive integer, or 0 for unlimited)`).option(`--force`,`Replace existing goal with a different objective`).option(`--encrypt-sessions`,`Enable encryption for the .aimax data directory`).option(`--disable-topic-segmentation`,`Disable smart topic segmentation for this resume run`).option(`--disable-title`,`Skip LLM session title generation for new sessions (overrides AIMAX_DISABLE_TITLE)`).action(async e=>{await Fn(e)})}function Rn(e,t){return{notify:(n,r=`info`)=>{t?.readyState===1?t.send(JSON.stringify({type:`diagnostic`,sessionId:e,level:r,message:n})):console.log(`[${r}] ${n}`)},confirm:async n=>!t||t.readyState!==1?!1:new Promise(r=>{let i=`confirm-${Date.now()}`;t.send(JSON.stringify({type:`hitl_confirm`,sessionId:e,id:i,message:n}));let a=e=>{try{let t=JSON.parse(String(e));r(t.id===i&&t.confirmed===!0)}catch{r(!1)}};typeof t.once==`function`?t.once(`message`,a):t.addEventListener(`message`,e=>a(e.data),{once:!0})}),select:async(n,r)=>{if(!(!t||t.readyState!==1))return new Promise(i=>{let a=`select-${Date.now()}`;t.send(JSON.stringify({type:`hitl_select`,sessionId:e,id:a,title:n,options:r}));let o=e=>{try{let t=JSON.parse(String(e));i(t.id===a?t.selected:void 0)}catch{i(void 0)}};typeof t.once==`function`?t.once(`message`,o):t.addEventListener(`message`,e=>o(e.data),{once:!0})})},setStatus:n=>{t?.readyState===1?t.send(JSON.stringify({type:`diagnostic`,sessionId:e,level:`info`,message:n})):console.log(`[status] ${n}`)}}}const zn=[`start`,`text`,`done`,`error`],Bn=[`off`,`gate`,`dry_run`,`write`];function Vn(e){if(!e?.trim())return new Set(zn);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(zn)}function Hn(e){if(e.disableTopicSegmentation===!0||process.env.AIMAX_DISABLE_TOPIC_SEGMENTATION===`true`)return{enabled:!1};let t=sn();return t?{embeddingModelDir:t}:void 0}function Un(e){return e.disableTitle===!0||process.env.AIMAX_DISABLE_TITLE===`true`?{enabled:!1}:void 0}function Y(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 Wn(e){return e?.trim()||void 0}function Gn(e){let t=(e.systemAgentsDir??process.env.AIMAX_SYSTEM_AGENTS_DIR)?.trim();if(t){if(!C.isAbsolute(t)){let n=e.systemAgentsDir===void 0?`AIMAX_SYSTEM_AGENTS_DIR`:`--system-agents-dir`;throw Error(`Invalid ${n}: ${t}. Path must be absolute.`)}return t}}function Kn(e){let t=(e.systemAgentTeamsDir??process.env.AIMAX_SYSTEM_AGENT_TEAMS_DIR)?.trim();if(t){if(!C.isAbsolute(t)){let n=e.systemAgentTeamsDir===void 0?`AIMAX_SYSTEM_AGENT_TEAMS_DIR`:`--system-agent-teams-dir`;throw Error(`Invalid ${n}: ${t}. Path must be absolute.`)}return t}}function X(e){return e?.trim()||void 0}function qn(e){return e??`WEB`}function Jn(e){return e?f(e):void 0}function Yn(e,t){return e===`CRON`?`crons`:Jn(t)}function Xn(e){if(!e?.trim())return[];let t=e.split(`,`).map(e=>e.trim()).filter(Boolean),n=new Set,r=[];for(let e of t){if(!C.isAbsolute(e))throw Error(`Invalid --skillsLoadPaths entry: ${e}. Each path must be absolute.`);n.has(e)||(n.add(e),r.push(e))}return r}function Zn(e){if(!e?.trim())return[];let t=e.split(`,`).map(e=>e.trim()).filter(Boolean),n=new Set,r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}function Qn(e){let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`\\`&&n+1<e.length){let r=e[n+1];if(r===`,`||r===`\\`||r===`=`){t+=r,n+=1;continue}}t+=r}return t}function $n(e){let t=[],n=``;for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`\\`&&r+1<e.length){let t=e[r+1];if(t===`,`||t===`\\`){n+=t,r+=1;continue}}if(i===`,`){t.push(n),n=``;continue}n+=i}return t.push(n),t}function er(e){if(!e?.trim())return{};let t=[],n=new Set;for(let r of $n(e)){let e=r.trim();if(!e)continue;let i=e.indexOf(`=`);if(i<=0)throw Error(`Invalid --env entry: ${e}. Expected KEY=VALUE (use \\= to embed an equals sign in the value).`);let a=e.slice(0,i).trim(),o=e.slice(i+1).trim();if(!a)throw Error(`Invalid --env entry: ${e}. Key must not be empty.`);if(n.has(a))throw Error(`Invalid --env entry: duplicate key ${a}.`);n.add(a),t.push([a,Qn(o)])}return Object.fromEntries(t)}function tr(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if([`true`,`1`,`yes`,`on`].includes(n))return!0;if([`false`,`0`,`no`,`off`].includes(n))return!1;throw Error(`Invalid ${t}: ${e}. Must be true or false.`)}}function nr(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(Bn.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of off,gate,dry_run,write.`)}}function rr(e){let t=e.autoSkillsLoadEnabled===void 0?tr(process.env.AIMAX_AUTO_SKILLS_LOAD_ENABLED,`AIMAX_AUTO_SKILLS_LOAD_ENABLED`):tr(e.autoSkillsLoadEnabled,`--auto-skills-load-enabled`),n=e.autoSkillsReviewMode===void 0?nr(process.env.AIMAX_AUTO_SKILLS_REVIEW_MODE,`AIMAX_AUTO_SKILLS_REVIEW_MODE`):nr(e.autoSkillsReviewMode,`--auto-skills-review-mode`),r={};return t!==void 0&&(r.load={enabled:t}),n!==void 0&&(r.review={mode:n}),r.load||r.review?r:void 0}function ir(e,t){return e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`}function ar(e,t){if(t<=0)return[``];let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n.length>0?n:[``]}function or(e,t,n=78){let r=Math.max(0,n-4),i=e?e.length+2:0,a=Math.max(r,i,...t.map(e=>e.length)),o=a+2,s=e?` ${ir(e,Math.max(0,a-2))} `:``,c=e?`┌${s}${`─`.repeat(Math.max(0,o-s.length))}┐`:`┌${`─`.repeat(o)}┐`,l=`└${`─`.repeat(o)}┘`;return[c,...t.flatMap(e=>ar(e,a).map(e=>`│ ${e.padEnd(a,` `)} │`)),l].join(`
|
|
9
|
-
`)}function sr(e){return e.kind===`text`?`inline message (${e.message.length} chars)`:e.source===`file`?`message file (${e.messages.length} messages)`:`inline messages (${e.messages.length} messages)`}function Z(e,t=`-`){return e==null||e===``?t:String(e)}function cr(e){return e?`set`:`unset`}function lr(e){return e?`true`:`false`}function ur(e,t){let n=Yn(t.channel,e.sessionStore)??`sessions`,r=t.timeoutMs===void 0?`default`:`${t.timeoutMs}`,i=e.callbackUrl?`enabled`:`disabled`,a=e.streamUrl?`enabled`:`disabled`,o=sr(t.input),s=t.input.kind===`text`?`inline`:e.fromFile??t.input.source,c=oe(),l=Hn(e)?.enabled===!1?`disabled`:`enabled`,u=Un(e)?.enabled===!1?`disabled`:`enabled`,d=e.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,f=[...Vn(e.streamEvents)].join(`,`),p=t.autoSkills?.load?.enabled,m=t.autoSkills?.review?.mode,h=e.tokenBudget===`0`?`unlimited`:Z(e.tokenBudget),g=t.artifactsUrlWhitelist?.join(`,`)??`-`,_=e.env?Object.keys(er(e.env)):[],v=_.length===0?`-`:`${_.length} key${_.length===1?``:`s`}`;return{banner:or(void 0,[`AIMax CLI`,`Stateless Agent Runner`]),contextBox:or(`Run Context`,[`time : ${c}`,`dataDir : ${t.dataDir}`,`projectDir : ${Wn(e.projectDir)??`-`}`,`systemAgents : ${t.systemAgentsDir??`/aimax/agents`}`,`agentTeams : ${t.systemAgentTeamsDir??`/aimax/agent-teams`}`,`agent : ${X(e.agent)??`-`}`,`team : ${X(e.team)??`-`}`,`channel : ${t.channel}`,`user : ${e.user??`-`}`,`message : ${e.message===void 0?`-`:`inline (${e.message.length} chars)`}`,`fromFile : ${Z(e.fromFile)}`,`input : ${o}`,`skillsPaths : ${t.skillsLoadPaths.length>0?t.skillsLoadPaths.join(`,`):`-`}`,`autoSkillLoad: ${p===void 0?`-`:String(p)}`,`autoSkillRev : ${m??`-`}`,`sessionId : ${e.sessionId??`new`}`,`sessionStore : ${n}`,`messageId : ${e.messageId??`-`}`,`workspace : ${C.join(t.dataDir,`workspace`)}`,`baseUrl : ${t.llm.baseUrl}`,`apiKey : ${cr(t.llm.apiKey)}`,`authToken : ${cr(e.authToken)}`,`model : ${t.llm.model}`,`contextWindow: ${Z(t.llm.contextWindow)}`,`flashModel : ${Z(t.llm.flashModel)}`,`thinking : ${Z(t.llm.thinking)}`,`temperature : ${Z(t.llm.temperature)}`,`topK : ${Z(t.llm.topK)}`,`topP : ${Z(t.llm.topP)}`,`callbackUrl : ${Z(e.callbackUrl)}`,`streamUrl : ${Z(e.streamUrl)}`,`streamAuth : ${cr(e.streamAuthToken)}`,`streamEvents : ${f}`,`artifactUrls : ${g}`,`output : ${t.format}`,`callback : ${i}`,`websocket : ${a}`,`timeoutMs : ${r}`,`pluginsConfig: ${Z(d)}`,`env : ${v}`,`goal : ${e.goal===void 0?`-`:`inline (${e.goal.length} chars)`}`,`goalFile : ${Z(e.goalFile)}`,`tokenBudget : ${h}`,`force : ${lr(e.force)}`,`resumeReqId : ${Z(e.resumeRequestId)}`,`resumeInput : ${e.resumeInputJson===void 0?`-`:`inline (${e.resumeInputJson.length} chars)`}`,`resumeFile : ${Z(e.resumeFromFile)}`,`encryptSess : ${lr(e.encryptSessions)}`,`topicSegment : ${l}`,`titleGen : ${u}`]),logContext:{time:c,channel:t.channel,user:e.user,dataDir:t.dataDir,projectDir:Wn(e.projectDir),systemAgentsDir:t.systemAgentsDir,systemAgentTeamsDir:t.systemAgentTeamsDir,agent:X(e.agent),team:X(e.team),workspaceDir:C.join(t.dataDir,`workspace`),sessionId:e.sessionId??`new`,sessionStore:n,messageId:e.messageId,hasMessage:e.message!==void 0,fromFile:e.fromFile,skillsLoadPaths:t.skillsLoadPaths.join(`,`)||void 0,autoSkillsLoadEnabled:p,autoSkillsReviewMode:m,baseUrl:t.llm.baseUrl,hasApiKey:!!t.llm.apiKey,hasAuthToken:!!e.authToken,model:t.llm.model,contextWindow:t.llm.contextWindow,flashModel:t.llm.flashModel,thinking:t.llm.thinking,temperature:t.llm.temperature,topK:t.llm.topK,topP:t.llm.topP,callbackUrl:e.callbackUrl,streamUrl:e.streamUrl,hasStreamAuthToken:!!e.streamAuthToken,streamEvents:f,artifactsUrlWhitelist:t.artifactsUrlWhitelist?.join(`,`)||void 0,output:t.format,hasCallback:!!e.callbackUrl,hasStream:!!e.streamUrl,timeoutMs:t.timeoutMs,pluginsConfig:d,envKeys:_.length>0?_.join(`,`):void 0,hasGoal:e.goal!==void 0,goalFile:e.goalFile,tokenBudget:h===`-`?void 0:h,force:!!e.force,resumeRequestId:e.resumeRequestId,hasResumeInputJson:e.resumeInputJson!==void 0,resumeFromFile:e.resumeFromFile,encryptSessions:!!e.encryptSessions,topicSegmentation:l,titleGeneration:u,inputKind:t.input.kind,inputSource:s,inputSummary:o}}}async function dr(e,t){let n=Y(e),r=qn(e.channel),i=wt({apiFormat:e.apiFormat,baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow?Number(e.contextWindow):void 0,flashModel:e.flashModel,thinking:e.thinking,temperature:e.temperature===void 0?void 0:Number(e.temperature),topK:e.topK===void 0?void 0:Number(e.topK),topP:e.topP===void 0?void 0:Number(e.topP)});return{dataDir:n,systemAgentsDir:Gn(e),systemAgentTeamsDir:Kn(e),channel:r,format:e.output===`json`?`json`:`text`,timeoutMs:e.timeout?Number(e.timeout):void 0,llm:i,input:t,skillsLoadPaths:Xn(e.skillsLoadPaths),workdirAllowlist:Zn(e.workdirAllowlist),artifactsUrlWhitelist:un(e.artifactsUrlWhitelist),autoSkills:rr(e)}}function fr(e){if(e.kind===`text`)return e.message;if(e.messages.length!==1)return null;let[t]=e.messages;if(t.role!==`user`)return null;if(typeof t.content==`string`)return t.content;if(t.content.length===0)return null;let n=[];for(let e of t.content){if(e.type!==`text`)return null;n.push(e.text)}return n.join(`
|
|
10
|
-
`)}async function pr(e,t){if(!e.sessionId)return null;let n=fr(t);if(!n)return null;let r=await l(Y(e),e.sessionId,{storeName:Jn(e.sessionStore),encryptSessions:e.encryptSessions});return!r||r.status!==`pending`||!x(n,r.request)?null:{requestId:r.request.requestId,inputText:n}}function mr(e){let t=[],n=null;return e.callbackUrl&&t.push(new Kt(e.callbackUrl)),e.streamUrl&&(n=new tn(e.streamUrl,Vn(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new Gt(t),websocketSink:n}}async function Q(e,t){M.info(`dispatching external event`,Pr(t)),await e.sink.send(t)}function hr(e){let t={sessionId:e.sessionId,messageId:e.messageId,parentSessionId:e.parentSessionId,depth:e.depth,scope:e.scope,phase:e.phase,...e.details};if(e.level===`error`){M.error(e.message,t);return}if(e.level===`warn`){M.warn(e.message,t);return}M.info(e.message,t)}function gr(e,t,n,r,i){return{sink:e,websocketSink:t,channel:n,defaultMessageId:r,user:i}}function _r(e){let t=new AbortController,n=n=>{M.warn(`run abort signal received`,{signal:n,uptimeMs:Math.round(process.uptime()*1e3),alreadyAborted:t.signal.aborted,...e?.()}),t.abort()},r=()=>n(`SIGTERM`),i=()=>n(`SIGINT`);return process.once(`SIGTERM`,r),process.once(`SIGINT`,i),{controller:t,cleanup:()=>{process.off(`SIGTERM`,r),process.off(`SIGINT`,i)}}}function vr(e){return{activeSessionId:e??`pending`,finalResult:null,loggerSessionId:void 0}}function yr(e,t,n,r){!r||n.loggerSessionId===r||(ye(e,{messageId:t.messageId,sessionId:r,sessionStoreName:Yn(t.channel,t.sessionStore)}),n.loggerSessionId=r)}function br(e,t){e.activeSessionId=t.sessionId??e.activeSessionId}function xr(e,t){return e.messageId??t}async function Sr(e,t,n){if(!await c(e.dataDir)){if(await $(t,e.format,n.activeSessionId,e.dataDir,`checking`),(await i(e.dataDir)).performedBootstrap){await $(t,e.format,n.activeSessionId,e.dataDir,`initializing`),await $(t,e.format,n.activeSessionId,e.dataDir,`initialized`);return}await $(t,e.format,n.activeSessionId,e.dataDir,`ready`)}}async function $(e,t,n,r,i){let a={type:`bootstrap`,phase:i,dataDir:r};t===`text`&&F(a),await Q(e,{sessionId:n,channel:e.channel,messageId:e.defaultMessageId,user:e.user,type:`progress`,event:a})}function Cr(e,t,n,r){return async i=>{if(br(n,i),yr(e.dataDir,{...r,channel:e.channel},n,i.sessionId),y(i)){hr(i);return}if(i.type===`stream_text_delta`){e.format===`text`&&F(i),await t.websocketSink?.sendTextDelta({sessionId:n.activeSessionId,channel:e.channel,messageId:xr(i,t.defaultMessageId),user:t.user,text:i.text});return}e.format===`text`&&F(i);let a=xr(i,t.defaultMessageId);if(i.type===`hitl_requested`){await Q(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:a,user:t.user,type:`hitl`,request:i.request}),await Q(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:a,user:t.user,type:`progress`,event:i});return}if(i.type===`start`){await Q(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:a,user:t.user,type:`start`,message:i.message});return}if(i.type===`session_reset`){await Q(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:a,user:t.user,type:`session_reset`,action:i.action,previousSessionId:i.previousSessionId,message:i.message});return}await Q(t,{sessionId:n.activeSessionId,channel:e.channel,messageId:a,user:t.user,type:`progress`,event:i})}}function wr(e){let t=Rn(e);return{confirm:(e,n)=>t.confirm(e),select:(e,n,r)=>t.select?t.select(e,n):Promise.resolve(void 0)}}function Tr(e,t,n,r,i,a){let o=jt(),s={dataDir:t.dataDir,projectDir:Wn(e.projectDir),systemAgentsDir:t.systemAgentsDir,systemAgentTeamsDir:t.systemAgentTeamsDir,agentPolicy:X(e.agent)||X(e.team)?{...X(e.agent)?{requestedAgentName:X(e.agent)}:{},...X(e.team)?{requestedTeamName:X(e.team)}:{}}:void 0,sessionStoreName:Yn(t.channel,e.sessionStore),sessionId:e.sessionId,messageId:e.messageId,channel:t.channel,llm:t.llm,skillsLoadPaths:t.skillsLoadPaths,workdirAllowlist:t.workdirAllowlist,artifactsUrlWhitelist:t.artifactsUrlWhitelist,autoSkills:t.autoSkills,timeoutMs:t.timeoutMs,abortSignal:n.signal,pendingGoal:a,encryptSessions:e.encryptSessions??!1,topicSegmentation:Hn(e),titleGeneration:Un(e),env:er(e.env),...o?{memory:{core:o}}:{},plugins:i?{config:i,dataDir:t.dataDir,workspaceDir:C.join(t.dataDir,`workspace`),bundledDir:process.env.AIMAX_PLUGINS_BUNDLED_DIR,llmAllowlist:i.llmAllowlist}:void 0,onProgress:r,onLog:xe,createPiExtensionDialogBridge:wr};return t.input.kind===`messages`?{...s,messages:t.input.messages}:{...s,message:t.input.message}}async function Er(e,t,n,r){if(t.activeSessionId=r.sessionId,t.finalResult=r,r.error){await Q(e,{sessionId:r.sessionId,channel:e.channel,messageId:n,user:e.user,type:`error`,message:r.error});return}await Q(e,{sessionId:r.sessionId,channel:e.channel,messageId:n,user:e.user,type:`done`,result:ln(r)})}async function Dr(e,t,n,r){await Q(e,{sessionId:t.finalResult?.sessionId??t.activeSessionId,channel:e.channel,messageId:n,user:e.user,type:`error`,message:`Fatal: ${r.message}`})}function Or(e,t){let n=ur(e,t);M.info([`run command started`,n.banner,n.contextBox].join(`
|
|
11
|
-
`),n.logContext),t.format===`text`&&(N(n.banner),N(``),N(n.contextBox),N(``))}function kr(e,t,n){return I(t,n),t.error?M.error(`run command failed: ${t.error}`):M.info(`run command succeeded`),e.end(),t.error?1:0}function Ar(e){let t=be();if(!t)return;let n=`[${oe()}] [ERROR] ${e}\n`;try{S.appendFileSync(C.join(t.logDir,`app.log`),n),S.appendFileSync(C.join(t.logDir,`errors.log`),n)}catch{}}async function jr(e,t){let n=`run command error: ${t.message}`;M.error(n),Ar(n),P(`Fatal: ${t.message}`),e.end(),await Se(),process.exit(1)}async function Mr(e){if(e.resumeInputJson&&e.resumeFromFile)throw Error(`--resume-input-json and --resume-from-file are mutually exclusive`);if(!e.resumeFromFile)return e.resumeInputJson;try{return await T.readFile(e.resumeFromFile,`utf-8`)}catch(e){throw Error(`Failed to read resume input file: ${e.message}`)}}async function Nr(n){let r=Y(n);try{await dt(r,n,async i=>{let a=vr(n.sessionId);yr(r,{...n,channel:qn(n.channel)},a,n.sessionId),n.encryptSessions&&M.info(`--encrypt-sessions run mount state after logger initialization`,{dataDir:r,mounted:i?.mounted??!1,plainDir:i?.plainDir,encryptedDir:i?.encryptedDir});let o=new we(`run command`),s=await Mr(n);if(n.resumeRequestId||s||n.resumeFromFile){if(!n.sessionId||!n.resumeRequestId||!s)throw Error(`--session-id, --resume-request-id, and exactly one of --resume-input-json or --resume-from-file must be provided together`);await Fn({dataDir:n.dataDir,projectDir:n.projectDir,systemAgentsDir:n.systemAgentsDir,systemAgentTeamsDir:n.systemAgentTeamsDir,team:n.team,sessionId:n.sessionId,sessionStore:n.sessionStore,requestId:n.resumeRequestId,inputJson:s,channel:n.channel,baseUrl:n.baseUrl,apiKey:n.apiKey,authToken:n.authToken,model:n.model,contextWindow:n.contextWindow,flashModel:n.flashModel,thinking:n.thinking,callbackUrl:n.callbackUrl,streamUrl:n.streamUrl,streamAuthToken:n.streamAuthToken,streamEvents:n.streamEvents,timeout:n.timeout,output:n.output,pluginsConfig:n.pluginsConfig,artifactsUrlWhitelist:n.artifactsUrlWhitelist,skillsLoadPaths:n.skillsLoadPaths,workdirAllowlist:n.workdirAllowlist,autoSkillsLoadEnabled:n.autoSkillsLoadEnabled,autoSkillsReviewMode:n.autoSkillsReviewMode,messageId:n.messageId,user:n.user,goal:n.goal,goalFile:n.goalFile,tokenBudget:n.tokenBudget,force:n.force,encryptSessions:n.encryptSessions,disableTopicSegmentation:n.disableTopicSegmentation,disableTitle:n.disableTitle});return}let c;try{c=await Wt({message:n.message,fromFile:n.fromFile,messages:n.messages})}catch(e){await jr(o,e);return}let l=await pr(n,c);if(l){await Fn({dataDir:n.dataDir,projectDir:n.projectDir,systemAgentsDir:n.systemAgentsDir,systemAgentTeamsDir:n.systemAgentTeamsDir,team:n.team,sessionId:n.sessionId,sessionStore:n.sessionStore,requestId:l.requestId,inputText:l.inputText,channel:n.channel,baseUrl:n.baseUrl,apiKey:n.apiKey,authToken:n.authToken,model:n.model,contextWindow:n.contextWindow,flashModel:n.flashModel,thinking:n.thinking,callbackUrl:n.callbackUrl,streamUrl:n.streamUrl,streamAuthToken:n.streamAuthToken,streamEvents:n.streamEvents,timeout:n.timeout,output:n.output,pluginsConfig:n.pluginsConfig,artifactsUrlWhitelist:n.artifactsUrlWhitelist,skillsLoadPaths:n.skillsLoadPaths,workdirAllowlist:n.workdirAllowlist,autoSkillsLoadEnabled:n.autoSkillsLoadEnabled,autoSkillsReviewMode:n.autoSkillsReviewMode,messageId:n.messageId,user:n.user,goal:n.goal,goalFile:n.goalFile,tokenBudget:n.tokenBudget,force:n.force,encryptSessions:n.encryptSessions,disableTopicSegmentation:n.disableTopicSegmentation,disableTitle:n.disableTitle});return}let u=n.channel??`WEB`,{controller:d,cleanup:f}=_r(()=>({activeSessionId:a.activeSessionId,finalSessionId:a.finalResult?.sessionId,messageId:n.messageId,channel:u,user:n.user})),m=null;try{let r=await dr(n,c);u=r.channel,Or(n,r);let i=mr(n);m=i.sink,M.info(`external sink configured`,{callbackUrl:n.callbackUrl,streamUrl:n.streamUrl,streamEvents:n.streamEvents});let s=gr(m,i.websocketSink,r.channel,n.messageId,n.user);await Sr(r,s,a);let l,f=null;if(n.goal||n.goalFile){let i;i=n.goalFile?await T.readFile(n.goalFile,`utf-8`):n.goal;let a=rn(i),o=Jn(n.sessionStore),s=n.tokenBudget===void 0?void 0:n.tokenBudget===`0`||n.tokenBudget===``?null:Number(n.tokenBudget);s!=null&&(Number.isNaN(s)||s<=0)&&(P(`error: --token-budget must be a positive integer, or 0 for unlimited`),process.exit(1));try{if(n.sessionId){let e=await p(r.dataDir,n.sessionId,{storeName:o}),i=await t({dataDir:r.dataDir,sessionId:n.sessionId,objective:a,tokenBudget:s,force:n.force,storeName:o});f=on({sessionId:n.sessionId,before:e,result:i})}else l={objective:a,tokenBudget:s??null}}catch(t){throw t instanceof e&&(P(t.message),P(`Existing: ${t.existingObjectivePreview}`),process.exit(2)),t}}let h=n.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,g=await G(r.dataDir,h),v=Cr(r,s,a,n);f&&await v(f);let y=await _(Tr(n,r,d,v,g,l));yr(r.dataDir,{...n,channel:r.channel},a,y.sessionId),await Er(s,a,n.messageId,y),process.exitCode=kr(o,y,r.format)}catch(e){let t=e;m&&await Dr(gr(m,null,u,n.messageId,n.user),a,n.messageId,t),await jr(o,t)}finally{await m?.close(),f()}})}finally{await Se()}}function Pr(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 Fr(e){e.command(`run`).description(`Run an agent task`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).option(`--project-dir <path>`,`Current project directory used as the default cwd context`).option(`--system-agents-dir <path>`,`System agent definition directory (overrides AIMAX_SYSTEM_AGENTS_DIR, default: /aimax/agents)`).option(`--system-agent-teams-dir <path>`,`System Agent team definition directory (overrides AIMAX_SYSTEM_AGENT_TEAMS_DIR, default: /aimax/agent-teams)`).option(`--agent <name>`,`Custom agent name to run as the root agent`).option(`--team <name>`,`Agent team name to run with its configured coordinator`).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(`--skillsLoadPaths <paths>`,`Comma-separated absolute skill load paths`).option(`--workdir-allowlist <paths>`,`Comma-separated additional roots allowed as cwd for exec-style tools`).option(`--auto-skills-load-enabled <boolean>`,`Enable learned auto-skill loading for the main agent (overrides AIMAX_AUTO_SKILLS_LOAD_ENABLED)`).option(`--auto-skills-review-mode <mode>`,`Auto-skill review mode: off, gate, dry_run, or write (overrides AIMAX_AUTO_SKILLS_REVIEW_MODE)`).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-format <format>`,`LLM API format: openai-completions or anthropic-messages (overrides AIMAX_API_FORMAT)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY / AIMAX_LLM_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(`--thinking <level>`,`Explicit thinking level: minimal, low, medium, high, or xhigh (overrides AIMAX_THINKING)`).option(`--temperature <n>`,`LLM sampling temperature, 0 to 2 (overrides AIMAX_TEMPERATURE)`).option(`--top-k <n>`,`LLM top-k sampling value, positive integer (overrides AIMAX_TOP_K)`).option(`--top-p <n>`,`LLM nucleus sampling top-p value, 0 to 1 (overrides AIMAX_TOP_P)`).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(`--artifacts-url-whitelist <urls>`,`Comma-separated URL artifact hostnames or URLs to collect; unset collects all URL artifacts`).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`).option(`--env <kvlist>`,`Session-scoped env vars injected into the run. Comma-separated KEY=VALUE pairs. Backslash-escape "," and "=" inside values. Available to plugins via api.runtime.session.env and merged into child process environments spawned by the exec/process tools.`).option(`--goal <text>`,`Set or replace the thread goal objective before running`).option(`--goal-file <path>`,`Read goal objective from a file`).option(`--token-budget <n>`,`Token budget for the goal (positive integer, or 0 for unlimited)`).option(`--force`,`Replace existing goal with a different objective`).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`).option(`--resume-from-file <path>`,`Load structured HITL resume payload from a file (alternative to --resume-input-json)`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).option(`--disable-topic-segmentation`,`Disable smart topic segmentation for this run`).option(`--disable-title`,`Skip LLM session title generation for new sessions (title falls back to a truncated first message; overrides AIMAX_DISABLE_TITLE)`).action(async e=>{await Nr(e)})}export{N as _,Kt as a,M as b,Nt as c,Pe as d,F as f,P as g,je as h,tn as i,wt as l,Me as m,Fr as n,Gt as o,Ne as p,Ln as r,G as s,Nr as t,dt as u,we as v,Se as x,ye as y};
|
|
9
|
+
`)}function sr(e){return e.kind===`text`?`inline message (${e.message.length} chars)`:e.source===`file`?`message file (${e.messages.length} messages)`:`inline messages (${e.messages.length} messages)`}function Z(e,t=`-`){return e==null||e===``?t:String(e)}function cr(e){return e?`set`:`unset`}function lr(e){return e?`true`:`false`}function ur(e,t){let n=Yn(t.channel,e.sessionStore)??`sessions`,r=t.timeoutMs===void 0?`default`:`${t.timeoutMs}`,i=e.callbackUrl?`enabled`:`disabled`,a=e.streamUrl?`enabled`:`disabled`,o=sr(t.input),s=t.input.kind===`text`?`inline`:e.fromFile??t.input.source,c=oe(),l=Hn(e)?.enabled===!1?`disabled`:`enabled`,u=Un(e)?.enabled===!1?`disabled`:`enabled`,d=e.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,f=[...Vn(e.streamEvents)].join(`,`),p=t.autoSkills?.load?.enabled,m=t.autoSkills?.review?.mode,h=e.tokenBudget===`0`?`unlimited`:Z(e.tokenBudget),g=t.artifactsUrlWhitelist?.join(`,`)??`-`,_=e.env?Object.keys(er(e.env)):[],v=_.length===0?`-`:`${_.length} key${_.length===1?``:`s`}`;return{banner:or(void 0,[`AIMax CLI`,`Stateless Agent Runner`]),contextBox:or(`Run Context`,[`time : ${c}`,`dataDir : ${t.dataDir}`,`projectDir : ${Wn(e.projectDir)??`-`}`,`systemAgents : ${t.systemAgentsDir??`/aimax/agents`}`,`agentTeams : ${t.systemAgentTeamsDir??`/aimax/agent-teams`}`,`agent : ${X(e.agent)??`-`}`,`team : ${X(e.team)??`-`}`,`channel : ${t.channel}`,`user : ${e.user??`-`}`,`message : ${e.message===void 0?`-`:`inline (${e.message.length} chars)`}`,`fromFile : ${Z(e.fromFile)}`,`input : ${o}`,`skillsPaths : ${t.skillsLoadPaths.length>0?t.skillsLoadPaths.join(`,`):`-`}`,`autoSkillLoad: ${p===void 0?`-`:String(p)}`,`autoSkillRev : ${m??`-`}`,`sessionId : ${e.sessionId??`new`}`,`parentSessionId: ${e.parentSessionId??`-`}`,`sessionStore : ${n}`,`messageId : ${e.messageId??`-`}`,`workspace : ${C.join(t.dataDir,`workspace`)}`,`baseUrl : ${t.llm.baseUrl}`,`apiKey : ${cr(t.llm.apiKey)}`,`authToken : ${cr(e.authToken)}`,`model : ${t.llm.model}`,`contextWindow: ${Z(t.llm.contextWindow)}`,`flashModel : ${Z(t.llm.flashModel)}`,`thinking : ${Z(t.llm.thinking)}`,`temperature : ${Z(t.llm.temperature)}`,`topK : ${Z(t.llm.topK)}`,`topP : ${Z(t.llm.topP)}`,`callbackUrl : ${Z(e.callbackUrl)}`,`streamUrl : ${Z(e.streamUrl)}`,`streamAuth : ${cr(e.streamAuthToken)}`,`streamEvents : ${f}`,`artifactUrls : ${g}`,`output : ${t.format}`,`callback : ${i}`,`websocket : ${a}`,`timeoutMs : ${r}`,`pluginsConfig: ${Z(d)}`,`env : ${v}`,`goal : ${e.goal===void 0?`-`:`inline (${e.goal.length} chars)`}`,`goalFile : ${Z(e.goalFile)}`,`tokenBudget : ${h}`,`force : ${lr(e.force)}`,`resumeReqId : ${Z(e.resumeRequestId)}`,`resumeInput : ${e.resumeInputJson===void 0?`-`:`inline (${e.resumeInputJson.length} chars)`}`,`resumeFile : ${Z(e.resumeFromFile)}`,`encryptSess : ${lr(e.encryptSessions)}`,`topicSegment : ${l}`,`titleGen : ${u}`]),logContext:{time:c,channel:t.channel,user:e.user,dataDir:t.dataDir,projectDir:Wn(e.projectDir),systemAgentsDir:t.systemAgentsDir,systemAgentTeamsDir:t.systemAgentTeamsDir,agent:X(e.agent),team:X(e.team),workspaceDir:C.join(t.dataDir,`workspace`),sessionId:e.sessionId??`new`,parentSessionId:e.parentSessionId,sessionStore:n,messageId:e.messageId,hasMessage:e.message!==void 0,fromFile:e.fromFile,skillsLoadPaths:t.skillsLoadPaths.join(`,`)||void 0,autoSkillsLoadEnabled:p,autoSkillsReviewMode:m,baseUrl:t.llm.baseUrl,hasApiKey:!!t.llm.apiKey,hasAuthToken:!!e.authToken,model:t.llm.model,contextWindow:t.llm.contextWindow,flashModel:t.llm.flashModel,thinking:t.llm.thinking,temperature:t.llm.temperature,topK:t.llm.topK,topP:t.llm.topP,callbackUrl:e.callbackUrl,streamUrl:e.streamUrl,hasStreamAuthToken:!!e.streamAuthToken,streamEvents:f,artifactsUrlWhitelist:t.artifactsUrlWhitelist?.join(`,`)||void 0,output:t.format,hasCallback:!!e.callbackUrl,hasStream:!!e.streamUrl,timeoutMs:t.timeoutMs,pluginsConfig:d,envKeys:_.length>0?_.join(`,`):void 0,hasGoal:e.goal!==void 0,goalFile:e.goalFile,tokenBudget:h===`-`?void 0:h,force:!!e.force,resumeRequestId:e.resumeRequestId,hasResumeInputJson:e.resumeInputJson!==void 0,resumeFromFile:e.resumeFromFile,encryptSessions:!!e.encryptSessions,topicSegmentation:l,titleGeneration:u,inputKind:t.input.kind,inputSource:s,inputSummary:o}}}async function dr(e,t){let n=Y(e),r=qn(e.channel),i=wt({apiFormat:e.apiFormat,baseUrl:e.baseUrl,apiKey:e.apiKey,authToken:e.authToken,model:e.model,contextWindow:e.contextWindow?Number(e.contextWindow):void 0,flashModel:e.flashModel,thinking:e.thinking,temperature:e.temperature===void 0?void 0:Number(e.temperature),topK:e.topK===void 0?void 0:Number(e.topK),topP:e.topP===void 0?void 0:Number(e.topP)});return{dataDir:n,systemAgentsDir:Gn(e),systemAgentTeamsDir:Kn(e),channel:r,format:e.output===`json`?`json`:`text`,timeoutMs:e.timeout?Number(e.timeout):void 0,llm:i,input:t,skillsLoadPaths:Xn(e.skillsLoadPaths),workdirAllowlist:Zn(e.workdirAllowlist),artifactsUrlWhitelist:un(e.artifactsUrlWhitelist),autoSkills:rr(e)}}function fr(e){if(e.kind===`text`)return e.message;if(e.messages.length!==1)return null;let[t]=e.messages;if(t.role!==`user`)return null;if(typeof t.content==`string`)return t.content;if(t.content.length===0)return null;let n=[];for(let e of t.content){if(e.type!==`text`)return null;n.push(e.text)}return n.join(`
|
|
10
|
+
`)}async function pr(e,t){if(!e.sessionId)return null;let n=fr(t);if(!n)return null;let r=await l(Y(e),e.sessionId,{storeName:Jn(e.sessionStore),encryptSessions:e.encryptSessions});return!r||r.status!==`pending`||!x(n,r.request)?null:{requestId:r.request.requestId,inputText:n}}function mr(e){let t=[],n=null;return e.callbackUrl&&t.push(new Kt(e.callbackUrl)),e.streamUrl&&(n=new tn(e.streamUrl,Vn(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new Gt(t),websocketSink:n}}async function Q(e,t){M.info(`dispatching external event`,Pr(t)),await e.sink.send(t)}function hr(e){let t={sessionId:e.sessionId,messageId:e.messageId,parentSessionId:e.parentSessionId,depth:e.depth,scope:e.scope,phase:e.phase,...e.details};if(e.level===`error`){M.error(e.message,t);return}if(e.level===`warn`){M.warn(e.message,t);return}M.info(e.message,t)}function gr(e,t,n,r,i,a){return{sink:e,websocketSink:t,channel:n,defaultMessageId:r,user:i,parentSessionId:a}}function _r(e){let t=new AbortController,n=n=>{M.warn(`run abort signal received`,{signal:n,uptimeMs:Math.round(process.uptime()*1e3),alreadyAborted:t.signal.aborted,...e?.()}),t.abort()},r=()=>n(`SIGTERM`),i=()=>n(`SIGINT`);return process.once(`SIGTERM`,r),process.once(`SIGINT`,i),{controller:t,cleanup:()=>{process.off(`SIGTERM`,r),process.off(`SIGINT`,i)}}}function vr(e){return{activeSessionId:e??`pending`,finalResult:null,loggerSessionId:void 0}}function yr(e,t,n,r){!r||n.loggerSessionId===r||(ye(e,{messageId:t.messageId,sessionId:r,sessionStoreName:Yn(t.channel,t.sessionStore)}),n.loggerSessionId=r)}function br(e,t){e.activeSessionId=t.sessionId??e.activeSessionId}function xr(e,t){return e.messageId??t}async function Sr(e,t,n){if(!await c(e.dataDir)){if(await $(t,e.format,n.activeSessionId,e.dataDir,`checking`),(await i(e.dataDir)).performedBootstrap){await $(t,e.format,n.activeSessionId,e.dataDir,`initializing`),await $(t,e.format,n.activeSessionId,e.dataDir,`initialized`);return}await $(t,e.format,n.activeSessionId,e.dataDir,`ready`)}}async function $(e,t,n,r,i){let a={type:`bootstrap`,phase:i,dataDir:r};t===`text`&&F(a),await Q(e,{sessionId:n,parentSessionId:e.parentSessionId,channel:e.channel,messageId:e.defaultMessageId,user:e.user,type:`progress`,event:a})}function Cr(e,t,n,r){return async i=>{if(br(n,i),yr(e.dataDir,{...r,channel:e.channel},n,i.sessionId),y(i)){hr(i);return}if(i.type===`stream_text_delta`){e.format===`text`&&F(i),await t.websocketSink?.sendTextDelta({sessionId:n.activeSessionId,parentSessionId:i.parentSessionId??t.parentSessionId,channel:e.channel,messageId:xr(i,t.defaultMessageId),user:t.user,text:i.text});return}e.format===`text`&&F(i);let a=xr(i,t.defaultMessageId);if(i.type===`hitl_requested`){await Q(t,{sessionId:n.activeSessionId,parentSessionId:i.parentSessionId??t.parentSessionId,channel:e.channel,messageId:a,user:t.user,type:`hitl`,request:i.request}),await Q(t,{sessionId:n.activeSessionId,parentSessionId:i.parentSessionId??t.parentSessionId,channel:e.channel,messageId:a,user:t.user,type:`progress`,event:i});return}if(i.type===`start`){await Q(t,{sessionId:n.activeSessionId,parentSessionId:i.parentSessionId??t.parentSessionId,channel:e.channel,messageId:a,user:t.user,type:`start`,message:i.message});return}if(i.type===`session_reset`){await Q(t,{sessionId:n.activeSessionId,parentSessionId:i.parentSessionId??t.parentSessionId,channel:e.channel,messageId:a,user:t.user,type:`session_reset`,action:i.action,previousSessionId:i.previousSessionId,message:i.message});return}await Q(t,{sessionId:n.activeSessionId,parentSessionId:i.parentSessionId??t.parentSessionId,channel:e.channel,messageId:a,user:t.user,type:`progress`,event:i})}}function wr(e){let t=Rn(e);return{confirm:(e,n)=>t.confirm(e),select:(e,n,r)=>t.select?t.select(e,n):Promise.resolve(void 0)}}function Tr(e,t,n,r,i,a){let o=jt(),s={dataDir:t.dataDir,projectDir:Wn(e.projectDir),systemAgentsDir:t.systemAgentsDir,systemAgentTeamsDir:t.systemAgentTeamsDir,agentPolicy:X(e.agent)||X(e.team)?{...X(e.agent)?{requestedAgentName:X(e.agent)}:{},...X(e.team)?{requestedTeamName:X(e.team)}:{}}:void 0,sessionStoreName:Yn(t.channel,e.sessionStore),sessionId:e.sessionId,parentSessionId:e.parentSessionId,messageId:e.messageId,channel:t.channel,llm:t.llm,skillsLoadPaths:t.skillsLoadPaths,workdirAllowlist:t.workdirAllowlist,artifactsUrlWhitelist:t.artifactsUrlWhitelist,autoSkills:t.autoSkills,timeoutMs:t.timeoutMs,abortSignal:n.signal,pendingGoal:a,encryptSessions:e.encryptSessions??!1,topicSegmentation:Hn(e),titleGeneration:Un(e),env:er(e.env),...o?{memory:{core:o}}:{},plugins:i?{config:i,dataDir:t.dataDir,workspaceDir:C.join(t.dataDir,`workspace`),bundledDir:process.env.AIMAX_PLUGINS_BUNDLED_DIR,llmAllowlist:i.llmAllowlist}:void 0,onProgress:r,onLog:xe,createPiExtensionDialogBridge:wr};return t.input.kind===`messages`?{...s,messages:t.input.messages}:{...s,message:t.input.message}}async function Er(e,t,n,r){if(t.activeSessionId=r.sessionId,t.finalResult=r,r.error){await Q(e,{sessionId:r.sessionId,parentSessionId:e.parentSessionId,channel:e.channel,messageId:n,user:e.user,type:`error`,message:r.error});return}await Q(e,{sessionId:r.sessionId,parentSessionId:e.parentSessionId,channel:e.channel,messageId:n,user:e.user,type:`done`,result:ln(r)})}async function Dr(e,t,n,r){await Q(e,{sessionId:t.finalResult?.sessionId??t.activeSessionId,parentSessionId:e.parentSessionId,channel:e.channel,messageId:n,user:e.user,type:`error`,message:`Fatal: ${r.message}`})}function Or(e,t){let n=ur(e,t);M.info([`run command started`,n.banner,n.contextBox].join(`
|
|
11
|
+
`),n.logContext),t.format===`text`&&(N(n.banner),N(``),N(n.contextBox),N(``))}function kr(e,t,n){return I(t,n),t.error?M.error(`run command failed: ${t.error}`):M.info(`run command succeeded`),e.end(),t.error?1:0}function Ar(e){let t=be();if(!t)return;let n=`[${oe()}] [ERROR] ${e}\n`;try{S.appendFileSync(C.join(t.logDir,`app.log`),n),S.appendFileSync(C.join(t.logDir,`errors.log`),n)}catch{}}async function jr(e,t){let n=`run command error: ${t.message}`;M.error(n),Ar(n),P(`Fatal: ${t.message}`),e.end(),await Se(),process.exit(1)}async function Mr(e){if(e.resumeInputJson&&e.resumeFromFile)throw Error(`--resume-input-json and --resume-from-file are mutually exclusive`);if(!e.resumeFromFile)return e.resumeInputJson;try{return await T.readFile(e.resumeFromFile,`utf-8`)}catch(e){throw Error(`Failed to read resume input file: ${e.message}`)}}async function Nr(n){let r=Y(n);try{await dt(r,n,async i=>{let a=vr(n.sessionId);yr(r,{...n,channel:qn(n.channel)},a,n.sessionId),n.encryptSessions&&M.info(`--encrypt-sessions run mount state after logger initialization`,{dataDir:r,mounted:i?.mounted??!1,plainDir:i?.plainDir,encryptedDir:i?.encryptedDir});let o=new we(`run command`),s=await Mr(n);if(n.resumeRequestId||s||n.resumeFromFile){if(!n.sessionId||!n.resumeRequestId||!s)throw Error(`--session-id, --resume-request-id, and exactly one of --resume-input-json or --resume-from-file must be provided together`);await Fn({dataDir:n.dataDir,projectDir:n.projectDir,systemAgentsDir:n.systemAgentsDir,systemAgentTeamsDir:n.systemAgentTeamsDir,team:n.team,sessionId:n.sessionId,sessionStore:n.sessionStore,requestId:n.resumeRequestId,inputJson:s,channel:n.channel,baseUrl:n.baseUrl,apiKey:n.apiKey,authToken:n.authToken,model:n.model,contextWindow:n.contextWindow,flashModel:n.flashModel,thinking:n.thinking,callbackUrl:n.callbackUrl,streamUrl:n.streamUrl,streamAuthToken:n.streamAuthToken,streamEvents:n.streamEvents,timeout:n.timeout,output:n.output,pluginsConfig:n.pluginsConfig,artifactsUrlWhitelist:n.artifactsUrlWhitelist,skillsLoadPaths:n.skillsLoadPaths,workdirAllowlist:n.workdirAllowlist,autoSkillsLoadEnabled:n.autoSkillsLoadEnabled,autoSkillsReviewMode:n.autoSkillsReviewMode,messageId:n.messageId,user:n.user,goal:n.goal,goalFile:n.goalFile,tokenBudget:n.tokenBudget,force:n.force,encryptSessions:n.encryptSessions,disableTopicSegmentation:n.disableTopicSegmentation,disableTitle:n.disableTitle});return}let c;try{c=await Wt({message:n.message,fromFile:n.fromFile,messages:n.messages})}catch(e){await jr(o,e);return}let l=await pr(n,c);if(l){await Fn({dataDir:n.dataDir,projectDir:n.projectDir,systemAgentsDir:n.systemAgentsDir,systemAgentTeamsDir:n.systemAgentTeamsDir,team:n.team,sessionId:n.sessionId,sessionStore:n.sessionStore,requestId:l.requestId,inputText:l.inputText,channel:n.channel,baseUrl:n.baseUrl,apiKey:n.apiKey,authToken:n.authToken,model:n.model,contextWindow:n.contextWindow,flashModel:n.flashModel,thinking:n.thinking,callbackUrl:n.callbackUrl,streamUrl:n.streamUrl,streamAuthToken:n.streamAuthToken,streamEvents:n.streamEvents,timeout:n.timeout,output:n.output,pluginsConfig:n.pluginsConfig,artifactsUrlWhitelist:n.artifactsUrlWhitelist,skillsLoadPaths:n.skillsLoadPaths,workdirAllowlist:n.workdirAllowlist,autoSkillsLoadEnabled:n.autoSkillsLoadEnabled,autoSkillsReviewMode:n.autoSkillsReviewMode,messageId:n.messageId,user:n.user,goal:n.goal,goalFile:n.goalFile,tokenBudget:n.tokenBudget,force:n.force,encryptSessions:n.encryptSessions,disableTopicSegmentation:n.disableTopicSegmentation,disableTitle:n.disableTitle});return}let u=n.channel??`WEB`,{controller:d,cleanup:f}=_r(()=>({activeSessionId:a.activeSessionId,finalSessionId:a.finalResult?.sessionId,messageId:n.messageId,channel:u,user:n.user})),m=null;try{let r=await dr(n,c);u=r.channel,Or(n,r);let i=mr(n);m=i.sink,M.info(`external sink configured`,{callbackUrl:n.callbackUrl,streamUrl:n.streamUrl,streamEvents:n.streamEvents});let s=gr(m,i.websocketSink,r.channel,n.messageId,n.user,n.parentSessionId);await Sr(r,s,a);let l,f=null;if(n.goal||n.goalFile){let i;i=n.goalFile?await T.readFile(n.goalFile,`utf-8`):n.goal;let a=rn(i),o=Jn(n.sessionStore),s=n.tokenBudget===void 0?void 0:n.tokenBudget===`0`||n.tokenBudget===``?null:Number(n.tokenBudget);s!=null&&(Number.isNaN(s)||s<=0)&&(P(`error: --token-budget must be a positive integer, or 0 for unlimited`),process.exit(1));try{if(n.sessionId){let e=await p(r.dataDir,n.sessionId,{storeName:o}),i=await t({dataDir:r.dataDir,sessionId:n.sessionId,objective:a,tokenBudget:s,force:n.force,storeName:o});f=on({sessionId:n.sessionId,before:e,result:i})}else l={objective:a,tokenBudget:s??null}}catch(t){throw t instanceof e&&(P(t.message),P(`Existing: ${t.existingObjectivePreview}`),process.exit(2)),t}}let h=n.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,g=await G(r.dataDir,h),v=Cr(r,s,a,n);f&&await v(f);let y=await _(Tr(n,r,d,v,g,l));yr(r.dataDir,{...n,channel:r.channel},a,y.sessionId),await Er(s,a,n.messageId,y),process.exitCode=kr(o,y,r.format)}catch(e){let t=e;m&&await Dr(gr(m,null,u,n.messageId,n.user,n.parentSessionId),a,n.messageId,t),await jr(o,t)}finally{await m?.close(),f()}})}finally{await Se()}}function Pr(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 Fr(e){e.command(`run`).description(`Run an agent task`).option(`-d, --data-dir <path>`,`Data directory path (overrides AIMAX_DATA_DIR)`).option(`--project-dir <path>`,`Current project directory used as the default cwd context`).option(`--system-agents-dir <path>`,`System agent definition directory (overrides AIMAX_SYSTEM_AGENTS_DIR, default: /aimax/agents)`).option(`--system-agent-teams-dir <path>`,`System Agent team definition directory (overrides AIMAX_SYSTEM_AGENT_TEAMS_DIR, default: /aimax/agent-teams)`).option(`--agent <name>`,`Custom agent name to run as the root agent`).option(`--team <name>`,`Agent team name to run with its configured coordinator`).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(`--skillsLoadPaths <paths>`,`Comma-separated absolute skill load paths`).option(`--workdir-allowlist <paths>`,`Comma-separated additional roots allowed as cwd for exec-style tools`).option(`--auto-skills-load-enabled <boolean>`,`Enable learned auto-skill loading for the main agent (overrides AIMAX_AUTO_SKILLS_LOAD_ENABLED)`).option(`--auto-skills-review-mode <mode>`,`Auto-skill review mode: off, gate, dry_run, or write (overrides AIMAX_AUTO_SKILLS_REVIEW_MODE)`).option(`-s, --session-id <id>`,`Resume an existing session by ID`).option(`--parent-session-id <id>`,`Associate this run with an originating parent session`).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-format <format>`,`LLM API format: openai-completions or anthropic-messages (overrides AIMAX_API_FORMAT)`).option(`--api-key <key>`,`LLM API key (overrides AIMAX_API_KEY / AIMAX_LLM_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(`--thinking <level>`,`Explicit thinking level: minimal, low, medium, high, or xhigh (overrides AIMAX_THINKING)`).option(`--temperature <n>`,`LLM sampling temperature, 0 to 2 (overrides AIMAX_TEMPERATURE)`).option(`--top-k <n>`,`LLM top-k sampling value, positive integer (overrides AIMAX_TOP_K)`).option(`--top-p <n>`,`LLM nucleus sampling top-p value, 0 to 1 (overrides AIMAX_TOP_P)`).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(`--artifacts-url-whitelist <urls>`,`Comma-separated URL artifact hostnames or URLs to collect; unset collects all URL artifacts`).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`).option(`--env <kvlist>`,`Session-scoped env vars injected into the run. Comma-separated KEY=VALUE pairs. Backslash-escape "," and "=" inside values. Available to plugins via api.runtime.session.env and merged into child process environments spawned by the exec/process tools.`).option(`--goal <text>`,`Set or replace the thread goal objective before running`).option(`--goal-file <path>`,`Read goal objective from a file`).option(`--token-budget <n>`,`Token budget for the goal (positive integer, or 0 for unlimited)`).option(`--force`,`Replace existing goal with a different objective`).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`).option(`--resume-from-file <path>`,`Load structured HITL resume payload from a file (alternative to --resume-input-json)`).option(`--encrypt-sessions`,`Enable gocryptfs-backed encryption for the .aimax data directory`).option(`--disable-topic-segmentation`,`Disable smart topic segmentation for this run`).option(`--disable-title`,`Skip LLM session title generation for new sessions (title falls back to a truncated first message; overrides AIMAX_DISABLE_TITLE)`).action(async e=>{await Nr(e)})}export{N as _,Kt as a,M as b,Nt as c,Pe as d,F as f,P as g,je as h,tn as i,wt as l,Me as m,Fr as n,Gt as o,Ne as p,Ln as r,G as s,Nr as t,dt as u,we as v,Se as x,ye as y};
|
package/dist/run.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as executeRun, t as RunOptions } from "./run-
|
|
1
|
+
import { n as executeRun, t as RunOptions } from "./run-xTw5VXAH.js";
|
|
2
2
|
export { type RunOptions, executeRun };
|
package/dist/run.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./pkg-path-D6anqptM.js";import{t as e}from"./run-
|
|
1
|
+
import"./pkg-path-D6anqptM.js";import{t as e}from"./run-DgS7vRrF.js";export{e as executeRun};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gencode/cli",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"aimax": "./dist/bin.js"
|
|
@@ -32,8 +32,8 @@
|
|
|
32
32
|
"commander": "^14.0.3",
|
|
33
33
|
"gensign-node": "latest",
|
|
34
34
|
"log4js": "^6.9.1",
|
|
35
|
-
"@gencode/agents": "0.21.
|
|
36
|
-
"@gencode/shared": "0.7.
|
|
35
|
+
"@gencode/agents": "0.21.2",
|
|
36
|
+
"@gencode/shared": "0.7.2"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@types/node": "^22.0.0",
|