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
24 changes: 20 additions & 4 deletions src/agent/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { awaitNativeProxyOrigin } from "./native-bootstrap.js";
import { disposeSubagentSelfReg, selfRegisterForSession, type SubagentSelfRegState } from "./pi-subagent-registry.js";
import { isModelApiUrl, nativeInterceptInstalled } from "./native-intercept.js";
import { wirePiSubagents } from "./pi-subagents.js";
import { asciiHeaderValue, detectProxyBase, destinationRoutedThroughProxy, fetchManifest, forwardTool, fetchStatus, fetchProxyVersion, postIdentityRegister, reportRuntimeInfoOnChange, armedIdleNotice, noSessionWarning, nonHttpProvidersFromEnv, type ManifestTool } from "./shared.js";
import { asciiHeaderValue, detectProxyBase, destinationRoutedThroughProxy, fetchManifest, forwardTool, fetchStatus, fetchProxyVersion, postIdentityRegister, reportRuntimeInfoOnChange, armedIdleNotice, noSessionWarning, nonHttpProvidersFromEnv, type ForwardedToolResult, type ManifestTool } from "./shared.js";
import { createForkAdopter } from "./fork-adopt.js";

export type Ctx = {
Expand All @@ -39,7 +39,11 @@ export type Ctx = {
};

type TextBlock = { type: "text"; text: string };
type ToolResult = { content: TextBlock[]; isError?: boolean };
// #2752: `details` is pi's AgentToolResult metadata channel (persisted with the
// session, excluded from model input) — bili uses it to expose the endpoint's
// machine-readable outcome/blocksCreated to analysis tooling. Older pi hosts
// ignore unknown result fields.
type ToolResult = { content: TextBlock[]; isError?: boolean; details?: unknown };

type ToolDefinition = {
name: string;
Expand Down Expand Up @@ -527,6 +531,14 @@ function renderAcpStatus(s: Record<string, unknown>): string {
return lines.join("\n");
}

function outcomeDetailsOf(output: ForwardedToolResult): Record<string, unknown> | undefined {
if (output.outcome === undefined && output.blocksCreated === undefined) return undefined;
const details: Record<string, unknown> = {};
if (output.outcome !== undefined) details.outcome = output.outcome;
if (output.blocksCreated !== undefined) details.blocksCreated = output.blocksCreated;
return details;
}

function manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): ToolDefinition {
return {
name: tool.name,
Expand Down Expand Up @@ -557,8 +569,12 @@ function manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): T
// #2204: a business failure (e.g. a refused export) must reach
// the host as isError — rendering it as plain success text is
// what hid the #2204 write failures from OMP.
if (output.failed) return { content: [{ type: "text", text: output.text }], isError: true };
return { content: [{ type: "text", text: output.text }] };
// #2752: the structured business state rides pi's details channel
// on BOTH branches — a refused/failure receipt carries its
// outcome too, so analysis tooling can classify every call.
const details = outcomeDetailsOf(output);
if (output.failed) return { content: [{ type: "text", text: output.text }], isError: true, details };
return { content: [{ type: "text", text: output.text }], details };
} catch (err) {
return { content: [{ type: "text", text: `bili tool error: ${err instanceof Error ? err.message : String(err)}` }], isError: true };
}
Expand Down
23 changes: 19 additions & 4 deletions src/agent/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
// package as the proxy ⇒ same version ⇒ no kernel-skew bug class.

import { envMillis } from "./native-bootstrap.js";
import { parseBlocksCreated, parseToolOutcome, partialOutcomeNote } from "../proxy-tool-result.js";
import type { ToolOutcomeKind } from "../proxy-tool-result.js";

export type ManifestTool = {
name: string;
Expand Down Expand Up @@ -290,8 +292,11 @@ export async function reportRuntimeInfoOnChange(proxyBase: string | undefined, i
/** #2204: business outcome of a forwarded tool call. ok:true means the tool
* RAN; whether it achieved its effect rides the endpoint's machine-readable
* `outcome` field (#1875). `failed` mirrors mcp.ts's mapping so every host
* lane renders the same receipt the same way. */
export type ForwardedToolResult = { text: string; failed: boolean };
* lane renders the same receipt the same way. #2752: the structured state now
* rides through (defensively parsed) — hosts with a metadata channel expose it
* (pi `details`, MCP `structuredContent`); string-only lanes read the appended
* partial note in `text`. Absent on legacy envelopes without the fields. */
export type ForwardedToolResult = { text: string; failed: boolean; outcome?: ToolOutcomeKind; blocksCreated?: number };

export async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal, nativeCaller: boolean = false): Promise<ForwardedToolResult> {
const body: { conversationId: string; tool: string; args: unknown; nativeCaller?: boolean } = { conversationId, tool, args: args ?? {} };
Expand All @@ -306,11 +311,21 @@ export async function forwardTool(proxyBase: string, conversationId: string, too
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
}, effectiveToolTimeoutMs(proxyBase, tool), signal);
const data = json as { ok?: boolean; result?: string; error?: string; outcome?: string } | undefined;
const data = json as { ok?: boolean; result?: string; error?: string; outcome?: unknown; blocksCreated?: unknown } | undefined;
if (!ok || !data?.ok) {
throw new Error(`bili proxy tool ${tool} failed (${status}): ${data?.error ?? "unknown error"}`);
}
return { text: data.result ?? "", failed: data.outcome === "failure" || data.outcome === "refused" };
const outcome = parseToolOutcome(data.outcome);
const blocksCreated = parseBlocksCreated(data.blocksCreated);
let text = data.result ?? "";
// #2752: a partial fold must stay distinguishable on lanes whose host shape
// carries no structured state — the note rides the text. Applied/refused/
// failure envelopes keep their exact historical bytes (no note).
if (outcome === "partial") text += `\n${partialOutcomeNote(blocksCreated)}`;
const out: ForwardedToolResult = { text, failed: outcome === "failure" || outcome === "refused" };
if (outcome !== undefined) out.outcome = outcome;
if (blocksCreated !== undefined) out.blocksCreated = blocksCreated;
return out;
}

/** Soft-fail by design: the status read is best-effort UI data; undefined
Expand Down
38 changes: 34 additions & 4 deletions src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { isPidAlive, isProxyInstanceFile, readProxyInstanceFile } from "./instance.js";
import { parseBlocksCreated, parseToolOutcome, partialOutcomeNote } from "./proxy-tool-result.js";
import type { ToolOutcomeKind } from "./proxy-tool-result.js";

const VERSION = (() => {
try {
Expand Down Expand Up @@ -143,7 +145,13 @@ function ensureManifest(): Promise<void> {
return manifestPromise;
}

export async function forwardTool(tool: string, args: unknown, timeoutMs: number = TOOL_TIMEOUT_MS, conversationIdOverride: string | undefined = undefined, nativeCaller: boolean = false): Promise<{ text: string; failed: boolean }> {
// #2752: same contract as agent/shared.ts's ForwardedToolResult — the endpoint's
// machine-readable outcome/blocksCreated ride through (defensively parsed) so
// the shim can expose them as MCP structuredContent; `text` carries the appended
// partial note for clients that only render content text.
export type McpForwardedToolResult = { text: string; failed: boolean; outcome?: ToolOutcomeKind; blocksCreated?: number };

export async function forwardTool(tool: string, args: unknown, timeoutMs: number = TOOL_TIMEOUT_MS, conversationIdOverride: string | undefined = undefined, nativeCaller: boolean = false): Promise<McpForwardedToolResult> {
const effectiveConversationId = conversationIdOverride ?? conversationId;
for (let attempt = 0; ; attempt++) {
let res: Response;
Expand All @@ -164,11 +172,23 @@ export async function forwardTool(tool: string, args: unknown, timeoutMs: number
if (err instanceof Error && err.name === "TimeoutError") throw new Error(`tool forward timed out after ${timeoutMs}ms: ${tool}`);
throw err;
}
const data = (await res.json()) as { ok?: boolean; result?: string; error?: string; outcome?: string };
const data = (await res.json()) as { ok?: boolean; result?: string; error?: string; outcome?: unknown; blocksCreated?: unknown };
// #1875: ok:true means the tool RAN; the business effect rides outcome.
// failure/refusal receipts become MCP isError so hosts surface them to
// the model — partial still counts as success.
if (res.ok && data.ok) return { text: data.result ?? "", failed: data.outcome === "failure" || data.outcome === "refused" };
if (res.ok && data.ok) {
const outcome = parseToolOutcome(data.outcome);
const blocksCreated = parseBlocksCreated(data.blocksCreated);
let text = data.result ?? "";
// #2752: same partial-note contract as agent/shared.ts — only a
// partial fold gains the appended line; every other envelope keeps
// its exact historical bytes.
if (outcome === "partial") text += `\n${partialOutcomeNote(blocksCreated)}`;
const out: McpForwardedToolResult = { text, failed: outcome === "failure" || outcome === "refused" };
if (outcome !== undefined) out.outcome = outcome;
if (blocksCreated !== undefined) out.blocksCreated = blocksCreated;
return out;
}
// #656: the shim's captured id was never registered — the host likely
// resumed its session and forked a new id after this shim spawned.
// Adopt the proxy's latest active conversation and retry once. Armed
Expand Down Expand Up @@ -328,7 +348,17 @@ async function handleMessage(msg: {
// genuinely cannot tell. The shim no longer hard-fails here.
try {
const out = await forwardTool(tool, args, effectiveToolTimeoutMs(tool), routeOverride, nativeThreadId !== undefined);
sendResult(id, { content: [{ type: "text", text: out.text }], isError: out.failed });
// #2752: the business state rides MCP structuredContent (spec
// field alongside content; clients predating it ignore it).
// isError semantics are unchanged — partial stays non-error.
const result: Record<string, unknown> = { content: [{ type: "text", text: out.text }], isError: out.failed };
if (out.outcome !== undefined || out.blocksCreated !== undefined) {
const structured: Record<string, unknown> = {};
if (out.outcome !== undefined) structured.outcome = out.outcome;
if (out.blocksCreated !== undefined) structured.blocksCreated = out.blocksCreated;
result.structuredContent = structured;
}
sendResult(id, result);
} catch (err) {
// Protocol failures are results (isError), not JSON-RPC
// errors, so the host surfaces them to the model.
Expand Down
29 changes: 28 additions & 1 deletion src/proxy-tool-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,34 @@
// tool is binary success | failure. Consumers that only know the old envelope
// shape ignore the extra fields and keep working off result text.
type CompressOutcomeKind = "applied" | "partial" | "refused";
type ToolOutcomeKind = CompressOutcomeKind | "success" | "failure";
export type ToolOutcomeKind = CompressOutcomeKind | "success" | "failure";

/** #2752: defensive parse of the endpoint's machine-readable `outcome` field —
* only the known enum values survive; anything else (legacy proxies without
* the field, typos, numbers) degrades to absent so old envelopes keep their
* exact shape and no new behavior is inferred from garbage. */
export function parseToolOutcome(value: unknown): ToolOutcomeKind | undefined {
return value === "applied" || value === "partial" || value === "refused" || value === "success" || value === "failure" ? value : undefined;
}

/** #2752: defensive parse of the endpoint's `blocksCreated` counter — a finite
* non-negative integer only (the kernel emits exactly that); anything else is
* treated as absent rather than forwarded into host-visible structured state. */
export function parseBlocksCreated(value: unknown): number | undefined {
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
}

/** #2752: host-visible marker for a PARTIAL compress fold. The receipt's
* leading line reads as a clean success ("Compressed … → N block(s), … saved")
* with per-range errors riding after it — in large receipts a partial fold is
* indistinguishable from a full one without this line. Appended by the
* forwarding layer (agent/shared.ts + mcp.ts) ONLY when the endpoint reported
* outcome:"partial": applied needs no marker (the leading line says all-folded)
* and refused/failure already surface as isError/throw on every lane. */
export function partialOutcomeNote(blocksCreated?: number): string {
const created = blocksCreated !== undefined ? `${blocksCreated} block(s) created; ` : "";
return `[acp-result: PARTIAL — ${created}some requested range(s) were NOT folded. Retry ONLY the failed range(s) listed above; do not re-fold the ranges that were applied.]`;
}

export interface ProxyToolResult {
text: string;
Expand Down
Loading
Loading