8000 refactor(mcp): bound results with chord output helpers by geminixiang · Pull Request #186 · geminixiang/mikan · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/research/pi-1.3-retirement-2026-10.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Retiring mikan code that Pi 1.3 now provides

All `@earendil-works/*` packages are at 1.3.0, the latest published version, and `src/` has no deep `dist` imports. This note lists mikan code that duplicates a public Pi capability, with each answer's source and the experiment that checked it.

## Findings

| # | mikan code | Pi capability (source) | Experiment | Result |
| --- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | `MikanToolResult` carries `content`; `withLabel` turned Pi's `output` into `content` and `toPiTool` turned it back | `ToolExecutionResult.output` (pi-durable 1.2 CHANGELOG, `dist/harness/types.d.ts`) | Removed both conversions and ran the full suite | Equivalent. `ToolExecutionResult` is a weak type, so TypeScript accepts a result with `content` and Pi then shows the retained `output()` text instead; reverting the subagent tool's `output` fails 13 subagent tests |
| 2 | ~20 tools written as pi-agent-core `AgentTool` and adapted by `adaptAgentTool` | `ToolRegistration` with `api.details`, `api.callId`, `context.abortSignal`, `control.terminate` (pi-durable README, `types.d.ts`) | Rewrote every tool as a `ToolRegistration` and ran the full suite | Equivalent; the adapter only renamed fields, deep-copied `details` through JSON, and defaulted `replay` to Pi's own default `unsafe`. Two tests covered only the adapter (dropping progress `content`, the harness-tool marker) and were removed |
| 3 | `pi-agent-core` is imported only for types | pi-durable does not depend on it; `ThinkingLevel` is exported by `pi-ai` | Replaced the imports and searched every reader | pi-agent-core's `AgentMessage` is pi-ai's `Message` (mikan adds no custom messages) and its `ThinkingLevel` is pi-ai's `ModelThinkingLevel`; the only other reader was `ARCHITECTURE.md`, and no package depends on it transitively |
| 4 | `mcp-result.ts` truncates with its own `headTruncate`/`sliceToBytes` | `boundOutput`, `utf8ByteLength` from `@earendil-works/chord/output` (chord 1.3 CHANGELOG) | Ran `boundOutput` on line, multi-line, and multibyte input; ran the new `mcp-result` tests on `main` and on the change | `boundOutput` keeps the line's trailing newline and counts it in the byte budget; dropping it gives the same text as before on both trees |
| 5 | `JSON.parse(JSON.stringify(x))` copies (`pi-tools.ts`, `mcp-result.ts`, `subagent.ts`, `session-store.ts`) | `copyJson` from `@earendil-works/chord` | `copyJson` on `undefined` properties, array holes, `NaN`, `Date`, functions, and `bigint` | `copyJson` throws on every non-JSON value except `undefined` properties with `omitUndefinedProperties`, where `JSON.stringify` silently converts or drops them. It replaces only the MCP script result, whose input is wire JSON; the other copies take values from arbitrary tools and stay |
| 6 | The presenter times tools with `Date.now()` between start and end events | `pi.tool-result` `durationMs` and `NestedToolExecutionResult.durationMs` (pi-durable 1.1 CHANGELOG, `dist/harness/tool.js`) | Read `tool.js`; asserted `durationMs` on a real faux-provider tool run | Pi measures `execute()` with `performance.now()` and leaves it absent for calls that never ran to a result (aborted, interrupted), so the presenter keeps its wall-clock fallback for those |
| 7 | `compaction_end` looks up the task outcome with `getTask` | `compaction_end.error` (pi-durable 1.2, `dist/harness/events.js`) | Read `events.js` and `live.js` | Not retired: the event carries only `error` from `pi.live.compactionFailure`, which an aborted compaction leaves unchanged, so telling an aborted compaction from a completed one still needs the task outcome |

## Kept local

