Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(observability): log compaction failure request shapes

vastsac915f72eb4f1
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index 58098e73b..4cc39c34d 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -248,6 +248,36 @@ export function createSidecarRuntime({
} satisfies AgentEventEnvelope);
}
}
+ if (method === "agent.diagnostic") {
+ const diagnostic = params as {
+ kind?: unknown;
+ sessionId?: unknown;
+ turnId?: unknown;
+ requestId?: unknown;
+ data?: unknown;
+ };
+ if (
+ (diagnostic.kind === "compaction_failure" || diagnostic.kind === "compaction_shape") &&
+ typeof diagnostic.sessionId === "string" &&
+ typeof diagnostic.requestId === "string" &&
+ diagnostic.data && typeof diagnostic.data === "object"
+ ) {
+ const isFailure = diagnostic.kind === "compaction_failure";
+ logger.app(
+ "session",
+ isFailure ? "warn" : "info",
+ isFailure ? "context compaction failed" : "context compaction request shape",
+ {
+ sessionId: diagnostic.sessionId,
+ ...(typeof diagnostic.turnId === "string" ? { turnId: diagnostic.turnId } : {}),
+ requestId: diagnostic.requestId,
+ event: isFailure ? "session.compaction.failed" : "session.compaction.request_shape",
+ data: diagnostic.data,
+ },
+ );
+ }
+ return;
+ }
// permissions.request reaches the renderer once, via wireHost; the
// sidecar no longer relays it (agent-sidecar.setHost filters it out).
});
diff --git a/docs/spec/03-runtime/09-logging-and-observability.md b/docs/spec/03-runtime/09-logging-and-observability.md
index e23646949..cd2eecbac 100644
--- a/docs/spec/03-runtime/09-logging-and-observability.md
+++ b/docs/spec/03-runtime/09-logging-and-observability.md
@@ -141,6 +141,15 @@ record.
- host/agent spawn, handshake, and unexpected exit;
- session create/delete;
- prompt accepted/aborted;
+- failed context compaction: one `session.compaction.failed` record and one
+ `session.compaction.request_shape` record per summary request. The failure
+ record carries only provider/model identifiers, closed-vocabulary failure
+ reason, bounded token budgets, status/error codes, and a request-shape state
+ (`observed`, `not_sent`, or `unobserved`). The shape record carries the wire
+ API, bounded top-level field names, role counts, tool count, and numeric
+ output limit (or `omitted`). It never carries prompt text, tool schemas,
+ endpoint URLs, credentials, or provider error prose. Retries and chunked
+ summaries use a fresh request id at every request boundary.
- tool completion/failure/interruption and permission request/decision/cancellation;
- Plan artifact creation, approval, expiry, rejection, execution transition,
and startup interruption;
diff --git a/packages/agent-runtime/src/compaction-diagnostics.test.ts b/packages/agent-runtime/src/compaction-diagnostics.test.ts
new file mode 100644
index 000000000..0e095d0a0
--- /dev/null
+++ b/packages/agent-runtime/src/compaction-diagnostics.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import { compactionRequestShape } from "./compaction-diagnostics.js";
+
+const model = { api: "openai-responses" } as never;
+
+describe("compactionRequestShape", () => {
+ it("records bounded wire shape without message or tool contents", () => {
+ expect(
+ compactionRequestShape({
+ model,
+ payload: {
+ model: "secret-model-name-is-not-copied",
+ input: [{ role: "user", content: "private prompt" }],
+ max_output_tokens: 4096,
+ authorization: "Bearer secret",
+ },
+ messages: [
+ { role: "user" },
+ { role: "assistant" },
+ { role: "toolResult" },
+ ],
+ tools: [{ name: "private-tool" }],
+ }),
+ ).toEqual({
+ api: "openai-responses",
+ topLevelFields: ["model", "input", "max_output_tokens", "authorization"],
+ roleCounts: { user: 1, assistant: 1, toolResult: 1 },
+ toolCount: 1,
+ outputLimit: 4096,
+ });
+ });
+
+ it("reports omitted output limits and ignores invalid field names", () => {
+ expect(
+ compactionRequestShape({
+ model,
+ payload: { "x bad": true, valid_field: true },
+ messages: [],
+ }),
+ ).toMatchObject({
+ topLevelFields: ["valid_field"],
+ outputLimit: "omitted",
+ toolCount: 0,
+ });
+ });
+});
diff --git a/packages/agent-runtime/src/compaction-diagnostics.ts b/packages/agent-runtime/src/compaction-diagnostics.ts
new file mode 100644
index 000000000..08a9a3d05
--- /dev/null
+++ b/packages/agent-runtime/src/compaction-diagnostics.ts
@@ -0,0 +1,45 @@
+import type { Model, Api } from "@earendil-works/pi-ai";
+
+export type CompactionRequestShape = {
+ api: string;
+ topLevelFields: string[];
+ roleCounts: Record<string, number>;
+ toolCount: number;
+ outputLimit: number | "omitted";
+};
+
+const MAX_FIELDS = 32;
+const FIELD_RE = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;
+
+function outputLimit(payload: Record<string, unknown>): number | "omitted" {
+ for (const key of ["max_output_tokens", "max_tokens", "max_tokens_to_sample"]) {
+ const value = payload[key];
+ if (typeof value === "number" && Number.isFinite(value)) return value;
+ }
+ return "omitted";
+}
+export function compactionRequestShape(input: {
+ model: Model<Api>;
+ payload: unknown;
+ messages: readonly { role?: unknown }[];
+ tools?: readonly unknown[];
+}): CompactionRequestShape {
+ const payloadRecord =
+ input.payload && typeof input.payload === "object" && !Array.isArray(input.payload)
+ ? (input.payload as Record<string, unknown>)
+ : {};
+ const roleCounts: Record<string, number> = {};
+ for (const message of input.messages) {
+ if (typeof message.role !== "string") continue;
+ roleCounts[message.role] = (roleCounts[message.role] ?? 0) + 1;
+ }
+ return {
+ api: input.model.api,
+ topLevelFields: Object.keys(payloadRecord)
+ .filter((field) => FIELD_RE.test(field))
+ .slice(0, MAX_FIELDS),
+ roleCounts,
+ toolCount: input.tools?.length ?? 0,
+ outputLimit: outputLimit(payloadRecord),
+ };
+}
diff --git a/packages/agent-runtime/src/compaction-request.test.ts b/packages/agent-runtime/src/compaction-request.test.ts
index 19858579c..1702b1dfa 100644
--- a/packages/agent-runtime/src/compaction-request.test.ts
+++ b/packages/agent-runtime/src/compaction-request.test.ts
@@ -136,6 +136,39 @@ describe("withCompactionRequestHeaders", () => {
expect(wrapped.getModel("row-uuid", "glm-5.3-flash")).toBe(model);
expect(getModel).toHaveBeenCalledWith("row-uuid", "glm-5.3-flash");
});
+
+ it("reports the bounded payload shape for every wire API", async () => {
+ const completeSimple = vi.fn(
+ async (_model: Model<Api>, _context: unknown, options: ModelsSimpleStreamOptions) => {
+ await options.onPayload?.(
+ { messages: [{ role: "user", content: "private" }], max_tokens: 512 },
+ model,
+ );
+ return "assistant-message";
+ },
+ );
+ const shapes: unknown[] = [];
+ const collection = { completeSimple } as unknown as Models;
+ const wrapped = withCompactionRequestHeaders(
+ collection,
+ provider,
+ "session-1",
+ undefined,
+ (shape) => shapes.push(shape),
+ );
+
+ await wrapped.completeSimple(model, { messages: [{ role: "user" }] } as never);
+
+ expect(shapes).toEqual([
+ {
+ api: "openai-completions",
+ topLevelFields: ["messages", "max_tokens"],
+ roleCounts: { user: 1 },
+ toolCount: 0,
+ outputLimit: 512,
+ },
+ ]);
+ });
});
describe("compaction summary conversation key", () => {
diff --git a/packages/agent-runtime/src/compaction-request.ts b/packages/agent-runtime/src/compaction-request.ts
index d12052ac2..708d4e35e 100644
--- a/packages/agent-runtime/src/compaction-request.ts
+++ b/packages/agent-runtime/src/compaction-request.ts
@@ -30,6 +30,7 @@ import {
type RuntimeProviderConfig,
} from "./provider-binding.js";
import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";
+import { compactionRequestShape, type CompactionRequestShape } from "./compaction-diagnostics.js";
/**
* The header set `streamFn` puts on a turn, applied to a summary request.
@@ -107,12 +108,13 @@ export function withCompactionRequestHeaders(
provider: RuntimeProviderConfig,
sessionId: string,
onUsage?: UsageObserver,
+ onRequestShape?: (shape: CompactionRequestShape) => void,
): Models {
const completeSimple: Models["completeSimple"] = async (model, context, options) => {
const identity = { ...requestUsageIdentity(model, provider.id), costStatus: nativeCostStatus(provider.modelConfig?.nativeCost) };
const requestOptions = compactionRequestOptions({ provider, sessionId, model, context, options });
const previousOnPayload = requestOptions.onPayload;
- if (SUMMARY_CONVERSATION_APIS.has(model.api)) {
+ if (SUMMARY_CONVERSATION_APIS.has(model.api) || onRequestShape) {
requestOptions.onPayload = async (payload, requestModel) => {
const replacement = await previousOnPayload?.(payload, requestModel);
const base = replacement === undefined ? payload : replacement;
@@ -123,6 +125,12 @@ export function withCompactionRequestHeaders(
});
// Nothing to change keeps the hook's own return value, so an untouched
// payload stays the adapter's object instead of a copy of it.
+ onRequestShape?.(compactionRequestShape({
+ model: requestModel,
+ payload: keyed ?? base,
+ messages: context.messages,
+ tools: (context as Context & { tools?: readonly unknown[] }).tools,
+ }));
return keyed === base ? replacement : keyed;
};
}
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 98aa572dd..64a28cc64 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -214,6 +214,7 @@ import {
withOpenCodeSessionHeaders,
} from "./opencode-session-headers.js";
import { withCompactionRequestHeaders } from "./compaction-request.js";
+import type { CompactionRequestShape } from "./compaction-diagnostics.js";
import {
addSummaryUsage,
compactionSummaryInputLimit,
@@ -951,6 +952,8 @@ export type AgentRuntimeOptions = {
* a second containment root. */
scratchDir?: string;
onEvent: (envelope: AgentEventEnvelope) => void;
+ /** Bounded diagnostics routed to the Electron logger, never the transcript. */
+ onDiagnostic?: (diagnostic: AgentRuntimeDiagnostic) => void;
/**
* Subagent definitions this session may delegate to (ADR 0062), already
* merged and capped by Electron main. Empty means no `Task` tool at all.
@@ -967,6 +970,14 @@ export type AgentRuntimeOptions = {
subagentModelKeys?: string[];
};
+export type AgentRuntimeDiagnostic = {
+ kind: "compaction_failure" | "compaction_shape";
+ sessionId: string;
+ turnId?: string;
+ requestId: string;
+ data: Record<string, unknown>;
+};
+
export type RuntimeMatchConfig = {
mode: Mode;
provider: RuntimeProviderConfig;
@@ -1595,6 +1606,7 @@ export class DesktopAgentRuntime {
private thinkingLevel: SessionThinkingLevel;
private host: RuntimeHost;
private onEvent: (envelope: AgentEventEnvelope) => void;
+ private onDiagnostic: (diagnostic: AgentRuntimeDiagnostic) => void;
private streamSink: StreamCoalescer;
private baseSystemPrompt: string;
private customSystemPrompt?: CustomSystemPrompt;
@@ -1793,6 +1805,13 @@ export class DesktopAgentRuntime {
private activeToolProgressCleanups = new Set<(flush: boolean) => void>();
private hostCloseUnsubscribe?: () => void;
private turnSubagentUsage?: MessageUsage;
+ private compactionRequestShape?: CompactionRequestShape;
+ private compactionShapeLogged = false;
+ private compactionDiagnosticBudget?: {
+ hardLimit: number;
+ outputBudget: number;
+ plannedChunks: number;
+ };
constructor(opts: AgentRuntimeOptions) {
this.sessionId = opts.sessionId;
@@ -1803,6 +1822,7 @@ export class DesktopAgentRuntime {
this.thinkingLevel = clampThinkingLevel(opts.provider, opts.thinkingLevel);
this.infiniteProviderRetry = opts.infiniteProviderRetry === true;
this.host = opts.host;
+ this.onDiagnostic = opts.onDiagnostic ?? (() => undefined);
this.hostCloseUnsubscribe = this.host.onClose?.(() => {
this.cleanupActiveToolProgress();
});
@@ -6420,6 +6440,55 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
});
}
+ private emitCompactionDiagnostic(
+ kind: AgentRuntimeDiagnostic["kind"],
+ requestId: string,
+ data: Record<string, unknown>,
+ ): void {
+ this.onDiagnostic({
+ kind,
+ sessionId: this.sessionId,
+ ...(this.turnId ? { turnId: this.turnId } : {}),
+ requestId,
+ data,
+ });
+ }
+
+ private emitCompactionFailureDiagnostic(
+ requestId: string,
+ reason: CompactionFailureReason,
+ tokensBefore: number | undefined,
+ error: unknown,
+ extra: Record<string, unknown> = {},
+ ): void {
+ if (!this.compactionShapeLogged) {
+ this.emitCompactionDiagnostic("compaction_shape", requestId, {
+ requestShape: extra.requestShape ?? "unobserved",
+ ...(this.compactionRequestShape ?? {}),
+ });
+ this.compactionShapeLogged = true;
+ }
+ const candidate = error as {
+ code?: unknown;
+ details?: { providerStatus?: unknown; requestId?: unknown };
+ };
+ this.emitCompactionDiagnostic("compaction_failure", requestId, {
+ provider: this.provider.id,
+ model: this.provider.modelId,
+ reason,
+ ...(typeof candidate.code === "string" ? { errorCode: candidate.code } : {}),
+ ...(typeof candidate.details?.providerStatus === "number"
+ ? { httpStatus: candidate.details.providerStatus }
+ : {}),
+ ...(typeof candidate.details?.requestId === "string"
+ ? { upstreamRequestId: candidate.details.requestId }
+ : {}),
+ ...(tokensBefore !== undefined ? { tokensBefore } : {}),
+ ...(this.compactionDiagnosticBudget ?? {}),
+ ...extra,
+ });
+ }
+
private reasoningReplayIdentity(): ReasoningReplayIdentity {
const requiresCompletionsReasoningReplay =
@@ -6873,23 +6942,53 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
signal: AbortSignal,
): Promise<Awaited<ReturnType<typeof compact>>> {
const usageTurnId = this.turnId;
- return compact(
- preparation,
- // The summary is a provider request like any other turn, but
- // pi-agent-core builds its options itself and never reaches `streamFn`,
- // so the headers have to ride on the collection.
- withCompactionRequestHeaders(this.models, this.provider, this.sessionId,
- usage => this.emit({ type: "usage", usage }, usageTurnId)),
- this.model,
- undefined,
- agentThinkingLevel(this.thinkingLevel),
- // Without a policy pi-ai returns the first failed response as-is, which
- // made a single dropped stream or 503 discard the whole summary (#543).
- // pi's classifier decides what is transient; the waits honour `signal`.
- COMPACTION_SUMMARY_RETRY_POLICY,
- undefined,
- withAbortSignal(signal, BACKGROUND_CONTEXT),
+ const requestId = randomUUID();
+ this.compactionRequestShape = undefined;
+ this.compactionShapeLogged = false;
+ const models = withCompactionRequestHeaders(
+ this.models,
+ this.provider,
+ this.sessionId,
+ (usage) => this.emit({ type: "usage", usage }, usageTurnId),
+ (shape) => {
+ this.compactionRequestShape = shape;
+ this.compactionShapeLogged = true;
+ this.emitCompactionDiagnostic("compaction_shape", requestId, {
+ requestShape: "observed",
+ ...shape,
+ });
+ },
);
+ try {
+ const result = await compact(
+ preparation,
+ // The summary is a provider request like any other turn, but
+ // pi-agent-core builds its options itself and never reaches `streamFn`,
+ // so the headers have to ride on the collection.
+ models,
+ this.model,
+ undefined,
+ agentThinkingLevel(this.thinkingLevel),
+ // Without a policy pi-ai returns the first failed response as-is, which
+ // made a single dropped stream or 503 discard the whole summary (#543).
+ // pi's classifier decides what is transient; the waits honour `signal`.
+ COMPACTION_SUMMARY_RETRY_POLICY,
+ undefined,
+ withAbortSignal(signal, BACKGROUND_CONTEXT),
+ );
+ if (!result.ok) {
+ this.emitCompactionFailureDiagnostic(
+ requestId,
+ "summary_provider",
+ preparation.tokensBefore,
+ result.error,
+ );
+ }
+ return result;
+ } catch (error) {
+ this.emitCompactionFailureDiagnostic(requestId, "summary_provider", preparation.tokensBefore, error);
+ throw error;
+ }
}
/**
@@ -6949,6 +7048,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
signal: AbortSignal,
retentionMode: CompactionRetentionMode,
): Promise<CheckpointBuild> {
+ this.compactionDiagnosticBudget = undefined;
const entries = this.entriesWithCompaction();
const context = buildSessionContext(entries, this.reasoningReplayIdentity());
const budget = this.contextBudget(context.messages);
@@ -6959,6 +7059,21 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
retentionMode,
);
if (!preparation.ok || !preparation.value) {
+ this.emitCompactionFailureDiagnostic(
+ randomUUID(),
+ preparation.ok ? "no_new_history" : "summary_budget",
+ undefined,
+ preparation.ok ? "No new context is available to compact" : preparation.error,
+ {
+ requestShape: "not_sent",
+ hardLimit: budget.hardLimit,
+ outputBudget: compactionSummaryOutputBudget({
+ requestHeadroom: budget.requestHeadroom,
+ modelMaxTokens: this.model.maxTokens,
+ }),
+ plannedChunks: 0,
+ },
+ );
return {
ok: false,
entries,
@@ -6982,7 +7097,30 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
const chunks = summaryInput
? undefined
: this.planSummaryRequests(preparation.value, budget);
+ this.compactionDiagnosticBudget = {
+ hardLimit: budget.hardLimit,
+ outputBudget: compactionSummaryOutputBudget({
+ requestHeadroom: budget.requestHeadroom,
+ modelMaxTokens: this.model.maxTokens,
+ }),
+ plannedChunks: chunks?.length ?? 1,
+ };
if (!summaryInput && !chunks) {
+ this.emitCompactionFailureDiagnostic(
+ randomUUID(),
+ "summary_budget",
+ preparation.value.tokensBefore,
+ "Compaction summary input exceeds the safe model budget",
+ {
+ requestShape: "not_sent",
+ hardLimit: budget.hardLimit,
+ outputBudget: compactionSummaryOutputBudget({
+ requestHeadroom: budget.requestHeadroom,
+ modelMaxTokens: this.model.maxTokens,
+ }),
+ plannedChunks: 0,
+ },
+ );
return {
ok: false,
entries,
diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.ts
index 0a8ce0a9e..84344b2fc 100644
--- a/packages/agent-runtime/src/sidecar.ts
+++ b/packages/agent-runtime/src/sidecar.ts
@@ -300,6 +300,7 @@ async function runtimeFor(
? params.scratchDir
: undefined,
onEvent: (envelope: AgentEventEnvelope) => notify("agent.event", envelope),
+ onDiagnostic: (diagnostic) => notify("agent.diagnostic", diagnostic),
});
runtimes.set(sessionId, runtime);
// Load failures are diagnostics, never a failed prompt (spec 16 §4.4).