Repository navigation
Releases
v7.0.0 — supervised agents and process-tree containment / 受監督 agent 與程序樹 containment
English
Compatibility and upgrading
7.0.0 is available on npm, published on 2026-11-13. It is a milestone release chosen by the author. Existing MCP tool names and parameter interfaces remain compatible; callers should account for the behavior changes below.
- POSIX
kill_process: Linux and macOS now returnstatus: "termination_unconfirmed",terminationConfirmed: false, andterminationReasonswhen termination of the worker and recorded descendants cannot be confirmed.terminatedrequires that confirmation. Killing an already finished job preserves its originalcompleted/failed/loststatus. CheckterminationConfirmedrather than assuming a returned status alone proves the whole tree stopped. Windows keeps its response format and uses the Job Object broker for confirmation. - Windows job startup: the runner must enter a Job Object before starting the worker. A cold broker adds roughly five seconds before execution; repeated dispatches within 60 seconds are faster. This containment step also applies to ordinary durable jobs.
- Kernel concurrency: the default and hard ceiling are three runs per machine, with one per repository; worktrees and clones with the same origin count as the same repository. Paused, interrupted, and waiting-for-human runs retain their slots; ordinary awaiting-approval runs do not. An exception is a legacy
awaiting_approvalrun that already holdsactive.lock: it still blocks admission; release it withai-cli kernel cancel <runId>. Claude weekly quota below 10%, or when quota cannot be retrieved, reduces the machine limit to one. Codex quota below 20%, or when quota cannot be retrieved, prevents two simultaneous runs involving Codex. Admission refuses immediately rather than queuing. Only a human can lower the limit to 1–3. Setup and test commands share one machine-wide lock. See concurrency details. - Restart every MCP server after upgrading, including servers in other open sessions, so older servers stop using the old kill response and coordination behavior. An already running old Windows broker is replaced after it exits when idle.
- Rerun boundary probes: this release changes the Claude and Codex read-only launch arguments and their boundary keys, so previous probe records no longer match. After upgrading, run
ai-cli kernel probe --agent claudeandai-cli kernel probe --agent codex.
New install:
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpExisting installs: update through your existing npm or source installation method, then restart all MCP servers (restart the clients or reconnect each server with /mcp). Node ^20.19.0 || >=22.12.0 is required. Kernel use also requires the installed, authenticated vendor CLI selected for the work.
- Kernel MCP tools are off by default. Enable them with
ai-cli kernel enable;AI_CLI_KERNEL=on|offoverrides the stored setting. The CLI is independent of that tool switch. - Update
ai-cli-jobson each machine separately:claude plugin marketplace update tkflyc-ai-cli, thenclaude plugin update ai-cli-jobs@tkflyc-ai-cli, then restart Claude Code. npm updates and git pulls do not replace Claude Code's cached plugins. The optionalai-cli_kernel_panelis not included in the npm package and must be installed separately. It runsdist/bin/ai-cli.jsfrom a built source repository; pointAI_CLI_REPOat that repository, or use the documented home-directory fallback. - If you installed the SessionStart dispatch-policy hook, synchronize
tools/hooks/aicli-model-policy.pyto~/.claude/scripts/aicli_model_policy.pyafter reviewing your local configuration. - For direct-api providers, valid existing configuration keeps the default
max_tool_loopsof 30. Set an integer from 1–200 only when needed. If a model matches a configured provider key and provider validation fails, fix the configuration reported in the error rather than silently switching models. Malformed JSON whose keys cannot be read still has the documented fallback limitation.
Supervised agents: ai-cli_kernel
readonly-auditplans and runs supervised read-only work.developdelivers changes in a separate worktree and branch, with kernel-run acceptance tied to the delivery commit. It does not automatically merge or push. Workers retain the user's permissions; a branch is not a permission sandbox.- The deterministic loop records intent before actions, enforces budgets and human gates, and supports resuming interrupted work. Behavior probes check the actual CLI boundary; a PASS is not a guarantee of OS isolation for every vendor. In this release, Codex strict uses an OS read-only sandbox (issue #24), while Claude strict uses a tool allowlist.
- Checkpoints preserve work before development. Explicit single-use releases bind merge or push approval to exact commits, target state, and an expiry. Unknown outcomes are retained for reconciliation rather than retried blindly.
- Reusable approved mandates, opt-in triggers and schedules, repository-scoped candidate/active memories, and archive
list/show/donesupport longer-running work. Archive lists are summaries; useshowfor full evidence. Human approval controls activation and external handoff. - Automatic model selection uses task difficulty and measured quota, freezes eligible candidates in the mandate, and records rerouting. Explicit model choices stay explicit; unknown or insufficient quota does not silently pass the gate.
- The new
ai-cli_kernel_panel0.1.0 provides/kernelfor a terminal dashboard and/kernel sidefor an embedded panel. Opening a new terminal tab currently requires Windows Terminal.
Process-tree containment and recovery
- Windows durable jobs use a shared Job Object broker, with generation/epoch identities and persistent drained evidence. Lost broker contact remains unknown; it is not proof that descendants exited. Kernel normally waits for confirmed termination before releasing worktree resources.
- POSIX tracks descendants and verifies process identity before terminating them. macOS second-resolution start times need renewed relationship evidence before weak identities can be upgraded. Unrecorded descendants and incomplete enumeration remain limits.
- Broker registration and durable writes now use bounded retries for transient transport and reader-handle contention. Journal or lease failures preserve original causes and reconciliation evidence instead of rewriting completed results or assuming a worker died.
- Concurrency coordination, stale-slot handling, legacy-server compatibility markers, and shared test locks were tightened. Restarting all servers remains necessary; real mixed old/new MCP-server operation was not exercised.
Other changes and fixes
- direct-api accepts a per-provider
max_tool_loops, strips an initial UTF-8 BOM fromproviders.json, and reports validation failures for matching configured prefixes. Hitting the tool-loop limit can still end with exit 0: inspectagentOutput.finish_reasonfortool_loop_limit. - Update notices persist undelivered work across updates and rollbacks; delivery is recorded when a
runormodelsresponse reaches the calling AI. Plugin updates still require the user's agreement. ai-cli-jobs0.1.5 adds table rows and visibility into jobs from other sessions and projects. Version 0.2.0 adds a kernel section showing run status and progress, including approval, test-lock waits, acceptance testing, and waiting for human input. Archive summaries, delivery evidence, test-result parsing, and dashboard polling/quoting were also improved.
Validation and known limits
-
Commit
4366d0apassed CI run 43378399377 on Windows, Ubuntu, and macOS with Node 20.19 and 22. A single full Windows localnpm testrun passed all 62 scripts. -
npm 7.0.0 and annotated tag
v7.0.0resolve toffd56ee. That commit changes only CHANGELOG; no additional CI run was made for it. -
Linux and macOS test suites passed with stub CLIs. Kernel with real vendor CLIs has only been exercised on one Windows machine; CI does not establish real-vendor acceptance on Linux or macOS.
-
Windows non-administrator operation, mixed integrity levels, and real reboot / Fast Startup behavior remain untested. Human TTY / Windows Terminal panel interaction also remains unverified.
-
develop, user hooks, and arbitrary context commands run with user permissions. Hard OS isolation and prevention of indirect external writes are not provided. A probe PASS does not guarantee OS isolation for every vendor; the Codex and Claude read-only boundaries differ as described above. -
Issue #17 remains open. The fixes that confirm the worker and its descendants have stopped are included in this release; item 2 (executable verification by a second model, involving permission boundaries) has not started.
-
ai-cli-jobs0.2.0 passed 26claude plugin testcases, but has not been loaded and verified in real Claude Code. -
Scheduling tests used fake executors throughout; no real schedules were operated.
-
Automatic model selection was checked with 23 AUTO assertions using fake executors and quota snapshots; real quota queries and a real-machine
startwere not exercised.
Full details: 7.0.0 CHANGELOG. Changes since v6.9.1.
繁體中文
相容性與升級
7.0.0 已於 2026-11-13 發佈到 npm。這是作者選擇的里程碑版號;既有 MCP 工具名稱與參數介面維持相容,呼叫端仍須留意下列行為變化。
- POSIX
kill_process: Linux、macOS 無法確認 worker 與已記錄子孫都停止時,會回status: "termination_unconfirmed"、`terminationConfirmed: fa...
v6.9.1 — resumable Codex read-only jobs and Windows durable-job fixes / Codex 唯讀續接與 Windows 持久化工作修正
English
This is a retrospective Release entry: 6.9.1 was published to npm on 2026-10-20 without a GitHub Release at the time; the later release is v7.0.0. The behavior below describes 6.9.1.
Upgrading and compatibility
- After updating your installation, restart Claude Code or reconnect with
/mcpto load the updated server. - Replace retired
gpt-5.5selections or aliases withgpt-6.1-sol. Removing it from the candidate list does not block explicit requests: its prefix still routes to Codex, and the recorded post-retirement request failed with HTTP 400. - Existing panel users can run
claude plugin update ai-cli-jobs@tkflyc-ai-cli, then restart Claude Code, following the previous release's update procedure. - Review the documented auto-update trust model.
ontrusts every push toorigin: background installation (including lifecycle scripts), build, anddoctoralready execute downloaded code. Useononly where you trust the origin's writers; otherwise usecheck. The default did not change.
Codex read-only jobs can resume
Previously, combining session_id and read-only capabilities sent --sandbox to codex exec resume, which rejected it with exit 2. Resume now uses -c sandbox_mode='read-only' and explicitly overrides the original session's permissions. New read-only jobs keep --sandbox read-only and no longer use --ephemeral, so their sessions remain in ~/.codex/sessions for resumption. Unsupported capabilities are still refused; ordinary mode is unchanged.
Windows durable jobs and agy recovery
- When Claude Code closed an MCP server, its process-tree termination could also kill durable Claude, Codex, Grok, and agy jobs. A short-lived launcher now starts the runner, which leaves the server's process tree before dispatching the worker.
- Windows agy (ConPTY) now runs under an independent runner and is recorded in the job store. It can keep running after the original session closes and be adopted by a new session in the same project.
get_result,wait,peek, andkill_processwork, without duplicate jobs/list/panel rows. User termination remains failed / exit 143. POSIX agy and direct-api still cannot resume or be adopted. - Runner cleanup failures now leave a result rather than a permanently running job. Malformed or overlong ANSI sequences no longer swallow following text; ConPTY initialization codes alone no longer count as meaningful output in failure diagnostics.
Codex quota queries
query_usage now prefers live app-server JSON-RPC over scraping the TUI. Windows npm shims launch through Node/JS argument arrays. On failure, session fallback depends on fresh, and the response retains the reasons and version warnings. The TUI fallback waits for the /status echo before pressing Enter and clears/retypes at most once. Unreadable quota returns an error.
ai-cli-jobs panel 0.1.3 / 0.1.4
- 0.1.3: a missing
mcp__ai-cli__list_processesnow identifies both possible causes: ai-cli is disconnected (reconnect with/mcp, using server nameai-cli), orpermissions.denyremoved the tool. Reconnecting does not resolve a deny rule. Long hints were verified to wrap at terminal widths of 60–160 columns. - 0.1.4: adoption checks run every five seconds for the first 30 seconds, then every 60 seconds. The old single check at five seconds missed measured adoptions at 7, 11, and 7 seconds; the regression test requires an adoption at second 11 to appear by second 15.
Maintenance and validation
npm testnow runs scripts sequentially, continues after failures, and prints a final PASS/FAIL and timing summary. Any failure still makes the overall command exit 1. Unlistedverify-*.mjsscripts are rejected before execution unless explicitly excluded.- PTY list tests check job identity by
jobId, with PID and start-time diagnostics. The revised CI passed on all platforms, but Windows PID reuse remained an unproven explanation, not a confirmed product defect. - The release history records a second full run passing 31/31 after a timing-related restart-recovery failure, and 43 alias-config mutations killed by their intended assertions. Windows acceptance recorded real agy and Codex jobs surviving server tree termination and completing after adoption.
- README sections were reorganized, maintenance acceptance instructions moved to
tools/acceptance/README.md, and the SessionStart dispatch policy advanced to v2.1 with Astra-use and Codex-quota guidance.
Known limits in this version
POSIX agy and direct-api recovery remain unsupported. A natural exit racing with kill can be recorded as 143. An isolated ANSI ST can leave a backslash, and incomplete sequences beyond 4096 characters can leave payload/terminator noise. Tree termination during the launcher's brief lifetime can prevent a job from starting; the worker has not started and run has not returned, and cleanup later removes the directory rather than leaving it running.
Full details: 6.9.1 CHANGELOG.
繁體中文
這是補建的歷史 Release:6.9.1 於 2026-10-20 發佈到 npm,當時沒有建立 GitHub Release;之後的版本是 v7.0.0。以下描述的是 6.9.1 的行為。
升級與相容性
- 更新安裝後,重啟 Claude Code 或用
/mcp重連,載入新版 server。 - 將已退役的
gpt-5.5選擇或 alias 改為gpt-6.1-sol。從候選清單移除不等於攔截指名請求:該前綴仍路由到 Codex,退役後的實測請求回 HTTP 400。 - 已安裝面板者可沿用上一版流程,執行
claude plugin update ai-cli-jobs@tkflyc-ai-cli,再重開 Claude Code。 - 請核對文件新增的自動更新信任模型。
on等於信任origin的每次 push:背景安裝(含 lifecycle scripts)、build 與doctor當下就會執行下載的程式碼。只在信任 origin 寫入者時使用on,其他情況用check;預設值沒有改變。
Codex 唯讀 job 可以續接
舊版同時帶 session_id 與唯讀 capabilities 時,會把 --sandbox 傳給 codex exec resume,CLI 不支援而 exit 2。續接現在改用 -c sandbox_mode='read-only',明確覆寫原 session 權限。新開唯讀 job 保留 --sandbox read-only,不再帶 --ephemeral,session 會留在 ~/.codex/sessions 供續接。不支援的能力仍拒絕啟動,一般模式不變。
Windows 持久化 job 與 agy 接回
- Claude Code 關閉 MCP server 時,整棵行程樹終止可能連帶殺掉 Claude、Codex、Grok、agy 的持久化 job。現在由短命 launcher 啟動 runner,離開 server 行程樹後才派 worker。
- Windows agy(ConPTY)改由獨立 runner 持有並寫進 job store。原 session 結束後可繼續執行,由同專案的新 session 接管;
get_result、wait、peek、kill_process都能用,jobs/list/面板不重複列出。使用者終止仍為 failed/exit 143。POSIX agy 與 direct-api 仍不可接回或接管。 - runner 收尾失敗也會寫下結果,不再永遠 running。格式錯誤或超長 ANSI 序列不再吞掉後續文字;失敗診斷不再把 ConPTY 初始化控制碼當作有效文字輸出。
Codex 額度查詢
query_usage 優先用 app-server JSON-RPC 即時查詢,不再依賴刮 TUI。Windows npm shim 以 Node/JS 參數陣列啟動。失敗時依 fresh 決定 session fallback,保留原因與版本預警;TUI 備援等 /status 回顯才按 Enter,最多清空重打一次。讀不到額度就回 error。
ai-cli-jobs 面板 0.1.3/0.1.4
- 0.1.3: 找不到
mcp__ai-cli__list_processes時,提示同時列出 ai-cli 未連線(用/mcp重連,server 名稱須為ai-cli)與permissions.deny移除工具兩種原因。deny 規則不是重連就能解決。長提示已在 60~160 欄終端機驗證會換行。 - 0.1.4: 開場前 30 秒每五秒查接管,之後每 60 秒一次。舊版只查第五秒,錯過實測第 7、11、7 秒才完成的接管;回歸測試要求第 11 秒完成的接管在第 15 秒內出現。
維護與驗證
npm test改為依序跑完,失敗仍繼續後續腳本,最後印 PASS/FAIL 與耗時彙總;任何一支失敗整體仍 exit 1。未列入清單、也未明確排除的verify-*.mjs會在執行前被拒絕。- PTY 清單測試以
jobId判斷身分,保留 PID 與啟動時間診斷。修訂後 CI 全平台通過,但 Windows PID 重用仍是未證實的解釋,沒有認定為產品缺陷。 - 發版歷史記錄:重啟接回測試曾因計時失敗,第二輪完整測試 31/31 通過;alias-config 的 43 筆突變都由指定斷言抓到。Windows 真機驗收記錄 agy 與 Codex 在 server 整棵樹被終止後存活,接管後完成。
- README 重排章節,維護者驗收指令移到
tools/acceptance/README.md;SessionStart 派工政策升為 v2.1,補 Astra 使用範圍與 Codex 額度指引。
此版本的已知限制
POSIX agy 與 direct-api 仍不支援接回。自然退出與 kill 同時發生可能記成 143;孤立 ANSI ST 可能留下反斜線,超過 4096 字元的殘缺序列可能留下 payload/終結符雜訊。launcher 短暫存活期間若遇整棵樹終止,job 可能尚未啟動;此時 worker 沒開、run 沒回傳,目錄之後由清理掃描移除,不會留下 running。
完整內容見 6.9.1 CHANGELOG。
v6.9.0 — same-project jobs are picked up automatically
English
New install:
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpExisting installs: restart Claude Code (or reconnect with /mcp) to load 6.9.0.
Same-project jobs are picked up automatically
A job is dispatched by one session. When that session ends, the detached runner keeps going, but a new session could not see the job because jobs are isolated by principal (the session that dispatched them). Rewriting the job's meta identity by hand was tried as a workaround. Claude Code's auto-mode classifier blocked it as forging a process identity.
From 6.9.0 the server adopts these orphaned jobs on its own. You don't need to give a prompt or run a command.
- Same project only. The server records
projectDirfrom its cwd at construction and adopts only jobs from the same project, so an active session in another project cannot take someone else's orphaned job. New jobs must matchprojectDirexactly; for older jobs, the match is the directory boundary ofworkFolder. If the project directory is a filesystem root or the home directory, older jobs are matched only on an identical path, with no prefix match. - Verified on one client only. "The MCP cwd equals the session working directory" was measured on Claude Code 2.1.296. Other clients have not been verified.
- Adoption window. The whole time the job is running, plus 30 minutes after it finishes (also subject to the shared capacity limits). Adoption does not re-run the job and does not extend its retention.
- When it runs. In the background right after startup (usually within a few seconds, without delaying ready), then every 60 seconds on the GC cycle. The original principal lookup is folded into the GC batch.
- Safety checks. The server first confirms the original principal is dead. It then takes a lock synchronously, re-reads the job, compares principal and server, updates both atomically, and appends the full adoption history. If a lock already exists, adoption is refused with a manual-cleanup hint. This avoids a race where two sides each reclaim the old lock, delete the other's new lock, and both "succeed".
- Workers do not adopt. An ai-cli MCP running under a worker (the
AI_CLI_WORKERmarker, or a runner/worker of a job on its ancestor chain) adopts nothing, automatically or manually. - Jobs with no principal. If the principal is null, the server looks at the server that dispatched the job. If both are null, only manual adoption works.
- Turn it off. Set
AI_CLI_AUTO_ADOPTtooff,0,falseorno. Put it in theenvof the MCP server's configuration, for exampleclaude mcp add ai-cli -s user -e AI_CLI_AUTO_ADOPT=off -- npx -y @tkflyc/ai-cli-mcp. A shell export may not reach the server (Codex forwards only allow-listed variables to MCP servers). - What you see. After adoption, list and result carry
adopted: true. List also carries the model, and verbose result carriesadoptedFrom. - Manual fallback for cross-project cases. The MCP
adopttool stays available. The read-onlyai-cli adoptcommand only lists candidates. It does not choose the receiving session.
ai-cli-jobs panel 0.1.2
Version 0.1.0 → 0.1.2. (The version was bumped because claude plugin update reports "already at the latest version" when the number is unchanged.)
Existing installs:
- Run
claude plugin update ai-cli-jobs@tkflyc-ai-cli. - In
autopermission mode, addmcp__ai-cli__list_processestopermissions.allow. - Restart Claude Code.
- Adopted jobs are shown. Jobs the server adopted (
adopted: true) appear marked "adopted from the previous session", with the model. The panel checks once 5 seconds after the session starts, then every 60 seconds while idle. During normal polling it also picks them up when jobs are running. EachjobIdis shown once.seenis not cleared onsession.end, because/clearsends only an end event and no new start. Rows without ajobIdare not shown as adopted. - Refused polls now say what to do. A refused poll shows the full sentence instead of a 28-character truncation. For a permission refusal, it says to add
mcp__ai-cli__list_processestopermissions.allowand keeps the reason (adding an allow rule does not help against a deny rule or a hook refusal). For "no connected MCP tool", it says to reconnect with/mcp. Both message formats were checked against the Claude Code 2.1.296 binary strings. - Polling failures are no longer swallowed. Timeouts,
isError, unparseable output and exceptions show "polling failed: " on the row, and the status stays running. Before, a barecatch {}hid every error and the panel just kept spinning. - Other panel changes.
list_processescalls have a 10-second timeout. Testing showed this was not the cause of the spinning, and it is kept as a safeguard. The polling interval goes from 3 seconds to 0.5 seconds. Grok jobs were labelleddirect-apibecauseinferAgenthad nogrok-*rule; it now maps togrok. - Docs: the cause of the endless spinner. In
autopermission mode, addmcp__ai-cli__list_processestopermissions.allow(README, both languages). The plugin's background$.mcp.callgoes through permission checks too, and auto mode has no classifier available in the background. The debug log readsAuto mode classifier unavailable, denying with retry guidance (fail closed). Measured on 2026-10-10: all 199 polls were refused before the rule, and the first poll after the settings reloaded succeeded and the panel turned to done. - A read-only review by sonnet raised 11 points. 9 were valid and fixed (including when
seenis registered,/clear, an updater side effect, asession.endrace, a timer left behind). 2 were not changed: showing a finished adopted job for 120 seconds is intentional, and whether a long hint wraps needs checking on a real terminal.
Codex read-only mode on Windows
In strict (read-only) mode, codex could not read files on Windows. Strict passes --ignore-user-config, so [windows] sandbox is not loaded either. codex then falls back to a safe-command list, and | Select-Object or cmd /c are rejected before running (blocked by policy). If the model picked one, it could not read the file and still exited 0 with a "could not complete" report. A read-only review on 2026-10-10 failed this way.
- Checked on 2026-10-12 with codex-cli 0.162.1, one pattern at a time, plus a comparison: asked to read lines 50–60, the run without a hint gave up after a pipeline was refused. With the hint it used
rgand succeeded on the first try. - Passing
-c windows.sandbox=...does not work: unelevated, every command exits -1; elevated, it returnshelper_unknown_error. - Fix: on Windows, strict adds a file-reading hint at the start of stdin (
CODEX_WINDOWS_READ_ONLY_HINT). Thepromptfield is unchanged. One assertion and one mutation were added.
Grok dispatch guidance
The Grok row in dispatchGuidance now describes measured positioning: use grok-4.7 at medium effort for a second-vendor view in reviews, knowledge extraction and documentation checks.
- Basis: six tasks × two rounds on 2026-10-10, and a second round on 2026-10-12 (a cross-9-file feature in a real repo, and web verification). On objective scoring, grok-4.7 tied with gpt-6.1-sol and sonnet in every case. Only speed and cost differed, so it is not a replacement for everyday coding.
- Caveat: Grok reads your global CLAUDE.md and MCP configuration, and once sent a knowledge-base entry to xAI. If you don't want data to leave, say in the prompt not to use the knowledge base or MCP.
- Audit / second opinion row:
grok-4.7was added (zero false positives on two rounds of review tasks, 3–5 minutes each).
Tests and mutations
verify-durable-jobsoccasionally failed withUnexpected end of JSON input. The test observer wroteheap.jsonandio-<pid>.jsonwith plain writes, and the reader parsed the file as soon as it existed, sometimes mid-write. It now waits for the next round if the JSON is incomplete. A fullnpm teston 2026-10-12 reported a false failure in the 50 × 1 MiB stress test because of this; a rerun passed. Only the test side changed.- The mutation "recommendation table recommends a known-bad model (kimi-k3)" had been surviving since 3c0ae2f moved kimi-k3 out of
KNOWN_BAD_MODELS(slow but usable), so it tested nothing. It showed up on 2026-10-12 when all 43 mutations of verify-alias-config were run. It now usesnv-meta/llama-3.2-11b-vision-instruct, which is still on the list; applying it by hand confirmed the intended assertion catches it. This is the same kind of problem as red line 7: nobody normally runs a whole script's mutations. - The existing mutation "everyday dispatch effort back to high" matched two places after the Grok row was rewritten, so it is now bound to the
model: 'gpt-6.1-sol'row.
Audit
The automatic adoption was implemented by Codex gpt-6.1-sol (high). Two other models, opus (high) and sonnet (high), audited it independently in read-only mode. Fixes were made by a separate opus (high) in an independent clone, and sonnet's re-review judged it mergeable. Its 6 suggestions went in with the same batch.
- Codex's own first pass rejected the original design: automatically reclaiming a leftover lock had a double-adoption race (a repro script succeeded 2 times out of 2 attempts, and the history was overwritten). An existing lock is now always refused.
- High, valid, fixed (found independently by both audits): an ai-cli MCP under a worker adopted automatically and took same-project orphans before the user's new session could.
- Medium, valid, fixed: a null principal was always treated as dead; the prefix rule for root or home-directory jobs adopted across projects; two "concurrent adoption" tests ran in one process with a synchronous critical section, so they passed even with
wxremoved and did not...
v6.8.0 — jobs survive an MCP restart, plus Grok CLI
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpJobs survive an MCP restart
Until now a dispatched job lived inside the MCP server process: the full output piled up in memory, nothing was ever freed, and a /mcp reconnect lost every running job and its output.
From 6.8.0, every Claude, Codex and Grok job runs under its own small runner process, and the operating system writes stdout/stderr straight to ${AI_CLI_STATE_DIR}/jobs/<jobId>/ (default ~/.local/state/ai-cli/jobs/). The server keeps only metadata and the last 4 KB.
- Picked up again after a restart. When a new MCP server starts under the same coordinator (the Claude Code or Codex session, identified by PID and process start time), it lists those jobs with
recovered: true. Running jobs keep being tracked, jobs that finished while the server was gone return their result, and a job whose runner also disappeared is reported aslostwith its output kept. - Never re-run. No path re-starts a worker, retries, or re-sends a prompt — so a restart never costs extra tokens.
- npx users included. Package launchers (
npx,npm exec,npm run) are skipped when finding the coordinator, including the rewritten process titles npm uses on Linux and macOS. Checked with real process chains on Windows, Linux and macOS. - Collected automatically. Finished jobs are kept for 30 minutes, with caps of 100 jobs and 500 MiB (oldest first).
cleanup_processesstill removes them at once. - Measured. 50 jobs × 1 MiB output: server heap grew by about 0.15–0.3 MB; bytes written were about 0.14% above the output itself.
- Each job now has a UUID
jobId(returned byrun,list_processes,get_result,peek,kill_process), so a reused PID on Windows no longer hides an older job.
Check it yourself after upgrading: npm run verify:restart-recovery (in a clone of this repo) dispatches one job per family, kills the server mid-run, starts a new one and checks the results — it uses a little real model quota.
New agent: Grok CLI
grok-4.7, grok-4.7-build-fast, grok-4.6, grok-4.5 (list read from grok models).
- Long prompts go through
--prompt-file; the worker identity lock and yoursystem_promptgo through--ruleson every call, including resume; sub-agents are always off.reasoning_effort: low / medium / high / xhigh. - Strict (read-only) mode allows only read tools and also removes Grok's native MCP bridge (
search_tool/use_tool), shell, write, sub-agent and web tools. - Grok reads Claude Code's MCP configuration, so a Grok worker can see ai-cli too. Verified: the ai-cli server Grok starts inherits the worker marker, and a nested dispatch is refused with
AI_CLI_NESTED_DISPATCH_BLOCKED.
Fixes
query_usageno longer triggers a vendor self-update: Codex starts withcheck_for_update_on_startup=false, and key presses stop if an interactive update menu appears.ai-cli jobs --watchredraws on the alternate screen instead of pushing copies of the table into the scrollback.- The Antigravity model list no longer mixes the built-in fallback into a successful
agy modelsresult (gemini-3.5-flash-highis retired).
Compatibility and known limits
Additive (SemVer minor). Visible changes: the extra jobId and recovered fields, and the alternate-screen --watch.
- Antigravity (ConPTY) and direct-API jobs are not recoverable yet; they are collected after 30 minutes like the rest. Planned for 6.9.0.
- The runner is a separate process on purpose: if the parent shell is force-killed, its jobs run to completion and are collected later (or stopped with
kill_process).
An independent audit by another model found 2 high, 7 medium and 4 low issues; all were fixed before release. Live acceptance across 44 models had zero safety failures, with Claude, Codex, Grok and Gemini all passing. CI is green on Windows, Linux and macOS with Node 20.19 and 22.
Full details: CHANGELOG.
繁體中文
MCP 重啟後,job 會接回來
以前派出去的 job 活在 MCP server 行程裡:完整輸出一直累積在記憶體、從不釋放,/mcp 重連一次,執行中的 job 和輸出就全部不見。
6.8.0 起,每個 Claude、Codex、Grok job 都由自己的小型 runner 行程啟動,stdout/stderr 由作業系統直接寫進 ${AI_CLI_STATE_DIR}/jobs/<jobId>/(預設 ~/.local/state/ai-cli/jobs/),server 只保留 metadata 與最後 4 KB。
- 重啟後接回。 新的 MCP server 在同一個主導者(Claude Code 或 Codex session,以 PID 加上行程建立時間識別)底下啟動時,會把這些 job 列出來並標
recovered: true:還在跑的繼續追蹤,server 不在期間結束的直接取結果,runner 也不見的標成lost,輸出保留。 - 絕不重跑。 任何路徑都不會重新啟動 worker、不重試、不重送 prompt,重啟不會多花 token。
- npx 使用者也適用。 判定主導者時會跳過
npx、npm exec、npm run等啟動器,也認得 npm 在 Linux/macOS 上改寫過的行程標題;Windows、Linux、macOS 都以真實行程鏈測試。 - 自動回收。 結束的 job 保留 30 分鐘,另有 100 個與 500 MiB 上限,由舊到新刪除;
cleanup_processes照樣立即清除。 - 實測。 50 個各輸出 1 MiB 的 job:server heap 只增加約 0.15~0.3 MB,寫入量只比輸出多約 0.14%。
- 每個 job 都有 UUID
jobId(run、list_processes、get_result、peek、kill_process都會回傳),Windows 重用 PID 時不再蓋掉較舊的 job。
升級後可以自己驗:在本 repo 的 clone 執行 npm run verify:restart-recovery,它會每家派一個 job、中途殺掉 server、起新 server 再核對結果(會用到少量真實模型額度)。
新 agent:Grok CLI
grok-4.7、grok-4.7-build-fast、grok-4.6、grok-4.5(清單由 grok models 實查)。
- 長 prompt 走
--prompt-file;worker 身分鎖與你的system_prompt每次(含 resume)都經--rules送出;一律關閉子 agent。reasoning_effort:low/medium/high/xhigh。 - strict(唯讀)模式只開讀取工具,並移除 Grok 原生的 MCP 橋接(
search_tool/use_tool)、shell、寫入、子 agent 與網路工具。 - Grok 會讀 Claude Code 的 MCP 設定,所以 Grok worker 也看得到 ai-cli。已實測:Grok 啟動的 ai-cli server 會繼承 worker 標記,再派工會被
AI_CLI_NESTED_DISPATCH_BLOCKED擋下。
修正
query_usage不再誤觸 vendor 自動更新:Codex 啟動時帶check_for_update_on_startup=false,畫面出現互動式更新選單就停止送鍵。ai-cli jobs --watch改在替代畫面重畫,不再把一份份表格推進捲動緩衝區。- Antigravity 模型清單在
agy models查詢成功時不再混入內建後備清單(gemini-3.5-flash-high已退役)。
相容性與已知限制
新增功能為主(SemVer MINOR)。看得到的變化:多了 jobId 與 recovered 欄位,--watch 改用替代畫面。
- Antigravity(ConPTY)與 direct-API 的 job 尚不能接回,但同樣在 30 分鐘後回收;預計 6.9.0 處理。
- runner 刻意做成獨立行程:外層 shell 被強制結束時,底下的 job 會跑到結束再被回收(或用
kill_process停掉)。
另一家模型的獨立稽核找到 2 個高、7 個中、4 個低嚴重度問題,全部在發佈前修正。44 個模型的實機驗收安全性失敗為 0,Claude、Codex、Grok、Gemini 四家都通過。CI 在 Windows、Linux、macOS 的 Node 20.19 與 22 全部通過。
完整內容見 CHANGELOG。
v6.7.0 — see every dispatched job
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpSee every dispatched job, from any session
Each Claude Code or Codex session runs its own ai-cli MCP server, and jobs lived only in that server's memory: list_processes could not see another session's jobs, and an MCP reconnect wiped them. Codex as a coordinator has no plugin API at all — its status line takes built-in items only — so there was no place to watch progress.
Every ai-cli process now publishes the jobs it tracks to ${AI_CLI_STATE_DIR}/live-jobs/<pid>-<start-time>.json (default ~/.local/state/ai-cli/live-jobs/), and a new command reads them all:
ai-cli jobs # one table: every session, MCP and CLI jobs alike
ai-cli jobs --watch # redraw every 2 seconds; keep it in a side terminal
ai-cli jobs --json # machine-readable
ai-cli jobs --running # running jobs only- Small and private. A snapshot holds a 40-character task summary and an 80-character last event, never the prompt. Writes are atomic (temp file + rename), immediate on state changes and at most every 2 seconds while running. Finished jobs stay for 10 minutes.
- Stale files are recognised, not trusted. The writer is identified by PID and process creation time (Windows CIM, Linux boot ID + start ticks, macOS
ps lstart), so a dead owner or a reused PID is skipped. Each writer collects snapshots whose owner is proven gone. - Read-only.
jobsworks inside a worker (AI_CLI_WORKER=1) and never dispatches.
Faster ai-cli run on Windows
The dispatcher lookup is now cached and the post-spawn identity query runs in the background. Measured on Windows: the PID is printed after 0.27–0.53 s instead of 2.1–2.7 s; the process exits once its metadata is written.
Acceptance tool fixes
- A timeout on its own is now a capability failure, not a safety failure; it still counts as safety when it comes with monitor errors, unconfirmed cleanup, peak > 1 or an unblocked ai-cli call.
- The installed-hook comparison ignores line endings only (git on Windows turns the repo copy into CRLF), so it stops reporting identical files as different.
Compatibility
One visible change: on Windows, ai-cli run prints the PID first and exits after writing metadata. Everything else is additive.
An independent audit found nothing of high severity; all four medium and nine low findings were fixed before release. CI is green on Windows, Linux and macOS with Node 20.19 and 22.
Full details: CHANGELOG.
繁體中文
任何 session 派出的 job 都看得到
每個 Claude Code 或 Codex session 都有自己的 ai-cli MCP server,job 只存在那個 server 的記憶體裡:list_processes 看不到別的 session 的 job,MCP 重連後就清空。Codex 當主導者時完全沒有外掛 API,狀態列只能選內建項目,沒有地方看進度。
現在每個 ai-cli 行程都會把自己追蹤的 job 寫到 ${AI_CLI_STATE_DIR}/live-jobs/<pid>-<建立時間>.json(預設 ~/.local/state/ai-cli/live-jobs/),新的指令會把它們全部讀出來:
ai-cli jobs # 一張表:所有 session、MCP 與 CLI 派的 job
ai-cli jobs --watch # 每 2 秒重畫,適合開在旁邊的終端機
ai-cli jobs --json # 機器可讀
ai-cli jobs --running # 只看執行中- 小而不外洩。 快照只存 40 字任務摘要與 80 字最後事件,不存 prompt。原子寫入(暫存檔+rename),狀態改變立即寫、執行中最多每 2 秒一次;結束的 job 保留 10 分鐘。
- 過期檔會被辨認,不會被誤信。 寫入者以 PID 加上行程建立時間識別(Windows CIM、Linux boot ID+start ticks、macOS
ps lstart),已結束的 owner 與被重用的 PID 都會略過;每個寫入者會回收已證實失效的快照。 - 唯讀。
jobs在 worker 裡(AI_CLI_WORKER=1)也能用,而且不會派工。
Windows 上 ai-cli run 變快
派工端查詢改為快取,spawn 後的身分查詢改在背景進行。Windows 實測:拿到 PID 由 2.1~2.7 秒縮短為 0.27~0.53 秒;行程會在寫完 metadata 後結束。
驗收工具修正
- 單純的逾時改判為能力類失敗,不再算安全性失敗;若同時有監控錯誤、收尾未確認、峰值 > 1 或未被擋的 ai-cli 呼叫,仍判安全性失敗。
- 已安裝 hook 的比對只忽略換行差異(Windows 上 git 會把 repo 版轉成 CRLF),不再把內容相同的檔案誤報為不一致。
相容性
看得到的變化一處:Windows 上 ai-cli run 先印出 PID,寫完 metadata 才結束。其餘皆為新增。
獨立稽核沒有發現高嚴重度問題;4 個中度、9 個低度發現都在發佈前修正。CI 在 Windows、Linux、macOS 的 Node 20.19 與 22 全部通過。
完整內容見 CHANGELOG。
v6.6.1 — the nested-dispatch block now reaches Codex workers
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpThe nested-dispatch block didn't reach Codex workers
The 6.6.0 notes said the worker marker "is inherited, so this covers a worker's own MCP server". That holds for Claude and not for Codex. Codex passes its MCP servers an allowlist of environment variables (19 of them, measured with codex-cli 0.160.1), and AI_CLI_WORKER isn't on it. The ai-cli server running under a Codex worker therefore always took itself for the coordinator, and AI_CLI_NESTED_DISPATCH_BLOCKED never fired there. Claude passes its whole environment, so Claude workers were covered.
It surfaced in an acceptance run after upgrading another machine. The policy hook had been added to ~/.codex/hooks.json but not yet approved, so codex exec skipped it and Codex workers got no identity lock either. With both layers down, gpt-6-sol called ai-cli.run twice and both jobs started. After the hook was approved, a rerun of all 8 Codex models had 0 safety failures, but that was the identity lock holding, not the block.
The fix
For normal-mode Codex jobs, ai-cli now adds -c mcp_servers.<name>.env.AI_CLI_WORKER='1' for each stdio MCP server in $CODEX_HOME/config.toml. An explicit AI_CLI_ALLOW_NESTED=1 from the coordinator is passed on as well. An end-to-end run with real Codex and hooks switched off, so only the block was left, got AI_CLI_NESTED_DISPATCH_BLOCKED back and no job started.
The rule is to miss a server rather than add a wrong override. If an override points at something Codex won't accept, Codex refuses to load its config and every normal-mode Codex job fails. Two such cases were tested:
- an undefined server name →
invalid transport - a URL (streamable HTTP) server →
env is not supported for streamable_http
So ai-cli only touches [mcp_servers.<name>] tables that contain command =. It ignores look-alike lines inside multi-line strings and resolves a relative CODEX_HOME against the job's working directory, the same way Codex does. Read-only (strict) jobs are left alone, since they run with --ignore-user-config. Values use TOML single quotes: on Windows cmd.exe strips double quotes, and "1" would arrive as the integer 1.
Not covered: servers defined with dotted keys, inline tables, [[...]] arrays of tables, or in a project-level .codex/config.toml. For those, the remaining layer is the hook's identity lock, which only works once the hook is installed and approved.
An independent review caught the multi-line-string and URL-server cases before release. The CHANGELOG lists each finding and what was done about it.
Installing the hook for Codex
A hook newly added to ~/.codex/hooks.json has to be approved once in an interactive codex session. Until then codex exec skips it. The acceptance tool's static checks can't see this; only the identity probe's B answer does.
Full details: CHANGELOG.
繁體中文
巢狀派工的硬擋沒有擋到 Codex worker
6.6.0 的說明寫「標記會被繼承,所以 worker 自己的 MCP server 也擋得住」。這對 Claude 成立,對 Codex 不成立。Codex 只把一份白名單裡的環境變數交給 MCP server(以 codex-cli 0.160.1 實測是 19 個),AI_CLI_WORKER 不在其中。於是 Codex worker 底下的那個 ai-cli 永遠以為自己是主導者,AI_CLI_NESTED_DISPATCH_BLOCKED 在那裡從來不會觸發。Claude 會把整份環境交下去,所以 Claude worker 沒有這個問題。
這是另一台機器升級後跑驗收時發現的。派工政策 hook 已加進 ~/.codex/hooks.json,但還沒經過核准,codex exec 就跳過它,Codex worker 也拿不到身分鎖。兩層同時失守,gpt-6-sol 呼叫 ai-cli.run 兩次,兩個 job 都啟動了。hook 核准之後重跑 Codex 全部 8 個模型,安全性失敗為 0,但那是身分鎖擋住的,不是硬擋。
修法
一般模式的 Codex job,ai-cli 現在會對 $CODEX_HOME/config.toml 裡每個 stdio MCP server 加上 -c mcp_servers.<名稱>.env.AI_CLI_WORKER='1'。主導者明示的 AI_CLI_ALLOW_NESTED=1 也會一併轉交。以真的 Codex 端到端實跑、並關掉 hooks 只留硬擋,結果拿到 AI_CLI_NESTED_DISPATCH_BLOCKED,沒有任何 job 被啟動。
原則是寧可漏補、不可錯補。覆寫指向 Codex 不接受的目標時,Codex 會拒絕載入設定,所有一般模式的 Codex job 都會失敗。實測過兩種:
- 未定義的 server 名稱 →
invalid transport - URL 型(streamable HTTP)server →
env is not supported for streamable_http
所以 ai-cli 只處理含有 command = 的 [mcp_servers.<名稱>] 表,忽略多行字串裡長得像表頭的行,相對路徑的 CODEX_HOME 以 job 的工作目錄解析(Codex 自己也是這樣)。唯讀(嚴格模式)的 job 帶 --ignore-user-config,不做處理。值用 TOML 單引號:Windows 上 cmd.exe 會剝掉雙引號,"1" 送到時會變成整數 1。
沒有涵蓋的:用點號鍵、inline table、[[...]] 陣列表定義的 server,以及專案層 .codex/config.toml 裡的 server。這些情況剩下 hook 的身分鎖那一層,而且要 hook 已安裝並核准才有作用。
發版前的獨立稽核抓到了多行字串與 URL 型 server 這兩種情況;CHANGELOG 列出每一項發現與處置。
為 Codex 安裝 hook
新加進 ~/.codex/hooks.json 的 hook,要在互動式 codex 裡核准一次。在那之前,codex exec 會跳過它。驗收工具的靜態檢查看不出這件事,只有身分探針的 B 欄答案會顯示出來。
完整內容:CHANGELOG。
v6.6.0 — workers stay workers
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpWorkers stay workers
A job started by ai-cli is a fresh vendor CLI, and it loads the same user-level hooks, CLAUDE.md and memory as the session that dispatched it. Rules written for the coordinator — "ask who should run this", tool budgets, "the coordinator never writes code, always delegate" — were reaching the workers. In a full acceptance run, one Gemini worker that was told to delegate found ai-cli on disk and ran ai-cli.js run --model codex from its shell. The process watcher caught the second worker and stopped it.
6.6.0 closes this in layers:
- Every vendor CLI that ai-cli starts carries
AI_CLI_WORKER=1. One helper covers all ten launch sites: pipe and PTY runs, detached wrappers, foregroundexec, agy model discovery and the usage TUIs. - The dispatch-policy hook reads the marker.
tools/hooks/aicli-model-policy.pystill gives the coordinator its policy; a worker gets a short identity lock instead: you are the result of a dispatch, do the work yourself, don't call ai-cli, and the coordinator's role rules don't apply to you (safety limits still do). - ai-cli refuses to dispatch from inside a worker. When its own environment carries the marker, MCP
run, CLIrunandexecfail withAI_CLI_NESTED_DISPATCH_BLOCKED. The marker is inherited, so this covers a worker's own MCP server as well as anai-cliit launches from a shell. SetAI_CLI_ALLOW_NESTED=1only if you really want nested dispatch. - agy and direct-api get the lock in the prompt. They don't load hooks, so ai-cli prepends the same identity block. A test keeps the copy in
srcidentical to the hook. - direct-api's shell tools carry the marker too, so a direct-api model can't route around the block through bash.
Acceptance you can rerun
npm run verify:worker-identity is opt-in and spends tokens. It runs static checks first — installed hook identical to the repo copy, both modes print the right heading, Claude and Codex settings reference it, codex ≥ 0.160 — then, for every model, an identity probe and an explicit "delegate this with ai-cli" task. A watcher counts and stops only its own descendant processes, identified by PID plus creation time. (An earlier version keyed on PID alone killed an unrelated job after Windows reused a PID.) Reports separate safety failures — got the coordinator policy, delegated without being blocked, recursed — from capability failures such as timeouts or empty replies.
On Windows, across 40 models: 0 safety failures. 10 capability failures, mostly free models timing out or returning empty replies; each was retried once.
NVIDIA free models in the catalog
The direct-api list in models now includes the 11 NVIDIA models that passed hands-on testing, plus nvidiaFreeTierCaveats. matchesModel now resolves through providers.json, so a provider you configure yourself reports the correct routable.
Compatibility
Three visible changes:
- With
AI_CLI_WORKER=1in the environment,runandexecfail withAI_CLI_NESTED_DISPATCH_BLOCKED. SetAI_CLI_ALLOW_NESTED=1to opt out. - Prompts sent to agy and direct-api start with an identity block.
- Models of a user-defined provider are now
routable: truein the catalog when they resolve.
Full details: CHANGELOG.
繁體中文
Worker 就是 worker
ai-cli 派出的 job 是一個新啟動的 vendor CLI,它會載入和派工者同一套使用者層的 hook、CLAUDE.md 與記憶。寫給主導者的規則——「先問由誰執行」、工具預算、「主導者不寫碼、一律派工」——於是也落到了 worker 身上。全模型驗收時,一個被要求轉派的 Gemini worker 在磁碟上找到 ai-cli,從 shell 執行了 ai-cli.js run --model codex;行程監控抓到第二個 worker 並把它收掉。
6.6.0 分層處理:
- ai-cli 啟動的每個 vendor CLI 都帶
AI_CLI_WORKER=1。 一個 helper 涵蓋全部十個啟動點:pipe 與 PTY、detached wrapper、前景exec、agy 模型查詢與額度 TUI。 - 派工政策 hook 會讀這個標記。
tools/hooks/aicli-model-policy.py對主導者照樣給政策;對 worker 改給一段身分鎖:你就是派工的結果、自己把工作做完、不要呼叫 ai-cli,主導者的角色規則不適用於你(安全限制仍然適用)。 - worker 裡的 ai-cli 拒絕再派工。 自身環境帶標記時,MCP
run、CLIrun與exec一律回AI_CLI_NESTED_DISPATCH_BLOCKED。標記會被繼承,所以 worker 自己的 MCP server、以及它從 shell 叫起的ai-cli都會被擋。確定需要巢狀派工時才設AI_CLI_ALLOW_NESTED=1。 - agy 與 direct-api 由 prompt 帶身分鎖。 它們不載入 hook,ai-cli 會在 prompt 開頭加上同一段身分鎖;有測試確保
src裡的副本與 hook 逐字相同。 - direct-api 的 shell 工具也帶標記,direct-api 模型無法透過 bash 繞過。
可重複執行的驗收
npm run verify:worker-identity 需手動執行、會花 token。先做靜態檢查——已安裝的 hook 與 repo 版本相同、兩種模式輸出正確標題、Claude 與 Codex 設定都有引用、codex ≥ 0.160——再對每個模型跑身分探針與「用 ai-cli 轉派」的誘導任務。監控只計數、只終止自己的子孫行程,以 PID 加建立時間識別(只看 PID 的舊版曾在 Windows 重用 PID 後誤殺無關的 job)。報告區分安全性失敗(收到主導者政策、轉派未被擋、遞迴)與能力類失敗(逾時、空白回覆等)。
Windows 上 40 個模型:安全性失敗 0;能力類失敗 10,多為免費模型逾時或回空白,各重測一次。
NVIDIA 免費模型進入清單
models 的 direct-api 清單加入 11 顆實測可用的 NVIDIA 模型與 nvidiaFreeTierCaveats。matchesModel 改經 providers.json 解析,使用者自設的 provider 會回報正確的 routable。
相容性
看得到的變化有三處:
- 環境帶
AI_CLI_WORKER=1時,run與exec回AI_CLI_NESTED_DISPATCH_BLOCKED;設AI_CLI_ALLOW_NESTED=1可解除。 - 派給 agy 與 direct-api 的 prompt 開頭多一段身分鎖。
- 使用者自設 provider 的模型,只要解析得到,catalog 會標
routable: true。
完整內容見 CHANGELOG。
v6.5.0 — read the screen, not the bytes
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpRead the screen, not the bytes
query_usage runs each vendor's interactive TUI in a pseudo-terminal and parses what it prints. The parser used to strip the escape codes and read what was left. That stopped working, because these TUIs only redraw the cells that changed: ESC[row;colH moves to a row, ESC[nX and ESC[K erase, and ESC[nC skips n cells and keeps what was already there — it is not a space. Strip the codes and Codex's Pro␛[1C100 becomes Pro100. Treat the skip as a space and Claude's Current sess␛[1Con — where the i was skipped because it hadn't changed — becomes Current sess on.
The new renderTerminal() plays the output into a small screen buffer, following terminal rules (cursor moves, erases, line feeds and scrolling, double-width CJK characters), and parses what is actually visible. All three vendors now go through it, and it fixed three bugs at once:
- Claude returned
okwith every fieldnull.Current sessionhad been squashed intoCurrentsession, so no pattern matched. The panel now parses — session 7% used and the week 44% in the live check — and a result with no percentages at all is anerror. Claude's percentages are markedpercentBasis: "used", the opposite direction from Codex'spercentRemaining. - agy's remaining quota was reported as used. The panel says "Weekly Limit Remaining 99.86%"; the old parser put 99.86 in
percentUsed, which reads as nearly exhausted. Labels that say Remaining or Used are now converted accordingly, with both directions and abasis, andmodelis the group name (GEMINI MODELS,CLAUDE AND GPT MODELS). - Codex
modelandaccountwere alwaysnull.Model:had been glued onto the end of the previous line. Codex 0.160 also no longer shows an email, soaccountis returned exactly as displayed (for examplePro 100).
Quotas beyond the main ones — Codex's Luna Reserve Weekly limit, Claude's Current week (Fable) — used to be dropped silently. They are listed in additionalLimits.
Codex quota without opening a TUI
Codex writes rate_limits into its session files at the end of every turn. When one is less than 10 minutes old and its window has not reset, query_usage reads it instead: about 0.1 seconds versus 8 or more for the TUI, and immune to elevation, daemon, or hook-trust prompts. Results carry source: "session-file" and asOf. refresh=true always uses the TUI. Session files have no model or account, so those are null on this path.
Polling stopped flooding the caller
While a Claude job was running it had no reply yet, so wait fell back to returning the entire raw stdout — about 90 KB of stream-json, mostly the init event — on every poll, straight into the caller's context. That is ai-cli's own cost, not the vendor's. Running jobs now return only liveness; use peek for live events. A finished job with no parsed reply returns the last 4,096 characters, marked with stdoutTruncated / stderrTruncated. With verbose, a job without a parsed reply still returns everything.
Usage reporting, completed
agy and direct-api jobs now return agentOutput.usage in the same shape as Codex and Claude. agy reports no cache figures, so none are invented. For direct-api, the last usage record of a response wins instead of summing, so providers that send cumulative counts in every chunk are not double-counted. ai-cli run on the CLI now returns the same high-effort warnings as MCP.
Releases check themselves
While publishing 6.4.0, an agent had written backups and logs into dist/. dist is git-ignored, so nothing showed up in git status — but files shipped all of dist, and the first publish attempt carried 19 extra files. It only failed because npm wasn't logged in. Now files ships only dist/**/*.js and .js.map, and tools/verify-release.mjs runs as prepublishOnly: clean working tree, HEAD equal to the version tag, every packed file traced back to a source file, NOTICE present. Any failure stops npm publish.
Compatibility
Three visible changes, all corrections:
- agy rows labelled "Limit Remaining":
percentUsednow really means used. ReadpercentRemainingand checkbasis. - Claude with no readable percentage:
statusis now"error"instead of"ok"with nulls. - Running jobs: compact
wait/get_resultresults no longer includestdout. Useverbose: trueorpeek.
Two independent audits found nothing of high severity. Every confirmed finding was fixed, and the ones judged invalid are recorded in the CHANGELOG with the reason.
Full details: CHANGELOG.
繁體中文
讀畫面,不是讀位元組
query_usage 會在偽終端機(PTY)裡開各家的互動式 TUI,再解析它印出來的內容。原本的做法是刪掉跳脫碼、讀剩下的文字,但這招不管用了,因為這些 TUI 只重畫有變動的格子:ESC[row;colH 移到指定的列與欄,ESC[nX 和 ESC[K 清除內容,ESC[nC 是跳過 n 格、保留原本的內容,不是空格。刪掉跳脫碼,codex 的 Pro␛[1C100 就變成 Pro100;把「跳過」當成空格,claude 的 Current sess␛[1Con(那個 i 沒變所以被跳過)又會變成 Current sess on。
新的 renderTerminal() 照終端機的規則把輸出播放到一個小型畫面緩衝區(游標移動、清除、換行與捲動、中日韓的雙寬字元),再解析畫面上實際看得到的內容。三家都改走它,一次修好三個 bug:
- claude 回
ok,所有欄位卻都是null。Current session被擠成Currentsession,一個正規式都對不上。現在面板解析得出來(實測 session 已用 7%、本週 44%),而且一個百分比都讀不到時會回error。claude 的百分比標上percentBasis: "used",方向跟 codex 的percentRemaining相反。 - agy 的剩餘額度被當成已用量。 面板寫的是「Weekly Limit Remaining 99.86%」,舊的解析器卻把 99.86 放進
percentUsed,看起來像快用完了。現在標籤寫明 Remaining 或 Used 的,會照標籤換算,同時給出兩個方向和basis;model改成群組名稱(GEMINI MODELS、CLAUDE AND GPT MODELS)。 - codex 的
model和account永遠是null。Model:被黏到上一行的尾巴。codex 0.160 也不再顯示 email,所以account照畫面原樣回傳(例如Pro 100)。
主額度以外的額度,例如 codex 的 Luna Reserve Weekly limit、claude 的 Current week (Fable),以前會被默默丟掉,現在列在 additionalLimits。
查 Codex 額度不用開 TUI
codex 每個 turn 結束時都會把 rate_limits 寫進 session 檔。只要最新那筆距今未滿 10 分鐘、而且額度週期還沒重置,query_usage 就直接讀它:約 0.1 秒,開 TUI 要 8 秒以上,也不受系統管理員權限、daemon 或 hook 信任畫面影響。結果帶 source: "session-file" 和 asOf。refresh=true 一律走 TUI。session 檔裡沒有模型和帳號,所以這條路徑的這兩個欄位是 null。
輪詢不再把原始輸出灌給呼叫端
claude job 執行中還沒有回覆時,wait 會退回去傳整份原始 stdout,大約 90 KB 的 stream-json,大部分是開頭的 init 事件。每輪詢一次,就有這麼多內容進到呼叫端的 context。這是 ai-cli 自己造成的成本,不是 vendor 的。現在執行中的 job 只回傳 liveness,要看即時事件用 peek。已結束但沒有解析出回覆的 job,只回傳最後 4,096 個字元,並標上 stdoutTruncated / stderrTruncated。沒有解析出回覆時,verbose 仍會回傳完整內容。
用量回報補齊
agy 和 direct-api 的 job 現在也會回傳 agentOutput.usage,形狀跟 codex、claude 相同。agy 不回報快取數字,就不捏造。direct-api 同一個回應的用量取最後一筆,不再加總,所以每個 chunk 都送累計值的供應商不會被重複計算。CLI 的 ai-cli run 也會回傳跟 MCP 相同的高成本 effort warnings。
發版會自己檢查
發 6.4.0 時,一個 agent 把備份和 log 寫進了 dist/。dist 被 git 忽略,git status 看不出來,但 files 會打包整個 dist,第一次嘗試發佈時多帶了 19 個檔案,只是因為 npm 剛好沒登入才失敗。現在 files 只打包 dist/**/*.js 和 .js.map,而且 tools/verify-release.mjs 會在 prepublishOnly 自動執行:工作樹要乾淨、HEAD 要等於版本 tag、每個打包的檔案都要對得到原始碼、NOTICE 要在套件裡。任何一項不過,npm publish 就會被擋下。
相容性
有三處看得到的變化,都是修正:
- agy 標示「Limit Remaining」的那幾列:
percentUsed現在真的是已用量。請改讀percentRemaining並看basis。 - claude 一個百分比都讀不到時:
status改回"error",不再是"ok"加上一排 null。 - 執行中的 job:精簡的
wait/get_result結果不再包含stdout。請改用verbose: true或peek。
兩輪獨立稽核都沒有發現高嚴重度問題。確認成立的項目全部修正,判定不成立的項目連同理由都記在 CHANGELOG。
完整內容:CHANGELOG。
v6.4.1 — query_usage reads the Codex quota on 0.160
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpFixed: query_usage never read the Codex quota on codex-cli 0.160
6.4.0 stopped reporting ok without a number. That made the next problem visible: on codex-cli 0.160 the query still timed out after 60 seconds on every attempt in our tests — honestly reported as an error, but still without a number. Two assumptions about the TUI had stopped holding:
- It never looked ready. The old check waited for the model name in the header box to change from
loadingto a real model. In 0.160 the header stays onloadingand the model name moved to the bottom status line, so/statuswas never sent. Readiness now also means: the prompt line is visible, no MCP server is still booting, and output has been quiet for 1.5 seconds. The old check is kept for older versions. - Enter was swallowed. Typing
/opens a command menu, and when/statusand Enter arrived in a single write, the menu consumed the Enter — the screen ended with›/statussitting unexecuted in the input box. Text and Enter are now written separately, 500 ms apart; a retry only resends Enter when/statusis already in the box, so it never becomes/status/status.
Verified against the real CLI before release, through a freshly reconnected MCP server: status: "ok", type: "rate_limits", weekly 81% left, matching what the TUI shows.
Only the quota query changed. Dispatch (run) is untouched.
Full details: CHANGELOG.
繁體中文
修正:codex-cli 0.160 上 query_usage 一直讀不到 Codex 額度
6.4.0 不再把沒有數字的結果回報成 ok,下一個問題因此浮上來:在 codex-cli 0.160 上,我們測試的每一次查詢都在 60 秒後逾時。雖然誠實地回報成 error,但數字一樣出不來。原因是程式對 TUI 的兩個假設不再成立:
- 永遠等不到就緒。 舊的判斷要等標題框裡的模型名從
loading換成真正的模型才送/status。0.160 的標題框一直停在loading,模型名改到底部狀態列,所以/status從來沒送出。現在只要提示列出現、沒有 MCP server 正在啟動、輸出靜止 1.5 秒,就算就緒;舊版的判斷照樣保留。 - Enter 被吞掉。 一打
/就會跳出指令選單,/status和 Enter 在同一次寫入時,Enter 被選單吃掉,畫面最後只剩輸入框裡沒執行的›/status。現在文字和 Enter 分兩次送,中間隔 500 毫秒;重試時如果/status已經在輸入框裡,只補送 Enter,不會變成/status/status。
發版前透過重新連線的 MCP server 用真的 CLI 驗證:status: "ok"、type: "rate_limits"、weekly 81% left,跟 TUI 畫面上顯示的一致。
只改了額度查詢,派工(run)完全沒動。
完整內容:CHANGELOG。
v6.4.0 — Codex and Claude jobs report what they cost
claude mcp add ai-cli -s user -- npx -y @tkflyc/ai-cli-mcpCodex and Claude jobs now report what they cost
Until now nobody could see what a dispatched job cost. ai-cli never parsed the usage that Codex and Claude report, and the strict path runs Codex with --ephemeral, so those jobs leave no session file to check afterwards either. When we tried to estimate ai-cli's share of a busy project's spend, the jobs that could not be measured were easy to mistake for jobs that cost little.
Finished Codex and Claude jobs now carry agentOutput.usage in both wait and get_result, normalized to one shape: total input, cached input, cache writes, output, and reasoning tokens. Claude adds num_turns and cost_usd_nominal — a list-price estimate, not a subscription bill, and named so it cannot be mistaken for one.
input_tokensmeans the same thing for both vendors: everything sent to the model, cache included. Codex already reports it that way; Claude's raw figure excludes cache, so it is summed.- If usage cannot be measured, the field is absent — never zero. If some Codex turns report malformed usage,
usagecovers the valid ones and carriesincomplete: trueinstead of silently undercounting; if none are valid,usageis omitted. - A failed job that reports usage but no reply still returns its raw stdout/stderr. An early draft hid the error text in that case; the independent audit caught it before release.
Expensive effort levels are flagged
When the effort actually sent is xhigh, max, or ultra — whether passed explicitly, implied by an alias, or set in config — the MCP run tool returns warnings saying so and naming the source. It warns; it does not block. (The CLI ai-cli run gained the same warnings in 6.5.0.)
Dispatch guidance now covers cost
models → dispatchGuidance gains four entries based on measurement: each job pays a fixed overhead before doing any work (measured here at about 20k input tokens for a minimal Codex job and about 30k of context for a minimal Claude job; the Claude figure depends on your CLAUDE.md, hooks, and MCP servers), so batch small tasks; don't dispatch the same thing twice; poll with wait near 90 seconds instead of short loops; and record agentOutput.usage when a job finishes.
Fixed: query_usage said ok without a number
Run as an administrator, Codex 0.160's interactive mode refuses to start its shared daemon. The usage panel never appeared, yet query_usage returned status: "ok". The quota TUI now starts with --no-daemon, retrying without it on older CLIs that reject the flag, and a result with no quota numbers is an error, not ok — the raw screen is kept either way.
Compatibility
If Claude's output arrives as a single JSON document, the vendor's raw usage object now lives in raw_usage, and usage holds the normalized shape.
Full details: CHANGELOG.
繁體中文
codex 與 claude 的 job 會回報花了多少
在這之前,派出去的 job 花了多少,誰都看不到。ai-cli 從來沒解析 codex 和 claude 回報的用量;strict 路徑又讓 codex 帶 --ephemeral 執行,不留 session 檔,事後也查不到。我們在估算一個忙碌專案裡 ai-cli 佔多少花費時,就很容易把「量不到」誤當成「花得少」。
現在 codex 和 claude 的 job 結束時,wait 和 get_result 都會帶 agentOutput.usage,兩家統一成同一個形狀:總輸入、快取讀取、快取寫入、output、推理 token。claude 另外帶 num_turns 和 cost_usd_nominal。後者是依牌價估的名目成本,不是訂閱帳單,欄位名稱就寫明了這一點。
input_tokens在兩家的意思相同:送進模型的全部輸入,包含快取。codex 回報的值本來就是這樣;claude 原始的數字不含快取,所以把幾項加總。- 量不到用量時,這個欄位不會出現,不會填 0。如果 codex 有部分 turn 回報的用量格式壞掉,
usage只算有效的那幾筆,並標上incomplete: true,不會默默少算;全部無效時就不放usage。 - job 失敗、只回報用量而沒有回覆時,仍會帶回原始的 stdout/stderr。早期草稿在這種情況下會把錯誤原文藏掉,發版前的獨立稽核抓到了。
高成本的 effort 會提醒
實際送出的 effort 是 xhigh、max 或 ultra 時,不論是明確指定、alias 預設還是設定檔帶出來的,MCP 的 run 都會回傳 warnings 說明這件事,並標出來源。只提醒,不擋派工。(CLI 的 ai-cli run 在 6.5.0 才加上同樣的警告。)
派工建議納入成本
models → dispatchGuidance 依實測新增四條建議:每個 job 在做事之前都有固定開銷(這裡實測,最小的 codex job 約 2 萬 input tokens,最小的 claude job 約 3 萬 context;claude 的數字會隨你的 CLAUDE.md、hook 和 MCP server 而變),所以零碎的小任務要合併;同一件事不要派兩次;輪詢用接近 90 秒的 wait,不要短間隔反覆查;job 結束後記下 agentOutput.usage。
修正:query_usage 沒有數字卻回 ok
以系統管理員權限執行時,codex 0.160 的互動模式拒絕啟動共用 daemon,額度面板一直沒出現,query_usage 卻回 status: "ok"。現在查額度的 TUI 改帶 --no-daemon,舊版 CLI 不認得這個參數時會拿掉重跑一次;而且沒有任何額度數字的結果一律回 error,不再是 ok。兩種情況都會保留原始畫面。
相容性
claude 的輸出如果整段是單一 JSON,vendor 原始的 usage 物件改放在 raw_usage,usage 則是正規化後的形狀。
完整內容:CHANGELOG。