- `compaction-summary.ts`: Pi 1.3 still does not export the summary wrapper text.
- `generate_image`: `Models.generateImages()` exists, but pi-ai ships only the `openrouter-images` image API.
- The model catalog wrapper for abort logging: pi-durable does not expose provider transport admission.
- The `models.json` reader: Pi packages expose no public loader.
38 changes: 10 additions & 28 deletions src/harness/mcp-result.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { randomBytes } from "node:crypto";
import type { JsonValue } from "@earendil-works/chord";
import { copyJson, type Context, type JsonValue } from "@earendil-works/chord";
import { boundOutput, utf8ByteLength } from "@earendil-works/chord/output";
import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
import type { Context } from "@earendil-works/chord";
import type { ExecutionEnv } from "@earendil-works/pi-durable/env";
import { toLlmContent, type CallToolResult } from "@earendil-works/pi-mcp";
import type { MikanToolResult } from "./types.js";
Expand Down Expand Up @@ -80,29 +80,11 @@ function digest(value: unknown, level: DigestLevel, depth = 0): unknown {
}

function fits(text: string, limits: McpTextLimits): boolean {
return (
Buffer.byteLength(text, "utf8") <= limits.maxBytes && text.split("\n").length <= limits.maxLines
);
}

function sliceToBytes(text: string, maxBytes: number): string {
const buffer = Buffer.from(text, "utf8");
if (buffer.length <= maxBytes) return text;
let end = Math.max(0, maxBytes);
while (end > 0 && (buffer[end]! & 0xc0) === 0x80) end--;
return buffer.subarray(0, end).toString("utf8");
return utf8ByteLength(text) <= limits.maxBytes && text.split("\n").length <= limits.maxLines;
}

function headTruncate(text: string, limits: McpTextLimits): string {
const kept: string[] = [];
let bytes = 0;
for (const line of text.split("\n").slice(0, limits.maxLines)) {
const lineBytes = Buffer.byteLength(line, "utf8") + (kept.length > 0 ? 1 : 0);
if (bytes + lineBytes > limits.maxBytes) break;
kept.push(line);
bytes += lineBytes;
}
return kept.length === 0 ? sliceToBytes(text, limits.maxBytes) : kept.join("\n");
return boundOutput(text, { ...limits, retain: "head" }).text.replace(/\n$/, "");
}

function formatSize(bytes: number): string {
Expand All @@ -123,7 +105,7 @@ export function boundMcpText(text: string, limits: McpTextLimits): BoundedMcpTex
if (fits(digested, limits)) return { text: digested, digest: true };
}
const smallest = JSON.stringify(digest(parsed.value, DIGEST_LEVELS.at(-1)!));
return { text: sliceToBytes(smallest, limits.maxBytes), digest: true };
return { text: headTruncate(smallest, limits), digest: true };
}

function compactMcpText(text: string): string {
Expand Down Expand Up @@ -169,14 +151,14 @@ function truncationNotice(
}

function scriptResult(result: CallToolResult): JsonValue {
const copy: JsonValue = JSON.parse(
JSON.stringify({
return copyJson(
{
content: Array.isArray(result.content) ? result.content : [],
structuredContent: result.structuredContent ?? undefined,
isError: result.isError === true ? true : undefined,
}),
},
{ omitUndefinedProperties: true },
);
return copy;
}

export async function guardMcpToolResult(
Expand All @@ -199,7 +181,7 @@ export async function guardMcpToolResult(
return { content: blocks, details: undefined, structuredOutput };
const bounded = boundMcpText(combined, RESULT_LIMITS);
const spillPath = await spillFullResult(env, combined, context);
const notice = truncationNotice(bounded, Buffer.byteLength(combined, "utf8"), spillPath);
const notice = truncationNotice(bounded, utf8ByteLength(combined), spillPath);
return {
content: [{ type: "text", text: `${bounded.text}\n\n${notice}` }, ...images],
details: undefined,
Expand Down
10 changes: 10 additions & 0 deletions src/test/mcp-result.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ describe("boundMcpText", () => {
expect(bounded.text.split("\n").length).toBeLessThanOrEqual(limits.maxLines);
});

it("keeps whole lines without a trailing newline before the notice", () => {
const bounded = boundMcpText("a\nbb\nccc\ndddd", { maxBytes: 9, maxLines: 10 });
expect(bounded).toEqual({ text: "a\nbb\nccc" });
});

it("cuts a single oversized line on a character boundary", () => {
const bounded = boundMcpText("é".repeat(10), { maxBytes: 5, maxLines: 10 });
expect(bounded).toEqual({ text: "éé" });
});

it("fits a single huge string within the byte limit", () => {
const bounded = boundMcpText(JSON.stringify({ html: "<p>".repeat(100_000) }), limits);
expect(bounded.digest).toBe(true);
Expand Down
Loading
0