@zenera/neo 1.1.54 → 1.1.56

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.
package/dist/index.d.ts CHANGED
@@ -17,6 +17,7 @@ export * from './memory/graph.ts';
17
17
  export * from './memory/grep.ts';
18
18
  export * from './memory/index.ts';
19
19
  export * from './memory/merge.ts';
20
+ export * from './memory/migrate.ts';
20
21
  export * from './memory/page.ts';
21
22
  export * from './memory/recall.ts';
22
23
  export * from './memory/render.ts';
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ export * from "./memory/graph.js";
17
17
  export * from "./memory/grep.js";
18
18
  export * from "./memory/index.js";
19
19
  export * from "./memory/merge.js";
20
+ export * from "./memory/migrate.js";
20
21
  export * from "./memory/page.js";
21
22
  export * from "./memory/recall.js";
22
23
  export * from "./memory/render.js";
package/dist/kernel.d.ts CHANGED
@@ -8,7 +8,7 @@ import type { Services } from './services.ts';
8
8
  import { type Skill } from './skills.ts';
9
9
  import type { AgentState } from './state.ts';
10
10
  import { type CompactionNode, type FinalOutputNode, type UserInputNode } from './trajectory.ts';
11
- import { type AnyTool, type Input, type TokenUsage, type ToolOutcome } from './types.ts';
11
+ import { type AnyTool, type Input, type SuspendSpec, type TokenUsage, type ToolOutcome } from './types.ts';
12
12
  /**
13
13
  * The kernel is a module of plain functions: it holds no state and no
14
14
  * configuration, so there is nothing to instantiate and nothing hidden. All
@@ -129,6 +129,16 @@ export declare function applyLlmResponse<TCtx>(state: AgentState, res: ModelResp
129
129
  * and performs a hand-off when the call was a `transfer_to_*`.
130
130
  */
131
131
  export declare function applyToolResult(state: AgentState, callId: string, outcome: ToolOutcome, env: KernelEnv): Promise<AgentState>;
132
+ /**
133
+ * Records that a pending call suspended the run. The call stays pending - no
134
+ * result is written - so the model still sees it unanswered until it is.
135
+ */
136
+ export declare function applySuspension(state: AgentState, call: {
137
+ callId: string;
138
+ name: string;
139
+ }, spec: SuspendSpec, at: string): AgentState;
140
+ /** Lets a suspended call run again: what it waited for is done. */
141
+ export declare function releaseSuspension(state: AgentState, callId: string): AgentState;
132
142
  /** Records a memory recall or mutation performed by the driver. */
133
143
  export declare function applyMemoryEffect(state: AgentState, effect: MemoryRecallSpec | MemoryOpSpec, env: KernelEnv): Promise<AgentState>;
134
144
  /** Records a skill activation and the tools it unlocked. */
package/dist/kernel.js CHANGED
@@ -650,7 +650,30 @@ export async function applyToolResult(state, callId, outcome, env) {
650
650
  : state.pendingFork?.branches.length
651
651
  ? 'awaiting_branches'
652
652
  : 'awaiting_llm';
653
- return b.commit({ phase, pendingToolCalls, agentName });
653
+ const suspended = state.suspended?.filter((s) => s.callId !== callId);
654
+ return b.commit({
655
+ phase,
656
+ pendingToolCalls,
657
+ agentName,
658
+ suspended: suspended?.length ? suspended : undefined,
659
+ });
660
+ }
661
+ /**
662
+ * Records that a pending call suspended the run. The call stays pending - no
663
+ * result is written - so the model still sees it unanswered until it is.
664
+ */
665
+ export function applySuspension(state, call, spec, at) {
666
+ if (!state.pendingToolCalls.includes(call.callId)) {
667
+ throw new Error(`no pending tool call ${call.callId} in run ${state.runId}`);
668
+ }
669
+ const others = (state.suspended ?? []).filter((s) => s.callId !== call.callId);
670
+ const entry = { callId: call.callId, name: call.name, at, ...spec };
671
+ return { ...state, suspended: [...others, entry] };
672
+ }
673
+ /** Lets a suspended call run again: what it waited for is done. */
674
+ export function releaseSuspension(state, callId) {
675
+ const suspended = (state.suspended ?? []).filter((s) => s.callId !== callId);
676
+ return { ...state, suspended: suspended.length ? suspended : undefined };
654
677
  }
