@alexein/sdk 0.3.4 → 0.3.5

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,101 @@
1
+ import { M as Memory, e as Author, I as Item, Z as SearchResult } from './client-76Fz2eLa.cjs';
2
+
3
+ /**
4
+ * What the model-client wrappers and the AI SDK middleware share: one app user's memory as a
5
+ * wrapped model uses it - one lookup before each call, within a time budget, and the exchange
6
+ * saved after it - and the block of memory a system prompt is given. Built on the client alone.
7
+ */
8
+
9
+ /** What the model is told about the memory block, above it. */
10
+ declare const HEADER: string;
11
+ /** What memory adds and saves around each model call. Every field is optional but `userId`. */
12
+ interface AutoMemoryOptions {
13
+ /** Your id for the app user whose memory this is. Never taken from a model or a request body. */
14
+ userId: string;
15
+ /**
16
+ * The conversation: what is saved is grouped under it, and a retried call edits what it saved
17
+ * rather than copying it.
18
+ */
19
+ session?: string;
20
+ /** Who the user is (`{ name, id }`); what they say is saved as theirs. */
21
+ author?: Author;
22
+ /** Look memory up before each call. Default true. */
23
+ recall?: boolean;
24
+ /** Save the user's message and the reply after each call. Default true. */
25
+ save?: boolean;
26
+ /** The longest a call waits for memory, in milliseconds. Default 1500. */
27
+ budget?: number;
28
+ /** About how many tokens of memory a call is given at most. Default 600. */
29
+ maxTokens?: number;
30
+ /**
31
+ * Skip search's relevance check: quicker, a little less precise. Default true. With `false`,
32
+ * what memory judges not to hold the answer is left out, and a search takes longer: raise
33
+ * `budget` with it.
34
+ */
35
+ fast?: boolean;
36
+ /** Replace phone numbers, cards, keys and the like before memory keeps any copy. */
37
+ redact?: boolean;
38
+ /**
39
+ * Sees the items about to be saved and answers those to save: changed, fewer, or none (an
40
+ * empty list, null or undefined saves nothing).
41
+ */
42
+ beforeSave?: (items: Item[]) => Item[] | null | undefined | Promise<Item[] | null | undefined>;
43
+ }
44
+ /** How the last lookup before a call went, for your metrics. */
45
+ interface RecallInfo {
46
+ /** Milliseconds the call waited. */
47
+ readonly ms: number;
48
+ /** Characters it added to the system prompt. */
49
+ readonly chars: number;
50
+ readonly timedOut: boolean;
51
+ readonly failed: boolean;
52
+ /** Served from an earlier call for the same message (a tool loop's next step). */
53
+ readonly reused: boolean;
54
+ /** Nothing was looked up: recall is off, or the call holds no message from the user. */
55
+ readonly skipped: boolean;
56
+ }
57
+ /** The user's latest words in a call, the reply before them, and where they sit. */
58
+ interface Asked {
59
+ readonly text: string;
60
+ readonly before: string;
61
+ readonly at: number;
62
+ }
63
+ /** What a model answered: its words, and whether it is the turn's last answer. */
64
+ declare class Reply {
65
+ parts: string[];
66
+ callsTool: boolean;
67
+ done: boolean;
68
+ get text(): string;
69
+ get final(): boolean;
70
+ }
71
+ /**
72
+ * What `found` adds to a system prompt: the header, then its memories inside `<memory>`, one a
73
+ * line with when and by whom, at most four, cut at a whole memory within `maxTokens`. With
74
+ * `gated`, without the lines memory lists after the excerpts. Empty when nothing is left.
75
+ */
76
+ declare function memoryBlock(found: SearchResult, maxTokens: number, gated?: boolean): string;
77
+ /**
78
+ * One app user's memory as a wrapped model uses it. `memoryOf(client)` answers it, for `last`
79
+ * and `flush()`.
80
+ */
81
+ declare class AutoMemory {
82
+ #private;
83
+ readonly userId: string;
84
+ /** How the last lookup went; null before the first. */
85
+ last: RecallInfo | null;
86
+ constructor(memory: Memory | undefined, options: AutoMemoryOptions);
87
+ /**
88
+ * What memory adds to the system prompt for `asked`, within `budget` milliseconds; "" when it
89
+ * has nothing that bears on it, is down, or is late. Never throws.
90
+ */
91
+ lookup(asked: Asked | null): Promise<string>;
92
+ /**
93
+ * Save the user's message and the turn's final reply, in the background, the hook included: it
94
+ * never delays the call or throws. `flush()` waits for it.
95
+ */
96
+ remember(asked: Asked | null, reply: Reply): void;
97
+ /** Wait for the saves still on their way: before a short-lived process or a serverless call ends. */
98
+ flush(): Promise<void>;
99
+ }
100
+
101
+ export { AutoMemory as A, HEADER as H, type RecallInfo as R, type AutoMemoryOptions as a, memoryBlock as m };
@@ -0,0 +1,101 @@
1
+ import { M as Memory, e as Author, I as Item, Z as SearchResult } from './client-76Fz2eLa.js';
2
+
3
+ /**
4
+ * What the model-client wrappers and the AI SDK middleware share: one app user's memory as a
5
+ * wrapped model uses it - one lookup before each call, within a time budget, and the exchange
6
+ * saved after it - and the block of memory a system prompt is given. Built on the client alone.
7
+ */
8
+
9
+ /** What the model is told about the memory block, above it. */
10
+ declare const HEADER: string;
11
+ /** What memory adds and saves around each model call. Every field is optional but `userId`. */
12
+ interface AutoMemoryOptions {
13
+ /** Your id for the app user whose memory this is. Never taken from a model or a request body. */
14
+ userId: string;
15
+ /**
16
+ * The conversation: what is saved is grouped under it, and a retried call edits what it saved
17
+ * rather than copying it.
18
+ */
19
+ session?: string;
20
+ /** Who the user is (`{ name, id }`); what they say is saved as theirs. */
21
+ author?: Author;
22
+ /** Look memory up before each call. Default true. */
23
+ recall?: boolean;
24
+ /** Save the user's message and the reply after each call. Default true. */
25
+ save?: boolean;
26
+ /** The longest a call waits for memory, in milliseconds. Default 1500. */
27
+ budget?: number;
28
+ /** About how many tokens of memory a call is given at most. Default 600. */
29
+ maxTokens?: number;
30
+ /**
31
+ * Skip search's relevance check: quicker, a little less precise. Default true. With `false`,
32
+ * what memory judges not to hold the answer is left out, and a search takes longer: raise
33
+ * `budget` with it.
34
+ */
35
+ fast?: boolean;
36
+ /** Replace phone numbers, cards, keys and the like before memory keeps any copy. */
37
+ redact?: boolean;
38
+ /**
39
+ * Sees the items about to be saved and answers those to save: changed, fewer, or none (an
40
+ * empty list, null or undefined saves nothing).
41
+ */
42
+ beforeSave?: (items: Item[]) => Item[] | null | undefined | Promise<Item[] | null | undefined>;
43
+ }
44
+ /** How the last lookup before a call went, for your metrics. */
45
+ interface RecallInfo {
46
+ /** Milliseconds the call waited. */
47
+ readonly ms: number;
48
+ /** Characters it added to the system prompt. */
49
+ readonly chars: number;
50
+ readonly timedOut: boolean;
51
+ readonly failed: boolean;
52
+ /** Served from an earlier call for the same message (a tool loop's next step). */
53
+ readonly reused: boolean;
54
+ /** Nothing was looked up: recall is off, or the call holds no message from the user. */
55
+ readonly skipped: boolean;
56
+ }
57
+ /** The user's latest words in a call, the reply before them, and where they sit. */
58
+ interface Asked {
59
+ readonly text: string;
60
+ readonly before: string;
61
+ readonly at: number;
62
+ }
63
+ /** What a model answered: its words, and whether it is the turn's last answer. */
64
+ declare class Reply {
65
+ parts: string[];
66
+ callsTool: boolean;
67
+ done: boolean;
68
+ get text(): string;
69
+ get final(): boolean;
70
+ }
71
+ /**
72
+ * What `found` adds to a system prompt: the header, then its memories inside `<memory>`, one a
73
+ * line with when and by whom, at most four, cut at a whole memory within `maxTokens`. With
74
+ * `gated`, without the lines memory lists after the excerpts. Empty when nothing is left.
75
+ */
76
+ declare function memoryBlock(found: SearchResult, maxTokens: number, gated?: boolean): string;
77
+ /**
78
+ * One app user's memory as a wrapped model uses it. `memoryOf(client)` answers it, for `last`
79
+ * and `flush()`.
80
+ */
81
+ declare class AutoMemory {
82
+ #private;
83
+ readonly userId: string;
84
+ /** How the last lookup went; null before the first. */
85
+ last: RecallInfo | null;
86
+ constructor(memory: Memory | undefined, options: AutoMemoryOptions);
87
+ /**
88
+ * What memory adds to the system prompt for `asked`, within `budget` milliseconds; "" when it
89
+ * has nothing that bears on it, is down, or is late. Never throws.
90
+ */
91
+ lookup(asked: Asked | null): Promise<string>;
92
+ /**
93
+ * Save the user's message and the turn's final reply, in the background, the hook included: it
94
+ * never delays the call or throws. `flush()` waits for it.
95
+ */
96
+ remember(asked: Asked | null, reply: Reply): void;
97
+ /** Wait for the saves still on their way: before a short-lived process or a serverless call ends. */
98
+ flush(): Promise<void>;
99
+ }
100
+
101
+ export { AutoMemory as A, HEADER as H, type RecallInfo as R, type AutoMemoryOptions as a, memoryBlock as m };
@@ -11,13 +11,13 @@
11
11
 
