# @gencode/agents

## 0.26.0

### Minor Changes

- 1d4571c: 插件调用 `api.llm.chat()` 现在支持传入 `headers` 参数，在单次请求中追加或覆盖 HTTP headers。

  ```ts
  await api.llm.chat({
    user: "hello",
    headers: { "X-Tenant": "acme" },
  });
  ```

  `headers` 是可选的，per-call headers 会叠加在全局 `llm.headers` 配置之上，同名 key 以 per-call 为准。不需要修改任何配置文件即可使用。

### Patch Changes

- 3e866df: Expose the normalized session storage directory on plugin hook context as `ctx.sessionStore`. Hooks can now locate the current root session under `<dataDir>/.aimax/<sessionStore>/<sessionId>/`; the value defaults to `sessions` and preserves configured nested store paths without a trailing slash.

## 0.25.1

### Patch Changes

- 042b8cc: HTTP callback 与 WebSocket 的最终 `done` 和模型执行 `error` 消息现在会在顶层返回 `requestId`，其值与产生最终结果或错误的最后一次模型请求所发送的 `X-Request-Id` 一致。无需新增配置；未发生模型请求的短路任务、参数校验错误和其他前置失败继续省略该字段。

## 0.25.0

### Minor Changes

- 42eeadf: Added tool disabling via the profile config: tools listed under `tools.disabledList` in `config.yaml` (default or profile) are now removed from the loaded tool set at runtime. Matching is case-insensitive and applies to both built-in and plugin-provided tools. The `tools` field stays in the merged config object and is never written to or deleted from the config files.

## 0.24.0

### Minor Changes

- e837f68: Removed the session export tools snapshot feature: the agent runtime no longer writes `session-tools.json` into session directories (`<data_dir>/.aimax/sessions/<session_id>/`). Previously this file was regenerated on every run so `aimax export-html` could render an "Available Tools" section; exported HTML no longer contains that section, and existing legacy `session-tools.json` / `system-prompt.txt` files are ignored. The deprecated compatibility APIs (`persistSystemPromptSnapshot`, `loadSystemPromptSnapshot`, `persistSessionExportSnapshots`) remain exported but are no-ops that never write files. Public snapshot APIs (`persistSessionToolsSnapshot`, `loadSessionToolsSnapshot`, `loadSessionExportSnapshots`, `sessionToolsSnapshotPath`, `serializeToolsForSnapshot`) and the `includeSnapshots` export option have been removed. Leftover snapshot files on disk are harmless and can be cleaned up manually if desired.

### Patch Changes

- 28f43b6: 模型网关请求现在通过 `X-Request-Id` 接收每次请求独立生成的 UUID。HTTP callback 与 WebSocket 的模型相关消息也会返回顶层 `requestId`；同一次请求产生的流式文本、工具开始和工具结果共享该值，工具结果回灌后的下一次模型请求会使用新值，便于后端按请求关联调用和用量统计。
- 71c57af: Improve title generation stability by truncating assistant response context to 2000 characters before sending to the summary model. This prevents title generation failures when the flash model has limited context window capacity.

## 0.23.7

### Patch Changes

- 758aeb6: Prevent session search from hanging indefinitely when a historical-session summary model request stalls. Each session summary now falls back to transcript snippets after one minute, and canceled runs stop the search immediately.

## 0.23.6

### Patch Changes

- fb742da: `read_file` 工具现在能自动识别并解析 `.eml` 邮件文件。读取 `.eml` 时，会先用邮件解析器提取结构化内容，返回 `Subject`、`From`、`To`、`Cc`、`Date` 等字段以及纯文本正文，而不是原始 RFC822 文本，方便后续处理直接理解邮件内容。多部分（multipart）邮件会优先返回 `text/plain` 部分；若只有 HTML，会从中提取纯文本。如果某个 `.eml` 文件解析失败，会自动降级为按普通文本读取，不影响原有行为。其他类型的文件完全不受影响。
- fb4c642: Historical-session search now summarizes returned sessions with bounded concurrency, reducing latency while preserving ranked result order and per-session extractive fallback behavior. The default remains `summary_mode: "llm"`; callers that only need fast IDs, original snippets, or locating clues can set `summary_mode: "off"` to avoid summary LLM calls.

## 0.23.5

### Patch Changes

- 0949ee7: `read_file` now returns at most 30 KB of visible text per call, truncates individual lines after 2000 characters, and tells the agent which `offset` to use to continue reading. This reduces the chance that reading large or minified files fills the model context while preserving line-numbered, slice-by-slice navigation.

## 0.23.4

### Patch Changes

- eb90f99: Prevent fork sessions from being recorded with the `/fork ...` control command as their title. Fork runs no longer emit a `start` callback with the slash command text; consumers should use the `session_forked` and `title_updated` events, which carry `Fork of <original title>`, followed by the empty-text `done` event that only terminates the run.

## 0.23.3

### Patch Changes

- a93accd: L6 context compaction and related summary requests now send the same AIMax LLM routing headers as normal model calls, including session, message, channel, model, and configured custom headers. Deployments that rely on gateway headers for session affinity, auditing, or tenant routing now get consistent metadata during automatic summary generation.
- Updated dependencies [3cdc204]
  - @gencode/shared@0.8.3

## 0.23.2

### Patch Changes

- 4b6dff4: Update session forking to work with schedulers that require the run `sessionId` to be the newly created fork session ID. Send `/fork {"fromSessionId":"<sourceSessionId>","fromMessageId":"<messageId>"}` while passing the fork session ID through run / CLI `sessionId`; the fork is created in the same `--session-store`, copies `transcript.jsonl` through the selected completed assistant reply, and writes a fresh `session.json` titled `Fork of <original title>`.

  Fork callbacks and websocket streams continue to emit `session_forked` and `title_updated` for the new session. The final `done` event for the `/fork` control command now also uses the new fork session ID because that is the run session ID supplied by the caller.

- Updated dependencies [4b6dff4]
  - @gencode/shared@0.8.2

## 0.23.1

### Patch Changes

- 8cbb217: The `session_forked` callback and websocket event now include a human-readable `message` field alongside the existing `title`, `sourceSessionId`, `fromMessageId`, and `copiedEntryCount`. Its value mirrors the new session's `title`, giving consumers a single field to surface a fork notice to end users in the same way they already use the `message` field on the `start` and `session_reset` events. This is an additive, backward-compatible change — existing handlers that ignore unknown fields are unaffected.
- Updated dependencies [8cbb217]
  - @gencode/shared@0.8.1

## 0.23.0

### Minor Changes

- edca43f: Propagate subagent HITL pause signals to parent agents with two-phase resume

  When a subagent triggers a HITL pause (e.g. tool safety approval), the pause signal now automatically bubbles up to the parent agent, which also pauses and waits for user input.

  Resume uses a two-phase mechanism:

  1. First resume the paused subagent session so it completes the HITL interaction and produces a result.
  2. Then inject the subagent result back into the parent's `subagent_spawn` tool call so the parent can continue.

  No configuration changes required — behavior is automatic. Subagent status now includes a `"paused"` enum value; pause details are available via `SubagentRegistry` or `SubagentRunRecord.pausedInfo`.

### Patch Changes

- 50f0b9a: Fixed `/fork` so it no longer modifies the source session's transcript. Previously, running `/fork {"newSessionId":"<uuid>","fromMessageId":"<messageId>"}` in a session would append a `/fork ...` user message and a `Forked session …` assistant reply to that source session's `transcript.jsonl`. Now the source session is left byte-identical — `/fork` only creates the new sibling session, nothing is written back to the source.

  As a result, the run result for `/fork` no longer carries a reply text. Consumers that read the fork outcome should use the `session_forked` callback/websocket event (which already reports `newSessionId`, `fromMessageId`, `title`, and `copiedEntryCount`); the source session's final `done` callback now ships an empty `result.text`. `/fork` is also no longer treated as a session turn — it does not emit the `agent_end` cycle or the `session_end` hook on the source session; it ends immediately after the fork/title progress events (or a `diagnostic` event on failure).

- Updated dependencies [50f0b9a]
- Updated dependencies [edca43f]
  - @gencode/shared@0.8.0

## 0.22.12

### Patch Changes

- b5c3377: Add session forking through the `/fork` slash command. Send `/fork {"newSessionId":"<uuid>","fromMessageId":"<messageId>"}` in an existing session to create a new session in the same `--session-store`; the new session receives a copied `transcript.jsonl` through the selected message's completed assistant reply and a fresh `session.json` titled `Fork of <original title>`.

  Callbacks and websocket streams can now receive a top-level `session_forked` creation event for the new session, followed by a top-level `title_updated` event for `Fork of <original title>`. The `/fork` command itself still completes on the source session, so the final `done` callback remains associated with the session where the command was sent.

- Updated dependencies [b5c3377]
  - @gencode/shared@0.7.8

## 0.22.11

### Patch Changes

- 1f0ae6b: `record_artifacts` now treats user-requested PDF, Word, PowerPoint, and Excel reports or documents as final artifacts after they are successfully produced, alongside existing Markdown, HTML, and supported online document URLs.

## 0.22.10

### Patch Changes

- 653bb11: `--session-store` now accepts slash-separated nested relative paths such as `groupchat/<group_id>/<user_id>/`. Session transcripts, metadata, logs, HITL state, goals, and Uni artifacts for that store are written under `<dataDir>/.aimax/groupchat/<group_id>/<user_id>/<sessionId>/`; unsafe store values such as absolute paths, `..`, empty path segments, or backslash-separated paths are still rejected. Root session IDs are also validated as single safe path segments before session files are created.

## 0.22.9

### Patch Changes

- 192051d: 会话启动时的引导文件加载阶段新增耗时日志并改为并行读取，用于定位 `session_start` 钩子完成到 `bootstrap context loaded` 之间的耗时。

  新增的 INFO 级日志（每次会话启动都会输出，无需额外配置）：

  - `bootstrap file loaded` / `bootstrap file missing`：每个引导文件（`AGENTS.md`、`SOUL.md`、`TOOLS.md`、`IDENTITY.md`、`USER.md`、`MEMORY.md`、`BOOTSTRAP.md`）的读取结果与耗时（`file`、`bytes`、`durationMs`），路径为 `<dataDir>/.aimax/`。
  - `bootstrap files loaded`：整批引导文件加载汇总（`count`、`missingCount`、`durationMs`）。
  - `project agents file loaded` / `project agents file missing`：项目级 `AGENTS.md`（位于 `<projectDir>/AGENTS.md`）的读取结果与耗时。
  - `system prompt loaded` / `system prompt missing, using default`：系统提示词（默认路径 `/aimax_pvc/system_prompt.md`）的读取结果与耗时。
  - `runtime inputs loaded`：上述三段并行加载的总耗时（`sessionId`、`durationMs`）。

  性能改动：7 个引导文件的读取从串行改为 `Promise.all` 并行，三段独立的加载（引导文件 / 项目 `AGENTS.md` / 系统提示词）也改为并行执行，可减少网络挂载（如 PVC）上的往返耗时。引导文件注入顺序、`BOOTSTRAP.md` 一次性删除语义、文件缺失（ENOENT）处理均与改动前一致。

## 0.22.8

### Patch Changes

- 07d527b: Add runtime controls that keep memory auxiliary to agent runs. Use `aimax run --disable-memory`, `aimax resume --disable-memory`, or `AIMAX_DISABLE_MEMORY=true` to skip memory providers, `.aimax/.index.sqlite`, memory plugins, indexing/watch/sync, recall/capture, and memory/session search tools while continuing to persist the original session transcript. When memory remains enabled, automatic run/resume maintenance such as capture indexing, search drain, and session delta projection now has a default 3s budget; if embedding/cache/sqlite projection cannot finish in time, that best-effort pass is discarded without changing the current index state and the agent run continues. Existing memory files and indexes are left untouched, and explicit `aimax memory ...` maintenance commands remain available for full indexing or rebuilds.
- 38fdbf7: Fix incorrect model perception when a before-tool HITL approval is denied. Previously, when a user rejected a tool execution request (e.g. a file write), the tool result was marked with `isError: false` and the skip message was ambiguous, causing the model to believe the tool had executed successfully and reference the intended file paths in its response. The tool result is now marked with `isError: true`, the skip message explicitly states that the tool was not executed and no files or system state were modified, and the history replay instruction for skipped HITL checkpoints now clearly instructs the model not to assume the tool succeeded.
- cd80262: Prevent normal AIMax runs from automatically rebuilding all historical session memory when projection metadata is missing or incompatible. Runs stay available in a degraded memory state; restore the session index with `aimax memory index --include-sessions` or `--rebuild`.

  Without a real embedding provider, builtin memory now indexes and searches in FTS-only mode (no mock embedding CPU work). Explicit `memory index` / `--rebuild` uses mtime/size-first session discovery and batch yields. Failed or stale projections fall back to canonical Memory Markdown instead of returning outdated index rows; unrelated Memory edits no longer hide healthy session recall. Touching a transcript without content changes only refreshes index metadata.

- 92e2b64: Allow Windows users to select Git Bash or CMD with `AIMAX_SHELL`. When unset
  on Windows, AIMax now prefers `C:\Program Files\Git\bin\bash.exe` and
  falls back to CMD. The active `shell=bash` or `shell=cmd` mode is also included
  in the agent runtime prompt so generated commands use matching syntax without
  relying on PowerShell.

## 0.22.7

### Patch Changes

