@useavalon/caelence-agent 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,295 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { cosineSimilarity, type Embedder, fuseRankings } from "./embeddings.ts";
4
+ import {
5
+ completeHits,
6
+ deleteFact,
7
+ insertFacts,
8
+ keywordHits,
9
+ listFacts,
10
+ type MemoryFact,
11
+ type MemoryScope,
12
+ memoryPathForScope,
13
+ prepareFacts,
14
+ rankFacts,
15
+ } from "./store.ts";
16
+
17
+ export interface NewMemoryFact {
18
+ text: string;
19
+ scope?: MemoryScope;
20
+ sessionId?: string;
21
+ }
22
+
23
+ /** What the agent needs from memory. Hosts supply their own; the harness ships a file-backed one. */
24
+ export interface MemoryStore {
25
+ list(): Promise<MemoryFact[]>;
26
+ /** Store new facts. Duplicates, secrets and noise are dropped. Returns what was stored. */
27
+ add(items: NewMemoryFact[]): Promise<MemoryFact[]>;
28
+ remove(id: string): Promise<MemoryFact | undefined>;
29
+ /** The facts most relevant to the query, best first. Never throws. */
30
+ search(query: string, topK?: number): Promise<MemoryFact[]>;
31
+ }
32
+
33
+ /** A stored fact with its vector, when it has one. */
34
+ export interface MemoryRecord extends MemoryFact {
35
+ embedding?: number[];
36
+ embeddingModel?: string;
37
+ }
38
+
39
+ export interface MemoryEmbeddingRow {
40
+ id: string;
41
+ embedding: number[];
42
+ embeddingModel: string;
43
+ }
44
+
45
+ /**
46
+ * Where facts live. A host implements this over its own database, scoped to one user or project;
47
+ * `createMemoryStore` adds the validation, deduplication and ranking on top.
48
+ */
49
+ export interface MemoryBackend {
50
+ load(): Promise<MemoryRecord[]>;
51
+ insert(facts: MemoryFact[]): Promise<void>;
52
+ remove(id: string): Promise<MemoryFact | undefined>;
53
+ /** Store vectors for facts already inserted. Without it vectors are recomputed each search. */
54
+ saveEmbeddings?(rows: MemoryEmbeddingRow[]): Promise<void>;
55
+ /**
56
+ * Nearest facts to a query vector, best first. A backend with a vector index (pgvector, for
57
+ * one) implements this so a search does not load every fact. Without it the store ranks the
58
+ * loaded records itself, which is fine up to a few thousand facts per scope.
59
+ */
60
+ nearest?(embedding: number[], embeddingModel: string, topK: number): Promise<MemoryFact[]>;
61
+ }
62
+
63
+ export interface CreateMemoryStoreOptions {
64
+ backend: MemoryBackend;
65
+ /** Adds semantic recall. Without one, recall is keyword-only. */
66
+ embedder?: Embedder;
67
+ /** Facts less similar than this to the query are not semantic hits. Default 0.25. */
68
+ minSimilarity?: number;
69
+ /** Give up on the embedding call after this long and answer from keywords. Default 2500. */
70
+ embedTimeoutMs?: number;
71
+ }
72
+
73
+ const DEFAULT_MIN_SIMILARITY = 0.25;
74
+ const DEFAULT_EMBED_TIMEOUT_MS = 2500;
75
+ /** Facts embedded lazily in one search, so the first search over old facts stays bounded. */
76
+ const MAX_LAZY_EMBEDS = 256;
77
+
78
+ function withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {
79
+ let timer: ReturnType<typeof setTimeout> | undefined;
80
+ const timeout = new Promise<never>((_, reject) => {
81
+ timer = setTimeout(() => reject(new Error("embedding timed out")), ms);
82
+ });
83
+ return Promise.race([work, timeout]).finally(() => {
84
+ if (timer) clearTimeout(timer);
85
+ });
86
+ }
87
+
88
+ function toFact(record: MemoryRecord): MemoryFact {
89
+ const { embedding: _embedding, embeddingModel: _model, ...fact } = record;
90
+ return fact;
91
+ }
92
+
93
+ export function createMemoryStore(options: CreateMemoryStoreOptions): MemoryStore {
94
+ const { backend, embedder } = options;
95
+ const minSimilarity = options.minSimilarity ?? DEFAULT_MIN_SIMILARITY;
96
+ const embedTimeoutMs = options.embedTimeoutMs ?? DEFAULT_EMBED_TIMEOUT_MS;
97
+
98
+ const embedAndSave = async (facts: MemoryFact[]): Promise<Map<string, number[]>> => {
99
+ const vectors = new Map<string, number[]>();
100
+ if (!embedder || facts.length === 0) return vectors;
101
+ const embedded = await embedder.embed(facts.map((fact) => fact.text));
102
+ const rows: MemoryEmbeddingRow[] = [];
103
+ facts.forEach((fact, index) => {
104
+ const embedding = embedded[index];
105
+ if (!embedding) return;
106
+ vectors.set(fact.id, embedding);
107
+ rows.push({ id: fact.id, embedding, embeddingModel: embedder.model });
108
+ });
109
+ if (rows.length > 0) await backend.saveEmbeddings?.(rows);
110
+ return vectors;
111
+ };
112
+
113
+ /** Semantic hits, best first. Throws when the embedder or backend fails. */
114
+ const semanticHits = async (
115
+ records: MemoryRecord[],
116
+ query: string,
117
+ topK: number,
118
+ ): Promise<MemoryFact[]> => {
119
+ if (!embedder) return [];
120
+ const [queryVector] = await embedder.embed([query]);
121
+ if (!queryVector) return [];
122
+ if (backend.nearest) return backend.nearest(queryVector, embedder.model, topK);
123
+ const missing = records
124
+ .filter((record) => !record.embedding || record.embeddingModel !== embedder.model)
125
+ .slice(-MAX_LAZY_EMBEDS);
126
+ const fresh = await embedAndSave(missing);
127
+ return records
128
+ .map((record) => {
129
+ const vector =
130
+ fresh.get(record.id) ??
131
+ (record.embeddingModel === embedder.model ? record.embedding : undefined);
132
+ return { record, score: vector ? cosineSimilarity(queryVector, vector) : 0 };
133
+ })
134
+ .filter((row) => row.score >= minSimilarity)
135
+ .sort((a, b) => b.score - a.score)
136
+ .slice(0, topK)
137
+ .map((row) => row.record);
138
+ };
139
+
140
+ return {
141
+ async list() {
142
+ return (await backend.load()).map(toFact);
143
+ },
144
+ async add(items) {
145
+ const known = new Set((await backend.load()).map((record) => record.hash));
146
+ const facts = prepareFacts(known, items);
147
+ if (facts.length === 0) return [];
148
+ await backend.insert(facts);
149
+ // The facts are stored either way; a missing vector is filled in by a later search.
150
+ await embedAndSave(facts).catch(() => undefined);
151
+ return facts;
152
+ },
153
+ remove: (id) => backend.remove(id),
154
+ async search(query, topK = 10) {
155
+ let records: MemoryRecord[];
156
+ try {
157
+ records = await backend.load();
158
+ } catch {
159
+ return [];
160
+ }
161
+ if (records.length === 0) return [];
162
+ const keyword = keywordHits(records, query);
163
+ if (!embedder || !query.trim()) return rankFacts(records, query, topK).map(toFact);
164
+ let semantic: MemoryFact[] = [];
165
+ try {
166
+ semantic = await withTimeout(semanticHits(records, query, topK * 2), embedTimeoutMs);
167
+ } catch {
168
+ return rankFacts(records, query, topK).map(toFact);
169
+ }
170
+ const byId = new Map(records.map((record) => [record.id, record]));
171
+ const fused = fuseRankings<MemoryFact>([semantic, keyword ?? []], (fact) => fact.id)
172
+ .map((fact) => byId.get(fact.id) ?? fact)
173
+ .slice(0, topK);
174
+ return completeHits(fused, records, topK).map(toFact);
175
+ },
176
+ };
177
+ }
178
+
179
+ /** Facts held in memory only. For tests, and for hosts that want recall inside one process. */
180
+ export function createInMemoryMemoryBackend(seed: MemoryRecord[] = []): MemoryBackend {
181
+ const records: MemoryRecord[] = [...seed];
182
+ return {
183
+ async load() {
184
+ return records.map((record) => ({ ...record }));
185
+ },
186
+ async insert(facts) {
187
+ records.push(...facts);
188
+ },
189
+ async remove(id) {
190
+ const index = records.findIndex((record) => record.id === id);
191
+ if (index < 0) return undefined;
192
+ const [removed] = records.splice(index, 1);
193
+ return removed ? toFact(removed) : undefined;
194
+ },
195
+ async saveEmbeddings(rows) {
196
+ for (const row of rows) {
197
+ const record = records.find((item) => item.id === row.id);
198
+ if (!record) continue;
199
+ record.embedding = row.embedding;
200
+ record.embeddingModel = row.embeddingModel;
201
+ }
202
+ },
203
+ };
204
+ }
205
+
206
+ interface VectorsFile {
207
+ model?: string;
208
+ vectors?: Record<string, number[]>;
209
+ }
210
+
211
+ function vectorsPath(factsPath: string): string {
212
+ return resolve(factsPath, "..", "vectors.json");
213
+ }
214
+
215
+ function readVectors(factsPath: string): VectorsFile {
216
+ const path = vectorsPath(factsPath);
217
+ if (!existsSync(path)) return {};
218
+ try {
219
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as VectorsFile;
220
+ return parsed && typeof parsed === "object" ? parsed : {};
221
+ } catch {
222
+ return {};
223
+ }
224
+ }
225
+
226
+ function writeVectors(factsPath: string, file: VectorsFile): void {
227
+ const path = vectorsPath(factsPath);
228
+ mkdirSync(resolve(path, ".."), { recursive: true });
229
+ writeFileSync(path, `${JSON.stringify(file)}\n`);
230
+ }
231
+
232
+ /**
233
+ * The harness's own facts files (`~/.harness/memory/facts.json` and `.harness/memory/facts.json`).
234
+ * Vectors sit beside each in `vectors.json`, so the facts files stay readable and unchanged.
235
+ */
236
+ export function createFileMemoryBackend(
237
+ cwd: string,
238
+ env: Record<string, string | undefined> = process.env,
239
+ ): MemoryBackend {
240
+ const scopes = ["user", "project"] as const;
241
+ return {
242
+ async load() {
243
+ const byScope = new Map<MemoryScope, VectorsFile>();
244
+ for (const scope of scopes) {
245
+ byScope.set(scope, readVectors(memoryPathForScope(cwd, scope, env)));
246
+ }
247
+ return listFacts(cwd, env).map((fact): MemoryRecord => {
248
+ const file = byScope.get(fact.scope);
249
+ const embedding = file?.vectors?.[fact.id];
250
+ return embedding && file?.model ? { ...fact, embedding, embeddingModel: file.model } : fact;
251
+ });
252
+ },
253
+ async insert(facts) {
254
+ insertFacts(cwd, facts, env);
255
+ },
256
+ async remove(id) {
257
+ const removed = deleteFact(cwd, id, env);
258
+ if (!removed) return undefined;
259
+ const path = memoryPathForScope(cwd, removed.scope, env);
260
+ const file = readVectors(path);
261
+ if (file.vectors?.[removed.id]) {
262
+ delete file.vectors[removed.id];
263
+ writeVectors(path, file);
264
+ }
265
+ return removed;
266
+ },
267
+ async saveEmbeddings(rows) {
268
+ if (rows.length === 0) return;
269
+ const scopeOf = new Map(listFacts(cwd, env).map((fact) => [fact.id, fact.scope]));
270
+ for (const scope of scopes) {
271
+ const mine = rows.filter((row) => scopeOf.get(row.id) === scope);
272
+ if (mine.length === 0) continue;
273
+ const model = mine[0]?.embeddingModel;
274
+ const path = memoryPathForScope(cwd, scope, env);
275
+ const current = readVectors(path);
276
+ // A new embedding model starts a new vector space; the old vectors cannot be compared.
277
+ const vectors = current.model === model ? { ...(current.vectors ?? {}) } : {};
278
+ for (const row of mine) vectors[row.id] = row.embedding;
279
+ writeVectors(path, { model, vectors });
280
+ }
281
+ },
282
+ };
283
+ }
284
+
285
+ /** The default store: the facts files on disk, with semantic recall when given an embedder. */
286
+ export function createFileMemoryStore(options: {
287
+ cwd: string;
288
+ env?: Record<string, string | undefined>;
289
+ embedder?: Embedder;
290
+ }): MemoryStore {
291
+ return createMemoryStore({
292
+ backend: createFileMemoryBackend(options.cwd, options.env),
293
+ ...(options.embedder ? { embedder: options.embedder } : {}),
294
+ });
295
+ }
@@ -14,6 +14,8 @@ export interface MemoryFact {
14
14
  scope: MemoryScope;
15
15
  createdAt: string;
16
16
  sessionId?: string;
17
+ /** Which layer a layered store read this from ("project", "workspace"). Never stored. */
18
+ layer?: string;
17
19
  }
