@genkit-ai/ai
Version:
Genkit AI framework generative AI APIs.
201 lines (197 loc) • 8.13 kB
text/typescript
import { ActionContext } from '@genkit-ai/core';
import { EventEmitter } from '@genkit-ai/core/async';
import { Registry } from '@genkit-ai/core/registry';
import { SessionState, Artifact, SessionSnapshot } from './agent-types.mjs';
export { AgentFinishReason, AgentFinishReasonSchema, ArtifactSchema, SessionSnapshotSchema, SessionStateSchema } from './agent-types.mjs';
import { MessageData } from './model-types.mjs';
import './parts.mjs';
/**
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Input type for {@link SessionStore.saveSnapshot}.
*
* Identical to {@link SessionSnapshot} except that `snapshotId` is optional.
* When omitted the store is responsible for assigning a new identifier
* (enabling stores to encode grouping or routing information in the ID).
* When provided the store performs an upsert - updating the existing snapshot.
*/
type SessionSnapshotInput<S = unknown> = Omit<SessionSnapshot<S>, 'snapshotId'> & {
snapshotId?: string;
};
/**
* Options provided to the session store methods.
*/
interface SessionStoreOptions {
context?: ActionContext;
}
/**
* Lookup options for {@link SessionStore.getSnapshot}.
*
* Exactly one of `snapshotId` or `sessionId` must be provided:
*
* - `snapshotId` loads that specific snapshot.
* - `sessionId` loads the *latest* (leaf) snapshot of the session - the most
* recent snapshot that no other snapshot points to as its parent. This is
* the common case for simple session storage (e.g. `useChat`) where the
* client only tracks a stable session id and lets the server remember the
* conversation. A session with *branching* snapshots (more than one leaf,
* e.g. after a regenerate) has no single "latest"; by default the store
* returns the most-recent leaf, but it can be configured to reject the
* lookup with `FAILED_PRECONDITION` - in which case, resume by `snapshotId`.
*/
interface GetSnapshotOptions {
snapshotId?: string;
sessionId?: string;
context?: ActionContext;
}
/**
* A function that receives the current snapshot and returns the updated
* snapshot to persist.
*
* - Return the mutated snapshot to save it.
* - Return `null` to silently skip the update (no-op).
* - Throw to abort with an error (e.g. precondition failure).
*/
type SnapshotMutator<S = unknown> = (current: SessionSnapshot<S> | undefined) => SessionSnapshotInput<S> | null;
/**
* Interface for persistent session snapshot storage.
*/
interface SessionStore<S = unknown> {
/**
* Loads a snapshot either by its `snapshotId` or by `sessionId`.
*
* See {@link GetSnapshotOptions} for the lookup semantics (exactly one of
* `snapshotId` / `sessionId`; `sessionId` resolves to the session's latest
* leaf snapshot, optionally rejecting branching histories).
*/
getSnapshot(opts: GetSnapshotOptions): Promise<SessionSnapshot<S> | undefined>;
/**
* Atomically reads the current snapshot (if `snapshotId` is provided),
* passes it to `mutator`, and persists the result.
*
* - When `snapshotId` is provided the store reads the existing snapshot
* and passes it to the mutator. The mutator can inspect the current
* state (e.g. to check for concurrent status changes) and return the
* updated snapshot to save, or `null` to skip the write.
* - When `snapshotId` is `undefined` the store passes `undefined` to
* the mutator (signaling a new snapshot). The store assigns a new
* identifier.
*
* Implementations should ensure the read→mutate→write cycle is atomic
* to prevent race conditions (e.g. a "done" write overwriting a
* concurrent "aborted" status).
*
* The mutator can:
*
* - Return a snapshot to save it.
* - Return `null` to silently skip the write.
* - Throw to abort with an error.
*
* @returns The `snapshotId` that was used, or `null` when the mutator
* returned `null`.
*/
saveSnapshot(snapshotId: string | undefined, mutator: SnapshotMutator<S>, options?: SessionStoreOptions): Promise<string | null>;
onSnapshotStateChange?(snapshotId: string, callback: (snapshot: SessionSnapshot<S>) => void, options?: SessionStoreOptions): void | (() => void);
}
/**
* State manager for a session turn, tracking messages, custom state, and artifacts.
*/
declare class Session<S = unknown> extends EventEmitter {
private state;
private version;
/** Stable identifier that correlates traces across agent turns. */
readonly sessionId: string;
constructor(initialState: SessionState<S>);
/**
* Returns a deep copy of the current session state.
*/
getState(): SessionState<S>;
/**
* Retrieves all messages associated with the session.
*
* Returns a copy so callers cannot mutate the session's internal message
* array in place.
*/
getMessages(): MessageData[];
/**
* Appends a list of messages to the session.
*/
addMessages(messages: MessageData[]): void;
/**
* Overwrites the session messages.
*/
setMessages(messages: MessageData[]): void;
/**
* Retrieves the custom state of the session.
*/
getCustom(): S | undefined;
/**
* Updates the custom state of the session using a mutator function.
*/
updateCustom(fn: (custom?: S) => S): void;
/**
* Retrieves the list of artifacts generated during the session.
*/
getArtifacts(): Artifact[];
/**
* Adds artifacts to the session, deduplicating items by name.
* Emits 'artifactAdded' for new artifacts and 'artifactUpdated' for replacements.
*/
addArtifacts(artifacts: Artifact[]): void;
/**
* Runs the provided function inside the session's context.
*/
run<O>(fn: () => O): O;
/**
* Gets the current mutation version of the session state.
*/
getVersion(): number;
}
/**
* Utility to execute a function bound to a Session instance context.
*/
declare function runWithSession<S = any, O = any>(registry: Registry, session: Session<S>, fn: () => O): O;
/**
* Returns the Session instance active in the current context.
*/
declare function getCurrentSession<S = any>(registry: Registry): Session<S> | undefined;
/**
* Error thrown during session execution.
*/
declare class SessionError extends Error {
constructor(msg: string);
}
/**
* Validates that `sessionId` is a non-empty string, throwing a descriptive
* error otherwise.
*
* Session ids can be minted by the client and can be any non-empty string
* (e.g. a UUID, or an application-specific identifier). We only reject empty /
* blank values so the id stays usable as a key (and as a directory name in
* {@link FileSessionStore}).
*/
declare function assertValidSessionId(sessionId: string): void;
/**
* Mints a new `snapshotId` (a plain random UUID).
*
* The runtime normally supplies the snapshotId to the store at save time, but
* some flows need the id *ahead of time* - e.g. an agent turn that wants to
* know the snapshotId at turn *start* (to name a git branch / worktree after
* it) and have the snapshot persisted at turn end reuse that very id, or the
* detach path which pre-reserves the in-flight snapshot's id.
*/
declare function reserveSnapshotId(): string;
export { Artifact, type GetSnapshotOptions, Session, SessionError, SessionSnapshot, type SessionSnapshotInput, SessionState, type SessionStore, type SessionStoreOptions, type SnapshotMutator, assertValidSessionId, getCurrentSession, reserveSnapshotId, runWithSession };