- 44fabec: 标准 Agents 运行时会限制 `aimax run` 和 `aimax resume` 的成功 callback / WebSocket `done.result.operations` 以及 assistant transcript entry 的体积：最多返回本轮前 100 条轻量文件操作摘要，不再复制文件内容和仅供完整审计使用的元数据；`operationCount` 表示本轮完整操作数，超过上限时 `operationsTruncated` 为 `true`。完整操作审计仍保存在 Session 的 `artifacts.json.operations`，显式最终制品 `artifacts` 与 Uni Provider 行为保持不变。
- Updated dependencies [44fabec]
  - @gencode/shared@0.7.7

## 0.22.6

### Patch Changes

- d9ab5b5: 标准 Agents 运行时现在会在 `aimax run` 和 `aimax resume` 的成功 callback / WebSocket `done.result.operations` 中返回本轮经文件工具成功执行并持久化审计的文件变更，同时把同一非空数组记录到本轮最后一条 assistant transcript entry；CRON 同步到来源主会话的结论也保留这些变更。`operations` 与显式最终制品 `artifacts` 保持独立，空集合时省略，并且不会混入 Session 历史累计记录；root 结果包含本轮 root agent 与 subagent 的操作，可通过 `source` 和 `sessionId` 区分执行者。Uni Provider 的返回与 transcript 行为保持不变。
- 351e45b: 当 `aimax run --message-id <id>` 或 one-shot Server 请求提供 `messageId` 时，`.aimax/<session-store>/<session-id>/transcript.jsonl` 的对应 user 记录现在会保存该 ID，便于把用户输入与日志、回调及 WebSocket 事件关联定位。未提供 ID 时保持原有格式，不生成合成值。
- Updated dependencies [d9ab5b5]
  - @gencode/shared@0.7.6

## 0.22.5

### Patch Changes

- ecf9d8e: Fixed the `exec` tool failing validation on certain LLM providers (DeepSeek, Mistral, xAI/Grok, ZAI, Cerebras, etc.) that do not fully support `anyOf` in JSON Schema. The `riskLevel`, `riskReason`, and `isReadOnly` parameters were marked as required in the tool schema, causing tool calls to be rejected when these providers omitted them. These fields are now optional in the schema, and the tool description has been updated to strongly encourage the LLM to include all three parameters. When any of them are absent, the existing rule-based fallback assessment continues to apply.

## 0.22.4

### Patch Changes

- 19b7369: AIMax Agent 现在会把网页、邮件、文档、OCR 和工具结果视为不可信数据，阻止其中的嵌入指令扩大任务授权；同时在发送、提交、更新、删除等副作用前核对用户的精确授权，并在写入、计算或状态变更后完成有界验证。系统提示词还会对来自环境变量、工具、文件、日志或配置的凭证统一脱敏，避免原样输出 API key、token、密码和其他 secret。

## 0.22.3

### Patch Changes

- 556c23b: Improve context safety for Chinese and other multibyte text by accounting for UTF-8 width in local token estimates while preserving existing ASCII estimates. Topic segmentation, session-memory refresh, and context compaction now trigger closer to actual model usage when provider token usage is unavailable.
- 30042ad: 标准 Agents 运行时现在会在 `aimax run` 和 `aimax resume` 的成功 callback / WebSocket `done.result.artifacts` 中返回本轮通过 `record_artifacts` 成功登记的最终文件与 URL，并把同一非空数组记录到本轮最后一条 assistant transcript entry；CRON 同步到来源主会话的结论也保留这些产物。本轮结果不会混入 Session 历史累计产物或 `artifacts.json.operations`，没有产物时继续省略该可选字段。Uni Provider 的返回与 transcript 行为保持不变。
- Updated dependencies [30042ad]
  - @gencode/shared@0.7.5

## 0.22.2

### Patch Changes

- 23634ef: Prevent premature L6 context compaction by using the provider's latest complete token usage plus newly added messages during active agent loops. When provider usage is unavailable, system prompts and tool schemas now use the same token heuristic as message text instead of treating every UTF-8 byte as one token.

## 0.22.1

### Patch Changes

- b2d9fb0: Keep `.aimax/<session-store>/<session-id>/context.json` stable when parallel tools, overlapping task executions, or multiple containers refresh the same context snapshot. Snapshot writes now use collision-safe temporary files and serialize the complete merge-and-replace transaction; transient persistence failures are logged and retried without turning an otherwise healthy agent run into a Fatal error.

## 0.22.0

### Minor Changes

- eaf9fb8: The `exec` tool now requires an `isReadOnly` parameter. When calling the tool, the model self-assesses whether the command is read-only (no side effects on the filesystem or external state) and returns `true`/`false`, or `null` to let the system fall back to a rule-based assessment. The resolved `isReadOnly` value is included in every exec tool result's `details`, allowing callers and UIs to distinguish read-only commands from mutating ones.

## 0.21.11

### Patch Changes

- abc0365: The exec tool now requires the model to self-assess the command risk level (`riskLevel`) and reason (`riskReason`) on every call, returning one of low/medium/high/critical after analysis. Only when the risk genuinely cannot be determined may it return `null`, in which case the system falls back to a rule-based assessment. Previously these two fields were optional and could be omitted, leaving commands without risk annotation. Every shell command execution result now carries the risk assessment, making command risk consistently observable in the UI and logs.

## 0.21.10

### Patch Changes

- ae33473: Check L6 context pressure before every model request, including requests made after tool calls inside one agent loop. Long-running tasks now compact at the existing 70% threshold before sending an oversized follow-up request, while preserving the raw transcript for audit and session resume.

## 0.21.9

### Patch Changes

- 76b40e7: `.aimax/<session-store>/<session-id>/transcript.jsonl` 现在会在每次主 Agent 模型调用对应的 assistant 记录中保存完整 token usage，包括输入、输出、缓存读取、缓存写入和总 token。普通文本轮、工具调用轮及最终失败轮使用同一合同；Provider 未返回 usage 时不会写入全零占位数据。
- fea9970: 长会话的 `.aimax/<session-store>/<session-id>/context.json` 现在会在每次主 Agent 模型请求返回有效 usage 后立即刷新 `compaction.modelUsage`，不再等到整个 run 结束。checkpoint 的 token 字段、`recordedAt` 和 `coveredTranscriptEntryCount` 使用同一次请求边界；Provider 未返回 usage 时，适配层合成的全零值不会覆盖最近一次有效记录。

## 0.21.8

### Patch Changes

- 88e135e: Stabilize session context persistence so `.aimax/<session-store>/<session-id>/context.json` keeps the latest `compaction.modelUsage` checkpoint when overlapping task executions update other context fields such as session memory, tool result budgets, snips, or collapse spans. This helps L6 context compaction continue using the most recent token checkpoint instead of falling back after a stale writer saves the context snapshot.

## 0.21.7

### Patch Changes

- 4ff65b2: 长会话的 L6 自动压缩现在会使用模型返回的完整 token usage 预测下一轮上下文：`context.json` 的 `compaction.modelUsage` 升级为 V2，新增 `cacheReadTokens` 和 `cacheWriteTokens`，`totalTokens` 包含缓存 token。预测值按“上一轮完整 `totalTokens` + checkpoint 后新增历史 + 当前 prompt”计算；旧 V1 记录会安全回退到本地完整估算，避免缓存命中较高时无法触发约 70% 阈值的自动压缩。
- eb25c8a: AIMax 的 OpenAI-compatible 执行链将官方 OpenAI SDK 从 6.10.0 升级到 6.26.0，与内置 pi-ai 运行时使用的版本对齐，消除同一执行链中的重复 SDK 版本。现有 CLI 配置、请求格式与流式事件协议保持不变。
- eb25c8a: 修复 Pi 扩展 `getFlag` 误把 `registerFlag` 的 options 对象当 truthy 值返回，导致默认路径下 LSP 工具被当成禁用；并为扩展 tool `execute` 注入与 hook 共用的执行 context（至少稳定提供 `cwd`，有 run signal 时透传 `ctx.signal`），避免读 `cwd`/`signal` 崩溃。
- eb25c8a: 为通过 Pi 扩展加载的工具（如 `lsp_diagnostics` / `lsp_navigation`）增加执行硬超时，避免单个扩展工具挂死后整轮对话永久无响应。默认超时 120 秒，可用环境变量 `AIMAX_PI_EXTENSION_TOOL_TIMEOUT_MS` 覆盖；`lsp_*` 工具在传入 `waitMs` 时会按 `max(waitMs+5s, 30s)` 计算，未传时默认 60 秒。超时后工具返回明确错误并中止该次 tool call，不影响 `exec` 等内置工具的既有超时协议。
- eb25c8a: 修复 AIMax 文件工具名与 pi 社区扩展（如 pi-lens）不兼容的问题：`read_file` / `edit_file` / `write_file` 在扩展 hook 中会归一为 `read` / `edit` / `write`，`edit_file` 的 `old_string`/`new_string` 会映射为 pi 风格 `edits[{oldText,newText}]`。结果是 read-guard、tool_result 等扩展行为在 CLI 默认文件工具路径上生效，而无需改扩展源码。
- eb25c8a: 将 AIMax agent runtime 的 `pi-agent-core` 与 `pi-ai` 精确升级到 0.80.10，并通过公共 `/compat` 入口保持现有 provider registry 与 stream 集成。长上下文请求现在会依据模型上下文窗口自动 clamp 最大输出 token，降低 context overflow 风险；CLI 参数、session 与 stream 协议保持不变。
- d2b77c7: Agent Team runs now route every substantive workstream through configured members based on each Agent's `description`, expose member routing metadata as escaped `<agents><agent>...</agent></agents>` XML, and keep the coordinator focused on delegation, review, and synthesis. Existing Agent Team Markdown configuration paths and file formats are unchanged.
- eb25c8a: 修复插件 `tool_result` 钩子超时导致“文件已写成功、对话却报失败”的问题。`tool_result` 现在使用独立默认预算 60 秒（可用环境变量 `AIMAX_TOOL_RESULT_HOOK_TIMEOUT_MS` 覆盖），不再与 `before_tool_call` 等其它 blocking 钩子共用 10 秒上限。若写后增强（如 pi-lens format/LSP）仍超时，宿主会保留原始工具结果并记录诊断，**不会**把成功的 write/edit 标成 `isError`。
- Updated dependencies [4ff65b2]
  - @gencode/shared@0.7.4

## 0.21.6

### Patch Changes

- 6654e54: Keep subagent diagnostics inside the parent session hierarchy at `.aimax/<session-store>/<parent-session-id>/subagents/<tool-call-id>/logs/app.log` and `errors.log`. Subagent logs no longer add the root message ID as another directory or create an escaped top-level child session directory; root session logs remain isolated under `logs/<message-id>/`.
- ea9cac8: 自定义 Agent 的 `skills` 配置现在是运行时强制白名单。可在 `/aimax/agents/*.md`、`<dataDir>/.aimax/agents/*.md` 或 `<projectDir>/.aimax/agents/*.md` 的 front matter 中填写 Skill 名称；未配置时仍继承全部有效 Skills，显式 `skills: []` 时不再暴露任何 Skill。白名单同时限制提示词、Skill 列表/加载、Skill action、Slash Command、插件 hook、learned auto-skills、scene Skills 和未命名子 Agent 继承，不能再通过 `skillPath` 使用未配置的 Skill。

  每次运行自定义 Agent 时，`<dataDir>/.aimax/<session-store>/<session-id>/logs/<message-id>/app.log` 会写入中文 `自定义 Agent 已启用 Skills` 审计记录，列出配置、实际启用及缺失的 Skills；缺失项会额外记录警告，但不会回退为全部 Skills。

## 0.21.5

### Patch Changes

- e3b9e3f: `record_artifacts` 现在会在用户要求的 Markdown（`.md` / `.markdown`）或
  HTML（`.html` / `.htm`）报告/文档成功写入后，或神兵文档、Wizard Wiki、
  Pages 成功创建/更新并返回 URL 后及时登记。它不再作为会话结束检查点，没有
  合格产物时不会空调用；登记后仍可继续验证并输出完整结论。
- dd052a4: CRON 定时任务现在使用 `--session-store <name>` 选择 `parentSessionId` 对应主会话的目录：显式传入 `<userId>-sessions` 时，主会话的 `session.json`、`transcript.jsonl` 和定时任务终态结论位于 `.aimax/<userId>-sessions/<parentSessionId>/`；未传时仍默认 `.aimax/sessions/<parentSessionId>/`。CRON execution 的完整 transcript 与日志继续固定保存在 `.aimax/crons/<executionSessionId>/`，不会随 parent store 改变。
- 5250a8b: Session 文件变更审计与显式最终产物现在统一保存在
  `<dataDir>/.aimax/<sessionStore>/<sessionId>/artifacts.json` V2：
  `operations` 继续提供文件写入、编辑、删除和移动审计，新增的 `artifacts`
  保存 `record_artifacts` 登记的最终文件或 URL。新运行不再创建或追加
  `changes.json`；测试环境升级前需要清理使用旧结构的 Session 数据。CLI 返回值、
  callback、WebSocket done 和 transcript 继续不携带 artifacts。
- Updated dependencies [5250a8b]
  - @gencode/shared@0.7.3

## 0.21.4

### Patch Changes

