Welcome back! In the previous chapter, Update Threshold Logic, we taught our system when to update the memory. We decided that when the conversation grows large enough, it's time to take notes.
But here is the problem: Who writes the notes?
If your main AI agent stops talking to the user to say, "Hold on, I need to read our whole history and summarize it into a markdown file," two bad things happen:
In this chapter, we will build the Isolated Forked Agent.
Imagine the user asks: "Help me debug this Python script."
session-memory.md, and then disappears.In software terms, a "fork" is a split. Imagine a timeline of events. At point B, we split the timeline.
The Forked Agent receives a copy of the conversation history up to that moment. However, anything the Forked Agent says or thinks never goes back to the Main Agent. This prevents "Context Pollution."
We trust our Main Agent to do anything (run code, edit files). But the Forked Agent is a temporary worker. We don't want it accidentally deleting user files while trying to summarize. We restrict its tools so it can only edit the memory file.
Here is how the main thread spawns the worker and keeps going.
The magic happens in sessionMemory.ts. Let's look at how we configure and launch this "Clone."
Before we spawn the agent, we create a new context. This ensures that any file caching done by the clone doesn't mess up the main agent's cache.
// Inside extractSessionMemory
// Create isolated context based on the current tool usage
// This is like giving the intern their own desk.
const setupContext = createSubagentContext(toolUseContext)
createSubagentContext creates a shallow copy of the state. It allows the subagent to read the same files, but if it changes its internal tracking of them, the main agent isn't affected.This is a critical safety step. We create a special rule: "You can only use the FileEditTool, and ONLY on this specific file path."
// Define the rule
const safetyRule = createMemoryFileCanUseTool(memoryPath)
// How the rule works (simplified logic):
// 1. Is the tool 'file_edit'?
// 2. Is the file_path 'session-memory.md'?
// 3. If yes to both -> Allow.
// 4. Otherwise -> Deny.
package.json, this rule blocks it immediately.runForkedAgent)Now we call the function that actually runs the AI model in the background.
await runForkedAgent({
// 1. Give it the instruction (The Prompt)
promptMessages: [createUserMessage({ content: userPrompt })],
// 2. Share the history efficiently
cacheSafeParams: createCacheSafeParams(context),
// 3. Apply the handcuffs
canUseTool: safetyRule,
// 4. Label it for debugging
forkLabel: 'session_memory',
})
promptMessages: The specific instruction we generated (we'll cover this in the next chapter).cacheSafeParams: This passes the massive conversation history to the LLM without re-processing everything (saving money/time).canUseTool: Our safety rule.runForkedAgent
What actually happens inside runForkedAgent? It's a wrapper around the LLM's "Chat Loop."
[A, B, C] from the main thread.[A, B, C, "Summarize this"].I will edit the file (Tool Call).session-memory.md).[A, B, C, "Summarize this", "I'm finished"] is thrown away. The Main Thread still only has [A, B, C].
Let's look specifically at the createMemoryFileCanUseTool function in sessionMemory.ts. This is a great example of defensive coding.
export function createMemoryFileCanUseTool(memoryPath: string): CanUseToolFn {
// Return a function that checks every tool call
return async (tool: Tool, input: unknown) => {
// Check 1: Is it the Edit Tool?
const isEditTool = tool.name === FILE_EDIT_TOOL_NAME
// Check 2: Does the input target our memory file?
// (We cast input to check 'file_path' safely)
const isCorrectFile = input.file_path === memoryPath
if (isEditTool && isCorrectFile) {
return { behavior: 'allow' }
}
// If checks failed, block the action!
return {
behavior: 'deny',
message: `only editing ${memoryPath} is allowed`,
}
}
}
We have created the perfect employee: the Isolated Forked Agent.
But what exactly do we tell this agent to do? If we just say "Summarize," it might write a poem or a novel. We need a very specific set of instructions to ensure the memory file is useful.
In the next chapter, we will learn how to write the System Prompt that guides this agent.
Next Chapter: Prompt Construction & Templating
Generated by Code IQ