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

session-entry.ts

108 lines3.9 KB

1import { isStandardSchema, validateWithStandardSchema } from '@tanstack/ai'
2import type { InferSchemaType, SchemaInput } from '@tanstack/ai'
3import type { SessionIndexEntry } from '@tanstack/ai-persistence'
4​
5/**
6 * The type of the session metadata that `TSchema` checks. Without a schema,
7 * or with a schema that gives no type (a plain JSON Schema), any record.
8 */
9export type MetadataOf<TSchema> = 0 extends 1 & TSchema
10 ? Record<string, unknown>
11 : TSchema extends SchemaInput
12 ? unknown extends InferSchemaType<TSchema>
13 ? Record<string, unknown>
14 : InferSchemaType<TSchema>
15 : Record<string, unknown>
16​
17/**
18 * A change to a session index entry. Each field you pass replaces the stored
19 * one, so `metadata` replaces the whole object.
20 */
21export interface SessionEntryChange<TMetadata = Record<string, unknown>> {
22 title?: string
23 pinned?: boolean
24 metadata?: TMetadata
26​
27/**
28 * A change, or a function that makes the change from the current entry. Use
29 * the function to change part of `metadata`: when another host writes the
30 * entry first, the function runs again on the new entry, so neither change
31 * is lost. Return `undefined` to write nothing.
32 */
33export type SessionEntryUpdate<
34 TMetadata = Record<string, unknown>,
35 TChange = SessionEntryChange<TMetadata>,
36> = TChange | ((entry: SessionIndexEntry<TMetadata>) => TChange | undefined)
37​
38/** Session metadata that a `metadataSchema` refused. Nothing was written. */
39export class SessionMetadataError extends Error {
40 readonly issues: ReadonlyArray<{ message: string; path?: Array<string> }>
41 constructor(
42 issues: ReadonlyArray<{ message: string; path?: Array<string> }>,
43 ) {
44 super(
45 `The session metadata is not valid: ${issues.map((issue) => issue.message).join(', ')}`,
46 )
47 this.name = 'SessionMetadataError'
48 this.issues = issues
49 }
51​
52/**
53 * @internal Throw when `schema` is not a Standard Schema: a plain JSON Schema
54 * cannot check a write, so it would let any metadata in.
55 */
56export function assertMetadataSchema(owner: string, schema: unknown) {
57 if (schema !== undefined && !isStandardSchema(schema)) {
58 throw new Error(
59 `${owner}: metadataSchema must be a Standard Schema (for example a zod object). A plain JSON Schema cannot check the metadata.`,
60 )
61 }
63​
64/** The output of `schema` for `metadata`. Throws when it refuses the value. */
65async function checked(schema: SchemaInput, metadata: unknown) {
66 const result = await validateWithStandardSchema<Record<string, unknown>>(
67 schema,
68 metadata,
69 )
70 if (!result.success) throw new SessionMetadataError(result.issues)
71 return result.data
73​
74/**
75 * @internal The entry after `update`. `undefined` when there is no entry or
76 * the update writes nothing. The harness schema checks `metadata`, and the
77 * entry keeps its output. `pluginSchema` checks the same value, but its
78 * output is not kept: a plugin schema with fewer keys would drop the keys of
79 * the harness.
80 */
81export async function changedEntry(
82 entry: SessionIndexEntry | undefined,
83 update:
84 | SessionEntryUpdate<
85 any,
86 SessionEntryChange<any> & { usage?: SessionIndexEntry['usage'] }
87 >
88 | undefined,
89 harnessSchema: SchemaInput | undefined,
90 pluginSchema?: SchemaInput,
91): Promise<SessionIndexEntry | undefined> {
92 if (!entry) return undefined
93 const change = typeof update === 'function' ? update(entry) : update
94 if (!change) return undefined
95 let { metadata } = change
96 if (metadata !== undefined) {
97 if (pluginSchema) await checked(pluginSchema, metadata)
98 if (harnessSchema) metadata = await checked(harnessSchema, metadata)
99 }
100 return {
101 ...entry,
102 ...(change.title !== undefined ? { title: change.title } : {}),
103 ...(change.pinned !== undefined ? { pinned: change.pinned } : {}),
104 ...(metadata !== undefined ? { metadata } : {}),
105 ...(change.usage !== undefined ? { usage: change.usage } : {}),
106 updatedAt: Date.now(),
107 }