- 1014be9: 使用 `aimax run --channel CRON --parent-session-id <主会话ID>` 启动定时任务时，即使新用户尚未聊天、`.aimax/sessions/<主会话ID>/` 还不存在，任务也会先创建 `session.json` 和空 `transcript.jsonl` 后继续执行。自动创建的主会话默认使用 `title: "New session"`、`channel: "WEB"`；已有主会话文件不会被覆盖或清空。
- 6351f28: Silently skip internal and temporary files when recording Artifacts

  Files in `.aimax` or temp directories are now automatically ignored instead of throwing errors during `record_artifacts` calls. Only valid files in allowed directories are recorded.

## 0.21.3

### Patch Changes

- 326db97: Agent Team runs now load only the requested `<name>.md` definition across `/aimax/agent-teams`, `<dataDir>/.aimax/agent-teams`, and the optional project `.aimax/agent-teams` directory, so an invalid unrelated team no longer blocks a valid selected team. Duplicate definitions of the requested name still fail. Invalid `description` diagnostics now identify the source file and distinguish missing, non-string YAML, and over-limit values; the 200-character limit counts Unicode characters. Quote YAML-like text such as dates, numbers, `true`, `false`, or `null` when it should remain a string.
- c5ae0fd: Agent runs now retry transient model failures independently for each LLM turn. A timeout or retryable gateway error that occurs after earlier tool calls can recover without replaying those completed tools, and every new turn receives a fresh retry budget. No configuration is required; the existing safeguard still stops automatic retry when the failing turn itself has already streamed assistant text or produced a tool result.

## 0.21.2

### Patch Changes

- f943d95: 使用 `aimax run --channel CRON --parent-session-id <主会话ID>` 启动的定时任务，在继续把完整执行记录保存到 `.aimax/crons/<执行会话ID>/` 的同时，会在成功或失败终态把一条最终结论追加到 `.aimax/sessions/<主会话ID>/transcript.jsonl`。同一执行会话只追加一次；来源主会话不存在时任务会明确失败，避免创建无法展示的空壳会话。
- e8238b3: 新增显式最终产物登记：每个新的 root run 都应调用且只调用一次 `record_artifacts`，将已校验的文件或 URL 累计写入 Session 的 `artifacts.json` V2；没有产物时传入 `{ "artifacts": [] }`，历史轮次的调用不计入当前轮。漏调不会触发运行时终态门禁，也不会阻止运行成功结束；工具调用后的持久化失败仍会使运行失败。`--artifacts-url-whitelist` 按 hostname 限制 URL，未配置时允许全部域名。文件工具审计迁移到独立的 `changes.json` V1。运行结果、回调、WebSocket done 和 transcript 不再返回或推断 artifacts；Claude Code、Codex、OpenCode 与 Pi 通过各自运行时工具桥接登记，ACP 暂不支持。
- 0521d16: fix: edit_file tool supports files with mixed line endings

  Fix edit_file tool failing with "old_string not found" when file uses CRLF (`\r\n`) line endings but the model returns `old_string` with LF (`\n`) line endings.

  The tool now normalizes line endings automatically, ensuring it works correctly with both Windows and Unix formatted files.

- b7e60a9: 工具执行完成后，`tool_end.details` 现在会作为结构化 JSON 数据通过 callback/websocket 提供给 UI，并写入 `.aimax/sessions/<sessionId>/transcript.jsonl` 的 `tool_result.details`，便于页面展示、会话回放与审计。结构化 `tool_end.output` 不再重复包含顶层 `details`；该字段在当前轮和历史恢复的模型请求边界也会被移除，模型仍只接收工具的 `content`。
- Updated dependencies [e8238b3]
- Updated dependencies [b7e60a9]
  - @gencode/shared@0.7.2

## 0.21.1

### Patch Changes

- 0f9d5da: Agent Team 的协调提示词现使用英文，并要求协调 Agent 将成员职责可覆盖的实质性工作优先委派给团队成员；运行时会在 SubAgent 工具中提示精确成员选择和并行/串行协作方式。直接完成仅适用于简单答复、没有匹配成员或委派不可用的情况。
- c562e03: CRON 定时任务现在支持通过 `--parent-session-id <主会话ID>` 关联来源会话。调度器省略 `--session-id` 后，每次触发都会在 `.aimax/crons/<执行会话ID>/` 创建独立 transcript 和日志；callback 与 websocket 的 `sessionId` 表示本次执行，`parentSessionId` 表示来源主会话。生产调度配置需停止把主会话 ID 作为 `--session-id` 传入。
- Updated dependencies [c562e03]
  - @gencode/shared@0.7.1

## 0.21.0

### Minor Changes

- 82f4ca0: 新增 Agent 团队配置定义能力：团队可使用 Markdown + YAML front matter 落盘到 `/aimax/agent-teams`、`<dataDir>/.aimax/agent-teams` 或项目级 `.aimax/agent-teams`，并通过可选的 `mainAgent` 与必填的 `members` 引用已有自定义 Agent；未配置 `mainAgent` 时使用默认 Agent 协调。配置会校验名称、描述、系统提示词长度、成员唯一性、文件名匹配和跨目录重复名称。
- 82f4ca0: 支持通过 `aimax run --team <name>`（或 server `run.team`）使用 Agent 团队：团队的可选 `mainAgent` 负责协调，未配置时使用默认 Agent；团队 `members` 会按名称和描述注入协调 Agent 的系统提示词，并限制 SubAgent 调用范围；可通过 `--system-agent-teams-dir` 或 `AIMAX_SYSTEM_AGENT_TEAMS_DIR` 指定系统团队配置目录。

### Patch Changes

- 08214df: Bun compiled executables that host Pi extensions now load Jiti via the static entry so Babel transform assets are included in the standalone snapshot; Node.js CLI paths keep the regular Jiti entry. Fixes external extensions (including transform-heavy plugins such as pi-lens) failing with a missing `babel.cjs` module under `/$bunfs/root/`.
- 12db0bf: Builtin memory now writes canonical Markdown through a shared document store with cross-process locking, so concurrent agents no longer silently drop recent notes. Appends, recent logs, updates, structured merges, and deletes refresh only their affected SQLite projection files; search stays available from canonical Markdown if refresh fails. External file watches use affected refresh when the file is known and retain full-sync compatibility for directory or unknown events.

  Builtin memory projection now persists deterministic memory, session, recipe, target, and projected revisions in a versioned meta envelope. Freshness is true only when the persisted target revision equals the projected revision—not dirty flags or chunk counts. Concurrent sync, rebuild, affected, session, and recovery work share a single-flight scheduler so one manager never runs overlapping applies. Failed or partial applies keep the previous projected revision, surface error diagnostics, and recover on a later sync while search can fall back to canonical Markdown. Enabling or disabling session sources, changing the session store identity, or changing embedding recipe settings (provider/model key, chunk size/overlap, vector settings) invalidates the projection until a full-compatible sync repairs it; ranking-only overrides such as max results do not force a rebuild.

- 221dd2f: Builtin memory search now honors per-call `MemorySearchOptions.limit` and `sources` on all four paths (fresh SQLite, stale filesystem fallback, runtime corruption fallback, and construction-unavailable filesystem provider). Omitted `limit` uses the configured `maxResults` (construction-unavailable uses the builtin default of 6 instead of a hidden 20). `limit: 0` or `sources: []` returns an empty list without scanning; invalid limits or source tokens throw `RangeError`; positive limits are floored and clamped to 100. Requested sources only narrow the configured source set and never enable session projection or rewrite manager config. Filesystem fallback can discover session transcripts when sessions are in the resolved source set, while ranking and locators remain in the shared filesystem search. Plugin providers still receive options unchanged; the `memory_search` tool schema remains query-only.
- 766962b: Structured `MEMORY.md` search, update, and forget now share the same `path#heading` locator.

  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.

## 0.20.2

### Patch Changes

- 30e7078: Improve `before_tool_call` HITL resumption so the Agent continues directly from the persisted tool-call history after approval, denial, cancellation, timeout, or execution failure.

  - Resume outcomes are retained with the tool result and supplied to the model as part of the restored conversation context.
  - Approved tools are not prompted to run again after their checkpoint call has already executed.
  - Resume input, callback, and websocket envelope formats remain unchanged.

- 30e7078: Keep HITL pause and audit files in the session store selected for the run.

  Runs configured with `--session-store tasks` now persist `pending-hitl.json` and `hitl-history.jsonl` under `.aimax/tasks/<sessionId>/`, so later `resume` and `cancel` commands can find the paused state in the same store. Subagent HITL requests continue to bubble to the parent session root.

- 58acb1d: When `aimax run` or `aimax resume` receives `--project-dir <path>`, AIMax now automatically loads `<path>/AGENTS.md` when that file exists and injects it into the runtime system prompt as a separate project instructions section. The project file applies only to work in the current repository and does not replace the user-level `.aimax/AGENTS.md` identity and collaboration rules.
- Updated dependencies [2ccd4ba]
  - @gencode/shared@0.7.0

## 0.20.1

### Patch Changes

- aae9c3f: Make resumed `before_tool_call` approvals continue through a normal Agent response across agents, CLI, plugin integrations, console, and web consumers.

  - Approved calls now execute the exact checkpoint tool call once, then the model receives the persisted tool result and produces the final response.
  - Denied, cancelled, or timed-out calls are skipped and still return a model-generated explanation.
  - Existing resume input, callback, and websocket envelope formats are unchanged; approved streams include tool execution events before the final text.

- 1dadb7f: `aimax run` 现在支持按单次任务配置模型采样参数：`--temperature`、`--top-k`、`--top-p`，也可以通过 `AIMAX_TEMPERATURE`、`AIMAX_TOP_K`、`AIMAX_TOP_P` 设置默认值。`aimax-server` 的 `POST /run` 同步支持在 `run.temperature`、`run.topK`、`run.topP` 中传入这些值；未配置时不会向模型请求额外注入采样字段。
- 18c5760: 运行日志现在会记录模型首次返回响应的时间点，以及每个插件 hook handler 执行前、执行完成或失败的状态。通过 CLI 运行时，这些日志会继续写入本次消息对应的 `.aimax/<session-store>/<session-id>/logs/<message-id>/app.log`，便于排查模型首包延迟和插件 hook 耗时。
- Updated dependencies [2c7e63a]
  - @gencode/shared@0.6.2

## 0.20.0

### Minor Changes

- 2ab7f63: Make Thread Goal completion reliable across agents and all applications that consume agent runs.

  - Goal completion and blocking now use separate model tools with required completion evidence or blocking reasons.
  - Repeated invalid terminal submissions stop after a bounded number of equivalent failures instead of looping indefinitely.
  - Final responses report a persistence failure when delivery work exists but the Goal workflow has not reached `complete`.
  - Administrators can recover an individual historical session through the exported Goal recovery API or the `run-goal-recovery` command without editing Goal files directly.

- 2ab7f63: Improve `/goal` task planning consistency across agents, CLI, console, and web consumers.

  - Complex natural-language objectives can initialize 2–5 persistent execution tasks with acceptance criteria.
  - Vague objectives still start in clarify; models commit plans through the new public `goal_plan` tool instead of overloading `update_task`.
  - Clarify gate now covers the full run lifecycle (first turn, announce, continuations) until a later turn observes committed execution state.
  - Terminal `goal complete` rejects clarify-only or unfinished-clarify workflows.

## 0.19.1

### Patch Changes

- cc36dad: Improve URL artifact reporting for online documents and shared resources. When an agent creates or publishes a user-openable online resource and shows a link such as a document link, view link, share link, or download link in the final response, the runtime prompt now more explicitly instructs the model to include the same URL in the `<aimax_artifacts>` declaration so backend `done` payloads and transcript artifact metadata can surface it reliably.
- 8170e03: Support custom HITL approving choice IDs for before-tool safety gates. `HitlChoiceInput` now accepts an optional `approvingChoiceIds` field that declares which choice IDs mean "approve / continue". When resuming a paused run, both guarded operations (`skill_action_run`) and generic non-HITL `before_tool` resumes honor this list. Existing requests that omit the field continue to treat `"approve"` as the only approving choice, preserving backward compatibility.
- 0d0e504: Improve artifact reporting for Wizard Wiki pages. When the `wizard-wiki` skill creates a page through `scripts/create_page.py` or updates one through `scripts/edit_page.py` and the script response includes a page URL, AIMax now returns that URL in the run artifacts payload as a user-openable Wiki page artifact, distinguishing newly created pages from modified pages.
- Updated dependencies [8170e03]
  - @gencode/shared@0.6.1

## 0.19.0

### Minor Changes

- f3e27cb: Add `aimax generate --input <text>` for single-turn model generation without starting an Agent loop. The command uses the normal AIMax LLM configuration flags such as `--base-url`, `--api-format`, `--api-key`, `--model`, `--timeout`, and `--max-tokens`, and prints only the model response text.

## 0.18.3

### Patch Changes

- 3602bdf: HITL approval responses that select `deny` now skip the protected tool execution without marking the run as failed. CLI, callback, websocket, console, web, and one-shot server consumers will receive a normal completed result for the resumed run instead of a top-level error event, while the final text still states that the tool execution was skipped.

## 0.18.2

### Patch Changes

