fix(hooks): deep copy messages in context event before passing to hooks

The context event handler documentation promised a deep copy but the
implementation passed the original array reference. This could cause
hooks to accidentally mutate session messages.

Uses structuredClone() for fast native deep copying.
This commit is contained in:
Mario Zechner 2026-01-04 17:16:49 +01:00
parent 46047bc37e
commit 8b6bc30301

View file

@ -451,11 +451,11 @@ export class HookRunner {
* Handlers are chained - each gets the previous handler's output (if any).
* Returns the final modified messages, or the original if no modifications.
*
* Note: Messages are already deep-copied by the caller (pi-ai preprocessor).
* Messages are deep-copied before passing to hooks, so mutations are safe.
*/
async emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {
const ctx = this.createContext();
let currentMessages = messages;
let currentMessages = structuredClone(messages);
for (const hook of this.hooks) {
const handlers = hook.handlers.get("context");