Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
import { logger } from '../utils/logger.js';
import { ModeManager } from '../services/domain/ModeManager.js';
// TODO(#2233): migrate to Anthropic tool-use API for deterministic JSON output. This text-XML path is the bridge.
// Only strip fences when the entire payload is a single fenced block. Stripping
// the first opening + last closing fence anywhere in the string can corrupt
// content that contains internal fenced examples or surrounding prose
// (CodeRabbit review on PR #2282).
export function stripCodeFences(text: string): string {
const match = text.match(/^\s*```(?:xml)?\s*\n([\s\S]*?)\n```\s*$/i);
return match ? match[1] : text;
}
export interface ParsedObservation {
type: string;
title: string | null;
subtitle: string | null;
facts: string[];
narrative: string | null;
concepts: string[];
files_read: string[];
files_modified: string[];
/**
* Raw text of each `<attachment>` in the observation's first lowercase
* `<attachments>` block, trimmed, in document order (bounded). Absent when
* the observation has no such block or the block holds no elements. These
* are request labels the linkage rules still have to validate
* (src/services/media/inference.ts linkAttachmentRefs); they are never
* stored as text.
*/
attachments?: string[];
}
export interface ParsedSummary {
request: string | null;
investigated: string | null;
learned: string | null;
completed: string | null;
next_steps: string | null;
notes: string | null;
skipped?: boolean;
skip_reason?: string | null;
}
const OBSERVATION_TITLE_MAX_GRAPHEMES = 120;
const OBSERVATION_TITLE_TRUNCATE_AT = 117;
const observationGraphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
export type ParseResult =
| {
valid: true;
observations: ParsedObservation[];
summary: ParsedSummary | null;
/**
* Tags outside the observation schema found in blocks whose own fields
* were missing and whose content was salvaged — the model drifting off
* the schema (`<kind>`/`<detail>` for `<type>`/`<title>`, #3461). Sorted,
* lowercase; absent when there was no drift.
*/
schemaDrift?: string[];
}
| { valid: false };
/** Every tag the observation schema defines, wrappers and elements alike. */
const OBSERVATION_SCHEMA_TAGS = new Set([
'type', 'title', 'subtitle', 'narrative', 'facts', 'fact', 'concepts', 'concept',
'files_read', 'files_modified', 'file', 'attachments', 'attachment',
]);
// XML 1.0 S allows only space, tab, CR and LF before a tag's closing `>`.
// Share root patterns with the cut-off detector so a complete accepted reply
// is not reported as unfinished. Attributes remain outside this text schema.
const XML_TAG_SPACE = '[ \\t\\r\\n]*';
function elementPattern(name: string): string {
return `<${name}${XML_TAG_SPACE}>([\\s\\S]*?)</${name}${XML_TAG_SPACE}>`;
}
export const OBSERVATION_OPEN_TAG = new RegExp(`<observation${XML_TAG_SPACE}>`, 'i');
export const OBSERVATION_BLOCK = new RegExp(elementPattern('observation'), 'i');
export const SUMMARY_BLOCK = new RegExp(elementPattern('summary'), 'i');
/**
* docs/media-contract-v1.md "Observation XML attachment refs": lowercase tags,
* matched case-sensitively (unlike every other field here), first block only.
* Elements past MAX_PARSED_ATTACHMENTS are not kept; the linkage rules reject
* everything after the fourth anyway. Element text is clipped so a runaway
* label cannot grow the parse.
*/
const ATTACHMENTS_BLOCK = /<attachments>([\s\S]*?)<\/attachments>/;
const ATTACHMENT_ELEMENT = /<attachment>([\s\S]*?)<\/attachment>/g;
const MAX_PARSED_ATTACHMENTS = 16;
const MAX_PARSED_ATTACHMENT_CHARS = 128;
function extractAttachmentLabels(content: string): string[] | undefined {
const block = ATTACHMENTS_BLOCK.exec(maskXmlLiteralMarkup(content));
if (!block) return undefined;
const body = originalElementBody(content, block);
const labels: string[] = [];
for (const element of maskXmlLiteralMarkup(body).matchAll(ATTACHMENT_ELEMENT)) {
if (labels.length >= MAX_PARSED_ATTACHMENTS) break;
labels.push(originalElementBody(body, element).trim().slice(0, MAX_PARSED_ATTACHMENT_CHARS));
}
return labels.length > 0 ? labels : undefined;
}
export const SKIP_SUMMARY_TAG = /<skip_summary(?:\s+reason\s*=\s*(?:"([^"]*)"|'([^']*)'))?\s*\/>/i;
/**
* Hide markup inside CDATA sections and comments without changing offsets into
* the original text. An observer reply can quote XML examples in those regions;
* the tags they contain must not end a record or select its fields. Callers
* match structure on the masked view, then read field values from the original
* reply by offset, so each masked character is replaced one for one.
*
* Only terminated literals are masked. A bare `<!--` or `<![CDATA[` in prose
* (an observation about HTML, say) stays visible text, so it cannot hide every
* later closing tag and turn a valid reply into a parse failure that is resent.
* Comments cannot nest: a later opener starts a new candidate instead of
* pairing its terminator with a bare opener in an earlier observation.
*/
const XML_LITERAL_PATTERN = /<!\[CDATA\[[\s\S]*?\]\]>|<!--(?:(?!<!--)[\s\S])*?-->/g;
/** Element start, end and self-closing tags; escaped `<br/>` is not a tag. */
const XML_ELEMENT_TAG_PATTERN = /<\/?[A-Za-z_][\w-]*\b[^>]*>/g;
export function maskXmlLiteralMarkup(text: string): string {
return text.replace(XML_LITERAL_PATTERN,
literal => literal.replace(/[<>]/g, ' '));
}
/**
* Whether the reply ends in an `<observation>` the parser cannot store. Every
* whole block the parser reads is removed first, using its own matches
* (parseAgentXml: observations, the summary, a skip_summary), so an
* `<observation>` written inside a block's content (CDATA, prose about the
* format) is not mistaken for an unfinished block. Any opening left has no
* close after it, so it begins the cut-off tail.
*/
export function hasUnfinishedObservationBlock(text: string): boolean {
const outsideWholeBlocks = maskXmlLiteralMarkup(text)
.replace(new RegExp(OBSERVATION_BLOCK.source, 'gi'), '')
.replace(new RegExp(SUMMARY_BLOCK.source, 'gi'), '')
.replace(new RegExp(SKIP_SUMMARY_TAG.source, 'gi'), '');
return OBSERVATION_OPEN_TAG.test(outsideWholeBlocks);
}
/** Recover an element's original body after matching its structure on masked text. */
function originalElementBody(text: string, match: RegExpExecArray): string {
const start = match.index + match[0].indexOf('>') + 1;
return text.slice(start, start + match[1].length);
}
/**
* Read character data for storage eligibility without changing parsed values.
* Work on the original XML: after entity decoding, an escaped comment example
* is indistinguishable from an actual comment. CDATA is literal text (including
* any comment/entity examples inside it); only real comments are ignored.
* Match fields with the same literal masking and first-block rules as parsing.
*/
export function summaryFieldsHaveText(
raw: string,
fields: readonly (keyof Omit<ParsedSummary, 'skipped' | 'skip_reason'>)[],
): boolean {
raw = stripCodeFences(raw);
const block = SUMMARY_BLOCK.exec(maskXmlLiteralMarkup(raw));
if (!block) return false;
const body = originalElementBody(raw, block);
const markup = maskXmlLiteralMarkup(body);
return fields.some(field => {
const match = new RegExp(elementPattern(field), 'i').exec(markup);
if (!match) return false;
const value = originalElementBody(body, match);
// Markup alone (`<br/>`, `<p></p>`) is not character data. Tags are removed
// only outside CDATA, so a literal `<![CDATA[<br/>]]>` example still counts.
const segmentHasText = (segment: string) =>
decodeXmlReferences(segment.replace(XML_ELEMENT_TAG_PATTERN, '')).trim().length > 0;
let cursor = 0;
for (const literal of value.matchAll(XML_LITERAL_PATTERN)) {
if (segmentHasText(value.slice(cursor, literal.index))) return true;
if (literal[0].startsWith('<![CDATA[') && literal[0].slice(9, -3).trim()) return true;
cursor = literal.index + literal[0].length;
}
return segmentHasText(value.slice(cursor));
});
}
export function parseAgentXml(raw: string, correlationId?: string | number): ParseResult {
if (typeof raw !== 'string' || !raw.trim()) {
return { valid: false };
}
raw = stripCodeFences(raw);
const markup = maskXmlLiteralMarkup(raw);
const firstRoot = /<(observation|summary)\b/i.exec(markup);
const skipMatch = SKIP_SUMMARY_TAG.exec(markup);
if (skipMatch && (!firstRoot || skipMatch.index < firstRoot.index)) {
const originalSkip = SKIP_SUMMARY_TAG.exec(raw.slice(skipMatch.index, skipMatch.index + skipMatch[0].length))!;
const reason = originalSkip[1] ?? originalSkip[2];
return {
valid: true,
observations: [],
summary: {
request: null,
investigated: null,
learned: null,
completed: null,
next_steps: null,
notes: null,
skipped: true,
skip_reason: reason === undefined ? null : decodeXmlReferences(reason),
},
};
}
if (!firstRoot) {
return { valid: false };
}
const rootName = firstRoot[1].toLowerCase();
if (rootName === 'observation') {
const schemaDrift = new Set<string>();
const observations = parseObservationBlocks(raw, correlationId, schemaDrift);
if (observations.length === 0) {
return { valid: false };
}
return {
valid: true,
observations,
summary: null,
...(schemaDrift.size > 0 ? { schemaDrift: [...schemaDrift].sort() } : {}),
};
}
const summary = parseSummaryBlock(raw, correlationId);
if (!summary) {
return { valid: false };
}
return { valid: true, observations: [], summary };
}
function parseObservationBlocks(
text: string,
correlationId?: string | number,
schemaDrift?: Set<string>,
): ParsedObservation[] {
const observations: ParsedObservation[] = [];
const observationRegex = new RegExp(OBSERVATION_BLOCK.source, 'gi');
const markup = maskXmlLiteralMarkup(text);
let match;
while ((match = observationRegex.exec(markup)) !== null) {
const obsContent = originalElementBody(text, match);
const type = extractTypeField(obsContent);
const title = unwrapLabelWrappedTitle(extractField(obsContent, 'title'));
const subtitle = extractField(obsContent, 'subtitle');
const narrative = extractField(obsContent, 'narrative');
const facts = extractArrayElements(obsContent, 'facts', 'fact');
const concepts = extractArrayElements(obsContent, 'concepts', 'concept');
const files_read = extractArrayElements(obsContent, 'files_read', 'file');
const files_modified = extractArrayElements(obsContent, 'files_modified', 'file');
const attachments = extractAttachmentLabels(obsContent);
const mode = ModeManager.getInstance().getActiveMode();
const validTypes = mode.observation_types.map(t => t.id);
const fallbackType = validTypes[0];
let finalType = fallbackType;
if (type) {
finalType = type;
if (!validTypes.includes(type)) {
logger.error('PARSER', `Invalid observation type: ${type}, preserving emitted type`, { correlationId });
}
} else {
logger.error('PARSER', `Observation missing type field, defaulting to the first declared type: "${fallbackType}"`, { correlationId });
}
// #3379: concepts are matched exactly by the injection SQL, so a prefixed
// tag like "gotcha: WASM quirk" would never match. Truncate at the first
// ':' and trim, then drop empties and the observation type.
const cleanedConcepts = concepts
.map(c => {
const colonIndex = c.indexOf(':');
return (colonIndex === -1 ? c : c.slice(0, colonIndex)).trim();
})
.filter(c => c !== '' && c !== finalType);
let finalTitle = title;
let finalNarrative = narrative;
if (cleanedConcepts.length !== concepts.length) {
logger.debug('PARSER', 'Removed observation type from concepts array', {
correlationId,
type: finalType,
originalConcepts: concepts,
cleanedConcepts
});
}
if (!title && !narrative && facts.length === 0 && cleanedConcepts.length === 0) {
const salvageNarrative = extractUnstructuredObservationText(obsContent);
if (!salvageNarrative) {
logger.warn('PARSER', 'Skipping empty observation (all content fields null)', {
correlationId,
type: finalType
});
continue;
}
const salvage = extractObservationFallback(salvageNarrative);
finalTitle = salvage.title;
finalNarrative = salvage.narrative;
for (const tag of maskXmlLiteralMarkup(obsContent).matchAll(/<\/?([A-Za-z_][\w-]*)\b[^>]*>/g)) {
const name = tag[1].toLowerCase();
if (!OBSERVATION_SCHEMA_TAGS.has(name)) schemaDrift?.add(name);
}
logger.warn('PARSER', 'Salvaged unstructured observation prose as narrative', {
correlationId,
type: finalType,
chars: salvageNarrative.length
});
}
observations.push({
type: finalType,
title: finalTitle,
subtitle,
facts,
narrative: finalNarrative,
concepts: cleanedConcepts,
files_read,
files_modified,
...(attachments ? { attachments } : {}),
});
}
return observations;
}
function parseSummaryBlock(text: string, correlationId?: string | number): ParsedSummary | null {
const summaryMatch = SUMMARY_BLOCK.exec(maskXmlLiteralMarkup(text));
if (!summaryMatch) return null;
const summaryContent = originalElementBody(text, summaryMatch);
const request = extractField(summaryContent, 'request');
const investigated = extractField(summaryContent, 'investigated');
const learned = extractField(summaryContent, 'learned');
const completed = extractField(summaryContent, 'completed');
const next_steps = extractField(summaryContent, 'next_steps');
const notes = extractField(summaryContent, 'notes');
if (!request && !investigated && !learned && !completed && !next_steps && !notes) {
logger.warn('PARSER', 'Summary block has no sub-tags — rejecting false positive', { correlationId });
return null;
}
return {
request,
investigated,
learned,
completed,
next_steps,
notes,
};
}
// Some local observers echo the field label into the value, producing
// `<title>[**title**: Example observation]</title>`. Only this complete,
// unambiguous wrapper is unwrapped; partial forms and legitimately bracketed
// titles are stored as-is (#3907).
const LABEL_WRAPPED_TITLE = /^\[\*\*title\*\*:\s*([\s\S]+?)\s*\]$/;
function unwrapLabelWrappedTitle(title: string | null): string | null {
if (title === null) return null;
const match = LABEL_WRAPPED_TITLE.exec(title);
if (!match) return title;
const inner = match[1].trim();
return inner === '' ? title : inner;
}
// Decode only after extracting markup: an escaped tag is character data, not
// another element. A single replacement pass keeps &lt; as literal <.
const XML_ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
export function decodeXmlReferences(value: string): string {
return value.replace(/<!\[CDATA\[[\s\S]*?\]\]>|&(?:amp|lt|gt|quot|apos|#(?:x[0-9a-fA-F]+|[0-9]+));/g, reference => {
if (reference.startsWith('<![CDATA[')) return reference;
const name = reference.slice(1, -1);
if (!name.startsWith('#')) return XML_ENTITIES[name];
const codePoint = name.startsWith('#x') ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
// Only XML 1.0 legal characters are references; retain existing literal
// behavior for malformed/undeclared references in this text-XML bridge.
if (codePoint === 9 || codePoint === 10 || codePoint === 13 ||
(codePoint >= 0x20 && codePoint <= 0xD7FF) ||
(codePoint >= 0xE000 && codePoint <= 0xFFFD) ||
(codePoint >= 0x10000 && codePoint <= 0x10FFFF)) {
return String.fromCodePoint(codePoint);
}
return reference;
});
}
function extractField(content: string, fieldName: string): string | null {
const regex = new RegExp(elementPattern(fieldName), 'i');
const match = regex.exec(maskXmlLiteralMarkup(content));
if (!match) return null;
const trimmed = decodeXmlReferences(originalElementBody(content, match).trim());
return trimmed.trim() === '' ? null : trimmed;
}
/**
* The type is a single id, so no markup belongs in it. Models sometimes close
* it with a stray tag and re-open it (`<type>bugfix</parameter> <type>discovery</type>`),
* or restart the whole observation mid-type. The last `<type>` opened before
* the first `</type>` is the value the model settled on; any tag left inside
* it is dropped.
*/
function extractTypeField(content: string): string | null {
const markup = maskXmlLiteralMarkup(content);
const match = /<type[ \t\r\n]*>((?:(?!<type[ \t\r\n]*>)[\s\S])*?)<\/type[ \t\r\n]*>/i.exec(markup);
if (!match) {
// No </type> at all: the model closed it with a stray tag
// (`<type>gotcha</reasoning_effort>`). Accept one bare id, never prose.
const stray = /<type[ \t\r\n]*>\s*([A-Za-z][\w-]*)\s*<\/[A-Za-z_][\w-]*[ \t\r\n]*>/i.exec(markup);
return stray ? stray[1] : null;
}
const value = decodeXmlReferences(originalElementBody(content, match).replace(XML_ELEMENT_TAG_PATTERN, '')).trim();
return value === '' ? null : value;
}
function extractArrayElements(content: string, arrayName: string, elementName: string): string[] {
const elements: string[] = [];
const arrayRegex = new RegExp(elementPattern(arrayName), 'i');
const arrayMatch = arrayRegex.exec(maskXmlLiteralMarkup(content));
if (!arrayMatch) {
return elements;
}
const arrayContent = originalElementBody(content, arrayMatch);
const arrayMarkup = maskXmlLiteralMarkup(arrayContent);
const elementRegex = new RegExp(elementPattern(elementName), 'gi');
let elementMatch;
while ((elementMatch = elementRegex.exec(arrayMarkup)) !== null) {
const trimmed = decodeXmlReferences(originalElementBody(arrayContent, elementMatch).trim());
if (trimmed.trim()) {
elements.push(trimmed);
}
}
return elements;
}
function extractUnstructuredObservationText(content: string): string | null {
if (/<\/?(summary|skip_summary)\b/i.test(content)) {
return null;
}
const stripped = content
.replace(
/<(type|title|subtitle|narrative|facts|concepts|files_read|files_modified|attachments)(?:[ \t\r\n]*\/>|[ \t\r\n]*>[\s\S]*?<\/\1[ \t\r\n]*>)/gi,
' '
)
.replace(/<[^>]+>/g, ' ')
.replace(/\r\n/g, '\n')
.split('\n')
.map(line => line.trim())
.filter(line => line !== '')
.join('\n')
.trim();
return stripped === '' ? null : stripped;
}
function extractObservationFallback(text: string): { title: string; narrative: string | null } {
const lines = text
.split('\n')
.map(line => line.trim())
.filter(line => line !== '');
const firstLine = lines[0] ?? text.trim();
const firstLineGraphemes = Array.from(observationGraphemeSegmenter.segment(firstLine), part => part.segment);
const hasOverflow = firstLineGraphemes.length > OBSERVATION_TITLE_MAX_GRAPHEMES;
const title = hasOverflow
? `${firstLineGraphemes.slice(0, OBSERVATION_TITLE_TRUNCATE_AT).join('')}...`
: firstLine;
const narrativeLines = hasOverflow
? [firstLineGraphemes.slice(OBSERVATION_TITLE_TRUNCATE_AT).join('').trim(), ...lines.slice(1)]
: lines.slice(1);
const narrative = narrativeLines
.filter(line => line !== '')
.join('\n')
.trim();
return {
title,
narrative: narrative === '' ? null : narrative,
};
}