- 0e09aac: 所有发往模型网关的请求现在都会携带 `X-Model-Id` header，其值为该请求最终实际使用的模型名，包括主 Agent、子 Agent、插件、摘要和主题拆分等调用路径；无需新增配置。
- f7335c1: Skill 的高风险命令现在必须在 `SKILL.md` 同级的 `actions.yml` 中声明，并通过 `skill_action_run` 执行；运行时不再向 Agent 提供可直接审批任意命令的 `guarded_exec` 工具。已有 skill 如果直接调用该工具，需要先把命令、输入校验和 `hitl` 策略迁移到 `actions.yml`。
- e691d24: HITL 暂停且当前轮没有模型文本时，返回内容现在直接展示确认请求的标题和说明，不再添加 `[HITL paused]` 前缀；暂停状态及恢复协议保持不变。
- ed68c0c: Topic-filtered conversations now compact oversized selected topics without replacing unrelated session history. Topic compaction is stored in `.aimax/sessions/<sessionId>/topic-segments.json`, while `transcript.jsonl` remains complete; ordinary conversations and `/compact` keep their existing global compaction behavior. Automatic compaction also reserves context for the base system prompt and visible tool schemas before deciding how much history to retain.

## 0.18.1

### Patch Changes

- bc161b3: Expose the current user data root on plugin hook context as `ctx.dataDir`. Plugin hooks can now distinguish the persistent AIMax data directory from the effective working directory exposed as `ctx.workspaceDir`, which may point to `--project-dir` when a run is scoped to a specific repository.
- d77a70b: 插件现在可以通过 `api.hitl.pause()` 发起持久化人工确认，并通过 `api.hitl.isPause()` 识别暂停信号。插件只需使用 `@gencode/plugin-sdk` 的类型，不再需要运行时引入 `@gencode/agents`；请求 ID、当前会话 ID 和创建时间由 AIMax 自动补齐，现有暂停、恢复与外部事件行为保持不变。

## 0.18.0

### Minor Changes

- 37f0256: Add `--workdir-allowlist` CLI option to allow specifying additional directories that exec-style tools can access as working directories. This enables users to grant agents access to directories outside the default workspace root when needed.

  Usage: `aimax run --workdir-allowlist "/path/to/dir1,/path/to/dir2" --message "your task"`

  The allowlist is automatically propagated to child agents spawned via subagent tools and applies to all exec-style tools (bash, skill actions, etc.).

- 0279e82: Add Phase 2 core memory lifecycle wiring for recall, capture, and compaction recall. All features remain default-off until explicitly enabled via `memory.core` structured config. Retrieval regression fixture gates recall quality before default enablement.
- 0279e82: Add Phase 3 Knowledge Controller integration as an optional core memory fallback layer. CLI parses `AIMAX_MEMORY_KC_*` env vars into structured `memory.core.knowledgeController` config; agents dynamically import KC only when enabled with `searchMode=fallback` and local recall is empty or weak. KC failures emit diagnostics without blocking agent runtime creation.
- 6717f94: Add `llm.headers` option to allow passing custom HTTP headers into every LLM request. Default AIMax headers (`Client-Code`, `X-Session-Id`, etc.) are preserved; entries in `llm.headers` are merged on top and can override defaults.

  Usage:

  ```json
  {
    "llm": {
      "baseUrl": "https://api.example.com/v1",
      "apiKey": "...",
      "model": "...",
      "headers": {
        "Client-Code": "MyApp",
        "X-Custom": "value"
      }
    }
  }
  ```

- 9ff9574: Add `api.yaml` to PluginApi, giving plugins direct access to the `yaml` module for parsing, stringifying, and manipulating YAML documents.

  Plugins can now use `api.yaml.parse()`, `api.yaml.stringify()`, `api.yaml.Document`, and all other exports from the `yaml` npm package without adding their own dependency.

### Patch Changes

- 0279e82: Default local memory is now built into the core: daily entries go to `.aimax/memory/YYYY-MM-DD.md`, structured `MEMORY.md` updates merge by section, and no plugin is required for the default provider path. Optional core capabilities—recall, capture, compaction recall, and Knowledge Controller—are configured via `memory.core` and remain off unless explicitly enabled (`memory.core.*.enabled`). CLI parses `AIMAX_MEMORY_KC_*` into structured `memory.core.knowledgeController` for agents. The `aimax-memory-plugin` continues to provide Mem0 Cloud, Mem0 OSS, and third-party memory provider overrides when selected through `plugins.slots.memory` in `plugins.json` or a file passed with `--plugins-config`, with plugin discovery configured through `plugins.load.paths`.
- 0279e82: The built-in memory provider now handles recent memory writes without requiring a plugin: daily entries are appended to `.aimax/memory/YYYY-MM-DD.md`, session entries use `.aimax/memory/session-<sessionId>.md`, and structured `MEMORY.md` updates replace matching sections while preserving unrelated sections. This keeps the default CLI memory path aligned with the local memory layout users already configure under `.aimax`.
- 0279e82: Require the public `goal` completion tool to submit a per-task acceptance report. A complete goal now needs `completedTasks` entries covering every required task and required acceptance criterion with evidence summaries and sources; AIMax records those entries as manual evidence before marking the workflow complete.

  Goal continuation context now includes the required task and acceptance-criterion ids needed to build that completion report. Calls that omit required summaries, tasks, criteria, or evidence sources are rejected with structured errors such as `missing_summary`, `missing_completed_tasks`, `missing_required_completed_task`, `missing_required_acceptance_evidence`, `blocked_tasks_remain`, `unknown_completed_task`, `unknown_acceptance_criterion`, `missing_evidence_summary`, `missing_evidence_source`, `workflow_not_initialized`, or `workflow_corrupt`.

- 0279e82: `aimax run` now releases built-in memory index watchers and timers at the end of each agent run. This keeps the default core memory provider path from holding the Node.js process open after the final session output has been written, while preserving the existing `.aimax/MEMORY.md` and `.aimax/memory/YYYY-MM-DD.md` storage layout.
- Updated dependencies [0279e82]
  - @gencode/shared@0.6.0

## 0.17.2

### Patch Changes

- 0334050: Add automatic RTK command rewriting for `exec` tool calls when `rtk >= 0.23.0` is available on PATH. AIMax now delegates command optimization to `rtk rewrite` before execution, aligns RTK lookup with run-level and per-call `exec.env` values, leaves commands unchanged when RTK is missing or unhealthy, and supports `RTK_DISABLED=1` as a runtime off switch.

## 0.17.1

### Patch Changes

- bb18ff9: AIMax no longer saves the runtime system prompt into session data. New `aimax run` executions do not create or overwrite `<dataDir>/.aimax/<sessionStore>/<sessionId>/system-prompt.txt`, and `aimax export-html` ignores any legacy `system-prompt.txt` files that may already exist, so exported HTML no longer shows historical system prompts. Transcript export remains available, and the existing `<dataDir>/.aimax/<sessionStore>/<sessionId>/session-tools.json` tools snapshot continues to power the Available Tools section. Deprecated snapshot APIs such as `persistSystemPromptSnapshot`, `loadSystemPromptSnapshot`, and `persistSessionExportSnapshots` are retained for compatibility, but system prompt persistence/reading is disabled: the system prompt helpers no-op or return `null`, and the export snapshot helper only writes tools. If your deployment has old `system-prompt.txt` files, clean them with an operations-approved filesystem cleanup job.

## 0.17.0

### Minor Changes

- b352a92: Add Phase 2 core memory lifecycle wiring for recall, capture, and compaction recall. All features remain default-off until explicitly enabled via `memory.core` structured config. Retrieval regression fixture gates recall quality before default enablement.
- b352a92: Add Phase 3 Knowledge Controller integration as an optional core memory fallback layer. CLI parses `AIMAX_MEMORY_KC_*` env vars into structured `memory.core.knowledgeController` config; agents dynamically import KC only when enabled with `searchMode=fallback` and local recall is empty or weak. KC failures emit diagnostics without blocking agent runtime creation.

### Patch Changes

- b352a92: Default local memory is now built into the core: daily entries go to `.aimax/memory/YYYY-MM-DD.md`, structured `MEMORY.md` updates merge by section, and no plugin is required for the default provider path. Optional core capabilities—recall, capture, compaction recall, and Knowledge Controller—are configured via `memory.core` and remain off unless explicitly enabled (`memory.core.*.enabled`). CLI parses `AIMAX_MEMORY_KC_*` into structured `memory.core.knowledgeController` for agents. The `aimax-memory-plugin` continues to provide Mem0 Cloud, Mem0 OSS, and third-party memory provider overrides when selected through `plugins.slots.memory` in `plugins.json` or a file passed with `--plugins-config`, with plugin discovery configured through `plugins.load.paths`.
- b352a92: The built-in memory provider now handles recent memory writes without requiring a plugin: daily entries are appended to `.aimax/memory/YYYY-MM-DD.md`, session entries use `.aimax/memory/session-<sessionId>.md`, and structured `MEMORY.md` updates replace matching sections while preserving unrelated sections. This keeps the default CLI memory path aligned with the local memory layout users already configure under `.aimax`.
- b352a92: Require the public `goal` completion tool to submit a per-task acceptance report. A complete goal now needs `completedTasks` entries covering every required task and required acceptance criterion with evidence summaries and sources; AIMax records those entries as manual evidence before marking the workflow complete.

  Goal continuation context now includes the required task and acceptance-criterion ids needed to build that completion report. Calls that omit required summaries, tasks, criteria, or evidence sources are rejected with structured errors such as `missing_summary`, `missing_completed_tasks`, `missing_required_completed_task`, `missing_required_acceptance_evidence`, `blocked_tasks_remain`, `unknown_completed_task`, `unknown_acceptance_criterion`, `missing_evidence_summary`, `missing_evidence_source`, `workflow_not_initialized`, or `workflow_corrupt`.

- b352a92: `aimax run` now releases built-in memory index watchers and timers at the end of each agent run. This keeps the default core memory provider path from holding the Node.js process open after the final session output has been written, while preserving the existing `.aimax/MEMORY.md` and `.aimax/memory/YYYY-MM-DD.md` storage layout.
- 02c5263: Skills can now request approval for side-effectful shell work without writing a plugin. Skill authors can declare validated actions in `actions.yml` next to `SKILL.md` and invoke them through `skill_action_run`, or ask for one-off command approval with `guarded_exec`. Invalid action configuration, invalid inputs, workspace escapes, and commands changed after approval fail before any script runs.
- Updated dependencies [b352a92]
  - @gencode/shared@0.5.0

## 0.16.4

### Patch Changes

- c96335b: Container prestart deployments can now preload system plugins before the real user request arrives. Start `aimax-server` with `--plugins-config /path/to/plugins.json` or `AIMAX_SERVER_PLUGINS_CONFIG=/path/to/plugins.json`; the server reads that file during warmup and preloads the configured plugins. If a `/run` request does not provide its own `run.pluginsConfig` and does not override `AIMAX_PLUGINS_CONFIG` in request `env`, the run automatically inherits the startup plugins config path, so the CLI execution reuses the preloaded plugin registry. Plugin runtime values such as session env and LLM access remain bound to the actual run request.

## 0.16.3

### Patch Changes

- 718e1da: 修复通过 `aimax-server` 或 `aimax run` 执行任务时，终态 callback 已送达但 `<dataDir>/.aimax/<sessionStore>/<sessionId>/logs/<messageId>/app.log` 缺少 `done` / `error` 投递记录的问题。CLI 运行现在通过既有 `onLog` 合同接管 agents 日志持久化，并在终态 callback 发送后统一完成刷盘，避免 agents logger 提前关闭 CLI 使用的日志后端；无需新增配置。

## 0.16.2

### Patch Changes

- 56d8304: Plugin hook handlers now receive the current external `messageId` on `ctx.messageId` when a run is started with `--message-id` or an equivalent API option. Existing callback, websocket, and progress payloads keep their previous `messageId` behavior.
- a4171d5: Avoid recursive filesystem watching of `.aimax/sessions`, `.aimax/tasks`, and other session stores during memory indexing. Session transcript updates are now tracked through the existing explicit transcript update notification path, reducing watcher usage in large deployments while preserving memory search behavior for normal `aimax run` and `resume` flows.

## 0.16.1

### Patch Changes

- 8abfeba: Fixes run log persistence when AIMax is executed through the one-shot server path. Logs for each request are now flushed by the CLI and agent runtime lifecycle itself, so deployments using `aimax-server` can rely on `app.log` and `errors.log` being written under `<dataDir>/.aimax/<sessionStore>/<sessionId>/logs/<messageId>/` after the real request creates or resumes a session.

## 0.16.0

### Minor Changes

- 40ba841: Thread Goal now exposes a single minimal `goal` model tool by default. Users still manage goals through CLI commands and Console `/goal`; the model-facing tool is only used to submit terminal `complete` or `blocked` status, while task planning, evidence recording, and workflow repair stay internal to the runtime and no longer appear in the default tool list or session tool snapshots.
- 32c7221: Agents can now publish lightweight task plans with the built-in `update_task` tool during multi-step work. Agents are instructed to publish an initial plan before substantive multi-step work, advance it after user-visible steps, and, for explicit numbered or bulleted user steps, update the completed step before starting the next one so several completed steps are not batched into one late update. Callback and websocket consumers receive these snapshots as normal progress events with `event.type: "task_updated"`, including `toolCallId`, optional `explanation`, `updatedAt`, and ordered task items whose status is `pending`, `in_progress`, or `completed`. Console displays the latest task snapshot in the event timeline, while dependency-chain entrypoints are versioned so installing the latest CLI, Web bridge, server, or plugin SDK packages picks up the new runtime and shared progress protocol. AIMax does not create a separate task-plan store, so reconnect/resume behavior continues to rely on the transcript and progress stream.