12
12
 
13
13
 
14
- var _chunkH4YONLGPcjs = require('./chunk-H4YONLGP.cjs');
14
+ var _chunkNKBLBBGOcjs = require('./chunk-NKBLBBGO.cjs');
15
15
 
16
16
 
17
17
 
18
18
 
19
19
 
20
- var _chunkAJUBXMERcjs = require('./chunk-AJUBXMER.cjs');
20
+ var _chunkWMDI4HIScjs = require('./chunk-WMDI4HIS.cjs');
21
21
 
22
22
  // src/openai-agents/run.ts
23
23
  function userIdOf(context) {
@@ -53,7 +53,7 @@ function answer(output) {
53
53
  }
54
54
  async function item(said, role, turn, author) {
55
55
  if (!said.trim()) return void 0;
56
- const id = await _chunkH4YONLGPcjs.stableId.call(void 0, turn, role, said);
56
+ const id = await _chunkNKBLBBGOcjs.stableId.call(void 0, turn, role, said);
57
57
  return { id, role, text: said, ...author ? { author } : {} };
58
58
  }
59
59
  async function turnItems(result, session) {
@@ -73,13 +73,13 @@ var _agents = require('@openai/agents');
73
73
  var _zod = require('zod');
74
74
  function failed(strict) {
75
75
  return (run, error) => {
76
- const yours = error instanceof _chunkAJUBXMERcjs.AuthenticationError || error instanceof _chunkAJUBXMERcjs.PermissionDeniedError;
77
- const outage = error instanceof _chunkAJUBXMERcjs.AlexeinError && error.outage;
76
+ const yours = error instanceof _chunkWMDI4HIScjs.AuthenticationError || error instanceof _chunkWMDI4HIScjs.PermissionDeniedError;
77
+ const outage = error instanceof _chunkWMDI4HIScjs.AlexeinError && error.outage;
78
78
  const noUser = !_optionalChain([run, 'access', _5 => _5.context, 'optionalAccess', _6 => _6.userId]);
79
79
  if (yours || noUser || strict && outage) throw error;
80
80
  if (outage) {
81
81
  console.warn(`Alexein is unavailable: ${error.message}`);
82
- return _chunkH4YONLGPcjs.UNAVAILABLE;
82
+ return _chunkNKBLBBGOcjs.UNAVAILABLE;
83
83
  }
84
84
  return `That did not work: ${error instanceof Error ? error.message : String(error)}`;
85
85
  };
@@ -92,8 +92,8 @@ function buildTools(memory, write) {
92
92
  parameters: _zod.z.object({ query: _zod.z.string().describe("What to look for") }),
93
93
  errorFunction,
94
94
  async execute({ query }, run) {
95
- const found = await _chunkH4YONLGPcjs.searchFor.call(void 0, memory.userOf(_optionalChain([run, 'optionalAccess', _7 => _7.context])), query, memory.fast);
96
- return _chunkH4YONLGPcjs.searchAnswer.call(void 0, found, memory.maxChars);
95
+ const found = await _chunkNKBLBBGOcjs.searchFor.call(void 0, memory.userOf(_optionalChain([run, 'optionalAccess', _7 => _7.context])), query, memory.fast);
96
+ return _chunkNKBLBBGOcjs.searchAnswer.call(void 0, found, memory.maxChars);
97
97
  }
98
98
  });
99
99
  const open = _agents.tool.call(void 0, {
@@ -103,10 +103,10 @@ function buildTools(memory, write) {
103
103
  errorFunction,
104
104
  async execute({ ref }, run) {
105
105
  try {
106
- return _chunkH4YONLGPcjs.openAnswer.call(void 0, await memory.userOf(_optionalChain([run, 'optionalAccess', _8 => _8.context])).open(ref));
106
+ return _chunkNKBLBBGOcjs.openAnswer.call(void 0, await memory.userOf(_optionalChain([run, 'optionalAccess', _8 => _8.context])).open(ref));
107
107
  } catch (error) {
108
- if (!(error instanceof _chunkAJUBXMERcjs.NotFoundError)) throw error;
109
- return _chunkH4YONLGPcjs.notFoundAnswer.call(void 0, error);
108
+ if (!(error instanceof _chunkWMDI4HIScjs.NotFoundError)) throw error;
109
+ return _chunkNKBLBBGOcjs.notFoundAnswer.call(void 0, error);
110
110
  }
111
111
  }
112
112
  });
@@ -120,7 +120,7 @@ function buildTools(memory, write) {
120
120
  kind: "note",
121
121
  session: sessionIdOf(_optionalChain([run, 'optionalAccess', _10 => _10.context]))
122
122
  });
123
- return saved.failed ? _chunkH4YONLGPcjs.UNAVAILABLE : _chunkH4YONLGPcjs.SAVED;
123
+ return saved.failed ? _chunkNKBLBBGOcjs.UNAVAILABLE : _chunkNKBLBBGOcjs.SAVED;
124
124
  }
125
125
  });
