@witqq/agent-sdk 0.6.1 → 0.8.0
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/README.md +539 -6
- package/dist/{types-BvwNzZCj.d.cts → agent-CW9XbmG_.d.ts} +148 -95
- package/dist/{types-BvwNzZCj.d.ts → agent-DxY68NZL.d.cts} +148 -95
- package/dist/auth/index.cjs +260 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +21 -138
- package/dist/auth/index.d.ts +21 -138
- package/dist/auth/index.js +260 -3
- package/dist/auth/index.js.map +1 -1
- package/dist/backends/claude.cjs +653 -140
- package/dist/backends/claude.cjs.map +1 -1
- package/dist/backends/claude.d.cts +4 -1
- package/dist/backends/claude.d.ts +4 -1
- package/dist/backends/claude.js +653 -140
- package/dist/backends/claude.js.map +1 -1
- package/dist/backends/copilot.cjs +428 -88
- package/dist/backends/copilot.cjs.map +1 -1
- package/dist/backends/copilot.d.cts +13 -4
- package/dist/backends/copilot.d.ts +13 -4
- package/dist/backends/copilot.js +428 -88
- package/dist/backends/copilot.js.map +1 -1
- package/dist/backends/vercel-ai.cjs +349 -77
- package/dist/backends/vercel-ai.cjs.map +1 -1
- package/dist/backends/vercel-ai.d.cts +3 -1
- package/dist/backends/vercel-ai.d.ts +3 -1
- package/dist/backends/vercel-ai.js +349 -77
- package/dist/backends/vercel-ai.js.map +1 -1
- package/dist/backends-BSrsBYFn.d.cts +39 -0
- package/dist/backends-BSrsBYFn.d.ts +39 -0
- package/dist/chat/accumulator.cjs +147 -0
- package/dist/chat/accumulator.cjs.map +1 -0
- package/dist/chat/accumulator.d.cts +64 -0
- package/dist/chat/accumulator.d.ts +64 -0
- package/dist/chat/accumulator.js +145 -0
- package/dist/chat/accumulator.js.map +1 -0
- package/dist/chat/backends.cjs +3524 -0
- package/dist/chat/backends.cjs.map +1 -0
- package/dist/chat/backends.d.cts +66 -0
- package/dist/chat/backends.d.ts +66 -0
- package/dist/chat/backends.js +3512 -0
- package/dist/chat/backends.js.map +1 -0
- package/dist/chat/context.cjs +280 -0
- package/dist/chat/context.cjs.map +1 -0
- package/dist/chat/context.d.cts +191 -0
- package/dist/chat/context.d.ts +191 -0
- package/dist/chat/context.js +277 -0
- package/dist/chat/context.js.map +1 -0
- package/dist/chat/core.cjs +305 -0
- package/dist/chat/core.cjs.map +1 -0
- package/dist/chat/core.d.cts +84 -0
- package/dist/chat/core.d.ts +84 -0
- package/dist/chat/core.js +282 -0
- package/dist/chat/core.js.map +1 -0
- package/dist/chat/errors.cjs +273 -0
- package/dist/chat/errors.cjs.map +1 -0
- package/dist/chat/errors.d.cts +97 -0
- package/dist/chat/errors.d.ts +97 -0
- package/dist/chat/errors.js +266 -0
- package/dist/chat/errors.js.map +1 -0
- package/dist/chat/events.cjs +203 -0
- package/dist/chat/events.cjs.map +1 -0
- package/dist/chat/events.d.cts +245 -0
- package/dist/chat/events.d.ts +245 -0
- package/dist/chat/events.js +196 -0
- package/dist/chat/events.js.map +1 -0
- package/dist/chat/index.cjs +5550 -0
- package/dist/chat/index.cjs.map +1 -0
- package/dist/chat/index.d.cts +77 -0
- package/dist/chat/index.d.ts +77 -0
- package/dist/chat/index.js +5505 -0
- package/dist/chat/index.js.map +1 -0
- package/dist/chat/react/theme.css +2517 -0
- package/dist/chat/react.cjs +3589 -0
- package/dist/chat/react.cjs.map +1 -0
- package/dist/chat/react.d.cts +1088 -0
- package/dist/chat/react.d.ts +1088 -0
- package/dist/chat/react.js +3547 -0
- package/dist/chat/react.js.map +1 -0
- package/dist/chat/runtime.cjs +1245 -0
- package/dist/chat/runtime.cjs.map +1 -0
- package/dist/chat/runtime.d.cts +182 -0
- package/dist/chat/runtime.d.ts +182 -0
- package/dist/chat/runtime.js +1243 -0
- package/dist/chat/runtime.js.map +1 -0
- package/dist/chat/server.cjs +2668 -0
- package/dist/chat/server.cjs.map +1 -0
- package/dist/chat/server.d.cts +648 -0
- package/dist/chat/server.d.ts +648 -0
- package/dist/chat/server.js +2628 -0
- package/dist/chat/server.js.map +1 -0
- package/dist/chat/sessions.cjs +380 -0
- package/dist/chat/sessions.cjs.map +1 -0
- package/dist/chat/sessions.d.cts +158 -0
- package/dist/chat/sessions.d.ts +158 -0
- package/dist/chat/sessions.js +376 -0
- package/dist/chat/sessions.js.map +1 -0
- package/dist/chat/sqlite.cjs +441 -0
- package/dist/chat/sqlite.cjs.map +1 -0
- package/dist/chat/sqlite.d.cts +128 -0
- package/dist/chat/sqlite.d.ts +128 -0
- package/dist/chat/sqlite.js +435 -0
- package/dist/chat/sqlite.js.map +1 -0
- package/dist/chat/state.cjs +190 -0
- package/dist/chat/state.cjs.map +1 -0
- package/dist/chat/state.d.cts +95 -0
- package/dist/chat/state.d.ts +95 -0
- package/dist/chat/state.js +180 -0
- package/dist/chat/state.js.map +1 -0
- package/dist/chat/storage.cjs +249 -0
- package/dist/chat/storage.cjs.map +1 -0
- package/dist/chat/storage.d.cts +197 -0
- package/dist/chat/storage.d.ts +197 -0
- package/dist/chat/storage.js +245 -0
- package/dist/chat/storage.js.map +1 -0
- package/dist/errors-C-so0M4t.d.cts +33 -0
- package/dist/errors-C-so0M4t.d.ts +33 -0
- package/dist/errors-CmVvczxZ.d.cts +28 -0
- package/dist/errors-CmVvczxZ.d.ts +28 -0
- package/dist/in-process-transport-C1JnJGVR.d.ts +228 -0
- package/dist/in-process-transport-C7DSqPyX.d.cts +228 -0
- package/dist/index.cjs +365 -59
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +322 -125
- package/dist/index.d.ts +322 -125
- package/dist/index.js +359 -60
- package/dist/index.js.map +1 -1
- package/dist/provider-types-PTSlRPNB.d.cts +39 -0
- package/dist/provider-types-PTSlRPNB.d.ts +39 -0
- package/dist/refresh-manager-B81PpYBr.d.cts +153 -0
- package/dist/refresh-manager-Dlv_iNZi.d.ts +153 -0
- package/dist/testing.cjs +383 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +132 -0
- package/dist/testing.d.ts +132 -0
- package/dist/testing.js +377 -0
- package/dist/testing.js.map +1 -0
- package/dist/token-store-CSUBgYwn.d.ts +48 -0
- package/dist/token-store-CuC4hB9Z.d.cts +48 -0
- package/dist/transport-Cdh3M0tS.d.cts +68 -0
- package/dist/transport-Ciap4PWK.d.ts +68 -0
- package/dist/types-4vbcmPTp.d.cts +143 -0
- package/dist/types-BxggH0Yh.d.ts +143 -0
- package/dist/types-DRgd_9R7.d.cts +363 -0
- package/dist/types-ajANVzf7.d.ts +363 -0
- package/package.json +178 -6
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { b as ChatId, g as ChatSession, c as ChatMessage, j as ChatSessionConfig } from '../types-ajANVzf7.js';
|
|
2
|
+
import { IStorageAdapter } from './storage.js';
|
|
3
|
+
export { StorageError } from './storage.js';
|
|
4
|
+
import '../agent-CW9XbmG_.js';
|
|
5
|
+
import 'zod';
|
|
6
|
+
import '../errors-C-so0M4t.js';
|
|
7
|
+
import '../types-BxggH0Yh.js';
|
|
8
|
+
import '../errors-CmVvczxZ.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @witqq/agent-sdk/chat/sessions
|
|
12
|
+
*
|
|
13
|
+
* Session store layer wrapping generic storage adapters.
|
|
14
|
+
* Provides session-specific operations: message management,
|
|
15
|
+
* paginated retrieval, search, and session lifecycle.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Options for creating a new session */
|
|
19
|
+
interface CreateSessionOptions<TCustom extends Record<string, unknown> = Record<string, unknown>> {
|
|
20
|
+
/** Session title (defaults to "Untitled") */
|
|
21
|
+
title?: string;
|
|
22
|
+
/** Session configuration (optional — runtime defaults used when omitted) */
|
|
23
|
+
config?: Partial<ChatSessionConfig>;
|
|
24
|
+
/** Initial tags */
|
|
25
|
+
tags?: string[];
|
|
26
|
+
/** Custom metadata */
|
|
27
|
+
custom?: TCustom;
|
|
28
|
+
}
|
|
29
|
+
/** Paginated result of messages */
|
|
30
|
+
interface PaginatedMessages {
|
|
31
|
+
/** Messages in this page */
|
|
32
|
+
messages: ChatMessage[];
|
|
33
|
+
/** Total number of messages in session */
|
|
34
|
+
total: number;
|
|
35
|
+
/** Whether there are more messages after this page */
|
|
36
|
+
hasMore: boolean;
|
|
37
|
+
}
|
|
38
|
+
/** Options for listing sessions */
|
|
39
|
+
interface SessionListOptions {
|
|
40
|
+
/** Filter predicate */
|
|
41
|
+
filter?: (session: ChatSession) => boolean;
|
|
42
|
+
/** Sort comparator */
|
|
43
|
+
sort?: (a: ChatSession, b: ChatSession) => number;
|
|
44
|
+
/** Maximum number of sessions to return */
|
|
45
|
+
limit?: number;
|
|
46
|
+
/** Number of sessions to skip */
|
|
47
|
+
offset?: number;
|
|
48
|
+
}
|
|
49
|
+
/** Search options for finding sessions */
|
|
50
|
+
interface SessionSearchOptions {
|
|
51
|
+
/** Text query to match against title and message content */
|
|
52
|
+
query: string;
|
|
53
|
+
/** Maximum results (default: 20) */
|
|
54
|
+
limit?: number;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Read-only session operations.
|
|
58
|
+
* Consumers needing read-only access (dashboards, analytics) implement only this.
|
|
59
|
+
*/
|
|
60
|
+
interface ISessionReader {
|
|
61
|
+
getSession(id: ChatId): Promise<ChatSession | null>;
|
|
62
|
+
listSessions(options?: SessionListOptions): Promise<ChatSession[]>;
|
|
63
|
+
loadMessages(sessionId: ChatId, options?: {
|
|
64
|
+
limit?: number;
|
|
65
|
+
offset?: number;
|
|
66
|
+
}): Promise<PaginatedMessages>;
|
|
67
|
+
searchSessions(options: SessionSearchOptions): Promise<ChatSession[]>;
|
|
68
|
+
count(): Promise<number>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Write/mutate session operations.
|
|
72
|
+
* Consumers needing full access implement both ISessionReader & ISessionWriter.
|
|
73
|
+
*/
|
|
74
|
+
interface ISessionWriter {
|
|
75
|
+
createSession(options: CreateSessionOptions): Promise<ChatSession>;
|
|
76
|
+
updateTitle(id: ChatId, title: string): Promise<void>;
|
|
77
|
+
updateConfig(id: ChatId, config: Partial<ChatSessionConfig>): Promise<void>;
|
|
78
|
+
deleteSession(id: ChatId): Promise<void>;
|
|
79
|
+
appendMessage(sessionId: ChatId, message: ChatMessage): Promise<void>;
|
|
80
|
+
saveMessages(sessionId: ChatId, messages: ChatMessage[]): Promise<void>;
|
|
81
|
+
clear(): Promise<void>;
|
|
82
|
+
/** Release any resources held by this store (optional). */
|
|
83
|
+
dispose?(): Promise<void>;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Full session store interface — union of reader and writer.
|
|
87
|
+
* Backward-compatible: all existing implementations continue to work.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```typescript
|
|
91
|
+
* const store = new InMemorySessionStore();
|
|
92
|
+
* const session = await store.createSession({ config: { model: "gpt-4", backend: "vercel-ai" } });
|
|
93
|
+
* await store.appendMessage(session.id, message);
|
|
94
|
+
* const page = await store.loadMessages(session.id, { limit: 20, offset: 0 });
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
interface IChatSessionStore extends ISessionReader, ISessionWriter {
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Base session store implementation backed by any `IStorageAdapter<ChatSession>`.
|
|
101
|
+
* Handles all session-specific logic; subclasses only need to provide the adapter.
|
|
102
|
+
*/
|
|
103
|
+
declare class BaseSessionStore implements IChatSessionStore {
|
|
104
|
+
protected readonly adapter: IStorageAdapter<ChatSession>;
|
|
105
|
+
constructor(adapter: IStorageAdapter<ChatSession>);
|
|
106
|
+
createSession(options: CreateSessionOptions): Promise<ChatSession>;
|
|
107
|
+
getSession(id: ChatId): Promise<ChatSession | null>;
|
|
108
|
+
listSessions(options?: SessionListOptions): Promise<ChatSession[]>;
|
|
109
|
+
updateTitle(id: ChatId, title: string): Promise<void>;
|
|
110
|
+
updateConfig(id: ChatId, config: Partial<ChatSessionConfig>): Promise<void>;
|
|
111
|
+
deleteSession(id: ChatId): Promise<void>;
|
|
112
|
+
appendMessage(sessionId: ChatId, message: ChatMessage): Promise<void>;
|
|
113
|
+
saveMessages(sessionId: ChatId, messages: ChatMessage[]): Promise<void>;
|
|
114
|
+
loadMessages(sessionId: ChatId, options?: {
|
|
115
|
+
limit?: number;
|
|
116
|
+
offset?: number;
|
|
117
|
+
}): Promise<PaginatedMessages>;
|
|
118
|
+
searchSessions(options: SessionSearchOptions): Promise<ChatSession[]>;
|
|
119
|
+
count(): Promise<number>;
|
|
120
|
+
clear(): Promise<void>;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* In-memory session store. Data is lost when the process exits.
|
|
124
|
+
* Uses `InMemoryStorage` internally.
|
|
125
|
+
*
|
|
126
|
+
* @example
|
|
127
|
+
* ```typescript
|
|
128
|
+
* const store = new InMemorySessionStore();
|
|
129
|
+
* const session = await store.createSession({
|
|
130
|
+
* config: { model: "gpt-4", backend: "vercel-ai" },
|
|
131
|
+
* });
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
declare class InMemorySessionStore extends BaseSessionStore {
|
|
135
|
+
constructor();
|
|
136
|
+
}
|
|
137
|
+
/** Configuration for FileSessionStore */
|
|
138
|
+
interface FileSessionStoreOptions {
|
|
139
|
+
/** Directory to store session JSON files */
|
|
140
|
+
directory: string;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* File-based session store. Each session is a JSON file on disk.
|
|
144
|
+
* Uses `FileStorage` internally.
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```typescript
|
|
148
|
+
* const store = new FileSessionStore({ directory: "./data/sessions" });
|
|
149
|
+
* const session = await store.createSession({
|
|
150
|
+
* config: { model: "claude-3", backend: "claude" },
|
|
151
|
+
* });
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
declare class FileSessionStore extends BaseSessionStore {
|
|
155
|
+
constructor(options: FileSessionStoreOptions);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export { type CreateSessionOptions, FileSessionStore, type FileSessionStoreOptions, type IChatSessionStore, type ISessionReader, type ISessionWriter, InMemorySessionStore, type PaginatedMessages, type SessionListOptions, type SessionSearchOptions };
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { existsSync, readdirSync, unlinkSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
|
|
4
|
+
// src/chat/types.ts
|
|
5
|
+
function createChatId() {
|
|
6
|
+
return crypto.randomUUID();
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// src/errors.ts
|
|
10
|
+
var AgentSDKError = class extends Error {
|
|
11
|
+
/** @internal Marker for cross-bundle identity checks */
|
|
12
|
+
_agentSDKError = true;
|
|
13
|
+
/** Machine-readable error code. Prefer values from the ErrorCode enum. */
|
|
14
|
+
code;
|
|
15
|
+
/** Whether this error is safe to retry */
|
|
16
|
+
retryable;
|
|
17
|
+
/** HTTP status code hint for error classification */
|
|
18
|
+
httpStatus;
|
|
19
|
+
constructor(message, options) {
|
|
20
|
+
super(message, options);
|
|
21
|
+
this.name = "AgentSDKError";
|
|
22
|
+
this.code = options?.code;
|
|
23
|
+
this.retryable = options?.retryable ?? false;
|
|
24
|
+
this.httpStatus = options?.httpStatus;
|
|
25
|
+
}
|
|
26
|
+
/** Check if an error is an AgentSDKError (works across bundled copies) */
|
|
27
|
+
static is(error) {
|
|
28
|
+
return error instanceof Error && "_agentSDKError" in error && error._agentSDKError === true;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// src/chat/storage.ts
|
|
33
|
+
var StorageError = class extends AgentSDKError {
|
|
34
|
+
/** Machine-readable error code from the unified ErrorCode enum */
|
|
35
|
+
code;
|
|
36
|
+
constructor(message, code) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "StorageError";
|
|
39
|
+
this.code = code;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var InMemoryStorage = class {
|
|
43
|
+
data = /* @__PURE__ */ new Map();
|
|
44
|
+
/** @inheritdoc */
|
|
45
|
+
async get(key) {
|
|
46
|
+
const item = this.data.get(key);
|
|
47
|
+
return item !== void 0 ? structuredClone(item) : null;
|
|
48
|
+
}
|
|
49
|
+
/** @inheritdoc */
|
|
50
|
+
async list(options) {
|
|
51
|
+
let items = Array.from(this.data.values()).map((item) => structuredClone(item));
|
|
52
|
+
if (options?.filter) {
|
|
53
|
+
items = items.filter(options.filter);
|
|
54
|
+
}
|
|
55
|
+
if (options?.sort) {
|
|
56
|
+
items.sort(options.sort);
|
|
57
|
+
}
|
|
58
|
+
if (options?.offset !== void 0) {
|
|
59
|
+
items = items.slice(options.offset);
|
|
60
|
+
}
|
|
61
|
+
if (options?.limit !== void 0) {
|
|
62
|
+
items = items.slice(0, options.limit);
|
|
63
|
+
}
|
|
64
|
+
return items;
|
|
65
|
+
}
|
|
66
|
+
/** @inheritdoc */
|
|
67
|
+
async create(key, item) {
|
|
68
|
+
if (this.data.has(key)) {
|
|
69
|
+
throw new StorageError(
|
|
70
|
+
`Item with key "${key}" already exists`,
|
|
71
|
+
"STORAGE_DUPLICATE_KEY" /* STORAGE_DUPLICATE_KEY */
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
this.data.set(key, structuredClone(item));
|
|
75
|
+
}
|
|
76
|
+
/** @inheritdoc */
|
|
77
|
+
async update(key, item) {
|
|
78
|
+
if (!this.data.has(key)) {
|
|
79
|
+
throw new StorageError(
|
|
80
|
+
`Item with key "${key}" not found`,
|
|
81
|
+
"STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
this.data.set(key, structuredClone(item));
|
|
85
|
+
}
|
|
86
|
+
/** @inheritdoc */
|
|
87
|
+
async delete(key) {
|
|
88
|
+
if (!this.data.has(key)) {
|
|
89
|
+
throw new StorageError(
|
|
90
|
+
`Item with key "${key}" not found`,
|
|
91
|
+
"STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
this.data.delete(key);
|
|
95
|
+
}
|
|
96
|
+
/** @inheritdoc */
|
|
97
|
+
async has(key) {
|
|
98
|
+
return this.data.has(key);
|
|
99
|
+
}
|
|
100
|
+
/** @inheritdoc */
|
|
101
|
+
async count() {
|
|
102
|
+
return this.data.size;
|
|
103
|
+
}
|
|
104
|
+
/** @inheritdoc */
|
|
105
|
+
async clear() {
|
|
106
|
+
this.data.clear();
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
var FileStorage = class {
|
|
110
|
+
directory;
|
|
111
|
+
extension;
|
|
112
|
+
constructor(options) {
|
|
113
|
+
this.directory = options.directory;
|
|
114
|
+
this.extension = options.extension ?? ".json";
|
|
115
|
+
this.ensureDirectory();
|
|
116
|
+
}
|
|
117
|
+
/** @inheritdoc */
|
|
118
|
+
async get(key) {
|
|
119
|
+
const filePath = this.keyToPath(key);
|
|
120
|
+
if (!existsSync(filePath)) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
return this.readFile(filePath);
|
|
124
|
+
}
|
|
125
|
+
/** @inheritdoc */
|
|
126
|
+
async list(options) {
|
|
127
|
+
this.ensureDirectory();
|
|
128
|
+
const files = readdirSync(this.directory).filter(
|
|
129
|
+
(f) => f.endsWith(this.extension)
|
|
130
|
+
);
|
|
131
|
+
let items = [];
|
|
132
|
+
for (const file of files) {
|
|
133
|
+
const item = this.readFile(join(this.directory, file));
|
|
134
|
+
items.push(item);
|
|
135
|
+
}
|
|
136
|
+
if (options?.filter) {
|
|
137
|
+
items = items.filter(options.filter);
|
|
138
|
+
}
|
|
139
|
+
if (options?.sort) {
|
|
140
|
+
items.sort(options.sort);
|
|
141
|
+
}
|
|
142
|
+
if (options?.offset !== void 0) {
|
|
143
|
+
items = items.slice(options.offset);
|
|
144
|
+
}
|
|
145
|
+
if (options?.limit !== void 0) {
|
|
146
|
+
items = items.slice(0, options.limit);
|
|
147
|
+
}
|
|
148
|
+
return items;
|
|
149
|
+
}
|
|
150
|
+
/** @inheritdoc */
|
|
151
|
+
async create(key, item) {
|
|
152
|
+
const filePath = this.keyToPath(key);
|
|
153
|
+
if (existsSync(filePath)) {
|
|
154
|
+
throw new StorageError(
|
|
155
|
+
`Item with key "${key}" already exists`,
|
|
156
|
+
"STORAGE_DUPLICATE_KEY" /* STORAGE_DUPLICATE_KEY */
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
this.writeFile(filePath, item);
|
|
160
|
+
}
|
|
161
|
+
/** @inheritdoc */
|
|
162
|
+
async update(key, item) {
|
|
163
|
+
const filePath = this.keyToPath(key);
|
|
164
|
+
if (!existsSync(filePath)) {
|
|
165
|
+
throw new StorageError(
|
|
166
|
+
`Item with key "${key}" not found`,
|
|
167
|
+
"STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
this.writeFile(filePath, item);
|
|
171
|
+
}
|
|
172
|
+
/** @inheritdoc */
|
|
173
|
+
async delete(key) {
|
|
174
|
+
const filePath = this.keyToPath(key);
|
|
175
|
+
if (!existsSync(filePath)) {
|
|
176
|
+
throw new StorageError(
|
|
177
|
+
`Item with key "${key}" not found`,
|
|
178
|
+
"STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
unlinkSync(filePath);
|
|
182
|
+
}
|
|
183
|
+
/** @inheritdoc */
|
|
184
|
+
async has(key) {
|
|
185
|
+
return existsSync(this.keyToPath(key));
|
|
186
|
+
}
|
|
187
|
+
/** @inheritdoc */
|
|
188
|
+
async count() {
|
|
189
|
+
this.ensureDirectory();
|
|
190
|
+
return readdirSync(this.directory).filter(
|
|
191
|
+
(f) => f.endsWith(this.extension)
|
|
192
|
+
).length;
|
|
193
|
+
}
|
|
194
|
+
/** @inheritdoc */
|
|
195
|
+
async clear() {
|
|
196
|
+
this.ensureDirectory();
|
|
197
|
+
const files = readdirSync(this.directory).filter(
|
|
198
|
+
(f) => f.endsWith(this.extension)
|
|
199
|
+
);
|
|
200
|
+
for (const file of files) {
|
|
201
|
+
unlinkSync(join(this.directory, file));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
keyToPath(key) {
|
|
205
|
+
const safeKey = key.replace(
|
|
206
|
+
/[^a-zA-Z0-9_-]/g,
|
|
207
|
+
(c) => "%" + c.charCodeAt(0).toString(16).padStart(2, "0")
|
|
208
|
+
);
|
|
209
|
+
return join(this.directory, `${safeKey}${this.extension}`);
|
|
210
|
+
}
|
|
211
|
+
ensureDirectory() {
|
|
212
|
+
if (!existsSync(this.directory)) {
|
|
213
|
+
mkdirSync(this.directory, { recursive: true });
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
readFile(filePath) {
|
|
217
|
+
try {
|
|
218
|
+
const content = readFileSync(filePath, "utf-8");
|
|
219
|
+
return JSON.parse(content);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
if (error instanceof SyntaxError) {
|
|
222
|
+
throw new StorageError(
|
|
223
|
+
`Failed to parse file: ${filePath}`,
|
|
224
|
+
"STORAGE_SERIALIZATION_ERROR" /* STORAGE_SERIALIZATION_ERROR */
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
throw new StorageError(
|
|
228
|
+
`Failed to read file: ${filePath}`,
|
|
229
|
+
"STORAGE_IO_ERROR" /* STORAGE_IO_ERROR */
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
writeFile(filePath, item) {
|
|
234
|
+
try {
|
|
235
|
+
const content = JSON.stringify(item, null, 2);
|
|
236
|
+
writeFileSync(filePath, content, "utf-8");
|
|
237
|
+
} catch {
|
|
238
|
+
throw new StorageError(
|
|
239
|
+
`Failed to write file: ${filePath}`,
|
|
240
|
+
"STORAGE_IO_ERROR" /* STORAGE_IO_ERROR */
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
// src/chat/sessions.ts
|
|
247
|
+
var BaseSessionStore = class {
|
|
248
|
+
constructor(adapter) {
|
|
249
|
+
this.adapter = adapter;
|
|
250
|
+
}
|
|
251
|
+
async createSession(options) {
|
|
252
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
253
|
+
const id = createChatId();
|
|
254
|
+
const session = {
|
|
255
|
+
id,
|
|
256
|
+
title: options.title ?? "Untitled",
|
|
257
|
+
messages: [],
|
|
258
|
+
config: {
|
|
259
|
+
model: options.config?.model ?? "",
|
|
260
|
+
backend: options.config?.backend ?? "",
|
|
261
|
+
...options.config
|
|
262
|
+
},
|
|
263
|
+
metadata: {
|
|
264
|
+
messageCount: 0,
|
|
265
|
+
totalTokens: 0,
|
|
266
|
+
tags: options.tags ? [...options.tags] : void 0,
|
|
267
|
+
custom: options.custom ? { ...options.custom } : void 0
|
|
268
|
+
},
|
|
269
|
+
status: "active",
|
|
270
|
+
createdAt: now,
|
|
271
|
+
updatedAt: now
|
|
272
|
+
};
|
|
273
|
+
await this.adapter.create(id, session);
|
|
274
|
+
return structuredClone(session);
|
|
275
|
+
}
|
|
276
|
+
async getSession(id) {
|
|
277
|
+
return this.adapter.get(id);
|
|
278
|
+
}
|
|
279
|
+
async listSessions(options) {
|
|
280
|
+
return this.adapter.list(options);
|
|
281
|
+
}
|
|
282
|
+
async updateTitle(id, title) {
|
|
283
|
+
const session = await this.adapter.get(id);
|
|
284
|
+
if (!session) {
|
|
285
|
+
throw new StorageError(`Session "${id}" not found`, "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */);
|
|
286
|
+
}
|
|
287
|
+
session.title = title;
|
|
288
|
+
session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
289
|
+
await this.adapter.update(id, session);
|
|
290
|
+
}
|
|
291
|
+
async updateConfig(id, config) {
|
|
292
|
+
const session = await this.adapter.get(id);
|
|
293
|
+
if (!session) {
|
|
294
|
+
throw new StorageError(`Session "${id}" not found`, "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */);
|
|
295
|
+
}
|
|
296
|
+
session.config = { ...session.config, ...config };
|
|
297
|
+
session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
298
|
+
await this.adapter.update(id, session);
|
|
299
|
+
}
|
|
300
|
+
async deleteSession(id) {
|
|
301
|
+
await this.adapter.delete(id);
|
|
302
|
+
}
|
|
303
|
+
async appendMessage(sessionId, message) {
|
|
304
|
+
const session = await this.adapter.get(sessionId);
|
|
305
|
+
if (!session) {
|
|
306
|
+
throw new StorageError(`Session "${sessionId}" not found`, "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */);
|
|
307
|
+
}
|
|
308
|
+
session.messages.push(structuredClone(message));
|
|
309
|
+
session.metadata.messageCount = session.messages.length;
|
|
310
|
+
session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
311
|
+
await this.adapter.update(sessionId, session);
|
|
312
|
+
}
|
|
313
|
+
async saveMessages(sessionId, messages) {
|
|
314
|
+
if (messages.length === 0) return;
|
|
315
|
+
const session = await this.adapter.get(sessionId);
|
|
316
|
+
if (!session) {
|
|
317
|
+
throw new StorageError(`Session "${sessionId}" not found`, "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */);
|
|
318
|
+
}
|
|
319
|
+
for (const msg of messages) {
|
|
320
|
+
session.messages.push(structuredClone(msg));
|
|
321
|
+
}
|
|
322
|
+
session.metadata.messageCount = session.messages.length;
|
|
323
|
+
session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
324
|
+
await this.adapter.update(sessionId, session);
|
|
325
|
+
}
|
|
326
|
+
async loadMessages(sessionId, options) {
|
|
327
|
+
const session = await this.adapter.get(sessionId);
|
|
328
|
+
if (!session) {
|
|
329
|
+
throw new StorageError(`Session "${sessionId}" not found`, "STORAGE_NOT_FOUND" /* STORAGE_NOT_FOUND */);
|
|
330
|
+
}
|
|
331
|
+
const total = session.messages.length;
|
|
332
|
+
const offset = options?.offset ?? 0;
|
|
333
|
+
const limit = options?.limit ?? total;
|
|
334
|
+
const messages = session.messages.slice(offset, offset + limit);
|
|
335
|
+
return {
|
|
336
|
+
messages: structuredClone(messages),
|
|
337
|
+
total,
|
|
338
|
+
hasMore: offset + limit < total
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
async searchSessions(options) {
|
|
342
|
+
const query = options.query.toLowerCase();
|
|
343
|
+
const limit = options.limit ?? 20;
|
|
344
|
+
return this.adapter.list({
|
|
345
|
+
filter: (session) => {
|
|
346
|
+
if (session.title?.toLowerCase().includes(query)) return true;
|
|
347
|
+
return session.messages.some((msg) => {
|
|
348
|
+
return msg.parts.some(
|
|
349
|
+
(part) => part.type === "text" && part.text.toLowerCase().includes(query)
|
|
350
|
+
);
|
|
351
|
+
});
|
|
352
|
+
},
|
|
353
|
+
limit
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
async count() {
|
|
357
|
+
return this.adapter.count();
|
|
358
|
+
}
|
|
359
|
+
async clear() {
|
|
360
|
+
return this.adapter.clear();
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
var InMemorySessionStore = class extends BaseSessionStore {
|
|
364
|
+
constructor() {
|
|
365
|
+
super(new InMemoryStorage());
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
var FileSessionStore = class extends BaseSessionStore {
|
|
369
|
+
constructor(options) {
|
|
370
|
+
super(new FileStorage({ directory: options.directory }));
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
export { FileSessionStore, InMemorySessionStore, StorageError };
|
|
375
|
+
//# sourceMappingURL=sessions.js.map
|
|
376
|
+
//# sourceMappingURL=sessions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/chat/types.ts","../../src/errors.ts","../../src/chat/storage.ts","../../src/chat/sessions.ts"],"names":[],"mappings":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;AAsBO,IAAM,gBAAA,GAAN,cAA+B,gBAAA,CAAiB;AAAA,EACrD,YAAY,OAAA,EAAkC;AAC5C,IAAA,KAAA,CAAM,IAAI,WAAA,CAAyB,EAAE,WAAW,OAAA,CAAQ,SAAA,EAAW,CAAC,CAAA;AAAA,EACtE;AACF","file":"sessions.js","sourcesContent":["/**\n * @witqq/agent-sdk — Chat domain types\n *\n * All type definitions and interfaces for the chat layer.\n * Pure types + ChatId generation (tightly coupled to branded type).\n */\n\nimport type { UsageData, ToolDefinition, ErrorCode } from \"../types.js\";\nimport type { AuthToken } from \"../auth/types.js\";\n\n// ─── Unique ID ─────────────────────────────────────────────────\n\n/** Branded type for unique identifiers */\nexport type ChatId = string & { readonly __brand: \"ChatId\" };\n\n/**\n * Generate a new unique ChatId (crypto.randomUUID-based)\n * @returns Branded ChatId string\n */\nexport function createChatId(): ChatId {\n return crypto.randomUUID() as ChatId;\n}\n\n/** UUID v4 pattern for ChatId validation */\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/**\n * Cast a string to ChatId with UUID format validation.\n * Use this instead of manual `as ChatId` type assertions.\n *\n * @param value - String to validate and cast\n * @returns Branded ChatId\n * @throws {TypeError} If value is not a valid UUID v4 format\n */\nexport function toChatId(value: string): ChatId {\n if (!UUID_RE.test(value)) {\n throw new TypeError(`Invalid ChatId: \"${value}\" is not a valid UUID`);\n }\n return value as ChatId;\n}\n\n/**\n * Accepts either a plain string or branded ChatId for API convenience.\n * Use this in public API signatures so consumers don't need `as ChatId` casts.\n */\nexport type ChatIdLike = string | ChatId;\n\n// ─── Status Types ──────────────────────────────────────────────\n\n/** Lifecycle status of a message part (text, reasoning, etc.) */\nexport type PartStatus = \"pending\" | \"streaming\" | \"complete\" | \"error\";\n/** Lifecycle status of a tool call within a message */\nexport type ToolCallStatus = \"pending\" | \"running\" | \"requires_approval\" | \"complete\" | \"error\" | \"denied\";\n/** Lifecycle status of an entire message */\nexport type MessageStatus = \"pending\" | \"streaming\" | \"complete\" | \"error\" | \"cancelled\";\n/** Lifecycle status of a chat session */\nexport type SessionStatus = \"active\";\n/** Lifecycle status of the chat runtime */\nexport type RuntimeStatus = \"idle\" | \"streaming\" | \"error\" | \"disposed\";\n\n// ─── Message Parts (union) ─────────────────────────────────────\n\n/** Plain text content part */\nexport interface TextPart { type: \"text\"; text: string; status: PartStatus; }\n/** Model reasoning/thinking content part */\nexport interface ReasoningPart { type: \"reasoning\"; text: string; status: PartStatus; }\n/** Tool invocation part with call ID, arguments, optional result */\nexport interface ToolCallPart { type: \"tool_call\"; toolCallId: string; name: string; args: unknown; result?: unknown; status: ToolCallStatus; error?: string; }\n/** Source reference part (URL citation) */\nexport interface SourcePart { type: \"source\"; url: string; title?: string; status: PartStatus; }\n/** File attachment part (base64-encoded data) */\nexport interface FilePart { type: \"file\"; name: string; mimeType: string; data: string; status: PartStatus; }\n/** Union of all message part types */\nexport type MessagePart = TextPart | ReasoningPart | ToolCallPart | SourcePart | FilePart;\n\n// ─── Chat Message ──────────────────────────────────────────────\n\n/** Role of message author */\nexport type ChatRole = \"user\" | \"assistant\" | \"system\";\n\n/** Metadata attached to messages — useful preset for the TMetadata generic */\nexport interface ChatMessageMetadata {\n model?: string;\n backend?: string;\n usage?: UsageData;\n isSummary?: boolean;\n estimatedTokens?: number;\n custom?: Record<string, unknown>;\n}\n\n/** Message status */\nexport type ChatMessageStatus = MessageStatus;\n\n/** A single chat message — the fundamental unit of conversation */\nexport interface ChatMessage<TMetadata = unknown> {\n id: ChatId;\n role: ChatRole;\n parts: MessagePart[];\n metadata?: TMetadata;\n createdAt: string;\n updatedAt?: string;\n status: MessageStatus;\n}\n\n// ─── Supporting Types ──────────────────────────────────────────\n\n// ─── Chat Session ──────────────────────────────────────────────\n\n/** Session configuration snapshot */\nexport interface ChatSessionConfig {\n model: string;\n backend: string;\n systemPrompt?: string;\n temperature?: number;\n maxTokens?: number;\n}\n\n/**\n * Session metadata tracking usage statistics and custom extensions.\n *\n * Updated automatically by session stores on each `addMessage()` call.\n * The generic `TCustom` parameter allows type-safe application-specific\n * metadata via the `custom` field.\n *\n * @typeParam TCustom - Shape of the `custom` field (defaults to `Record<string, unknown>`)\n */\nexport interface ChatSessionMetadata<TCustom extends Record<string, unknown> = Record<string, unknown>> {\n /** Number of messages in the session (updated by session store) */\n messageCount: number;\n /** Total token count across all messages in the session */\n totalTokens: number;\n /** Optional tags for session categorization and filtering */\n tags?: string[];\n /** Application-specific metadata — typed via the TCustom generic parameter */\n custom?: TCustom;\n}\n\n/** Chat session — a conversation with ordered messages (pure serializable data) */\nexport interface ChatSession<TCustom extends Record<string, unknown> = Record<string, unknown>> {\n id: ChatId;\n title?: string;\n messages: ChatMessage[];\n config: ChatSessionConfig;\n metadata: ChatSessionMetadata<TCustom>;\n status: SessionStatus;\n createdAt: string;\n updatedAt: string;\n backendSessionId?: string;\n}\n\n/**\n * Reactive wrapper around ChatSession — provides subscribe/getSnapshot for\n * React useSyncExternalStore integration and lastMessage convenience getter.\n * Session stores may optionally return ObservableSession instances.\n */\nexport interface ObservableSession<TCustom extends Record<string, unknown> = Record<string, unknown>>\n extends ChatSession<TCustom> {\n /** Subscribe to session changes (for React useSyncExternalStore) */\n subscribe(callback: () => void): () => void;\n /** Get immutable snapshot of session state (for React useSyncExternalStore) */\n getSnapshot(): ChatSession<TCustom>;\n /** Last message in the session */\n readonly lastMessage: ChatMessage | undefined;\n}\n\n/** Lightweight session info for listing (without full message array) */\nexport interface SessionInfo {\n id: ChatId;\n title?: string;\n status: SessionStatus;\n messageCount: number;\n lastMessage?: ChatMessage;\n createdAt: string;\n updatedAt: string;\n}\n\n// ─── Chat Events ───────────────────────────────────────────────\n\n/** Events emitted during chat operation */\nexport type ChatEvent =\n | { type: \"message:start\"; messageId: ChatId; role: ChatRole }\n | { type: \"message:delta\"; messageId: ChatId; text: string }\n | { type: \"message:complete\"; messageId: ChatId; message: ChatMessage }\n | {\n type: \"tool:start\";\n messageId: ChatId;\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n }\n | {\n type: \"tool:complete\";\n messageId: ChatId;\n toolCallId: string;\n toolName: string;\n result: unknown;\n isError?: boolean;\n }\n | { type: \"thinking:start\"; messageId: ChatId }\n | { type: \"thinking:delta\"; messageId: ChatId; text: string }\n | { type: \"thinking:end\"; messageId: ChatId }\n | {\n type: \"permission:request\";\n messageId: ChatId;\n toolName: string;\n toolArgs: Record<string, unknown>;\n }\n | {\n type: \"permission:response\";\n messageId: ChatId;\n toolName: string;\n allowed: boolean;\n }\n | {\n type: \"usage\";\n promptTokens: number;\n completionTokens: number;\n model?: string;\n }\n | { type: \"session:created\"; sessionId: ChatId }\n | { type: \"session:updated\"; sessionId: ChatId }\n | {\n type: \"error\";\n error: string;\n recoverable: boolean;\n code?: ErrorCode;\n messageId?: ChatId;\n }\n | { type: \"typing:start\" }\n | { type: \"typing:end\" }\n | { type: \"heartbeat\" }\n | { type: \"done\"; finalOutput?: string };\n\n/** All possible ChatEvent type strings */\nexport type ChatEventType = ChatEvent[\"type\"];\n\n// ─── Chat Middleware ───────────────────────────────────────────\n\n/** Context passed to ChatMiddleware hooks */\nexport interface ChatMiddlewareContext {\n sessionId: ChatId;\n signal: AbortSignal;\n}\n\n/** Runtime-level middleware for the send/receive lifecycle.\n * Different from EventMiddleware which operates at the event bus level. */\nexport interface ChatMiddleware {\n /** Transform message before sending to backend. Return null to reject the send. */\n onBeforeSend?(message: ChatMessage, context: ChatMiddlewareContext): ChatMessage | null | Promise<ChatMessage | null>;\n /** Transform/intercept stream events */\n onEvent?(event: ChatEvent, context: ChatMiddlewareContext): ChatEvent | null | Promise<ChatEvent | null>;\n /** Transform completed message after receiving from backend */\n onAfterReceive?(message: ChatMessage, context: ChatMiddlewareContext): ChatMessage | Promise<ChatMessage>;\n /** Intercept errors — return null to suppress, return error to propagate */\n onError?(error: Error, context: ChatMiddlewareContext): Error | null | Promise<Error | null>;\n}\n\n// ─── Chat Provider Abstraction ─────────────────────────────────\n\n/** Options for sending a message to a provider */\nexport interface SendMessageOptions {\n signal?: AbortSignal;\n /** Model to use for this request. Required for server-side runtime.send(). */\n model?: string;\n /** Per-call system prompt override (forwarded to the backend agent) */\n systemPrompt?: string;\n context?: Record<string, unknown>;\n /** Additional tools to include in this request */\n tools?: ToolDefinition[];\n}\n\n/** Options for runtime.send() — requires backend routing info */\nexport interface RuntimeSendOptions {\n /** Backend to route this request to (key in backends map) */\n backend: string;\n /** Authentication credentials for the backend factory */\n credentials: AuthToken;\n /** Model to use for this request */\n model: string;\n /** Per-call system prompt override (forwarded to the backend agent) */\n systemPrompt?: string;\n /** Abort signal */\n signal?: AbortSignal;\n /** Request-scoped context */\n context?: Record<string, unknown>;\n /** Additional tools */\n tools?: ToolDefinition[];\n}\n\n/**\n * @deprecated IChatProvider has been inlined into IChatBackend.\n * Import IChatBackend from \"@witqq/agent-sdk/chat/backends\" instead.\n * Kept as type alias for backward compatibility.\n */\nexport type IChatProvider = import(\"./backends/types.js\").IChatBackend;\n\n// ─── Factory Functions ─────────────────────────────────────────\n\n/**\n * Create a simple text ChatMessage.\n *\n * @param text - Message text content\n * @param role - Message role (default: \"user\")\n * @returns A complete ChatMessage with a single TextPart\n */\nexport function createTextMessage(text: string, role: ChatRole = \"user\"): ChatMessage {\n return {\n id: createChatId(),\n role,\n parts: [{ type: \"text\", text, status: \"complete\" }],\n createdAt: new Date().toISOString(),\n status: \"complete\",\n };\n}\n\n/** Type guard: checks if a session has reactive API (subscribe/getSnapshot) */\nexport function isObservableSession<TCustom extends Record<string, unknown> = Record<string, unknown>>(\n session: ChatSession<TCustom>,\n): session is ObservableSession<TCustom> {\n return \"subscribe\" in session && typeof (session as ObservableSession<TCustom>).subscribe === \"function\"\n && \"getSnapshot\" in session && typeof (session as ObservableSession<TCustom>).getSnapshot === \"function\";\n}\n","import { ErrorCode } from \"./types/errors.js\";\n\n/** Options for constructing an AgentSDKError */\nexport interface AgentSDKErrorOptions extends ErrorOptions {\n /** Machine-readable error code */\n code?: string;\n /** Whether this error is retryable (default: false) */\n retryable?: boolean;\n /** HTTP status code hint (e.g. 401, 429, 500) */\n httpStatus?: number;\n}\n\n/** Base error class for agent-sdk.\n *\n * Use `AgentSDKError.is(err)` for reliable cross-module `instanceof` checks\n * (works across separately bundled entry points where `instanceof` may fail). */\nexport class AgentSDKError extends Error {\n /** @internal Marker for cross-bundle identity checks */\n readonly _agentSDKError = true as const;\n /** Machine-readable error code. Prefer values from the ErrorCode enum. */\n readonly code?: string;\n /** Whether this error is safe to retry */\n readonly retryable: boolean;\n /** HTTP status code hint for error classification */\n readonly httpStatus?: number;\n\n constructor(message: string, options?: AgentSDKErrorOptions) {\n super(message, options);\n this.name = \"AgentSDKError\";\n this.code = options?.code;\n this.retryable = options?.retryable ?? false;\n this.httpStatus = options?.httpStatus;\n }\n\n /** Check if an error is an AgentSDKError (works across bundled copies) */\n static is(error: unknown): error is AgentSDKError {\n return (\n error instanceof Error &&\n \"_agentSDKError\" in error &&\n (error as AgentSDKError)._agentSDKError === true\n );\n }\n}\n\n/** Thrown when agent.run() is called while already running (M8 re-entrancy guard) */\nexport class ReentrancyError extends AgentSDKError {\n constructor() {\n super(\"Agent is already running. Await the current run before starting another.\", {\n code: ErrorCode.REENTRANCY,\n });\n this.name = \"ReentrancyError\";\n }\n}\n\n/** Thrown when an operation is attempted on a disposed agent/service */\nexport class DisposedError extends AgentSDKError {\n constructor(entity: string) {\n super(`${entity} has been disposed and cannot be used.`, {\n code: ErrorCode.DISPOSED,\n });\n this.name = \"DisposedError\";\n }\n}\n\n/** Thrown when a backend is not found in the registry */\nexport class BackendNotFoundError extends AgentSDKError {\n constructor(backend: string) {\n super(\n `Unknown backend: \"${backend}\". ` +\n `Built-in: copilot, claude, vercel-ai. ` +\n `Custom: use registerBackend() first.`,\n { code: ErrorCode.BACKEND_NOT_INSTALLED },\n );\n this.name = \"BackendNotFoundError\";\n }\n}\n\n/** Thrown when a backend is already registered */\nexport class BackendAlreadyRegisteredError extends AgentSDKError {\n constructor(backend: string) {\n super(`Backend \"${backend}\" is already registered. Use a different name or unregister first.`);\n this.name = \"BackendAlreadyRegisteredError\";\n }\n}\n\n/** Thrown when subprocess management fails */\nexport class SubprocessError extends AgentSDKError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, { ...options, code: ErrorCode.DEPENDENCY_MISSING });\n this.name = \"SubprocessError\";\n }\n}\n\n/** Thrown when a required peer dependency is not installed */\nexport class DependencyError extends AgentSDKError {\n public readonly packageName: string;\n\n constructor(packageName: string) {\n super(`${packageName} is not installed. Install it: npm install ${packageName}`, {\n code: ErrorCode.DEPENDENCY_MISSING,\n });\n this.name = \"DependencyError\";\n this.packageName = packageName;\n }\n}\n\n/** Thrown when an agent run is aborted */\nexport class AbortError extends AgentSDKError {\n constructor() {\n super(\"Agent run was aborted.\", { code: ErrorCode.ABORTED });\n this.name = \"AbortError\";\n }\n}\n\n/** Thrown when a tool execution fails */\nexport class ToolExecutionError extends AgentSDKError {\n public readonly toolName: string;\n\n constructor(toolName: string, message: string, options?: ErrorOptions) {\n super(`Tool \"${toolName}\" failed: ${message}`, { ...options, code: ErrorCode.TOOL_EXECUTION });\n this.name = \"ToolExecutionError\";\n this.toolName = toolName;\n }\n}\n\n/** Thrown when a stream has no activity within the configured timeout */\nexport class ActivityTimeoutError extends AgentSDKError {\n constructor(timeoutMs: number) {\n super(`Stream activity timeout: no event received within ${timeoutMs}ms.`, {\n code: ErrorCode.TIMEOUT,\n retryable: true,\n });\n this.name = \"ActivityTimeoutError\";\n }\n}\n\n/** Thrown when structured output parsing fails */\nexport class StructuredOutputError extends AgentSDKError {\n constructor(message: string, options?: ErrorOptions) {\n super(`Structured output error: ${message}`, { ...options, code: ErrorCode.INVALID_RESPONSE });\n this.name = \"StructuredOutputError\";\n }\n}\n","/**\n * @witqq/agent-sdk/chat/storage\n *\n * Generic storage adapter layer with pluggable backends.\n * Provides CRUD operations for any data type via `IStorageAdapter<T>`.\n * Implementations: `InMemoryStorage` (Map-based) and `FileStorage` (JSON files).\n */\n\nimport { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { AgentSDKError } from \"../errors.js\";\nimport { ErrorCode } from \"../types/errors.js\";\n\n// ─── Storage Errors ────────────────────────────────────────────\n\n/**\n * Error thrown by storage operations.\n *\n * @example\n * ```typescript\n * try {\n * await store.get(\"missing-id\");\n * } catch (e) {\n * if (e instanceof StorageError && e.code === ErrorCode.STORAGE_NOT_FOUND) {\n * // handle missing item\n * }\n * }\n * ```\n */\nexport class StorageError extends AgentSDKError {\n /** Machine-readable error code from the unified ErrorCode enum */\n readonly code: StorageErrorCode;\n\n constructor(message: string, code: StorageErrorCode) {\n super(message);\n this.name = \"StorageError\";\n this.code = code;\n }\n}\n\n/** Storage-specific subset of ErrorCode */\nexport type StorageErrorCode =\n | ErrorCode.STORAGE_NOT_FOUND\n | ErrorCode.STORAGE_DUPLICATE_KEY\n | ErrorCode.STORAGE_IO_ERROR\n | ErrorCode.STORAGE_SERIALIZATION_ERROR;\n\n// ─── Storage Adapter Interface ─────────────────────────────────\n\n/**\n * Options for listing stored items.\n *\n * @typeParam T - The type of stored items\n */\nexport interface ListOptions<T> {\n /** Filter predicate — return `true` to include the item */\n filter?: (item: T) => boolean;\n /** Sort comparator — standard Array.sort semantics */\n sort?: (a: T, b: T) => number;\n /** Maximum number of items to return */\n limit?: number;\n /** Number of items to skip (for pagination) */\n offset?: number;\n}\n\n/**\n * Generic storage adapter for CRUD operations on any data type.\n * Items are identified by a string key.\n *\n * @typeParam T - The type of stored items\n *\n * @example\n * ```typescript\n * const store: IStorageAdapter<{ name: string }> = new InMemoryStorage();\n * await store.create(\"key1\", { name: \"Alice\" });\n * const item = await store.get(\"key1\"); // { name: \"Alice\" }\n * ```\n */\nexport interface IStorageAdapter<T> {\n /**\n * Retrieve an item by key.\n * @param key - Unique identifier\n * @returns The item, or `null` if not found\n */\n get(key: string): Promise<T | null>;\n\n /**\n * List items with optional filtering, sorting, and pagination.\n * @param options - Filter, sort, limit, offset options\n * @returns Array of matching items\n */\n list(options?: ListOptions<T>): Promise<T[]>;\n\n /**\n * Create a new item. Throws `StorageError` with code `DUPLICATE_KEY` if key exists.\n * @param key - Unique identifier\n * @param item - Data to store\n */\n create(key: string, item: T): Promise<void>;\n\n /**\n * Update an existing item. Throws `StorageError` with code `NOT_FOUND` if key missing.\n * @param key - Unique identifier\n * @param item - Updated data\n */\n update(key: string, item: T): Promise<void>;\n\n /**\n * Delete an item by key. Throws `StorageError` with code `NOT_FOUND` if key missing.\n * @param key - Unique identifier\n */\n delete(key: string): Promise<void>;\n\n /**\n * Check whether a key exists.\n * @param key - Unique identifier\n * @returns `true` if key exists\n */\n has(key: string): Promise<boolean>;\n\n /**\n * Return the number of stored items.\n * @returns Count of items\n */\n count(): Promise<number>;\n\n /**\n * Remove all items from storage.\n */\n clear(): Promise<void>;\n\n /**\n * Release any resources held by this adapter (DB connections, file handles).\n * Optional — adapters that don't hold resources need not implement this.\n */\n dispose?(): Promise<void>;\n}\n\n// ─── InMemoryStorage ───────────────────────────────────────────\n\n/**\n * In-memory storage adapter backed by a `Map`.\n * Suitable for development, testing, and short-lived processes.\n * Data is lost when the process exits.\n *\n * @typeParam T - The type of stored items\n *\n * @example\n * ```typescript\n * const store = new InMemoryStorage<{ name: string }>();\n * await store.create(\"k1\", { name: \"Alice\" });\n * await store.create(\"k2\", { name: \"Bob\" });\n * const items = await store.list({ filter: i => i.name.startsWith(\"A\") });\n * // [{ name: \"Alice\" }]\n * ```\n */\nexport class InMemoryStorage<T> implements IStorageAdapter<T> {\n private readonly data = new Map<string, T>();\n\n /** @inheritdoc */\n async get(key: string): Promise<T | null> {\n const item = this.data.get(key);\n return item !== undefined ? structuredClone(item) : null;\n }\n\n /** @inheritdoc */\n async list(options?: ListOptions<T>): Promise<T[]> {\n let items = Array.from(this.data.values()).map((item) => structuredClone(item));\n\n if (options?.filter) {\n items = items.filter(options.filter);\n }\n if (options?.sort) {\n items.sort(options.sort);\n }\n if (options?.offset !== undefined) {\n items = items.slice(options.offset);\n }\n if (options?.limit !== undefined) {\n items = items.slice(0, options.limit);\n }\n\n return items;\n }\n\n /** @inheritdoc */\n async create(key: string, item: T): Promise<void> {\n if (this.data.has(key)) {\n throw new StorageError(\n `Item with key \"${key}\" already exists`,\n ErrorCode.STORAGE_DUPLICATE_KEY,\n );\n }\n this.data.set(key, structuredClone(item));\n }\n\n /** @inheritdoc */\n async update(key: string, item: T): Promise<void> {\n if (!this.data.has(key)) {\n throw new StorageError(\n `Item with key \"${key}\" not found`,\n ErrorCode.STORAGE_NOT_FOUND,\n );\n }\n this.data.set(key, structuredClone(item));\n }\n\n /** @inheritdoc */\n async delete(key: string): Promise<void> {\n if (!this.data.has(key)) {\n throw new StorageError(\n `Item with key \"${key}\" not found`,\n ErrorCode.STORAGE_NOT_FOUND,\n );\n }\n this.data.delete(key);\n }\n\n /** @inheritdoc */\n async has(key: string): Promise<boolean> {\n return this.data.has(key);\n }\n\n /** @inheritdoc */\n async count(): Promise<number> {\n return this.data.size;\n }\n\n /** @inheritdoc */\n async clear(): Promise<void> {\n this.data.clear();\n }\n}\n\n// ─── FileStorage ───────────────────────────────────────────────\n\n/**\n * Options for configuring `FileStorage`.\n */\nexport interface FileStorageOptions {\n /** Directory path where JSON files are stored */\n directory: string;\n /** File extension (default: `.json`) */\n extension?: string;\n}\n\n/**\n * File-based storage adapter that persists each item as a JSON file.\n * Suitable for local applications, CLI tools, and development.\n * Creates the storage directory if it doesn't exist.\n *\n * @typeParam T - The type of stored items (must be JSON-serializable)\n *\n * @example\n * ```typescript\n * const store = new FileStorage<ChatSession>({\n * directory: \"./data/sessions\",\n * });\n * await store.create(\"session-1\", mySession);\n * ```\n */\nexport class FileStorage<T> implements IStorageAdapter<T> {\n private readonly directory: string;\n private readonly extension: string;\n\n constructor(options: FileStorageOptions) {\n this.directory = options.directory;\n this.extension = options.extension ?? \".json\";\n this.ensureDirectory();\n }\n\n /** @inheritdoc */\n async get(key: string): Promise<T | null> {\n const filePath = this.keyToPath(key);\n if (!existsSync(filePath)) {\n return null;\n }\n return this.readFile(filePath);\n }\n\n /** @inheritdoc */\n async list(options?: ListOptions<T>): Promise<T[]> {\n this.ensureDirectory();\n const files = readdirSync(this.directory).filter((f) =>\n f.endsWith(this.extension),\n );\n\n let items: T[] = [];\n for (const file of files) {\n const item = this.readFile(join(this.directory, file));\n items.push(item);\n }\n\n if (options?.filter) {\n items = items.filter(options.filter);\n }\n if (options?.sort) {\n items.sort(options.sort);\n }\n if (options?.offset !== undefined) {\n items = items.slice(options.offset);\n }\n if (options?.limit !== undefined) {\n items = items.slice(0, options.limit);\n }\n\n return items;\n }\n\n /** @inheritdoc */\n async create(key: string, item: T): Promise<void> {\n const filePath = this.keyToPath(key);\n if (existsSync(filePath)) {\n throw new StorageError(\n `Item with key \"${key}\" already exists`,\n ErrorCode.STORAGE_DUPLICATE_KEY,\n );\n }\n this.writeFile(filePath, item);\n }\n\n /** @inheritdoc */\n async update(key: string, item: T): Promise<void> {\n const filePath = this.keyToPath(key);\n if (!existsSync(filePath)) {\n throw new StorageError(\n `Item with key \"${key}\" not found`,\n ErrorCode.STORAGE_NOT_FOUND,\n );\n }\n this.writeFile(filePath, item);\n }\n\n /** @inheritdoc */\n async delete(key: string): Promise<void> {\n const filePath = this.keyToPath(key);\n if (!existsSync(filePath)) {\n throw new StorageError(\n `Item with key \"${key}\" not found`,\n ErrorCode.STORAGE_NOT_FOUND,\n );\n }\n unlinkSync(filePath);\n }\n\n /** @inheritdoc */\n async has(key: string): Promise<boolean> {\n return existsSync(this.keyToPath(key));\n }\n\n /** @inheritdoc */\n async count(): Promise<number> {\n this.ensureDirectory();\n return readdirSync(this.directory).filter((f) =>\n f.endsWith(this.extension),\n ).length;\n }\n\n /** @inheritdoc */\n async clear(): Promise<void> {\n this.ensureDirectory();\n const files = readdirSync(this.directory).filter((f) =>\n f.endsWith(this.extension),\n );\n for (const file of files) {\n unlinkSync(join(this.directory, file));\n }\n }\n\n private keyToPath(key: string): string {\n const safeKey = key.replace(/[^a-zA-Z0-9_-]/g, (c) =>\n \"%\" + c.charCodeAt(0).toString(16).padStart(2, \"0\"),\n );\n return join(this.directory, `${safeKey}${this.extension}`);\n }\n\n private ensureDirectory(): void {\n if (!existsSync(this.directory)) {\n mkdirSync(this.directory, { recursive: true });\n }\n }\n\n private readFile(filePath: string): T {\n try {\n const content = readFileSync(filePath, \"utf-8\");\n return JSON.parse(content) as T;\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new StorageError(\n `Failed to parse file: ${filePath}`,\n ErrorCode.STORAGE_SERIALIZATION_ERROR,\n );\n }\n throw new StorageError(\n `Failed to read file: ${filePath}`,\n ErrorCode.STORAGE_IO_ERROR,\n );\n }\n }\n\n private writeFile(filePath: string, item: T): void {\n try {\n const content = JSON.stringify(item, null, 2);\n writeFileSync(filePath, content, \"utf-8\");\n } catch {\n throw new StorageError(\n `Failed to write file: ${filePath}`,\n ErrorCode.STORAGE_IO_ERROR,\n );\n }\n }\n}\n","/**\n * @witqq/agent-sdk/chat/sessions\n *\n * Session store layer wrapping generic storage adapters.\n * Provides session-specific operations: message management,\n * paginated retrieval, search, and session lifecycle.\n */\n\nimport type {\n ChatSession,\n ChatMessage,\n ChatId,\n ChatSessionConfig,\n} from \"./core.js\";\nimport { createChatId } from \"./core.js\";\nimport type { IStorageAdapter, ListOptions } from \"./storage.js\";\nimport { InMemoryStorage, FileStorage, StorageError } from \"./storage.js\";\nimport { ErrorCode } from \"../types/errors.js\";\n\n// ─── Session Store Interface ───────────────────────────────────\n\n/** Options for creating a new session */\nexport interface CreateSessionOptions<TCustom extends Record<string, unknown> = Record<string, unknown>> {\n /** Session title (defaults to \"Untitled\") */\n title?: string;\n /** Session configuration (optional — runtime defaults used when omitted) */\n config?: Partial<ChatSessionConfig>;\n /** Initial tags */\n tags?: string[];\n /** Custom metadata */\n custom?: TCustom;\n}\n\n/** Paginated result of messages */\nexport interface PaginatedMessages {\n /** Messages in this page */\n messages: ChatMessage[];\n /** Total number of messages in session */\n total: number;\n /** Whether there are more messages after this page */\n hasMore: boolean;\n}\n\n/** Options for listing sessions */\nexport interface SessionListOptions {\n /** Filter predicate */\n filter?: (session: ChatSession) => boolean;\n /** Sort comparator */\n sort?: (a: ChatSession, b: ChatSession) => number;\n /** Maximum number of sessions to return */\n limit?: number;\n /** Number of sessions to skip */\n offset?: number;\n}\n\n/** Search options for finding sessions */\nexport interface SessionSearchOptions {\n /** Text query to match against title and message content */\n query: string;\n /** Maximum results (default: 20) */\n limit?: number;\n}\n\n/**\n * Read-only session operations.\n * Consumers needing read-only access (dashboards, analytics) implement only this.\n */\nexport interface ISessionReader {\n getSession(id: ChatId): Promise<ChatSession | null>;\n listSessions(options?: SessionListOptions): Promise<ChatSession[]>;\n loadMessages(\n sessionId: ChatId,\n options?: { limit?: number; offset?: number },\n ): Promise<PaginatedMessages>;\n searchSessions(options: SessionSearchOptions): Promise<ChatSession[]>;\n count(): Promise<number>;\n}\n\n/**\n * Write/mutate session operations.\n * Consumers needing full access implement both ISessionReader & ISessionWriter.\n */\nexport interface ISessionWriter {\n createSession(options: CreateSessionOptions): Promise<ChatSession>;\n updateTitle(id: ChatId, title: string): Promise<void>;\n updateConfig(id: ChatId, config: Partial<ChatSessionConfig>): Promise<void>;\n deleteSession(id: ChatId): Promise<void>;\n appendMessage(sessionId: ChatId, message: ChatMessage): Promise<void>;\n saveMessages(sessionId: ChatId, messages: ChatMessage[]): Promise<void>;\n clear(): Promise<void>;\n /** Release any resources held by this store (optional). */\n dispose?(): Promise<void>;\n}\n\n/**\n * Full session store interface — union of reader and writer.\n * Backward-compatible: all existing implementations continue to work.\n *\n * @example\n * ```typescript\n * const store = new InMemorySessionStore();\n * const session = await store.createSession({ config: { model: \"gpt-4\", backend: \"vercel-ai\" } });\n * await store.appendMessage(session.id, message);\n * const page = await store.loadMessages(session.id, { limit: 20, offset: 0 });\n * ```\n */\nexport interface IChatSessionStore extends ISessionReader, ISessionWriter {}\n\n// ─── Base Session Store ────────────────────────────────────────\n\n/**\n * Base session store implementation backed by any `IStorageAdapter<ChatSession>`.\n * Handles all session-specific logic; subclasses only need to provide the adapter.\n */\nclass BaseSessionStore implements IChatSessionStore {\n constructor(protected readonly adapter: IStorageAdapter<ChatSession>) {}\n\n async createSession(options: CreateSessionOptions): Promise<ChatSession> {\n const now = new Date().toISOString();\n const id = createChatId();\n const session: ChatSession = {\n id,\n title: options.title ?? \"Untitled\",\n messages: [],\n config: {\n model: options.config?.model ?? \"\",\n backend: options.config?.backend ?? \"\",\n ...options.config,\n },\n metadata: {\n messageCount: 0,\n totalTokens: 0,\n tags: options.tags ? [...options.tags] : undefined,\n custom: options.custom ? { ...options.custom } : undefined,\n },\n status: \"active\" as const,\n createdAt: now,\n updatedAt: now,\n };\n await this.adapter.create(id, session);\n return structuredClone(session);\n }\n\n async getSession(id: ChatId): Promise<ChatSession | null> {\n return this.adapter.get(id);\n }\n\n async listSessions(options?: SessionListOptions): Promise<ChatSession[]> {\n return this.adapter.list(options as ListOptions<ChatSession>);\n }\n\n async updateTitle(id: ChatId, title: string): Promise<void> {\n const session = await this.adapter.get(id);\n if (!session) {\n throw new StorageError(`Session \"${id}\" not found`, ErrorCode.STORAGE_NOT_FOUND);\n }\n session.title = title;\n session.updatedAt = new Date().toISOString();\n await this.adapter.update(id, session);\n }\n\n async updateConfig(\n id: ChatId,\n config: Partial<ChatSessionConfig>,\n ): Promise<void> {\n const session = await this.adapter.get(id);\n if (!session) {\n throw new StorageError(`Session \"${id}\" not found`, ErrorCode.STORAGE_NOT_FOUND);\n }\n session.config = { ...session.config, ...config };\n session.updatedAt = new Date().toISOString();\n await this.adapter.update(id, session);\n }\n\n async deleteSession(id: ChatId): Promise<void> {\n await this.adapter.delete(id);\n }\n\n async appendMessage(sessionId: ChatId, message: ChatMessage): Promise<void> {\n const session = await this.adapter.get(sessionId);\n if (!session) {\n throw new StorageError(`Session \"${sessionId}\" not found`, ErrorCode.STORAGE_NOT_FOUND);\n }\n session.messages.push(structuredClone(message));\n session.metadata.messageCount = session.messages.length;\n session.updatedAt = new Date().toISOString();\n await this.adapter.update(sessionId, session);\n }\n\n async saveMessages(sessionId: ChatId, messages: ChatMessage[]): Promise<void> {\n if (messages.length === 0) return;\n const session = await this.adapter.get(sessionId);\n if (!session) {\n throw new StorageError(`Session \"${sessionId}\" not found`, ErrorCode.STORAGE_NOT_FOUND);\n }\n for (const msg of messages) {\n session.messages.push(structuredClone(msg));\n }\n session.metadata.messageCount = session.messages.length;\n session.updatedAt = new Date().toISOString();\n await this.adapter.update(sessionId, session);\n }\n\n async loadMessages(\n sessionId: ChatId,\n options?: { limit?: number; offset?: number },\n ): Promise<PaginatedMessages> {\n const session = await this.adapter.get(sessionId);\n if (!session) {\n throw new StorageError(`Session \"${sessionId}\" not found`, ErrorCode.STORAGE_NOT_FOUND);\n }\n const total = session.messages.length;\n const offset = options?.offset ?? 0;\n const limit = options?.limit ?? total;\n const messages = session.messages.slice(offset, offset + limit);\n return {\n messages: structuredClone(messages),\n total,\n hasMore: offset + limit < total,\n };\n }\n\n async searchSessions(\n options: SessionSearchOptions,\n ): Promise<ChatSession[]> {\n const query = options.query.toLowerCase();\n const limit = options.limit ?? 20;\n return this.adapter.list({\n filter: (session) => {\n if (session.title?.toLowerCase().includes(query)) return true;\n return session.messages.some((msg) => {\n return msg.parts.some(\n (part) =>\n part.type === \"text\" &&\n part.text.toLowerCase().includes(query),\n );\n });\n },\n limit,\n });\n }\n\n async count(): Promise<number> {\n return this.adapter.count();\n }\n\n async clear(): Promise<void> {\n return this.adapter.clear();\n }\n}\n\n// ─── InMemorySessionStore ──────────────────────────────────────\n\n/**\n * In-memory session store. Data is lost when the process exits.\n * Uses `InMemoryStorage` internally.\n *\n * @example\n * ```typescript\n * const store = new InMemorySessionStore();\n * const session = await store.createSession({\n * config: { model: \"gpt-4\", backend: \"vercel-ai\" },\n * });\n * ```\n */\nexport class InMemorySessionStore extends BaseSessionStore {\n constructor() {\n super(new InMemoryStorage<ChatSession>());\n }\n}\n\n// ─── FileSessionStore ──────────────────────────────────────────\n\n/** Configuration for FileSessionStore */\nexport interface FileSessionStoreOptions {\n /** Directory to store session JSON files */\n directory: string;\n}\n\n/**\n * File-based session store. Each session is a JSON file on disk.\n * Uses `FileStorage` internally.\n *\n * @example\n * ```typescript\n * const store = new FileSessionStore({ directory: \"./data/sessions\" });\n * const session = await store.createSession({\n * config: { model: \"claude-3\", backend: \"claude\" },\n * });\n * ```\n */\nexport class FileSessionStore extends BaseSessionStore {\n constructor(options: FileSessionStoreOptions) {\n super(new FileStorage<ChatSession>({ directory: options.directory }));\n }\n}\n\n// Re-export StorageError for consumers that only import from chat/sessions\nexport { StorageError } from \"./storage.js\";\n"]}
|