fix(runtime): compact context inside worker
This commit is contained in:
1 parent
33c6ede381
commit
6dfa1a851d
13 files changed
+214
-92
No files matched your search
@@ -12,10 +12,9 @@
|
|||||||
* `buildAgentHooks` collapses the wiring into a single object whose
|
* `buildAgentHooks` collapses the wiring into a single object whose
|
||||||
* shape mirrors the subset of `AgentOptions` that we populate. The
|
* shape mirrors the subset of `AgentOptions` that we populate. The
|
||||||
* factory spreads the result into `new Agent({...})`, so the agent
|
* factory spreads the result into `new Agent({...})`, so the agent
|
||||||
* contract is still the pi-defined one — this is a pure organizational
|
* contract is still the pi-defined one. Tool policy stays routed
|
||||||
* refactor. Behavior (RPC shapes, failure modes, tool-name semantics)
|
* through `WorkerRpcClient`; context compaction runs inside the worker
|
||||||
* is preserved verbatim by routing through the same `WorkerRpcClient`
|
* so the full transcript never crosses the worker-main boundary.
|
||||||
* the factory previously held.
|
|
||||||
*
|
*
|
||||||
* The signatures below are pinned to pi via `pi-hook-contract`: any
|
* The signatures below are pinned to pi via `pi-hook-contract`: any
|
||||||
* drift in `AgentOptions.beforeToolCall` / `afterToolCall` /
|
* drift in `AgentOptions.beforeToolCall` / `afterToolCall` /
|
||||||
@@ -34,21 +33,28 @@ import type {
|
|||||||
AfterToolCallRpcResult,
|
AfterToolCallRpcResult,
|
||||||
BeforeToolCallRpcPayload,
|
BeforeToolCallRpcPayload,
|
||||||
BeforeToolCallRpcResult,
|
BeforeToolCallRpcResult,
|
||||||
TransformContextRpcPayload,
|
|
||||||
TransformContextRpcResult,
|
|
||||||
} from "./hook-rpc";
|
} from "./hook-rpc";
|
||||||
import type { WorkerRpcClient } from "../worker/entry/rpc";
|
import type { WorkerRpcClient } from "../worker/entry/rpc";
|
||||||
|
import {
|
||||||
|
compactMessagesIfNeeded,
|
||||||
|
type CompactionTelemetry,
|
||||||
|
} from "./context-compactor";
|
||||||
|
|
||||||
|
export interface ContextCompactionTelemetry extends CompactionTelemetry {
|
||||||
|
runId: string;
|
||||||
|
emittedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inputs the aggregator needs to produce a hook bundle. `rpc` is the
|
* Inputs the aggregator needs to produce a hook bundle. `rpc` is the
|
||||||
* worker-side RPC client that ships hook invocations back to main
|
* worker-side RPC client that ships policy hook invocations back to
|
||||||
* where the actual policy (approval gate, artifact projection, context
|
* main. `runId` is the routing key main uses to look up the per-run
|
||||||
* compaction) lives. `runId` is the routing key main uses to look up
|
* `ActiveRunContext` in `RuntimeBridge`.
|
||||||
* the per-run `ActiveRunContext` in `RuntimeBridge`.
|
|
||||||
*/
|
*/
|
||||||
export interface AgentHooksDeps {
|
export interface AgentHooksDeps {
|
||||||
runId: string;
|
runId: string;
|
||||||
rpc: WorkerRpcClient;
|
rpc: WorkerRpcClient;
|
||||||
|
onContextCompaction?: (telemetry: ContextCompactionTelemetry) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -74,11 +80,11 @@ export interface AgentHookBundle {
|
|||||||
* must never silently bypass main's approval gate.
|
* must never silently bypass main's approval gate.
|
||||||
* - `afterToolCall`: fail-open RPC. Projection is observational; if
|
* - `afterToolCall`: fail-open RPC. Projection is observational; if
|
||||||
* main cannot be reached the tool result stands unchanged.
|
* main cannot be reached the tool result stands unchanged.
|
||||||
* - `transformContext`: fail-open RPC. The pi contract forbids throws
|
* - `transformContext`: worker-local compaction. The transcript stays
|
||||||
* here, so on RPC failure we return the original transcript.
|
* inside the worker; main receives telemetry only.
|
||||||
*/
|
*/
|
||||||
export function buildAgentHooks(deps: AgentHooksDeps): AgentHookBundle {
|
export function buildAgentHooks(deps: AgentHooksDeps): AgentHookBundle {
|
||||||
const { runId, rpc } = deps;
|
const { runId, rpc, onContextCompaction } = deps;
|
||||||
|
|
||||||
const beforeToolCall: AgentHookBundle["beforeToolCall"] = async (
|
const beforeToolCall: AgentHookBundle["beforeToolCall"] = async (
|
||||||
ctx,
|
ctx,
|
||||||
@@ -129,12 +135,24 @@ export function buildAgentHooks(deps: AgentHooksDeps): AgentHookBundle {
|
|||||||
const transformContext: AgentHookBundle["transformContext"] = async (
|
const transformContext: AgentHookBundle["transformContext"] = async (
|
||||||
messages,
|
messages,
|
||||||
): Promise<AgentMessage[]> => {
|
): Promise<AgentMessage[]> => {
|
||||||
const payload: TransformContextRpcPayload = { messages };
|
try {
|
||||||
const response = await rpc.invoke(runId, "transformContext", payload);
|
const outcome = compactMessagesIfNeeded(messages);
|
||||||
if (!response.ok) return messages;
|
if (outcome.changed && outcome.messages) {
|
||||||
const result = response.result as TransformContextRpcResult;
|
if (outcome.telemetry) {
|
||||||
if (result.changed && result.messages) return result.messages;
|
onContextCompaction?.({
|
||||||
return messages;
|
...outcome.telemetry,
|
||||||
|
runId,
|
||||||
|
emittedAt: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return outcome.messages;
|
||||||
|
}
|
||||||
|
return messages;
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`transformContext compaction failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return { beforeToolCall, afterToolCall, transformContext };
|
return { beforeToolCall, afterToolCall, transformContext };
|
||||||
|
|||||||
@@ -51,6 +51,15 @@ interface MessageLike {
|
|||||||
export interface CompactionOutcome {
|
export interface CompactionOutcome {
|
||||||
changed: boolean;
|
changed: boolean;
|
||||||
messages: AgentMessage[] | null;
|
messages: AgentMessage[] | null;
|
||||||
|
telemetry: CompactionTelemetry | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompactionTelemetry {
|
||||||
|
estimatedTokens: number;
|
||||||
|
originalMessageCount: number;
|
||||||
|
compactedMessageCount: number;
|
||||||
|
compactedOlderMessageCount: number;
|
||||||
|
retainedRecentMessageCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,16 +78,16 @@ export interface CompactionOutcome {
|
|||||||
export function compactMessagesIfNeeded(messages: AgentMessage[]): CompactionOutcome {
|
export function compactMessagesIfNeeded(messages: AgentMessage[]): CompactionOutcome {
|
||||||
const estimatedTokens = estimateTokens(messages);
|
const estimatedTokens = estimateTokens(messages);
|
||||||
if (estimatedTokens < COMPACTION_TRIGGER_TOKENS) {
|
if (estimatedTokens < COMPACTION_TRIGGER_TOKENS) {
|
||||||
return { changed: false, messages: null };
|
return { changed: false, messages: null, telemetry: null };
|
||||||
}
|
}
|
||||||
if (messages.length <= RECENT_MESSAGE_TAIL + 1) {
|
if (messages.length <= RECENT_MESSAGE_TAIL + 1) {
|
||||||
return { changed: false, messages: null };
|
return { changed: false, messages: null, telemetry: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
const desiredCutoff = messages.length - RECENT_MESSAGE_TAIL;
|
const desiredCutoff = messages.length - RECENT_MESSAGE_TAIL;
|
||||||
const cutoff = findSafeCutoff(messages, desiredCutoff);
|
const cutoff = findSafeCutoff(messages, desiredCutoff);
|
||||||
if (cutoff === null) {
|
if (cutoff === null) {
|
||||||
return { changed: false, messages: null };
|
return { changed: false, messages: null, telemetry: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
const older = messages.slice(0, cutoff);
|
const older = messages.slice(0, cutoff);
|
||||||
@@ -91,7 +100,18 @@ export function compactMessagesIfNeeded(messages: AgentMessage[]): CompactionOut
|
|||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
} as AgentMessage;
|
} as AgentMessage;
|
||||||
|
|
||||||
return { changed: true, messages: [summary, ...recent] };
|
const compactedMessages = [summary, ...recent];
|
||||||
|
return {
|
||||||
|
changed: true,
|
||||||
|
messages: compactedMessages,
|
||||||
|
telemetry: {
|
||||||
|
estimatedTokens,
|
||||||
|
originalMessageCount: messages.length,
|
||||||
|
compactedMessageCount: compactedMessages.length,
|
||||||
|
compactedOlderMessageCount: older.length,
|
||||||
|
retainedRecentMessageCount: recent.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,15 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* Main-side implementations of pi's tool-execution hooks. Invoked by
|
* Main-side implementations of pi's tool-execution hooks. Invoked by
|
||||||
* `RuntimeBridge.handleRpc` when the worker proxies `beforeToolCall`,
|
* `RuntimeBridge.handleRpc` when the worker proxies `beforeToolCall`
|
||||||
* `afterToolCall`, or `transformContext`.
|
* or `afterToolCall`.
|
||||||
*
|
*
|
||||||
* Each handler is deliberately isolated to one concern:
|
* Each handler is deliberately isolated to one concern:
|
||||||
* - `beforeToolCall`: operational-approval gate (blocks destructive
|
* - `beforeToolCall`: operational-approval gate (blocks destructive
|
||||||
* tools only while an approval that gates EXECUTION is pending)
|
* tools only while an approval that gates EXECUTION is pending)
|
||||||
* - `afterToolCall`: filesystem artifact projection (bash/write/edit
|
* - `afterToolCall`: filesystem artifact projection (bash/write/edit
|
||||||
* outputs become `work_products`)
|
* outputs become `work_products`)
|
||||||
* - `transformContext`: per-LLM-call auto-compaction via a pure
|
|
||||||
* reducer
|
|
||||||
*
|
*
|
||||||
* Policy lives here; `RuntimeBridge` stays a pure IPC router.
|
* Policy lives here; `RuntimeBridge` stays a pure IPC router.
|
||||||
*/
|
*/
|
||||||
@@ -20,14 +18,11 @@ import type {
|
|||||||
AfterToolCallRpcResult,
|
AfterToolCallRpcResult,
|
||||||
BeforeToolCallRpcPayload,
|
BeforeToolCallRpcPayload,
|
||||||
BeforeToolCallRpcResult,
|
BeforeToolCallRpcResult,
|
||||||
TransformContextRpcPayload,
|
|
||||||
TransformContextRpcResult,
|
|
||||||
} from "./hook-rpc";
|
} from "./hook-rpc";
|
||||||
import {
|
import {
|
||||||
projectToolExecutionToWorkProduct,
|
projectToolExecutionToWorkProduct,
|
||||||
type ArtifactProjectorRunContext,
|
type ArtifactProjectorRunContext,
|
||||||
} from "./artifact-projector";
|
} from "./artifact-projector";
|
||||||
import { compactMessagesIfNeeded } from "./context-compactor";
|
|
||||||
import {
|
import {
|
||||||
isCofounderMandatoryApproval,
|
isCofounderMandatoryApproval,
|
||||||
isOperationalApproval,
|
isOperationalApproval,
|
||||||
@@ -194,18 +189,3 @@ export function handleAfterToolCall(
|
|||||||
}
|
}
|
||||||
return NO_OP_AFTER;
|
return NO_OP_AFTER;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Context-transform hook. Delegates to `compactMessagesIfNeeded`,
|
|
||||||
* which is a pure, provider-free deterministic compactor. Runs before
|
|
||||||
* every LLM call; short transcripts short-circuit on the token-budget
|
|
||||||
* check so the steady-state cost is negligible.
|
|
||||||
*/
|
|
||||||
export function handleTransformContext(
|
|
||||||
_deps: HookHandlerDeps,
|
|
||||||
_ctx: ActiveRunContext,
|
|
||||||
payload: TransformContextRpcPayload,
|
|
||||||
): TransformContextRpcResult {
|
|
||||||
const outcome = compactMessagesIfNeeded(payload.messages);
|
|
||||||
return { changed: outcome.changed, messages: outcome.messages };
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,19 @@
|
|||||||
/**
|
/**
|
||||||
* Hook RPC contracts — the parent↔worker half of pi-agent-core's
|
* Hook RPC contracts — the parent↔worker half of pi-agent-core's
|
||||||
* `beforeToolCall` / `afterToolCall` / `transformContext` hooks.
|
* `beforeToolCall` / `afterToolCall` hooks.
|
||||||
*
|
*
|
||||||
* The Agent instance lives in the utility process. Policy (approval,
|
* The Agent instance lives in the utility process. Policy (approval,
|
||||||
* compaction, filesystem projection) lives in main. The hooks are
|
* filesystem projection) lives in main. The hooks are therefore proxied:
|
||||||
* therefore proxied: the worker invokes an RPC that main answers from
|
* the worker invokes an RPC that main answers from the same
|
||||||
* the same `RuntimeBridge` that already owns agent-event and
|
* `RuntimeBridge` that already owns agent-event and `persistMessage`
|
||||||
* `persistMessage` handling.
|
* handling. Context compaction runs in the worker process and reports
|
||||||
|
* telemetry through a worker message.
|
||||||
*
|
*
|
||||||
* Payloads intentionally exclude pi's `AgentContext` (systemPrompt,
|
* Payloads intentionally exclude pi's `AgentContext` (systemPrompt,
|
||||||
* messages, tools) because main policy never needs it. Stripping it
|
* messages, tools) because main policy never needs it. Stripping it
|
||||||
* keeps each hook IPC well under the structured-clone budget even for
|
* keeps each hook IPC well under the structured-clone budget even for
|
||||||
* large transcripts.
|
* large transcripts.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { AgentMessage } from "@mariozechner/pi-agent-core";
|
|
||||||
|
|
||||||
// ─── beforeToolCall ───────────────────────────────────────────────────────
|
// ─── beforeToolCall ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface BeforeToolCallRpcPayload {
|
export interface BeforeToolCallRpcPayload {
|
||||||
@@ -51,19 +49,3 @@ export interface AfterToolCallRpcResult {
|
|||||||
contentOverride: { type: "text"; text: string }[] | null;
|
contentOverride: { type: "text"; text: string }[] | null;
|
||||||
isErrorOverride: boolean | null;
|
isErrorOverride: boolean | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── transformContext ─────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface TransformContextRpcPayload {
|
|
||||||
messages: AgentMessage[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TransformContextRpcResult {
|
|
||||||
/**
|
|
||||||
* Transformed transcript. When `changed` is false the worker keeps its
|
|
||||||
* original array instance instead of replacing it — saves structured
|
|
||||||
* clone on the common "no compaction yet" path.
|
|
||||||
*/
|
|
||||||
changed: boolean;
|
|
||||||
messages: AgentMessage[] | null;
|
|
||||||
}
|
|
||||||
@@ -20,14 +20,12 @@ import { captureBaselineIfRequired, reconcileWorkspaceArtifacts } from "./artifa
|
|||||||
import {
|
import {
|
||||||
handleBeforeToolCall,
|
handleBeforeToolCall,
|
||||||
handleAfterToolCall,
|
handleAfterToolCall,
|
||||||
handleTransformContext,
|
|
||||||
type ActiveRunContext,
|
type ActiveRunContext,
|
||||||
type ActiveRunLifecycleState,
|
type ActiveRunLifecycleState,
|
||||||
} from "./hook-handlers";
|
} from "./hook-handlers";
|
||||||
import type {
|
import type {
|
||||||
AfterToolCallRpcPayload,
|
AfterToolCallRpcPayload,
|
||||||
BeforeToolCallRpcPayload,
|
BeforeToolCallRpcPayload,
|
||||||
TransformContextRpcPayload,
|
|
||||||
} from "./hook-rpc";
|
} from "./hook-rpc";
|
||||||
import { routeInternalToolCall } from "./internal-tools/router";
|
import { routeInternalToolCall } from "./internal-tools/router";
|
||||||
import type { InvokeInternalToolRpcPayload } from "@main/worker/runtime/internal-tools/internal-tool-rpc";
|
import type { InvokeInternalToolRpcPayload } from "@main/worker/runtime/internal-tools/internal-tool-rpc";
|
||||||
@@ -85,9 +83,9 @@ type RpcMethod = WorkerRpcMethod;
|
|||||||
* - Forwards `agent-event` from the worker to the renderer (push channel).
|
* - Forwards `agent-event` from the worker to the renderer (push channel).
|
||||||
* - Persists each `message_end` message via `SqliteSessionStore`.
|
* - Persists each `message_end` message via `SqliteSessionStore`.
|
||||||
* - Calls `CostWriter` for assistant messages with usage.
|
* - Calls `CostWriter` for assistant messages with usage.
|
||||||
* - Proxies pi's tool-execution hooks (`beforeToolCall` / `afterToolCall`
|
* - Proxies pi's tool-execution hooks (`beforeToolCall` / `afterToolCall`)
|
||||||
* / `transformContext`) into policy handlers: approval-gate checks,
|
* into policy handlers: approval-gate checks and filesystem artifact
|
||||||
* filesystem artifact projection, and context compaction.
|
* projection.
|
||||||
*
|
*
|
||||||
* Policy itself lives in `hook-handlers.ts`; this class is a pure IPC
|
* Policy itself lives in `hook-handlers.ts`; this class is a pure IPC
|
||||||
* router plus an `ActiveRunContext` cache.
|
* router plus an `ActiveRunContext` cache.
|
||||||
@@ -563,8 +561,6 @@ export class RuntimeBridge {
|
|||||||
return this.handleBeforeToolCallRpc(request.runId, request.payload as BeforeToolCallRpcPayload);
|
return this.handleBeforeToolCallRpc(request.runId, request.payload as BeforeToolCallRpcPayload);
|
||||||
case "afterToolCall":
|
case "afterToolCall":
|
||||||
return this.handleAfterToolCallRpc(request.runId, request.payload as AfterToolCallRpcPayload);
|
return this.handleAfterToolCallRpc(request.runId, request.payload as AfterToolCallRpcPayload);
|
||||||
case "transformContext":
|
|
||||||
return this.handleTransformContextRpc(request.runId, request.payload as TransformContextRpcPayload);
|
|
||||||
case "invokeInternalTool":
|
case "invokeInternalTool":
|
||||||
return this.handleInvokeInternalToolRpc(request.runId, request.payload as InvokeInternalToolRpcPayload);
|
return this.handleInvokeInternalToolRpc(request.runId, request.payload as InvokeInternalToolRpcPayload);
|
||||||
default: {
|
default: {
|
||||||
@@ -733,15 +729,4 @@ export class RuntimeBridge {
|
|||||||
return { ok: true, result };
|
return { ok: true, result };
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleTransformContextRpc(
|
|
||||||
runId: string,
|
|
||||||
payload: TransformContextRpcPayload,
|
|
||||||
): { ok: true; result: unknown } | { ok: false; error: string } {
|
|
||||||
const ctx = this.activeRuns.get(runId);
|
|
||||||
if (!ctx) {
|
|
||||||
return { ok: false, error: `transformContext: no active run ${runId}` };
|
|
||||||
}
|
|
||||||
const result = handleTransformContext(this.deps, ctx, payload);
|
|
||||||
return { ok: true, result };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ import type { workerMessageSchema } from "./types";
|
|||||||
import { handleRunLog } from "../handlers/run-log-handler";
|
import { handleRunLog } from "../handlers/run-log-handler";
|
||||||
import { handleRunStatus } from "../handlers/run-status-handler";
|
import { handleRunStatus } from "../handlers/run-status-handler";
|
||||||
import { handleRunFinished } from "../handlers/run-finished-handler";
|
import { handleRunFinished } from "../handlers/run-finished-handler";
|
||||||
|
import { handleContextCompaction } from "../handlers/context-compaction-handler";
|
||||||
import type { HandlerContext, HandlerDeps } from "../handlers/handler-context";
|
import type { HandlerContext, HandlerDeps } from "../handlers/handler-context";
|
||||||
|
|
||||||
export async function handleWorkerMessage(
|
export async function handleWorkerMessage(
|
||||||
@@ -67,6 +68,9 @@ export async function handleWorkerMessage(
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
case "context-compaction":
|
||||||
|
handleContextCompaction(event, deps, context);
|
||||||
|
return;
|
||||||
case "rpc-request": {
|
case "rpc-request": {
|
||||||
const bridge = deps.getRuntimeBridge?.();
|
const bridge = deps.getRuntimeBridge?.();
|
||||||
const response = bridge
|
const response = bridge
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ export const workerRpcMethodSchema = z.enum([
|
|||||||
"prepareRun",
|
"prepareRun",
|
||||||
"beforeToolCall",
|
"beforeToolCall",
|
||||||
"afterToolCall",
|
"afterToolCall",
|
||||||
"transformContext",
|
|
||||||
"invokeInternalTool",
|
"invokeInternalTool",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -65,6 +64,16 @@ export const workerMessageSchema = z.union([
|
|||||||
emittedAt: z.string(),
|
emittedAt: z.string(),
|
||||||
event: z.record(z.string(), z.unknown()).and(z.object({ type: z.string() })),
|
event: z.record(z.string(), z.unknown()).and(z.object({ type: z.string() })),
|
||||||
}),
|
}),
|
||||||
|
z.object({
|
||||||
|
type: z.literal("context-compaction"),
|
||||||
|
runId: z.string().uuid(),
|
||||||
|
emittedAt: z.string(),
|
||||||
|
estimatedTokens: z.number(),
|
||||||
|
originalMessageCount: z.number().int(),
|
||||||
|
compactedMessageCount: z.number().int(),
|
||||||
|
compactedOlderMessageCount: z.number().int(),
|
||||||
|
retainedRecentMessageCount: z.number().int(),
|
||||||
|
}),
|
||||||
z.object({
|
z.object({
|
||||||
type: z.literal("rpc-request"),
|
type: z.literal("rpc-request"),
|
||||||
rpcId: z.string(),
|
rpcId: z.string(),
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { persistRunEvent } from "../observability/run-event-recorder";
|
||||||
|
import type { HandlerContext, HandlerDeps, WorkerMessageEvent } from "./handler-context";
|
||||||
|
|
||||||
|
export function handleContextCompaction(
|
||||||
|
event: Extract<WorkerMessageEvent, { type: "context-compaction" }>,
|
||||||
|
deps: HandlerDeps,
|
||||||
|
_context: HandlerContext,
|
||||||
|
): void {
|
||||||
|
const runState = deps.db.runs.getRunAuthState(event.runId);
|
||||||
|
if (!runState) {
|
||||||
|
deps.logger.warn(`[context-compaction] run ${event.runId} disappeared before telemetry could be recorded.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
persistRunEvent(deps.db, deps.logger, {
|
||||||
|
companyId: runState.companyId,
|
||||||
|
runId: event.runId,
|
||||||
|
agentId: runState.agentId,
|
||||||
|
eventType: "context_compaction",
|
||||||
|
level: "info",
|
||||||
|
message: `Compacted ${event.compactedOlderMessageCount} older messages into a summary.`,
|
||||||
|
payload: {
|
||||||
|
emittedAt: event.emittedAt,
|
||||||
|
estimatedTokens: event.estimatedTokens,
|
||||||
|
originalMessageCount: event.originalMessageCount,
|
||||||
|
compactedMessageCount: event.compactedMessageCount,
|
||||||
|
compactedOlderMessageCount: event.compactedOlderMessageCount,
|
||||||
|
retainedRecentMessageCount: event.retainedRecentMessageCount,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -77,6 +77,16 @@ export type ChildMessage =
|
|||||||
emittedAt: string;
|
emittedAt: string;
|
||||||
event: { type: string } & Record<string, unknown>;
|
event: { type: string } & Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
| {
|
||||||
|
type: "context-compaction";
|
||||||
|
runId: string;
|
||||||
|
emittedAt: string;
|
||||||
|
estimatedTokens: number;
|
||||||
|
originalMessageCount: number;
|
||||||
|
compactedMessageCount: number;
|
||||||
|
compactedOlderMessageCount: number;
|
||||||
|
retainedRecentMessageCount: number;
|
||||||
|
}
|
||||||
| { type: "rpc-request"; rpcId: string; runId: string; method: string; payload: unknown }
|
| { type: "rpc-request"; rpcId: string; runId: string; method: string; payload: unknown }
|
||||||
| { type: "run-agent-state"; runId: string; state: RunAgentLifecycleState }
|
| { type: "run-agent-state"; runId: string; state: RunAgentLifecycleState }
|
||||||
| { type: "steer-ack"; runId: string; correlationId: string; accepted: boolean };
|
| { type: "steer-ack"; runId: string; correlationId: string; accepted: boolean };
|
||||||
|
|||||||
@@ -178,6 +178,18 @@ export class WorkerRunner {
|
|||||||
apiKey: prepared.apiKey,
|
apiKey: prepared.apiKey,
|
||||||
extraHeaders,
|
extraHeaders,
|
||||||
rpc,
|
rpc,
|
||||||
|
onContextCompaction: (telemetry) => {
|
||||||
|
post({
|
||||||
|
type: "context-compaction",
|
||||||
|
runId: telemetry.runId,
|
||||||
|
emittedAt: telemetry.emittedAt,
|
||||||
|
estimatedTokens: telemetry.estimatedTokens,
|
||||||
|
originalMessageCount: telemetry.originalMessageCount,
|
||||||
|
compactedMessageCount: telemetry.compactedMessageCount,
|
||||||
|
compactedOlderMessageCount: telemetry.compactedOlderMessageCount,
|
||||||
|
retainedRecentMessageCount: telemetry.retainedRecentMessageCount,
|
||||||
|
});
|
||||||
|
},
|
||||||
});
|
});
|
||||||
this.activeAgents.set(job.runId, agent);
|
this.activeAgents.set(job.runId, agent);
|
||||||
post({ type: "run-agent-state", runId: job.runId, state: "agent_active" });
|
post({ type: "run-agent-state", runId: job.runId, state: "agent_active" });
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
* none of which the worker should replicate.
|
* none of which the worker should replicate.
|
||||||
*
|
*
|
||||||
* This is structurally the same pattern as `beforeToolCall`/
|
* This is structurally the same pattern as `beforeToolCall`/
|
||||||
* `afterToolCall`/`transformContext` in `hook-rpc.ts`; what's different
|
* `afterToolCall` in `hook-rpc.ts`; what's different
|
||||||
* is that those are side-effect hooks around pi's own tools, whereas
|
* is that those are side-effect hooks around pi's own tools, whereas
|
||||||
* this is a primary-effect tool whose business logic lives entirely in
|
* this is a primary-effect tool whose business logic lives entirely in
|
||||||
* main. Keeping the payload shape minimal (name + JSON args) mirrors
|
* main. Keeping the payload shape minimal (name + JSON args) mirrors
|
||||||
|
|||||||
@@ -9,8 +9,8 @@
|
|||||||
* thrown hooks — a thrown `beforeToolCall` produces an error tool
|
* thrown hooks — a thrown `beforeToolCall` produces an error tool
|
||||||
* result, a thrown `afterToolCall` likewise — so RPC failures degrade
|
* result, a thrown `afterToolCall` likewise — so RPC failures degrade
|
||||||
* to a deterministic tool-error instead of crashing the run. The
|
* to a deterministic tool-error instead of crashing the run. The
|
||||||
* `transformContext` contract explicitly forbids throwing, so on RPC
|
* `transformContext` runs the deterministic compactor in the worker
|
||||||
* failure we return the original messages unchanged.
|
* process and lets compaction failures fail the run explicitly.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
} from "@mariozechner/pi-agent-core";
|
} from "@mariozechner/pi-agent-core";
|
||||||
import { streamSimple, type Api, type Model } from "@mariozechner/pi-ai";
|
import { streamSimple, type Api, type Model } from "@mariozechner/pi-ai";
|
||||||
import { buildAgentHooks } from "@main/agent-runtime/agent-hooks";
|
import { buildAgentHooks } from "@main/agent-runtime/agent-hooks";
|
||||||
|
import type { ContextCompactionTelemetry } from "@main/agent-runtime/agent-hooks";
|
||||||
import type { WorkerRpcClient } from "../entry/rpc";
|
import type { WorkerRpcClient } from "../entry/rpc";
|
||||||
// Side-effect import: drags the hook signature contract into the typecheck
|
// Side-effect import: drags the hook signature contract into the typecheck
|
||||||
// graph so any drift in pi-agent-core hook shapes breaks the build here.
|
// graph so any drift in pi-agent-core hook shapes breaks the build here.
|
||||||
@@ -40,6 +41,7 @@ export interface PiAgentFactoryInput {
|
|||||||
apiKey: string;
|
apiKey: string;
|
||||||
extraHeaders: Record<string, string> | undefined;
|
extraHeaders: Record<string, string> | undefined;
|
||||||
rpc: WorkerRpcClient;
|
rpc: WorkerRpcClient;
|
||||||
|
onContextCompaction?: (telemetry: ContextCompactionTelemetry) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Map the UI-facing `thinkingEffort` string onto pi's `ThinkingLevel`. */
|
/** Map the UI-facing `thinkingEffort` string onto pi's `ThinkingLevel`. */
|
||||||
@@ -61,7 +63,11 @@ export function resolveThinkingLevel(effort: string | null | undefined): Thinkin
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function createPiAgent(input: PiAgentFactoryInput): Agent {
|
export function createPiAgent(input: PiAgentFactoryInput): Agent {
|
||||||
const hooks = buildAgentHooks({ runId: input.runId, rpc: input.rpc });
|
const hooks = buildAgentHooks({
|
||||||
|
runId: input.runId,
|
||||||
|
rpc: input.rpc,
|
||||||
|
onContextCompaction: input.onContextCompaction,
|
||||||
|
});
|
||||||
return new Agent({
|
return new Agent({
|
||||||
initialState: {
|
initialState: {
|
||||||
systemPrompt: input.systemPrompt,
|
systemPrompt: input.systemPrompt,
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import type { AgentMessage } from "@mariozechner/pi-agent-core";
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { buildAgentHooks } from "../../src/main/agent-runtime/agent-hooks";
|
||||||
|
import type { WorkerRpcClient } from "../../src/main/worker/entry/rpc";
|
||||||
|
|
||||||
|
function createRpc() {
|
||||||
|
return {
|
||||||
|
invoke: vi.fn(async () => ({ ok: true, result: undefined })),
|
||||||
|
} as unknown as WorkerRpcClient & { invoke: ReturnType<typeof vi.fn> };
|
||||||
|
}
|
||||||
|
|
||||||
|
function largeTranscript(): AgentMessage[] {
|
||||||
|
const messages: AgentMessage[] = [];
|
||||||
|
for (let i = 0; i < 46; i += 1) {
|
||||||
|
const role = i % 2 === 0 ? "user" : "assistant";
|
||||||
|
messages.push({
|
||||||
|
role,
|
||||||
|
content: [{
|
||||||
|
type: "text",
|
||||||
|
text: `${role} turn ${i}\n${"context ".repeat(6_000)}`,
|
||||||
|
}],
|
||||||
|
timestamp: i,
|
||||||
|
} as AgentMessage);
|
||||||
|
}
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("worker-side context compaction", () => {
|
||||||
|
it("compacts inside the worker without transformContext RPC", async () => {
|
||||||
|
const rpc = createRpc();
|
||||||
|
const onContextCompaction = vi.fn();
|
||||||
|
const hooks = buildAgentHooks({
|
||||||
|
runId: "8b3f07b2-841a-4e16-9d1c-9d2a27c3c2ad",
|
||||||
|
rpc,
|
||||||
|
onContextCompaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
const messages = largeTranscript();
|
||||||
|
const transformed = await hooks.transformContext(messages);
|
||||||
|
|
||||||
|
expect(rpc.invoke).not.toHaveBeenCalledWith(
|
||||||
|
expect.any(String),
|
||||||
|
"transformContext",
|
||||||
|
expect.anything(),
|
||||||
|
);
|
||||||
|
expect(transformed.length).toBeLessThan(messages.length);
|
||||||
|
expect(transformed[0]).toMatchObject({ role: "user" });
|
||||||
|
expect(onContextCompaction).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
runId: "8b3f07b2-841a-4e16-9d1c-9d2a27c3c2ad",
|
||||||
|
originalMessageCount: messages.length,
|
||||||
|
compactedMessageCount: transformed.length,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("propagates compaction failures instead of returning the original transcript", async () => {
|
||||||
|
const rpc = createRpc();
|
||||||
|
const hooks = buildAgentHooks({
|
||||||
|
runId: "b9f6aa93-0db7-4f39-8f28-2d87742ef414",
|
||||||
|
rpc,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(hooks.transformContext(null as unknown as AgentMessage[])).rejects.toThrow(
|
||||||
|
"transformContext compaction failed",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user