The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 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 | }); |