126
126
  return write ? [search, open, add] : [search, open];
@@ -149,12 +149,12 @@ var AlexeinMemory = (_class = class {
149
149
  #recalled = /* @__PURE__ */ new WeakMap();
150
150
  /** `client` defaults to one made on first use: fail-open unless strict, a 10 s timeout. */
151
151
  constructor(client, options = {}) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);
152
- const given = _chunkH4YONLGPcjs.isClient.call(void 0, client) ? client : void 0;
153
- const settings = _chunkH4YONLGPcjs.isClient.call(void 0, client) ? options : { ...client, ...options };
152
+ const given = _chunkNKBLBBGOcjs.isClient.call(void 0, client) ? client : void 0;
153
+ const settings = _chunkNKBLBBGOcjs.isClient.call(void 0, client) ? options : { ...client, ...options };
154
154
  this.fast = _nullishCoalesce(settings.fast, () => ( false));
155
155
  this.maxChars = _nullishCoalesce(settings.maxChars, () => ( 4e3));
156
156
  this.strict = _nullishCoalesce(settings.strict, () => ( false));
157
- this.#client = new (0, _chunkH4YONLGPcjs.LazyClient)(given, "openai-agents", this.strict, settings.timeout);
157
+ this.#client = new (0, _chunkNKBLBBGOcjs.LazyClient)(given, "openai-agents", this.strict, settings.timeout);
158
158
  }