### Patch Changes

- 132ee84: CRON channel runs now keep their session data, logs, and subagent outputs under `<dataDir>/.aimax/crons/<sessionId>/`. Root CRON logs are written to `<dataDir>/.aimax/crons/<sessionId>/logs/<messageId>/`, and subagents spawned by the CRON run are nested under `<dataDir>/.aimax/crons/<sessionId>/subagents/<childSessionId>/` with their own logs, transcript, context, and tool-results. This prevents CRON diagnostics and subagent files from escaping into the default `.aimax/sessions/` store or into top-level sibling `crons` sessions.
- 89f1931: AIMax now protects agent runs from stalled plugin hooks. Hooks that only observe lifecycle events, such as session, turn, LLM, agent-end, and memory change notifications, run with a per-plugin timeout and report a plugin diagnostic if one plugin hangs or fails, while the main run continues toward its normal done or error callback. Hooks whose return values control the run, such as prompt, model, tool, context, resource, and compaction hooks, also run with a timeout but surface a clear failure to the run instead of hanging indefinitely.
- Updated dependencies [32c7221]
  - @gencode/shared@0.4.0

## 0.15.0

### Minor Changes

- 5af5e22: Add an opt-out switch for LLM session title generation. New sessions now generate a conversational title via the flash model by default (unchanged), but you can skip that LLM call for runs that don't need it — for example batch/one-shot jobs, embedded API usage, or CI.

  - CLI: pass `--disable-title` on `aimax run` or `aimax resume`. It overrides the new env var `AIMAX_DISABLE_TITLE=true`.
  - Programmatic: set `titleGeneration: { enabled: false }` on `AgentRunParams`.

  When the switch is off, the session still gets a title — it falls back to a truncated version of the first user message, so the session list is never blank. No token cost and no network call happen. The switch controls only title generation; topic segmentation is unaffected. Start-up logs now show the resolved state as `titleGen: enabled|disabled`.

### Patch Changes

- cbd1dba: AIMax now treats `LLMRequestError` model failures as retryable transient LLM failures even when the upstream gateway also reports non-retryable-looking metadata such as `BadRequestError` or HTTP 400. Runs still avoid replaying an attempt after assistant text or tool results have already been produced, and the agent log now records why a retry was skipped with fields such as `reason`, `retryableError`, `attemptRecordCount`, `recordsWithToolResults`, and `recordsWithAssistantText`.
- cbd1dba: AIMax now retries LLM turns when the streaming connection is torn down mid-response by the network or upstream, instead of failing the whole run on the first attempt.

  Previously, if the HTTP socket was closed while the model was still streaming (for example an upstream gateway or load balancer dropping the connection, surfacing in logs as `streamErrorType="TypeError"`, `streamErrorMessage="terminated"`, `streamErrorCauseCode="UND_ERR_SOCKET"`, or Node errno codes such as `ECONNRESET`/`EPIPE`/`ETIMEDOUT`), the error reached the turn-retry loop without any retryable metadata, so it was treated as a final failure and the run stopped at `attempt=1` even though `maxAttempts` was higher.

  Such transport-level failures are now recognized as transient and replayed within the existing turn-retry budget (default 3 attempts, exponential backoff). No configuration is required — the new behavior is on by default. User-initiated aborts and genuine non-retryable provider errors (e.g. HTTP 4xx with a real status code) are still not retried, and an attempt is still never replayed once assistant text or tool results have been produced.

## 0.14.0

### Minor Changes

- 5773651: Add the `aimax-server` one-shot prestart entry for container deployments. It starts a local HTTP server, warms system-level AIMax runtime state before the user request arrives, accepts one `/run` request with the same run options used by `aimax run`, delegates execution through the CLI path, and exits after the agent loop finishes. The normal `aimax run` command remains available as the cold-path fallback.

## 0.13.0

### Minor Changes

- 51a02bc: Add Phase 2 core memory lifecycle wiring for recall, capture, and compaction recall. All features remain default-off until explicitly enabled via `memory.core` structured config. Retrieval regression fixture gates recall quality before default enablement.
- 51a02bc: Add Phase 3 Knowledge Controller integration as an optional core memory fallback layer. CLI parses `AIMAX_MEMORY_KC_*` env vars into structured `memory.core.knowledgeController` config; agents dynamically import KC only when enabled with `searchMode=fallback` and local recall is empty or weak. KC failures emit diagnostics without blocking agent runtime creation.

### Patch Changes

- 51a02bc: Default local memory is now built into the core: daily entries go to `.aimax/memory/YYYY-MM-DD.md`, structured `MEMORY.md` updates merge by section, and no plugin is required for the default provider path. Optional core capabilities—recall, capture, compaction recall, and Knowledge Controller—are configured via `memory.core` and remain off unless explicitly enabled (`memory.core.*.enabled`). CLI parses `AIMAX_MEMORY_KC_*` into structured `memory.core.knowledgeController` for agents. The `aimax-memory-plugin` continues to provide Mem0 Cloud, Mem0 OSS, and third-party memory provider overrides when selected through `plugins.slots.memory` in `plugins.json` or a file passed with `--plugins-config`, with plugin discovery configured through `plugins.load.paths`.
- aef73a7: Fixed long-running sessions so internal context-collapse summaries are kept as hidden continuity context instead of appearing as assistant replies such as `[context collapse]` in user-facing chat, callbacks, or websocket output. Existing session audit files such as `collapse-log.jsonl` and `context.json` continue to record the condensed spans for debugging.
- 51a02bc: The built-in memory provider now handles recent memory writes without requiring a plugin: daily entries are appended to `.aimax/memory/YYYY-MM-DD.md`, session entries use `.aimax/memory/session-<sessionId>.md`, and structured `MEMORY.md` updates replace matching sections while preserving unrelated sections. This keeps the default CLI memory path aligned with the local memory layout users already configure under `.aimax`.
- 327b71d: Agent runs now recover cleanly when the configured model gateway returns an empty assistant response with no text and no tool calls. AIMax treats the empty response as a retryable transient failure, removes the empty assistant tail from the in-memory turn history before retrying, and avoids writing no-op empty assistant turns to the session transcript, so affected runs no longer fail with `Cannot continue from message role: assistant`.
- 51a02bc: `aimax run` now releases built-in memory index watchers and timers at the end of each agent run. This keeps the default core memory provider path from holding the Node.js process open after the final session output has been written, while preserving the existing `.aimax/MEMORY.md` and `.aimax/memory/YYYY-MM-DD.md` storage layout.
- 2fac38f: Agent runs now tolerate a corrupted built-in memory SQLite index at `<dataDir>/.aimax/.index.sqlite`. When the derived index is malformed, AIMax isolates the broken SQLite files, rebuilds the index from `MEMORY.md`, `memory/*.md`, and session transcripts when available, and falls back to direct Markdown file operations if SQLite remains unavailable so the main agent task can continue.
- Updated dependencies [51a02bc]
  - @gencode/shared@0.3.0

## 0.12.1

### Patch Changes

- d960faf: `aimax run` and `aimax resume` done payloads can now include an `artifacts` array for user-relevant files and URLs produced during the run. Agents self-report these artifacts with a runtime-only `<aimax_artifacts>` declaration block that AIMax strips from streamed text and final text; the normalized final artifact metadata is also recorded on the current run's last assistant entry in `transcript.jsonl` so session replay can see the same produced files and URLs as the backend done payload. AIMax also conservatively falls back to the current tool execution result when a file or URL is already explicit in `write_file`, `edit_file`, `apply_patch`, or `exec` / bash output, covering edited files, shell-generated files, Excel files produced by skills, and skill scripts that return a URL. The agent prompt now keeps an explicit per-turn artifact audit list so shell, skill, plugin, UI tool, and subagent deliverables are less likely to be omitted from the returned payload. Each returned artifact includes `kind`, `timestamp`, `label`, and either `file` or `url`; AIMax normalizes relative file paths against the run workspace and deduplicates self-reported and tool-inferred artifacts by file path or URL. Operators can pass `aimax run --artifacts-url-whitelist <urls>` with comma-separated values such as `example.test,http://reports.example.test` to collect URL artifacts only from exact hostnames in the whitelist; when omitted, all URL artifacts continue to be returned. This backend return field and transcript metadata are separate from the existing per-session `artifacts.json` audit file and do not read, write, or merge with it.
- 3388ae9: `/goal` continuation now exposes a smaller default workflow tool surface to agents. The default model tools no longer include legacy `update_goal`, `goal_checkpoint`, or manual task switching through `goal_task_start`; goals are completed through `goal_complete` after required tasks and final evidence are recorded.

  Goal evidence registration is now available through a single `goal_record_evidence` tool with `kind: "note" | "manual" | "exec" | "snapshot"`. Existing evidence refs keep the same prefixes (`note:`, `manual:`, `command:`, and `snapshot:`), and `goal_task_done` / `goal_complete` continue to require registered evidence refs before marking work complete.

- Updated dependencies [d960faf]
  - @gencode/shared@0.2.3

## 0.12.0

### Minor Changes

- a9f87b5: Move the `export-html` presentation layer (HTML templates, transcript-to-HTML rendering, batch export, and index generation) out of `@gencode/agents` into `@gencode/cli`, where all process-facing presentation/output already lives. This is a package-boundary cleanup only; `aimax export-html` keeps the same commands and options.

  Notable changes for integrators:

  - `@gencode/agents` no longer re-exports the export-html functions (`exportSessionTranscriptToHtml`, `exportTranscriptFileToHtml`, `exportTranscriptContentToHtml`, `exportAllSessionTranscriptsToHtml`, `exportTranscriptGlobToHtml`, `writeExportHtmlIndex`) or their option types (`ExportTranscriptHtmlOptions`, `BatchExportTranscriptHtmlResult`). If you imported these from `@gencode/agents`, they are now internal to `@gencode/cli`.
  - The session snapshot **domain** behavior stays in `@gencode/agents`: `persistSessionExportSnapshots` / `loadSessionExportSnapshots` / `serializeToolsForSnapshot` and the `system-prompt.txt` / `session-tools.json` write timing are unchanged.
  - Exported HTML pages now load `marked` and `highlight.js` from a CDN at view time (jsDelivr) instead of bundling vendored copies inside the package. The pages remain self-contained for session data; viewing requires network access the first time the libraries are fetched (after which the browser cache serves them).

### Patch Changes

- 2f6ada8: 修复 CLI 启动时崩溃的问题：`aimax`（以及任何加载 `@gencode/agents` 的入口）在 Node ESM 下启动会立即抛出 `ERR_PACKAGE_PATH_NOT_EXPORTED`，导致命令一执行就报错退出。

  - **现象**：运行 `aimax -V`、`aimax --version` 或任意子命令时，进程在加载阶段失败，报 `Package subpath './dist/utils/sanitize-unicode.js' is not defined by "exports" in .../pi-ai/package.json`。
  - **根因**：`@gencode/agents` 的 OpenAI-compatible provider 直接 deep-import 了 `@earendil-works/pi-ai` 的内部 `dist/` 子路径（`sanitize-unicode`、`simple-options`、`transform-messages`、`github-copilot-headers`），而这些路径并未被该包的 `exports` 暴露。构建产物保留了这些 import，Node 在运行时强制校验 `exports` 即报错。
  - **修复**：把必需的三个叶子工具（`sanitizeSurrogates`、`buildBaseOptions`、`transformMessages`，均为零依赖纯函数）就近内联到 agents 内部；移除未使用的 `clampReasoning` 导入；移除不再需要的 GitHub Copilot 动态请求头注入（`buildCopilotDynamicHeaders` / `hasCopilotVisionInput`）。运行时不再触碰 pi-ai 的内部子路径，CLI 可正常启动并返回版本号。
  - **用户感知**：此前任何 `aimax` 调用都会立即崩溃；修复后 CLI 恢复可用。openai-completions 兼容 provider 的既有消息处理行为不变。

## 0.11.0

### Minor Changes

- 674c296: Move the `export-html` presentation layer (HTML templates, transcript-to-HTML rendering, batch export, and index generation) out of `@gencode/agents` into `@gencode/cli`, where all process-facing presentation/output already lives. This is a package-boundary cleanup only; `aimax export-html` keeps the same commands and options.

  Notable changes for integrators:

  - `@gencode/agents` no longer re-exports the export-html functions (`exportSessionTranscriptToHtml`, `exportTranscriptFileToHtml`, `exportTranscriptContentToHtml`, `exportAllSessionTranscriptsToHtml`, `exportTranscriptGlobToHtml`, `writeExportHtmlIndex`) or their option types (`ExportTranscriptHtmlOptions`, `BatchExportTranscriptHtmlResult`). If you imported these from `@gencode/agents`, they are now internal to `@gencode/cli`.
  - The session snapshot **domain** behavior stays in `@gencode/agents`: `persistSessionExportSnapshots` / `loadSessionExportSnapshots` / `serializeToolsForSnapshot` and the `system-prompt.txt` / `session-tools.json` write timing are unchanged.
  - Exported HTML pages now load `marked` and `highlight.js` from a CDN at view time (jsDelivr) instead of bundling vendored copies inside the package. The pages remain self-contained for session data; viewing requires network access the first time the libraries are fetched (after which the browser cache serves them).

