Store and read back hosted memory with TypeScript
Step 1: Build the SDK and install the lesson project
You need a workspace-scoped MEMORY_API_KEY for a dedicated test workspace on
NAMS. This lesson does not call a model, so OPENAI_API_KEY is not required.
Use Git, Node.js 22.9 or later with npm, and a POSIX shell. The lesson
commands load .env with Node’s --env-file-if-exists flag, added in
Node.js 22.9; the SDK itself supports Node.js 22. These lessons
share one repository checkout. The example-based lessons build the SDK from
source so they run against current source; application code, including the
MCP lesson’s standalone my-memory-mcp project, installs the published
@neo4j-labs/[email protected] package from npm. Keep this checkout for the
remaining TypeScript lessons.
For your first lesson, clone and build the SDK:
git clone https://github.com/neo4j-labs/agent-memory.git
cd agent-memory
export AGENT_MEMORY_TUTORIAL_ROOT="$PWD"
cd typescript
npm ci
npm run build
cd "$AGENT_MEMORY_TUTORIAL_ROOT"
Expected: the build finishes without errors and typescript/dist/index.js
exists. The example-based lessons use this built SDK; installing an example
does not build it. The MCP lesson’s project uses the npm package instead, so
it does not depend on this build.
Continuing from another lesson, keep your existing checkout and skip the clone/build block above. From any directory inside that checkout, run:
cd "$(git rev-parse --show-toplevel)"
export AGENT_MEMORY_TUTORIAL_ROOT="$PWD"
Both entry paths finish at the repository root. If you changed the SDK source since the preceding lesson, rebuild it before continuing with an example-based lesson.
Enter the shared lesson project — its package.json pins the SDK with
file:../.. so it always runs against the checkout you just built. On its
first use, install its locked dependencies; subsequent lessons reuse them.
Create the tutorial environment file only if it does not already exist:
cd "$AGENT_MEMORY_TUTORIAL_ROOT/typescript/examples/vercel-ai"
if [ ! -d node_modules ]; then npm ci; fi
if [ ! -e .env ]; then
(umask 077; set -C; cat .env.tutorial.example > .env)
fi
chmod 600 .env
npm run lint
Expected: typechecking finishes without errors. It does not authenticate or
write to NAMS. Edit the private .env with the keys required by this lesson;
keep it out of version control. An existing .env is preserved: add missing
tutorial settings without replacing its other values.
For the two model lessons, set OPENAI_MODEL=gpt-4o-mini and supply
OPENAI_API_KEY; an existing demo configuration may select a different model.
If an earlier install was interrupted, or the lockfile changed, run npm ci
again from this project directory, then npm run lint. The directory check
above only avoids an unnecessary reinstall; it does not prove the dependencies
are complete. npm ci replaces node_modules from the lockfile and preserves
your .env and .tutorial-state/ files.
Keep a private note of the selected NAMS workspace name/ID and its key owner.
The optional MEMORY_WORKSPACE_ID is a selector, not proof of ownership. A
workspace-scoped key may not need it. Keep the same endpoint, key and selector
for the run’s authenticated verification and cleanup; do not print the key or
use a different workspace to work around a failed check.
The tutorial template uses gpt-4o-mini for model lessons. DEMO_USER_ID,
newest-conversation reuse and the gpt-5-mini default in .env.example belong
to the separate npm start demo. These lessons create or explicitly resume
their own conversations instead.
All remaining commands run in typescript/examples/vercel-ai/.
--env-file-if-exists=.env loads that file; exported shell variables take
precedence, so keep them consistent with the selected workspace. The project
sets ESM and supplies the compiler configuration; no global TypeScript install
is needed.
Step 2: Inspect the complete program
Open src/tutorials/hosted-quickstart.ts:
import { TutorialRun, isTutorialEntryPoint } from "../../../shared/tutorial-state.js";
import { runTutorialCommand } from "../../../shared/tutorial-cleanup.js";
export async function hostedQuickstart(run: TutorialRun) {
const conversation = await run.createConversation();
console.log(`CONVERSATION_ID=${conversation.id}`);
await run.addMessage("user", `I am planning the fictional ${run.name} project.`);
const stored = await run.verify();
const context = await run.client.shortTerm.getContext(conversation.id);
console.log(`Stored messages verified: ${stored.messages}`);
console.log(`Recent context messages: ${context.recentMessages.length}`);
console.log(`Keep run state: ${run.path}`);
return conversation.id;
}
if (isTutorialEntryPoint(import.meta.url)) {
runTutorialCommand("hosted-quickstart", process.argv.slice(2), "seed", ["seed"],
(_mode, run) => hostedQuickstart(run)).catch(error => { console.error(error); process.exitCode = 1; });
}
The maintained state and cleanup helpers are in typescript/examples/shared/.
Keep the private .tutorial-state/ directory with this checkout. Each run binds
its saved IDs to the endpoint, workspace selector and credential; a changed
identity stops authenticated use of those IDs; local inspect remains available. Reseeding an existing state is refused.
TutorialRun and runTutorialCommand are local teaching helpers, not exports
from the published SDK. They keep a private ledger around these public APIs:
| In this lesson | Public SDK operation underneath |
|---|---|
|
Constructs |
|
|
|
|
|
Reads |
|
|
|
Tutorial-only tracking around middleware |
The helper also retains uncertain operations and scopes cleanup to this run.
When adapting the lesson, use run.client to see the actual SDK calls, and keep
an equivalent ownership and failure policy before removing the teaching
helpers. See the TypeScript API reference
for public methods and the middleware guide
for agentMemoryMiddleware and its best-effort storage behavior.
Step 3: Store and inspect one message
npx tsx --env-file-if-exists=.env \
src/tutorials/hosted-quickstart.ts seed .tutorial-state/hosted-quickstart.json
Expect Stored messages verified: 1 and a Recent context messages: count.
The separate message readback checks the returned ID and fictional project
content; a context count alone would not prove those contents. The run
prints its actual IDs; search ranking and model output are not part of this
storage check. A successful write does not mean asynchronous extraction has
finished.
This introductory path creates no reasoning steps: the service has no verified delete route for steps or tool calls, so lesson cleanup could not remove them (see Hosted cleanup and retained resources). The reasoning methods are listed in the TypeScript API reference.
Verify in a fresh process
Run these commands from the same directory, using the state created above:
npx tsx src/tutorials/hosted-quickstart.ts \
inspect .tutorial-state/hosted-quickstart.json
npx tsx --env-file-if-exists=.env \
src/tutorials/hosted-quickstart.ts verify .tutorial-state/hosted-quickstart.json
inspect shows local saved IDs and operation status without loading .env
or contacting NAMS. verify opens another authenticated client and reads the
recorded conversation and exact message IDs, roles and content digests. Expect
Verified stored messages: with the conversation ID and message count.
Verification makes no model calls and creates no records. It establishes
persistence across client processes; it does not imply that the hosted service
restarted.
Clean up and inspect the disposition
From the same lesson directory, clean up this run using its saved state:
npx tsx --env-file-if-exists=.env \
src/tutorials/hosted-quickstart.ts cleanup .tutorial-state/hosted-quickstart.json
npx tsx src/tutorials/hosted-quickstart.ts \
inspect .tutorial-state/hosted-quickstart.json
The cleanup command waits for the recorded messages' extraction to finish, checks the entities derived from those messages and any explicitly created entities, and deletes only records with proven exclusive ownership. It verifies deleted records are absent. Shared, merged or uncertain records remain listed; inspect their disposition instead of treating partial cleanup as a complete reset. A timeout or failed readback stops cleanup and preserves the state.
Keep the state until every resource has a verified disposition. Closing the client alone does not delete data. Do not remove the state file to bypass an unfinished run or bulk-delete workspace entities.
Read the cleanup result before starting another run. These are illustrative shapes; your IDs and counts differ:
Cleanup: {"complete":true,"retainedIds":[],"residualIds":[]}
Cleanup: {"complete":false,"retainedIds":["<entity-id>"],"residualIds":[]}
| Result | Next action |
|---|---|
|
Keep the original ledger as the completed record. A new run uses a new state path. |
|
Inspect each retained resource’s reason. Ask the workspace owner to review its ownership; do not delete it by name or force a workspace reset. |
Error, exit status |
Preserve the ledger and error. A timeout can be retried against the same state; an uncertain write or residual ID needs review before further writes or deletion. |
inspect reads only the local ledger and works without .env, a current key,
or a service connection. It reports IDs, operation status and cleanup
dispositions, omitting credentials, credential fingerprints, workspace
selectors and message digests. It does not establish the current remote state.
After key rotation, verify, record and cleanup still refuse a changed
identity. Do not edit the ledger’s identity to bypass that guard.
For an uncertain or retained result, privately give the workspace owner the run ID, recorded resource IDs, operation statuses, selected workspace note and the failing command. Retain any original MCP create receipt. Do not send keys or the raw ledger. The owner must resolve the exact records before a cleanup claim; a new key or a repeated write is not evidence that the earlier attempt failed.
Only after a completed run, start the next exercise with a distinct filename:
npx tsx --env-file-if-exists=.env \
src/tutorials/hosted-quickstart.ts seed .tutorial-state/hosted-quickstart-2.json
Use that new filename for all subsequent commands for the new run. Preserve
the original ledger and any receipts; do not remove them to make seed,
teach or init accept a used path.