ACP adapter does not surface failed turns (non-auth failures resolve as end_turn, error only in session log)
What issue are you seeing?
The ACP adapter does not surface a failed turn to the client. When a turn fails for a non-auth reason (e.g. a non-retryable upstream HTTP 400, a rate limit, an expired token after retries are exhausted), packages/acp-adapter/src/session.ts handles turn.ended with reason: 'failed' by calling log.warn(...) and then resolving session/prompt with stopReason: 'end_turn' (only auth-coded failures are routed to a JSON-RPC error via authRequiredFromPayload). The actual error is written to the session log (~/.kimi-code/sessions/.../logs/kimi-code.log) but is not exposed on the ACP wire — not on the JSON-RPC error channel, not as refusal, and not in PromptResponse.
Consequence for ACP orchestration clients (Multica, OpenCode, Claude Code running kimi as a backend): a genuinely failed turn is indistinguishable from a clean, empty completion. The client reports the task as successfully completed with no output, and the actionable error stays buried in the local log.
Concrete case that motivated this report: a session accumulated an empty assistant message, so every subsequent prompt got 400 the message at position N with role 'assistant' must not be empty. kimi acp exited 0 with no output; the orchestrator recorded status=completed, output_bytes=0 on each attempt — a silent no-op the user experienced as "Kimi returns nothing".
Related: #1855 (usage not reported over ACP). Both are ACP-adapter observability gaps; this one is about failure visibility.
What steps can reproduce the bug?
- Drive kimi over ACP (
kimi acp) from any ACP client. - Force a non-auth, non-retryable turn failure — e.g. resume a session whose history contains an empty
assistantmessage (server returns400 ... must not be empty), or otherwise trigger a 4xx that exhausts retries. - Observe:
session/promptresolves withstopReason: end_turn, no error is delivered to the client, and the failure appears only inlogs/kimi-code.log(WARN llm request failed ... statusCode=400).
What is the expected behavior?
A non-auth turn failure should be observable by the ACP client without reading kimi's local log — e.g. surface the error on the JSON-RPC error channel, or attach the failure payload to PromptResponse (the spec provides _meta for out-of-band data), or otherwise signal that the turn did not complete cleanly. As-is, clients cannot tell a failed turn from an empty successful one.
Additional information
- Version: Kimi Code 0.26.0
- Source pointer:
packages/acp-adapter/src/session.ts, theturn.endedhandler —reason === 'failed'non-auth branch resolves{ stopReason: turnEndReasonToStopReason(...) }=end_turn, per the documented rationale inevents-map.ts(ACPStopReasonhas nofailedvariant, so the failure is only logged). - Downstream: MoonshotAI/kimi-code#1855 (usage). Multica has landed a defensive daemon-side workaround (promote completed+empty+no-usage → failed), but the robust fix belongs here.
I traced #1813 and #1865 to the same turn.ended(reason: "failed") branch.
Proposed contract:
- keep auth failures as
authRequired (-32000); - keep provider filtering and hook blocks as
refusal; - reject other failed turns with
internalError (-32603); - expose only
{ code, retryable, statusCode? }inerror.data, never the provider message, full details, request ID, or stack.
I will cover both event-delivered failures and prompt rejections over the real ACP JSON-RPC connection, including a resumed-session regression. I am treating #2037 as related rather than fixed unless its missing-terminal-event path can be reproduced separately.
Does this error shape match the intended ACP contract?
Another reproduction, this time for quota exhaustion, seen from an ACP client (T3 Code driving kimi as an ACP agent). Kimi Code 2.5.2, Windows 11, model kimi-code/k3.1-pro.
In a single session, 4 turns hit the 5-hour usage limit. Every one of them reached the client as a normal end_turn, so the client marked each turn as completed successfully.
The session's wire.jsonl records each failure correctly:
{"type":"turn.ended","turnId":10,"reason":"failed","error":{"code":"provider.api_error","message":"You've reached your 5-hour usage limit. Your quota will reset when the current 5-hour window ends. ...","name":"APIProviderQuotaExhaustedError","details":{"statusCode":429, ...}}}
{"type":"prompt.completed","finishedAt":"2026-11-11T14:42:27.329Z","reason":"failed"}
The client recorded that same turn as completed at 14:42:27.330Z, with no content and no error. The timing lines up at all 4 failures (02:57, 12:06, 14:42, 17:37 UTC). The cause is turnEndReasonToStopReason in the ACP adapter: it maps failed to end_turn, and only auth errors are rejected.
What users see:
- Quota runs out mid-turn: the agent stops partway through a task, and the client shows its last progress message as if it were the final answer.
- Prompting while still over quota: an empty reply within 2 to 4 seconds, shown as a successful completion.
Neither case gives the user any hint that the quota is the problem. For quota specifically, a distinguishable error (e.g. a retryable flag, or the HTTP status as in the contract proposed above) would let clients show "usage limit reached, resets at …" instead of failing silently. +1 for #3161.
Small related bug in the same path: the matching agent.turn.ended event stores the error as the literal text "errorMessage": "[object Object]", so the error object is being stringified with String() somewhere.
Additional reproduction and a focused fix
I can reproduce the non-auth failure path on current main with a deterministic invalid provider. I also have a small patch ready with real ACP turn coverage.
Environment
- Kimi Code:
2.6.2 - Platform:
Darwin 27.3.0 arm64 arm - Authentication: Kimi Code managed OAuth login (no plan-specific claim)
- Model: local default selected in the existing Kimi configuration
Self-contained reproduction
Use an isolated KIMI_CODE_HOME with this provider configuration:
default_model = "test/fail"
[providers.test]
type = "openai"
base_url = "http://127.0.0.1:9/v1"
api_key = "dummy"
[models."test/fail"]
provider = "test"
model = "test-model"
max_context_size = 8192
capabilities = ["tool_use"]
[loop_control]
max_attempts_per_step = 1
max_steps_per_turn = 1
Then drive kimi acp through the normal public methods:
initializewithprotocolVersion: 1.session/newwith a disposablecwdandmcpServers: [].session/set_config_optionwithconfigId: 'mode', value: 'auto'.session/set_config_optionwithconfigId: 'model', value: 'test/fail'.session/promptwith a short text prompt.
Before the fix, the non-auth provider failure resolves as stopReason: 'end_turn', which is indistinguishable from a successful turn.
Proposed fix and test coverage
Reject non-filtered failed turns with RequestError.internalError(undefined, 'Turn failed'), matching the contract proposed earlier in this issue. Authentication failures keep auth_required, and provider.filtered remains refusal.
The patch adds real TurnEnded event-bus regressions asserting:
- Non-auth failure returns exactly
{ code: -32603, message: 'Internal error: Turn failed' }, with no provider message or stack exposure. provider.filteredresolves asrefusal.provider.auth_errorpreserves the-32000authentication path and message.
All 161 ACP-server tests pass across 14 files, and ACP typecheck passes. The changeset is a patch-level entry for @moonshot-ai/kimi-code.
Coordination
This is closely related to #1813 and #3107. I am happy to submit the focused fix if maintainers would find it useful, or to provide the reproduction and regression cases if another contributor is already taking it. Please let me know whether this approach matches the intended ACP contract before I open a PR.
Still reproduces on 2.7.2, the latest release (published 2026-11-20). Tested on macOS arm64 with kimi-code/k3.1-pro on a managed subscription at its monthly limit.
kimi -preportsAPIProviderQuotaExhaustedError.- Over
kimi acp, the sequenceinitialize,session/new,session/promptreturns{"stopReason": "end_turn"}, with noagent_message_chunkand no error. - Earlier reports here were on 2.5.2 and 2.6.2.
Two details that are not covered above yet:
- A quota failure partway through a turn looks like a finished answer. In a T3 Code session, the quota ran out after about 4 minutes and roughly 30 tool calls (
turnStep=0.9in the session log). The client gotend_turn, and the turn's last assistant message, a progress note ("I'm checking those sources now"), was shown as the final result. This is the quota version of the partial-output case reported in #3107. - One of the two turn-end events loses the cause. The same session's
wire.jsonlhas the structured error onturn.ended(provider.api_error,APIProviderQuotaExhaustedError). Theagent.turn.endedevent for that turn records"errorMessage": "[object Object]", so anything that reads that event loses the cause.
+1 to the contract linxule proposed: -32603 for non-auth failures, refusal for provider.filtered, and -32000 kept for auth. Could a maintainer /approve this issue so the tested patch can be opened as a PR?
Minimal ACP client used above (Python standard library only)
import json, subprocess, sys, threading, time
p = subprocess.Popen(["kimi", "acp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
out = []
def reader():
for line in p.stdout:
out.append(line.rstrip("\n"))
threading.Thread(target=reader, daemon=True).start()
def send(i, method, params):
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": i, "method": method, "params": params}) + "\n"); p.stdin.flush()
def wait_id(i, t=60):
end = time.time() + t
while time.time() < end:
for l in out:
try:
m = json.loads(l)
except ValueError:
continue
if m.get("id") == i and ("result" in m or "error" in m):
return m
time.sleep(0.2)
send(1, "initialize", {"protocolVersion": 1, "clientCapabilities": {}})
r = wait_id(1); print("init:", "error" in r if r else "timeout")
send(2, "session/new", {"cwd": "/tmp", "mcpServers": []})
r = wait_id(2); sid = (r or {}).get("result", {}).get("sessionId"); print("session:", bool(sid), (r or {}).get("error"))
send(3, "session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": "Reply with OK."}]})
r = wait_id(3, 90)
print("prompt response:", json.dumps(r)[:600])
for l in out:
try:
m = json.loads(l)
except ValueError:
continue
if m.get("method") == "session/update":
u = m["params"].get("update", {})
print("update:", u.get("sessionUpdate"), json.dumps(u.get("content", ""))[:300])
p.terminate()
print("stderr tail:", p.stderr.read()[-400:] if p.poll() is not None else "")
To test a specific release without installing it, replace ["kimi", "acp"] with ["npx", "-y", "@moonshot-ai/[email protected]", "acp"].
Reproduced by Claude Opus 5.5 (Claude Code in T3).
Update on the patch from my earlier comment, rebuilt on current main (packages/acp-server).
One correction: it now follows the contract shizhigu proposed, including sanitized error.data, which my earlier comment did not have.
| Turn outcome | session/prompt result |
|---|---|
| Non-auth failure | JSON-RPC -32603, Internal error: Turn failed, data: { code, retryable, statusCode? } |
| Auth failure | -32000, unchanged |
provider.filtered |
stopReason: refusal, unchanged |
data carries only typed fields of the normalized error. The provider message, request ID, trace ID, details and stack are never included, and the tests assert that.
Five regression tests drive a real ACP connection against the testkit fake model: HTTP 400, HTTP 429, 401, filtered, and a resumed session with an empty assistant message. Three fail on main and pass with the patch. ACP typecheck, pnpm run lint and the changeset check pass. The ACP suite is 166/167; the remaining failure (session/delete in lifecycle.test.ts) also fails on main for me.
The change is about 30 lines in session.ts. I can push the branch or paste the diff here if that helps.
Could a maintainer /approve this issue so I can open the PR? If the team would rather fix this internally, I'm glad to hand over the tests instead.