Skip to content

Commit 275c128

Browse files
committed
feat(plugins): add sanitized model call hooks
1 parent 9ffe764 commit 275c128

8 files changed

Lines changed: 321 additions & 44 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ Docs: https://docs.openclaw.ai
2424
- Plugins/compat: mark `OPENCLAW_DISABLE_PERSISTED_PLUGIN_REGISTRY` as a deprecated break-glass switch and point operators at registry repair instead. Thanks @vincentkoc.
2525
- Plugins/registry: ignore stale persisted registry reads when plugin policy no longer matches current config, and stamp generated registry files with a do-not-edit warning. Thanks @vincentkoc.
2626
- Diagnostics/OTEL: surface provider request identifiers as bounded hashes on model-call diagnostics and span events, without exporting raw request IDs or metric labels. Thanks @Lidang-Jiang and @vincentkoc.
27+
- Plugins/diagnostics: add metadata-only `model_call_started` and `model_call_ended` hooks for provider/model call telemetry without exposing prompts, responses, headers, request bodies, or raw provider request IDs. Thanks @vincentkoc.
2728
- Diagnostics/OTEL: add bounded outbound message delivery lifecycle diagnostics and export them as low-cardinality delivery spans/metrics without message body, recipient, room, or media-path data. (#71471) Thanks @vincentkoc and @jlapenna.
2829
- Diagnostics/OTEL: emit bounded exec-process diagnostics and export them as `openclaw.exec` spans without exposing command text, working directories, or container identifiers. (#71451) Thanks @vincentkoc and @jlapenna.
2930
- Diagnostics/OTEL: support `OPENCLAW_OTEL_PRELOADED=1` so the plugin can reuse an already-registered OpenTelemetry SDK while keeping OpenClaw diagnostic listeners wired. (#71450) Thanks @vincentkoc and @jlapenna.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
f6d9588737310773031e744b6726ba80a9ca742205db335aae95fbd1e2925dc8 plugin-sdk-api-baseline.json
2-
a4c86fe92b7bea538f33139e9b57cfada766b7d504323c2e20a7ca205994be44 plugin-sdk-api-baseline.jsonl
1+
fae367b052828a57feab3bfcd10a58ebeacd6c858b337d0aab72726863952946 plugin-sdk-api-baseline.json
2+
1bb8995e1486f7d900928aaace87421a8297fe41264197f9bf849f07c65c8f2b plugin-sdk-api-baseline.jsonl

‎docs/plugins/hooks.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ observation-only.
6868

6969
**Conversation observation**
7070

71+
- `model_call_started` / `model_call_ended` — observe sanitized provider/model call metadata, timing, outcome, and bounded request-id hashes without prompt or response content
7172
- `llm_input` — observe provider input (system prompt, prompt, history)
7273
- `llm_output` — observe provider output
7374

@@ -162,6 +163,13 @@ so your plugin does not depend on a legacy combined phase.
162163
`before_agent_start` and `agent_end` include `event.runId` when OpenClaw can
163164
identify the active run. The same value is also available on `ctx.runId`.
164165

166+
Use `model_call_started` and `model_call_ended` for provider-call telemetry
167+
that should not receive raw prompts, history, responses, headers, request
168+
bodies, or provider request IDs. These hooks include stable metadata such as
169+
`runId`, `callId`, `provider`, `model`, optional `api`/`transport`, terminal
170+
`durationMs`/`outcome`, and `upstreamRequestIdHash` when OpenClaw can derive a
171+
bounded provider request-id hash.
172+
165173
Non-bundled plugins that need `llm_input`, `llm_output`, or `agent_end` must set:
166174

167175
```json

‎src/agents/pi-embedded-runner/run/attempt.model-diagnostic-events.test.ts‎

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
import type { StreamFn } from "@mariozechner/pi-agent-core";
2-
import { beforeEach, describe, expect, it } from "vitest";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import {
44
onInternalDiagnosticEvent,
55
resetDiagnosticEventsForTest,
66
type DiagnosticEventPayload,
77
} from "../../../infra/diagnostic-events.js";
88
import { createDiagnosticTraceContext } from "../../../infra/diagnostic-trace-context.js";
9+
import {
10+
initializeGlobalHookRunner,
11+
resetGlobalHookRunner,
12+
} from "../../../plugins/hook-runner-global.js";
13+
import { createHookRunnerWithRegistry } from "../../../plugins/hooks.test-helpers.js";
914
import { wrapStreamFnWithDiagnosticModelCallEvents } from "./attempt.model-diagnostic-events.js";
1015

1116
async function collectModelCallEvents(run: () => Promise<void>): Promise<DiagnosticEventPayload[]> {
@@ -33,6 +38,11 @@ async function drain(stream: AsyncIterable<unknown>): Promise<void> {
3338
describe("wrapStreamFnWithDiagnosticModelCallEvents", () => {
3439
beforeEach(() => {
3540
resetDiagnosticEventsForTest();
41+
resetGlobalHookRunner();
42+
});
43+
44+
afterEach(() => {
45+
resetGlobalHookRunner();
3646
});
3747

3848
it("emits started and completed events for async streams", async () => {
@@ -170,6 +180,79 @@ describe("wrapStreamFnWithDiagnosticModelCallEvents", () => {
170180
]);
171181
});
172182

183+
it("fires frozen sanitized model-call plugin hooks", async () => {
184+
const started = vi.fn();
185+
const ended = vi.fn();
186+
const { registry } = createHookRunnerWithRegistry([
187+
{ hookName: "model_call_started", handler: started },
188+
{ hookName: "model_call_ended", handler: ended },
189+
]);
190+
initializeGlobalHookRunner(registry);
191+
const secretChunk = "secret response with Bearer sk-test-secret-value";
192+
193+
async function* stream() {
194+
yield { type: "text", text: secretChunk };
195+
}
196+
const wrapped = wrapStreamFnWithDiagnosticModelCallEvents(
197+
(() => stream()) as unknown as StreamFn,
198+
{
199+
runId: "run-1",
200+
sessionKey: "session-key",
201+
sessionId: "session-id",
202+
provider: "openai",
203+
model: "gpt-5.4",
204+
api: "openai-responses",
205+
transport: "http",
206+
trace: createDiagnosticTraceContext(),
207+
nextCallId: () => "call-hook",
208+
},
209+
);
210+
211+
const events = await collectModelCallEvents(async () => {
212+
await drain(wrapped({} as never, {} as never, {} as never) as AsyncIterable<unknown>);
213+
});
214+
await new Promise<void>((resolve) => setImmediate(resolve));
215+
216+
expect(events.map((event) => event.type)).toEqual([
217+
"model.call.started",
218+
"model.call.completed",
219+
]);
220+
expect(started).toHaveBeenCalledWith(
221+
expect.objectContaining({
222+
runId: "run-1",
223+
callId: "call-hook",
224+
sessionKey: "session-key",
225+
sessionId: "session-id",
226+
provider: "openai",
227+
model: "gpt-5.4",
228+
api: "openai-responses",
229+
transport: "http",
230+
}),
231+
expect.objectContaining({
232+
runId: "run-1",
233+
sessionKey: "session-key",
234+
sessionId: "session-id",
235+
modelProviderId: "openai",
236+
modelId: "gpt-5.4",
237+
}),
238+
);
239+
expect(ended).toHaveBeenCalledWith(
240+
expect.objectContaining({
241+
runId: "run-1",
242+
callId: "call-hook",
243+
outcome: "completed",
244+
durationMs: expect.any(Number),
245+
}),
246+
expect.objectContaining({ runId: "run-1" }),
247+
);
248+
const startedEvent = started.mock.calls[0]?.[0];
249+
const startedCtx = started.mock.calls[0]?.[1];
250+
expect(Object.isFrozen(startedEvent)).toBe(true);
251+
expect(Object.isFrozen(startedCtx)).toBe(true);
252+
expect(Object.isFrozen((startedCtx as { trace?: unknown } | undefined)?.trace)).toBe(true);
253+
expect(JSON.stringify([started.mock.calls, ended.mock.calls])).not.toContain(secretChunk);
254+
});
255+
173256
it("emits error events when stream consumption stops early", async () => {
174257
async function* stream() {
175258
yield { type: "text", text: "first" };

‎src/agents/pi-embedded-runner/run/attempt.model-diagnostic-events.ts‎

Lines changed: 114 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { StreamFn } from "@mariozechner/pi-agent-core";
2+
import { fireAndForgetBoundedHook } from "../../../hooks/fire-and-forget.js";
23
import {
34
diagnosticErrorCategory,
45
diagnosticProviderRequestIdHash,
@@ -12,6 +13,12 @@ import {
1213
freezeDiagnosticTraceContext,
1314
type DiagnosticTraceContext,
1415
} from "../../../infra/diagnostic-trace-context.js";
16+
import { getGlobalHookRunner } from "../../../plugins/hook-runner-global.js";
17+
import type {
18+
PluginHookAgentContext,
19+
PluginHookModelCallEndedEvent,
20+
PluginHookModelCallStartedEvent,
21+
} from "../../../plugins/hook-types.js";
1522

1623
export { diagnosticErrorCategory };
1724

@@ -35,6 +42,10 @@ type ModelCallErrorFields = Pick<
3542
Extract<DiagnosticEventInput, { type: "model.call.error" }>,
3643
"errorCategory" | "upstreamRequestIdHash"
3744
>;
45+
type ModelCallEndedHookFields = Pick<
46+
PluginHookModelCallEndedEvent,
47+
"durationMs" | "outcome" | "errorCategory" | "upstreamRequestIdHash"
48+
>;
3849

3950
const MODEL_CALL_STREAM_RETURN_TIMEOUT_MS = 1000;
4051

@@ -90,6 +101,102 @@ function modelCallErrorFields(err: unknown): ModelCallErrorFields {
90101
};
91102
}
92103

104+
function modelCallHookEventBase(eventBase: ModelCallEventBase): PluginHookModelCallStartedEvent {
105+
return {
106+
runId: eventBase.runId,
107+
callId: eventBase.callId,
108+
...(eventBase.sessionKey ? { sessionKey: eventBase.sessionKey } : {}),
109+
...(eventBase.sessionId ? { sessionId: eventBase.sessionId } : {}),
110+
provider: eventBase.provider,
111+
model: eventBase.model,
112+
...(eventBase.api ? { api: eventBase.api } : {}),
113+
...(eventBase.transport ? { transport: eventBase.transport } : {}),
114+
};
115+
}
116+
117+
function modelCallHookContext(eventBase: ModelCallEventBase): PluginHookAgentContext {
118+
return Object.freeze({
119+
runId: eventBase.runId,
120+
trace: eventBase.trace,
121+
...(eventBase.sessionKey ? { sessionKey: eventBase.sessionKey } : {}),
122+
...(eventBase.sessionId ? { sessionId: eventBase.sessionId } : {}),
123+
modelProviderId: eventBase.provider,
124+
modelId: eventBase.model,
125+
}) as PluginHookAgentContext;
126+
}
127+
128+
function dispatchModelCallStartedHook(eventBase: ModelCallEventBase): void {
129+
const hookRunner = getGlobalHookRunner();
130+
if (!hookRunner?.hasHooks("model_call_started")) {
131+
return;
132+
}
133+
const event = Object.freeze(modelCallHookEventBase(eventBase)) as PluginHookModelCallStartedEvent;
134+
const hookCtx = modelCallHookContext(eventBase);
135+
fireAndForgetBoundedHook(
136+
() => hookRunner.runModelCallStarted(event, hookCtx),
137+
"model_call_started plugin hook failed",
138+
);
139+
}
140+
141+
function dispatchModelCallEndedHook(
142+
eventBase: ModelCallEventBase,
143+
fields: ModelCallEndedHookFields,
144+
): void {
145+
const hookRunner = getGlobalHookRunner();
146+
if (!hookRunner?.hasHooks("model_call_ended")) {
147+
return;
148+
}
149+
const event = Object.freeze({
150+
...modelCallHookEventBase(eventBase),
151+
...fields,
152+
}) as PluginHookModelCallEndedEvent;
153+
const hookCtx = modelCallHookContext(eventBase);
154+
fireAndForgetBoundedHook(
155+
() => hookRunner.runModelCallEnded(event, hookCtx),
156+
"model_call_ended plugin hook failed",
157+
);
158+
}
159+
160+
function emitModelCallStarted(eventBase: ModelCallEventBase): void {
161+
emitTrustedDiagnosticEvent({
162+
type: "model.call.started",
163+
...eventBase,
164+
});
165+
dispatchModelCallStartedHook(eventBase);
166+
}
167+
168+
function emitModelCallCompleted(eventBase: ModelCallEventBase, startedAt: number): void {
169+
const durationMs = Date.now() - startedAt;
170+
emitTrustedDiagnosticEvent({
171+
type: "model.call.completed",
172+
...eventBase,
173+
durationMs,
174+
});
175+
dispatchModelCallEndedHook(eventBase, {
176+
durationMs,
177+
outcome: "completed",
178+
});
179+
}
180+
181+
function emitModelCallError(
182+
eventBase: ModelCallEventBase,
183+
startedAt: number,
184+
fields: ModelCallErrorFields,
185+
): void {
186+
const durationMs = Date.now() - startedAt;
187+
emitTrustedDiagnosticEvent({
188+
type: "model.call.error",
189+
...eventBase,
190+
durationMs,
191+
...fields,
192+
});
193+
dispatchModelCallEndedHook(eventBase, {
194+
durationMs,
195+
outcome: "error",
196+
...fields,
197+
});
198+
}
199+
93200
async function safeReturnIterator(iterator: AsyncIterator<unknown>): Promise<void> {
94201
let returnResult: unknown;
95202
try {
@@ -137,29 +244,15 @@ async function* observeModelCallIterator<T>(
137244
yield next.value;
138245
}
139246
terminalEmitted = true;
140-
emitTrustedDiagnosticEvent({
141-
type: "model.call.completed",
142-
...eventBase,
143-
durationMs: Date.now() - startedAt,
144-
});
247+
emitModelCallCompleted(eventBase, startedAt);
145248
} catch (err) {
146249
terminalEmitted = true;
147-
emitTrustedDiagnosticEvent({
148-
type: "model.call.error",
149-
...eventBase,
150-
durationMs: Date.now() - startedAt,
151-
...modelCallErrorFields(err),
152-
});
250+
emitModelCallError(eventBase, startedAt, modelCallErrorFields(err));
153251
throw err;
154252
} finally {
155253
if (!terminalEmitted) {
156254
await safeReturnIterator(iterator);
157-
emitTrustedDiagnosticEvent({
158-
type: "model.call.error",
159-
...eventBase,
160-
durationMs: Date.now() - startedAt,
161-
errorCategory: "StreamAbandoned",
162-
});
255+
emitModelCallError(eventBase, startedAt, { errorCategory: "StreamAbandoned" });
163256
}
164257
}
165258
}
@@ -209,11 +302,7 @@ function observeModelCallResult(
209302
startedAt,
210303
);
211304
}
212-
emitTrustedDiagnosticEvent({
213-
type: "model.call.completed",
214-
...eventBase,
215-
durationMs: Date.now() - startedAt,
216-
});
305+
emitModelCallCompleted(eventBase, startedAt);
217306
return result;
218307
}
219308

@@ -225,10 +314,7 @@ export function wrapStreamFnWithDiagnosticModelCallEvents(
225314
const callId = ctx.nextCallId();
226315
const trace = freezeDiagnosticTraceContext(createChildDiagnosticTraceContext(ctx.trace));
227316
const eventBase = baseModelCallEvent(ctx, callId, trace);
228-
emitTrustedDiagnosticEvent({
229-
type: "model.call.started",
230-
...eventBase,
231-
});
317+
emitModelCallStarted(eventBase);
232318
const startedAt = Date.now();
233319

234320
try {
@@ -237,24 +323,14 @@ export function wrapStreamFnWithDiagnosticModelCallEvents(
237323
return result.then(
238324
(resolved) => observeModelCallResult(resolved, eventBase, startedAt),
239325
(err) => {
240-
emitTrustedDiagnosticEvent({
241-
type: "model.call.error",
242-
...eventBase,
243-
durationMs: Date.now() - startedAt,
244-
...modelCallErrorFields(err),
245-
});
326+
emitModelCallError(eventBase, startedAt, modelCallErrorFields(err));
246327
throw err;
247328
},
248329
);
249330
}
250331
return observeModelCallResult(result, eventBase, startedAt);
251332
} catch (err) {
252-
emitTrustedDiagnosticEvent({
253-
type: "model.call.error",
254-
...eventBase,
255-
durationMs: Date.now() - startedAt,
256-
...modelCallErrorFields(err),
257-
});
333+
emitModelCallError(eventBase, startedAt, modelCallErrorFields(err));
258334
throw err;
259335
}
260336
}) as StreamFn;

0 commit comments

Comments
 (0)