@gencode/cli 0.17.5 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,21 @@
1
1
  # @gencode/cli
2
2
 
3
- ## 0.17.5
3
+ ## 0.18.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 0f9d5da: Agent Team 的协调提示词现使用英文,并要求协调 Agent 将成员职责可覆盖的实质性工作优先委派给团队成员;运行时会在 SubAgent 工具中提示精确成员选择和并行/串行协作方式。直接完成仅适用于简单答复、没有匹配成员或委派不可用的情况。
8
+ - c562e03: CRON 定时任务现在支持通过 `--parent-session-id <主会话ID>` 关联来源会话。调度器省略 `--session-id` 后,每次触发都会在 `.aimax/crons/<执行会话ID>/` 创建独立 transcript 和日志;callback 与 websocket 的 `sessionId` 表示本次执行,`parentSessionId` 表示来源主会话。生产调度配置需停止把主会话 ID 作为 `--session-id` 传入。
9
+ - Updated dependencies [0f9d5da]
10
+ - Updated dependencies [c562e03]
11
+ - @gencode/agents@0.21.1
12
+ - @gencode/shared@0.7.1
13
+
14
+ ## 0.18.0
15
+
16
+ ### Minor Changes
17
+
18
+ - 82f4ca0: 支持通过 `aimax run --team <name>`(或 server `run.team`)使用 Agent 团队:团队的可选 `mainAgent` 负责协调,未配置时使用默认 Agent;团队 `members` 会按名称和描述注入协调 Agent 的系统提示词,并限制 SubAgent 调用范围;可通过 `--system-agent-teams-dir` 或 `AIMAX_SYSTEM_AGENT_TEAMS_DIR` 指定系统团队配置目录。
4
19
 
5
20
  ### Patch Changes
6
21
 
@@ -14,11 +29,13 @@
14
29
 
15
30
  Fresh SQLite projection and filesystem fallback both return that locator for structured hits, so tools no longer depend on guessing a heading from the snippet. Reordering sections or changing only metadata keeps the locator stable when the path and heading are unchanged; renaming a heading or file yields a new locator. Daily and session notes continue to use line-based ids.
16
31
 
32
+ - Updated dependencies [82f4ca0]
33
+ - Updated dependencies [82f4ca0]
17
34
  - Updated dependencies [08214df]
18
35
  - Updated dependencies [12db0bf]
19
36
  - Updated dependencies [221dd2f]
20
37
  - Updated dependencies [766962b]
21
- - @gencode/agents@0.20.3
38
+ - @gencode/agents@0.21.0
22
39
 
23
40
  ## 0.17.4
24
41
 
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-DI_ZBJw6.js";import{t as r}from"./program-B5ysMPzB.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{};
2
+ import"./pkg-path-D6anqptM.js";import{b as e,x as t,y as n}from"./run-UulnNwOa.js";import{t as r}from"./program-DCH5Atim.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
@@ -1,3 +1,3 @@
1
1
  import { createProgram, getDataDir } from "./program.js";
2
- import { n as executeRun, t as RunOptions } from "./run-Cvhpn0TE.js";
2
+ import { n as executeRun, t as RunOptions } from "./run-xTw5VXAH.js";
3
3
  export { type RunOptions, createProgram, executeRun, getDataDir };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import"./pkg-path-D6anqptM.js";import{t as e}from"./run-DI_ZBJw6.js";import{n as t,t as n}from"./program-B5ysMPzB.js";export{n as createProgram,e as executeRun,t as getDataDir};
