Protect high-priority agent context from pruning while still managing the memory budget.
The full prompt is available without an account.
Implement PinMemory(max_tokens, count_tokens).
- add(role, content, pin=False) appends a message. If pin=True,
mark the message as pinned.
- pin(msg_index) marks the message at the given index as pinned.
- unpin(msg_index) removes the pinned status.
- get_pinned() returns all pinned messages in order.
- render() returns a list of messages that fits within max_tokens.
Pinned messages are always included regardless of budget — they are
never evicted. Non-pinned messages are dropped oldest-first when
the budget is exceeded.
- A pinned message's token cost is subtracted from the budget first
(after any system messages).
Read-only Python 3.12 preview. Sign in to edit and execute it.
class PinMemory:
def __init__(self, max_tokens: int, count_tokens):
self.max_tokens = max_tokens
self.count_tokens = count_tokens
self.messages = []
self.pinned = set()
def add(self, role: str, content: str, pin=False) -> None:
self.messages.append({"role": role, "content": content})
if pin:
self.pinned.add(len(self.messages) - 1)
def pin(self, idx: int) -> None:
self.pinned.add(idx)
def unpin(self, idx: int) -> None:
self.pinned.discard(idx)
def get_pinned(self) -> list[dict]:
return [self.messages[i] for i in sorted(self.pinned)]
def render(self) -> list[dict]:
# TODO
return []