Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

session-log.md

336 lines17.0 KB

1---
2title: Build on the session log
3id: harness-session-log
4order: 4
5description: "Keep your framework's own records (signals, state writes, compaction) in the harness session log, and fold them into the model context."
6keywords:
7 - tanstack ai
8 - harness
9 - session log
10 - LogStore
11 - projection
12 - compaction
13 - encryption
14---
15​
16Your framework keeps its own state next to the conversation: signals for the model, state writes, a compaction summary. Kept in a second store, it can drift from the transcript after a crash. Put these records in the harness session log. They share its atomic appends, its order, and its recovery.
17​
18## Append your own records
19​
20`session.append` adds records to the [session log](./durable-sessions), in one batch after the events that wait:
21​
22```ts group=harness-session-log
23import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
24import { memoryPersistence } from '@tanstack/ai-persistence'
25import { openaiText } from '@tanstack/ai-openai'
26​
27const persistence = memoryPersistence()
28const { log } = persistence.stores
29const assistant = defineHarness({
30 name: 'acme/assistant',
31 adapter: openaiText('gpt-6.1-sol'),
32})
33const host = createHarnessHost({ persistence })
34const session = await host.open(assistant, { threadId: 'thread-1' })
35​
36await session.appendRecords({ records: [{ type: 'app.signal', text: 'The build failed.' }] })
37```
38​
39- A record is JSON with a `type`. Types that start with `harness.` belong to the harness, so `appendRecords` refuses them.
40- `appendRecords` resolves with a receipt when the records are in the log. When another host owns the thread, the receipt is `queued`, and the owner writes the records. See [One host drives a thread](./durable-sessions#one-host-drives-a-thread).
41- Pass `inputId` to make the append safe to send again: `session.appendRecords({ records, inputId: 'signal-7' })`. A second append with the same id writes nothing. Without `inputId`, the append gets a new id. The receipt has the id, as the log keeps it. `user` sets who appends. The default is the user who opened the session.
42- A record can belong to a child thread of the same log. See [One log for a session tree](./shared-logs).
43- In a tool, use `append` from [`durableTool`](./durable-tools), so the records land with the tool batch.
44- A key or a token of the session in a record goes into the log as `[redacted]`. See [Keep tokens out of the log and the model](./auth#keep-tokens-out-of-the-log-and-the-model).
45​
46### Keep records after a truncate
47​
48With [`keepLogRecords: 'since-snapshot'`](./lifecycle#drop-the-records-before-a-snapshot), the store drops the records before each snapshot. A plugin can make the snapshot keep the last records of its own types with `keepRecords`, and read them back with `ctx.session.keptRecords(type)`:
49​
50```ts group=harness-session-log
51import { defineCommand, definePlugin } from '@tanstack/ai-harness'
52​
53export const steps = definePlugin({
54 name: 'acme/steps',
55 keepRecords: { 'acme/steps:step': 100 },
56 setup: (ctx) => ({
57 commands: {
58 steps: defineCommand({
59 description: 'Count the kept steps',
60 run: async () => (await ctx.session.keptRecords('acme/steps:step')).length,
61 }),
62 },
63 }),
64})
65```
66​
67- The snapshot keeps the last 100 `acme/steps:step` records of each thread.
68- `keptRecords` gives the kept records of that type of this thread, oldest first. It works before and after a truncate.
69- [`snapshots()`](./snapshots#go-back-to-an-earlier-message) keeps its last 500 file steps this way, so `session.revert()` works after a truncate.
70- The plugins of the harness of the root thread decide, because that harness folds the log. A type in two plugins keeps the larger count.
71​
72## Fold records into the model context
73​
74By default, the model does not see your records. Set `durability.addRecordsToModelContext` on the harness to fold a record into the messages. Its `record` function gets one object, `{ messages, record }`, and returns the new list, or `undefined` for no change:
75​
76```ts group=harness-session-log
77import type { ProjectOptions } from '@tanstack/ai-harness'
78​
79const project: ProjectOptions = {
80 version: 'v1',
81 record: ({ messages, record }) => {
82 if (record.type === 'app.signal' && typeof record.text === 'string') {
83 return [...messages, { role: 'user', content: record.text }]
84 }
85 return undefined
86 },
88​
89export const projected = defineHarness({
90 name: 'acme/projected',
91 adapter: openaiText('gpt-6.1-sol'),
92 durability: { addRecordsToModelContext: project },
93})
94```
95​
96- `record` must be pure: the same log always folds to the same context, live and after a restart.
97- The model sees the change at its next model call. A message that arrives during a tool call comes after the tool result.
98- Readers see a message that `record` adds at the end of the list, for example the signal above. A change to earlier messages, for example a compaction summary, goes only to the model. `session.transcript()` keeps the full history.
99- Change `version` when you change `record`. A log snapshot with another version is not used, so the host folds the log again from the first record.
100- For compaction, use `projectCompaction` from `@tanstack/ai-compaction`. See [Compact a harness session](./compaction).
101- A chat middleware in a harness turn can append records itself with `getLogRecords(ctx).append([...])` from `@tanstack/ai`. The records land in the log at once. A plugin's middleware reads the writer with `getLogRecords(ctx, { optional: true })`. A plugin cannot list `LogRecordsCapability` in `requires`.
102​
103## Let a client add records
104​
105A webhook or a browser knows something that the model needs: the build failed, or a payment arrived. Let it add a record to the thread, and the next turn reads the record through `durability.addRecordsToModelContext`.
106​
1071. On the server, list the record types in `expose.records`, and set `durability.addRecordsToModelContext` on the same harness:
108​
109```ts group=harness-session-log
110import { createHarnessHandler } from '@tanstack/ai-harness/server'
111​
112export const watcher = defineHarness({
113 name: 'acme/build-watcher',
114 adapter: openaiText('gpt-6.1-sol'),
115 expose: { records: ['app.signal'] },
116 durability: { addRecordsToModelContext: project },
117})
118​
119const watcherHost = createHarnessHost({
120 persistence: memoryPersistence(),
121 access: {
122 getUser: ({ request }) =>
123 request.headers.get('authorization') === `Bearer ${process.env.HARNESS_TOKEN}`
124 ? { id: 'ci-bot' }
125 : null,
126 // The CI bot is the only user, so it can use every thread.
127 rules: { isAllowed: ({ user }) => user.id === 'ci-bot' },
128 },
129})
130​
131// Every instance signs media URLs with the same secret.
132const mediaSecret = process.env.HARNESS_MEDIA_SECRET
133if (!mediaSecret) throw new Error('Set HARNESS_MEDIA_SECRET.')
134​
135export const handler = createHarnessHandler({
136 host: watcherHost,
137 harness: watcher,
138 media: { secret: mediaSecret },
139})
140```
141​
1422. On the client, add the record with `client.append`. Then start a turn with `client.continue`, so the model answers the signal:
143​
144```ts group=harness-session-log-client
145import { createHarnessClient } from '@tanstack/ai-harness/client'
146import type { watcher } from './harness'
147​
148const client = createHarnessClient<typeof watcher>({
149 url: '/api/harness',
150 threadId: 'build-thread',
151 headers: { authorization: 'Bearer my-token' },
152})
153​
154await client.appendRecords({ records: [{ type: 'app.signal', text: 'The build failed.' }] })
155await client.continueWithoutMessage()
156```
157​
158- A record of another type is refused with `not_exposed`. So is a record with a `thread` field: a client writes only to its own thread.
159- Types that start with `harness.` belong to the harness. `defineHarness` throws if `expose.records` lists one.
160- An MCP client adds records with the `append` tool. See [Use a harness from any MCP client](./mcp-server#3-use-the-tools).
161​
162## Read the log
163​
164The store is yours, so read your records back from it, for example to rebuild your state when a session opens. The store keeps each log under an id with its tenant, so build the id with `logIdOf`:
165​
166```ts group=harness-session-log
167import { logIdOf } from '@tanstack/ai-harness'
168​
169// The default tenant. For a tenant, pass `tenantId` too: 'acme:thread-1'.
170const entries = await log.read({ logId: logIdOf({ logId: 'thread-1' }) })
171const signals = entries.filter((entry) => entry.record.type === 'app.signal')
172console.log(signals.map((entry) => entry.seq))
173```
174​
175Each `harness.input` record has the `user` of its sender: its `id`, `name`, and `tenantId`. Every kind of input has it when the sender is known, also a cancel, an answer, a delivery change, and a change of settings.
176​
177Two harness records tell who answers a thread and where a conversation went. See [Hand off a conversation](./handoffs).
178​
179- `harness.handoff`: another agent answers from now on. It has `from` and `to` (an agent name, `null` for the main model, or `{ human: true }` for a person), the `note`, the `runId`, and `by` (`'tool'`, `'code'`, `'router'`, or `'operator'`). A handoff to a person also has the `waitId` of its `human` wait. The last one is the active agent of the thread.
180- `harness.transferred`: `host.transfer` moved the conversation. The log of the target has `from`, and the log of the source has `to`. Each is `{ harness, threadId }`. Both records have the same `transferId`, the `user`, and `at`.
181​
182```ts group=harness-session-log
183const handoffs = entries.filter((entry) => entry.record.type === 'harness.handoff')
184console.log(handoffs.at(-1)?.record.to)
185```
186​
187A reader outside a session that needs a `MessageStore`, for example `reconstructChat`, uses `logMessageStore`. It folds the log with the same `addRecordsToModelContext`, and it reads and writes the transcript that readers see, not the model context. Pass `tenantId` to read the threads of a tenant:
188​
189```ts group=harness-session-log
190import { logMessageStore } from '@tanstack/ai-harness'
191​
192const messages = logMessageStore({ store: log, project })
193console.log(await messages.loadThread('thread-1'))
194```
195​
196## Find the runs in the log
197​
198Your dashboard shows every agent run of a thread, also the runs that ended long ago. The log has one `harness.run.node` record for each run that the session admits:
199​
200```ts group=harness-session-log
201const records = (await log.read({ logId: logIdOf({ logId: 'thread-1' }) })).map(
202 (entry) => entry.record,
204const agentNodes = records.filter(
205 (record) => record.type === 'harness.run.node' && record.kind === 'agent',
207console.log(agentNodes.map((record) => [record.runId, record.agent, record.parentRunId]))
208```
209​
210- A `harness.run.node` record has `runId`, `kind` (`turn`, `agent`, or `command`), and the `user` when it is known. An agent run also has `agent`, and `parentRunId`, `key`, `limits`, and `budget` when it has them.
211- Read only these fields. The other fields of the record are bookkeeping of the session, and they can change.
212- The tree also has `tool` runs. These come from `harness.run` records, not from `harness.run.node` records.
213- The status, the result, and the error come from later records: `harness.run`, `harness.run.update`, and `harness.agent.result`. A session folds them into one tree. See [The run tree](./subagents#the-run-tree).
214- Each `harness.usage` record has the `runId` of the run that made the model call. See [Usage of one run](./usage#usage-of-one-run).
215- A `harness.state` record has a `key` and one change to its value. It is the shared state of [`ctx.harness.state`](./subagents#share-state-between-agents).
216​
217## Encrypt the records in the store
218​
219Wrap the `LogStore` to encrypt the records that hold what people wrote. The host reads and writes through the wrapper, so it only sees plain records. `HarnessRecord` is the type of every record that the harness writes, so a wrong record type is a type error:
220​
221```ts group=harness-session-log
222import { createCipheriv, createDecipheriv, createHmac } from 'node:crypto'
223import { defineLogStore } from '@tanstack/ai-persistence'
224import type { LogRecord, LogStore } from '@tanstack/ai-persistence'
225import type { HarnessRecord } from '@tanstack/ai-harness'
226​
227// The harness records that hold messages, prompts, and tool results.
228const SEALED: ReadonlySet<string> = new Set([
229 'harness.transcript',
230 'harness.input',
231 'harness.event',
232 'harness.tool.result',
233] satisfies Array<HarnessRecord['type']>)
234​
235interface Keys {
236 aes: Buffer // 32 bytes
237 iv: Buffer // a second secret
239​
240// AES-256-GCM. The IV comes from the text, so the same text gives the same output.
241function seal(keys: Keys, text: string) {
242 const iv = createHmac('sha256', keys.iv).update(text).digest().subarray(0, 12)
243 const cipher = createCipheriv('aes-256-gcm', keys.aes, iv)
244 const data = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()])
245 return Buffer.concat([iv, cipher.getAuthTag(), data]).toString('base64')
247​
248function unseal(keys: Keys, sealed: string) {
249 const bytes = Buffer.from(sealed, 'base64')
250 const decipher = createDecipheriv('aes-256-gcm', keys.aes, bytes.subarray(0, 12))
251 decipher.setAuthTag(bytes.subarray(12, 28))
252 return Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]).toString('utf8')
254​
255const isLogRecord = (value: unknown): value is LogRecord =>
256 typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string'
257​
258export function sealedLogStore(store: LogStore, keys: Keys): LogStore {
259 const sealRecord = (record: LogRecord): LogRecord =>
260 SEALED.has(record.type)
261 ? { type: record.type, sealed: seal(keys, JSON.stringify(record)) }
262 : record
263 const openRecord = (record: LogRecord): LogRecord => {
264 if (!SEALED.has(record.type) || typeof record.sealed !== 'string') return record
265 const opened: unknown = JSON.parse(unseal(keys, record.sealed))
266 if (!isLogRecord(opened)) throw new Error('A sealed record did not open.')
267 return opened
268 }
269 return defineLogStore({
270 append: (batch) => store.append({ ...batch, records: batch.records.map(sealRecord) }),
271 read: async (query) =>
272 (await store.read(query)).map((entry) => ({ ...entry, record: openRecord(entry.record) })),
273 offerInput: (input) => store.offerInput({ ...input, record: sealRecord(input.record) }),
274 listOfferedInputs: async (query) =>
275 (await store.listOfferedInputs(query)).map((offer) => ({
276 ...offer,
277 record: openRecord(offer.record),
278 })),
279 // The snapshot holds the transcript too.
280 putSnapshot: (snapshot) =>
281 store.putSnapshot({ ...snapshot, state: seal(keys, JSON.stringify(snapshot.state)) }),
282 getSnapshot: async (query) => {
283 const snapshot = await store.getSnapshot(query)
284 if (!snapshot || typeof snapshot.state !== 'string') return snapshot
285 const state: unknown = JSON.parse(unseal(keys, snapshot.state))
286 return { ...snapshot, state }
287 },
288 // These calls carry no records.
289 subscribe: (watch) => store.subscribe(watch),
290 acquireOwnership: (claim) => store.acquireOwnership(claim),
291 renewOwnership: (claim) => store.renewOwnership(claim),
292 releaseOwnership: (claim) => store.releaseOwnership(claim),
293 pinToWorkers: (pin) => store.pinToWorkers(pin),
294 markHostAlive: (beat) => store.markHostAlive(beat),
295 listLogsWithoutOwner: (query) => store.listLogsWithoutOwner(query),
296 truncate: (cut) => store.truncate(cut),
297 deleteLog: (target) => store.deleteLog(target),
298 })
300​
301const keys = {
302 aes: Buffer.from(process.env.LOG_AES_KEY ?? '', 'base64'),
303 iv: Buffer.from(process.env.LOG_IV_KEY ?? '', 'base64'),
305const sealedHost = createHarnessHost({
306 persistence: { stores: { ...persistence.stores, log: sealedLogStore(log, keys) } },
307})
308```
309​
310CAUTION: The wrapper must give back on read exactly what it got on write: the same fields, the same values, and the same key order. If it does not, the duplicate-input checks and the folds of the session break. The host compares the records that it wrote with the records that it reads back. The store compares a second offer of an input with the first one by its JSON.
311​
312- `seal` must give the same output for the same text. With a random IV, a second offer of the same input is a `conflict`, not a `duplicate`. The cost: two equal records have equal ciphertext.
313- Keep `type` in the clear. The record types that you do not seal (thread settings, runs, usage) stay readable for your dashboards.
314- To redact in place of encrypt, keep the real values in your own store and put them back on read. A wrapper that drops data on write breaks the log.
315​
316## Tune how text streams into the log
317​
318A host merges streamed text and tool call arguments for `log.bufferStreamWriteMs` milliseconds (default 100) before it appends them. A message start or end, a tool call start or end, and your own records append at once.
319​
320```ts group=harness-session-log
321const smoothHost = createHarnessHost({
322 persistence: memoryPersistence(),
323 log: { bufferStreamWriteMs: 250 },
324})
325```
326​
327A larger value writes less often, and clients get text in larger parts.
328​
329## What you have now
330​
331- Your records in the same durable log as the conversation.
332- A model context that folds them in, the same live and after a restart.
333- Records that a webhook or a browser adds, for the record types you expose.
334- A transcript that any reader can fold from the log.
335- Every run of the thread, and the shared state of its agents, in records that you can read.
336- A log store that keeps the messages of your users encrypted.