- 75731b8: AIMax now supports loading and running pi-coding-agent extensions via the built-in `PiExtensionHost`. Extensions written for pi (factory-style `export default function(pi)` modules) can be loaded from any directory by adding paths to `plugins.load.paths` in the configuration.

  **What users get:**

  - 9 new hooks aligned with the pi extension event model: `tool_result`, `turn_start`, `turn_end`, `agent_start`, `before_agent_start`, `input`, `resources_discover`, `context`, and `before_provider_request`.
  - Extensions can register tools, flags, and slash commands that appear alongside AIMax built-in commands.
  - Tool interception now uses agent-core's built-in hooks (`beforeToolCall` / `afterToolCall`) as the single authority, eliminating double-dispatch between AIMax wrapper and pi interceptors.
  - `getFlag(name)` allows extensions to query runtime flags at runtime, with fallback to the plugin's `config` entry in `plugins.json`.
  - `ctx.ui.setStatus(text)` is available for extensions that need to display status information; it is surfaced through the CLI progress diagnostics channel.
  - Container-friendly cold-start: call `preloadExtensions(["/path/to/extensions"])` before starting the server to pre-compile extensions, so the first user request sees zero loading delay.
  - `pi.exec` for subprocess execution; `ctx.sessionManager` read-only transcript adapter; `ui.select` / `ui.confirm` with optional `dialogBridge`; `ctx.hasUI` when a dialog bridge is present; `session_before_switch` / `session_before_fork` session guard hooks.

  **Configuration:**

  - Add extension paths via `plugins.load.paths` in `~/.aimax/plugins.json` or workspace-level `.aimax/plugins.json`.
  - Pre-compile large extensions (for example pi-lens) with `tsc` in your Docker image; the loader automatically prefers compiled `.js` over `.ts` source for faster cold starts (2.2s vs 6.6s).
  - Use `preloadExtensions()` in your container entrypoint to warm the extension cache before accepting requests.

  **pi-agent-core upgrade:**
  The underlying agent runtime has been upgraded from `@mariozechner/pi-agent-core@0.55.3` to `@earendil-works/pi-agent-core@0.78.0`, and `@mariozechner/pi-ai@0.55.3` to `@earendil-works/pi-ai@0.78.0`. This includes:

  - Async `Agent.subscribe()` with `AbortSignal` support.
  - Parallel tool execution by default (can be set to sequential via `toolExecution: "sequential"` if needed).
  - `AgentState.errorMessage` replaces the mutable `error` field.
  - Node.js 22.19+ is now required.

### Patch Changes

- d5d9531: Add `onLog` callback to `runAgent` for intercepting agent log output. When set, logs are routed to the callback instead of `process.stderr`; file logging via log4js is unaffected. The callback is bound to the async context via `AsyncLocalStorage`, so all internal modules (including plugin loggers) are covered.
- 75731b8: `aimax run` and `aimax resume` now accept an explicit thinking/reasoning level via `--thinking <level>` (`minimal`, `low`, `medium`, `high`, `xhigh`) or the `AIMAX_THINKING` environment variable (CLI flag takes precedence). When set, AIMax enables thinking for compatible OpenAI-style models such as GLM-5.1 by sending `thinking: { type: "enabled" }` and `reasoning_effort` in the request payload. When omitted, existing provider defaults are unchanged (for example DeepSeek behavior is preserved; GLM is not auto-enabled by model name alone).
- 75731b8: Improves `/goal` first-turn execution guidance. During the initial clarify workflow, plain `exec` remains blocked, but the error now directs command work to `goal_record_exec`, which executes bounded commands and records workflow evidence. Goal steering also tells agents to use `goal_record_exec` by default for command execution inside goal workflows, reducing blocked `exec` retries while preserving evidence tracking.
- 75731b8: `/goal` 在首轮执行时现在会加载当前 workflow context：当自然语言目标先进入 `clarify plan and acceptance` 阶段时，模型会先看到当前任务、验收项和 clarify 规则。该阶段首轮会阻止直接调用 `write_file`、`edit_file`、`apply_patch`、`exec` 等交付型工具，要求先通过 `goal_plan_update`、`goal_add_task` 或 `goal_task_done` 补齐任务计划后再继续执行，避免长目标被直接跳过规划阶段。
- 75731b8: Renames the `/goal` command-evidence tool from `goal_record_command` to `goal_record_exec` to better signal that it executes a bounded command and registers its result as goal evidence. Use `goal_record_exec` when command output should serve as acceptance evidence; it still returns a `command:<id>` evidenceRef and exitCode. Plain `exec` remains unregistered. This is a pre-launch rename with no alias.
- 75731b8: Improves `/goal` V2-lite self-healing when models misuse evidence refs or task start. Unregistered refs in `goal_task_done` / `goal_complete` now return a structured `repairPlan` suggesting `goal_record_note`, `goal_record_exec`, or `goal_record_snapshot`. Missing `source` on manual notes returns `retryWith` without writing the registry. `goal_task_start` is idempotent when the current task is already `doing`.
- 75731b8: Improves `/goal` V2-lite evidence guidance when completing tasks or goals. If a model passes an unregistered evidence reference such as a natural-language description or file path, the workflow now explains that evidence must first be registered with `goal_record_note`, `goal_record_exec`, or `goal_record_snapshot`, then retried with the returned `evidenceRef`. Workflow steering also clarifies that command output intended for acceptance evidence should use `goal_record_exec`; ordinary `exec` output is not registered in `goal/artifacts/registry.jsonl`.
- 75731b8: Goal workflow mutations in the same process/session are now serialized with a per-store lock and unique temporary files for atomic writes, preventing concurrent `goal_add_task` calls from corrupting `goal/state.json`. When `goal/state.json` is unreadable, tools return a structured `workflow_corrupt` error and `goal_repair_workflow_state` (confirm:true) can safely reinitialize from the saved objective without opening arbitrary writes under `.aimax`. The first-turn clarify gate stays active for corrupt workflows but always allows the repair tool, and `goal_add_task.kind` now accepts only `execution`.
- 75731b8: Improve compatibility for deprecated `after_tool_call` audit hooks. The hook remains a read-only notification, but now includes `durationMs`, reports `error` for failed tools when available, and also fires when a `before_tool_call` hook blocks a tool. Plugins that need to modify tool results should continue migrating to `tool_result`.
- 75731b8: Thread goals now use the V2-lite workflow layout for newly created goals. New goals are stored under the session `goal/` directory (`goal/goal.json`, `goal/objective.md`, `goal/events.jsonl`, `goal/state.json`, `goal/plan.md`, and `goal/artifacts/`) and legacy root-level goal files are not read or migrated.

  When users create or replace a goal, AIMax initializes a lightweight task plan with acceptance criteria. Goal workflow tools such as `goal_task_done`, `goal_task_blocked`, `goal_record_note`, `goal_record_exec`, `goal_record_snapshot`, and `goal_complete` now require registered evidence refs before tasks or goals can be marked complete. `get_goal` returns the workflow summary, `/goal get` shows workflow status/current task/blockers, and `update_goal(status="complete")` no longer bypasses the V2-lite evidence gate.

  Goal continuation now injects the current workflow task, acceptance criteria, blocked reason, and open questions from `goal/state.json` on each continuation turn, so resumed work follows the persisted workflow state instead of relying on conversation memory alone.

- 75731b8: 新增 `aimax export-html` 命令，可将 transcript.jsonl 导出为可在浏览器中查阅的独立 HTML。每次 `aimax run`（及 resume、summarize 等经 runAgent 的入口）会在会话目录覆盖写入 `system-prompt.txt` 与 `session-tools.json`，记录该次运行 hook 之后的最终 system prompt 与工具列表；导出 HTML 时仅读取这两份快照并在页面展示 System Prompt 与 Available Tools（旧会话无快照则不显示）。支持单文件、`-d -s`、`-d --all --output-dir` 与 `--glob` 批量导出；批量模式默认生成 `index.html` 索引页。
- Updated dependencies [75731b8]
  - @gencode/shared@0.2.2

## 0.10.14

### Patch Changes

- 1c947fd: Smart topic segmentation now degrades to the normal history path when its optional local embedding or topic-selection path throws at runtime. `aimax run` and `aimax resume` continue the request with the existing session history instead of failing with errors such as `undefined is not an object (evaluating 'config.embeddingModelDir')`; deployments without `models/Xenova/bge-small-zh-v1.5/` still keep the documented non-embedding fallback behavior.

## 0.10.13

### Patch Changes

- 37b2031: Fix session creation when `aimax run --session-id <id>` is called for a new session whose directory already exists because run logs were initialized first. AIMax now treats `session.json` as the session metadata contract, so sessions with pre-created `logs/<messageId>/` directories still get a proper `session.json` written under `<dataDir>/.aimax/<sessionStore>/<sessionId>/`.

## 0.10.12

### Patch Changes

- 471dfe9: Run logs are now stored next to the session transcript. For each `aimax run` or resume request, `app.log` and `errors.log` are written under `<dataDir>/.aimax/<sessionStore>/<sessionId>/logs/<messageId>/`, using `sessions` as the default store. This keeps per-message diagnostics, `transcript.jsonl`, and other session files together so operators can inspect or clean up a session from one directory.

## 0.10.11

### Patch Changes

- a8c7e9e: Improve AIMax CLI resilience when multiple containers run against the same NAS-mounted user data directory. If the process stdout or stderr stream reports a write failure while rendering progress output, the CLI now records a local diagnostic under `<dataDir>/.aimax/logs/<messageId>/app.log`, suppresses further writes to that failed stream, and continues the agent run so callback and websocket delivery can still complete. Runtime environments should still mount shared NAS storage with working lock and sync semantics, for example the deployment-required NFS v3 plus `sync` configuration rather than `nolock`.

## 0.10.10

### Patch Changes

- 275442d: Run logs are now isolated by message ID. When `aimax run`, `resume`, `cancel`, or `summarize` receives `--message-id <id>`, CLI and agent logs are written to `<dataDir>/.aimax/logs/<id>/app.log` and `<dataDir>/.aimax/logs/<id>/errors.log` instead of the shared `<dataDir>/.aimax/app.log` files. Runs without a message ID use `<dataDir>/.aimax/logs/no-message-<pid>/`, so parallel containers no longer share the same default log file.
- c102527: Plugin startup diagnostics now include per-plugin load duration. During `aimax run`, each enabled plugin's `plugin_loaded` progress diagnostic reports `details.durationMs`, while the existing `plugin_system_initialized.details.durationMs` continues to report total plugin system initialization time.

## 0.10.9

### Patch Changes

- 825ae82: 提升 exec 命令执行的稳定性，修复进程异常和卡死导致 agent 无法继续的问题

  - **命令不再因子进程异常而中断 agent**：子进程输出流发生底层错误（如管道断开 EPIPE）时，错误会被记录到命令输出而不再让整个进程崩溃。
  - **读取标准输入的命令不再卡死**：`cat`、交互式提示等会读取 stdin 的命令现在会立即收到 EOF 并正常结束，而不是一直等待直到超时。
  - **长命令默认自动转后台**：前台执行的命令默认最多等待 60 秒（可用 `yieldMs` 调整等待窗口），超过后返回 running 状态，再用 `process` 工具轮询，避免真正卡死的命令长时间阻塞。常见的安装、构建、测试命令一般能在该窗口内直接跑完。`timeout` 参数现在表示命令的最大总运行时长（默认 1800 秒），到时强制结束。
  - **批量长跑不再残留孤儿进程**：在 Linux/macOS 上，命令被超时或取消时会终止整个进程组，连同管道、`&&`、后台任务派生的子进程一并清理，避免长时间批量执行累积僵尸/孤儿进程耗尽系统资源。
  - **进程级兜底保护**：CLI 入口新增未捕获异常和未处理 Promise 拒绝的兜底处理，发生此类故障时会先记录诊断日志并刷新日志文件，再以退出码 1 受控退出，便于外层容器或调度器干净地重启单次任务。
  - **后台进程随任务结束自动清理**：任务执行期间通过 `background:true` 启动的进程（如 dev server）若在任务结束时仍未停止，会被自动终止（连同其进程组），不会残留到任务之外。工具说明也更新了长驻进程的正确用法：用 `background:true` 启动、用一条会自行结束的命令探测就绪、用完再 `process` kill，而不是用 poll 等它结束。

## 0.10.8

### Patch Changes

- 1a98921: Context-limit errors now fail normally instead of triggering automatic emergency compaction during the same `aimax run`. Operators will no longer receive emergency compaction progress events over stdout, callback, or websocket when a provider reports the prompt is too large; use `/compact`, reduce tool output, or start a new session before retrying long conversations.

## 0.10.7

### Patch Changes

- ffd2a26: AIMax now records richer diagnostics when an LLM stream or run is terminated. Agent logs include the provider error source, retry metadata, AbortSignal state, stream chunk count, model/provider/api, and flattened error/cause fields such as `streamErrorName`, `streamErrorMessage`, `streamErrorCode`, and `streamErrorCauseCode`. The CLI also logs SIGTERM/SIGINT with uptime, channel, user, messageId, and active/final session IDs so operators can distinguish external container cancellation from upstream model gateway failures.

## 0.10.6

### Patch Changes

- Republish the latest topic segmentation diagnostics release with npm package metadata that resolves internal AIMax workspace dependencies to published package versions. This fixes installs from npm for `@gencode/agents`, `@gencode/cli`, `@gencode/plugin-sdk`, `@gencode/console`, and `@gencode/web` by ensuring registry packages depend on concrete `@gencode/*` versions instead of workspace-only dependency specifiers.

## 0.10.5

### Patch Changes

- 92be501: Topic segmentation diagnostics now include the first 50 characters of each dropped turn's user and assistant messages in both the local diagnostics log and the session `topic-segmentation-log.jsonl` audit file. Operators can map a dropped topic turn back to the original conversation more easily when investigating why history was omitted from a run.

## 0.10.4

### Patch Changes

- 189ba29: Model request previews are no longer emitted as callback or websocket progress events. `aimax run` now records the preview payload through internal diagnostics only, keeping callback/websocket streams reserved for formal task notifications while still leaving request-shape details available in `<dataDir>/.aimax/app.log` for troubleshooting.
- bf0a359: Transient LLM failures whose messages include a retryable provider status, such as `LLMRequestError: ... (BadRequestError 502)`, now enter the existing automatic turn retry policy even when the upstream SDK labels the provider type as `BadRequestError`. This keeps `aimax run` retry behavior aligned with the actual provider status code while preserving immediate failure for non-retryable statuses such as 400 or 404.
- Updated dependencies [189ba29]
  - @gencode/shared@0.2.1

## 0.10.3

### Patch Changes

- 7464e61: Tool progress now reports `tool_start` as soon as a model-planned tool begins execution, instead of waiting until the tool finishes. Operators consuming stdout, HTTP callback, or websocket progress can see long-running `exec` commands enter the running state immediately, while `tool_end` continues to report completion and output when the tool returns.
- ddbc7bb: Callback progress no longer reports session transcript persistence as `memory_changed`. AIMax still records transcript append/rewrite activity as diagnostic output for debugging and keeps memory indexing hooks active, but callback consumers now only receive `memory_changed` for actual memory provider or memory file changes such as `.aimax/MEMORY.md` and `.aimax/memory/*.md` updates.
- 31c69cf: AIMax now records diagnostic entries before and after each completed model-planned tool call. Operators can inspect `.aimax/app.log` to see the tool call id, tool name, full tool arguments, completion status, and tool output alongside the normal tool start/end progress. Diagnostic entries remain local runtime logs and are not forwarded as callback progress events.
- 749c489: Smart topic segmentation now writes detailed local diagnostics for the embedding retrieval path into `<dataDir>/.aimax/app.log` and failures into `<dataDir>/.aimax/errors.log`. The logs show whether `aimax run` passed an embedding model directory, which local model path was used, whether segment sidecar and `topic-segments.sqlite` sync ran, whether `sqlite-vec` was available, and why embedding retrieval degraded when the local `models/Xenova/bge-small-zh-v1.5/` files are missing or unreadable.

## 0.10.2

### Patch Changes

- 93a0318: Agent system prompts now tell the model to place temporary and intermediate files under the workspace cleanup directories: `workspace/temp/daily/`, `workspace/temp/weekly/`, or `workspace/temp/monthly/`. These directories are created only when needed; AIMax does not pre-initialize them during startup.

## 0.10.1

### Patch Changes

- faaebd5: Agent runs no longer stop after a built-in default timeout. Runs started without `timeoutMs`, including subagent runs launched through `subagent_spawn` or `batch_subagent_spawn`, can continue until they finish or are cancelled by an external abort. Use `aimax run --timeout <ms>` or pass `timeoutMs` directly when a specific execution limit is required.
- 798bf31: Adds Windows platform support for process execution and improves debugging visibility. The `exec` and `process` tools now handle Windows-specific shell invocation and process tree management, enabling reliable execution on Windows systems. Additionally, command execution details are logged for better debugging and troubleshooting. These changes improve cross-platform compatibility and operational visibility without affecting existing CLI behavior.

## 0.10.0

### Minor Changes

- c0def9b: `runAgent` now accepts an optional `env` field on `AgentRunParams` for passing session-scoped environment variables that are isolated to the current run. When supplied, the map is merged into the environment of every child process spawned by the built-in `exec` and `process` tools, and is also exposed to plugin scripts through the read-only `api.runtime.session.env` accessor (carried in the plugin runtime context under `env`). When a single `exec` call also passes its own `env`, the merge order is `process.env` < run-level `env` < per-call `env`, so per-call values override the run-level ones. The map is held in memory only for the duration of the run; it is never written to disk and never crosses a session boundary. The `subagent_spawn` and `batch_subagent_spawn` tools now also forward `env` to child runs through the standard `InheritedRunParams` plumbing, so subagent sessions inherit the same session-scoped env without any extra configuration. Downstream entry points that pass `AgentRunParams` through to the runner (`@gencode/cli`, `@gencode/plugin-sdk`, `@gencode/console`, `@gencode/web`) need to be re-released to expose the new field; no other call-site changes are required.

  The `aimax run` command now accepts a new `--env <kvlist>` flag for setting session-scoped env vars from the command line. The value is a comma-separated list of `KEY=VALUE` pairs (e.g. `--env TENANT=acme,TOKEN=secret`); backslash-escape `,` and `=` inside values if you need literal ones, and use `KEY=` to pass an empty string. The parsed map is forwarded as `AgentRunParams.env`, so the merge order, plugin visibility, and subagent inheritance described above all apply to CLI runs as well. The start banner shows only the number of keys injected — values are never printed.

### Patch Changes

- 364c7d9: Improves long-session context compaction stability. Session memory, automatic compaction, manual `/compact`, and context-limit recovery now build summarisation requests from bounded context views, so large historical turns are truncated or omitted before the summariser call instead of being sent as an oversized request. Default CLI behavior is unchanged; the fix applies automatically when continuing long sessions with the configured `--context-window` or `AIMAX_CONTEXT_WINDOW`.
- 03c58de: Agent runs are now resilient to progress delivery failures that happen immediately after an `exec` tool finishes. If stdout rendering, callback delivery, or websocket progress handling fails while reporting a tool result, `aimax run` logs the progress failure and continues the agent run instead of treating the reporting failure as a fatal task error. Tool result progress output is also normalized to text before rendering, so unusual or empty tool result payloads no longer crash the CLI output path.
- bcbb53f: Smart topic segmentation can now load its local embedding model from the installed CLI package. Set `AIMAX_EMBEDDING_MODEL_URL` during `@gencode/cli` installation to have the CLI `postinstall` download the model archive into `models/Xenova/bge-small-zh-v1.5/`; leave it unset to skip the download with no network access or install failure. Deployments may also set `AIMAX_EMBEDDING_MODEL_SHA256` to verify the archive. At runtime, `aimax run` and `aimax resume` automatically pass the installed `models/` directory to agents, while missing models continue to degrade without remote model downloads.
- 379f84e: `AgentRunParams.projectDir` is now honored as the effective session workspace directory. When `aimax run` or `aimax resume` is started with `--project-dir <path>` (or the equivalent `projectDir` field passed through the plugin SDK, console, or web entry point), the agent operates directly on that directory instead of the default `<dataDir>/workspace` mount. When `projectDir` is empty or omitted, the previous `<dataDir>/workspace` layout is preserved unchanged. The `subagent_spawn` and `subagents` tools now also forward `projectDir` to child runs, so subagents started inside a `--project-dir` session share the same project workspace without any extra configuration. The new `resolveWorkspaceDir` helper in `@gencode/agents` is the single source of truth for this rule, used by the runner, the session lifecycle, and the tool factory.
- d0edcb7: LLM provider errors returned inside an HTTP 200 stream now surface the provider's readable message directly, without the internal `LLM upstream returned an error payload in a 200 stream` prefix. Transient failures that only expose the generic `LLMRequestError` marker are also retried by the existing turn retry policy, while structured provider status codes such as `502`, `500`, and `429` keep the same retry behavior and non-retryable errors such as `404` still fail immediately.

## 0.9.3

### Patch Changes

- 4a2a4f7: 修复使用 `apiFormat: "anthropic-messages"` 连接 Anthropic Messages API 或兼容网关时，部分网关只在完整 assistant 消息中返回最终文本、或返回格式正常但没有文本和工具调用的空响应，导致 agent 可能丢失最终回复或静默结束的问题。修复后系统会从完整 assistant 消息中补齐最终文本，并将真正的空响应识别为可重试错误交给既有重试逻辑处理，无需调整 API 配置。
- 833f2dc: 为 agent 运行的收尾阶段增加超时保护与降级策略，避免因单个步骤阻塞导致整个流程挂起：

  - **Session 标题生成**：增加 5 秒超时上限，超时或生成失败时自动降级为基于首条消息的本地标题，不再阻塞 session 结算流程。
  - **Agent 运行超时**：启用 agent run 的 10 分钟默认超时（可通过 `timeoutMs` 参数配置），超时后优雅中止并记录诊断日志，而非无限挂起。
  - **HTTP Callback 回调**：为 callback 事件投递增加 5 秒超时，超时或网络错误时仅记录日志，不再抛出异常导致进程崩溃。
  - **WebSocket 连接与关闭**：为 WebSocket 建连和关闭分别增加 5 秒超时保护，防止连接异常时事件发送流程阻塞。

## 0.9.2

### Patch Changes

- 修复使用 `apiFormat: "anthropic-messages"` 连接 Anthropic Messages API 或兼容网关时，部分网关只在完整 assistant 消息中返回最终文本、或返回格式正常但没有文本和工具调用的空响应，导致 agent 可能丢失最终回复或静默结束的问题。修复后系统会从完整 assistant 消息中补齐最终文本，并将真正的空响应识别为可重试错误交给既有重试逻辑处理，无需调整 API 配置。

## 0.9.1

### Patch Changes

- f7a9b2f: 修复使用 `apiFormat: "anthropic-messages"` 连接第三方 Anthropic 兼容 API 网关时，因 SSE 事件顺序不严格（缺少 `message_start` 或 `message_delta` 先于 `message_start` 到达）导致请求失败并报 `Unexpected event order, got message_delta before "message_start"` 的问题。修复后系统会自动修正事件流顺序，无需调整 API 网关配置。

## 0.9.0

### Minor Changes

- dd8966e: Add Anthropic Messages API format support for AIMax runs. Users can keep the existing OpenAI-compatible default or set `AIMAX_API_FORMAT=anthropic-messages` / `--api-format anthropic-messages` with an Anthropic-compatible base URL, API key, and model. Agent turns, subagents, history compaction, topic segmentation, title generation, plugin LLM access, CLI runs, CLI resume, summarize, and Console-spawned runs now inherit the selected API format.

### Patch Changes

- c2278fa: When the LLM returns a recognizable context-limit error (typically HTTP 400, including messages such as `请求上下文过大`), a single `aimax run` now automatically performs emergency history compaction and retries the current turn before exiting. Each turn allows one compaction plus one retry; each run allows up to two compactions shared by the main agent and subagents. If recovery succeeds, the run completes normally (`exit 0`) and active goals continue as before. If compaction is skipped or the retry still fails, the run exits with `exit 1` and an error message that notes emergency compaction was attempted and suggests `/compact` or reducing tool output. Non-context errors (for example invalid API keys) are not retried via this path.
- e84813b: add updateAagent
- d747bbd: Localize AIMax `/goal` user-facing guidance and status messages for Chinese-first users while keeping the `/goal`, `/goal pause`, `/goal resume`, `/goal clear`, and `--token-budget` command syntax unchanged. The empty-goal help now includes examples that show how to write both the objective and clear completion criteria together, so goal completion is guided by verifiable conditions such as test results and bug reproduction checks.
- 2f4d004: Topic segmentation now maintains Flash-generated conversation segments, stores segment embeddings in a session-level `topic-segments.sqlite` vector index, and uses a local `transformers.js` embedding model from the mounted `model/` directory to retrieve older relevant topics before final classification. Long IM-style sessions can now return to much older topics more reliably while still preserving the existing transcript files, fallback behavior, and CLI usage. Online Flash rerank and turn-supplement fallbacks now share an 8-second request budget; when that budget is exhausted, AIMax immediately returns the local retrieval result instead of waiting longer on remote model calls.

## 0.8.2

### Patch Changes

- 3af48ab: 主题拆分（topic segmentation）现在支持通过挂载文件注入自定义补充提示词。用户可在 `/aimax_pvc/topic_segmentation_prompt.md` 中写入额外的分类指令，系统在主题拆分 LLM 调用前会自动加载并拼接到 prompt 中。文件不存在时静默跳过，不影响现有行为。
- d5fa9a7: 智能主题切分现在会在运行日志中记录分类调用的诊断信息，包括使用的模型、LLM base URL、超时时间、候选轮次数、上下文规模、额外 prompt 长度以及失败时的错误码和降级原因，便于排查 `LLM request timed out` 等环境相关问题；密钥和完整用户消息不会写入日志。
- 169a502: remove bun sqlite redundant debug console logs

## 0.8.1

### Patch Changes

- d60a8fb: Enable smart topic segmentation by default for eligible chat runs, add disable switches for CLI and console executions, and tune classifier timeout handling for real OpenAI-compatible providers.

## 0.8.0

### Minor Changes

- 376f7a0: Add optional topic segmentation prefiltering for long IM-style session histories.

## 0.7.7

### Patch Changes

- 0323cd2: Increase the Snip Compact inline tool-result window from 8 to 16 recent results.

## 0.7.6

### Patch Changes

- 64ce9f9: Expose skill version and SKILL.md modification metadata in prompts and skill_load results so resumed sessions can reload stale skill instructions.

## 0.7.5

### Patch Changes

- cde919a: Remove bracketed status labels from user-visible subagent completion summaries.