159
159
  get client() {
160
160
  return this.#client.client;
@@ -180,8 +180,8 @@ var AlexeinMemory = (_class = class {
180
180
  question = said && textOf(said).trim();
181
181
  }
182
182
  if (question !== void 0) {
183
- const found = question ? await _chunkH4YONLGPcjs.searchFor.call(void 0, user, question, this.fast) : void 0;
184
- this.#recalled.set(run, _chunkH4YONLGPcjs.promptBlock.call(void 0, _nullishCoalesce(_optionalChain([found, 'optionalAccess', _17 => _17.context, 'call', _18 => _18(this.maxChars)]), () => ( ""))));
183
+ const found = question ? await _chunkNKBLBBGOcjs.searchFor.call(void 0, user, question, this.fast) : void 0;
184
+ this.#recalled.set(run, _chunkNKBLBBGOcjs.promptBlock.call(void 0, _nullishCoalesce(_optionalChain([found, 'optionalAccess', _17 => _17.context, 'call', _18 => _18(this.maxChars)]), () => ( ""))));
185
185
  }
186
186
  const block = this.#recalled.get(run);
187
187
  if (!block) return modelData;
@@ -231,4 +231,4 @@ var memoryTools = (options = {}) => defaultMemory().tools(options);
231
231
 
232
232
 
233
233
 
234
- exports.AlexeinMemory = AlexeinMemory; exports.NOTHING_FOUND = _chunkH4YONLGPcjs.NOTHING_FOUND; exports.NOTHING_YET = _chunkH4YONLGPcjs.NOTHING_YET; exports.UNAVAILABLE = _chunkH4YONLGPcjs.UNAVAILABLE; exports.defaultMemory = defaultMemory; exports.memoryTools = memoryTools; exports.recall = recall; exports.remember = remember; exports.sessionIdOf = sessionIdOf; exports.userIdOf = userIdOf;
234
+ exports.AlexeinMemory = AlexeinMemory; exports.NOTHING_FOUND = _chunkNKBLBBGOcjs.NOTHING_FOUND; exports.NOTHING_YET = _chunkNKBLBBGOcjs.NOTHING_YET; exports.UNAVAILABLE = _chunkNKBLBBGOcjs.UNAVAILABLE; exports.defaultMemory = defaultMemory; exports.memoryTools = memoryTools; exports.recall = recall; exports.remember = remember; exports.sessionIdOf = sessionIdOf; exports.userIdOf = userIdOf;
@@ -1,5 +1,5 @@
1
1
  import { AgentInputItem, CallModelInputFilterArgs, ModelInputData, FunctionTool } from '@openai/agents';
2
- import { N as Memory, a4 as User } from './client-XsmLck0h.cjs';
2
+ import { M as Memory, a4 as User } from './client-76Fz2eLa.cjs';
3
3
  import { I as IntegrationOptions } from './shared-Btg8LbKC.cjs';
4
4
  export { N as NOTHING_FOUND, a as NOTHING_YET, U as UNAVAILABLE } from './shared-Btg8LbKC.cjs';
5
5
 
@@ -1,5 +1,5 @@
1
1
  import { AgentInputItem, CallModelInputFilterArgs, ModelInputData, FunctionTool } from '@openai/agents';
2
- import { N as Memory, a4 as User } from './client-XsmLck0h.js';
2
+ import { M as Memory, a4 as User } from './client-76Fz2eLa.js';
3
3
  import { I as IntegrationOptions } from './shared-Btg8LbKC.js';
4
4
  export { N as NOTHING_FOUND, a as NOTHING_YET, U as UNAVAILABLE } from './shared-Btg8LbKC.js';
5
5
 
@@ -11,13 +11,13 @@ import {
11
11
  searchAnswer,
12
12
  searchFor,
13
13
  stableId
14
- } from "./chunk-DE6WA7QF.js";
14
+ } from "./chunk-C3LLPVOJ.js";
15
15
  import {
16
16
  AlexeinError,
17
17
  AuthenticationError,
18
18
  NotFoundError,
19
19
  PermissionDeniedError
20
- } from "./chunk-2322CW56.js";
20
+ } from "./chunk-NFVCTK7P.js";
21
21
 
22
22
  // src/openai-agents/run.ts
23
23
  function userIdOf(context) {
package/dist/wrap.cjs ADDED
@@ -0,0 +1,318 @@
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; }
2
+
3
+
4
+
5
+
6
+
7
+
8
+ var _chunkDCKT6Y5Bcjs = require('./chunk-DCKT6Y5B.cjs');
9
+ require('./chunk-WMDI4HIS.cjs');
10
+
11
+ // src/wrap/index.ts
12
+ var PAUSED = ["tool_use", "pause_turn"];
13
+ var anthropicMessages = {
14
+ asked: (params) => _chunkDCKT6Y5Bcjs.latestAsked.call(void 0, params.messages),
15
+ inject(params, text) {
16
+ const system = params.system;
17
+ if (Array.isArray(system)) return { ...params, system: [...system, { type: "text", text }] };
18
+ if (typeof system === "string" && system.trim())
19
+ return { ...params, system: `${system}
20
+
21
+ ${text}` };
22
+ return { ...params, system: text };
23
+ },
24
+ reply(result) {
25
+ const reply = new (0, _chunkDCKT6Y5Bcjs.Reply)();
26
+ for (const part of Array.isArray(_optionalChain([result, 'optionalAccess', _ => _.content])) ? result.content : []) {
27
+ if (_optionalChain([part, 'optionalAccess', _2 => _2.type]) === "text") reply.parts.push(_nullishCoalesce(part.text, () => ( "")));
28
+ else if (_optionalChain([part, 'optionalAccess', _3 => _3.type]) === "tool_use") reply.callsTool = true;
29
+ }
30
+ reply.callsTool ||= PAUSED.includes(_optionalChain([result, 'optionalAccess', _4 => _4.stop_reason]));
31
+ reply.done = true;
32
+ return reply;
33
+ },
34
+ feed(reply, event) {
35
+ if (_optionalChain([event, 'optionalAccess', _5 => _5.type]) === "content_block_start" && _optionalChain([event, 'access', _6 => _6.content_block, 'optionalAccess', _7 => _7.type]) === "tool_use") {
36
+ reply.callsTool = true;
37
+ } else if (_optionalChain([event, 'optionalAccess', _8 => _8.type]) === "content_block_delta" && _optionalChain([event, 'access', _9 => _9.delta, 'optionalAccess', _10 => _10.type]) === "text_delta") {
38
+ reply.parts.push(_nullishCoalesce(event.delta.text, () => ( "")));
39
+ } else if (_optionalChain([event, 'optionalAccess', _11 => _11.type]) === "message_delta") {
40
+ reply.callsTool ||= PAUSED.includes(_optionalChain([event, 'access', _12 => _12.delta, 'optionalAccess', _13 => _13.stop_reason]));
41
+ } else if (_optionalChain([event, 'optionalAccess', _14 => _14.type]) === "message_stop") {
42
+ reply.done = true;
43
+ }
44
+ }
45
+ };
46
+ var INSTRUCTIONS = ["system", "developer"];
47
+ var TOOL_FINISH = ["tool_calls", "function_call"];
48
+ var chatCompletions = {
49
+ asked: (params) => _chunkDCKT6Y5Bcjs.latestAsked.call(void 0, params.messages),
50
+ inject(params, text) {
51
+ const messages = Array.isArray(params.messages) ? [...params.messages] : [];
52
+ let lead = 0;
53
+ while (lead < messages.length && INSTRUCTIONS.includes(_optionalChain([messages, 'access', _15 => _15[lead], 'optionalAccess', _16 => _16.role]))) lead++;
54
+ const role = lead ? messages[0].role : "system";
55
+ messages.splice(lead, 0, { role, content: text });
56
+ return { ...params, messages };
57
+ },
58
+ reply(result) {
59
+ const reply = new (0, _chunkDCKT6Y5Bcjs.Reply)();
60
+ const choice = _optionalChain([result, 'optionalAccess', _17 => _17.choices, 'optionalAccess', _18 => _18[0]]);
61
+ if (choice) {
62
+ const content = _optionalChain([choice, 'access', _19 => _19.message, 'optionalAccess', _20 => _20.content]);
63
+ reply.parts.push(typeof content === "string" ? content : _chunkDCKT6Y5Bcjs.textOf.call(void 0, content));
64
+ reply.callsTool = Boolean(_optionalChain([choice, 'access', _21 => _21.message, 'optionalAccess', _22 => _22.tool_calls, 'optionalAccess', _23 => _23.length]) || _optionalChain([choice, 'access', _24 => _24.message, 'optionalAccess', _25 => _25.function_call])) || TOOL_FINISH.includes(choice.finish_reason);
65
+ }
66
+ reply.done = true;
67
+ return reply;
68
+ },
69
+ feed(reply, event) {
70
+ const choice = _optionalChain([event, 'optionalAccess', _26 => _26.choices, 'optionalAccess', _27 => _27[0]]);
71
+ if (!choice) return;
72
+ if (typeof _optionalChain([choice, 'access', _28 => _28.delta, 'optionalAccess', _29 => _29.content]) === "string") reply.parts.push(choice.delta.content);
73
+ if (_optionalChain([choice, 'access', _30 => _30.delta, 'optionalAccess', _31 => _31.tool_calls, 'optionalAccess', _32 => _32.length]) || _optionalChain([choice, 'access', _33 => _33.delta, 'optionalAccess', _34 => _34.function_call])) reply.callsTool = true;
74
+ if (choice.finish_reason) {
75
+ reply.done = true;
76
+ reply.callsTool ||= TOOL_FINISH.includes(choice.finish_reason);
77
+ }
78
+ }
79
+ };
80
+ var CALLS = /* @__PURE__ */ new Set([
81
+ "function_call",
82
+ "custom_tool_call",
83
+ "computer_call",
84
+ "local_shell_call",
85
+ "shell_call",
86
+ "apply_patch_call",
87
+ "mcp_approval_request"
88
+ ]);
89
+ var responsesApi = {
90
+ asked(params) {
91
+ const input = params.input;
92
+ if (typeof input === "string")
93
+ return input.trim() ? { text: input.trim(), before: "", at: 0 } : null;
94
+ return _chunkDCKT6Y5Bcjs.latestAsked.call(void 0, input);
95
+ },
96
+ inject(params, text) {
97
+ const given = typeof params.instructions === "string" ? params.instructions.trim() : "";
98
+ return { ...params, instructions: given ? `${params.instructions}
99
+
100
+ ${text}` : text };
101
+ },
102
+ reply(result) {
103
+ const reply = new (0, _chunkDCKT6Y5Bcjs.Reply)();
104
+ for (const item of Array.isArray(_optionalChain([result, 'optionalAccess', _35 => _35.output])) ? result.output : []) {
105
+ if (CALLS.has(_optionalChain([item, 'optionalAccess', _36 => _36.type]))) reply.callsTool = true;
106
+ else if (_optionalChain([item, 'optionalAccess', _37 => _37.type]) === "message") reply.parts.push(_chunkDCKT6Y5Bcjs.textOf.call(void 0, item.content, ["output_text"]));
107
+ }
108
+ reply.done = _optionalChain([result, 'optionalAccess', _38 => _38.status]) === void 0 || _optionalChain([result, 'optionalAccess', _39 => _39.status]) === null || _optionalChain([result, 'optionalAccess', _40 => _40.status]) === "completed";
109
+ return reply;
110
+ },
111
+ feed(reply, event) {
112
+ if (_optionalChain([event, 'optionalAccess', _41 => _41.type]) === "response.output_text.delta") reply.parts.push(_nullishCoalesce(event.delta, () => ( "")));
113
+ else if (_optionalChain([event, 'optionalAccess', _42 => _42.type]) === "response.output_item.added" || _optionalChain([event, 'optionalAccess', _43 => _43.type]) === "response.output_item.done") {
114
+ reply.callsTool ||= CALLS.has(_optionalChain([event, 'access', _44 => _44.item, 'optionalAccess', _45 => _45.type]));
115
+ } else if (_optionalChain([event, 'optionalAccess', _46 => _46.type]) === "response.completed") reply.done = true;
116
+ }
117
+ };
118
+ function observed(stream, provider, done) {
119
+ const reply = new (0, _chunkDCKT6Y5Bcjs.Reply)();
120
+ let ended = false;
121
+ const end = () => {
122
+ if (!ended) {
123
+ ended = true;
124
+ done(reply);
125
+ }
126
+ };
127
+ return new Proxy(stream, {
128
+ get(target, prop) {
129
+ if (prop === Symbol.asyncIterator) {
130
+ return () => {
131
+ const inner = target[Symbol.asyncIterator]();
132
+ const iterator = {
133
+ async next() {
134
+ const step = await inner.next();
135
+ if (step.done) end();
136
+ else {
137
+ try {
138
+ provider.feed(reply, step.value);
139
+ } catch (e) {
140
+ }
141
+ }
142
+ return step;
143
+ },
144
+ return: (value2) => _nullishCoalesce(_optionalChain([inner, 'access', _47 => _47.return, 'optionalCall', _48 => _48(value2)]), () => ( Promise.resolve({ done: true, value: value2 }))),
145
+ throw: (error) => _nullishCoalesce(_optionalChain([inner, 'access', _49 => _49.throw, 'optionalCall', _50 => _50(error)]), () => ( Promise.reject(error))),
146
+ [Symbol.asyncIterator]() {
147
+ return iterator;
148
+ }
149
+ };
150
+ return iterator;
151
+ };
152
+ }
153
+ const value = Reflect.get(target, prop, target);
154
+ return typeof value === "function" ? value.bind(target) : value;
155
+ }
156
+ });
157
+ }
158
+ var Deferred = class {
159
+ constructor(start, seen) {
160
+ this.start = start;
161
+ this.seen = seen;
162
+ this.#answer().catch(() => {
163
+ });
164
+ }
165
+
166
+
167
+ #request;
168
+ #result;
169
+ #call() {
170
+ this.#request ??= this.start();
171
+ return this.#request;
172
+ }
173
+ #answer() {
174
+ this.#result ??= this.#call().then(
175
+ ({ call }) => Promise.resolve(call).then((data) => this.seen(data))
176
+ );
177
+ return this.#result;
178
+ }
179
+ then(onfulfilled, onrejected) {
180
+ return this.#answer().then(onfulfilled, onrejected);
181
+ }
182
+ catch(onrejected) {
183
+ return this.#answer().catch(onrejected);
184
+ }
185
+ finally(onfinally) {
186
+ return this.#answer().finally(onfinally);
187
+ }
188
+ async withResponse() {
189
+ const { call } = await this.#call();
190
+ const answered = await call.withResponse();
191
+ return { ...answered, data: this.seen(answered.data) };
192
+ }
193
+ async asResponse() {
194
+ const { call } = await this.#call();
195
+ return call.asResponse();
196
+ }
197
+ get [Symbol.toStringTag]() {
198
+ return "Promise";
199
+ }
200
+ };
201
+ function resource(target, provider, auto, client) {
202
+ function call(method) {
203
+ return (params, ...rest) => {
204
+ const asked = provider.asked(_nullishCoalesce(params, () => ( {})));
205
+ let saved = false;
206
+ const remember = (reply) => {
207
+ if (!saved) {
208
+ saved = true;
209
+ auto.remember(asked, reply);
210
+ }
211
+ };
212
+ const seen = (data) => {
213
+ if (_optionalChain([params, 'optionalAccess', _51 => _51.stream]) && data && typeof data === "object") {
214
+ return observed(data, provider, remember);
215
+ }
216
+ try {
217
+ remember(provider.reply(data));
218
+ } catch (e2) {
219
+ }
220
+ return data;
221
+ };
222
+ return new Deferred(async () => {
223
+ const text = await auto.lookup(asked);
224
+ return { call: target[method](text ? provider.inject(params, text) : params, ...rest) };
225
+ }, seen);
226
+ };
227
+ }
228
+ const wrapped2 = {
229
+ create: call("create"),
230
+ parse: call("parse")
231
+ };
232
+ const proxy = new Proxy(target, {
233
+ get(t, prop) {
234
+ if (prop in wrapped2) return wrapped2[prop];
235
+ if (prop === "_client") return client();
236
+ const value = Reflect.get(t, prop, t);
237
+ return typeof value === "function" ? (...args) => value.apply(proxy, args) : value;
238
+ }
239
+ });
240
+ return proxy;
241
+ }
242
+ function wrapped(target, resources, auto, rewrap) {
243
+ const made = /* @__PURE__ */ new Map();
244
+ const self = new Proxy(target, {
245
+ get(t, prop) {
246
+ if (prop === "alexein") return auto;
247
+ if (prop === "withOptions") {
248
+ return (...args) => rewrap(t.withOptions(...args));
249
+ }
250
+ const make = typeof prop === "string" ? resources[prop] : void 0;
251
+ if (make) {
252
+ if (!made.has(prop))
253
+ made.set(
254
+ prop,
255
+ make(Reflect.get(t, prop, t), () => self)
256
+ );
257
+ return made.get(prop);
258
+ }
259
+ const value = Reflect.get(t, prop, t);
260
+ return typeof value === "function" ? value.bind(t) : value;
261
+ }
262
+ });
263
+ return self;
264
+ }
265
+ function wrapAnthropic(client, memory, options) {
266
+ const auto = autoMemory(memory, options);
267
+ const rewrap = (target) => wrapped(
268
+ target,
269
+ { messages: (value, self) => resource(value, anthropicMessages, auto, self) },
270
+ auto,
271
+ rewrap
272
+ );
273
+ return rewrap(client);
274
+ }
275
+ function wrapOpenAI(client, memory, options) {
276
+ const auto = autoMemory(memory, options);
277
+ const rewrap = (target) => wrapped(
278
+ target,
279
+ {
280
+ chat: (value, self) => {
281
+ let completions;
282
+ return new Proxy(value, {
283
+ get(t, prop) {
284
+ if (prop === "completions") {
285
+ completions ??= resource(Reflect.get(t, prop, t), chatCompletions, auto, self);
286
+ return completions;
287
+ }
288
+ const inner = Reflect.get(t, prop, t);
289
+ return typeof inner === "function" ? inner.bind(t) : inner;
290
+ }
291
+ });
292
+ },
293
+ responses: (value, self) => resource(value, responsesApi, auto, self)
294
+ },
295
+ auto,
296
+ rewrap
297
+ );
298
+ return rewrap(client);
299
+ }
300
+ function autoMemory(memory, options) {
301
+ if (options) return new (0, _chunkDCKT6Y5Bcjs.AutoMemory)(memory, options);
302
+ if (memory && "userId" in memory) return new (0, _chunkDCKT6Y5Bcjs.AutoMemory)(void 0, memory);
303
+ throw new TypeError("Alexein needs to know whose memory this is: pass { userId }");
304
+ }
305
+ function memoryOf(client) {
306
+ const auto = _optionalChain([client, 'optionalAccess', _52 => _52.alexein]);
307
+ if (!(auto instanceof _chunkDCKT6Y5Bcjs.AutoMemory))
308
+ throw new TypeError("not a client wrapAnthropic or wrapOpenAI answered");
309
+ return auto;
310
+ }
311
+
312
+
313
+
314
+
315
+
316
+
317
+
318
+ exports.AutoMemory = _chunkDCKT6Y5Bcjs.AutoMemory; exports.HEADER = _chunkDCKT6Y5Bcjs.HEADER; exports.memoryBlock = _chunkDCKT6Y5Bcjs.memoryBlock; exports.memoryOf = memoryOf; exports.wrapAnthropic = wrapAnthropic; exports.wrapOpenAI = wrapOpenAI;