655
678
  function asReason(call) {
656
679
  // The reason travels in the call arguments, which are behind a payload; the
@@ -1,11 +1,39 @@
1
1
  import { type MemoryFile } from './types.ts';
2
- /** Where remembered files appear in the agent's namespace. */
3
- export declare const MEMORY_MOUNT = "/memory";
4
2
  /**
5
3
  * Big enough for any script or config worth re-running, small enough that the
6
4
  * memory directory cannot become a place where build outputs go to hide.
7
5
  */
8
6
  export declare const MAX_FILE_BYTES: number;
7
+ /**
8
+ * Where a remembered file's bytes come from, read for memory by whoever owns
9
+ * them — the workspace's own driver, so it does not matter whether the files
10
+ * are on this machine. `path` names it, and its extension decides the copy's.
11
+ */
12
+ export interface FileSource {
13
+ path: string;
14
+ stat(): Promise<{
15
+ size: number;
16
+ isFile(): boolean;
17
+ }>;
18
+ read(): Promise<Uint8Array>;
19
+ }
20
+ /** A file on this machine's disk, as a source. */
21
+ export declare function hostFile(path: string): FileSource;
22
+ /**
23
+ * The agent's workspace, as memory needs it: a file to remember is read from
24
+ * it, and a remembered file is copied back into it. Both are contained and
25
+ * permission-checked exactly as the file tools are. `Workspace` is one.
26
+ */
27
+ export interface WorkspaceFiles {
28
+ source(path: string): FileSource;
29
+ /**
30
+ * Writes bytes and answers with the path the model knows the file by.
31
+ * Refuses to replace an existing file unless told to.
32
+ */
33
+ write(path: string, data: Uint8Array, opts?: {
34
+ overwrite?: boolean;
35
+ }): Promise<string>;
36
+ }
9
37
  export interface RememberOptions {
10
38
  maxBytes?: number;
11
39
  /** Display path as passed to the tool, for reporting errors without leaking the host filesystem */
@@ -18,7 +46,13 @@ export interface RememberOptions {
18
46
  * the digest provably belongs to the copy that was kept — re-reading the source
19
47
  * to hash it would leave a window for it to change in between.
20
48
  */
21
- export declare function rememberFile(dir: string, source: string, id: string, opts?: RememberOptions): Promise<MemoryFile>;
49
+ export declare function rememberFile(dir: string, source: FileSource, id: string, opts?: RememberOptions): Promise<MemoryFile>;
50
+ /**
51
+ * What a remembered file is called: `<id>.<ext>`. The name the model is shown,
52
+ * and where a copy lands by default. Graphs written while the tree was still
53
+ * mounted stored `/memory/<id>.<ext>`; the base name is the same for both.
54
+ */
55
+ export declare function storedName(file: Pick<MemoryFile, 'path'>): string;
22
56
  /** The host path of a remembered file, for reading it back or deleting it. */
23
57
  export declare function hostPath(dir: string, file: Pick<MemoryFile, 'path'>): string;
24
58
  /** Drop the bytes of a forgotten node. Missing is success — the goal is absence. */
@@ -13,12 +13,12 @@ import { MemoryError } from "./types.js";
13
13
  // describes them. The copy is the point: a reference to a workspace path would
14
14
  // dangle the moment the run ends.
15
15
  //
16
- // The tree is mounted read-only at /memory. Nothing writes there through the
17
- // file tools, so every file under it has a node that explains what it is, and
18
- // the graph cannot acquire orphans that no recollection can ever surface.
16
+ // The tree is never mounted into a sandbox. A file leaves it only as a copy,
17
+ // through `memory_copy_file`, and enters it only through a commit, so every
18
+ // file here has a node that explains what it is and the graph cannot acquire
19
+ // orphans that no recollection can ever surface. It also means a sandbox holds
20
+ // nothing that changes under it while it runs.
19
21
  // ---------------------------------------------------------------------------
20
- /** Where remembered files appear in the agent's namespace. */
21
- export const MEMORY_MOUNT = '/memory';
22
22
  /**
23
23
  * Big enough for any script or config worth re-running, small enough that the
24
24
  * memory directory cannot become a place where build outputs go to hide.
@@ -26,6 +26,10 @@ export const MEMORY_MOUNT = '/memory';
26
26
  export const MAX_FILE_BYTES = 2 * 1024 * 1024;
27
27
  /** Extensions are for `run_command` and syntax hints, not a type system. */
28
28
  const MAX_FORMAT_LEN = 16;
29
+ /** A file on this machine's disk, as a source. */
30
+ export function hostFile(path) {
31
+ return { path, stat: () => stat(path), read: () => readFile(path) };
32
+ }
29
33
  /**
30
34
  * Copy `source` into the memory directory under `id` and describe it.
31
35
  *
@@ -35,7 +39,7 @@ const MAX_FORMAT_LEN = 16;
35
39
  */
36
40
  export async function rememberFile(dir, source, id, opts = {}) {
37
41
  const maxBytes = opts.maxBytes ?? MAX_FILE_BYTES;
38
- const name = opts.path ?? source;
42
+ const name = opts.path ?? source.path;
39
43
  const info = await describe(source, name);
40
44
  if (!info.isFile()) {
41
45
  throw new MemoryError(`${name} is not a regular file`, 'only files can be remembered; write a `fact` node describing a directory instead');
@@ -43,33 +47,41 @@ export async function rememberFile(dir, source, id, opts = {}) {
43
47
  if (info.size > maxBytes) {
44
48
  throw new MemoryError(`${name} is ${info.size} bytes, over the ${maxBytes} byte limit for a remembered file`, 'keep the artifact in the workspace and remember a `snippet` of the part that matters');
45
49
  }
46
- const bytes = await readFile(source);
50
+ const bytes = await source.read();
47
51
  if (bytes.byteLength > maxBytes) {
48
52
  throw new MemoryError(`${name} grew past the ${maxBytes} byte limit while being read`);
49
53
  }
50
- const format = formatOf(source);
51
- const fileName = id + (format ? `.${format}` : '');
54
+ const format = formatOf(source.path);
55
+ const stored = id + (format ? `.${format}` : '');
52
56
  await mkdir(join(dir, FILES_DIR), { recursive: true });
53
- await writeFile(join(dir, FILES_DIR, fileName), bytes);
57
+ await writeFile(join(dir, FILES_DIR, stored), bytes);
54
58
  return {
55
- path: `${MEMORY_MOUNT}/${fileName}`,
59
+ path: stored,
56
60
  bytes: bytes.byteLength,
57
61
  sha256: createHash('sha256').update(bytes).digest('hex'),
58
62
  format,
59
63
  };
60
64
  }
65
+ /**
66
+ * What a remembered file is called: `<id>.<ext>`. The name the model is shown,
67
+ * and where a copy lands by default. Graphs written while the tree was still
68
+ * mounted stored `/memory/<id>.<ext>`; the base name is the same for both.
69
+ */
70
+ export function storedName(file) {
71
+ return basename(file.path);
72
+ }
61
73
  /** The host path of a remembered file, for reading it back or deleting it. */
62
74
  export function hostPath(dir, file) {
63
75
  // Through `basename` so a stored path can never climb out of the tree.
64
- return join(dir, FILES_DIR, basename(file.path));
76
+ return join(dir, FILES_DIR, storedName(file));
65
77
  }
66
78
  /** Drop the bytes of a forgotten node. Missing is success — the goal is absence. */
67
79
  export async function forgetFile(dir, file) {
68
80
  await rm(hostPath(dir, file), { force: true });
69
81
  }
70
- async function describe(source, name = source) {
82
+ async function describe(source, name) {
71
83
  try {
72
- return await stat(source);
84
+ return await source.stat();
73
85
  }
74
86
  catch {
75
87
  throw new MemoryError(`${name} does not exist`, 'remember a file the run actually wrote, by the path the file tools use');
@@ -20,6 +20,14 @@ export interface NodePatch {
20
20
  }
21
21
  /** Deterministic, so the same link committed twice stays one edge. */
22
22
  export declare const edgeKey: (source: string, target: string, relation: Relation) => string;
23
+ /** What changed since the last `settle`, for a store that persists only that. */
24
+ export interface GraphChanges {
25
+ /** added or changed, and still present */
26
+ nodes: readonly string[];
27
+ dropped: readonly string[];
28
+ /** edge keys added or re-stamped; a dropped node takes its edges with it */
29
+ edges: readonly string[];
30
+ }
23
31
  export declare class MemoryGraph {
24
32
  #private;
25
33
  static from(serialized: unknown): MemoryGraph;
@@ -28,6 +36,20 @@ export declare class MemoryGraph {
28
36
  get size(): number;
29
37
  has(id: string): boolean;
30
38
  get(id: string): MemoryNode | undefined;
39
+ /** One edge by key, with its attributes. */
40
+ edge(key: string): {
41
+ source: string;
42
+ target: string;
43
+ attrs: MemoryEdgeAttrs;
44
+ } | undefined;
45
+ get dirty(): boolean;
46
+ /** Changed here and not yet persisted, so a reload must not overwrite it. */
47
+ isDirty(id: string): boolean;
48
+ changes(): GraphChanges;
49
+ /** The changes reached disk. */
50
+ settle(): void;
51
+ /** Mutations that mirror disk rather than change it: a store applying what another wrote. */
52
+ untracked<T>(fn: () => T): T;
31
53
  add(draft: NodeDraft, at: string): MemoryNode;
32
54
  /**
33
55
  * Put a node in exactly as it stands — id, timestamps, revision and counters
@@ -4,6 +4,10 @@ import { edgeVisible, visible, } from "./types.js";
4
4
  export const edgeKey = (source, target, relation) => `${source}|${relation}|${target}`;
5
5
  export class MemoryGraph {
6
6
  #graph = new MultiDirectedGraph();
7
+ #tracking = true;
8
+ #changed = new Set();
9
+ #dropped = new Set();
10
+ #linked = new Set();
7
11
  static from(serialized) {
8
12
  const g = new MemoryGraph();
9
13
  g.#graph.import(serialized);
@@ -24,6 +28,59 @@ export class MemoryGraph {
24
28
  get(id) {
25
29
  return this.#graph.hasNode(id) ? this.#graph.getNodeAttributes(id) : undefined;
26
30
  }
31
+ /** One edge by key, with its attributes. */
32
+ edge(key) {
33
+ if (!this.#graph.hasEdge(key)) {
34
+ return undefined;
35
+ }
36
+ return {
37
+ source: this.#graph.source(key),
38
+ target: this.#graph.target(key),
39
+ attrs: this.#graph.getEdgeAttributes(key),
40
+ };
41
+ }
42
+ get dirty() {
43
+ return this.#changed.size + this.#dropped.size + this.#linked.size > 0;
44
+ }
45
+ /** Changed here and not yet persisted, so a reload must not overwrite it. */
46
+ isDirty(id) {
47
+ return this.#changed.has(id) || this.#dropped.has(id);
48
+ }
49
+ changes() {
50
+ return {
51
+ nodes: [...this.#changed],
52
+ dropped: [...this.#dropped],
53
+ edges: [...this.#linked],
54
+ };
55
+ }
56
+ /** The changes reached disk. */
57
+ settle() {
58
+ this.#changed.clear();
59
+ this.#dropped.clear();
60
+ this.#linked.clear();
61
+ }
62
+ /** Mutations that mirror disk rather than change it: a store applying what another wrote. */
63
+ untracked(fn) {
64
+ const was = this.#tracking;
65
+ this.#tracking = false;
66
+ try {
67
+ return fn();
68
+ }
69
+ finally {
70
+ this.#tracking = was;
71
+ }
72
+ }
73
+ #node(id) {
74
+ if (this.#tracking) {
75
+ this.#changed.add(id);
76
+ this.#dropped.delete(id);
77
+ }
78
+ }
79
+ #edge(key) {
80
+ if (this.#tracking) {
81
+ this.#linked.add(key);
82
+ }
83
+ }
27
84
  add(draft, at) {
28
85
  const node = {
29
86
  id: draft.id,
@@ -39,6 +96,7 @@ export class MemoryGraph {
39
96
  ...(draft.file ? { file: draft.file } : {}),
40
97
  };
41
98
  this.#graph.addNode(node.id, node);
99
+ this.#node(node.id);
42
100
  return node;
43
101
  }
44
102
  /**
@@ -54,6 +112,7 @@ export class MemoryGraph {
54
112
  else {
55
113
  this.#graph.addNode(node.id, next);
56
114
  }
115
+ this.#node(node.id);
57
116
  }
58
117
  update(id, patch, at) {
59
118
  const current = this.#graph.getNodeAttributes(id);
@@ -71,6 +130,7 @@ export class MemoryGraph {
71
130
  revision: current.revision + 1,
72
131
  };
73
132
  this.#graph.replaceNodeAttributes(id, next);
133
+ this.#node(id);
74
134
  return next;
75
135
  }
76
136
  /** Reading is what counts as use — see `memory_load`, not `memory_search`. */
@@ -81,24 +141,29 @@ export class MemoryGraph {
81
141
  const node = this.#graph.getNodeAttributes(id);
82
142
  const next = { ...node, lastUsedAt: at, useCount: node.useCount + 1 };
83
143
  this.#graph.replaceNodeAttributes(id, next);
144
+ this.#node(id);
84
145
  return next;
85
146
  }
86
147
  link(source, target, relation, at) {
87
- this.#graph.mergeEdgeWithKey(edgeKey(source, target, relation), source, target, {
88
- relation,
89
- createdAt: at,
90
- });
148
+ const key = edgeKey(source, target, relation);
149
+ this.#graph.mergeEdgeWithKey(key, source, target, { relation, createdAt: at });
150
+ this.#edge(key);
91
151
  }
92
152
  /** `link` for an edge that already exists elsewhere: it keeps the stamp it had. */
93
153
  adoptEdge(source, target, attrs) {
94
- this.#graph.mergeEdgeWithKey(edgeKey(source, target, attrs.relation), source, target, {
95
- ...attrs,
96
- });
154
+ const key = edgeKey(source, target, attrs.relation);
155
+ this.#graph.mergeEdgeWithKey(key, source, target, { ...attrs });
156
+ this.#edge(key);
97
157
  }
98
158
  /** Drops the node and every edge touching it; the file it names is the store's to unlink. */
99
159
  forget(id) {
100
160
  const node = this.get(id);
101
161
  if (node) {
162
+ if (this.#tracking) {
163
+ this.#graph.forEachEdge(id, (key) => this.#linked.delete(key));
164
+ this.#changed.delete(id);
165
+ this.#dropped.add(id);
166
+ }
102
167
  this.#graph.dropNode(id);
103
168
  }
104
169
  return node;
@@ -18,8 +18,8 @@ import { MemoryError } from "./types.js";
18
18
  // the bytes of a remembered file are the thing itself. An exact match belongs
19
19
  // against all three.
20
20
  //
21
- // Two rules keep this honest against raw `grep` over /memory, which is what it
22
- // exists to replace. Superseded nodes are excluded unless asked for, and come
21
+ // Two rules keep this honest against a raw `grep` over the memory directory,
22
+ // which is what it exists to replace. Superseded nodes are excluded unless asked for, and come
23
23
  // back flagged when they are — serving a withdrawn correction as current is
24
24
  // the failure mode the mount is warned about. And reading here is not use:
25
25
  // recency decay is meant to track what an agent actually opened, and a finder
@@ -44,6 +44,7 @@ export async function grepMemory(store, pattern, filter = {}) {
44
44
  const kinds = filter.kinds?.length ? new Set(filter.kinds) : undefined;
45
45
  const cap = filter.hitsPerNode ?? HITS_PER_NODE;
46
46
  const want = filter.stale ?? 'exclude';
47
+ store.refresh();
47
48
  const superseded = store.graph.superseded(filter.sees);
48
49
  const matches = [];
49
50
  const skipped = [];
@@ -1,8 +1,9 @@
1
1
  import type { Embedder } from '../embedding.ts';
2
2
  import type { IdClock } from '../ids.ts';
3
- import type { MemoryGraph } from './graph.ts';
3
+ import { type FileSource } from './files.ts';
4
+ import { type MemoryGraph } from './graph.ts';
4
5
  import type { MemoryStore } from './store.ts';
5
- import { type MemoryNode, type MemoryQuery, type Recollection } from './types.ts';
6
+ import { type MemoryFile, type MemoryNode, type MemoryQuery, type Recollection } from './types.ts';
6
7
  /** Past this a `load` returns the path and lets the agent open it itself. */
7
8
  export declare const INLINE_FILE_BYTES: number;
8
9
  /**
@@ -28,9 +29,9 @@ export interface CommitNode {
28
29
  text?: string;
29
30
  audience?: string[];
30
31
  metadata?: Record<string, unknown>;
31
- /** absolute host path of a file to copy in, already resolved by the caller */
32
+ /** the file to copy in, already resolved and contained by the caller */
32
33
  file?: {
33
- source: string;
34
+ source: FileSource;
34
35
  path?: string;
35
36
  };
36
37
  expectedRevision?: number;
@@ -73,6 +74,8 @@ export declare class MemoryIndex {
73
74
  get graph(): MemoryGraph;
74
75
  get kinds(): readonly string[];
75
76
  get relations(): readonly string[];
77
+ /** Catches up with what other runs committed to the same memory. */
78
+ refresh(): void;
76
79
  /**
77
80
  * Read-only: a search returns nodes the model has not read, so nothing is
78
81
  * touched. `stale` is the audit view — it puts back the superseded nodes
@@ -96,6 +99,16 @@ export declare class MemoryIndex {
96
99
  * an agent actually read, and a search hands back context it never opened.
97
100
  */
98
101
  load(ids: readonly string[], sees: readonly string[], clock: IdClock): Promise<LoadedNode[]>;
102
+ /**
103
+ * A remembered file's record and bytes, for copying it back into a
104
+ * workspace. Visible nodes only, and missing reads the same as hidden.
105
+ * Not a load: copying a file is not reading the memory, so recency is
106
+ * left alone.
107
+ */
108
+ fileOf(id: string, sees: readonly string[]): Promise<{
109
+ file: MemoryFile;
110
+ bytes: Buffer;
111
+ }>;
99
112
  commit(tx: MemoryTransaction, opts: CommitOptions): Promise<CommitResult>;
100
113
  forget(ids: readonly string[], sees: readonly string[]): Promise<MemoryNode[]>;
101
114
  }