Skip to content

ACP: turns Kimi starts itself (background task results, CronCreate) send no session/update events #4109

Open

Description

@jbellis

Summary

Over ACP, Kimi Code sends no session/update events for turns it starts on its own: the turn that delivers a finished background agent's or background shell's result, and the turn a CronCreate schedule fires. An ACP client sees none of that turn's messages, thoughts, tool calls or its end; only terminal/* requests from it arrive. A client therefore cannot show what the agent did, and cannot tell that the agent is busy.

A related problem: a session/prompt sent while such a turn is running is answered at once with stopReason: "end_turn" and no content, then runs later as its own turn, which is again invisible to the client.

Versions

Kimi Code 2.0.2 and 2.1.1 (kimi acp), Linux x86_64. The same behavior is visible with 0.41.0. acp-server/src/session.ts is identical between 2.0.2 and 2.1.1.

Reproduction

  1. Start kimi acp and open a session from any ACP client.
  2. Send: "Start a background agent that runs sleep 20 && wc -l README.md and reports the line count; tell me when you have started it."
  3. The client receives the launch and the reply for this prompt, then end_turn.
  4. About 20 s later the background agent finishes and Kimi starts its own turn to report the result ("README.md has 37 lines."). That turn appears in Kimi's own session record, but the ACP client receives no session/update for it: no agent_message_chunk, no tool calls (except terminal/create and related requests if the turn runs shell commands), and nothing marking the turn's end.
  5. The same happens for turns started by a CronCreate schedule.
  6. Optional: send a session/prompt while such an agent-started turn is running. The response is immediate end_turn with no output; the prompt is then executed later as a separate turn whose updates are also not sent.

Cause (from reading the source)

In acp-server/src/session.ts, driverFor routes events only for turns that a session/prompt started; events of a turn with another origin (the session record shows origin.kind task or cron_job) are dropped.

Expected

  • Send session/update notifications for agent-started turns as for prompted ones (messages, thoughts, tool calls), so the client's transcript includes them. A turn-boundary signal for these turns (for example in _meta) would let clients show that the agent is busy.
  • For a session/prompt that arrives during an agent-started turn: either wait and run it after that turn with normal updates and a normal response, or refuse it with an error the client can retry, rather than answering end_turn immediately and running it unseen.

Observed with Mjolnir (an ACP client that runs Kimi Code sessions).

