Repository navigation
feat(cli): add headless single-shot maka run command - #7094
Conversation
ba5f867 to
8ce59bf
Compare
M4n5ter
left a comment
There was a problem hiding this comment.
English
The overall design of maka run is clean and aligns well with #6667: reusing the default product execution path, detaching cleanly on exit so background services survive until maka host retire, explicitly rejecting --timeout-ms, and reading Host's projected terminal failure diagnostic at ended_sequence. There are two verified reachable bugs and a few structural/test issues to address before merge:
-
Bug:
cancel_workaborts on commit-time CAS conflict duringPending -> Delivered, leaving the Run unstopped (products/maka/cli/src/run/cancel.rs:60-93)
On a newly created idle session, the background scheduler admits the queued prompt within milliseconds ofagent.send. IfSIGTERMarrives during that window:cancel_workobservesWork::Pendingand invokesagent.editQueue(Retract).edit_queue(plugins/agent/native/src/owner/queue/controls.rs:190-198) sees the expected queue revision during prepare and stagesPreparedEnqueue.- Before the SQLite transaction commits, the scheduler consumes the message and advances the revision, causing
cas()(plugins/agent/state/src/queue/sql.rs:92-98) to returnStoreError::RevisionConflict. - The Host runtime classifies
RevisionConflictviastate_rejected(platform/host-runtime/src/application/completion.rs:72-81) and records it asOperationResult::Failure { diagnostic }(platform/host-runtime/src/application/owner.rs:1835-1844) — notQueueMutationResult::RevisionConflict. mutate::<QueueMutationResult>(..., "editQueue", ...).await?atcancel.rs:61-73immediately propagatesErrand exitscancel_workwithout re-queryingagent.workor callingagent.stop, leaving the newly admitted Run executing in the background aftermaka runexits.- Fix: in the
Work::Pendingarm, do not fail out immediately on aneditQueuecommit error; continue the existing 15s polling loop to re-queryagent.workso the transition toWork::Deliverednaturally invokesagent.stop(and let the deadline bound persistent errors).
-
Bug: Answer pagination silently truncates and exits 0 on unexpected response (
products/maka/cli/src/run.rs:427-449)
agent.workpaginates answers in 8192-byte chunks (plugins/agent/native/src/owner/execution.rs:162-173). In the pagination loop:let Work::Delivered { answer: Some(next_page), .. } = query::<Work>(...).await? else { break; };
If a follow-up page returns
Work::Changed,Work::Missing, oranswer: None,maka runsilently breaks, writes a truncated answer to stdout, and exits0. This should returnErr(...)instead ofbreak. Also, none of the current tests verify full stdout reconstruction for an answer larger than 8192 bytes. -
Production module split distorted by a white-box test include (
products/maka/cli/src/run/cancel.rs,products/maka/cli/tests/integration/run.rs:20, 815-971)
src/run/cancel.rsmixescancel_workwith unrelated generic Host RPC helpers (open_call,query,mutate), while leavingsubscribeinsrc/run.rs, solely sotests/integration/run.rscan pull them in via#[path = "../../src/run/cancel.rs"] mod cancel;. Andrun_cancel_work_retracts_queued_message_before_admission(152 lines) never executes themaka runbinary at all — it drivesHostClientmanually to call the internalcancel::cancel_workhelper directly (and still missed the real commit-time CAS race above). Dropping that white-box test and#[path]lets the production code keep clean module boundaries. -
Test suite bloat (~55% of the PR) and minor polish
- Remove
run_cancel_work_retracts_queued_message_before_admission(white-box internal test) andrun_failure_reports_model_diagnostic_and_retires_idle_candidate(already covered byrun_preserves_background_http_server_across_completion_and_subsequent_failurefor HTTP 400 diagnostics andrun_failure_after_429_reports_terminal_output_limit_diagnosticfor failure + idle Host retirement). - Add an end-to-end test verifying complete stdout output for a >8KB paginated answer.
- Where practical, reuse existing harness utilities in
products/maka/cli/tests/support/host.rsinstead of duplicating ~350 lines of Host setup. bg_server_turn_plan(tests/integration/run.rs:271-306) embeds POSIX shell syntax (while [ ! -f ... ]) without#[cfg(unix)], which fails ifmaka-cli --test integrationis run on Windows.- Minor: subscribing to
agent.watchbeforeagent.sendcausesobserve_run(run.rs:330-345) to fire two redundantagent.workqueries on every normal run (on the initial empty queue snapshot and again upon dequeue); also formatting rejection enums viaserde_json::to_string(run.rs:213, 252, 410) leaks raw wire JSON into CLI stderr.
- Remove
简体中文
maka run 的整体设计很清晰,也贴合 #6667 的目标:直接复用产品默认执行链路、退出时干净断开以保证后台服务活到 maka host retire、显式拒绝 --timeout-ms,以及按 ended_sequence 直接读取 Host 投影好的终态失败诊断。不过查下来有两个真实可达的 bug,加上几处模块划分和测试质量问题,建议合入前处理掉:
-
Bug:
cancel_work在Pending -> Delivered并发窗口会直接报错退出,漏调agent.stop(products/maka/cli/src/run/cancel.rs:60-93)
在全新空闲 session 上,agent.send返回后后台调度器会在毫秒级内把排队消息 consume 掉启动 Run。如果SIGTERM恰好在这段窗口到达:cancel_work查agent.work看到Work::Pending,随即调用agent.editQueue(Retract);edit_queue(plugins/agent/native/src/owner/queue/controls.rs:190-198)在 prepare 阶段看到queue.revision匹配,打包出PreparedEnqueue;- 到 SQLite 提交事务前,调度器抢先 consume 消息推进了 revision,
cas()(plugins/agent/state/src/queue/sql.rs:92-98)返回StoreError::RevisionConflict; - Host 运行时通过
state_rejected(platform/host-runtime/src/application/completion.rs:72-81)将其归为操作失败,在platform/host-runtime/src/application/owner.rs:1835-1844记录为OperationResult::Failure { diagnostic }——而非业务层的QueueMutationResult::RevisionConflict; cancel.rs:61-73对mutate::<QueueMutationResult>(..., "editQueue", ...).await?直接?抛出错误退出cancel_work,既没有重查agent.work也没有调agent.stop,导致maka run带着cancel failed退出,刚启动的 Run 却留在后台继续运行。- 修复建议:
Work::Pending分支里editQueue提交失败时不要立刻?退出,留在现有 15 秒重试循环里重查agent.work,待状态切到Work::Delivered后自然进入agent.stop,真正持续异常交由 deadline 超时兜底。
-
Bug:
read_completed_answer分页中途异常时静默break,输出截断回答且以 0 退出(products/maka/cli/src/run.rs:427-449)
agent.work每次返回最多 8192 字节(plugins/agent/native/src/owner/execution.rs:162-173)。分页循环中:let Work::Delivered { answer: Some(next_page), .. } = query::<Work>(...).await? else { break; };
一旦后续页返回
Work::Changed、Work::Missing或answer: None,代码会直接break,把只拼了一半的截断文本写进 stdout 并返回退出码0。这里应该直接返回Err(...),同时补一条验证 >8KB 多页回答完整写到 stdout 的测试。 -
为了迁就白盒测试把生产模块拆歪了(
products/maka/cli/src/run/cancel.rs、products/maka/cli/tests/integration/run.rs:20, 815-971)
src/run/cancel.rs把cancel_work和毫不相干的通用 Host RPC 封装(open_call/query/mutate)混在了一起,而同级的subscribe却留在src/run.rs,唯一原因就是为了让tests/integration/run.rs通过#[path = "../../src/run/cancel.rs"] mod cancel;把内部模块硬 include 进去。run_cancel_work_retracts_queued_message_before_admission(152 行)压根没跑maka run二进制,纯属手工连HostClient调内部函数的白盒测试(而且因为只测了静止排队态,上面的真实 CAS 竞态也没测出来)。拔掉这条测试和#[path]后,生产模块边界就能收拾干净。 -
测试瘦身(测试占本次改动 ~55%)与细节打磨
- 删掉白盒的
run_cancel_work_retracts_queued_message_before_admission,以及和现有用例完全重叠的run_failure_reports_model_diagnostic_and_retires_idle_candidate(HTTP 400 诊断已在run_preserves_background_http_server_across_completion_and_subsequent_failure测过,失败后临时 Host 空闲回收已在run_failure_after_429_reports_terminal_output_limit_diagnostic测过)。 - 补一条 >8KB 分页回答完整输出到 stdout 的行为验证。
tests/integration/run.rs自己重写了 ~350 行 Host 脚手架,可考虑按需复用products/maka/cli/tests/support/host.rs。bg_server_turn_plan(tests/integration/run.rs:271-306)写了 POSIX shell 语法(while [ ! -f ... ])却没有#[cfg(unix)],在 Windows 上直接跑maka-cli --test integration会挂。- 小细节:在
agent.send之前订阅agent.watch会导致observe_run(run.rs:330-345)每次正常执行都在初始空队列和出队时白打两次agent.workRPC;另外run.rs:213, 252, 410直接拿serde_json::to_string拼 stderr 报错,会把原始内部 JSON 透给 CLI 用户。
- 删掉白盒的
Generated-by: Google Antigravity
…ut signal handling Generated-by: Google Antigravity
983f99e to
5b09174
Compare
…waits A `maka run "<prompt>"` without `--session` or `--no-wait` cancels its Run and exits 1 with `execution blocked by pending interaction(s): ...` when the Run stops on a question or approval, as apache#7094 did. Nothing can answer it later, and scripts, CI and evals treat a non-zero exit as failure. Session follow-ups (`--session` with a prompt, `--wait` or `--answer`) leave the Run waiting, print the `waiting` report and exit 3, so a script can tell a pending decision from an answer without parsing stdout. clap uses 2 for usage errors. Generated-by: Claude Code
* feat(cli): continue, wait on, answer and stop maka run Sessions
`maka run` could only run one prompt in a new Session, and a run that
stopped on a question or an approval was cancelled. A script or another
agent had no way to answer it or follow up.
Add `--session` to queue a prompt to an existing Session, `--no-wait`
to return a JSON receipt once the prompt or answer is accepted, `--wait`
to wait on the Session's current work, `--answer` to answer its pending
question and `--stop` to stop its active Run. A wait that reaches a
pending interaction now leaves the Run waiting and prints it as JSON.
Ctrl+C withdraws only a message this invocation queued.
Generated-by: Claude Code
* fix(cli): keep following when a question closes and reject a late stop
`maka run` reported `{"status":"waiting","interactions":[]}` when every
pending question was answered or closed between the Interactions page and
the `agent.interaction` read. The questions are now described inside the
follow loop, where Ctrl+C can interrupt the read, and an empty result keeps
following instead of reporting.
`--stop` ignored `Stopped.requested`, so a Run that ended between `observe`
and `stop` printed a stopped receipt. It now fails with `session has no
active run`, and Ctrl+C interrupts the wait for the Run to settle.
`--wait` on an idle Session reads the latest Run's result without opening a
watch, a result already read to check for completion is reused instead of
read again, and `--no-wait` skips the `observe` it never used.
Generated-by: Claude Code
* fix(cli): keep single-shot runs fail-fast and exit 3 while a Session waits
A `maka run "<prompt>"` without `--session` or `--no-wait` cancels its Run
and exits 1 with `execution blocked by pending interaction(s): ...` when the
Run stops on a question or approval, as #7094 did. Nothing can answer it
later, and scripts, CI and evals treat a non-zero exit as failure.
Session follow-ups (`--session` with a prompt, `--wait` or `--answer`) leave
the Run waiting, print the `waiting` report and exit 3, so a script can tell
a pending decision from an answer without parsing stdout. clap uses 2 for
usage errors.
Generated-by: Claude Code
English
Summary
Problem
Running Maka headlessly on a single task — whether from a shell script, a CI pipeline, or an external evaluation harness such as Harbor or FrontierHarness — requires two minimal, public capabilities from the released
makabinary: initializing a clean State Root with connections, credentials, default model, and workspace permissions without interactive setup, and submitting one prompt against a workspace so the agent completes the task and exits cleanly.maka host init --settings-stdinalready solves the first half, but Maka had no public single-shot execution command for the second half. Without it, non-interactive callers had to integrate interactive protocols directly or maintain private wrapper scripts, breaking product parity (running the exact releasedmakabinary with its real prompts, tools, skills, and permissions).A naive single-shot wrapper also hits two practical pitfalls:
What this PR does
Adds the public
maka runsubcommand strictly withinproducts/maka/cli/(zero overlap with #6977 inproducts/eval/and no dependency changes), pairing directly withmaka host init --settings-stdinto enable end-to-end headless single-task execution from the releasedmakabinary:--root,--workspace, and one prompt via positional argument or piped stdin, validating inputs (workspace path, non-empty prompt, non-TTY stdin) before touching the State Root. Routes diagnostic logs to stderr, writes the final assistant answer to stdout on success (exit 0), and writes clear failure or interruption diagnostics to stderr on non-zero exit.--timeout-msonmaka runinstead of silently ignoring it — the global--timeout-msflag is capped at 10 minutes for bounded Host and sandbox administrative operations, whereas real agent task budgets are enforced externally via OS signals (whichmaka runcatches to cancel queued or running work and interrupt blocked stdout writes cleanly). Exits cleanly if a queued prompt is retracted before starting or if the run pauses for interactive input, and reads Host's projected terminal failure diagnostic directly on failure instead of scanning request history or returning an empty error.maka host serve) is left untouched; an ephemeral Host auto-retires once idle, keeps active background services alive past its idle grace period until explicitly stopped withmaka host retire, and never lets a later failed run on the same Root terminate a prior run's surviving service.products/maka/cli/driving the realmakabinary and local Host across argument and piped-stdin prompts, idle ephemeral Host auto-retirement, background HTTP server survival across normal exit and a subsequent same-Root model failure untilmaka host retire, terminal failure diagnostics across HTTP 400 and a transient 429 retry followed by output length exhaustion, queued message retraction before admission so the retracted prompt never executes, SIGTERM interruption of both in-flight runs and blocked stdout pipes, pre-Root input validation, and preservation of externally managed Hosts.Refs #6667.
Verification
Verified on commit
983f99ea3(based on6d8de6bd4; 6 files underproducts/maka/cli/, no dependency changes):rustfmt --edition 2024 --check products/maka/cli/src/run.rs products/maka/cli/src/run/cancel.rs products/maka/cli/tests/integration/run.rs— passed.cargo clippy --locked -p maka-cli --bin maka --test integration --no-deps -- -D warnings— passed.cargo test --locked -p maka-cli --test integration run:: -- --nocapture—8 passed; 0 failed(21.90s).cargo build --locked -p maka-cli --bin maka --no-default-features— passed (1m 31s).node scripts/asf-license-headers.mjs check— passed (Audited 2571 covered and 3431 excluded file(s)).Not run locally on
983f99ea3:maka-evaland Harbor switch tomaka run).just checkandcargo clippy --all-targetsacrossmaka-cli(untouched test targets inmaka-clicurrently have pre-existing lint and formatting failures).node scripts/rust/dependencies.mjs check(cargo-denyis not installed locally;Cargo.toml,Cargo.lock, andDEPENDENCIES.rust.tsvare untouched).AI use
Select exactly one:
Tool(s) and scope: Google Antigravity implemented
maka run, CLI wiring, and the integration tests underproducts/maka/cli/, and drafted this PR description. Commits8ce59bfb8and983f99ea3carry theGenerated-by: Google Antigravitytrailer; preserve it when squashing.Checklist
Does this PR entail a change in behavior?
中文
概述
问题
想要以无头模式让 Maka 跑完单个任务——无论是 shell 脚本、CI 流水线,还是 Harbor、FrontierHarness 这类外部评测框架——调用方只需要发布版
maka二进制提供两项公开、最小的能力:先以非交互方式初始化一个干净的 State Root(写入模型连接、凭据、默认模型和工作区权限),再对着指定工作区提交一条任务,让 agent 跑完并干净退出。maka host init --settings-stdin已经解决了前半段,但后半段一直缺少公开的单次执行入口。没有这个入口时,非交互调用方只能直接对接交互式协议,或在外部维护私有包装脚本,破坏了产品一致性(无法直接用发布版maka及其默认的提示词、工具、技能和权限体系来执行任务)。如果只是简单包一层单次执行外壳,还会撞上两个现实问题:
本次改动
本 PR 仅在
products/maka/cli/下新增公开的maka run子命令(与 #6977 所在的products/eval/零文件重叠,无任何依赖变更),与maka host init --settings-stdin直接衔接,让发布版maka二进制可以通过单条命令完成端到端的无头单任务执行:--root、--workspace以及通过位置参数或管道标准输入传入的单条 prompt,在触碰 State Root 前先完成输入校验(工作区路径、非空 prompt、禁止直接从交互终端读取标准输入)。诊断日志输出到 stderr,正常完成时将最终回答输出到 stdout 并以 0 退出,失败或中断时向 stderr 输出明确诊断信息并以非 0 退出。maka run上显式拒绝--timeout-ms而非静默忽略——全局--timeout-ms上限为 10 分钟,仅用于有界限的 Host 与沙箱管理命令;真实 agent 任务的预算由外部通过 OS 信号控制,maka run会捕获中断信号并干净撤回排队任务、停止运行中任务或打断阻塞的 stdout 写出。若排队中的请求在启动前被撤回,或任务暂停等待交互式确认,命令也会明确报错退出;任务失败时直接读取 Host 投影好的终态失败诊断,不再自行扫描请求历史或输出空错误。maka host serve)完全不受影响;临时拉起的 Host 在空闲后自动回收,在存在活跃后台服务时则会越过空闲宽限期继续存活,直到显式调用maka host retire停止,且同 Root 上后续某次失败不会误杀先前成功任务留下的后台服务。products/maka/cli/下新增 8 组驱动真实maka二进制与本地 Host 的集成测试,覆盖参数与管道输入、空闲临时 Host 自动回收、后台 HTTP 服务在正常退出及同 Root 后续模型失败后的存活直至maka host retire、HTTP 400 与 429 重试后触发输出上限的终态诊断、排队消息在进入执行前的撤回保证、SIGTERM 对执行中任务及 stdout 阻塞管道的中断、触碰 Root 前的输入校验,以及对外部常驻 Host 的无干扰保护。Refs #6667.
验证
基于提交
983f99ea3(基准6d8de6bd4;仅改动products/maka/cli/下 6 个文件,无依赖变更)完成验证:rustfmt --edition 2024 --check products/maka/cli/src/run.rs products/maka/cli/src/run/cancel.rs products/maka/cli/tests/integration/run.rs— 通过。cargo clippy --locked -p maka-cli --bin maka --test integration --no-deps -- -D warnings— 通过。cargo test --locked -p maka-cli --test integration run:: -- --nocapture—8 passed; 0 failed(21.90s)。cargo build --locked -p maka-cli --bin maka --no-default-features— 通过(1m 31s)。node scripts/asf-license-headers.mjs check— 通过(Audited 2571 covered and 3431 excluded file(s))。在
983f99ea3上本地未运行:maka-eval与 Harbor 切换至maka run后补充验收)。just check与整个maka-cli的cargo clippy --all-targets(maka-cli中未改动的其他测试目标存在既有 lint 与格式问题)。node scripts/rust/dependencies.mjs check(本地未安装cargo-deny;Cargo.toml、Cargo.lock与DEPENDENCIES.rust.tsv均未改动)。AI 使用
单选:
工具与范围:Google Antigravity 实现了
products/maka/cli/中的maka run、CLI 接入与集成测试,并起草了本 PR 描述。提交8ce59bfb8与983f99ea3均附带Generated-by: Google Antigravitytrailer,squash 合并时请保留。检查清单
本 PR 是否带来行为变更?