18
20
 
19
21
  interface FactsFile {
@@ -62,6 +64,15 @@ export function userMemoryPath(env: Record<string, string | undefined> = process
62
64
  return resolve(harnessHome(env), "memory", "facts.json");
63
65
  }
64
66
 
67
+ /** Where one scope's facts are stored. */
68
+ export function memoryPathForScope(
69
+ cwd: string,
70
+ scope: MemoryScope,
71
+ env: Record<string, string | undefined> = process.env,
72
+ ): string {
73
+ return scope === "user" ? userMemoryPath(env) : projectMemoryPath(cwd);
74
+ }
75
+
65
76
  export function projectMemoryPath(cwd: string): string {
66
77
  return resolve(cwd, ".harness", "memory", "facts.json");
67
78
  }
@@ -108,34 +119,55 @@ export function listFacts(
108
119
  return [...readFactsFile(userMemoryPath(env)), ...readFactsFile(projectMemoryPath(cwd))];
109
120
  }
110
121
 
111
- export function addFacts(
112
- cwd: string,
122
+ /**
123
+ * Turn raw text into facts worth storing: trimmed, deduplicated against `known` hashes, and
124
+ * without secrets or noise. `known` gains the hash of every fact returned.
125
+ */
126
+ export function prepareFacts(
127
+ known: Set<string>,
113
128
  incoming: Array<{ text: string; scope?: MemoryScope; sessionId?: string }>,
114
- env: Record<string, string | undefined> = process.env,
115
129
  ): MemoryFact[] {
116
- const known = new Set(listFacts(cwd, env).map((fact) => fact.hash));
117
- const added: MemoryFact[] = [];
130
+ const out: MemoryFact[] = [];
118
131
  for (const item of incoming) {
119
132
  const text = normalizeFactText(item.text);
120
133
  if (text.length < 8 || text.length > 280 || isSecretLike(text)) continue;
121
134
  const hash = factHash(text);
122
135
  if (known.has(hash)) continue;
123
- const scope: MemoryScope = item.scope === "user" ? "user" : "project";
124
- const fact: MemoryFact = {
136
+ known.add(hash);
137
+ out.push({
125
138
  id: newId("mem"),
126
139
  hash,
127
140
  text,
128
- scope,
141
+ scope: item.scope === "user" ? "user" : "project",
129
142
  createdAt: new Date().toISOString(),
130
143
  ...(item.sessionId ? { sessionId: item.sessionId } : {}),
131
- };
144
+ });
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /** Append prepared facts to the file for their scope. */
150
+ export function insertFacts(
151
+ cwd: string,
152
+ facts: MemoryFact[],
153
+ env: Record<string, string | undefined> = process.env,
154
+ ): void {
155
+ for (const scope of ["user", "project"] as const) {
156
+ const rows = facts.filter((fact) => fact.scope === scope);
157
+ if (rows.length === 0) continue;
132
158
  const path = pathForScope(cwd, scope, env);
133
- const facts = readFactsFile(path);
134
- facts.push(fact);
135
- writeFactsFile(path, facts);
136
- known.add(hash);
137
- added.push(fact);
159
+ writeFactsFile(path, [...readFactsFile(path), ...rows]);
138
160
  }
161
+ }
162
+
163
+ export function addFacts(
164
+ cwd: string,
165
+ incoming: Array<{ text: string; scope?: MemoryScope; sessionId?: string }>,
166
+ env: Record<string, string | undefined> = process.env,
167
+ ): MemoryFact[] {
168
+ const known = new Set(listFacts(cwd, env).map((fact) => fact.hash));
169
+ const added = prepareFacts(known, incoming);
170
+ insertFacts(cwd, added, env);
139
171
  return added;
140
172
  }
141
173
 
@@ -181,13 +213,19 @@ export function searchFacts(
181
213
  topK = 10,
182
214
  env: Record<string, string | undefined> = process.env,
183
215
  ): MemoryFact[] {
184
- const facts = listFacts(cwd, env);
185
- if (facts.length === 0) return [];
216
+ return rankFacts(listFacts(cwd, env), query, topK);
217
+ }
218
+
219
+ /**
220
+ * Facts that match the query's words, best first. Undefined when the query has no usable words,
221
+ * which callers treat as "show the most recent".
222
+ */
223
+ export function keywordHits<T extends MemoryFact>(facts: T[], query: string): T[] | undefined {
186
224
  const tokens = tokenizeMemoryQuery(query);
187
- if (tokens.length === 0) return takeRecentFacts(facts, topK);
225
+ if (tokens.length === 0) return undefined;
188
226
  const needle = normalizeFactText(query).toLowerCase();
189
227
  const leftover = leftoverNameBoosts(facts, query, tokens);
190
- const hits = facts
228
+ return facts
191
229
  .map((fact, index) => ({
192
230
  fact,
193
231
  score: scoreFact(fact, index, facts.length, tokens, needle) + (leftover.get(fact.id) ?? 0),
@@ -195,6 +233,18 @@ export function searchFacts(
195
233
  .filter((row) => row.score > 1)
196
234
  .sort((a, b) => b.score - a.score)
197
235
  .map((row) => row.fact);
236
+ }
237
+
238
+ /** Pad a hit list to `topK` with recent user facts, as keyword recall always has. */
239
+ export function completeHits<T extends MemoryFact>(hits: T[], all: T[], topK: number): T[] {
240
+ return fillMemoryHits(hits, all, topK);
241
+ }
242
+
243
+ /** Keyword recall over facts already in memory. */
244
+ export function rankFacts<T extends MemoryFact>(facts: T[], query: string, topK = 10): T[] {
245
+ if (facts.length === 0) return [];
246
+ const hits = keywordHits(facts, query);
247
+ if (!hits) return takeRecentFacts(facts, topK);
198
248
  return fillMemoryHits(hits, facts, topK);
199
249
  }
200
250
 
@@ -273,11 +323,11 @@ function scoreFact(
273
323
  return score;
274
324
  }
275
325
 
276
- function takeRecentFacts(facts: MemoryFact[], topK: number): MemoryFact[] {
326
+ function takeRecentFacts<T extends MemoryFact>(facts: T[], topK: number): T[] {
277
327
  return facts.slice(-topK).reverse();
278
328
  }
279
329
 
280
- function fillMemoryHits(hits: MemoryFact[], all: MemoryFact[], topK: number): MemoryFact[] {
330
+ function fillMemoryHits<T extends MemoryFact>(hits: T[], all: T[], topK: number): T[] {
281
331
  const out = hits.slice(0, topK);
282
332
  const seen = new Set(out.map((fact) => fact.id));
283
333
  for (const fact of all.filter((item) => item.scope === "user").reverse()) {
@@ -85,6 +85,11 @@ function observationHandle(
85
85
  };
86
86
  }
87
87
 
88
+ function reportUnavailable(options: CreateObservabilityOptions, what: string, err: unknown): void {
89
+ const detail = err instanceof Error ? err.message : String(err);
90
+ safe(() => options.onUnavailable?.(`${what}: ${detail.slice(0, 300)}`));
91
+ }
92
+
88
93
  export async function tryCreateLangfuseObservability(
89
94
  options: CreateObservabilityOptions = {},
90
95
  ): Promise<Observability | undefined> {
@@ -112,7 +117,8 @@ export async function tryCreateLangfuseObservability(
112
117
  LangfuseSpanProcessor = otelMod.LangfuseSpanProcessor;
113
118
  NodeSDK = sdkMod.NodeSDK;
114
119
  LangfuseClient = clientMod.LangfuseClient;
115
- } catch {
120
+ } catch (err) {
121
+ reportUnavailable(options, "the Langfuse or OpenTelemetry packages did not load", err);
116
122
  return undefined;
117
123
  }
118
124
 
@@ -131,7 +137,8 @@ export async function tryCreateLangfuseObservability(
131
137
  const sdk = new NodeSDK({ spanProcessors: [processor] });
132
138
  sdk.start();
133
139
  otel = sdk;
134
- } catch {
140
+ } catch (err) {
141
+ reportUnavailable(options, "the OpenTelemetry SDK did not start", err);
135
142
  return undefined;
136
143
  }
137
144
 
@@ -92,6 +92,11 @@ export interface CreateObservabilityOptions {
92
92
  agentVersion?: string;
93
93
  environment?: string;
94
94
  env?: Record<string, string | undefined>;
95
+ /**
96
+ * Called once when the Langfuse keys are set but tracing could not start, with the reason.
97
+ * Without it the failure is silent and the caller gets the no-op observer.
98
+ */
99
+ onUnavailable?: (reason: string) => void;
95
100
  }
96
101
 
97
102
  export const FEEDBACK_CATEGORIES = [