@alexein/sdk 0.0.0-stage → 0.3.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.
@@ -0,0 +1,185 @@
1
+ import {
2
+ LazyClient,
3
+ NOTHING_FOUND,
4
+ NOTHING_YET,
5
+ SAVED,
6
+ UNAVAILABLE,
7
+ isClient,
8
+ notFoundAnswer,
9
+ openAnswer,
10
+ outageAnswer,
11
+ promptBlock,
12
+ searchAnswer,
13
+ searchFor,
14
+ stableId
15
+ } from "./chunk-OVDZ3D4M.js";
16
+ import {
17
+ NotFoundError
18
+ } from "./chunk-UNVZ22EN.js";
19
+
20
+ // src/langgraph/index.ts
21
+ import { AIMessage, HumanMessage } from "@langchain/core/messages";
22
+ import { tool } from "@langchain/core/tools";
23
+ import { Annotation, MessagesAnnotation, MessagesValue, StateSchema } from "@langchain/langgraph";
24
+ import { z } from "zod";
25
+ var MemoryAnnotation = Annotation.Root({
26
+ ...MessagesAnnotation.spec,
27
+ memory: Annotation({ reducer: (_, found) => found, default: () => "" })
28
+ });
29
+ var MemoryState = new StateSchema({
30
+ messages: MessagesValue,
31
+ memory: z.string().default("")
32
+ });
33
+ var MemoryContext = z.object({ user_id: z.string().optional() });
34
+ function userIdOf(config) {
35
+ const context = config?.context;
36
+ const found = context?.user_id ?? config?.configurable?.user_id;
37
+ if (found === void 0 || found === null || found === "") {
38
+ throw new Error(
39
+ 'Alexein needs to know whose memory this is: run the graph with { context: { user_id: "..." } }, or { configurable: { user_id: "..." } }'
40
+ );
41
+ }
42
+ return String(found);
43
+ }
44
+ function threadOf(config) {
45
+ const thread = config?.configurable?.thread_id;
46
+ return thread === void 0 || thread === null ? void 0 : String(thread);
47
+ }
48
+ function lastHuman(messages) {
49
+ return messages.findLast((m) => HumanMessage.isInstance(m));
50
+ }
51
+ function lastReply(messages) {
52
+ return messages.findLast((m) => AIMessage.isInstance(m) && !m.tool_calls?.length);
53
+ }
54
+ var AlexeinMemory = class {
55
+ fast;
56
+ maxChars;
57
+ strict;
58
+ #client;
59
+ /** `client` defaults to one made on first use: fail-open unless strict, a 10 s timeout. */
60
+ constructor(client, options = {}) {
61
+ const given = isClient(client) ? client : void 0;
62
+ const settings = isClient(client) ? options : { ...client, ...options };
63
+ this.fast = settings.fast ?? false;
64
+ this.maxChars = settings.maxChars ?? 4e3;
65
+ this.strict = settings.strict ?? false;
66
+ this.#client = new LazyClient(given, "langgraph", this.strict, settings.timeout);
67
+ }
68
+ get client() {
69
+ return this.#client.client;
70
+ }
71
+ user(config) {
72
+ return this.client.user(userIdOf(config));
73
+ }
74
+ /** A node: what memory holds for the latest human message, into `state.memory`. */
75
+ recall = async (state, config) => {
76
+ const asked = lastHuman(state.messages)?.text.trim();
77
+ const user = this.user(config);
78
+ if (!asked) return { memory: "" };
79
+ const found = await searchFor(user, asked, this.fast);
80
+ return { memory: found?.context(this.maxChars) ?? "" };
81
+ };
82
+ /**
83
+ * A node: save the turn - the latest human message and the last reply that is not a tool call -
84
+ * in the thread's session. Each message keeps its LangGraph id as its item id (else a stable
85
+ * hash), so running a turn again edits what was saved rather than adding a copy. Tool calls and
86
+ * tool results are not saved. Needs a key that writes.
87
+ */
88
+ remember = async (state, config) => {
89
+ const user = this.user(config);
90
+ const thread = threadOf(config);
91
+ const said = [
92
+ await item(lastHuman(state.messages), "user", thread),
93
+ await item(lastReply(state.messages), "assistant", thread)
94
+ ].filter((i) => i !== void 0);
95
+ if (said.length) await user.add(said, { session: thread });
96
+ return {};
97
+ };
98
+ /** What `recall` found, as a block for your system prompt; empty when it found nothing. */
99
+ prompt = (state) => promptBlock(state.memory ?? "");
100
+ /**
101
+ * Tools the model calls when it decides to: `memory_search` and `memory_open`, and with
102
+ * `write`, `memory_add`. The user comes from the run, which a model never sees.
103
+ */
104
+ tools({ write = false } = {}) {
105
+ const read = [this.searchTool(), this.openTool()];
106
+ return write ? [...read, this.addTool()] : read;
107
+ }
108
+ searchTool() {
109
+ return tool(
110
+ async ({ query }, config) => {
111
+ const found = await searchFor(this.user(config), query, this.fast);
112
+ return searchAnswer(found, this.maxChars);
113
+ },
114
+ {
115
+ name: "memory_search",
116
+ description: "Search what you remember about this user: what they said, did and decided in earlier conversations. Ask in plain language. Ends with the refs of what it found, to read whole with memory_open.",
117
+ schema: z.object({ query: z.string().describe("What to look for") })
118
+ }
119
+ );
120
+ }
121
+ openTool() {
122
+ return tool(
123
+ async ({ ref }, config) => {
124
+ const user = this.user(config);
125
+ try {
126
+ return openAnswer(await user.open(ref));
127
+ } catch (error) {
128
+ if (error instanceof NotFoundError) return notFoundAnswer(error);
129
+ return outageAnswer(error, this.strict);
130
+ }
131
+ },
132
+ {
133
+ name: "memory_open",
134
+ description: "Read one remembered memory whole, by a ref memory_search gave.",
135
+ schema: z.object({ ref: z.string().describe("A ref memory_search gave") })
136
+ }
137
+ );
138
+ }
139
+ addTool() {
140
+ return tool(
141
+ async ({ text }, config) => {
142
+ const saved = await this.user(config).add(text, {
143
+ kind: "note",
144
+ session: threadOf(config)
145
+ });
146
+ return saved.failed ? UNAVAILABLE : SAVED;
147
+ },
148
+ {
149
+ name: "memory_add",
150
+ description: "Remember something about this user for later conversations: a preference, a fact about them, a decision. Write it as one plain sentence. Never save passwords, keys or secrets.",
151
+ schema: z.object({ text: z.string().describe("One plain sentence") })
152
+ }
153
+ );
154
+ }
155
+ };
156
+ async function item(message, role, thread) {
157
+ const text = message?.text;
158
+ if (!text?.trim()) return void 0;
159
+ const id = message?.id ?? await stableId(thread, role, text);
160
+ return { id, role, text };
161
+ }
162
+ var fallback;
163
+ function defaultMemory() {
164
+ fallback ??= new AlexeinMemory();
165
+ return fallback;
166
+ }
167
+ var recall = (state, config) => defaultMemory().recall(state, config);
168
+ var remember = (state, config) => defaultMemory().remember(state, config);
169
+ var memoryPrompt = (state) => defaultMemory().prompt(state);
170
+ var memoryTools = (options = {}) => defaultMemory().tools(options);
171
+ export {
172
+ AlexeinMemory,
173
+ MemoryAnnotation,
174
+ MemoryContext,
175
+ MemoryState,
176
+ NOTHING_FOUND,
177
+ NOTHING_YET,
178
+ UNAVAILABLE,
179
+ defaultMemory,
180
+ memoryPrompt,
181
+ memoryTools,
182
+ recall,
183
+ remember,
184
+ userIdOf
185
+ };
@@ -0,0 +1,234 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+ var _chunkTLAHP2PBcjs = require('./chunk-TLAHP2PB.cjs');
15
+
16
+
17
+
18
+
19
+
20
+ var _chunk7KPDU3YVcjs = require('./chunk-7KPDU3YV.cjs');
21
+
22
+ // src/openai-agents/run.ts
23
+ function userIdOf(context) {
24
+ const found = _optionalChain([context, 'optionalAccess', _ => _.userId]);
25
+ if (!found) {
26
+ throw new Error(
27
+ 'Alexein needs to know whose memory this is: run the agent with { context: { userId: "..." } }'
28
+ );
29
+ }
30
+ return String(found);
31
+ }
32
+ function sessionIdOf(context) {
33
+ const found = _optionalChain([context, 'optionalAccess', _2 => _2.sessionId]);
34
+ return found ? String(found) : void 0;
35
+ }
36
+ function textOf(item2) {
37
+ const content = "content" in item2 ? item2.content : void 0;
38
+ if (typeof content === "string") return content;
39
+ if (!Array.isArray(content)) return "";
40
+ return content.flatMap((part) => "text" in part && typeof part.text === "string" ? [part.text] : []).join("\n");
41
+ }
42
+ var saidByUser = (item2) => "role" in item2 && item2.role === "user";
43
+ var turns = /* @__PURE__ */ new WeakMap();
44
+ function turnOf(result) {
45
+ if (result.lastResponseId) return result.lastResponseId;
46
+ const made = _nullishCoalesce(turns.get(result), () => ( crypto.randomUUID()));
47
+ turns.set(result, made);
48
+ return made;
49
+ }
50
+ function answer(output) {
51
+ if (output === void 0 || output === null) return "";
52
+ return typeof output === "string" ? output : JSON.stringify(output);
53
+ }
54
+ async function item(said, role, turn, author) {
55
+ if (!said.trim()) return void 0;
56
+ const id = await _chunkTLAHP2PBcjs.stableId.call(void 0, turn, role, said);
57
+ return { id, role, text: said, ...author ? { author } : {} };
58
+ }
59
+ async function turnItems(result, session) {
60
+ const input = _nullishCoalesce(result.input, () => ( []));
61
+ const said = typeof input === "string" ? [{ role: "user", content: input }] : input;
62
+ const asked2 = said.findLast(saidByUser);
63
+ const turn = `${_nullishCoalesce(session, () => ( ""))}|${turnOf(result)}`;
64
+ const items = [
65
+ await item(asked2 ? textOf(asked2) : "", "user", turn),
66
+ await item(answer(result.finalOutput), "assistant", turn, _optionalChain([result, 'access', _3 => _3.lastAgent, 'optionalAccess', _4 => _4.name]))
67
+ ];
68
+ return items.filter((i) => i !== void 0);
69
+ }
70
+
71
+ // src/openai-agents/tools.ts
72
+ var _agents = require('@openai/agents');
73
+ var _zod = require('zod');
74
+ function failed(strict) {
75
+ return (run, error) => {
76
+ const yours = error instanceof _chunk7KPDU3YVcjs.AuthenticationError || error instanceof _chunk7KPDU3YVcjs.PermissionDeniedError;
77
+ const outage = error instanceof _chunk7KPDU3YVcjs.AlexeinError && error.outage;
78
+ const noUser = !_optionalChain([run, 'access', _5 => _5.context, 'optionalAccess', _6 => _6.userId]);
79
+ if (yours || noUser || strict && outage) throw error;
80
+ if (outage) {
81
+ console.warn(`Alexein is unavailable: ${error.message}`);
82
+ return _chunkTLAHP2PBcjs.UNAVAILABLE;
83
+ }
84
+ return `That did not work: ${error instanceof Error ? error.message : String(error)}`;
85
+ };
86
+ }
87
+ function buildTools(memory, write) {
88
+ const errorFunction = failed(memory.strict);
89
+ const search = _agents.tool.call(void 0, {
90
+ name: "memory_search",
91
+ description: "Search what you remember about this user: what they said, did and decided in earlier conversations. Ask in plain language. Ends with the refs of what it found, to read whole with memory_open.",
92
+ parameters: _zod.z.object({ query: _zod.z.string().describe("What to look for") }),
93
+ errorFunction,
94
+ async execute({ query }, run) {
95
+ const found = await _chunkTLAHP2PBcjs.searchFor.call(void 0, memory.userOf(_optionalChain([run, 'optionalAccess', _7 => _7.context])), query, memory.fast);
96
+ return _chunkTLAHP2PBcjs.searchAnswer.call(void 0, found, memory.maxChars);
97
+ }
98
+ });
99
+ const open = _agents.tool.call(void 0, {
100
+ name: "memory_open",
101
+ description: "Read one remembered memory whole, by a ref memory_search gave.",
102
+ parameters: _zod.z.object({ ref: _zod.z.string().describe("A ref memory_search gave") }),
103
+ errorFunction,
104
+ async execute({ ref }, run) {
105
+ try {
106
+ return _chunkTLAHP2PBcjs.openAnswer.call(void 0, await memory.userOf(_optionalChain([run, 'optionalAccess', _8 => _8.context])).open(ref));
107
+ } catch (error) {
108
+ if (!(error instanceof _chunk7KPDU3YVcjs.NotFoundError)) throw error;
109
+ return _chunkTLAHP2PBcjs.notFoundAnswer.call(void 0, error);
110
+ }
111
+ }
112
+ });
113
+ const add = _agents.tool.call(void 0, {
114
+ name: "memory_add",
115
+ description: "Remember something about this user for later conversations: a preference, a fact about them, a decision. Write it as one plain sentence. Never save passwords, keys or secrets.",
116
+ parameters: _zod.z.object({ text: _zod.z.string().describe("One plain sentence") }),
117
+ errorFunction,
118
+ async execute({ text }, run) {
119
+ const saved = await memory.userOf(_optionalChain([run, 'optionalAccess', _9 => _9.context])).add(text, {
120
+ kind: "note",
121
+ session: sessionIdOf(_optionalChain([run, 'optionalAccess', _10 => _10.context]))
122
+ });
123
+ return saved.failed ? _chunkTLAHP2PBcjs.UNAVAILABLE : _chunkTLAHP2PBcjs.SAVED;
124
+ }
125
+ });
126
+ return write ? [search, open, add] : [search, open];
127
+ }
128
+
129
+ // src/openai-agents/index.ts
130
+ function asked(items) {
131
+ for (let i = items.length - 1; i >= 0; i--) {
132
+ const item2 = items[i];
133
+ const role = "role" in item2 ? item2.role : "";
134
+ if (role === "developer" || role === "system") continue;
135
+ return role === "user" ? textOf(item2).trim() : void 0;
136
+ }
137
+ return void 0;
138
+ }
139
+ var AlexeinMemory = (_class = class {
140
+
141
+
142
+
143
+ #client;
144
+ /**
145
+ * What `recall` found for each run - its context object - for the model calls after the first
146
+ * in a turn (a tool loop, a handoff), whose input no longer ends with the user's message. Per
147
+ * run, so two turns in flight for one user keep their own.
148
+ */
149
+ #recalled = /* @__PURE__ */ new WeakMap();
150
+ /** `client` defaults to one made on first use: fail-open unless strict, a 10 s timeout. */
151
+ constructor(client, options = {}) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);
152
+ const given = _chunkTLAHP2PBcjs.isClient.call(void 0, client) ? client : void 0;
153
+ const settings = _chunkTLAHP2PBcjs.isClient.call(void 0, client) ? options : { ...client, ...options };
154
+ this.fast = _nullishCoalesce(settings.fast, () => ( false));
155
+ this.maxChars = _nullishCoalesce(settings.maxChars, () => ( 4e3));
156
+ this.strict = _nullishCoalesce(settings.strict, () => ( false));
157
+ this.#client = new (0, _chunkTLAHP2PBcjs.LazyClient)(given, "openai-agents", this.strict, settings.timeout);
158
+ }
159
+ get client() {
160
+ return this.#client.client;
161
+ }
162
+ /** The memory of the app user a run's context names. */
163
+ userOf(context) {
164
+ return this.client.user(userIdOf(context));
165
+ }
166
+ /**
167
+ * `callModelInputFilter: memory.recall`: before the model, what memory holds for the user's
168
+ * latest message, added to the instructions. Already using a filter? Run both:
169
+ * `async (args) => yours({ ...args, modelData: await memory.recall(args) })`.
170
+ */
171
+ __init() {this.recall = exports.recall = async ({
172
+ modelData,
173
+ context
174
+ }) => {
175
+ const user = this.userOf(context);
176
+ const run = context;
177
+ let question = asked(modelData.input);
178
+ if (question === void 0 && !this.#recalled.has(run)) {
179
+ const said = modelData.input.findLast(saidByUser);
180
+ question = said && textOf(said).trim();
181
+ }
182
+ if (question !== void 0) {
183
+ const found = question ? await _chunkTLAHP2PBcjs.searchFor.call(void 0, user, question, this.fast) : void 0;
184
+ this.#recalled.set(run, _chunkTLAHP2PBcjs.promptBlock.call(void 0, _nullishCoalesce(_optionalChain([found, 'optionalAccess', _17 => _17.context, 'call', _18 => _18(this.maxChars)]), () => ( ""))));
185
+ }
186
+ const block = this.#recalled.get(run);
187
+ if (!block) return modelData;
188
+ const given = modelData.instructions;
189
+ return { ...modelData, instructions: given ? `${given}
190
+
191
+ ${block}` : block };
192
+ }}
193
+ /**
194
+ * Save the turn a run answered - the user's latest message and the final output, under the
195
+ * agent's name - in the context's `sessionId`. Call it once the run is done (for a stream, once
196
+ * `completed` resolves). Saving the same result again edits rather than copies. Tool calls and
197
+ * their results are not saved, and a run paused for an approval saves nothing. Needs a key that
198
+ * writes.
199
+ */
200
+ __init2() {this.remember = exports.remember = async (result) => {
201
+ if (_optionalChain([result, 'access', _19 => _19.interruptions, 'optionalAccess', _20 => _20.length])) return;
202
+ const context = _optionalChain([result, 'access', _21 => _21.runContext, 'optionalAccess', _22 => _22.context]);
203
+ const session = sessionIdOf(context);
204
+ const items = await turnItems(result, session);
205
+ if (items.length) await this.userOf(context).add(items, { session });
206
+ }}
207
+ /**
208
+ * Tools the model calls when it decides to: `memory_search` and `memory_open`, and with
209
+ * `write`, `memory_add`. The user comes from the run's context, which a model never sees.
210
+ */
211
+ tools({ write = false } = {}) {
212
+ return buildTools(this, write);
213
+ }
214
+ }, _class);
215
+ var fallback;
216
+ function defaultMemory() {
217
+ fallback ??= new AlexeinMemory();
218
+ return fallback;
219
+ }
220
+ var recall = (args) => defaultMemory().recall(args);
221
+ var remember = (result) => defaultMemory().remember(result);
222
+ var memoryTools = (options = {}) => defaultMemory().tools(options);
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
+
233
+
234
+ exports.AlexeinMemory = AlexeinMemory; exports.NOTHING_FOUND = _chunkTLAHP2PBcjs.NOTHING_FOUND; exports.NOTHING_YET = _chunkTLAHP2PBcjs.NOTHING_YET; exports.UNAVAILABLE = _chunkTLAHP2PBcjs.UNAVAILABLE; exports.defaultMemory = defaultMemory; exports.memoryTools = memoryTools; exports.recall = recall; exports.remember = remember; exports.sessionIdOf = sessionIdOf; exports.userIdOf = userIdOf;
@@ -0,0 +1,101 @@
1
+ import { AgentInputItem, CallModelInputFilterArgs, ModelInputData, FunctionTool } from '@openai/agents';
2
+ import { v as Memory, X as User } from './client-YKZ4fkK-.cjs';
3
+ import { I as IntegrationOptions } from './shared-Btg8LbKC.cjs';
4
+ export { N as NOTHING_FOUND, a as NOTHING_YET, U as UNAVAILABLE } from './shared-Btg8LbKC.cjs';
5
+
6
+ /**
7
+ * What a run says: whose memory it reads (its context), what the user asked, and the turn
8
+ * `remember` saves - the user's latest message and the final output.
9
+ */
10
+
11
+ /**
12
+ * Whose memory a run reads: pass it as the run's `context`, or give a context of your own a
13
+ * `userId` (and, if you like, a `sessionId`, which groups what is saved by conversation).
14
+ */
15
+ interface MemoryContext {
16
+ userId: string;
17
+ sessionId?: string;
18
+ }
19
+ /** The app user a run's context names; never the model. */
20
+ declare function userIdOf(context: unknown): string;
21
+ declare function sessionIdOf(context: unknown): string | undefined;
22
+ /** What `remember` reads of a run's result: a `RunResult` or a completed `StreamedRunResult`. */
23
+ interface SavedResult {
24
+ readonly interruptions?: readonly unknown[];
25
+ readonly runContext?: {
26
+ readonly context: unknown;
27
+ };
28
+ readonly input?: string | AgentInputItem[];
29
+ readonly finalOutput?: unknown;
30
+ readonly lastAgent?: {
31
+ readonly name: string;
32
+ } | undefined;
33
+ readonly lastResponseId?: string | undefined;
34
+ }
35
+
36
+ /**
37
+ * Long-term memory for OpenAI Agents SDK agents, from Alexein.
38
+ *
39
+ * ```ts
40
+ * import { AlexeinMemory } from "@alexein/sdk/openai-agents";
41
+ *
42
+ * const memory = new AlexeinMemory(); // or new AlexeinMemory(client, { fast, maxChars, strict })
43
+ * const agent = new Agent({ name: "Assistant", tools: memory.tools() });
44
+ * const result = await run(agent, message, {
45
+ * context: { userId: "dana", sessionId: "conv-7" },
46
+ * callModelInputFilter: memory.recall,
47
+ * });
48
+ * await memory.remember(result);
49
+ * ```
50
+ *
51
+ * `recall` searches once a turn, with the user's latest message, and adds what it finds to the
52
+ * instructions of every model call in that turn, so it is never written into your session or
53
+ * history. Whose memory is read is decided by your code, never by a model: the run's
54
+ * `context.userId`.
55
+ */
56
+
57
+ /** Memory for OpenAI Agents SDK runs: `recall`, `remember` and tools, over one client. */
58
+ declare class AlexeinMemory {
59
+ #private;
60
+ readonly fast: boolean;
61
+ readonly maxChars: number;
62
+ readonly strict: boolean;
63
+ /** `client` defaults to one made on first use: fail-open unless strict, a 10 s timeout. */
64
+ constructor(client?: Memory | IntegrationOptions, options?: IntegrationOptions);
65
+ get client(): Memory;
66
+ /** The memory of the app user a run's context names. */
67
+ userOf(context: unknown): User;
68
+ /**
69
+ * `callModelInputFilter: memory.recall`: before the model, what memory holds for the user's
70
+ * latest message, added to the instructions. Already using a filter? Run both:
71
+ * `async (args) => yours({ ...args, modelData: await memory.recall(args) })`.
72
+ */
73
+ readonly recall: ({ modelData, context, }: CallModelInputFilterArgs<unknown>) => Promise<ModelInputData>;
74
+ /**
75
+ * Save the turn a run answered - the user's latest message and the final output, under the
76
+ * agent's name - in the context's `sessionId`. Call it once the run is done (for a stream, once
77
+ * `completed` resolves). Saving the same result again edits rather than copies. Tool calls and
78
+ * their results are not saved, and a run paused for an approval saves nothing. Needs a key that
79
+ * writes.
80
+ */
81
+ readonly remember: (result: SavedResult) => Promise<void>;
82
+ /**
83
+ * Tools the model calls when it decides to: `memory_search` and `memory_open`, and with
84
+ * `write`, `memory_add`. The user comes from the run's context, which a model never sees.
85
+ */
86
+ tools({ write }?: {
87
+ write?: boolean;
88
+ }): FunctionTool<unknown, any, string>[];
89
+ }
90
+ /** The `AlexeinMemory` the module-level functions use: made on first use, from the environment. */
91
+ declare function defaultMemory(): AlexeinMemory;
92
+ /** `recall` of the default `AlexeinMemory`. */
93
+ declare const recall: (args: CallModelInputFilterArgs<unknown>) => Promise<ModelInputData>;
94
+ /** `remember` of the default `AlexeinMemory`. */
95
+ declare const remember: (result: SavedResult) => Promise<void>;
96
+ /** `tools` of the default `AlexeinMemory`. */
97
+ declare const memoryTools: (options?: {
98
+ write?: boolean;
99
+ }) => FunctionTool<unknown, any, string>[];
100
+
101
+ export { AlexeinMemory, IntegrationOptions as AlexeinMemoryOptions, type MemoryContext, type SavedResult, defaultMemory, memoryTools, recall, remember, sessionIdOf, userIdOf };
@@ -0,0 +1,101 @@
1
+ import { AgentInputItem, CallModelInputFilterArgs, ModelInputData, FunctionTool } from '@openai/agents';
2
+ import { v as Memory, X as User } from './client-YKZ4fkK-.js';
3
+ import { I as IntegrationOptions } from './shared-Btg8LbKC.js';
4
+ export { N as NOTHING_FOUND, a as NOTHING_YET, U as UNAVAILABLE } from './shared-Btg8LbKC.js';
5
+
6
+ /**
7
+ * What a run says: whose memory it reads (its context), what the user asked, and the turn
8
+ * `remember` saves - the user's latest message and the final output.
9
+ */
10
+
11
+ /**
12
+ * Whose memory a run reads: pass it as the run's `context`, or give a context of your own a
13
+ * `userId` (and, if you like, a `sessionId`, which groups what is saved by conversation).
14
+ */
15
+ interface MemoryContext {
16
+ userId: string;
17
+ sessionId?: string;
18
+ }
19
+ /** The app user a run's context names; never the model. */
20
+ declare function userIdOf(context: unknown): string;
21
+ declare function sessionIdOf(context: unknown): string | undefined;
22
+ /** What `remember` reads of a run's result: a `RunResult` or a completed `StreamedRunResult`. */
23
+ interface SavedResult {
24
+ readonly interruptions?: readonly unknown[];
25
+ readonly runContext?: {
26
+ readonly context: unknown;
27
+ };
28
+ readonly input?: string | AgentInputItem[];
29
+ readonly finalOutput?: unknown;
30
+ readonly lastAgent?: {
31
+ readonly name: string;
32
+ } | undefined;
33
+ readonly lastResponseId?: string | undefined;
34
+ }
35
+
36
+ /**
37
+ * Long-term memory for OpenAI Agents SDK agents, from Alexein.
38
+ *
39
+ * ```ts
40
+ * import { AlexeinMemory } from "@alexein/sdk/openai-agents";
41
+ *
42
+ * const memory = new AlexeinMemory(); // or new AlexeinMemory(client, { fast, maxChars, strict })
43
+ * const agent = new Agent({ name: "Assistant", tools: memory.tools() });
44
+ * const result = await run(agent, message, {
45
+ * context: { userId: "dana", sessionId: "conv-7" },
46
+ * callModelInputFilter: memory.recall,
47
+ * });
48
+ * await memory.remember(result);
49
+ * ```
50
+ *
51
+ * `recall` searches once a turn, with the user's latest message, and adds what it finds to the
52
+ * instructions of every model call in that turn, so it is never written into your session or
53
+ * history. Whose memory is read is decided by your code, never by a model: the run's
54
+ * `context.userId`.
55
+ */
56
+
57
+ /** Memory for OpenAI Agents SDK runs: `recall`, `remember` and tools, over one client. */
58
+ declare class AlexeinMemory {
59
+ #private;
60
+ readonly fast: boolean;
61
+ readonly maxChars: number;
62
+ readonly strict: boolean;
63
+ /** `client` defaults to one made on first use: fail-open unless strict, a 10 s timeout. */
64
+ constructor(client?: Memory | IntegrationOptions, options?: IntegrationOptions);
65
+ get client(): Memory;
66
+ /** The memory of the app user a run's context names. */
67
+ userOf(context: unknown): User;
68
+ /**
69
+ * `callModelInputFilter: memory.recall`: before the model, what memory holds for the user's
70
+ * latest message, added to the instructions. Already using a filter? Run both:
71
+ * `async (args) => yours({ ...args, modelData: await memory.recall(args) })`.
72
+ */
73
+ readonly recall: ({ modelData, context, }: CallModelInputFilterArgs<unknown>) => Promise<ModelInputData>;
74
+ /**
75
+ * Save the turn a run answered - the user's latest message and the final output, under the
76
+ * agent's name - in the context's `sessionId`. Call it once the run is done (for a stream, once
77
+ * `completed` resolves). Saving the same result again edits rather than copies. Tool calls and
78
+ * their results are not saved, and a run paused for an approval saves nothing. Needs a key that
79
+ * writes.
80
+ */
81
+ readonly remember: (result: SavedResult) => Promise<void>;
82
+ /**
83
+ * Tools the model calls when it decides to: `memory_search` and `memory_open`, and with
84
+ * `write`, `memory_add`. The user comes from the run's context, which a model never sees.
85
+ */
86
+ tools({ write }?: {
87
+ write?: boolean;
88
+ }): FunctionTool<unknown, any, string>[];
89
+ }
90
+ /** The `AlexeinMemory` the module-level functions use: made on first use, from the environment. */
91
+ declare function defaultMemory(): AlexeinMemory;
92
+ /** `recall` of the default `AlexeinMemory`. */
93
+ declare const recall: (args: CallModelInputFilterArgs<unknown>) => Promise<ModelInputData>;
94
+ /** `remember` of the default `AlexeinMemory`. */
95
+ declare const remember: (result: SavedResult) => Promise<void>;
96
+ /** `tools` of the default `AlexeinMemory`. */
97
+ declare const memoryTools: (options?: {
98
+ write?: boolean;
99
+ }) => FunctionTool<unknown, any, string>[];
100
+
101
+ export { AlexeinMemory, IntegrationOptions as AlexeinMemoryOptions, type MemoryContext, type SavedResult, defaultMemory, memoryTools, recall, remember, sessionIdOf, userIdOf };