## 0.7.4

### Patch Changes

- aaad130: Persist final model request failures to session transcripts after retry attempts are exhausted.

## 0.7.3

### Patch Changes

- 0e4d28c: Require matching @custom-agent mentions to delegate through subagent_spawn with the exact agent name.
- 402af3c: Refactor SQLite database adaptation logic to be compatible with both Bun and Node.js runtimes

## 0.7.2

### Patch Changes

- 46c7c4f: rollback better-sqlite3 to built-in node:sqlite module

## 0.7.1

### Patch Changes

- 2313e3f: remove redundant sqlite dependency and introduce wrapper

## 0.7.0

### Minor Changes

- ace4220: Add thread goal audit events, live goal status updates, and objective-change steering across the goal control flow.
- 7cd5fcc: Add persisted thread goals with CLI controls, automatic continuation, and goal status reporting across sessions.

### Patch Changes

- e1882f4: Retry 200-stream LLM payload errors when upstream 5xx details survive only in the error message text.
- 1df854a: Start work immediately after `/goal` activates or resumes a thread goal, while keeping non-executing goal commands short-circuited.
- 5422fc5: Add Bun runtime support to the requireNodeSqlite() function.
- cb8d8d7: - Dependency Migration : Added better-sqlite3@^12.10.0 and @types/better-sqlite3@^7.6.13 to dependencies, replacing the built-in node:sqlite module.
  - Database Interface Updates : Changed all database type references from DatabaseSync (node:sqlite) to Database (better-sqlite3) across:
  - manager.ts
  - memory-schema.ts
  - sqlite-vec.ts
  - memory.test.ts
  - SQLite Helper Refactor : Simplified sqlite.ts by removing Bun-specific SQLite handling ( bun:sqlite ) and creating a unified requireBetterSqlite() function.
  - Extension Loading : Removed explicit enableLoadExtension(true) call in sqlite-vec.ts as better-sqlite3 handles extension loading differently.
- Updated dependencies [ace4220]
- Updated dependencies [7cd5fcc]
  - @gencode/shared@0.2.0

## Unreleased

### Patch Changes

- Emit a WEB-channel-only `model_request` progress event before model invocation, including `systemPrompt`, tool definitions, and the full model request payload for console debugging.
- Export `buildOpenAICompletionsRequestParams()` from the OpenAI compat layer to reuse the real request-building path for debug previews.

## 0.6.2

### Patch Changes

- b739cce: Fix the published CLI bundle so `aimax -V` no longer fails with a duplicate ESM declaration error.

## 0.6.1

### Patch Changes

- 7d6e6c8: Replace CLI session encryption keys with gocryptfs-backed .aimax mounts while keeping the `--encrypt-sessions` switch.

## 0.6.0

### Minor Changes

- c0283fc: ### Auto-Skills Runtime and Review Workflow

  Added the learned auto-skills runtime and CLI controls.

  - Added `.aimax/auto-skills` storage support with `categories.json`, single-level category slugs, `SKILL.md` entrypoints, generated `metadata.json`, archived/active status handling, and `.reviews/run-log.jsonl` audit records for completed review-agent runs.
  - Added `AutoSkillsLoader` APIs to list categories, list active learned skills by category, search compact skill metadata, view a selected `SKILL.md`, and load bounded resource files inside an auto-skill directory.
  - Added manifest-based in-memory and prompt snapshot caching for auto-skill indexes, with cache invalidation after category, create, update, and archive writes.
  - Added main-agent read tools: `auto_skill_categories`, `auto_skill_list`, `auto_skill_search`, and `auto_skill_view`; these are hidden when `autoSkills.load.enabled` is false.
  - Added a system-prompt auto-skills section that routes the main agent from categories to list/view/search while preferring curated, user, and plugin skills when both apply.
  - Added the restricted `auto_skill_manage` tool for internal review-agent use only, supporting `create_category`, `create`, `update`, and `archive` actions with structured success/error payloads.
  - Added public/internal agent visibility, keeping `visibility: internal` definitions out of public custom-agent delegation and `subagent_spawn` selection while still allowing explicit internal orchestration to resolve them by name.
  - Added post-run auto-skill review lifecycle modes: `off`, `gate`, `dry_run`, and `write`, replacing legacy score thresholds with configurable scope-based gates for the full session, current run, and post-review window.
  - Added per-session auto-skill review state with `maxReviewsPerSession`, attempted/completed/failed timestamps, and a reviewed-transcript cursor so repeat reviews focus on newly accumulated work.
  - Added pre-gate skips for subagents, cron runs, run errors, HITL pauses, pending UI tools, gate misses, and sessions that already reached their review cap.
  - Added compact review packets with session/current-run/review-window ranges, stats, tool stats, loaded/viewed skills, failed tool summaries, active categories, review state, and evidence file locations.
  - Added the review-only `auto_skill_review_context_view` tool so the internal curator can read bounded review-window, current-run, recent-conversation, explicit transcript-range, or referenced tool-result evidence.
  - Added silent internal curator integration for dry-run and write review modes, including diagnostic timing events, sanitized tool-result diagnostics, sanitized write-tool arguments, durable-write summaries parsed from `auto_skill_manage` results, and completed/failed review run logs.
  - Added the named internal `auto-skill-reviewer` agent for review orchestration, applying its prompt, init prompt, model override, and tool restrictions to silent review turns; review runs now skip with diagnostics when that internal agent is not configured.
  - Added `--system-agents-dir` and `AIMAX_SYSTEM_AGENTS_DIR` controls for `run` and `resume`, including absolute-path validation, CLI-over-env precedence, start-log reporting, and propagation through direct runs, HITL resumes, UI tool resumes, and run-dispatched resume flows.
  - Added CLI controls for `run` and `resume`: `--auto-skills-load-enabled`, `--auto-skills-review-mode`, `AIMAX_AUTO_SKILLS_LOAD_ENABLED`, and `AIMAX_AUTO_SKILLS_REVIEW_MODE`, including validation, option-overrides-env precedence, and propagation through direct runs, resumed HITL runs, UI tool resumes, and run-dispatched resume flows; when these controls are unset, the agents layer defaults to `load.enabled=false` and `review.mode=write`.
  - Exported auto-skills loader helpers, review gate/state helpers, public types, and read-tool factories from the package entrypoints.

### Patch Changes

- 18e17e4: Relax Microcompact staleness handling so tool results stay inline for the last 48 hours and remain protected within the most recent three user turns.
- c39239c: Use AES-GCM session encryption with CLI-supplied key rotation support so session files no longer rely on reversible encoding alone.

## 0.5.0

### Minor Changes

- 970bf39: Subagent artifacts are now recorded in the agent session instead of a separate child session, with new `source` and `sessionId` fields on each operation to distinguish agent vs subagent provenance. CRON tasks no longer generate artifact records.
- Add `--max-tokens` support to the summarize command and allow agent runs to cap model output tokens.

### Patch Changes

- f799cc0: Restore custom agent delegation in prompts and subagent spawning, with stricter validation that only explicitly listed custom agent names may be selected.

## 0.4.0

### Minor Changes

- ff2729c: Add a batch_subagent_spawn tool that accepts multiple subagent tasks and runs them with a five-child concurrency limit.
- 80932da: Restrict subagent nesting depth from 3 to 2 and add depth-aware guardrails: system prompts now include a subagent constraint section discouraging deep nesting, and the subagent_spawn tool description warns subagents to prefer direct tool calls over spawning further subagents.

### Patch Changes

- 80932da: Fix sub-subagent session directories being placed at the sessions root instead of nested inside the parent subagent's directory. Added `parentDir` field to `SessionPathOptions` so the session layer can resolve child paths relative to the spawning session's absolute directory, correctly nesting subagents at any depth.
- f96b5fd: Record successful agent file write and edit operations in per-session artifacts.json files with tool metadata, operation names, move sources, timestamps, and bounded content previews.
- 7e0ecf4: Stop truncating agent log message previews by default so full task and message text is preserved in logs.

## 0.3.1

### Patch Changes

- 5661a10: Temporarily omit effective custom agents from agent prompts and the subagent spawn tool contract.
- Persist assistant transcript entries as soon as a blocking `subagent_spawn` assistant message is complete, while still appending the corresponding `tool_result` entries after the subagents settle.
- b4687b0: Report subagent runs that return runner errors as failed instead of completed.
- 4325f90: Store spawned subagent sessions under their parent session using the spawn tool call id as the child session id.

## 0.3.0

### Minor Changes

- c0e0240: Add local-first custom agent discovery and named subagent runtime policies for AIMax agent runs.
- 1c9ac08: Add project directory context for run and resume so callers can distinguish the current repository cwd from the workspace mount.

### Patch Changes

- eab7716: Add agents runtime file logging to the shared AIMax app and error logs, including request, model turn, subagent lifecycle, and finalization audit events. Normalize human-readable CLI and agents log timestamps to China local time.
- f059988: Wait for agent turn event processing to finish before finalizing runs, so transcript persistence and progress delivery cannot lag behind final callbacks.
- 43c3f8a: Retry transient LLM turn failures, including provider errors wrapped inside HTTP 200 streams, before failing an agent run.
- e4a07bd: Prefer Simplified Chinese in the default agent system prompt unless the user or task context requires another language.

## 0.2.4

### Patch Changes

- Stop returning the `[UI Tool] Waiting for user input:` fallback text when `aimax run` pauses for a UI tool; structured pending UI tool data remains the pause signal.

## 0.2.3

### Patch Changes

- 375ff6c: Clarify system prompt routing between `memory_write` (durable MEMORY.md) and `memory_log` (daily/session logs) to reduce duplicate writes across both surfaces.
- 375ff6c: Emit `appendRecent_route` and `appendRecent_fallback` `memory_changed` events for `memory_log`; log routing diagnostics to `<dataDir>/.aimax/app.log` via `dispatchDiagnostic` on CLI `run`.
- 375ff6c: Fix builtin `appendRecentToMemory` fallback to append to MEMORY.md directly without nesting through `appendToMemory` (avoids duplicate change events).
- 375ff6c: Add unit tests for plugin daily-log routing vs builtin MEMORY.md fallback.
- Preserve multiline input following `/skill` and direct skill slash commands.
- Stop returning the `[UI Tool] Waiting for user input:` fallback text when a UI tool pauses; structured `uiToolPending` data remains the pause signal.
- Repair memory index consistency:
  - Add Markdown file-scan fallback for stale or empty memory indexes.
  - Protect `MEMORY.md` from unsafe deletion via `memory_forget`.
  - Add post-mutation memory index sync and explicit rebuild status.
  - Return stable `path#heading` and `path#L<line>` entry IDs for memory search/list operations.
- Updated dependencies
  - @gencode/shared@0.1.1

## 0.2.2

### Patch Changes

- 8646035: Updated scene skill path from /scenes/<category>/<scene>/<item> to /aimax_pvc/scenes/<category>/<scene>/<item> in system prompt templates and corresponding tests. This aligns the skill loading path with the new PVC-mounted scenes directory structure.

## 0.2.1

### Patch Changes

- 5d8068e: Updated summarization prompt to preserve skill locations alongside names; added parseSkillLoadInfo() and parseSkillLoadPayload() functions to extract both name and path from skill_load results; updated buildSkillLoadSummaryHint() to include location info in folded content hints.

## 0.2.0

### Minor Changes

- Add CLI support for loading additional absolute skill directories and pass them through run and resume flows into the agent skill registry.

### Patch Changes

- 059d077: Expose completed subagent results in status polling and delay delivery marking until parent announce handling succeeds.

## 0.1.1

### Patch Changes

- 2908094: Preserve skill-loading correctness across context compaction by requiring explicit reloads when SKILL.md content is no longer visible.

## 0.1.0

### Minor Changes

- 6a154b5: Remove HEARTBEAT feature from @gencode/agents. Heartbeat is not applicable to the current architecture, so all related template, bootstrap file loading, system prompt section, and test references have been removed.
- 71b3e30: Add stable session metadata types to @gencode/shared, expand memory tool suite, and switch subagent spawn to synchronous result delivery.

  - @gencode/shared: export `SessionSummary` and `SessionMetadata` types for cross-package use
  - @gencode/agents: add memory_write, memory_log, memory_list, memory_forget, memory_update tools; improve memory tool descriptions and system prompt guidance; change subagent spawn from async acceptance to synchronous result return; suppress redundant assistant text after subagent completion
  - @gencode/cli: update memory tool test coverage to match new tools

### Patch Changes

- 8ef3f8f: Add `sessionExists` helper to check if a session directory exists, and use it in runner to correctly detect new sessions when the requested session ID does not exist on disk
- 839f628: Load preset system prompt from `/aimax/system_prompt.md` instead of hardcoding the identity line in builder
- 350b9d1: Add a publish-time changelog guard and include package changelogs in npm artifacts.
- a2149e3: Remove the Documentation section (`buildDocsSection`) from the agent system prompt and clean up the `docs` parameter from types, builder, runtime, and subagent tooling
- 5f15359: Rename tool `sessions_spawn` to `subagent_spawn` and strengthen description to explicitly require usage when user mentions subagent
- Updated dependencies [350b9d1]
- Updated dependencies [71b3e30]
  - @gencode/shared@0.1.0

## 0.0.54

### Patch Changes

- Establish the initial changelog baseline for the current published package version.
- Fix `subagent_spawn` transcript persistence so subagent completion is returned as the original tool result instead of adding extra assistant messages.
