Compare commits

...
9 Commits
Author SHA1 Message Date
ztimson 6bed8f20b5 Recursive agents update
Publish Library / Build NPM Project (push) Successful in 36s
Publish Library / Tag Version (push) Successful in 7s
2026-09-20 00:43:52 -04:00
ztimson dc45a99b04 Bump 1.6.13
Publish Library / Build NPM Project (push) Successful in 41s
Publish Library / Tag Version (push) Successful in 14s
2026-09-19 19:30:06 -04:00
ztimson 263a65c192 Fix open-ai early termination & memory improvements
Publish Library / Build NPM Project (push) Successful in 48s
Publish Library / Tag Version (push) Successful in 7s
2026-09-19 19:27:00 -04:00
ztimson 1e8c7c6662 Fix open-ai early termination
Publish Library / Build NPM Project (push) Successful in 1m47s
Publish Library / Tag Version (push) Successful in 8s
2026-09-19 13:22:48 -04:00
ztimson 1f1a4662d4 Entity based notes
Publish Library / Build NPM Project (push) Successful in 41s
Publish Library / Tag Version (push) Successful in 14s
2026-09-18 22:37:05 -04:00
ztimson ee4147e24e Fixed opanai early termination from tool calls
Publish Library / Build NPM Project (push) Successful in 46s
Publish Library / Tag Version (push) Successful in 15s
2026-09-18 16:07:58 -04:00
ztimson d29c0ca389 Fixed opanai early termination from tool calls
Publish Library / Build NPM Project (push) Successful in 55s
Publish Library / Tag Version (push) Successful in 9s
2026-09-18 02:15:02 -04:00
ztimson 4203cb34ef Better fact organization
Publish Library / Build NPM Project (push) Successful in 40s
Publish Library / Tag Version (push) Successful in 10s
2026-09-14 12:22:49 -04:00
ztimson d42c240362 Memorization optimziations
Publish Library / Build NPM Project (push) Successful in 1m2s
Publish Library / Tag Version (push) Successful in 10s
2026-08-31 12:38:40 -04:00
7 changed files with 632 additions and 301 deletions
+6 -6
View File
@@ -1,19 +1,19 @@
{ {
"name": "@ztimson/ai-utils", "name": "@ztimson/ai-utils",
"version": "1.5.0", "version": "1.6.6",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@ztimson/ai-utils", "name": "@ztimson/ai-utils",
"version": "1.5.0", "version": "1.6.6",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^0.102.0", "@anthropic-ai/sdk": "^0.102.0",
"@huggingface/transformers": "^4.2.0", "@huggingface/transformers": "^4.2.0",
"@tensorflow/tfjs": "^4.22.0", "@tensorflow/tfjs": "^4.22.0",
"@ztimson/node-utils": "^1.0.7", "@ztimson/node-utils": "^1.0.7",
"@ztimson/utils": "^0.29.4", "@ztimson/utils": "^0.30.8",
"cheerio": "^1.2.0", "cheerio": "^1.2.0",
"openai": "^6.42.0", "openai": "^6.42.0",
"pdf-parse": "^2.4.5", "pdf-parse": "^2.4.5",
@@ -1525,9 +1525,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@ztimson/utils": { "node_modules/@ztimson/utils": {
"version": "0.29.7", "version": "0.30.8",
"resolved": "https://registry.npmjs.org/@ztimson/utils/-/utils-0.29.7.tgz", "resolved": "https://registry.npmjs.org/@ztimson/utils/-/utils-0.30.8.tgz",
"integrity": "sha512-cjQ9+RjC5X7gKNA/hJHDf7OtyYCa+5E0PDc76lIaATwNAxXCSx2IO9r2wHiHtZGV5bldjnFmw7aOV8Jmq7SgKQ==", "integrity": "sha512-+vBjcinqckqMHkP95xWiQeQz2E7Q1oS0b+Odjp+F9rvQ4z0US4JdodjqhEaqh+RAO/yP77x4Eu0a04yBB4HNdw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"var-persist": "^1.0.1" "var-persist": "^1.0.1"
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@ztimson/ai-utils", "name": "@ztimson/ai-utils",
"version": "1.6.6", "version": "1.7.0",
"description": "AI Utility library", "description": "AI Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",
@@ -29,7 +29,7 @@
"@huggingface/transformers": "^4.2.0", "@huggingface/transformers": "^4.2.0",
"@tensorflow/tfjs": "^4.22.0", "@tensorflow/tfjs": "^4.22.0",
"@ztimson/node-utils": "^1.0.7", "@ztimson/node-utils": "^1.0.7",
"@ztimson/utils": "^0.29.4", "@ztimson/utils": "^0.30.8",
"cheerio": "^1.2.0", "cheerio": "^1.2.0",
"openai": "^6.42.0", "openai": "^6.42.0",
"pdf-parse": "^2.4.5", "pdf-parse": "^2.4.5",
+50
View File
@@ -13,6 +13,56 @@ export function extractLinks(content: string): string[] {
return [...new Set([...matches].map(m => m[1].trim()))]; return [...new Set([...matches].map(m => m[1].trim()))];
} }
/**
* Incrementally patch the graph for a set of changed memories, instead of
* re-scanning every document. Only the changed memories' own content is
* re-parsed for links; affected targets have their backlinks patched.
* Does NOT handle node deletion — full rebuildGraph() is still required
* when a memory is removed, since that needs a backlink sweep across
* everyone who might reference it.
*/
export function patchGraph(mems: Memory[], nodes: MemoryNode[], changed: Memory[]): MemoryNode[] {
const nameSet = new Set(mems.map(m => m.name));
const byName = new Map(nodes.map(n => [n.name, n]));
const ensureNode = (name: string): MemoryNode => {
let n = byName.get(name);
if (!n) {
n = {name, missing: !nameSet.has(name), links: [], backlinks: []};
byName.set(name, n);
}
return n;
};
for (const m of changed) {
const node = ensureNode(m.name);
node.missing = false; // real memory, promotes any pre-existing ghost entry
const oldLinks = m.links ?? [];
const newLinks = extractLinks(m.content).filter(l => l !== m.name);
for (const target of oldLinks.filter(l => !newLinks.includes(l))) {
const t = byName.get(target);
if (!t) continue;
t.backlinks = t.backlinks.filter(n => n !== m.name);
if (t.missing && !t.backlinks.length) byName.delete(target); // fully dereferenced ghost
}
for (const target of newLinks.filter(l => !oldLinks.includes(l))) {
const t = ensureNode(target);
if (!t.backlinks.includes(m.name)) t.backlinks.push(m.name);
}
m.links = newLinks;
node.links = newLinks;
}
for (const m of mems) {
const n = byName.get(m.name);
if (n) m.backlinks = n.backlinks;
}
return [...byName.values()];
}
export function rebuildGraph(memories: Memory[] | MemoryCache): MemoryNode[] { export function rebuildGraph(memories: Memory[] | MemoryCache): MemoryNode[] {
const mems = memories instanceof MemoryCache ? memories.memories : memories; const mems = memories instanceof MemoryCache ? memories.memories : memories;
const nameSet = new Set(mems.map(m => m.name)); const nameSet = new Set(mems.map(m => m.name));
+48 -7
View File
@@ -15,6 +15,7 @@ interface KDNode<T> {
axis: number; axis: number;
left: KDNode<T> | null; left: KDNode<T> | null;
right: KDNode<T> | null; right: KDNode<T> | null;
deleted?: boolean;
} }
// ─── Distance helpers ───────────────────────────────────────────────────────── // ─── Distance helpers ─────────────────────────────────────────────────────────
@@ -95,6 +96,7 @@ class BoundedMaxHeap<T> {
* *
* Supports: * Supports:
* - Insertion of labeled points * - Insertion of labeled points
* - Lazy (tombstone) removal, physically purged on rebalance()
* - k-nearest-neighbor (KNN) search * - k-nearest-neighbor (KNN) search
* - Radius search (all points within a given distance) * - Radius search (all points within a given distance)
* - Euclidean and cosine distance metrics * - Euclidean and cosine distance metrics
@@ -103,6 +105,7 @@ class BoundedMaxHeap<T> {
export class KDTree<T = unknown> { export class KDTree<T = unknown> {
private root: KDNode<T> | null = null; private root: KDNode<T> | null = null;
private _size = 0; private _size = 0;
private _tombstones = 0;
private readonly distanceFn: (a: number[], b: number[]) => number; private readonly distanceFn: (a: number[], b: number[]) => number;
readonly dims: number; readonly dims: number;
@@ -129,9 +132,15 @@ export class KDTree<T = unknown> {
} }
} }
/** Total number of points stored in the tree. */ /** Total number of live points stored in the tree (excludes tombstoned). */
get size(): number { return this._size; } get size(): number { return this._size; }
/** Fraction of physical nodes that are tombstoned (pending removal on next rebalance). */
get tombstoneRatio(): number {
const total = this._size + this._tombstones;
return total ? this._tombstones / total : 0;
}
// ── Insertion ────────────────────────────────────────────────────────────── // ── Insertion ──────────────────────────────────────────────────────────────
/** /**
@@ -144,10 +153,36 @@ export class KDTree<T = unknown> {
this._size++; this._size++;
} }
// ── Removal ────────────────────────────────────────────────────────────────
/**
* Lazily remove all live points whose payload matches `predicate`.
* O(n) traversal, but avoids a full tree rebuild. Call `rebalance()`
* periodically (e.g. once tombstoneRatio crosses ~0.25) to reclaim space
* and restore optimal query depth.
* @returns number of points removed
*/
remove(predicate: (payload: T) => boolean): number {
let removed = 0;
const visit = (node: KDNode<T> | null): void => {
if (!node) return;
if (!node.deleted && predicate(node.point.payload)) {
node.deleted = true;
removed++;
}
visit(node.left);
visit(node.right);
};
visit(this.root);
this._size -= removed;
this._tombstones += removed;
return removed;
}
// ── KNN search ───────────────────────────────────────────────────────────── // ── KNN search ─────────────────────────────────────────────────────────────
/** /**
* Find the k nearest neighbors to `query`. * Find the k nearest live neighbors to `query`.
* Returns results sorted by distance ascending. * Returns results sorted by distance ascending.
*/ */
knn(query: number[], k: number): KNNResult<T>[] { knn(query: number[], k: number): KNNResult<T>[] {
@@ -171,7 +206,7 @@ export class KDTree<T = unknown> {
// ── Radius search ────────────────────────────────────────────────────────── // ── Radius search ──────────────────────────────────────────────────────────
/** /**
* Return all points whose distance to `query` is ≤ `radius`, * Return all live points whose distance to `query` is ≤ `radius`,
* sorted by distance ascending. * sorted by distance ascending.
*/ */
radiusSearch(query: number[], radius: number): KNNResult<T>[] { radiusSearch(query: number[], radius: number): KNNResult<T>[] {
@@ -186,7 +221,7 @@ export class KDTree<T = unknown> {
// ── Conversion ───────────────────────────────────────────────────────────── // ── Conversion ─────────────────────────────────────────────────────────────
/** Collect all points in the tree (order not guaranteed). */ /** Collect all live points in the tree (order not guaranteed). */
toArray(): KDPoint<T>[] { toArray(): KDPoint<T>[] {
const out: KDPoint<T>[] = []; const out: KDPoint<T>[] = [];
this.collect(this.root, out); this.collect(this.root, out);
@@ -194,12 +229,14 @@ export class KDTree<T = unknown> {
} }
/** /**
* Rebuild the tree from its current points as a balanced tree. * Rebuild the tree from its current live points as a balanced tree.
* Useful after many individual insertions to restore O(log n) query time. * Physically purges tombstones and restores O(log n) query time.
*/ */
rebalance(): void { rebalance(): void {
const points = this.toArray(); const points = this.toArray();
this.root = points.length ? this.buildBalanced(points, 0) : null; this.root = points.length ? this.buildBalanced(points, 0) : null;
this._size = points.length;
this._tombstones = 0;
} }
// ── Private: build ───────────────────────────────────────────────────────── // ── Private: build ─────────────────────────────────────────────────────────
@@ -251,8 +288,10 @@ export class KDTree<T = unknown> {
): void { ): void {
if (node === null) return; if (node === null) return;
if (!node.deleted) {
const dist = this.distanceFn(query, node.point.vector); const dist = this.distanceFn(query, node.point.vector);
heap.push({ point: node.point, distance: dist }); heap.push({ point: node.point, distance: dist });
}
const axis = node.axis; const axis = node.axis;
const diff = query[axis] - node.point.vector[axis]; const diff = query[axis] - node.point.vector[axis];
@@ -285,10 +324,12 @@ export class KDTree<T = unknown> {
): void { ): void {
if (node === null) return; if (node === null) return;
if (!node.deleted) {
const dist = this.distanceFn(query, node.point.vector); const dist = this.distanceFn(query, node.point.vector);
if (dist <= radius) { if (dist <= radius) {
results.push({ point: node.point, distance: dist }); results.push({ point: node.point, distance: dist });
} }
}
const axis = node.axis; const axis = node.axis;
const diff = query[axis] - node.point.vector[axis]; const diff = query[axis] - node.point.vector[axis];
@@ -310,7 +351,7 @@ export class KDTree<T = unknown> {
private collect(node: KDNode<T> | null, out: KDPoint<T>[]): void { private collect(node: KDNode<T> | null, out: KDPoint<T>[]): void {
if (node === null) return; if (node === null) return;
out.push(node.point); if (!node.deleted) out.push(node.point);
this.collect(node.left, out); this.collect(node.left, out);
this.collect(node.right, out); this.collect(node.right, out);
} }
+19 -13
View File
@@ -19,6 +19,13 @@ const PDF_OCR_PAGE_THRESHOLD = 12; // above this many pages, OCR scanned pages i
export type AnthropicConfig = {proto: 'anthropic', token: string | string[]}; export type AnthropicConfig = {proto: 'anthropic', token: string | string[]};
export type OpenAiConfig = {proto: 'openai', host?: string, token: string | string[]}; export type OpenAiConfig = {proto: 'openai', host?: string, token: string | string[]};
export type AgentRef = {
name: string;
description?: string;
delegate?: boolean;
fn: () => Agent | null | Promise<Agent | null>;
}
export type Agent = { export type Agent = {
name: string; name: string;
description?: string; description?: string;
@@ -29,7 +36,7 @@ export type Agent = {
skills?: Skill[] | null; skills?: Skill[] | null;
tools?: AiTool[] | null; tools?: AiTool[] | null;
mcp?: McpServer[] | null; mcp?: McpServer[] | null;
agents?: string[] | null; agents?: AgentRef[] | null;
} }
export type LLMFile = { export type LLMFile = {
@@ -106,8 +113,8 @@ export type LLMRequest = {
skills?: Skill[]; skills?: Skill[];
/** MCP servers to connect and expose as tools */ /** MCP servers to connect and expose as tools */
mcp?: McpServer[]; mcp?: McpServer[];
/** Subagents exposed as delegatable/wrapped tools */ /** Subagents exposed as delegatable/wrapped tools, resolved lazily via their `fn` */
agents?: Agent[]; agents?: AgentRef[];
/** Attach files to request */ /** Attach files to request */
files?: LLMFile[]; files?: LLMFile[];
/** @internal recursion guard for nested agent delegation */ /** @internal recursion guard for nested agent delegation */
@@ -265,22 +272,21 @@ class LLM {
}; };
} }
private setupAgent(agents: Agent[] = [], allAgents: Agent[], history: LLMMessage[], aborts: ((keep?: boolean) => void)[], depth = 0, delegateState: {resp: string | null}): AiTool[] { private setupAgent(stubs: AgentRef[] = [], history: LLMMessage[], aborts: ((keep?: boolean) => void)[], depth = 0, delegateState: {resp: string | null}): AiTool[] {
return agents.map(a => { return stubs.map(stub => {
const toolName = `${a.delegate ? '' : 'sub'}agent_${snakeCase(a.name)}`; const toolName = `${stub.delegate ? '' : 'sub'}agent_${snakeCase(stub.name)}`;
return { return {
name: toolName, name: toolName,
description: `${a.delegate ? 'Delegate to ' : ''}Subagent: ${a.description || a.name}`, description: `${stub.delegate ? 'Delegate to ' : ''}Subagent: ${stub.description || stub.name}`,
args: clean<any>({ args: clean<any>({
context: !a.delegate ? {type: 'string', description: 'Summary of related messages, samples, files, etc...', required: true} : undefined, context: !stub.delegate ? {type: 'string', description: 'Summary of related messages, samples, files, etc...', required: true} : undefined,
instructions: {type: 'string', description: 'Detailed instructions for subagent to complete', required: true}, instructions: {type: 'string', description: 'Detailed instructions for subagent to complete', required: true},
}), }),
fn: async (args: any, stream: any, ai: any, id?: string) => { fn: async (args: any, stream: any, ai: any, id?: string) => {
if(depth >= MAX_AGENT_DEPTH) return 'Max agent delegation depth exceeded'; if(depth >= MAX_AGENT_DEPTH) return 'Max agent delegation depth exceeded';
const nested = (a.agents || []) const a = await stub.fn();
.map(name => allAgents.find(x => x.name === name)) if(!a) return `Agent "${stub.name}" could not be resolved`;
.filter((x): x is Agent => !!x && x.name !== a.name);
const q = a.delegate ? '' : `${args.instructions}${args.context ? `\n\n<context>${args.context}</context>` : ''}`; const q = a.delegate ? '' : `${args.instructions}${args.context ? `\n\n<context>${args.context}</context>` : ''}`;
@@ -297,7 +303,7 @@ ${a.system}`,
mcp: a.mcp || undefined, mcp: a.mcp || undefined,
skills: a.skills || undefined, skills: a.skills || undefined,
tools: a.tools || undefined, tools: a.tools || undefined,
agents: nested, agents: a.agents || [],
_agentDepth: depth + 1, _agentDepth: depth + 1,
} as any); } as any);
aborts.push(request.abort); aborts.push(request.abort);
@@ -451,7 +457,7 @@ ${a.system}`,
// Agents // Agents
const agents = options.agents || this.ai.options?.llm?.agents; const agents = options.agents || this.ai.options?.llm?.agents;
const delegateState: {resp: string | null} = {resp: null}; const delegateState: {resp: string | null} = {resp: null};
if(agents?.length) tools.push(...this.setupAgent(agents, agents, history, nestedAborts, options._agentDepth || 0, delegateState)); if(agents?.length) tools.push(...this.setupAgent(agents, history, nestedAborts, options._agentDepth || 0, delegateState));
// Memory // Memory
const mem = MemoryManager.normalize(options.memory); const mem = MemoryManager.normalize(options.memory);
+343 -186
View File
@@ -1,24 +1,21 @@
import {MemoryNode, rebuildGraph} from './helpers.ts'; import {MemoryNode, patchGraph, rebuildGraph} from './helpers.ts';
import {LLMRequest, LLMMessage} from './llm.ts'; import {LLMRequest, LLMMessage} from './llm.ts';
import {AiTool} from './tools.ts'; import {AiTool} from './tools.ts';
import {KDPoint, KDTree} from './kd-tree.ts'; import {KDTree} from './kd-tree.ts';
import {escapeRegex} from '@ztimson/utils';
const MERGE_THRESHOLD = 0.12; const FACT_SIMILARITY_THRESHOLD = 0.62;
const PENDING_HEADING = '## Pending'; const PENDING_HEADING = '## Pending';
const GENERIC_TEMPLATE = `# {{Title}} const TODO_HEADING = '## Todo list';
const TREE_TOMBSTONE_LIMIT = 0.25;
## Summary const ALIAS_MATCH_THRESHOLD = 0.55;
## Details
## Related`;
export type Memory = { export type Memory = {
name: string; name: string;
description: string; description: string;
content: string; content: string;
embedding: number[]; embedding: number[];
titleEmbedding?: number[];
bodyEmbeddings?: number[][];
links: string[]; links: string[];
backlinks: string[]; backlinks: string[];
} }
@@ -26,6 +23,7 @@ export type Memory = {
type MemoryRef = { type MemoryRef = {
name: string; name: string;
description: string; description: string;
distance?: number;
} }
type FactBucket = { type FactBucket = {
@@ -33,9 +31,17 @@ type FactBucket = {
facts: string[]; facts: string[];
} }
type MemoryTask = {
/** Exact node name / new persistent entity path this task belongs to, or '' for a personal task with no entity (goes to the journal) */
subject: string;
task: string;
done: boolean;
}
type FactAgentResult = { type FactAgentResult = {
buckets: FactBucket[]; buckets: FactBucket[];
journal: string; journal: string;
tasks: MemoryTask[];
} }
function dedupeFacts(facts: string[]): string[] { function dedupeFacts(facts: string[]): string[] {
@@ -61,18 +67,34 @@ function cosineDistance(a: number[], b: number[]): number {
function cosineSearch(query: number[], memories: Memory[], limit: number): MemoryRef[] { function cosineSearch(query: number[], memories: Memory[], limit: number): MemoryRef[] {
return memories return memories
.filter(m => m.embedding?.length) .filter(m => m.embedding?.length)
.map(m => ({ref: {name: m.name, description: m.description}, distance: cosineDistance(query, m.embedding)})) .map(m => ({name: m.name, description: m.description, distance: cosineDistance(query, m.embedding)}))
.sort((a, b) => a.distance - b.distance) .sort((a, b) => a.distance - b.distance)
.slice(0, limit) .slice(0, limit);
.map(s => s.ref); }
async function embedMemoryFields(node: Memory, llm: any): Promise<void> {
const body = stripHeader(node.content);
const [titleE] = await llm.embedding(node.name.split('/').pop() || node.name);
const [descE] = await llm.embedding(node.description || '');
const bodyChunks = body ? await llm.embedding(body) : [];
if(titleE) node.titleEmbedding = titleE.embedding;
if(descE) node.embedding = descE.embedding;
node.bodyEmbeddings = bodyChunks.map((c: any) => c.embedding).filter(Boolean);
} }
export function stripHeader(content: string): string { export function stripHeader(content: string): string {
return content.replace(/^---[\s\S]*?\n---\n?/, '').trimStart(); return content.replace(/^---[\s\S]*?\n---\n?/, '').trimStart();
} }
/** True if a task has no persistent entity of its own and belongs in the journal instead. */
function isPersonalTask(t: MemoryTask): boolean {
const s = (t.subject ?? '').trim().toLowerCase();
return !s || s === 'journal' || s.startsWith('journal/');
}
export class MemoryCache { export class MemoryCache {
private tree!: KDTree<MemoryRef>; private tree!: KDTree<MemoryRef>;
private indexed = new Map<string, number[]>();
public memories: Memory[]; public memories: Memory[];
public nodes: MemoryNode[] = []; public nodes: MemoryNode[] = [];
@@ -80,37 +102,47 @@ export class MemoryCache {
constructor(memories: Memory[]) { constructor(memories: Memory[]) {
this.memories = memories; this.memories = memories;
this.tree = new KDTree<MemoryRef>(0);
this.rebuild(); this.rebuild();
} }
private buildTree(): KDTree<MemoryRef> { private syncTree(): void {
const embedded = this.memories.filter(m => m.embedding?.length); const current = new Set(this.memories.map(m => m.name));
if (!embedded.length) return new KDTree<MemoryRef>(0);
const dims = embedded[0].embedding.length; for(const [name, emb] of [...this.indexed]) {
const points: KDPoint<MemoryRef>[] = embedded.map(m => ({ const mem = this.memories.find(m => m.name === name);
vector: m.embedding, if(!mem || !current.has(name) || mem.embedding !== emb) {
payload: {name: m.name, description: m.description}, this.tree.remove(p => p.name === name);
})); this.indexed.delete(name);
}
}
return new KDTree<MemoryRef>(dims, 'cosine', points); for(const mem of this.memories) {
if(!mem.embedding?.length || this.indexed.has(mem.name)) continue;
if(this.tree.dims === 0) this.tree = new KDTree<MemoryRef>(mem.embedding.length, 'cosine');
if(mem.embedding.length !== this.tree.dims) continue; // guard against embedding model/dim drift
this.tree.insert({vector: mem.embedding, payload: {name: mem.name, description: mem.description}});
this.indexed.set(mem.name, mem.embedding);
}
if(this.tree.tombstoneRatio > TREE_TOMBSTONE_LIMIT) this.tree.rebalance();
} }
search(query: number[], limit: number): MemoryRef[] { search(query: number[], limit: number): MemoryRef[] {
if(!this.tree || this.tree.dims === 0) return []; if(!this.tree || this.tree.dims === 0) return [];
return this.tree.knn(query, limit).map(r => r.point.payload); return this.tree.knn(query, limit).map(r => ({...r.point.payload, distance: r.distance}));
} }
add(memory: Memory): void { add(memory: Memory): void {
this.memories.push(memory); this.memories.push(memory);
this.rebuild(); this.rebuild([memory]);
} }
update(memory: Memory): void { update(memory: Memory): void {
const existing = this.memories.find(m => m.name === memory.name); const existing = this.memories.find(m => m.name === memory.name);
if(existing) Object.assign(existing, memory); if(existing) Object.assign(existing, memory);
else this.memories.push(memory); else this.memories.push(memory);
this.rebuild(); this.rebuild([existing ?? memory]);
} }
remove(name: string): void { remove(name: string): void {
@@ -121,9 +153,11 @@ export class MemoryCache {
} }
} }
rebuild(): void { rebuild(changed?: Memory[]): void {
this.nodes = rebuildGraph(this.memories); this.nodes = (changed?.length && this.nodes.length)
this.tree = this.buildTree(); ? patchGraph(this.memories, this.nodes, changed)
: rebuildGraph(this.memories);
this.syncTree();
} }
} }
@@ -140,9 +174,9 @@ class MemoryAccessor {
return this.list.find(m => m.name === name); return this.list.find(m => m.name === name);
} }
commit(): MemoryNode[] { commit(changed?: Memory[]): MemoryNode[] {
if(this.cache) { if(this.cache) {
this.cache.rebuild(); this.cache.rebuild(changed);
return this.cache.nodes; return this.cache.nodes;
} }
return rebuildGraph(this.list); return rebuildGraph(this.list);
@@ -168,10 +202,7 @@ class MemoryAccessor {
async backfillEmbeddings(llm: any): Promise<number> { async backfillEmbeddings(llm: any): Promise<number> {
const missing = this.list.filter(m => !m.embedding?.length); const missing = this.list.filter(m => !m.embedding?.length);
if(!missing.length) return 0; if(!missing.length) return 0;
await Promise.all(missing.map(async node => { await Promise.all(missing.map(node => embedMemoryFields(node, llm)));
const [e] = await llm.embedding(`${node.description}\n\n${stripHeader(node.content)}`.trim());
if (e) node.embedding = e.embedding;
}));
this.commit(); this.commit();
return missing.length; return missing.length;
} }
@@ -216,10 +247,10 @@ export class MemoryManager {
name: 'memory_recall', name: 'memory_recall',
description: 'Read the full content of a memory document', description: 'Read the full content of a memory document',
args: { args: {
name: {type: 'string', description: 'Exact memory name', required: true}, name: {type: 'string', description: 'Exact memory name', required: true}
}, },
fn: (args: any) => { fn: (args: any) => {
const mem = this.access(memories).find(args.name); const mem = new MemoryAccessor(memories).find(args.name);
if(!mem) return 'Document not found'; if(!mem) return 'Document not found';
this.touch(mem.name); this.touch(mem.name);
return mem.content; return mem.content;
@@ -234,7 +265,7 @@ export class MemoryManager {
limit: {type: 'number', description: 'Number of memories to return', default: 1}, limit: {type: 'number', description: 'Number of memories to return', default: 1},
}, },
fn: async ({query, limit}) => { fn: async ({query, limit}) => {
const mem = await this.recollect(query, memories, limit) const mem = await this.recollect(query, memories, limit);
return mem.map(m => `Memory: ${m.name} return mem.map(m => `Memory: ${m.name}
Description: ${m.description} Description: ${m.description}
Links: ${[...m.links, ...m.backlinks].join(', ')} Links: ${[...m.links, ...m.backlinks].join(', ')}
@@ -253,12 +284,11 @@ ${m.content}
return raw ? {memory: <Memory[] | MemoryCache>m, inject: true, tool: true, update: true} : {inject: true, tool: true, update: true, ...m}; return raw ? {memory: <Memory[] | MemoryCache>m, inject: true, tool: true, update: true} : {inject: true, tool: true, update: true, ...m};
} }
private access(memories: Memory[] | MemoryCache): MemoryAccessor {
return new MemoryAccessor(memories);
}
private stage(node: Memory, block: string): void { private stage(node: Memory, block: string): void {
this.ensureDoc(node); if(!node.content) {
const title = node.name.split('/').pop() ?? node.name;
node.content = this.touchHeader(node, `# ${title}\n`);
}
const body = stripHeader(node.content); const body = stripHeader(node.content);
const idx = body.indexOf(PENDING_HEADING); const idx = body.indexOf(PENDING_HEADING);
const newBody = idx === -1 const newBody = idx === -1
@@ -267,19 +297,30 @@ ${m.content}
node.content = this.touchHeader(node, newBody); node.content = this.touchHeader(node, newBody);
} }
private ensureDoc(node: Memory): void { private resolveSubject(subject: string, store: MemoryAccessor): string {
if (node.content) return; function normalize(name: string): string {
const title = node.name.split('/').pop() ?? node.name; return name.trim().toLowerCase().replace(/\s+/g, ' ');
node.content = this.touchHeader(node, `# ${title}\n`);
} }
private sanitizeDescription(text: string): string { const trimmed = subject.trim();
return (text ?? '').replace(/\s+/g, ' ').trim().slice(0, 240); const exact = store.find(trimmed);
} if(exact) return exact.name;
private relink(memories: Memory[], from: string, to: string): void { const normalized = normalize(trimmed);
const pattern = new RegExp(`\\[\\[${escapeRegex(from)}\\]\\]`, 'g'); const caseInsensitive = store.list.find(m => normalize(m.name) === normalized);
for (const m of memories) if (pattern.test(m.content)) m.content = m.content.replace(pattern, `[[${to}]]`); if(caseInsensitive) return caseInsensitive.name;
const root = trimmed.split('/')[0];
const leaf = trimmed.split('/').slice(1).join('/') || trimmed;
const candidates = store.list.filter(m => m.name.split('/')[0] === root && m.name !== trimmed);
if(!candidates.length) return trimmed;
const leaves = candidates.map(m => m.name.split('/').slice(1).join('/') || m.name);
const probe = leaves.length > 1 ? leaves : [...leaves, ''];
const {max, similarities} = this.llm.fuzzyMatch(leaf, ...probe);
if(max >= ALIAS_MATCH_THRESHOLD) return candidates[similarities.indexOf(max)].name;
return trimmed;
} }
private async factAgent(conversation: string, store: MemoryAccessor, options: LLMRequest): Promise<FactAgentResult> { private async factAgent(conversation: string, store: MemoryAccessor, options: LLMRequest): Promise<FactAgentResult> {
@@ -288,36 +329,70 @@ ${m.content}
const response = await this.llm.ask(conversation, { const response = await this.llm.ask(conversation, {
model: options.model, model: options.model,
temperature: 0.2, temperature: 0.2,
system: `You are a fact extractor for Obsidian-style knowledge vaults. Analyze the conversation and produce: system: `Turn this conversation into a persistent memory file by extracting information into organized bullet points
1. Journal recap (single paragraph) Think of this like an Obsidian vault with a clear division of responsibility:
- "Captains Log" style record keeping - The JOURNAL is a timeline. It answers "what happened, and when" and is the only place with a sense of time.
- What was discussed/worked on, decisions, user's events/state/mood, general context - ENTITY DOSSIERS are a wiki. They answer "what is currently true about this subject", with no sense of time — only current state.
- Leave empty only for trivial/empty exchanges/small talk - Never blur the two: a one-off event, conversation, or debugging session is a journal entry, not an entity, even if it's detailed.
2. Fact buckets 1. Journal Log
- ONLY facts the USER explicitly stated about themselves, their work, projects, or decisions made during this conversation - A chronological, skimmable log of what actually happened: real discussions, decisions made, progress on projects, problems worked through
- NEVER extract greetings, pleasantries, or anything the assistant itself said - This is NOT a transcript, and it is NOT a step-by-step record, its a compressed log of notable events & developments
- Extract the final/end state, not deltas - One line per development is usually enough: what was worked on and the outcome, not the blow-by-blow of how
- Skip small talk and trivial exchanges entirely. Skip anything that's purely a todo item (goes in Todo Tasks) or a durable fact about a subject (goes in Entity Dossiers)
Path assignment rules: 2. Todo Tasks
- Reuse existing node names whenever possible - Extract concrete tasks the user says need to be done, should be done, or were completed
- Documents should be grouped and named by the root subject - Return the task text and whether it is still todo or is done
- Person → People/Name - A completed task should be marked done, not recreated as a new todo
- Project → Projects/Name - Only extract actionable tasks, not general goals or observations
- Concept → Concepts/Name - Assign each task a subject:
- A bug report, its investigation, should be nested and attached to the same root subject node - If the task belongs to a persistent entity (a project, a class, etc.), use that entity's exact node name, or a new entity path if it doesn't exist yet
- Tickets/one-off tasks → file under the project/name/component they belong to - If it's a personal/life task with no entity of its own (reach out to someone, reply to an email, pay a bill, etc.), leave subject as an empty string — it belongs in the journal, not a new document
- Only create a new top-level node when the fact belongs to a genuinely new subject (person/project/concept)\`
3. Entity Dossiers
- Detailed dossiers with all information regarding a subject
- Record the final/end state, not intermediate changes
- Ignore assistant claims, guesses, greetings, or temporary details
- NEVER create a document for something that's only meaningful as a point in time — a single conversation, a one-off decision, a debugging session, a date. That's a journal entry, not an entity
- identify its HOME ENTITY:
- The HOME ENTITY name should always be a [abstract|pro]noun
- The grammatical subject/owner of the fact is the strongest clue
- Always preference an existing entity over creating a new one
- New child entities are appropriate only when they are themselves distinct persistent entities
- A document represents a persistent entity, not a topic, feature, bug, event, decision, setting, or conversation fragment
- Put project facts under the project they belong to, person facts under the person, etc
Example Entity Naming Convention:
- Projects/[Name]
- People/[Name]
- History/[Name]
- Science/[Name]
- [Subject]/[Name]
- Class/[Name]/[Chapter]
Use [[WikiLinks]] to express relationships between entities. NEVER create documents just to hold relationships
Keep journal material in the journal; don't turn journal events into entities unless they represent something persistent
Available nodes: Available nodes:
${this.listNodes(store.list).map(n => `- ${n.name}: ${n.description}`).join('\n') || 'None yet.'} ${this.listNodes(store.list).map(n => `- ${n.name}: ${n.description}`).join('\n') || 'None yet.'}
${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`, ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
schema: { schema: {
journal: {type: 'string', description: 'Short day-to-day recap; empty if nothing happened.', required: false}, journal: {type: 'string', description: 'Short day-to-day recap; empty if nothing happened.', required: false},
buckets: {type: 'array', description: 'Groups of facts to remember; empty array if nothing worth storing.', items: { tasks: {
type: 'array', description: 'Concrete tasks mentioned or completed in the conversation.', required: false, items: {
type: 'object', items: { type: 'object', items: {
subject: {type: 'string', description: 'Exact node name or new path (e.g. "People/Sarah", "Projects/Oxide")', required: true}, subject: {type: 'string', description: 'Exact node name / new persistent entity path this task belongs to, or an empty string if this is a personal task with no entity of its own (those go in the journal)', required: true},
task: {type: 'string', description: 'Concise actionable task', required: true},
done: {type: 'boolean', description: 'Whether the task is completed', required: true},
},
}
},
buckets: {
type: 'array', description: 'Groups of facts to remember; empty array if nothing worth storing.', items: {
type: 'object', items: {
subject: {type: 'string', description: 'Exact node name or new persistent entity path', required: true},
facts: {type: 'array', description: 'Facts to store here', items: {type: 'string'}}, facts: {type: 'array', description: 'Facts to store here', items: {type: 'string'}},
}, },
}, },
@@ -336,10 +411,11 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
return { return {
buckets: buckets.entries().toArray().map(([subject, facts]) => ({subject, facts})), buckets: buckets.entries().toArray().map(([subject, facts]) => ({subject, facts})),
journal: (response.journal ?? '').trim(), journal: (response.journal ?? '').trim(),
tasks: response.tasks ?? [],
}; };
} }
private getWeekMonday(date: Date = new Date()): string { private getWeekStart(date: Date = new Date()): string {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())); const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
const day = d.getUTCDay(); const day = d.getUTCDay();
const diff = day === 0 ? -6 : 1 - day; const diff = day === 0 ? -6 : 1 - day;
@@ -347,40 +423,86 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
return d.toISOString().slice(0, 10); return d.toISOString().slice(0, 10);
} }
private journalDescription(journalName?: string): string {
const start = journalName?.split('/').pop() || this.getWeekStart();
const d = new Date(`${start}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() + 6);
const end = d.toISOString().slice(0, 10);
return `Log from ${start} - ${end}`;
}
private getIncompleteTodos(content: string): string[] {
const body = stripHeader(content);
const match = body.match(/## Todo list\n([\s\S]*?)(?=\n## |$)/i);
if(!match) return [];
return match[1].split('\n')
.map(line => line.match(/^\s*-\s*\[([ xX])\]\s+(.+?)\s*$/))
.filter((m): m is RegExpMatchArray => !!m && m[1].toLowerCase() !== 'x')
.map(m => m[2].trim());
}
private listNodes(memories: Memory[]): MemoryRef[] { private listNodes(memories: Memory[]): MemoryRef[] {
return memories.map(m => ({name: m.name, description: m.description})); return memories.map(m => ({name: m.name, description: m.description}));
} }
private async checkMerge(node: Memory, memories: Memory[] | MemoryCache, options: LLMRequest, threshold = MERGE_THRESHOLD): Promise<Memory | null> { private async mergeAgent(node: Memory, memories: Memory[] | MemoryCache, options: LLMRequest): Promise<Memory | null> {
if (!node.embedding?.length || node.name.startsWith('Journal/')) return null; function factSimilarity(a: Memory, b: Memory): number {
const store = this.access(memories); if(!a.bodyEmbeddings?.length || !b.bodyEmbeddings?.length) return 0;
let best = 0;
let closest: Memory | null = null, closestDist = Infinity; for(const av of a.bodyEmbeddings) {
for (const other of store.list) { for(const bv of b.bodyEmbeddings) best = Math.max(best, 1 - cosineDistance(av, bv));
if (other.name === node.name || other.name.startsWith('Journal/') || !other.embedding?.length) continue; }
const d = cosineDistance(node.embedding, other.embedding); return best;
if (d < closestDist) { closestDist = d; closest = other; }
} }
if (!closest || closestDist > threshold) return null;
const result = await this.mergeAgent(node, closest, options); if(!node.embedding?.length || node.name.startsWith('Journal/')) return null;
const merged: Memory = {name: result.name, description: this.sanitizeDescription(result.description), content: '', embedding: [], links: [], backlinks: []}; const store = new MemoryAccessor(memories);
merged.content = this.touchHeader(merged, result.content); const candidates = store.list
const [e] = await this.llm.embedding(`${merged.description}\n\n${result.content}`.trim()); .filter(m => m.name !== node.name && !m.name.startsWith('Journal/'))
if (e) merged.embedding = e.embedding; .filter(m => factSimilarity(node, m) >= FACT_SIMILARITY_THRESHOLD);
this.relink(store.list, node.name, merged.name); if(!candidates.length) return null;
this.relink(store.list, closest.name, merged.name); const closest = candidates.sort((a, b) => factSimilarity(node, b) - factSimilarity(node, a))[0];
const result = await this.llm.ask('', {
model: options.model,
temperature: 0.3,
schema: {
aContent: {type: 'string', description: 'Updated document A body in markdown, without frontmatter.', required: true},
bContent: {type: 'string', description: 'Updated document B body in markdown, without frontmatter.', required: true},
},
system: `Maintain these two persistent knowledge-base documents like a wiki.
this.queues.get(closest.name)?.request?.abort?.(); Do NOT merge, rename, or delete either document. Both represent entities that should remain independently addressable.
this.queues.delete(closest.name);
store.forget(node.name); The documents were selected because their facts may overlap. Your job is to reconcile duplicated information and connect the documents:
store.forget(closest.name); - Decide which document is the HOME for each duplicated fact.
store.list.push(merged); - Keep the authoritative copy in that home document.
store.commit(); - In the other document, replace the information with a short preamble and [[WikiLink]] to the home entity explaining the relationship.
- If the documents are distinct entities but merely related, keep their distinct facts and add useful [[WikiLinks]] between them.
- Do not delete useful entity-specific facts just because they are similar.
- Do not invent relationships or facts.
- Preserve useful history, technical specifics, structure, and existing [[WikiLinks]].
- Most current truth wins when facts conflict.
- Keep both documents concise and information-dense.
- No frontmatter, preamble, filler, or AI commentary.
return merged; Document A ("${node.name}"):
\`\`\`markdown
${stripHeader(node.content)}
\`\`\`
Document B ("${closest.name}"):
\`\`\`markdown
${stripHeader(closest.content)}
\`\`\``,
});
const a = store.find(node.name);
const b = store.find(closest.name);
if(!a || !b || !result?.aContent || !result?.bContent) return null;
a.content = this.touchHeader(a, result.aContent);
b.content = this.touchHeader(b, result.bContent);
await Promise.all([embedMemoryFields(a, this.llm), embedMemoryFields(b, this.llm)]);
return a;
} }
private reconcile(node: Memory, memories: Memory[] | MemoryCache, options: LLMRequest): Promise<void> { private reconcile(node: Memory, memories: Memory[] | MemoryCache, options: LLMRequest): Promise<void> {
@@ -394,26 +516,62 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
const entry = {dirty: false, request: null, task: Promise.resolve()}; const entry = {dirty: false, request: null, task: Promise.resolve()};
this.queues.set(key, entry); this.queues.set(key, entry);
const store = this.access(memories); const store = new MemoryAccessor(memories);
entry.task = (async () => { entry.task = (async () => {
let current = node; let current = node;
try {
do { do {
entry.dirty = false; entry.dirty = false;
await this.docAgent(current, store.list, options, entry); await this.docAgent(current, store.list, options, entry);
this.mergeLock = this.mergeLock.then(() => this.checkMerge(current, memories, options)); this.mergeLock = this.mergeLock.then(() => this.mergeAgent(current, memories, options));
const merged = await this.mergeLock; const result = await this.mergeLock;
if(merged) current = merged; if(result) current = result;
} while(entry.dirty); } while(entry.dirty);
})().finally(() => { } finally {
store.commit([node]);
this.queues.delete(key); this.queues.delete(key);
store.commit(); }
}); })();
return entry.task; return entry.task;
} }
private async docAgent(node: Memory, memories: Memory[], options: LLMRequest, entry: {request: {abort?: () => void} | null}): Promise<void> { private async docAgent(node: Memory, memories: Memory[], options: LLMRequest, entry: {request: {abort?: () => void} | null}): Promise<void> {
if(!memories.includes(node)) return; if(!memories.includes(node)) return;
const currentBody = stripHeader(node.content); const currentBody = stripHeader(node.content);
const journal = node.name.startsWith('Journal/');
const system = (journal
? `You maintain one persistent journal document
Rewrite the ENTIRE journal, folding "## Pending" into the existing content removing the heading
Journal design:
- Preserve the chronological daily log
- Maintain a single \`## Todo list\` section for this entity: reconcile tasks semantically (merge equivalent tasks, remove duplicates, preserve incomplete tasks, check off completed ones), and keep it distinct from the narrative/fact sections
- Group information by day under a date heading
- Keep journal entries high level and concise: what was worked on and the outcome, not a step-by-step record of how — that detail lives in conversation history, not here
- Use [[WikiLinks]] for persistent entities; don't turn ordinary journal events into entities
- No frontmatter, preamble, filler, or AI commentary`
: `You maintain one persistent knowledge-base entity document
Rewrite the ENTIRE document, folding "## Pending" into the existing content. Remove the Pending section when finished.
Document design:
- The document represents one persistent entity. Keep information about that entity together and organized into sections
- Merge any pending information in, newest fact wins conflicts; remove redundant content
- Maintain a single \`## Todo list\` section for this entity: reconcile tasks semantically (merge equivalent tasks, remove duplicates, preserve incomplete tasks, check off completed ones), and keep it distinct from the narrative/fact sections
- Let the structure fit the entity; there is NO fixed template
- Add headings only when they meaningfully organize recurring information; don't create headings for one-off facts
- Keep the document concise and information-dense without removing useful technical specifics
- Current truth wins when facts conflict. Preserve older conflict as context, only when it adds useful meaning
- No frontmatter, preamble, filler, or AI commentary`) + `
Available nodes to link to:
${this.listNodes(memories).filter(n => n.name !== node.name).map(n => n.name).join(', ') || 'none'}
Current document:
\`\`\`markdown
${currentBody}
\`\`\``;
let update; let update;
try { try {
for(let i = 0; i < 2 && !update?.content; i++) { for(let i = 0; i < 2 && !update?.content; i++) {
@@ -424,30 +582,7 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
description: {type: 'string', description: 'One factual sentence describing the document\'s ENTIRE SUBJECT MATTER — for use as a search/merge fingerprint', required: true}, description: {type: 'string', description: 'One factual sentence describing the document\'s ENTIRE SUBJECT MATTER — for use as a search/merge fingerprint', required: true},
content: {type: 'string', description: 'Rewritten document body in markdown, without the frontmatter block', required: true}, content: {type: 'string', description: 'Rewritten document body in markdown, without the frontmatter block', required: true},
}, },
system: `You are a knowledge base editor maintaining one Obsidian-style document. system,
If it has a "## Pending" section, fold all new material into the appropriate part, resolve overlap, then remove the section entirely. If no section, just tidy per the rules below.
Use this loose structure, adapting headings to what the content needs:
\`\`\`markdown
${GENERIC_TEMPLATE}
\`\`\`
Rules:
- Contradictions: newer facts always win — delete outdated statements entirely
- Journals (Journal/...): keep entries as a chronological timeline; clean up grammar within entries but never delete history
- Use Obsidian markdown: # headings, **bold**, bullet/numbered lists, tables for 2D data
- Link specific entities and concepts with [[WikiLink]] (e.g., [[Projects/KiwixServer]]); skip generics
- Keep concise, factual, human-readable
- NO frontmatter, filler, preamble, or AI commentary
Available nodes to link to (don't duplicate their content):
${this.listNodes(memories).filter(n => n.name !== node.name).map(n => n.name).join(', ') || 'none'}
Current document:
\`\`\`markdown
${currentBody}
\`\`\``,
}); });
entry.request = request; entry.request = request;
update = await request; update = await request;
@@ -460,40 +595,9 @@ ${currentBody}
} }
if(!update?.content) return; if(!update?.content) return;
node.description = node.name !== 'People/User' ? this.sanitizeDescription(update.description) : 'All information about the current user'; node.description = node.name.startsWith('Journal/') ? this.journalDescription(node.name) : node.name !== 'People/User' ? update.description.replaceAll(/[\n:]/g, '') : 'All information about the current user';
node.content = this.touchHeader(node, update.content); node.content = this.touchHeader(node, update.content);
const [e] = await this.llm.embedding(`${node.description}\n\n${update.content}`.trim()); await embedMemoryFields(node, this.llm);
if (e) node.embedding = e.embedding;
}
private async mergeAgent(a: Memory, b: Memory, options: LLMRequest): Promise<{name: string, description: string, content: string}> {
return this.llm.ask('', {
model: options.model,
temperature: 0.3,
schema: {
name: {type: 'string', description: 'New path for the merged doc, collection/subject format (e.g. Projects/Oxide) — only reuse an old title if it\'s genuinely the best fit', required: true},
description: {type: 'string', description: 'One factual sentence describing the merged document\'s subject matter', required: true},
content: {type: 'string', description: 'Fully reconciled body in markdown, without frontmatter', required: true},
},
system: `You are a knowledge base editor merging two overlapping Obsidian documents into one. Newer facts win on contradiction.
Structure loosely:
\`\`\`markdown
${GENERIC_TEMPLATE}
\`\`\`
Combine both documents, resolve duplication and contradictions.
Document A ("${a.name}"):
\`\`\`markdown
${stripHeader(a.content)}
\`\`\`
Document B ("${b.name}"):
\`\`\`markdown
${stripHeader(b.content)}
\`\`\``,
});
} }
private parseFrontmatter(content: string): {fm: Map<string, string>, body: string} { private parseFrontmatter(content: string): {fm: Map<string, string>, body: string} {
@@ -506,7 +610,7 @@ ${stripHeader(b.content)}
const key = line.slice(0, i).trim(); const key = line.slice(0, i).trim();
const raw = line.slice(i + 1).trim(); const raw = line.slice(i + 1).trim();
let value = raw; let value = raw;
try { value = JSON.parse(raw); } catch { /* legacy unquoted value, keep raw */ } try { value = JSON.parse(raw); } catch { }
fm.set(key, value); fm.set(key, value);
} }
return {fm, body: match[2]}; return {fm, body: match[2]};
@@ -515,9 +619,9 @@ ${stripHeader(b.content)}
private touchHeader(node: Memory, body: string): string { private touchHeader(node: Memory, body: string): string {
const {fm} = this.parseFrontmatter(node.content); const {fm} = this.parseFrontmatter(node.content);
fm.set('name', node.name); fm.set('name', node.name);
fm.set('description', node.description || ''); fm.set('description', (node.name.startsWith('Journal/') ? this.journalDescription(node.name) : node.description) || 'Persistent memory document');
fm.set('modified', new Date().toISOString()); fm.set('modified', new Date().toISOString());
return this.writeFrontmatter(fm, body); return this.writeFrontmatter(fm, stripHeader(body));
} }
private writeFrontmatter(fm: Map<string, string>, body: string): string { private writeFrontmatter(fm: Map<string, string>, body: string): string {
@@ -537,20 +641,33 @@ ${stripHeader(b.content)}
} }
forget(name: string, memories: Memory[] | MemoryCache): boolean { forget(name: string, memories: Memory[] | MemoryCache): boolean {
return this.access(memories).forget(name); return new MemoryAccessor(memories).forget(name);
} }
async recollect(query: string, memories: Memory[] | MemoryCache, limit = 5, graphDepth = 1): Promise<Memory[]> { async recollect(query: string, memories: Memory[] | MemoryCache, limit = 5, graphDepth = 1): Promise<Memory[]> {
const store = this.access(memories); function rank(query: number[], candidates: Memory[], limit: number): Memory[] {
if (!store.list.length) return []; const scored = candidates.map(m => {
const titleSim = m.titleEmbedding?.length ? 1 - cosineDistance(query, m.titleEmbedding) : 0;
const descSim = m.embedding?.length ? 1 - cosineDistance(query, m.embedding) : 0;
const bodySim = m.bodyEmbeddings?.length
? Math.max(...m.bodyEmbeddings.map(b => 1 - cosineDistance(query, b)))
: 0;
return {memory: m, score: titleSim * 0.5 + descSim * 0.35 + bodySim * 0.15};
});
return scored.sort((a, b) => b.score - a.score).slice(0, limit).map(s => s.memory);
}
const store = new MemoryAccessor(memories);
if(!store.list.length) return [];
await store.backfillEmbeddings(this.llm); await store.backfillEmbeddings(this.llm);
const [e] = await this.llm.embedding(query); const [e] = await this.llm.embedding(query);
if(!e) return []; if(!e) return [];
const vectorResults = store.search(e.embedding, limit); const pool = store.search(e.embedding, Math.max(limit * 3, limit));
const found = new Set<string>(vectorResults.map(r => r.name)); const poolMemories = pool.map(r => store.find(r.name)).filter((m): m is Memory => !!m);
const ranked = rank(e.embedding, poolMemories, limit);
const found = new Set<string>(ranked.map(m => m.name));
if(graphDepth > 0) { if(graphDepth > 0) {
let frontier = [...found]; let frontier = [...found];
@@ -570,9 +687,9 @@ ${stripHeader(b.content)}
} }
} }
const vectorOrder = vectorResults.map(r => r.name); const rankedOrder = ranked.map(m => m.name);
const graphExpansions = [...found].filter(n => !vectorOrder.includes(n)); const graphExpansions = [...found].filter(n => !rankedOrder.includes(n));
return [...vectorOrder, ...graphExpansions].map(n => store.find(n)!).filter(Boolean); return [...rankedOrder, ...graphExpansions].map(n => store.find(n)!).filter(Boolean);
} }
async memorize(history: LLMMessage[], memories: Memory[] | MemoryCache, options: LLMRequest): Promise<Memory[]> { async memorize(history: LLMMessage[], memories: Memory[] | MemoryCache, options: LLMRequest): Promise<Memory[]> {
@@ -585,39 +702,79 @@ ${stripHeader(b.content)}
const pending = {role: 'tool', name: 'memory_process', id: uid, content: conversation} as unknown as LLMMessage; const pending = {role: 'tool', name: 'memory_process', id: uid, content: conversation} as unknown as LLMMessage;
history.push(pending); history.push(pending);
const store = this.access(memories); const store = new MemoryAccessor(memories);
const {buckets, journal} = await this.factAgent(conversation, store, options); const {buckets, journal, tasks} = await this.factAgent(conversation, store, options);
const touched: Memory[] = []; const touched: Memory[] = [];
if (journal) { const personalTasks = tasks.filter(isPersonalTask);
const journalName = `Journal/${this.getWeekMonday()}`; const entityTasks = tasks.filter(t => !isPersonalTask(t));
if(journal || personalTasks.length) {
const journalName = `Journal/${this.getWeekStart()}`;
let jnode = store.find(journalName); let jnode = store.find(journalName);
const isNew = !jnode;
if(!jnode) { if(!jnode) {
jnode = {name: journalName, description: '', content: '', embedding: [], links: [], backlinks: []}; jnode = {
name: journalName,
description: this.journalDescription(),
content: '',
embedding: [],
links: [],
backlinks: [],
};
store.list.push(jnode); store.list.push(jnode);
} }
this.stage(jnode, `### ${new Date().toISOString().slice(0, 10)}\n${journal}`);
const blocks: string[] = [];
if(journal) blocks.push(`### ${new Date().toISOString().slice(0, 10)}\n${journal}`);
if(isNew) {
const previousDate = new Date(`${this.getWeekStart()}T00:00:00Z`);
previousDate.setUTCDate(previousDate.getUTCDate() - 7);
const previous = store.find(`Journal/${previousDate.toISOString().slice(0, 10)}`);
if(previous) {
const todos = this.getIncompleteTodos(previous.content);
if(todos.length) blocks.push(`${TODO_HEADING}\n${todos.map(task => `- [ ] ${task}`).join('\n')}`);
}
}
if(personalTasks.length) blocks.push(`${TODO_HEADING}\n${personalTasks.map(task => `- [${task.done ? 'x' : ' '}] ${task.task}`).join('\n')}`);
if(blocks.length) this.stage(jnode, blocks.join('\n\n'));
touched.push(jnode); touched.push(jnode);
} }
const entityStaging = new Map<string, {facts: string[], tasks: MemoryTask[]}>();
for(const {subject, facts} of buckets) { for(const {subject, facts} of buckets) {
let node = store.find(subject); const resolved = this.resolveSubject(subject, store);
const entry = entityStaging.get(resolved) ?? {facts: [], tasks: []};
entry.facts.push(...facts);
entityStaging.set(resolved, entry);
}
for(const task of entityTasks) {
const resolved = this.resolveSubject(task.subject, store);
const entry = entityStaging.get(resolved) ?? {facts: [], tasks: []};
entry.tasks.push(task);
entityStaging.set(resolved, entry);
}
for(const [resolved, {facts, tasks: subjectTasks}] of entityStaging) {
let node = store.find(resolved);
if(!node) { if(!node) {
node = {name: subject, description: '', content: '', embedding: [], links: [], backlinks: []}; node = {name: resolved, description: 'Persistent memory document', content: '', embedding: [], links: [], backlinks: []};
store.list.push(node); store.list.push(node);
} }
this.stage(node, facts.map(f => `- ${f}`).join('\n')); const blocks: string[] = [];
if(facts.length) blocks.push(facts.map(f => `- ${f}`).join('\n'));
if(subjectTasks.length) blocks.push(`${TODO_HEADING}\n${subjectTasks.map(t => `- [${t.done ? 'x' : ' '}] ${t.task}`).join('\n')}`);
if(blocks.length) this.stage(node, blocks.join('\n\n'));
touched.push(node); touched.push(node);
} }
await Promise.all(touched.map(async node => { await Promise.all(touched.map(async node => {
const [e] = await this.llm.embedding(`${node.description}\n\n${stripHeader(node.content)}`.trim()); await embedMemoryFields(node, this.llm);
if (e) node.embedding = e.embedding;
this.touch(node.name); this.touch(node.name);
})); }));
if(touched.length) { if(touched.length) {
store.commit(); store.commit(touched);
(pending as any).content = `Saved to ${touched.map(n => `[[${n.name}]]`).join(', ')}`; (pending as any).content = `Saved to ${touched.map(n => `[[${n.name}]]`).join(', ')}`;
Promise.all(touched.map(node => this.reconcile(node, memories, options).catch(() => {}))); Promise.all(touched.map(node => this.reconcile(node, memories, options).catch(() => {})));
} else { } else {
@@ -629,7 +786,7 @@ ${stripHeader(b.content)}
} }
async reconcileAll(memories: Memory[] | MemoryCache, options: LLMRequest, scope: 'touched' | 'all' = 'touched'): Promise<void> { async reconcileAll(memories: Memory[] | MemoryCache, options: LLMRequest, scope: 'touched' | 'all' = 'touched'): Promise<void> {
const store = this.access(memories); const store = new MemoryAccessor(memories);
const targets = scope === 'all' ? store.list : store.list.filter(m => m.content.includes(PENDING_HEADING)); const targets = scope === 'all' ? store.list : store.list.filter(m => m.content.includes(PENDING_HEADING));
await Promise.all(targets.map(node => this.reconcile(node, memories, options))); await Promise.all(targets.map(node => this.reconcile(node, memories, options)));
store.commit(); store.commit();
+112 -35
View File
@@ -36,21 +36,49 @@ export class OpenAi extends LLMProvider {
private toWire(history: LLMMessage[], system?: string): any[] { private toWire(history: LLMMessage[], system?: string): any[] {
const wire: any[] = []; const wire: any[] = [];
if(system) wire.push({role: 'system', content: system}); if(system) wire.push({role: 'system', content: system});
for(const h of history) {
if(h.role === 'tool') { for(let i = 0; i < history.length; i++) {
const h = history[i];
if(h.role !== 'tool') {
wire.push({role: h.role, content: this.toWireContent(h.content)});
continue;
}
const calls: any[] = [];
const results: any[] = [];
while(i < history.length && history[i].role === 'tool') {
const tool: any = history[i];
calls.push({
id: tool.id,
type: 'function',
function: {
name: tool.name,
arguments: JSON.stringify(tool.args || {})
}
});
results.push({
role: 'tool',
tool_call_id: tool.id,
content: tool.error || tool.content || ''
});
i++;
}
wire.push({ wire.push({
role: 'assistant', role: 'assistant',
content: null, content: null,
tool_calls: [{id: h.id, type: 'function', function: {name: h.name, arguments: JSON.stringify(h.args)}}], tool_calls: calls
}, {
role: 'tool',
tool_call_id: h.id,
content: h.error || h.content || '',
}); });
} else {
wire.push({role: h.role, content: this.toWireContent(h.content)}); wire.push(...results);
} i--;
} }
return wire; return wire;
} }
@@ -60,13 +88,12 @@ export class OpenAi extends LLMProvider {
if(!options.history) options.history = []; if(!options.history) options.history = [];
const history = options.history; const history = options.history;
if(message) history.push({role: 'user', content: message, timestamp: Date.now()}); if(message) history.push({role: 'user', content: message, timestamp: Date.now()});
const tools = options.tools || this.ai.options.llm?.tools || []; const tools = options.tools || this.ai.options.llm?.tools || [];
const requestParams: any = { const requestParams: any = {
model: options.model || this.model, model: options.model || this.model,
stream: !!options.stream, stream: !!options.stream,
max_completion_tokens: options.maxTokens || this.ai.options.llm?.maxTokens || undefined, max_completion_tokens: options.maxTokens ?? this.ai.options.llm?.maxTokens,
temperature: options.temperature || this.ai.options.llm?.temperature || undefined, temperature: options.temperature ?? this.ai.options.llm?.temperature,
tools: tools.map(t => ({ tools: tools.map(t => ({
type: 'function', type: 'function',
function: { function: {
@@ -74,8 +101,12 @@ export class OpenAi extends LLMProvider {
description: t.description, description: t.description,
parameters: { parameters: {
type: 'object', type: 'object',
properties: t.args ? objectMap(t.args, (key, value) => ({...value, required: undefined})) : {}, properties: t.args
required: t.args ? Object.entries(t.args).filter(t => t[1].required).map(t => t[0]) : [] ? objectMap(t.args, (key, value) => ({...value, required: undefined}))
: {},
required: t.args
? Object.entries(t.args).filter(t => t[1].required).map(t => t[0])
: []
} }
} }
})) }))
@@ -83,60 +114,106 @@ export class OpenAi extends LLMProvider {
if(options.schema) { if(options.schema) {
const schema = convertSchema(options.schema); const schema = convertSchema(options.schema);
requestParams.response_format = {type: 'json_schema', json_schema: {name: 'response', strict: true, schema}}; requestParams.response_format = {
type: 'json_schema',
json_schema: {name: 'response', strict: true, schema}
};
} }
if(options.stream) requestParams.stream_options = {include_usage: true}; if(options.stream) requestParams.stream_options = {include_usage: true};
try { try {
let terminal = false; let terminal = false;
let iteration = 0;
do { do {
iteration++;
requestParams.messages = this.toWire(history.filter(h => h.role !== 'system'), options.system); requestParams.messages = this.toWire(history.filter(h => h.role !== 'system'), options.system);
const callStart = Date.now(); const callStart = Date.now();
const resp: any = await this.tokenPool.run(token => this.getClient(token).chat.completions.create(requestParams)).catch(err => { const resp: any = await this.tokenPool.run(token =>
this.getClient(token).chat.completions.create(requestParams)
).catch(err => {
err.message += `\n\nMessages:\n${JSON.stringify(requestParams.messages, null, 2)}`; err.message += `\n\nMessages:\n${JSON.stringify(requestParams.messages, null, 2)}`;
throw err; throw err;
}); });
let usage: any, msg: any = {content: '', tool_calls: []}; let usage: any;
let finishReason: string | undefined;
let msg: any = {content: '', tool_calls: []};
let streamedChars = 0;
if(options.stream) { if(options.stream) {
let streamCompleted = false;
try {
for await (const chunk of resp) { for await (const chunk of resp) {
if(controller.signal.aborted) break; if(controller.signal.aborted) break;
if(chunk.usage) usage = chunk.usage; if(chunk.usage) usage = chunk.usage;
if(chunk.choices[0]?.delta?.content) {
msg.content += chunk.choices[0].delta.content; const choice = chunk.choices?.[0];
options.stream({text: chunk.choices[0].delta.content}); if(choice?.finish_reason) finishReason = choice.finish_reason;
if(choice?.delta?.content) {
msg.content += choice.delta.content;
streamedChars += choice.delta.content.length;
options.stream({text: choice.delta.content});
} }
if(chunk.choices[0]?.delta?.tool_calls) {
for(const deltaTC of chunk.choices[0].delta.tool_calls) { if(choice?.delta?.tool_calls) {
const existing = msg.tool_calls.find((tc: any) => tc.index === deltaTC.index); for(const deltaTC of choice.delta.tool_calls) {
if(existing) { const index = deltaTC.index ?? msg.tool_calls.length;
let existing = msg.tool_calls.find((tc: any) => tc.index === index);
if(!existing) {
existing = {index, id: '', function: {name: '', arguments: ''}};
msg.tool_calls.push(existing);
}
if(deltaTC.id) existing.id = deltaTC.id; if(deltaTC.id) existing.id = deltaTC.id;
if(deltaTC.function?.name) existing.function.name = deltaTC.function.name; if(deltaTC.function?.name) existing.function.name = deltaTC.function.name;
if(deltaTC.function?.arguments) existing.function.arguments += deltaTC.function.arguments; if(deltaTC.function?.arguments) existing.function.arguments += deltaTC.function.arguments;
} else {
msg.tool_calls.push({
index: deltaTC.index,
id: deltaTC.id || '',
function: {name: deltaTC.function?.name || '', arguments: deltaTC.function?.arguments || ''}
});
} }
} }
} }
streamCompleted = true;
} catch(err) {
if(!controller.signal.aborted) throw err;
} }
if(streamCompleted && !finishReason) finishReason = msg.tool_calls.length ? 'tool_calls' : 'stop';
} else { } else {
usage = resp.usage; usage = resp.usage;
finishReason = resp.choices[0].finish_reason;
msg = resp.choices[0].message; msg = resp.choices[0].message;
} }
const duration = Date.now() - callStart; const duration = Date.now() - callStart;
const tps = usage?.completion_tokens && duration > 0 ? usage.completion_tokens / (duration / 1000) : 0; const tps = usage?.completion_tokens && duration > 0 ? usage.completion_tokens / (duration / 1000) : 0;
if(finishReason === 'length' && !controller.signal.aborted) {
if(msg.content?.trim()) history.push({role: 'assistant', content: msg.content.trim(), timestamp: Date.now(), duration, tps});
throw new Error(`[OpenAI] Response hit token limit before completing`);
}
if(!finishReason && !controller.signal.aborted) {
throw new Error('[OpenAI] Completion ended without a usable response');
}
const toolCalls = msg.tool_calls || []; const toolCalls = msg.tool_calls || [];
if(toolCalls.length && !controller.signal.aborted) { if(toolCalls.length && !controller.signal.aborted) {
if(msg.content?.trim()) history.push({role: 'assistant', content: msg.content.trim(), timestamp: Date.now(), duration, tps}); if(msg.content?.trim()) history.push({role: 'assistant', content: msg.content.trim(), timestamp: Date.now(), duration, tps});
const entries = toolCalls.map((tc: any) => { const entries = toolCalls.map((tc: any) => {
const entry: any = {role: 'tool', id: tc.id, name: tc.function.name, args: JSONAttemptParse(tc.function.arguments, {}), content: undefined, timestamp: Date.now()}; const entry: any = {
role: 'tool',
id: tc.id,
name: tc.function.name,
args: JSONAttemptParse(tc.function.arguments, {}),
content: undefined,
timestamp: Date.now()
};
history.push(entry); history.push(entry);
return {tc, entry}; return {tc, entry};
}); });
@@ -144,12 +221,13 @@ export class OpenAi extends LLMProvider {
await Promise.all(entries.map(async ({tc, entry}: any) => { await Promise.all(entries.map(async ({tc, entry}: any) => {
const tool = tools.find(findByProp('name', tc.function.name)); const tool = tools.find(findByProp('name', tc.function.name));
if(options.stream) options.stream({tool: tc.function.name}); if(options.stream) options.stream({tool: tc.function.name});
if(!tool) { entry.error = 'Tool not found'; return; } if(!tool) return entry.error = 'Tool not found';
try { try {
const toolStream = options.stream && ((chunk: any) => { const toolStream = options.stream && ((chunk: any) => {
if(chunk.done) { terminal = true; return; } if(chunk.done) return;
options.stream!(chunk); options.stream!(chunk);
}); });
const result = await tool.fn(entry.args, toolStream, this.ai, tc.id); const result = await tool.fn(entry.args, toolStream, this.ai, tc.id);
entry.content = typeof result === 'object' ? JSONSanitize(result) : result; entry.content = typeof result === 'object' ? JSONSanitize(result) : result;
} catch(err: any) { } catch(err: any) {
@@ -164,7 +242,6 @@ export class OpenAi extends LLMProvider {
} while(!terminal && !controller.signal.aborted); } while(!terminal && !controller.signal.aborted);
if(options.stream) options.stream({done: true}); if(options.stream) options.stream({done: true});
const turnStart = history.map(h => h.role).lastIndexOf('user'); const turnStart = history.map(h => h.role).lastIndexOf('user');
const finalContent = history.slice(turnStart + 1).reduce((str, h) => h.role === 'assistant' ? str + (h.content || '') : str, '').trim(); const finalContent = history.slice(turnStart + 1).reduce((str, h) => h.role === 'assistant' ? str + (h.content || '') : str, '').trim();
res(options.schema ? JSONAttemptParse(finalContent, finalContent) : finalContent); res(options.schema ? JSONAttemptParse(finalContent, finalContent) : finalContent);