Activity

  1. added a commit that references this issue on Oct 2, 2026
  2. jason5545 commented on Oct 24, 2026

    @jason5545

    Another trigger for the same queued-prompt path: /compact over ACP (Kimi Code 2.3.1)

    The "prompt answered at once with end_turn, then run later invisibly" behavior described above also happens right after /compact, with no background task or cron involved.

    Reproduction

    1. In an ACP session with a fair amount of context, send /compact as a session/prompt.
    2. The response arrives within ~30 ms with stopReason: "end_turn" and the message "Context compaction started — it runs in the background and the compacted context applies once it finishes." The compaction request itself takes much longer (about 98 s in our case).
    3. While compaction is still running, send a normal session/prompt. It is answered in ~15 ms with end_turn and no content.
    4. When compaction finishes, Kimi runs the queued prompt as its own turn. The session log shows the model working and files being edited, but the ACP client receives no session/update for that turn.
    5. Re-sending the prompt during that invisible turn queues it again, so the same task runs twice.

    Cause (from reading the bundled source)

    • /compact is handled by driveBuiltinCommand, which calls agent.compact() and returns end_turn immediately; the compaction is not registered as a turn.
    • driveTurn guards with assertNoActiveTurn, which only checks for an in-flight prompt, so background compaction does not block a new prompt.
    • With the engine busy, agent.prompt() queues the message and returns undefined. The ACP layer treats that as "no turn started" and answers end_turn, although the nearby comment notes this case should be rejected because the queued turn's events would be unattributed.
    • When the queued turn runs, driverFor(turnId) finds no driver, so all its updates are dropped.

    Suggested fix

    • In driveTurn, when agent.prompt() queues instead of starting a turn, return an error (or wait and run it as a normal turn) instead of end_turn.
    • Make /compact over ACP resolve only when compaction completes or is cancelled, or have assertNoActiveTurn treat a running compaction as an active turn.

    As a client-side workaround, we now hold the /compact prompt open until Kimi emits "Compaction completed." / "Compaction cancelled." before sending the next prompt.

    Investigated with AI assistance (Claude Code), from T3 Code provider logs, the Kimi session log and the source bundled in the kimi 2.3.1 binary.

  3. Dante-dan commented on Oct 24, 2026

    @Dante-dan

    I traced both reports to the current ACP adapter: it filters turn-scoped output through the driver for an outstanding session/prompt, while task/Cron turns and background compaction can keep the engine busy without that driver.

    The reference change tracks turn.started / turn.ended separately from RPC settlement. It forwards messages, thoughts and tool updates for independently started main-agent turns, while only the matching RPC driver can settle a prompt. The busy check also covers those turns and the compaction lifecycle, so a prompt during /compact is rejected with the existing retryable busy error instead of silently entering the engine queue. The compaction launch marker is released in finally; completion, cancellation and blocking release the lifecycle marker. This keeps the existing background /compact response and completion notices.

    Fixed reference diff.

    Validation: package typecheck, source lint and git diff --check passed. The existing ACP turn suite completed all 24 assertions successfully, but its command exited 1 due to 21 unhandled EMFILE filesystem-watcher errors; the whole ACP suite also hit watcher limits, including with one worker. These checks used Node 24.12.0, below the repository's 24.15.0 minimum. I have not reproduced the actual task/Cron scenarios in a live client, and this change does not add a new turn-boundary protocol extension.

    Please /approve if this approach is acceptable; I can continue from the reference branch.

  4. IvanLarin commented on Nov 1, 2026

    @IvanLarin

    Reproduced on Kimi Code 2.4.1 / Windows / Zed ACP: completion turn appears only after restart

    I reproduced this with a minimal 30-second background Bash task, without any project-specific code.

    Environment:

    • Kimi Code CLI 2.4.1
    • Zed with ACP
    • Windows NT 10.0.26300.0 x64
    • GNU Bash 4.4.23

    Steps:

    1. Ask the agent to run sleep 30 via Bash(run_in_background=true).
    2. The agent ends its turn immediately, saying it will report when the task finishes.
    3. Do not call TaskList, TaskOutput, or WaitFor, and keep the client idle for 40–60 seconds.
    4. Observe that no live completion message appears in Zed.
    5. Send a user prompt. In this recording, two prompts produced no visible response before restart.
    6. Restart Zed and reload the same session.

    Expected:

    • The background-task completion turn is streamed to the ACP client as it happens.
    • User prompts receive visible responses without restarting the client.

    Actual:

    • The process finished successfully, but Zed showed no live completion turn.
    • The agent internally received the completion notification after 30.870 seconds and generated a response, but that response was not displayed.
    • After restarting Zed and reloading the session, the completion notification and the agent's response appeared in the restored history.
    • The user prompts then began processing.

    Task evidence:

    • Started: 10:46:30 UTC.
    • Completion marker: 10:47:00 UTC.
    • TaskOutput: completed, exit code 0.
    • Task ID: bash-sy2k6322.

    This distinguishes the failure stage: task execution and agent-side notification completed, but the live autonomous turn was not delivered to or displayed by the ACP client until session reload.

    The behavior also matches the history-replay observation in #2878.

    I have a screen recording showing the launch, the missing live response, two unanswered prompts, the Zed restart, and the subsequent appearance of the missing turn in history. Local paths and unrelated session information will be redacted before sharing.

    The issue is intermittent in my controlled series: one client-visible failure was observed across ten background-task probes with varying durations and interaction patterns.

  5. alexanderfedyunin-bit commented on Nov 22, 2026

    @alexanderfedyunin-bit

    Reproduced on Windows with Orca 1.4.269 and bundled Kimi Code 2.7.2.

    After background Bash tasks complete or fail, Kimi starts task-origin turns internally without sending their updates over ACP.

    User prompts submitted during those invisible turns are immediately recorded by Orca as completed/success after 20-30 ms, with no content. Kimi's wire.jsonl shows that the same prompts actually start 5-6 minutes later and execute normally, but their updates never reach Orca.

    Concrete example:

    • Orca submission: 10:37:12.628
    • Orca completed/success: 10:37:12.654 (26 ms)
    • Kimi actually started the prompt: 10:42:12.251
    • Kimi completed the prompt: 10:43:52.009

    The same happened to two subsequent user prompts.

    This is not merely a display issue. Queued prompts can execute file modifications later without user visibility, and repeated submissions can potentially repeat those modifications. Please prioritize the ACP queue handling fix.

  6. jzissimos commented on Nov 23, 2026

    @jzissimos

    Also on Kimi Code 2.7.2 with T3 Code 0.1.11 (macOS, Intel). A background Bash task finished mid-turn, and Kimi started its own turn (task:…:completed) at 05:17:59 UTC that ran for 11 minutes. Three prompts sent during it returned in 21–26 ms, then ran later, one after another. None of that output reached the client. Please send session/update for self-started turns, and refuse or hold prompts until they can run.

  7. whynpc9 commented on Dec 1, 2026

    @whynpc9

    Kimi Code 2.8.1 also loses goal-continuation output over ACP

    I observed the same symptom with Kimi's automatic goal continuation in T3 Code. The ACP client recorded the initial response and marked the run complete, while Kimi continued working in the same native session.

    Environment: macOS arm64, Kimi Code CLI 2.8.1, kimi-code/k3.1-pro, T3 Code Nightly 0.1.14-nightly.20261128.5385, Kimi launched as an ACP subprocess.

    Observed sequence (relative times, with message content omitted):

    Time Kimi's native session record T3's persisted transcript
    T+0 A normal user turn ends after creating a goal with CreateGoal. Its final response is recorded. The response is present and the run completes.
    T+4 ms A new turn starts with origin.kind=system_trigger and origin.name=goal_continuation. No corresponding turn output appears.
    T+22 s The first assistant text from the continuation is recorded. That text is absent.
    Following 47 minutes The native log contains 31 assistant text blocks between the last visible response and the next visible response. All 31 blocks are absent. A later ordinary user prompt and its response appear normally.

    Standalone reproduction: A stdlib-only Python client launched Kimi Code 2.8.1 over stdio in a scratch workspace. A loopback model fixture scripted three responses: a CreateGoal tool call, an initial text marker, and a second marker during automatic goal continuation. The client kept the connection open after the first session/prompt completed. It observed this result:

    Initial session/prompt stopReason: end_turn
    Initial marker in ACP output: True
    Continuation marker in native session: True
    Continuation marker in ACP output: False
    

    The standalone probe uses synthetic data and the installed kimi binary. Run the accompanying script with python3 repro-kimi-acp-goal-output.py "$(command -v kimi)".

    Expected: After the initial prompt completes, the client can observe output from goal continuation, with enough lifecycle information to tell when Kimi is working and when it is idle.

    In the 2.8.1 ACP source, driveLaunch binds a driver to a specific turn, and onAssistantDelta returns before emitting a notification when no driver matches that turn. The T3 observation comes from persisted transcripts. The standalone reproduction captures the ACP output directly.

    repro-kimi-acp-goal-output.py
    """Probe Kimi ACP goal continuation with a synthetic model on loopback."""
    import argparse
    from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
    import json
    import os
    from pathlib import Path
    import queue
    import subprocess
    import tempfile
    import threading
    import time
    
    FIRST = "ACP_CONTROL_FIRST"
    SECOND = "ACP_CONTINUATION_SECOND"
    
    
    class MockModel(BaseHTTPRequestHandler):
        requests = 0
    
        def log_message(self, *args):
            pass
    
        def do_POST(self):
            if self.path != "/v1/chat/completions":
                self.send_error(404)
                return
            request = json.loads(self.rfile.read(int(self.headers["content-length"])))
            MockModel.requests += 1
            index = MockModel.requests
            if index == 1:
                tool_names = {tool["function"]["name"] for tool in request.get("tools", [])}
                if "CreateGoal" not in tool_names:
                    self.send_error(400, "Expected CreateGoal in the tool list")
                    return
                arguments = json.dumps({
                    "objective": "Emit two synthetic markers in separate turns.",
                    "completionCriterion": "Emit the second marker during automatic continuation.",
                })
                delta = {"tool_calls": [{
                    "index": 0, "id": "call_goal_fixture", "type": "function",
                    "function": {"name": "CreateGoal", "arguments": arguments},
                }]}
                finish_reason = "tool_calls"
            else:
                delta = {"content": FIRST if index == 2 else SECOND}
                finish_reason = "stop"
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.end_headers()
            try:
                for item in ({"role": "assistant"}, delta, {}):
                    data = {
                        "id": f"chatcmpl-fixture-{index}", "object": "chat.completion.chunk",
                        "created": 1, "model": "synthetic",
                        "choices": [{"index": 0, "delta": item,
                                     "finish_reason": None if item else finish_reason}],
                    }
                    self.wfile.write(b"data: " + json.dumps(data).encode() + b"\n\n")
                self.wfile.write(b"data: [DONE]\n\n")
            except BrokenPipeError:
                pass
    
    
    def probe(process, state_dir, workspace):
        incoming = queue.Queue()
    
        def drain():
            for line in process.stdout:
                incoming.put(json.loads(line))
    
        threading.Thread(target=drain, daemon=True).start()
        text = []
    
        def send(message):
            process.stdin.write(json.dumps({"jsonrpc": "2.0", **message}) + "\n")
            process.stdin.flush()
    
        def receive(timeout):
            message = incoming.get(timeout=timeout)
            if message.get("method") == "session/request_permission":
                options = message["params"]["options"]
                allow = next((option for option in options if option["kind"] == "allow_once"), None)
                if allow is None:
                    raise RuntimeError("Fixture needs an allow-once option for goal creation")
                send({"id": message["id"], "result": {"outcome": {
                    "outcome": "selected", "optionId": allow["optionId"],
                }}})
            update = message.get("params", {}).get("update", {})
            if update.get("sessionUpdate") == "agent_message_chunk":
                text.append(update["content"]["text"])
            return message
    
        def rpc(id_, method, params):
            send({"id": id_, "method": method, "params": params})
            end = time.monotonic() + 10
            while time.monotonic() < end:
                message = receive(max(0.01, end - time.monotonic()))
                if message.get("id") == id_ and ("result" in message or "error" in message):
                    if "error" in message:
                        raise RuntimeError(f"{method} returned {message['error']['code']}")
                    return message["result"]
            raise RuntimeError(f"{method} timed out")
    
        init = rpc(1, "initialize", {"protocolVersion": 1, "clientCapabilities": {}})
        new = rpc(2, "session/new", {"cwd": str(workspace), "mcpServers": []})
        result = rpc(3, "session/prompt", {
            "sessionId": new["sessionId"],
            "prompt": [{"type": "text", "text": "Run the synthetic two-turn goal fixture."}],
        })
        deadline = time.monotonic() + 10
        native_continuation = False
        while time.monotonic() < deadline:
            native = "".join(
                path.read_text() for path in state_dir.glob("sessions/*/*/agents/main/wire.jsonl")
            )
            if "goal_continuation" in native and SECOND in native:
                native_continuation = True
                break
            try:
                receive(0.05)
            except queue.Empty:
                pass
        sync_end = time.monotonic() + 0.5
        while time.monotonic() < sync_end:
            try:
                receive(max(0.01, sync_end - time.monotonic()))
            except queue.Empty:
                break
        first_seen = FIRST in "".join(text)
        second_seen = SECOND in "".join(text)
        print(f"Kimi Code version: {init['agentInfo']['version']}")
        print(f"Initial session/prompt stopReason: {result['stopReason']}")
        print(f"Initial marker in ACP output: {first_seen}")
        print(f"Continuation marker in native session: {native_continuation}")
        print(f"Continuation marker in ACP output: {second_seen}")
        if result["stopReason"] != "end_turn" or not first_seen or not native_continuation:
            raise SystemExit("INCONCLUSIVE: the fixture did not complete both positive controls")
        if not second_seen:
            raise SystemExit("REPRODUCED: the continuation produced text without an ACP message")
    
    
    def main():
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("kimi", type=Path, help="Path to the Kimi Code executable")
        args = parser.parse_args()
        with tempfile.TemporaryDirectory(prefix="kimi-acp-goal-") as temp:
            root = Path(temp)
            workspace = root / "workspace"
            workspace.mkdir()
            state_dir = root / "kimi"
            with ThreadingHTTPServer(("127.0.0.1", 0), MockModel) as server:
                threading.Thread(target=server.serve_forever, daemon=True).start()
                env = {key: value for key, value in os.environ.items()
                       if not key.startswith(("KIMI_", "MOONSHOT_"))}
                env.update(
                    HOME=temp, KIMI_CODE_HOME=str(state_dir), KIMI_MODEL_NAME="synthetic",
                    KIMI_MODEL_API_KEY="local-test-placeholder", KIMI_MODEL_PROVIDER_TYPE="openai",
                    KIMI_MODEL_BASE_URL=f"http://127.0.0.1:{server.server_port}/v1",
                    KIMI_DISABLE_TELEMETRY="1",
                )
                try:
                    with subprocess.Popen([str(args.kimi.resolve()), "acp"], env=env,
                                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                          stderr=subprocess.DEVNULL, text=True) as process:
                        try:
                            probe(process, state_dir, workspace)
                        finally:
                            process.terminate()
                            process.wait(timeout=4)
                finally:
                    server.shutdown()
    
    
    if __name__ == "__main__":
        main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions