@devries-cameron20 / t3code-1 / commits / d68a2fa673
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): a Kimi turn that fails after a tool call now shows as failed (#37555)

Julius Marminge committed Nov 15, 2026 at 23:59 UTC d68a2fa6734a4889b6f3f89ea7ad71a514a814a9
3 files changed +209
packages/provider-acp-registry/src/server/adapter.ts
+9
@@ -10,6 +10,7 @@ import {
10 devinAnswerablePermissionOptions,
11 } from "./devinAcp.ts";
12 import { extractDroidElicitationForm } from "./droidAcp.ts";
13 +import { makeKimiPromptOutcomeWatch } from "./kimiAcp.ts";
14 import { extractOmpElicitationForm } from "./ompAcp.ts";
15 import { extractOpenCodeElicitationForm } from "./opencodeAcp.ts";
16 import {
@@ -206,6 +207,10 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
207 registryAgentId === "github-copilot-cli" ||
208 (options.settings.source === "local" &&
209 /^copilot(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
210 + const isKimi =
211 + registryAgentId === "kimi-code" ||
212 + (options.settings.source === "local" &&
213 + /^kimi(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
214 const isClaude =
215 registryAgentId === "claude-acp" ||
216 (options.settings.source === "local" &&
@@ -222,6 +227,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
227 },
228 }
229 : options;
230 + const watchKimiPromptOutcome = isKimi
231 + ? yield* makeKimiPromptOutcomeWatch(options.environment.KIMI_CODE_HOME)
232 + : undefined;
233 const copilotRouting = isCopilot ? makeCopilotSubagentRouting() : undefined;
234 // Copilot CLI 1.0.105 rejects stdio MCP servers from the client, and Command Code cannot
235 // start the stdio bridge on Windows (it spawns MCP commands through cmd.exe, which splits
@@ -249,6 +257,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
257 : {}),
258 // glm-acp-agent is the one agent whose per-turn usage a live probe has verified.
259 ...(registryAgentId === "glm-acp-agent" ? { reportsPerTurnPromptUsage: true } : {}),
260 + ...(watchKimiPromptOutcome === undefined ? {} : { watchPromptOutcome: watchKimiPromptOutcome }),
261 ...(registryAgentId === "mistral-vibe"
262 ? { registerExtensions: registerMistralVibeAcpExtensions }
263 : {}),
packages/provider-acp-registry/src/server/kimiAcp.test.ts new
+66
@@ -0,0 +1,66 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { assert, it } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import * as Fiber from "effect/Fiber";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Path from "effect/Path";
7 +import * as TestClock from "effect/testing/TestClock";
8 +
9 +import { makeKimiPromptOutcomeWatch } from "./kimiAcp.ts";
10 +
11 +const SESSION_ID = "session_06abd65a-ab8c-4f7a-a504-9b105fc7cd0d";
12 +const endTurn = { stopReason: "end_turn" } as const;
13 +// Records trimmed from Kimi Code 2.5.3's wire.jsonl after the follow-up model request failed.
14 +const failedTurn = (turnId: number) =>
15 + JSON.stringify({
16 + type: "turn.ended",
17 + agentId: "main",
18 + turnId,
19 + reason: "failed",
20 + error: {
21 + code: "provider.overloaded",
22 + message: "upstream overloaded",
23 + name: "APIProviderOverloadedError",
24 + details: { statusCode: 500 },
25 + retryable: true,
26 + },
27 + durationMs: 138873,
28 + time: 1794813146537,
29 + }) + "\n";
30 +const completedTurn = (turnId: number) =>
31 + JSON.stringify({ type: "turn.ended", agentId: "main", turnId, reason: "completed" }) + "\n";
32 +
33 +it.layer(NodeServices.layer)("makeKimiPromptOutcomeWatch", (it) => {
34 + it.effect("fails only the turn this prompt ended, once Kimi writes its outcome", () =>
35 + Effect.gen(function* () {
36 + const fileSystem = yield* FileSystem.FileSystem;
37 + const path = yield* Path.Path;
38 + const home = yield* fileSystem.makeTempDirectoryScoped();
39 + const agentDirectory = path.join(home, "sessions", "wd_proj_1", SESSION_ID, "agents", "main");
40 + yield* fileSystem.makeDirectory(agentDirectory, { recursive: true });
41 + const wire = path.join(agentDirectory, "wire.jsonl");
42 + // An earlier turn's failure is history, not this prompt's outcome.
43 + yield* fileSystem.writeFileString(wire, failedTurn(0));
44 + const append = (text: string) => fileSystem.writeFileString(wire, text, { flag: "a" });
45 + const watch = yield* makeKimiPromptOutcomeWatch(home);
46 +
47 + const completed = yield* watch(SESSION_ID);
48 + yield* append(completedTurn(1));
49 + assert.isUndefined(yield* completed(endTurn));
50 +
51 + // Kimi answers the prompt before `turn.ended` reaches disk.
52 + const failed = yield* watch(SESSION_ID);
53 + const pending = yield* failed(endTurn).pipe(Effect.forkChild);
54 + yield* append(failedTurn(2).slice(0, 40));
55 + yield* TestClock.adjust("50 millis");
56 + yield* append(failedTurn(2).slice(40));
57 + yield* TestClock.adjust("50 millis");
58 + assert.deepStrictEqual(yield* Fiber.join(pending), {
59 + class: "provider_error",
60 + message: "upstream overloaded",
61 + code: "provider.overloaded",
62 + retryable: true,
63 + });
64 + }),
65 + );
66 +});
packages/provider-acp-registry/src/server/kimiAcp.ts new
+134
@@ -0,0 +1,134 @@
1 +import type { OrchestrationV2ProviderFailure } from "@t3tools/contracts";
2 +import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
3 +import * as HostProcess from "@t3tools/shared/HostProcess";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Option from "effect/Option";
7 +import * as Path from "effect/Path";
8 +import * as Schedule from "effect/Schedule";
9 +import * as Schema from "effect/Schema";
10 +import type * as EffectAcpSchema from "effect-acp/compat";
11 +
12 +const NATIVE_SESSION_ID = /^[\w-]+$/;
13 +const READ_CHUNK_BYTES = 65_536;
14 +
15 +const KimiTurnEnded = Schema.fromJsonString(
16 + Schema.Struct({
17 + type: Schema.Literal("turn.ended"),
18 + agentId: Schema.Literal("main"),
19 + reason: Schema.String,
20 + error: Schema.optional(
21 + Schema.Struct({
22 + code: Schema.optional(Schema.String),
23 + message: Schema.optional(Schema.String),
24 + retryable: Schema.optional(Schema.Boolean),
25 + }),
26 + ),
27 + }),
28 +);
29 +const decodeTurnEnded = Schema.decodeUnknownOption(KimiTurnEnded);
30 +type KimiTurnEnded = typeof KimiTurnEnded.Type;
31 +
32 +class KimiTurnNotEnded extends Schema.TaggedError<KimiTurnNotEnded>()("KimiTurnNotEnded", {}) {}
33 +
34 +const noOutcome = (_result: EffectAcpSchema.PromptResponse) =>
35 + Effect.succeed<OrchestrationV2ProviderFailure | undefined>(undefined);
36 +
37 +function turnFailure(ended: KimiTurnEnded): OrchestrationV2ProviderFailure | undefined {
38 + if (ended.reason !== "failed") return undefined;
39 + const code = ended.error?.code;
40 + return makeProviderFailure({
41 + message: ended.error?.message ?? "Kimi stopped this turn because of an error.",
42 + code: code ?? null,
43 + class:
44 + code === "provider.rate_limit"
45 + ? "usage_limit"
46 + : code === "provider.connection_error"
47 + ? "transport_error"
48 + : "provider_error",
49 + retryable: ended.error?.retryable ?? null,
50 + });
51 +}
52 +
53 +/**
54 + * Kimi Code (2.5.3, 2.6.1) answers a failed turn with `end_turn` and no error. Its main
55 + * agent's `wire.jsonl` records the real outcome, so the check reads the `turn.ended`
56 + * this prompt appended.
57 + */
58 +export const makeKimiPromptOutcomeWatch = Effect.fn("KimiTurnOutcome.make")(function* (
59 + configuredHome: string | undefined,
60 +) {
61 + const fileSystem = yield* FileSystem.FileSystem;
62 + const path = yield* Path.Path;
63 + const sessionsDirectory = path.join(
64 + configuredHome || path.join(yield* HostProcess.HomeDirectory, ".kimi-code"),
65 + "sessions",
66 + );
67 +
68 + return Effect.fn("KimiTurnOutcome.watch")(function* (sessionId: string) {
69 + if (!NATIVE_SESSION_ID.test(sessionId)) return noOutcome;
70 + const wirePath = (workspace: string) =>
71 + path.join(sessionsDirectory, workspace, sessionId, "agents", "main", "wire.jsonl");
72 + const findWire = fileSystem.readDirectory(sessionsDirectory).pipe(
73 + Effect.flatMap((workspaces) =>
74 + Effect.findFirst(workspaces, (workspace) => fileSystem.exists(wirePath(workspace))),
75 + ),
76 + Effect.map(Option.map(wirePath)),
77 + Effect.orElseSucceed(() => Option.none<string>()),
78 + );
79 + const before = yield* findWire;
80 + const startOffset = Option.isSome(before)
81 + ? yield* fileSystem.stat(before.value).pipe(
82 + Effect.map((info) => info.size),
83 + Effect.orElseSucceed(() => 0n),
84 + )
85 + : 0n;
86 +
87 + return Effect.fn("KimiTurnOutcome.check")(function* (result: EffectAcpSchema.PromptResponse) {
88 + if (result.stopReason !== "end_turn") return undefined;
89 + // A new session's log can first appear with its first prompt.
90 + const wire = Option.isSome(before) ? before : yield* findWire;
91 + if (Option.isNone(wire)) return undefined;
92 + let offset = startOffset;
93 + let ended: KimiTurnEnded | undefined;
94 + // Each poll decodes only the complete lines appended since the last one.
95 + const readAppended = Effect.scoped(
96 + Effect.gen(function* () {
97 + const file = yield* fileSystem.open(wire.value, { flag: "r" });
98 + const chunks: Array<Uint8Array> = [];
99 + let position = offset;
100 + while (true) {
101 + const chunk = yield* file.readAlloc(READ_CHUNK_BYTES, { position });
102 + if (Option.isNone(chunk) || chunk.value.length === 0) break;
103 + chunks.push(chunk.value);
104 + position += BigInt(chunk.value.length);
105 + }
106 + const bytes = Buffer.concat(chunks);
107 + const complete = bytes.lastIndexOf(0x0a) + 1;
108 + offset += BigInt(complete);
109 + for (const line of bytes.subarray(0, complete).toString("utf8").split("\n")) {
110 + if (!line.includes('"turn.ended"')) continue;
111 + const record = decodeTurnEnded(line);
112 + if (Option.isSome(record)) ended = record.value;
113 + }
114 + if (ended === undefined) return yield* new KimiTurnNotEnded();
115 + return ended;
116 + }),
117 + );
118 + // Kimi writes `turn.ended` on a microtask after it answers the prompt.
119 + return yield* readAppended.pipe(
120 + Effect.retry({
121 + times: 40,
122 + schedule: Schedule.spaced("50 millis"),
123 + while: (error) => error._tag === "KimiTurnNotEnded",
124 + }),
125 + Effect.map(turnFailure),
126 + Effect.catch(() =>
127 + Effect.logWarning("Kimi's session log has no outcome for this turn.").pipe(
128 + Effect.as(undefined),
129 + ),
130 + ),
131 + );
132 + });
133 + });
134 +});