@zenera/neo 1.1.25 → 1.1.26

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,80 @@
1
+ import { rankMemories, } from "../memory.js";
2
+ /**
3
+ * Reference implementation: scoped maps plus token-overlap scoring. Good enough
4
+ * for tests and local runs; production deployments swap in a vector store
5
+ * without touching the kernel.
6
+ */
7
+ export class InMemoryMemoryStore {
8
+ id;
9
+ #scopes = new Map();
10
+ /** opId → record id, so a replayed op returns the original result */
11
+ #ops = new Map();
12
+ #seq = 0;
13
+ constructor(id = 'mem') {
14
+ this.id = id;
15
+ }
16
+ async search(scope, q) {
17
+ return rankMemories(this.#space(scope).values(), q);
18
+ }
19
+ async get(scope, id) {
20
+ return this.#space(scope).get(id);
21
+ }
22
+ async write(scope, rec, opId) {
23
+ const known = this.#ops.get(opId);
24
+ if (known) {
25
+ const existing = this.#space(scope).get(known);
26
+ if (existing) {
27
+ return existing;
28
+ }
29
+ }
30
+ const now = new Date().toISOString();
31
+ const record = {
32
+ id: `m${++this.#seq}`,
33
+ scope,
34
+ kind: rec.kind ?? 'fact',
35
+ text: rec.text,
36
+ metadata: rec.metadata,
37
+ createdAt: now,
38
+ updatedAt: now,
39
+ revision: 1,
40
+ };
41
+ this.#space(scope).set(record.id, record);
42
+ this.#ops.set(opId, record.id);
43
+ return record;
44
+ }
45
+ async update(scope, id, patch, opId) {
46
+ const space = this.#space(scope);
47
+ const cur = space.get(id);
48
+ if (!cur) {
49
+ throw new Error(`memory record not found: ${scope}/${id}`);
50
+ }
51
+ if (this.#ops.get(opId) === id) {
52
+ return cur;
53
+ }
54
+ if (patch.expectedRevision !== undefined && patch.expectedRevision !== cur.revision) {
55
+ throw new Error(`memory conflict on ${scope}/${id}: expected revision ` +
56
+ `${patch.expectedRevision}, found ${cur.revision}`);
57
+ }
58
+ const next = {
59
+ ...cur,
60
+ kind: patch.kind ?? cur.kind,
61
+ text: patch.text ?? cur.text,
62
+ metadata: patch.metadata ?? cur.metadata,
63
+ updatedAt: new Date().toISOString(),
64
+ revision: cur.revision + 1,
65
+ };
66
+ space.set(id, next);
67
+ this.#ops.set(opId, id);
68
+ return next;
69
+ }
70
+ async delete(scope, id, opId) {
71
+ this.#space(scope).delete(id);
72
+ this.#ops.set(opId, id);
73
+ }
74
+ #space(scope) {
75
+ const s = this.#scopes.get(scope) ?? new Map();
76
+ this.#scopes.set(scope, s);
77
+ return s;
78
+ }
79
+ }
80
+ //# sourceMappingURL=in-memory.js.map
@@ -0,0 +1,4 @@
1
+ export * from './factory.ts';
2
+ export * from './file.ts';
3
+ export * from './in-memory.ts';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ // Backends for the `MemoryStore` contract in `../memory.ts`.
2
+ export * from "./factory.js";
3
+ export * from "./file.js";
4
+ export * from "./in-memory.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,115 @@
1
+ import { type AnyTool } from './types.ts';
2
+ export interface MemoryRecord {
3
+ id: string;
4
+ /** memory space this record belongs to */
5
+ scope: string;
6
+ /** app-defined: 'fact' | 'preference' | 'episode' | … */
7
+ kind: string;
8
+ text: string;
9
+ metadata?: Record<string, unknown>;
10
+ createdAt: string;
11
+ updatedAt: string;
12
+ /** optimistic-concurrency token */
13
+ revision: number;
14
+ }
15
+ export interface MemoryDraft {
16
+ kind?: string;
17
+ text: string;
18
+ metadata?: Record<string, unknown>;
19
+ }
20
+ export interface MemoryPatch {
21
+ kind?: string;
22
+ text?: string;
23
+ metadata?: Record<string, unknown>;
24
+ /** when given, the update fails unless the stored revision matches */
25
+ expectedRevision?: number;
26
+ }
27
+ export interface MemoryQuery {
28
+ /** semantic query; omitted ⇒ pure filter listing */
29
+ text?: string;
30
+ filter?: Record<string, unknown>;
31
+ kind?: string;
32
+ limit?: number;
33
+ minScore?: number;
34
+ }
35
+ export interface MemoryHit {
36
+ record: MemoryRecord;
37
+ /** 0..1, backend-normalized */
38
+ score: number;
39
+ }
40
+ /**
41
+ * Embedding generation is the store's business, not the kernel's: a pgvector
42
+ * implementation embeds inside `write`/`search`, the in-memory one below falls
43
+ * back to token overlap. The kernel never sees vectors.
44
+ */
45
+ export interface MemoryStore {
46
+ readonly id: string;
47
+ search(scope: string, q: MemoryQuery): Promise<MemoryHit[]>;
48
+ get(scope: string, id: string): Promise<MemoryRecord | undefined>;
49
+ /** `opId` makes writes idempotent under retry/replay */
50
+ write(scope: string, rec: MemoryDraft, opId: string): Promise<MemoryRecord>;
51
+ update(scope: string, id: string, patch: MemoryPatch, opId: string): Promise<MemoryRecord>;
52
+ delete(scope: string, id: string, opId: string): Promise<void>;
53
+ }
54
+ export interface MemoryBinding<TCtx = unknown> {
55
+ /** MemoryStore id */
56
+ store: string;
57
+ /** namespace; default `agent:${agent.name}`. A function is resolved per run. */
58
+ scope?: string | ((ctx: TCtx) => string);
59
+ access: 'read' | 'read-write';
60
+ /** inject top-k matches before an LLM call */
61
+ autoRecall?: {
62
+ query: 'last_user_input' | 'none';
63
+ limit: number;
64
+ };
65
+ }
66
+ /** A binding with its scope already resolved against the run context. */
67
+ export interface ResolvedBinding {
68
+ store: string;
69
+ scope: string;
70
+ access: 'read' | 'read-write';
71
+ autoRecall?: {
72
+ query: 'last_user_input' | 'none';
73
+ limit: number;
74
+ };
75
+ }
76
+ export interface MemoryRecallSpec {
77
+ kind: 'recall';
78
+ store: string;
79
+ scope: string;
80
+ query: MemoryQuery;
81
+ hits: {
82
+ id: string;
83
+ score: number;
84
+ revision: number;
85
+ }[];
86
+ /** the rendered block the model actually saw */
87
+ content: string;
88
+ }
89
+ export interface MemoryOpSpec {
90
+ kind: 'op';
91
+ op: 'write' | 'update' | 'delete';
92
+ store: string;
93
+ scope: string;
94
+ /** sha256(runId, callId) — deterministic, so replay re-issues the same write */
95
+ opId: string;
96
+ recordId: string;
97
+ revision: number;
98
+ before?: string;
99
+ after?: string;
100
+ }
101
+ export declare function memoryOpId(runId: string, callId: string): string;
102
+ export declare function renderMemories(hits: MemoryHit[]): string;
103
+ /**
104
+ * Filtering plus token-overlap scoring, shared by the backends that have no
105
+ * embeddings of their own. A vector store ignores this and ranks in the
106
+ * database instead — the kernel only ever sees `MemoryHit[]`.
107
+ */
108
+ export declare function rankMemories(records: Iterable<MemoryRecord>, q: MemoryQuery): MemoryHit[];
109
+ /**
110
+ * Memory is reachable both explicitly (these tools) and implicitly (auto-recall
111
+ * in the runner). Both land in the trajectory; only the explicit path is
112
+ * visible to the model as a tool.
113
+ */
114
+ export declare function memoryTools<TCtx>(bindings: ResolvedBinding[]): AnyTool<TCtx>[];
115
+ //# sourceMappingURL=memory.d.ts.map
package/dist/memory.js ADDED
@@ -0,0 +1,213 @@
1
+ import { hash } from "./payload.js";
2
+ import { MEMORY_DELETE_TOOL, MEMORY_SEARCH_TOOL, MEMORY_UPDATE_TOOL, MEMORY_WRITE_TOOL, tool, withEffects, } from "./types.js";
3
+ export function memoryOpId(runId, callId) {
4
+ return hash(`${runId}\u0000${callId}`);
5
+ }
6
+ export function renderMemories(hits) {
7
+ if (!hits.length) {
8
+ return '';
9
+ }
10
+ const lines = hits.map((h) => `- [${h.record.id}] (${h.record.kind}, score ${h.score.toFixed(2)}) ${h.record.text}`);
11
+ return `Relevant memories:\n${lines.join('\n')}`;
12
+ }
13
+ // ---------------------------------------------------------------------------
14
+ // Shared ranking
15
+ // ---------------------------------------------------------------------------
16
+ /**
17
+ * Filtering plus token-overlap scoring, shared by the backends that have no
18
+ * embeddings of their own. A vector store ignores this and ranks in the
19
+ * database instead — the kernel only ever sees `MemoryHit[]`.
20
+ */
21
+ export function rankMemories(records, q) {
22
+ const limit = q.limit ?? 8;
23
+ const terms = tokenize(q.text ?? '');
24
+ const hits = [];
25
+ for (const rec of records) {
26
+ if (q.kind && rec.kind !== q.kind) {
27
+ continue;
28
+ }
29
+ if (q.filter && !matches(rec.metadata, q.filter)) {
30
+ continue;
31
+ }
32
+ const score = terms.length ? overlap(terms, tokenize(rec.text)) : 1;
33
+ if (score <= 0 || (q.minScore !== undefined && score < q.minScore)) {
34
+ continue;
35
+ }
36
+ hits.push({ record: rec, score });
37
+ }
38
+ return hits.sort((a, b) => b.score - a.score).slice(0, limit);
39
+ }
40
+ function tokenize(v) {
41
+ return v
42
+ .toLowerCase()
43
+ .split(/[^a-z0-9]+/)
44
+ .filter((t) => t.length > 2);
45
+ }
46
+ function overlap(a, b) {
47
+ const set = new Set(b);
48
+ const shared = a.filter((t) => set.has(t)).length;
49
+ return a.length ? shared / a.length : 0;
50
+ }
51
+ function matches(meta, filter) {
52
+ return Object.entries(filter).every(([k, v]) => meta?.[k] === v);
53
+ }
54
+ // ---------------------------------------------------------------------------
55
+ // Built-in memory tools
56
+ // ---------------------------------------------------------------------------
57
+ function spaceParam(bindings) {
58
+ return bindings.length > 1
59
+ ? { type: 'string', enum: bindings.map((b) => b.scope), description: 'memory space' }
60
+ : undefined;
61
+ }
62
+ function pick(bindings, space) {
63
+ const b = space ? bindings.find((x) => x.scope === space) : bindings[0];
64
+ if (!b) {
65
+ throw new Error(`unknown memory space: ${space ?? '(default)'}`);
66
+ }
67
+ return b;
68
+ }
69
+ /**
70
+ * Memory is reachable both explicitly (these tools) and implicitly (auto-recall
71
+ * in the runner). Both land in the trajectory; only the explicit path is
72
+ * visible to the model as a tool.
73
+ */
74
+ export function memoryTools(bindings) {
75
+ if (!bindings.length) {
76
+ return [];
77
+ }
78
+ const writable = bindings.filter((b) => b.access === 'read-write');
79
+ const space = spaceParam(bindings);
80
+ const withSpace = (props) => (space ? { ...props, space } : props);
81
+ const tools = [
82
+ tool({
83
+ name: MEMORY_SEARCH_TOOL,
84
+ description: 'Search long-lived memories.',
85
+ parameters: {
86
+ type: 'object',
87
+ properties: withSpace({
88
+ query: { type: 'string' },
89
+ kind: { type: 'string' },
90
+ limit: { type: 'integer' },
91
+ }),
92
+ required: ['query'],
93
+ additionalProperties: false,
94
+ },
95
+ execute: async (args, tc) => {
96
+ const b = pick(bindings, args.space);
97
+ const store = tc.services.memoryStore(b.store);
98
+ const hits = await store.search(b.scope, {
99
+ text: args.query,
100
+ kind: args.kind,
101
+ limit: args.limit,
102
+ });
103
+ return hits.map((h) => ({
104
+ id: h.record.id,
105
+ kind: h.record.kind,
106
+ text: h.record.text,
107
+ revision: h.record.revision,
108
+ score: Number(h.score.toFixed(3)),
109
+ }));
110
+ },
111
+ }),
112
+ ];
113
+ if (!writable.length) {
114
+ return tools;
115
+ }
116
+ const wSpace = spaceParam(writable);
117
+ const withWSpace = (props) => wSpace ? { ...props, space: wSpace } : props;
118
+ tools.push(tool({
119
+ name: MEMORY_WRITE_TOOL,
120
+ description: 'Store a new long-lived memory.',
121
+ parameters: {
122
+ type: 'object',
123
+ properties: withWSpace({ text: { type: 'string' }, kind: { type: 'string' } }),
124
+ required: ['text'],
125
+ additionalProperties: false,
126
+ },
127
+ execute: async (args, tc) => {
128
+ const b = pick(writable, args.space);
129
+ const opId = memoryOpId(tc.state.runId, tc.callId);
130
+ const rec = await tc.services
131
+ .memoryStore(b.store)
132
+ .write(b.scope, { text: args.text, kind: args.kind }, opId);
133
+ return withEffects(`stored memory ${rec.id}`, {
134
+ kind: 'memory_op',
135
+ spec: {
136
+ kind: 'op',
137
+ op: 'write',
138
+ store: b.store,
139
+ scope: b.scope,
140
+ opId,
141
+ recordId: rec.id,
142
+ revision: rec.revision,
143
+ after: rec.text,
144
+ },
145
+ });
146
+ },
147
+ }), tool({
148
+ name: MEMORY_UPDATE_TOOL,
149
+ description: 'Update an existing memory by id.',
150
+ parameters: {
151
+ type: 'object',
152
+ properties: withWSpace({
153
+ id: { type: 'string' },
154
+ text: { type: 'string' },
155
+ kind: { type: 'string' },
156
+ }),
157
+ required: ['id'],
158
+ additionalProperties: false,
159
+ },
160
+ execute: async (args, tc) => {
161
+ const b = pick(writable, args.space);
162
+ const store = tc.services.memoryStore(b.store);
163
+ const before = await store.get(b.scope, args.id);
164
+ const opId = memoryOpId(tc.state.runId, tc.callId);
165
+ const rec = await store.update(b.scope, args.id, { text: args.text, kind: args.kind }, opId);
166
+ return withEffects(`updated memory ${rec.id}`, {
167
+ kind: 'memory_op',
168
+ spec: {
169
+ kind: 'op',
170
+ op: 'update',
171
+ store: b.store,
172
+ scope: b.scope,
173
+ opId,
174
+ recordId: rec.id,
175
+ revision: rec.revision,
176
+ before: before?.text,
177
+ after: rec.text,
178
+ },
179
+ });
180
+ },
181
+ }), tool({
182
+ name: MEMORY_DELETE_TOOL,
183
+ description: 'Delete a memory by id.',
184
+ parameters: {
185
+ type: 'object',
186
+ properties: withWSpace({ id: { type: 'string' } }),
187
+ required: ['id'],
188
+ additionalProperties: false,
189
+ },
190
+ execute: async (args, tc) => {
191
+ const b = pick(writable, args.space);
192
+ const store = tc.services.memoryStore(b.store);
193
+ const before = await store.get(b.scope, args.id);
194
+ const opId = memoryOpId(tc.state.runId, tc.callId);
195
+ await store.delete(b.scope, args.id, opId);
196
+ return withEffects(`deleted memory ${args.id}`, {
197
+ kind: 'memory_op',
198
+ spec: {
199
+ kind: 'op',
200
+ op: 'delete',
201
+ store: b.store,
202
+ scope: b.scope,
203
+ opId,
204
+ recordId: args.id,
205
+ revision: before?.revision ?? 0,
206
+ before: before?.text,
207
+ },
208
+ });
209
+ },
210
+ }));
211
+ return tools;
212
+ }
213
+ //# sourceMappingURL=memory.js.map
@@ -48,10 +48,10 @@ declare const modelSpec: z.ZodObject<{
48
48
  thinkingBudgetTokens: z.ZodOptional<z.ZodInt>;
49
49
  thinkingBudget: z.ZodOptional<z.ZodInt>;
50
50
  thinkingLevel: z.ZodOptional<z.ZodEnum<{
51
+ minimal: "minimal";
51
52
  low: "low";
52
53
  medium: "medium";
53
54
  high: "high";
54
- minimal: "minimal";
55
55
  }>>;
56
56
  includeThoughts: z.ZodOptional<z.ZodBoolean>;
57
57
  routing: z.ZodOptional<z.ZodObject<{
@@ -163,15 +163,15 @@ declare const sandbox: z.ZodObject<{
163
163
  cpus: z.ZodOptional<z.ZodNumber>;
164
164
  memory: z.ZodOptional<z.ZodInt>;
165
165
  network: z.ZodOptional<z.ZodEnum<{
166
+ bridge: "bridge";
166
167
  none: "none";
167
168
  host: "host";
168
- bridge: "bridge";
169
169
  }>>;
170
170
  workdir: z.ZodOptional<z.ZodString>;
171
171
  timeout: z.ZodOptional<z.ZodInt>;
172
172
  hardening: z.ZodOptional<z.ZodEnum<{
173
- strict: "strict";
174
173
  standard: "standard";
174
+ strict: "strict";
175
175
  }>>;
176
176
  user: z.ZodOptional<z.ZodString>;
177
177
  persist: z.ZodOptional<z.ZodBoolean>;
@@ -220,10 +220,10 @@ export declare const projectSchema: z.ZodObject<{
220
220
  thinkingBudgetTokens: z.ZodOptional<z.ZodInt>;
221
221
  thinkingBudget: z.ZodOptional<z.ZodInt>;
222
222
  thinkingLevel: z.ZodOptional<z.ZodEnum<{
223
+ minimal: "minimal";
223
224
  low: "low";
224
225
  medium: "medium";
225
226
  high: "high";
226
- minimal: "minimal";
227
227
  }>>;
228
228
  includeThoughts: z.ZodOptional<z.ZodBoolean>;
229
229
  routing: z.ZodOptional<z.ZodObject<{
@@ -293,15 +293,15 @@ export declare const projectSchema: z.ZodObject<{
293
293
  cpus: z.ZodOptional<z.ZodNumber>;
294
294
  memory: z.ZodOptional<z.ZodInt>;
295
295
  network: z.ZodOptional<z.ZodEnum<{
296
+ bridge: "bridge";
296
297
  none: "none";
297
298
  host: "host";
298
- bridge: "bridge";
299
299
  }>>;
300
300
  workdir: z.ZodOptional<z.ZodString>;
301
301
  timeout: z.ZodOptional<z.ZodInt>;
302
302
  hardening: z.ZodOptional<z.ZodEnum<{
303
- strict: "strict";
304
303
  standard: "standard";
304
+ strict: "strict";
305
305
  }>>;
306
306
  user: z.ZodOptional<z.ZodString>;
307
307
  persist: z.ZodOptional<z.ZodBoolean>;
@@ -325,8 +325,8 @@ export declare const projectSchema: z.ZodObject<{
325
325
  provider: z.ZodOptional<z.ZodString>;
326
326
  discovery: z.ZodDefault<z.ZodEnum<{
327
327
  none: "none";
328
- search: "search";
329
328
  index: "index";
329
+ search: "search";
330
330
  }>>;
331
331
  allow: z.ZodOptional<z.ZodArray<z.ZodString>>;
332
332
  preload: z.ZodOptional<z.ZodArray<z.ZodString>>;
@@ -357,15 +357,15 @@ export declare const projectSchema: z.ZodObject<{
357
357
  cpus: z.ZodOptional<z.ZodNumber>;
358
358
  memory: z.ZodOptional<z.ZodInt>;
359
359
  network: z.ZodOptional<z.ZodEnum<{
360
+ bridge: "bridge";
360
361
  none: "none";
361
362
  host: "host";
362
- bridge: "bridge";
363
363
  }>>;
364
364
  workdir: z.ZodOptional<z.ZodString>;
365
365
  timeout: z.ZodOptional<z.ZodInt>;
366
366
  hardening: z.ZodOptional<z.ZodEnum<{
367
- strict: "strict";
368
367
  standard: "standard";
368
+ strict: "strict";
369
369
  }>>;
370
370
  user: z.ZodOptional<z.ZodString>;
371
371
  persist: z.ZodOptional<z.ZodBoolean>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenera/neo",
3
- "version": "1.1.25",
3
+ "version": "1.1.26",
4
4
  "description": "A multi-agent runtime for Node.js: agents, models, tools, skills, memory and an append-only trajectory.",
5
5
  "keywords": [
6
6
  "agents",