1
+ import"./pkg-path-D6anqptM.js";import{t as e}from"./run-UulnNwOa.js";import{n as t,t as n}from"./program-DCH5Atim.js";export{n as createProgram,e as executeRun,t as getDataDir};
@@ -1,4 +1,4 @@
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-DI_ZBJw6.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(`
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-UulnNwOa.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(`
package/dist/program.js CHANGED
@@ -1 +1 @@
1
- import"./run-DI_ZBJw6.js";import{n as e,t}from"./program-B5ysMPzB.js";export{t as createProgram,e as getDataDir};
1
+ import"./run-UulnNwOa.js";import{n as e,t}from"./program-DCH5Atim.js";export{t as createProgram,e as getDataDir};
@@ -0,0 +1,11 @@
1
+ import{GoalConflictError as e,applyCliGoalBeforeRun as t,buildResumeNarration as n,clearPendingUiTool as r,ensureBootstrapMountLayout as i,formatApprovalResolution as a,formatClarifyResolution as o,formatReviewResolution as s,hasBootstrapSentinel as c,loadPendingHitl as l,loadPendingUiTool as u,loadTranscript as d,normalizeSessionStoreName as f,readGoal as p,resolvePendingHitl as m,resolvePendingUiTool as h,rewriteTranscript as g,runAgent as _}from"@gencode/agents";import{formatTaskForDisplay as v,isAgentDiagnosticEvent as y,isHitlTool as b,parseMatchedTextToResolution as x,parseTextToResolution as ee}from"@gencode/shared";import S from"node:fs";import C from"node:path";import w from"log4js";import T from"node:fs/promises";import E from"node:os";import{execFile as te,execFileSync as ne}from"node:child_process";import re from"gensign-node";import{fileURLToPath as ie}from"node:url";function ae(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function oe(e=new Date){let t=ae(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let D=function(e){return e.INFO=`INFO`,e.ERROR=`ERROR`,e.WARN=`WARN`,e}({}),O=null,k=!1,A=[],se=Promise.resolve();function ce(){return oe()}function le(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${ue(t)}`);return t.length>0?` ${t.join(` `)}`:``}function ue(e){return JSON.stringify(de(e,new WeakSet))??`undefined`}function de(e,t){return typeof e==`bigint`?e.toString():e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:typeof e!=`object`&&typeof e!=`function`?String(e):t.has(e)?`[Circular]`:(t.add(e),Array.isArray(e)?e.map(e=>de(e,t)):Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,n])=>[e,de(n,t)])))}function fe(e){return C.join(e,`.aimax`)}function pe(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function me(e,t){let n=pe(t?.messageId),r=t?.sessionStoreName?.trim()||`sessions`;return t?.sessionId?{runLogId:n,logDir:C.join(fe(e),r,t.sessionId,`logs`,n)}:{runLogId:n,logDir:C.join(fe(e),`logs`,n)}}function he(e){return{appLogPath:C.join(e,`app.log`),errorLogPath:C.join(e,`errors.log`)}}function ge(e){let{appLogPath:t,errorLogPath:n}=he(e);w.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function _e(e,t,n){return`[${ce()}] [${e}] ${t}${le(n)}`}function ve(e,t,n){try{process.stderr.write(`${_e(e,t,n)}\n`)}catch{}}function j(e,t,n){if(!O){A.push({level:e,message:t,context:n}),A.length>200&&(A=A.slice(-200)),ve(e,t,n);return}k||=(ge(O.logDir),!0);let r=_e(e,t,n),i=w.getLogger();if(e===D.ERROR){i.error(r);return}if(e===D.WARN){i.warn(r);return}i.info(r)}function ye(e,t){let{logDir:n,runLogId:r}=me(e,t);if(k&&O?.dataDir===e&&O.runLogId===r&&O.logDir===n)return;S.mkdirSync(n,{recursive:!0}),ge(n),k=!0,O={dataDir:e,logDir:n,runLogId:r};let i=A;A=[];for(let e of i)j(e.level,e.message,e.context)}function be(){return O?{...O}:null}function xe(e){if(!e.logDir){e.level===`ERROR`?j(D.ERROR,e.message,e.context):e.level===`WARN`?j(D.WARN,e.message,e.context):j(D.INFO,e.message,e.context);return}let{appLogPath:t,errorLogPath:n}=he(e.logDir),r=`${e.formatted}\n`;se=se.then(async()=>{await S.promises.mkdir(e.logDir,{recursive:!0}),await S.promises.appendFile(t,r,`utf-8`),e.level===`ERROR`&&await S.promises.appendFile(n,r,`utf-8`)}).catch(t=>{ve(D.ERROR,`delegated agent log write failed`,{logDir:e.logDir,error:t instanceof Error?t.message:String(t)})})}async function Se(){await se;try{await Ce()}finally{k=!1}}function Ce(){return new Promise((e,t)=>{w.shutdown(n=>{if(n){t(n);return}e()})})}const M={info:(e,t)=>j(D.INFO,e,t),warn:(e,t)=>j(D.WARN,e,t),error:(e,t)=>j(D.ERROR,e,t)};var we=class{startTime;name;constructor(e){this.name=e,this.startTime=Date.now()}end(){let e=Date.now()-this.startTime;return M.info(`${this.name} completed in ${e}ms`),e}};function Te(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}const Ee=new Set;function De(e){return e instanceof Error?{name:e.name,message:e.message,code:e.code}:{message:String(e)}}function Oe(e,t){try{M.warn(`CLI ${e} write failed; suppressing further ${e} writes`,{stream:e,...De(t)})}catch{}}function ke(e,t){if(Ee.has(e))return;let n=e===`stdout`?process.stdout:process.stderr;try{n.write(t)}catch(t){Ee.add(e),Oe(e,t)}}function Ae(e){ke(`stdout`,e)}function N(e){ke(`stdout`,e+`
2
+ `)}function P(e){ke(`stderr`,e+`
3
+ `)}function F(e){switch(e.type){case`start`:N(`\n[start] ${e.message}`);break;case`text`:Ae(e.text);break;case`stream_text_delta`:Ae(e.text);break;case`bootstrap`:N(`\n[bootstrap:${e.phase}] ${e.dataDir}`);break;case`session_reset`:N(`\n[session:${e.action}] ${e.message}`);break;case`tool_start`:N(`\n[tool:${e.name}] ${JSON.stringify(e.input??{})}`);break;case`tool_end`:{let t=Te(e.output);N(`[tool:${e.name}] ${e.isError?`ERROR`:`OK`} ${t.slice(0,200)}`);break}case`compaction`:N(`\n[compaction${e.layer?`:${e.layer}`:``}] ${e.reason}${e.strategy?` (${e.strategy})`:``}`);break;case`skill_used`:N(`\n[skill] ${e.skillName} agent=${e.agent} task=${e.taskId}`);break;case`custom`:N(`\n[plugin:${e.pluginId}] ${e.name}${e.label?` ${e.label}`:``}${e.data?` ${JSON.stringify(e.data)}`:``}`);break;case`error`:P(`\n[error] ${e.message}`);break;case`diagnostic`:break;case`subagent_spawn`:N(`\n[subagent:spawn]${e.label?` "${e.label}"`:``} ${v(e.task)}`);break;case`subagent_complete`:N(`[subagent:${e.status}] ${v(e.task)}`);break;case`hitl_requested`:if(N(`\n[hitl:${e.request.kind}] ${e.request.title}`),N(` prompt: ${e.request.prompt}`),N(` requestId: ${e.request.requestId}`),e.request.input.mode===`choice`)for(let t of e.request.input.choices)N(` - [${t.id}] ${t.label}`);break;case`hitl_resumed`:N(`\n[hitl:resumed] requestId=${e.requestId} action=${e.resolution.action}`);break;case`hitl_expired`:N(`\n[hitl:expired] requestId=${e.requestId} reason=${e.reason}`);break;case`hitl_cancelled`:N(`\n[hitl:cancelled] requestId=${e.requestId}${e.reason?` reason=${e.reason}`:``}`);break;case`ui_tool_request`:N(`\n[ui-tool:${e.request.toolName}] ${e.request.outputSchema.title}`),N(` requestId: ${e.request.requestId}`),N(` toolCallId: ${e.request.toolCallId}`);break;case`ui_tool_result`:N(`\n[ui-tool:resumed] requestId=${e.requestId} tool=${e.toolName}`);break}}function I(e,t){if(t===`json`){e&&N(JSON.stringify(e,null,2));return}N(`
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
+ `)){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
+ `)){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,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}:{},...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]
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`}`,`parentSession: ${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};
@@ -69,7 +69,9 @@ type RunOptions = {
69
69
  dataDir?: string;
70
70
  projectDir?: string;
71
71
  systemAgentsDir?: string;
72
+ systemAgentTeamsDir?: string;
72
73
  agent?: string;
74
+ team?: string;
73
75
  user?: string;
74
76
  message?: string;
75
77
  messages?: StructuredMessages;
@@ -79,6 +81,7 @@ type RunOptions = {
79
81
  autoSkillsLoadEnabled?: string;
80
82
  autoSkillsReviewMode?: string;
81
83
  sessionId?: string;
84
+ parentSessionId?: string;
82
85
  sessionStore?: string;
83
86
  messageId?: string;
84
87
  channel?: Channel;
package/dist/run.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { n as executeRun, t as RunOptions } from "./run-Cvhpn0TE.js";
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-DI_ZBJw6.js";export{e as executeRun};
1
+ import"./pkg-path-D6anqptM.js";import{t as e}from"./run-UulnNwOa.js";export{e as executeRun};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/cli",
3
- "version": "0.17.5",
3
+ "version": "0.18.1",
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.20.3",
36
- "@gencode/shared": "0.7.0"
35
+ "@gencode/agents": "0.21.1",
36
+ "@gencode/shared": "0.7.1"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@types/node": "^22.0.0",
@@ -1,11 +0,0 @@
1
- import{GoalConflictError as e,applyCliGoalBeforeRun as t,buildResumeNarration as n,clearPendingUiTool as r,ensureBootstrapMountLayout as i,formatApprovalResolution as a,formatClarifyResolution as o,formatReviewResolution as s,hasBootstrapSentinel as c,loadPendingHitl as l,loadPendingUiTool as u,loadTranscript as d,normalizeSessionStoreName as f,readGoal as p,resolvePendingHitl as m,resolvePendingUiTool as h,rewriteTranscript as g,runAgent as _}from"@gencode/agents";import{formatTaskForDisplay as v,isAgentDiagnosticEvent as y,isHitlTool as b,parseMatchedTextToResolution as x,parseTextToResolution as ee}from"@gencode/shared";import S from"node:fs";import C from"node:path";import w from"log4js";import T from"node:fs/promises";import E from"node:os";import{execFile as te,execFileSync as ne}from"node:child_process";import re from"gensign-node";import{fileURLToPath as ie}from"node:url";function ae(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function oe(e=new Date){let t=ae(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let D=function(e){return e.INFO=`INFO`,e.ERROR=`ERROR`,e.WARN=`WARN`,e}({}),O=null,k=!1,A=[],se=Promise.resolve();function ce(){return oe()}function le(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${ue(t)}`);return t.length>0?` ${t.join(` `)}`:``}function ue(e){return JSON.stringify(de(e,new WeakSet))??`undefined`}function de(e,t){return typeof e==`bigint`?e.toString():e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:typeof e!=`object`&&typeof e!=`function`?String(e):t.has(e)?`[Circular]`:(t.add(e),Array.isArray(e)?e.map(e=>de(e,t)):Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,n])=>[e,de(n,t)])))}function fe(e){return C.join(e,`.aimax`)}function pe(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function me(e,t){let n=pe(t?.messageId),r=t?.sessionStoreName?.trim()||`sessions`;return t?.sessionId?{runLogId:n,logDir:C.join(fe(e),r,t.sessionId,`logs`,n)}:{runLogId:n,logDir:C.join(fe(e),`logs`,n)}}function he(e){return{appLogPath:C.join(e,`app.log`),errorLogPath:C.join(e,`errors.log`)}}function ge(e){let{appLogPath:t,errorLogPath:n}=he(e);w.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function _e(e,t,n){return`[${ce()}] [${e}] ${t}${le(n)}`}function ve(e,t,n){try{process.stderr.write(`${_e(e,t,n)}\n`)}catch{}}function j(e,t,n){if(!O){A.push({level:e,message:t,context:n}),A.length>200&&(A=A.slice(-200)),ve(e,t,n);return}k||=(ge(O.logDir),!0);let r=_e(e,t,n),i=w.getLogger();if(e===D.ERROR){i.error(r);return}if(e===D.WARN){i.warn(r);return}i.info(r)}function ye(e,t){let{logDir:n,runLogId:r}=me(e,t);if(k&&O?.dataDir===e&&O.runLogId===r&&O.logDir===n)return;S.mkdirSync(n,{recursive:!0}),ge(n),k=!0,O={dataDir:e,logDir:n,runLogId:r};let i=A;A=[];for(let e of i)j(e.level,e.message,e.context)}function be(){return O?{...O}:null}function xe(e){if(!e.logDir){e.level===`ERROR`?j(D.ERROR,e.message,e.context):e.level===`WARN`?j(D.WARN,e.message,e.context):j(D.INFO,e.message,e.context);return}let{appLogPath:t,errorLogPath:n}=he(e.logDir),r=`${e.formatted}\n`;se=se.then(async()=>{await S.promises.mkdir(e.logDir,{recursive:!0}),await S.promises.appendFile(t,r,`utf-8`),e.level===`ERROR`&&await S.promises.appendFile(n,r,`utf-8`)}).catch(t=>{ve(D.ERROR,`delegated agent log write failed`,{logDir:e.logDir,error:t instanceof Error?t.message:String(t)})})}async function Se(){await se;try{await Ce()}finally{k=!1}}function Ce(){return new Promise((e,t)=>{w.shutdown(n=>{if(n){t(n);return}e()})})}const M={info:(e,t)=>j(D.INFO,e,t),warn:(e,t)=>j(D.WARN,e,t),error:(e,t)=>j(D.ERROR,e,t)};var we=class{startTime;name;constructor(e){this.name=e,this.startTime=Date.now()}end(){let e=Date.now()-this.startTime;return M.info(`${this.name} completed in ${e}ms`),e}};function Te(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}const Ee=new Set;function De(e){return e instanceof Error?{name:e.name,message:e.message,code:e.code}:{message:String(e)}}function Oe(e,t){try{M.warn(`CLI ${e} write failed; suppressing further ${e} writes`,{stream:e,...De(t)})}catch{}}function ke(e,t){if(Ee.has(e))return;let n=e===`stdout`?process.stdout:process.stderr;try{n.write(t)}catch(t){Ee.add(e),Oe(e,t)}}function Ae(e){ke(`stdout`,e)}function N(e){ke(`stdout`,e+`
2
- `)}function P(e){ke(`stderr`,e+`
3
- `)}function F(e){switch(e.type){case`start`:N(`\n[start] ${e.message}`);break;case`text`:Ae(e.text);break;case`stream_text_delta`:Ae(e.text);break;case`bootstrap`:N(`\n[bootstrap:${e.phase}] ${e.dataDir}`);break;case`session_reset`:N(`\n[session:${e.action}] ${e.message}`);break;case`tool_start`:N(`\n[tool:${e.name}] ${JSON.stringify(e.input??{})}`);break;case`tool_end`:{let t=Te(e.output);N(`[tool:${e.name}] ${e.isError?`ERROR`:`OK`} ${t.slice(0,200)}`);break}case`compaction`:N(`\n[compaction${e.layer?`:${e.layer}`:``}] ${e.reason}${e.strategy?` (${e.strategy})`:``}`);break;case`skill_used`:N(`\n[skill] ${e.skillName} agent=${e.agent} task=${e.taskId}`);break;case`custom`:N(`\n[plugin:${e.pluginId}] ${e.name}${e.label?` ${e.label}`:``}${e.data?` ${JSON.stringify(e.data)}`:``}`);break;case`error`:P(`\n[error] ${e.message}`);break;case`diagnostic`:break;case`subagent_spawn`:N(`\n[subagent:spawn]${e.label?` "${e.label}"`:``} ${v(e.task)}`);break;case`subagent_complete`:N(`[subagent:${e.status}] ${v(e.task)}`);break;case`hitl_requested`:if(N(`\n[hitl:${e.request.kind}] ${e.request.title}`),N(` prompt: ${e.request.prompt}`),N(` requestId: ${e.request.requestId}`),e.request.input.mode===`choice`)for(let t of e.request.input.choices)N(` - [${t.id}] ${t.label}`);break;case`hitl_resumed`:N(`\n[hitl:resumed] requestId=${e.requestId} action=${e.resolution.action}`);break;case`hitl_expired`:N(`\n[hitl:expired] requestId=${e.requestId} reason=${e.reason}`);break;case`hitl_cancelled`:N(`\n[hitl:cancelled] requestId=${e.requestId}${e.reason?` reason=${e.reason}`:``}`);break;case`ui_tool_request`:N(`\n[ui-tool:${e.request.toolName}] ${e.request.outputSchema.title}`),N(` requestId: ${e.request.requestId}`),N(` toolCallId: ${e.request.toolCallId}`);break;case`ui_tool_result`:N(`\n[ui-tool:resumed] requestId=${e.requestId} tool=${e.toolName}`);break}}function I(e,t){if(t===`json`){e&&N(JSON.stringify(e,null,2));return}N(`
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 L=`.aimax`,Fe=`${L}.pre-gocryptfs.`,Ie=[`app.log`,`errors.log`],Le=[`logs`],Re=[`fusermount3`,`fusermount`,`umount`],ze=[{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 Be(e){return C.join(e,`.aimax.enc`)}function Ve(e){return C.join(e,L)}function He(e){return C.join(e,`${Fe}${process.pid}.${Date.now()}`)}function Ue(e){return C.join(e,`${L}.plaintext-restore.${process.pid}.${Date.now()}`)}function We(e){return e.replace(/\\([0-7]{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}async function R(e){try{let t=await qe.read(),n=C.resolve(e);for(let e of t.split(`
5
- `)){if(!e.trim())continue;let t=e.split(` `);if(t.length>=5&&C.resolve(We(t[4]??``))===n)return!0}return!1}catch{return!1}}function Ge(e){try{let t=S.readFileSync(`/proc/self/mountinfo`,`utf-8`),n=C.resolve(e);for(let e of t.split(`
6
- `)){if(!e.trim())continue;let t=e.split(` `);if(t.length>=5&&C.resolve(We(t[4]??``))===n)return!0}return!1}catch{return!1}}async function Ke(){return await T.readFile(`/proc/self/mountinfo`,`utf-8`)}const qe={read:Ke};async function z(e){try{return await T.stat(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function B(e){await T.mkdir(e,{recursive:!0})}async function Je(e){if(await B(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 Ye(e){return await z(e)?(await T.readdir(e)).length===0:!0}async function V(e){if(await z(e))return(await T.readdir(e)).length}async function Xe(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()&&Le.includes(e.name))&&!(e.isFile()&&Ie.some(t=>e.name.startsWith(t)))){n=!0;break}return{exists:!0,entryCount:t.length,isEmpty:t.length===0,containsUserData:n}}async function Ze(e){let t=await T.readdir(e,{withFileTypes:!0});for(let n of t){if(n.isDirectory()&&Le.includes(n.name)){await T.rm(C.join(e,n.name),{recursive:!0,force:!0}).catch(()=>{});continue}n.isFile()&&Ie.some(e=>n.name.startsWith(e))&&await T.rm(C.join(e,n.name),{force:!0}).catch(()=>{})}}async function Qe(e){if(!await z(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 $e(e){return(await T.readdir(e,{withFileTypes:!0})).filter(e=>e.isDirectory()&&e.name.startsWith(Fe)).map(t=>C.join(e,t.name)).sort()}async function H(e,t){if(!await z(t))return null;let n=He(e);return M.info(`--encrypt-sessions moving plaintext .aimax aside before migration`,{plainDir:t,backupDir:n}),await T.rename(t,n),n}async function U(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 et(e,t){if(e.length===0)return[];await B(t);let n=[];for(let r of e)await z(r)&&(await U(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 tt(e){let t=Date.now(),n=Be(e),r=Ve(e),i=await z(n);if(!i)return;let a=i&&await z(C.join(n,`gocryptfs.conf`)),o=await Xe(r),s=o.exists?await R(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 B(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 Ze(r));try{await it()}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 B(r);return}let c=Ue(e),l=!1;try{await Je(r),await at(n,r),l=!0,await T.rm(c,{recursive:!0,force:!0}),await B(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 V(c)}),await W(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 W(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 B(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 nt(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 rt(e){let t=e.includes(`-init`)?`init`:`mount`;M.info(`--encrypt-sessions starting gocryptfs ${t}`);try{await dt(`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 it(){M.info(`--encrypt-sessions checking encryption dependencies`),await pt(`gocryptfs`,`required for --encrypt-sessions`),M.info(`--encrypt-sessions dependency available`,{command:`gocryptfs`});for(let e of Re)if(await ft(e)){M.info(`--encrypt-sessions unmount dependency available`,{command:e});return}throw Error(`--encrypt-sessions requires one of ${Re.join(`, `)} to be installed for secure unmount cleanup.`)}async function at(e,t){M.info(`--encrypt-sessions mounting encrypted .aimax`,{encryptedDir:e,plainDir:t}),await nt(async n=>{await rt([`-q`,`-passfile`,n,e,t])})}async function ot(e){M.info(`--encrypt-sessions initializing encrypted .aimax directory`,{encryptedDir:e}),await nt(async t=>{await rt([`-q`,`-init`,`-passfile`,t,e])})}async function W(e){let t=[];M.info(`--encrypt-sessions unmounting encrypted .aimax`,{plainDir:e});for(let n of ze)try{if(M.info(`--encrypt-sessions attempting encrypted .aimax unmount`,{command:n.label,plainDir:e}),await dt(n.command,[...n.args,e]),!await R(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=mt(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 st(e){for(let t of ze)try{if(ne(t.command,[...t.args,e],{stdio:`ignore`}),!Ge(e))return}catch{}}function ct(e){let t=!1,n=()=>{t||(t=!0,st(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 lt(e){let t=Be(e),n=Ve(e),r=await z(n),i=await z(t),a=i&&await z(C.join(t,`gocryptfs.conf`)),o=r?await R(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 V(n),encryptedDirEntryCount:await V(t)});let s=()=>({mounted:!1,plainDir:n,encryptedDir:t,async cleanup(){}});try{await it()}catch(e){return M.warn(`--encrypt-sessions is unavailable; continuing with plaintext .aimax`,{error:e instanceof Error?e.message:String(e)}),await B(n),s()}if(await R(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 $e(e),l.length>0&&M.warn(`--encrypt-sessions found interrupted pre-gocryptfs migration backups`,{count:l.length}),!await z(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 H(e,n):c=await H(e,n),await B(t),await ot(t),await B(n),await at(t,n),f=!0,d=ct(n),M.info(`--encrypt-sessions mounted encrypted .aimax`,{plainDir:n,encryptedDir:t}),l.length>0){for(let e of l)await U(e,n,!0);u&&=(await U(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 U(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 V(n)}),await Qe(t),l.length>0?u=await H(e,n):await Ye(n)||(c=await H(e,n)),await Je(n),await at(t,n),f=!0,d=ct(n),M.info(`--encrypt-sessions mounted encrypted .aimax`,{plainDir:n,encryptedDir:t}),l.length>0){for(let e of l)await U(e,n,!0);u&&=(await U(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 U(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 R(n),plainDirEntryCount:await V(n),encryptedDirEntryCount:await V(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 W(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 W(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 z(c)&&await Ye(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 z(u)&&await Ye(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 et(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 B(n),s()}}async function ut(e,t,n){if(!t.encryptSessions)return await tt(e),n();M.info(`--encrypt-sessions wrapper starting encrypted .aimax preparation`,{dataDir:e});let r=await lt(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 dt(e,t){await new Promise((n,r)=>{te(e,t,{encoding:`utf-8`},e=>{if(e){r(e);return}n()})})}async function ft(e){try{return await dt(`sh`,[`-c`,`command -v "${e}" >/dev/null 2>&1`]),!0}catch{return!1}}async function pt(e,t){if(!await ft(e))throw Error(`--encrypt-sessions requires ${e}: ${t}.`)}function mt(e,t){return`${e} failed: ${t instanceof Error?t.message:String(t)}`}function ht(e){return re.sm4_encrypt_ecb(e)}function gt(e){return ht(e)}const _t=[`minimal`,`low`,`medium`,`high`,`xhigh`];function vt(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(_t.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of ${_t.join(`, `)}.`)}}function G(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 yt(e,t){let n=G(e,t);if(n!==void 0){if(!Number.isInteger(n))throw Error(`Invalid ${t}: ${e}. Must be an integer.`);return n}}function bt(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 xt(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 St(e,t){if(e!==void 0){if(e<=0)throw Error(`Invalid ${t}: ${e}. Must be a positive integer.`);return e}}function Ct(e={}){let t=wt(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?gt(e.authToken):r?gt(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?vt(process.env.AIMAX_THINKING,`AIMAX_THINKING`):vt(e.thinking,`--thinking`),temperature:e.temperature===void 0?bt(G(process.env.AIMAX_TEMPERATURE,`AIMAX_TEMPERATURE`),`AIMAX_TEMPERATURE`):bt(e.temperature,`--temperature`),topK:e.topK===void 0?St(yt(process.env.AIMAX_TOP_K,`AIMAX_TOP_K`),`AIMAX_TOP_K`):St(e.topK,`--top-k`),topP:e.topP===void 0?xt(G(process.env.AIMAX_TOP_P,`AIMAX_TOP_P`),`AIMAX_TOP_P`):xt(e.topP,`--top-p`)}}function wt(e){if(!e||e===`openai-completions`||e===`anthropic-messages`)return e;throw Error(`Unsupported LLM API format: ${e}`)}const Tt=[`off`,`fallback`];function Et(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 Dt(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(Tt.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of ${Tt.join(`, `)}.`)}}function Ot(){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 kt(e){return Object.values(e).some(e=>e!==void 0)}function At(e={}){if(!(!kt(e)&&!Ot()))return{knowledgeController:{enabled:e.kcEnabled??Et(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?Dt(process.env.AIMAX_MEMORY_KC_SEARCH_MODE,`AIMAX_MEMORY_KC_SEARCH_MODE`)??`off`:Dt(e.kcSearchMode,`kcSearchMode`),topK:e.kcTopK??G(process.env.AIMAX_MEMORY_KC_TOP_K,`AIMAX_MEMORY_KC_TOP_K`),scoreThreshold:e.kcScoreThreshold??G(process.env.AIMAX_MEMORY_KC_SCORE_THRESHOLD,`AIMAX_MEMORY_KC_SCORE_THRESHOLD`),timeoutMs:e.kcTimeoutMs??G(process.env.AIMAX_MEMORY_KC_TIMEOUT_MS,`AIMAX_MEMORY_KC_TIMEOUT_MS`),syncEnabled:e.kcSyncEnabled??Et(process.env.AIMAX_MEMORY_KC_SYNC_ENABLED,`AIMAX_MEMORY_KC_SYNC_ENABLED`)}}}function jt(e,t){return t?C.resolve(t):C.join(e,`.aimax`,`plugins.json`)}async function K(e,t){let n=jt(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 Mt(e,t,n){let r=jt(e,n);await T.mkdir(C.dirname(r),{recursive:!0}),await T.writeFile(r,JSON.stringify(t,null,2),`utf-8`)}function q(e){return typeof e==`object`&&!!e}function Nt(e){return q(e)&&e.type===`text`&&typeof e.text==`string`&&(e.textSignature===void 0||typeof e.textSignature==`string`)}function Pt(e){return q(e)&&e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`}function Ft(e){return q(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 It(e){return q(e)&&e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`&&q(e.arguments)&&(e.thoughtSignature===void 0||typeof e.thoughtSignature==`string`)}function Lt(e){return typeof e==`string`||Array.isArray(e)&&e.every(e=>Nt(e)||Pt(e))}function Rt(e){return Array.isArray(e)&&e.every(e=>Nt(e)||Ft(e)||It(e))}function zt(e){return q(e)&&typeof e.input==`number`&&typeof e.output==`number`&&typeof e.cacheRead==`number`&&typeof e.cacheWrite==`number`&&typeof e.totalTokens==`number`&&q(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 Bt(e){return!q(e)||typeof e.role!=`string`?!1:e.role===`user`?Lt(e.content):e.role===`assistant`?Rt(e.content)&&typeof e.api==`string`&&typeof e.provider==`string`&&typeof e.model==`string`&&zt(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=>Nt(e)||Pt(e))&&typeof e.isError==`boolean`:!1}async function Vt(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 Ht(n,`Message file`)}function Ht(e,t=`Messages input`){let n=Array.isArray(e)?e:[e];if(n.length===0||!n.every(e=>Bt(e)))throw Error(`${t} must contain one Message object or an array of Message objects`);return n}async function Ut(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 Vt(e.fromFile),source:`file`}:e.messages===void 0?{kind:`text`,message:e.message}:{kind:`messages`,messages:Ht(e.messages),source:`inline`}}var Wt=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()}))}},Gt=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=Kt(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 Kt(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 qt(e,t){if(t.kind===`none`)return e;let n=new URL(e);return n.searchParams.set(`authToken`,t.token),n.toString()}const Jt=5e3,Yt=5e3,Xt=6e4;function J(){let e=globalThis.WebSocket;if(!e)throw Error(`WebSocket is not available in this runtime`);return e}function Zt(e){return e?{kind:`query_token`,token:e}:{kind:`none`}}function Qt(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 $t(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 en=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=J();if(e.readyState!==t.CLOSED)try{await tn(new Promise(t=>{Qt(e,`close`,()=>t()),e.close()}),Yt,`WebSocket close timed out after ${Yt}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=J();if(this.socket&&this.socket.readyState===e.OPEN)return;if(this.connectPromise){await this.connectPromise;return}let t=new e(qt(this.url,Zt(this.authToken)));this.connectPromise=new Promise((e,n)=>{Qt(t,`open`,()=>{this.socket=t,this.markSent(),$t(t,`close`,()=>{this.socket===t&&(this.socket=null),this.stopHeartbeat()}),e()}),Qt(t,`error`,e=>{n(e)})});try{await this.connectPromise}finally{this.connectPromise=null}}async sendPayload(e){await tn(this.ensureConnected(),Jt,`WebSocket connection timed out after ${Jt}ms`);let t=J();!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()},Xt)}stopHeartbeat(){this.heartbeatTimer&&=(clearTimeout(this.heartbeatTimer),null)}async sendHeartbeatIfIdle(){if(!this.enabled)return;let e=J();if(!(!this.socket||this.socket.readyState!==e.OPEN)&&!(Date.now()-this.lastSentAt<Xt)&&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 tn(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 nn(e){let t=e.trim();if(!t)throw Error(`Goal objective cannot be empty`);return t}function rn(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 an(e){let t=rn(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 on(e){let t=e?.packageRoot??sn(),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 sn(){let e=C.dirname(ie(import.meta.url));return C.basename(e)===`src`||C.basename(e)===`dist`?C.resolve(e,`..`):e}function cn(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 ln(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=un(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 un(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 dn=[`start`,`text`,`done`,`error`,`hitl`],fn=[`off`,`gate`,`dry_run`,`write`];function pn(e){if(!e?.trim())return new Set(dn);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(dn)}function mn(e){if(e.disableTopicSegmentation===!0||process.env.AIMAX_DISABLE_TOPIC_SEGMENTATION===`true`)return{enabled:!1};let t=on();return t?{embeddingModelDir:t}:void 0}function hn(e){return e.disableTitle===!0||process.env.AIMAX_DISABLE_TITLE===`true`?{enabled:!1}:void 0}function gn(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 _n(e){return e?.trim()||void 0}function vn(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 yn(e){return e?f(e):void 0}function bn(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 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)n.has(e)||(n.add(e),r.push(e));return r}function Sn(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 Cn(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(fn.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of off,gate,dry_run,write.`)}}function wn(e){let t=e.autoSkillsLoadEnabled===void 0?Sn(process.env.AIMAX_AUTO_SKILLS_LOAD_ENABLED,`AIMAX_AUTO_SKILLS_LOAD_ENABLED`):Sn(e.autoSkillsLoadEnabled,`--auto-skills-load-enabled`),n=e.autoSkillsReviewMode===void 0?Cn(process.env.AIMAX_AUTO_SKILLS_REVIEW_MODE,`AIMAX_AUTO_SKILLS_REVIEW_MODE`):Cn(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 Tn(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 En(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 Dn(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 On(e){let t=gn(e),n=e.channel??`WEB`,r=Ct({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:vn(e),channel:n,format:e.output===`json`?`json`:`text`,timeoutMs:e.timeout?Number(e.timeout):void 0,llm:r,skillsLoadPaths:bn(e.skillsLoadPaths),workdirAllowlist:xn(e.workdirAllowlist),artifactsUrlWhitelist:ln(e.artifactsUrlWhitelist),autoSkills:wn(e)}}function kn(e){let t=[],n=null;return e.callbackUrl&&t.push(new Gt(e.callbackUrl)),e.streamUrl&&(n=new en(e.streamUrl,pn(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new Wt(t),websocketSink:n}}async function An(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 jn(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 Mn(){let e=At();return e?{core:e}:void 0}async function Nn(n){let i=gn(n);await ut(i,n,async()=>{ye(i,{messageId:n.messageId,sessionId:n.sessionId,sessionStoreName:yn(n.sessionStore)});let a=new we(`resume command`),o=null;try{let i=await On(n),s=yn(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=nn(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=an({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=Tn(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=Pn(e,r.request.kind);await An({dataDir:i.dataDir,sessionId:n.sessionId,sessionStoreName:s,toolCallId:r.toolContext?.toolCallId,toolName:r.toolContext?.toolName,resolution:e,encryptSessions:n.encryptSessions});let u=kn(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 K(i.dataDir,h),v;try{v=await _({dataDir:i.dataDir,projectDir:_n(n.projectDir),systemAgentsDir:i.systemAgentsDir,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:mn(n),titleGeneration:hn(n),memory:Mn(),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:cn(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=En(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 jn({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=kn(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 Dn({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 K(i.dataDir,S),E=await _({dataDir:i.dataDir,projectDir:_n(n.projectDir),systemAgentsDir:i.systemAgentsDir,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
- 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:mn(n),titleGeneration:hn(n),memory:Mn(),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:cn(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 Pn(e,t){return n(e,t)}function Fn(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)`).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 Nn(e)})}function In(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 Ln=[`start`,`text`,`done`,`error`],Rn=[`off`,`gate`,`dry_run`,`write`];function zn(e){if(!e?.trim())return new Set(Ln);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(Ln)}function Bn(e){if(e.disableTopicSegmentation===!0||process.env.AIMAX_DISABLE_TOPIC_SEGMENTATION===`true`)return{enabled:!1};let t=on();return t?{embeddingModelDir:t}:void 0}function Vn(e){return e.disableTitle===!0||process.env.AIMAX_DISABLE_TITLE===`true`?{enabled:!1}:void 0}function Hn(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 Y(e){return e?.trim()||void 0}function Un(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 X(e){return e?.trim()||void 0}function Wn(e){return e??`WEB`}function Gn(e){return e?f(e):void 0}function Kn(e,t){return e===`CRON`?`crons`:Gn(t)}function qn(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 Jn(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 Yn(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 Xn(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 Zn(e){if(!e?.trim())return{};let t=[],n=new Set;for(let r of Xn(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,Yn(o)])}return Object.fromEntries(t)}function Qn(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 $n(e,t){if(e===void 0)return;let n=e.trim().toLowerCase();if(n){if(Rn.includes(n))return n;throw Error(`Invalid ${t}: ${e}. Must be one of off,gate,dry_run,write.`)}}function er(e){let t=e.autoSkillsLoadEnabled===void 0?Qn(process.env.AIMAX_AUTO_SKILLS_LOAD_ENABLED,`AIMAX_AUTO_SKILLS_LOAD_ENABLED`):Qn(e.autoSkillsLoadEnabled,`--auto-skills-load-enabled`),n=e.autoSkillsReviewMode===void 0?$n(process.env.AIMAX_AUTO_SKILLS_REVIEW_MODE,`AIMAX_AUTO_SKILLS_REVIEW_MODE`):$n(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 tr(e,t){return e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`}function nr(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 rr(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?` ${tr(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=>nr(e,a).map(e=>`│ ${e.padEnd(a,` `)} │`)),l].join(`
9
- `)}function ir(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 ar(e){return e?`set`:`unset`}function or(e){return e?`true`:`false`}function sr(e,t){let n=Kn(t.channel,e.sessionStore)??`sessions`,r=t.timeoutMs===void 0?`default`:`${t.timeoutMs}`,i=e.callbackUrl?`enabled`:`disabled`,a=e.streamUrl?`enabled`:`disabled`,o=ir(t.input),s=t.input.kind===`text`?`inline`:e.fromFile??t.input.source,c=oe(),l=Bn(e)?.enabled===!1?`disabled`:`enabled`,u=Vn(e)?.enabled===!1?`disabled`:`enabled`,d=e.pluginsConfig??process.env.AIMAX_PLUGINS_CONFIG,f=[...zn(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(Zn(e.env)):[],v=_.length===0?`-`:`${_.length} key${_.length===1?``:`s`}`;return{banner:rr(void 0,[`AIMax CLI`,`Stateless Agent Runner`]),contextBox:rr(`Run Context`,[`time : ${c}`,`dataDir : ${t.dataDir}`,`projectDir : ${Y(e.projectDir)??`-`}`,`systemAgents : ${t.systemAgentsDir??`/aimax/agents`}`,`agent : ${X(e.agent)??`-`}`,`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 : ${ar(t.llm.apiKey)}`,`authToken : ${ar(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 : ${ar(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 : ${or(e.force)}`,`resumeReqId : ${Z(e.resumeRequestId)}`,`resumeInput : ${e.resumeInputJson===void 0?`-`:`inline (${e.resumeInputJson.length} chars)`}`,`resumeFile : ${Z(e.resumeFromFile)}`,`encryptSess : ${or(e.encryptSessions)}`,`topicSegment : ${l}`,`titleGen : ${u}`]),logContext:{time:c,channel:t.channel,user:e.user,dataDir:t.dataDir,projectDir:Y(e.projectDir),systemAgentsDir:t.systemAgentsDir,agent:X(e.agent),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 cr(e,t){let n=Hn(e),r=Wn(e.channel),i=Ct({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:Un(e),channel:r,format:e.output===`json`?`json`:`text`,timeoutMs:e.timeout?Number(e.timeout):void 0,llm:i,input:t,skillsLoadPaths:qn(e.skillsLoadPaths),workdirAllowlist:Jn(e.workdirAllowlist),artifactsUrlWhitelist:ln(e.artifactsUrlWhitelist),autoSkills:er(e)}}function lr(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 ur(e,t){if(!e.sessionId)return null;let n=lr(t);if(!n)return null;let r=await l(Hn(e),e.sessionId,{storeName:Gn(e.sessionStore),encryptSessions:e.encryptSessions});return!r||r.status!==`pending`||!x(n,r.request)?null:{requestId:r.request.requestId,inputText:n}}function dr(e){let t=[],n=null;return e.callbackUrl&&t.push(new Gt(e.callbackUrl)),e.streamUrl&&(n=new en(e.streamUrl,zn(e.streamEvents),e.streamAuthToken),t.push(n)),{sink:new Wt(t),websocketSink:n}}async function Q(e,t){M.info(`dispatching external event`,jr(t)),await e.sink.send(t)}function fr(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 pr(e,t,n,r,i){return{sink:e,websocketSink:t,channel:n,defaultMessageId:r,user:i}}function mr(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 hr(e){return{activeSessionId:e??`pending`,finalResult:null,loggerSessionId:void 0}}function gr(e,t,n,r){!r||n.loggerSessionId===r||(ye(e,{messageId:t.messageId,sessionId:r,sessionStoreName:Kn(t.channel,t.sessionStore)}),n.loggerSessionId=r)}function _r(e,t){e.activeSessionId=t.sessionId??e.activeSessionId}function vr(e,t){return e.messageId??t}async function yr(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 br(e,t,n,r){return async i=>{if(_r(n,i),gr(e.dataDir,{...r,channel:e.channel},n,i.sessionId),y(i)){fr(i);return}if(i.type===`stream_text_delta`){e.format===`text`&&F(i),await t.websocketSink?.sendTextDelta({sessionId:n.activeSessionId,channel:e.channel,messageId:vr(i,t.defaultMessageId),user:t.user,text:i.text});return}e.format===`text`&&F(i);let a=vr(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 xr(e){let t=In(e);return{confirm:(e,n)=>t.confirm(e),select:(e,n,r)=>t.select?t.select(e,n):Promise.resolve(void 0)}}function Sr(e,t,n,r,i,a){let o=At(),s={dataDir:t.dataDir,projectDir:Y(e.projectDir),systemAgentsDir:t.systemAgentsDir,agentPolicy:X(e.agent)?{requestedAgentName:X(e.agent)}:void 0,sessionStoreName:Kn(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:Bn(e),titleGeneration:Vn(e),env:Zn(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:xr};return t.input.kind===`messages`?{...s,messages:t.input.messages}:{...s,message:t.input.message}}async function Cr(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:cn(r)})}async function wr(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 Tr(e,t){let n=sr(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 Er(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 Dr(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 Or(e,t){let n=`run command error: ${t.message}`;M.error(n),Dr(n),P(`Fatal: ${t.message}`),e.end(),await Se(),process.exit(1)}async function kr(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 Ar(n){let r=Hn(n);try{await ut(r,n,async i=>{let a=hr(n.sessionId);gr(r,{...n,channel:Wn(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 kr(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 Nn({dataDir:n.dataDir,projectDir:n.projectDir,systemAgentsDir:n.systemAgentsDir,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 Ut({message:n.message,fromFile:n.fromFile,messages:n.messages})}catch(e){await Or(o,e);return}let l=await ur(n,c);if(l){await Nn({dataDir:n.dataDir,projectDir:n.projectDir,systemAgentsDir:n.systemAgentsDir,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}=mr(()=>({activeSessionId:a.activeSessionId,finalSessionId:a.finalResult?.sessionId,messageId:n.messageId,channel:u,user:n.user})),m=null;try{let r=await cr(n,c);u=r.channel,Tr(n,r);let i=dr(n);m=i.sink,M.info(`external sink configured`,{callbackUrl:n.callbackUrl,streamUrl:n.streamUrl,streamEvents:n.streamEvents});let s=pr(m,i.websocketSink,r.channel,n.messageId,n.user);await yr(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=nn(i),o=Gn(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=an({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 K(r.dataDir,h),v=br(r,s,a,n);f&&await v(f);let y=await _(Sr(n,r,d,v,g,l));gr(r.dataDir,{...n,channel:r.channel},a,y.sessionId),await Cr(s,a,n.messageId,y),process.exitCode=Er(o,y,r.format)}catch(e){let t=e;m&&await wr(pr(m,null,u,n.messageId,n.user),a,n.messageId,t),await Or(o,t)}finally{await m?.close(),f()}})}finally{await Se()}}function jr(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 Mr(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(`--agent <name>`,`Custom agent name to run as the root agent`).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 Ar(e)})}export{N as _,Gt as a,M as b,Mt as c,Pe as d,F as f,P as g,je as h,en as i,Ct as l,Me as m,Mr as n,Wt as o,Ne as p,Fn as r,K as s,Ar as t,ut as u,we as v,Se as x,ye as y};