Skip to content

feat(cli): add headless single-shot maka run command - #7094

Merged
M4n5ter merged 2 commits into
apache:rust-previewfrom
Colafornia:feat/cli-run
Nov 21, 2026
Merged

M4n5ter merged 2 commits into
apache:rust-previewfrom
Colafornia:feat/cli-run

Conversation

@Colafornia

@Colafornia Colafornia commented Nov 20, 2026 •

Copy link
Copy Markdown
Member
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 maka binary: 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-stdin already 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 released maka binary with its real prompts, tools, skills, and permissions).

A naive single-shot wrapper also hits two practical pitfalls:

  • Background-service lifecycle: Real tasks and evaluation verifiers often ask the agent to leave a background process running (such as a local HTTP server) that gets checked after the agent exits. Force-stopping the local Host on exit — or on a later failed run sharing the same Root — kills services that still need to stay alive; conversely, failing to retire an idle ephemeral Host leaks background processes across runs.
  • Honest timeout and error boundaries: Silently accepting a short timeout flag that does not govern long-running agent tasks, hanging indefinitely when a queued prompt is retracted before execution starts, or collapsing ordinary model errors into an empty failure message makes automated runs hard to operate and diagnose.

What this PR does

Adds the public maka run subcommand strictly within products/maka/cli/ (zero overlap with #6977 in products/eval/ and no dependency changes), pairing directly with maka host init --settings-stdin to enable end-to-end headless single-task execution from the released maka binary:

  • Public single-shot CLI contract: Accepts --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.
  • Direct reuse of the Host's default product execution path: Connects to or starts the local Host on the target Root and executes with the Root's configured default model, tools, and permissions — introducing no parallel execution protocol and no benchmark-specific flags.
  • Explicit timeout, cancellation, and diagnostic boundaries: Explicitly rejects --timeout-ms on maka run instead of silently ignoring it — the global --timeout-ms flag is capped at 10 minutes for bounded Host and sandbox administrative operations, whereas real agent task budgets are enforced externally via OS signals (which maka run catches 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.
  • Safe Host and background-service lifecycle: Always detaches cleanly on both success and failure rather than force-stopping the Host. An externally managed Host (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 with maka host retire, and never lets a later failed run on the same Root terminate a prior run's surviving service.
  • End-to-end integration tests: Adds eight CLI integration tests under products/maka/cli/ driving the real maka binary 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 until maka 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 on 6d8de6bd4; 6 files under products/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:

  • Linux Harbor real-task validation including task budget expiry (deferred to follow-up feat(eval): rebuild the measurement and control plane in Rust #6667 integration once maka-eval and Harbor switch to maka run).
  • Full-repo just check and cargo clippy --all-targets across maka-cli (untouched test targets in maka-cli currently have pre-existing lint and formatting failures).
  • node scripts/rust/dependencies.mjs check (cargo-deny is not installed locally; Cargo.toml, Cargo.lock, and DEPENDENCIES.rust.tsv are untouched).

AI use

Select exactly one:

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: Google Antigravity implemented maka run, CLI wiring, and the integration tests under products/maka/cli/, and drafted this PR description. Commits 8ce59bfb8 and 983f99ea3 carry the Generated-by: Google Antigravity trailer; preserve it when squashing.

Checklist

  • Tests cover the change and fail without it
  • Format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No
中文

概述

问题

想要以无头模式让 Maka 跑完单个任务——无论是 shell 脚本、CI 流水线,还是 Harbor、FrontierHarness 这类外部评测框架——调用方只需要发布版 maka 二进制提供两项公开、最小的能力:先以非交互方式初始化一个干净的 State Root(写入模型连接、凭据、默认模型和工作区权限),再对着指定工作区提交一条任务,让 agent 跑完并干净退出。

maka host init --settings-stdin 已经解决了前半段,但后半段一直缺少公开的单次执行入口。没有这个入口时,非交互调用方只能直接对接交互式协议,或在外部维护私有包装脚本,破坏了产品一致性(无法直接用发布版 maka 及其默认的提示词、工具、技能和权限体系来执行任务)。

如果只是简单包一层单次执行外壳,还会撞上两个现实问题:

  • 后台服务生命周期冲突:真实任务和评测校验器经常要求 agent 启动并保留一个后台进程(例如本地 HTTP 服务),待 agent 退出后再做验收。如果单次执行命令在退出时——或在同 Root 上后续某次失败时——强行关闭本地 Host,就会把仍需存活的服务一并杀掉;反过来,如果不回收空闲的临时 Host,每次运行结束后都会残留后台进程。
  • 超时与错误边界失真:静默接受一个并不控制长时 agent 任务的短超时参数、排队中的请求在启动前被撤回时无限卡死、或把普通模型错误吞成空错误信息,都会让自动化运行难以运维与排障。

本次改动

本 PR 仅在 products/maka/cli/ 下新增公开的 maka run 子命令(与 #6977 所在的 products/eval/ 零文件重叠,无任何依赖变更),与 maka host init --settings-stdin 直接衔接,让发布版 maka 二进制可以通过单条命令完成端到端的无头单任务执行:

  • 公开的单次执行 CLI 契约:接收 --root、--workspace 以及通过位置参数或管道标准输入传入的单条 prompt,在触碰 State Root 前先完成输入校验(工作区路径、非空 prompt、禁止直接从交互终端读取标准输入)。诊断日志输出到 stderr,正常完成时将最终回答输出到 stdout 并以 0 退出,失败或中断时向 stderr 输出明确诊断信息并以非 0 退出。
  • 直接复用 Host 的默认产品执行链路:连接或拉起目标 Root 上的本地 Host,直接使用该 Root 已配置的默认模型、工具与权限体系,不引入平行的执行协议,也不添加仅面向评测的专用参数。
  • 明确的超时、取消与诊断边界:在 maka run 上显式拒绝 --timeout-ms 而非静默忽略——全局 --timeout-ms 上限为 10 分钟,仅用于有界限的 Host 与沙箱管理命令;真实 agent 任务的预算由外部通过 OS 信号控制,maka run 会捕获中断信号并干净撤回排队任务、停止运行中任务或打断阻塞的 stdout 写出。若排队中的请求在启动前被撤回,或任务暂停等待交互式确认,命令也会明确报错退出;任务失败时直接读取 Host 投影好的终态失败诊断,不再自行扫描请求历史或输出空错误。
  • 安全的 Host 与后台服务生命周期:无论成功还是失败,退出前都只干净断开连接而不强行终止 Host。外部常驻管理的 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 上本地未运行:

  • Linux Harbor 真题与任务预算到期实跑(待后续 feat(eval): rebuild the measurement and control plane in Rust #6667 集成工作将 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 Antigravity trailer,squash 合并时请保留。

检查清单

  • 测试覆盖本次变更且无修复前会失败
  • 格式、类型检查与受影响测试集已在本地通过

本 PR 是否带来行为变更?

  • 是 — 如上文概述所述
  • 否

@Colafornia
Colafornia marked this pull request as draft November 20, 2026 13:32
@Colafornia
Colafornia force-pushed the feat/cli-run branch 3 times, most recently from ba5f867 to 8ce59bf Compare November 20, 2026 14:46
@Colafornia
Colafornia marked this pull request as ready for review November 20, 2026 16:01
@github-actions github-actions Bot added the effort/XL Under 2500 readable lines label Nov 21, 2026

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Bug: cancel_work aborts on commit-time CAS conflict during Pending -> 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 of agent.send. If SIGTERM arrives during that window:

    • cancel_work observes Work::Pending and invokes agent.editQueue(Retract).
    • edit_queue (plugins/agent/native/src/owner/queue/controls.rs:190-198) sees the expected queue revision during prepare and stages PreparedEnqueue.
    • 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 return StoreError::RevisionConflict.
    • The Host runtime classifies RevisionConflict via state_rejected (platform/host-runtime/src/application/completion.rs:72-81) and records it as OperationResult::Failure { diagnostic } (platform/host-runtime/src/application/owner.rs:1835-1844) — not QueueMutationResult::RevisionConflict.
    • mutate::<QueueMutationResult>(..., "editQueue", ...).await? at cancel.rs:61-73 immediately propagates Err and exits cancel_work without re-querying agent.work or calling agent.stop, leaving the newly admitted Run executing in the background after maka run exits.
    • Fix: in the Work::Pending arm, do not fail out immediately on an editQueue commit error; continue the existing 15s polling loop to re-query agent.work so the transition to Work::Delivered naturally invokes agent.stop (and let the deadline bound persistent errors).
  2. Bug: Answer pagination silently truncates and exits 0 on unexpected response (products/maka/cli/src/run.rs:427-449)
    agent.work paginates 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, or answer: None, maka run silently breaks, writes a truncated answer to stdout, and exits 0. This should return Err(...) instead of break. Also, none of the current tests verify full stdout reconstruction for an answer larger than 8192 bytes.

  3. 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.rs mixes cancel_work with unrelated generic Host RPC helpers (open_call, query, mutate), while leaving subscribe in src/run.rs, solely so tests/integration/run.rs can pull them in via #[path = "../../src/run/cancel.rs"] mod cancel;. And run_cancel_work_retracts_queued_message_before_admission (152 lines) never executes the maka run binary at all — it drives HostClient manually to call the internal cancel::cancel_work helper 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.

  4. Test suite bloat (~55% of the PR) and minor polish

    • Remove run_cancel_work_retracts_queued_message_before_admission (white-box internal test) and run_failure_reports_model_diagnostic_and_retires_idle_candidate (already covered by run_preserves_background_http_server_across_completion_and_subsequent_failure for HTTP 400 diagnostics and run_failure_after_429_reports_terminal_output_limit_diagnostic for 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.rs instead 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 if maka-cli --test integration is run on Windows.
    • Minor: subscribing to agent.watch before agent.send causes observe_run (run.rs:330-345) to fire two redundant agent.work queries on every normal run (on the initial empty queue snapshot and again upon dequeue); also formatting rejection enums via serde_json::to_string (run.rs:213, 252, 410) leaks raw wire JSON into CLI stderr.
简体中文

maka run 的整体设计很清晰,也贴合 #6667 的目标:直接复用产品默认执行链路、退出时干净断开以保证后台服务活到 maka host retire、显式拒绝 --timeout-ms,以及按 ended_sequence 直接读取 Host 投影好的终态失败诊断。不过查下来有两个真实可达的 bug,加上几处模块划分和测试质量问题,建议合入前处理掉:

  1. 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 超时兜底。
  2. 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 的测试。

  3. 为了迁就白盒测试把生产模块拆歪了(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] 后,生产模块边界就能收拾干净。

  4. 测试瘦身(测试占本次改动 ~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.work RPC;另外 run.rs:213, 252, 410 直接拿 serde_json::to_string 拼 stderr 报错,会把原始内部 JSON 透给 CLI 用户。

…ut signal handling

Generated-by: Google Antigravity
@M4n5ter
M4n5ter merged commit 4ab6cab into apache:rust-preview Nov 21, 2026
13 of 14 checks passed
@Colafornia
Colafornia deleted the feat/cli-run branch November 21, 2026 10:14
YongGoose added a commit to YongGoose/maka that referenced this pull request Nov 25, 2026
…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
M4n5ter pushed a commit that referenced this pull request Nov 25, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/XL Under 2500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants