@abassey/aid 0.1.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.
Files changed (53) hide show
  1. package/dist/agents/index.cjs +741 -0
  2. package/dist/agents/index.d.cts +78 -0
  3. package/dist/agents/index.d.ts +78 -0
  4. package/dist/agents/index.js +741 -0
  5. package/dist/ai-AWJOUXFM.js +9 -0
  6. package/dist/ai-DOAYJKKI.cjs +9 -0
  7. package/dist/chunk-2TNYBUNK.js +124 -0
  8. package/dist/chunk-3LGKZRGY.cjs +124 -0
  9. package/dist/chunk-AUR2BBB5.cjs +1436 -0
  10. package/dist/chunk-IJLTRQF4.cjs +276 -0
  11. package/dist/chunk-JPD7UBAZ.js +58 -0
  12. package/dist/chunk-M4RQALTT.js +276 -0
  13. package/dist/chunk-NB65IHJE.cjs +58 -0
  14. package/dist/chunk-YNIEOBDF.js +1436 -0
  15. package/dist/client/index.cjs +18 -0
  16. package/dist/client/index.d.cts +8 -0
  17. package/dist/client/index.d.ts +8 -0
  18. package/dist/client/index.js +18 -0
  19. package/dist/errors-CUVTnseb.d.ts +13 -0
  20. package/dist/errors-CgCce4cK.d.cts +158 -0
  21. package/dist/errors-CgCce4cK.d.ts +158 -0
  22. package/dist/errors-zAPbTlpe.d.cts +13 -0
  23. package/dist/eval/index.cjs +308 -0
  24. package/dist/eval/index.d.cts +106 -0
  25. package/dist/eval/index.d.ts +106 -0
  26. package/dist/eval/index.js +308 -0
  27. package/dist/index.cjs +35 -0
  28. package/dist/index.d.cts +107 -0
  29. package/dist/index.d.ts +107 -0
  30. package/dist/index.js +35 -0
  31. package/dist/middleware/index.cjs +201 -0
  32. package/dist/middleware/index.d.cts +36 -0
  33. package/dist/middleware/index.d.ts +36 -0
  34. package/dist/middleware/index.js +201 -0
  35. package/dist/observability/index.cjs +147 -0
  36. package/dist/observability/index.d.cts +30 -0
  37. package/dist/observability/index.d.ts +30 -0
  38. package/dist/observability/index.js +147 -0
  39. package/dist/react/index.cjs +253 -0
  40. package/dist/react/index.d.cts +64 -0
  41. package/dist/react/index.d.ts +64 -0
  42. package/dist/react/index.js +253 -0
  43. package/dist/serve/index.cjs +545 -0
  44. package/dist/serve/index.d.cts +69 -0
  45. package/dist/serve/index.d.ts +69 -0
  46. package/dist/serve/index.js +545 -0
  47. package/dist/types-BJReASS-.d.cts +196 -0
  48. package/dist/types-BJReASS-.d.ts +196 -0
  49. package/dist/types-CguX3F16.d.cts +173 -0
  50. package/dist/types-CrFH-_qp.d.cts +68 -0
  51. package/dist/types-DvdzPmW0.d.ts +173 -0
  52. package/dist/types-qfE32ADy.d.ts +68 -0
  53. package/package.json +144 -0
@@ -0,0 +1,147 @@
1
+ import {
2
+ InMemoryTraceStore,
3
+ globalTraceStore,
4
+ traceContext
5
+ } from "../chunk-JPD7UBAZ.js";
6
+
7
+ // src/observability/trace.ts
8
+ async function trace(name, fn, options) {
9
+ const id = crypto.randomUUID();
10
+ const startTime = Date.now();
11
+ const metadata = { ...options?.metadata ?? {} };
12
+ const parent = traceContext.getStore();
13
+ const activeSpan = {
14
+ get id() {
15
+ return id;
16
+ },
17
+ get name() {
18
+ return name;
19
+ },
20
+ annotate(key, value) {
21
+ metadata[key] = value;
22
+ }
23
+ };
24
+ try {
25
+ const result = await traceContext.run(
26
+ activeSpan,
27
+ () => fn(activeSpan)
28
+ );
29
+ const endTime = Date.now();
30
+ globalTraceStore.add({
31
+ id,
32
+ parentId: parent?.id,
33
+ name,
34
+ startTime,
35
+ endTime,
36
+ durationMs: endTime - startTime,
37
+ model: "trace",
38
+ provider: "trace",
39
+ tokens: { input: 0, output: 0, total: 0 },
40
+ cost: 0,
41
+ status: "ok",
42
+ metadata
43
+ });
44
+ return result;
45
+ } catch (error) {
46
+ const endTime = Date.now();
47
+ globalTraceStore.add({
48
+ id,
49
+ parentId: parent?.id,
50
+ name,
51
+ startTime,
52
+ endTime,
53
+ durationMs: endTime - startTime,
54
+ model: "trace",
55
+ provider: "trace",
56
+ tokens: { input: 0, output: 0, total: 0 },
57
+ cost: 0,
58
+ status: "error",
59
+ error: {
60
+ message: error instanceof Error ? error.message : String(error)
61
+ },
62
+ metadata
63
+ });
64
+ throw error;
65
+ }
66
+ }
67
+
68
+ // src/observability/cost-tracker.ts
69
+ function resolvePeriod(period) {
70
+ if (typeof period === "object" && "from" in period) {
71
+ return period;
72
+ }
73
+ const now = Date.now();
74
+ const d = new Date(now);
75
+ const todayMidnight = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
76
+ switch (period) {
77
+ case "today":
78
+ return { from: todayMidnight, to: now };
79
+ case "yesterday": {
80
+ const yesterdayMidnight = todayMidnight - 24 * 60 * 60 * 1e3;
81
+ return { from: yesterdayMidnight, to: todayMidnight };
82
+ }
83
+ case "this-week": {
84
+ const dayOfWeek = d.getUTCDay();
85
+ const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
86
+ const mondayMidnight = todayMidnight - daysToMonday * 24 * 60 * 60 * 1e3;
87
+ return { from: mondayMidnight, to: now };
88
+ }
89
+ case "this-month": {
90
+ const monthStart = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1);
91
+ return { from: monthStart, to: now };
92
+ }
93
+ }
94
+ }
95
+ var CostTracker = class {
96
+ constructor(store) {
97
+ this.store = store;
98
+ }
99
+ report(period) {
100
+ const { from, to } = resolvePeriod(period);
101
+ const spans = this.store.list({ from, to }).filter((s) => s.model !== "trace");
102
+ const totalTokens = { input: 0, output: 0, total: 0 };
103
+ let totalCost = 0;
104
+ const byModel = {};
105
+ const byProvider = {};
106
+ for (const span of spans) {
107
+ totalCost += span.cost;
108
+ totalTokens.input += span.tokens.input;
109
+ totalTokens.output += span.tokens.output;
110
+ totalTokens.total += span.tokens.total;
111
+ if (!byModel[span.model]) {
112
+ byModel[span.model] = {
113
+ cost: 0,
114
+ calls: 0,
115
+ tokens: { input: 0, output: 0, total: 0 }
116
+ };
117
+ }
118
+ byModel[span.model].cost += span.cost;
119
+ byModel[span.model].calls += 1;
120
+ byModel[span.model].tokens.input += span.tokens.input;
121
+ byModel[span.model].tokens.output += span.tokens.output;
122
+ byModel[span.model].tokens.total += span.tokens.total;
123
+ if (!byProvider[span.provider]) {
124
+ byProvider[span.provider] = { cost: 0, calls: 0 };
125
+ }
126
+ byProvider[span.provider].cost += span.cost;
127
+ byProvider[span.provider].calls += 1;
128
+ }
129
+ return {
130
+ totalCost,
131
+ totalTokens,
132
+ calls: spans.length,
133
+ byModel,
134
+ byProvider,
135
+ period: { from, to }
136
+ };
137
+ }
138
+ };
139
+ function costReport(period) {
140
+ return new CostTracker(globalTraceStore).report(period);
141
+ }
142
+ export {
143
+ CostTracker,
144
+ InMemoryTraceStore,
145
+ costReport,
146
+ trace
147
+ };
@@ -0,0 +1,253 @@
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
+ var _chunkIJLTRQF4cjs = require('../chunk-IJLTRQF4.cjs');
5
+
6
+ // src/react/context.ts
7
+ var _react = require('react');
8
+
9
+ var AidContext = _react.createContext.call(void 0, null);
10
+ function AidProvider({ baseUrl, client, children }) {
11
+ const aidClient = _react.useMemo.call(void 0, () => {
12
+ if (client) return client;
13
+ if (baseUrl) return new (0, _chunkIJLTRQF4cjs.AidClient)({ baseUrl });
14
+ throw new Error("AidProvider requires either baseUrl or client prop");
15
+ }, [baseUrl, client]);
16
+ return _react.createElement.call(void 0, AidContext.Provider, { value: aidClient }, children);
17
+ }
18
+ function useAidClient() {
19
+ const client = _react.useContext.call(void 0, AidContext);
20
+ if (!client) {
21
+ throw new Error("useAidClient must be used within an AidProvider");
22
+ }
23
+ return client;
24
+ }
25
+
26
+ // src/react/use-ai.ts
27
+
28
+ function useAi(initialPrompt, options) {
29
+ const client = useAidClient();
30
+ const [data, setData] = _react.useState.call(void 0, null);
31
+ const [loading, setLoading] = _react.useState.call(void 0, false);
32
+ const [error, setError] = _react.useState.call(void 0, null);
33
+ const abortRef = _react.useRef.call(void 0, null);
34
+ const run = _react.useCallback.call(void 0,
35
+ async (prompt, runOptions) => {
36
+ _optionalChain([abortRef, 'access', _ => _.current, 'optionalAccess', _2 => _2.abort, 'call', _3 => _3()]);
37
+ const controller = new AbortController();
38
+ abortRef.current = controller;
39
+ setLoading(true);
40
+ setError(null);
41
+ try {
42
+ const response = await client.ai(prompt, { ...options, ...runOptions, signal: controller.signal });
43
+ if (!controller.signal.aborted) {
44
+ setData(response);
45
+ }
46
+ } catch (err) {
47
+ if (!controller.signal.aborted) {
48
+ setData(null);
49
+ setError(err);
50
+ }
51
+ } finally {
52
+ if (!controller.signal.aborted) {
53
+ setLoading(false);
54
+ }
55
+ }
56
+ },
57
+ [client, options]
58
+ );
59
+ _react.useEffect.call(void 0, () => {
60
+ if (initialPrompt) {
61
+ run(initialPrompt);
62
+ }
63
+ }, [initialPrompt]);
64
+ _react.useEffect.call(void 0, () => {
65
+ return () => {
66
+ _optionalChain([abortRef, 'access', _4 => _4.current, 'optionalAccess', _5 => _5.abort, 'call', _6 => _6()]);
67
+ };
68
+ }, []);
69
+ return { data, loading, error, run };
70
+ }
71
+
72
+ // src/react/use-stream.ts
73
+
74
+ function useStream() {
75
+ const client = useAidClient();
76
+ const [text, setText] = _react.useState.call(void 0, "");
77
+ const [loading, setLoading] = _react.useState.call(void 0, false);
78
+ const [error, setError] = _react.useState.call(void 0, null);
79
+ const [tokens, setTokens] = _react.useState.call(void 0, null);
80
+ const [cost, setCost] = _react.useState.call(void 0, null);
81
+ const abortRef = _react.useRef.call(void 0, null);
82
+ const stop = _react.useCallback.call(void 0, () => {
83
+ _optionalChain([abortRef, 'access', _7 => _7.current, 'optionalAccess', _8 => _8.abort, 'call', _9 => _9()]);
84
+ abortRef.current = null;
85
+ setLoading(false);
86
+ }, []);
87
+ const start = _react.useCallback.call(void 0,
88
+ (prompt, options) => {
89
+ _optionalChain([abortRef, 'access', _10 => _10.current, 'optionalAccess', _11 => _11.abort, 'call', _12 => _12()]);
90
+ const controller = new AbortController();
91
+ abortRef.current = controller;
92
+ setText("");
93
+ setError(null);
94
+ setTokens(null);
95
+ setCost(null);
96
+ setLoading(true);
97
+ (async () => {
98
+ try {
99
+ for await (const chunk of client.stream(prompt, { ...options, signal: controller.signal })) {
100
+ if (controller.signal.aborted) break;
101
+ if (chunk.type === "text") {
102
+ setText(chunk.text);
103
+ } else if (chunk.type === "done") {
104
+ setText(chunk.text);
105
+ if (chunk.tokens) setTokens(chunk.tokens);
106
+ if (chunk.cost != null) setCost(chunk.cost);
107
+ } else if (chunk.type === "error") {
108
+ setError(new (0, _chunkIJLTRQF4cjs.AidClientError)(_nullishCoalesce(chunk.code, () => ( "unknown")), _nullishCoalesce(chunk.message, () => ( "Stream error")), 0));
109
+ }
110
+ }
111
+ } catch (err) {
112
+ if (!controller.signal.aborted) {
113
+ setError(err);
114
+ }
115
+ } finally {
116
+ if (!controller.signal.aborted) {
117
+ setLoading(false);
118
+ }
119
+ }
120
+ })();
121
+ },
122
+ [client]
123
+ );
124
+ _react.useEffect.call(void 0, () => {
125
+ return () => {
126
+ _optionalChain([abortRef, 'access', _13 => _13.current, 'optionalAccess', _14 => _14.abort, 'call', _15 => _15()]);
127
+ };
128
+ }, []);
129
+ return { text, loading, start, stop, tokens, cost, error };
130
+ }
131
+
132
+ // src/react/use-chat.ts
133
+
134
+ var idCounter = 0;
135
+ function generateId() {
136
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
137
+ return crypto.randomUUID();
138
+ }
139
+ return `msg-${++idCounter}`;
140
+ }
141
+ function useChat(options) {
142
+ const client = useAidClient();
143
+ const [messages, setMessages] = _react.useState.call(void 0, []);
144
+ const [loading, setLoading] = _react.useState.call(void 0, false);
145
+ const [error, setError] = _react.useState.call(void 0, null);
146
+ const [input, setInput] = _react.useState.call(void 0, "");
147
+ const chatRef = _react.useRef.call(void 0, null);
148
+ const getChat = _react.useCallback.call(void 0, () => {
149
+ if (!chatRef.current) {
150
+ chatRef.current = client.chat(options);
151
+ }
152
+ return chatRef.current;
153
+ }, [client, options]);
154
+ const send = _react.useCallback.call(void 0,
155
+ async (message) => {
156
+ const chat = getChat();
157
+ const userMsg = { role: "user", content: message, id: generateId() };
158
+ setMessages((prev) => [...prev, userMsg]);
159
+ setLoading(true);
160
+ setError(null);
161
+ try {
162
+ const response = await chat.send(message);
163
+ const assistantMsg = { role: "assistant", content: response.text, id: generateId() };
164
+ setMessages((prev) => [...prev, assistantMsg]);
165
+ } catch (err) {
166
+ setError(err);
167
+ } finally {
168
+ setLoading(false);
169
+ }
170
+ },
171
+ [getChat]
172
+ );
173
+ const clear = _react.useCallback.call(void 0, () => {
174
+ setMessages([]);
175
+ setError(null);
176
+ setInput("");
177
+ if (chatRef.current) {
178
+ chatRef.current.destroy().catch(() => {
179
+ });
180
+ chatRef.current = null;
181
+ }
182
+ }, []);
183
+ _react.useEffect.call(void 0, () => {
184
+ return () => {
185
+ _optionalChain([chatRef, 'access', _16 => _16.current, 'optionalAccess', _17 => _17.destroy, 'call', _18 => _18(), 'access', _19 => _19.catch, 'call', _20 => _20(() => {
186
+ })]);
187
+ };
188
+ }, []);
189
+ return { messages, send, loading, error, input, setInput, clear };
190
+ }
191
+
192
+ // src/react/use-agent.ts
193
+
194
+ function useAgent(agentName) {
195
+ const client = useAidClient();
196
+ const [result, setResult] = _react.useState.call(void 0, null);
197
+ const [steps, setSteps] = _react.useState.call(void 0, []);
198
+ const [loading, setLoading] = _react.useState.call(void 0, false);
199
+ const [error, setError] = _react.useState.call(void 0, null);
200
+ const abortRef = _react.useRef.call(void 0, null);
201
+ const run = _react.useCallback.call(void 0,
202
+ (task) => {
203
+ _optionalChain([abortRef, 'access', _21 => _21.current, 'optionalAccess', _22 => _22.abort, 'call', _23 => _23()]);
204
+ const controller = new AbortController();
205
+ abortRef.current = controller;
206
+ setResult(null);
207
+ setSteps([]);
208
+ setError(null);
209
+ setLoading(true);
210
+ (async () => {
211
+ try {
212
+ for await (const event of client.agentStream(agentName, task, { signal: controller.signal })) {
213
+ if (controller.signal.aborted) break;
214
+ if (event.type === "done") {
215
+ setResult({
216
+ text: _nullishCoalesce(event.text, () => ( "")),
217
+ model: "",
218
+ tokens: _nullishCoalesce(event.tokens, () => ( { input: 0, output: 0, total: 0 })),
219
+ cost: _nullishCoalesce(event.cost, () => ( 0)),
220
+ steps: _nullishCoalesce(event.steps, () => ( 0))
221
+ });
222
+ } else {
223
+ setSteps((prev) => [...prev, event]);
224
+ }
225
+ }
226
+ } catch (err) {
227
+ if (!controller.signal.aborted) {
228
+ setError(err);
229
+ }
230
+ } finally {
231
+ if (!controller.signal.aborted) {
232
+ setLoading(false);
233
+ }
234
+ }
235
+ })();
236
+ },
237
+ [client, agentName]
238
+ );
239
+ _react.useEffect.call(void 0, () => {
240
+ return () => {
241
+ _optionalChain([abortRef, 'access', _24 => _24.current, 'optionalAccess', _25 => _25.abort, 'call', _26 => _26()]);
242
+ };
243
+ }, []);
244
+ return { result, steps, loading, error, run };
245
+ }
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+ exports.AidProvider = AidProvider; exports.useAgent = useAgent; exports.useAi = useAi; exports.useAidClient = useAidClient; exports.useChat = useChat; exports.useStream = useStream;
@@ -0,0 +1,64 @@
1
+ import * as react from 'react';
2
+ import { A as AidClient, a as AgentResponse, b as AgentStreamEvent, e as AidClientError, d as AiResponse, c as AiRequest } from '../errors-CgCce4cK.cjs';
3
+
4
+ interface UseAiReturn {
5
+ data: AiResponse | null;
6
+ loading: boolean;
7
+ error: AidClientError | null;
8
+ run: (prompt: string, options?: Partial<AiRequest>) => Promise<void>;
9
+ }
10
+ interface UseChatMessage {
11
+ role: "user" | "assistant";
12
+ content: string;
13
+ id: string;
14
+ }
15
+ interface UseChatReturn {
16
+ messages: UseChatMessage[];
17
+ send: (message: string) => Promise<void>;
18
+ loading: boolean;
19
+ error: AidClientError | null;
20
+ input: string;
21
+ setInput: (value: string) => void;
22
+ clear: () => void;
23
+ }
24
+ interface UseStreamReturn {
25
+ text: string;
26
+ loading: boolean;
27
+ start: (prompt: string, options?: Partial<AiRequest>) => void;
28
+ stop: () => void;
29
+ tokens: {
30
+ input: number;
31
+ output: number;
32
+ total: number;
33
+ } | null;
34
+ cost: number | null;
35
+ error: AidClientError | null;
36
+ }
37
+ interface UseAgentReturn {
38
+ result: AgentResponse | null;
39
+ steps: AgentStreamEvent[];
40
+ loading: boolean;
41
+ error: AidClientError | null;
42
+ run: (task: string) => void;
43
+ }
44
+ interface AidProviderProps {
45
+ baseUrl?: string;
46
+ client?: AidClient;
47
+ children: React.ReactNode;
48
+ }
49
+
50
+ declare function AidProvider({ baseUrl, client, children }: AidProviderProps): react.FunctionComponentElement<react.ProviderProps<AidClient | null>>;
51
+ declare function useAidClient(): AidClient;
52
+
53
+ declare function useAi(initialPrompt?: string, options?: Partial<AiRequest>): UseAiReturn;
54
+
55
+ declare function useStream(): UseStreamReturn;
56
+
57
+ declare function useChat(options?: {
58
+ system?: string;
59
+ model?: string;
60
+ }): UseChatReturn;
61
+
62
+ declare function useAgent(agentName: string): UseAgentReturn;
63
+
64
+ export { AidProvider, type AidProviderProps, type UseAgentReturn, type UseAiReturn, type UseChatMessage, type UseChatReturn, type UseStreamReturn, useAgent, useAi, useAidClient, useChat, useStream };
@@ -0,0 +1,64 @@
1
+ import * as react from 'react';
2
+ import { A as AidClient, a as AgentResponse, b as AgentStreamEvent, e as AidClientError, d as AiResponse, c as AiRequest } from '../errors-CgCce4cK.js';
3
+
4
+ interface UseAiReturn {
5
+ data: AiResponse | null;
6
+ loading: boolean;
7
+ error: AidClientError | null;
8
+ run: (prompt: string, options?: Partial<AiRequest>) => Promise<void>;
9
+ }
10
+ interface UseChatMessage {
11
+ role: "user" | "assistant";
12
+ content: string;
13
+ id: string;
14
+ }
15
+ interface UseChatReturn {
16
+ messages: UseChatMessage[];
17
+ send: (message: string) => Promise<void>;
18
+ loading: boolean;
19
+ error: AidClientError | null;
20
+ input: string;
21
+ setInput: (value: string) => void;
22
+ clear: () => void;
23
+ }
24
+ interface UseStreamReturn {
25
+ text: string;
26
+ loading: boolean;
27
+ start: (prompt: string, options?: Partial<AiRequest>) => void;
28
+ stop: () => void;
29
+ tokens: {
30
+ input: number;
31
+ output: number;
32
+ total: number;
33
+ } | null;
34
+ cost: number | null;
35
+ error: AidClientError | null;
36
+ }
37
+ interface UseAgentReturn {
38
+ result: AgentResponse | null;
39
+ steps: AgentStreamEvent[];
40
+ loading: boolean;
41
+ error: AidClientError | null;
42
+ run: (task: string) => void;
43
+ }
44
+ interface AidProviderProps {
45
+ baseUrl?: string;
46
+ client?: AidClient;
47
+ children: React.ReactNode;
48
+ }
49
+
50
+ declare function AidProvider({ baseUrl, client, children }: AidProviderProps): react.FunctionComponentElement<react.ProviderProps<AidClient | null>>;
51
+ declare function useAidClient(): AidClient;
52
+
53
+ declare function useAi(initialPrompt?: string, options?: Partial<AiRequest>): UseAiReturn;
54
+
55
+ declare function useStream(): UseStreamReturn;
56
+
57
+ declare function useChat(options?: {
58
+ system?: string;
59
+ model?: string;
60
+ }): UseChatReturn;
61
+
62
+ declare function useAgent(agentName: string): UseAgentReturn;
63
+
64
+ export { AidProvider, type AidProviderProps, type UseAgentReturn, type UseAiReturn, type UseChatMessage, type UseChatReturn, type UseStreamReturn, useAgent, useAi, useAidClient, useChat, useStream };