@hilbras/sdk 3.5.0 → 3.6.1

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 (36) hide show
  1. package/README.md +17 -10
  2. package/dist/core/execution/request-pipeline.js +138 -73
  3. package/dist/features/agent/plan-and-execute.js +1 -1
  4. package/dist/features/agent/react.js +1 -1
  5. package/dist/features/agent/tool-loop.js +1 -1
  6. package/dist/frameworks/angular/angular-shim.d.ts +1 -1
  7. package/dist/frameworks/angular/angular-shim.js +1 -1
  8. package/dist/frameworks/angular/chat.service.js +1 -1
  9. package/dist/frameworks/angular/completion.service.js +1 -1
  10. package/dist/frameworks/angular/object.service.js +1 -1
  11. package/dist/frameworks/nextjs/server.js +1 -1
  12. package/dist/frameworks/react-client/index.d.ts +35 -0
  13. package/dist/frameworks/react-client/index.js +31 -0
  14. package/dist/frameworks/react-client/provider.d.ts +45 -0
  15. package/dist/frameworks/react-client/provider.js +40 -0
  16. package/dist/frameworks/react-client/use-chat.d.ts +85 -0
  17. package/dist/frameworks/react-client/use-chat.js +202 -0
  18. package/dist/frameworks/react-client/use-completion.d.ts +66 -0
  19. package/dist/frameworks/react-client/use-completion.js +117 -0
  20. package/dist/frameworks/react-client/use-cost.d.ts +62 -0
  21. package/dist/frameworks/react-client/use-cost.js +68 -0
  22. package/dist/frameworks/svelte/use-chat.js +1 -1
  23. package/dist/frameworks/vue/use-chat.js +1 -1
  24. package/dist/security/audit-logger.d.ts +7 -1
  25. package/dist/security/audit-logger.js +7 -5
  26. package/dist/security/pii-guard.js +21 -1
  27. package/dist/security/prompt-injection-guard.js +1 -1
  28. package/dist/security/rate-limiter.d.ts +2 -0
  29. package/dist/security/rate-limiter.js +8 -1
  30. package/dist/security/rbac.js +2 -2
  31. package/dist/security/request-signer.d.ts +2 -0
  32. package/dist/security/request-signer.js +3 -1
  33. package/dist/security/url-guard.d.ts +1 -1
  34. package/dist/security/url-guard.js +4 -3
  35. package/dist/utils/sse-writer.js +1 -1
  36. package/package.json +9 -3
@@ -0,0 +1,45 @@
1
+ import { type ReactNode } from "react";
2
+ import { HilbrasClient, type HilbrasClientConfig } from "../../client/client.js";
3
+ interface HilbrasContextValue {
4
+ client: HilbrasClient;
5
+ }
6
+ export interface HilbrasProviderProps {
7
+ children: ReactNode;
8
+ /**
9
+ * HilbrasClient config — creates a new client if not provided.
10
+ *
11
+ * @warning Passing an API key here bundles it into your client-side
12
+ * JavaScript, where anyone can read it. In a browser this is a public secret.
13
+ * Prefer passing a server-created `client` down from a Server Component, or
14
+ * use the route-based hooks in `@hilbras/sdk/react` instead.
15
+ */
16
+ config?: HilbrasClientConfig;
17
+ /**
18
+ * Pre-existing client instance (overrides config).
19
+ *
20
+ * Build this on the server and pass it in, so no credential is serialised
21
+ * into the browser bundle.
22
+ */
23
+ client?: HilbrasClient;
24
+ }
25
+ /**
26
+ * HilbrasProvider — wraps your app and provides a shared HilbrasClient.
27
+ *
28
+ * @warning The client this provides calls providers **from the browser**. For a
29
+ * public app, use `@hilbras/sdk/react`'s route-based `useChat` with
30
+ * `createChatHandler` from `@hilbras/sdk/nextjs` so the key stays on your
31
+ * server. See `@hilbras/sdk/react-client` for when this is appropriate.
32
+ *
33
+ * @example
34
+ * ```tsx
35
+ * <HilbrasProvider client={client}>
36
+ * <App />
37
+ * </HilbrasProvider>
38
+ * ```
39
+ */
40
+ export declare function HilbrasProvider({ children, config, client: existingClient }: HilbrasProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<HilbrasContextValue | null>>;
41
+ /**
42
+ * Access the shared HilbrasClient from the nearest HilbrasProvider.
43
+ */
44
+ export declare function useHilbrasClient(): HilbrasClient;
45
+ export {};
@@ -0,0 +1,40 @@
1
+ "use client";
2
+ import { createContext, createElement, useContext, useMemo } from "react";
3
+ import { HilbrasClient } from "../../client/client.js";
4
+ const HilbrasContext = createContext(null);
5
+ /**
6
+ * HilbrasProvider — wraps your app and provides a shared HilbrasClient.
7
+ *
8
+ * @warning The client this provides calls providers **from the browser**. For a
9
+ * public app, use `@hilbras/sdk/react`'s route-based `useChat` with
10
+ * `createChatHandler` from `@hilbras/sdk/nextjs` so the key stays on your
11
+ * server. See `@hilbras/sdk/react-client` for when this is appropriate.
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * <HilbrasProvider client={client}>
16
+ * <App />
17
+ * </HilbrasProvider>
18
+ * ```
19
+ */
20
+ export function HilbrasProvider({ children, config, client: existingClient }) {
21
+ const value = useMemo(() => {
22
+ const client = existingClient ?? new HilbrasClient(config);
23
+ return { client };
24
+ }, [existingClient, config]);
25
+ // `createElement` rather than JSX: the SDK ships no `.tsx` and its tsconfig has
26
+ // no `--jsx`, matching how `src/frameworks/react/generative-ui.ts` builds
27
+ // elements. Enabling JSX for one file would change the build for all of src.
28
+ return createElement(HilbrasContext.Provider, { value }, children);
29
+ }
30
+ /**
31
+ * Access the shared HilbrasClient from the nearest HilbrasProvider.
32
+ */
33
+ export function useHilbrasClient() {
34
+ const ctx = useContext(HilbrasContext);
35
+ if (!ctx) {
36
+ throw new Error("useHilbrasClient must be used within a <HilbrasProvider>. " +
37
+ "Wrap your app with <HilbrasProvider config={...}> or pass a client directly.");
38
+ }
39
+ return ctx.client;
40
+ }
@@ -0,0 +1,85 @@
1
+ export interface ChatMessage {
2
+ id: string;
3
+ role: "user" | "assistant" | "system";
4
+ content: string;
5
+ timestamp: number;
6
+ provider?: string;
7
+ model?: string;
8
+ tokens?: {
9
+ input: number;
10
+ output: number;
11
+ total: number;
12
+ };
13
+ cost?: number;
14
+ }
15
+ export interface UseChatOptions {
16
+ /** Provider name */
17
+ provider: string;
18
+ /** Model ID */
19
+ model: string;
20
+ /** System prompt */
21
+ systemPrompt?: string;
22
+ /** Initial messages */
23
+ initialMessages?: ChatMessage[];
24
+ /** Max messages to keep in context (older messages trimmed) */
25
+ maxContextMessages?: number;
26
+ /** Called on each text chunk during streaming */
27
+ onChunk?: (chunk: {
28
+ text: string;
29
+ accumulated: string;
30
+ }) => void;
31
+ /** Called when a message completes */
32
+ onComplete?: (message: ChatMessage) => void;
33
+ /** Called on error */
34
+ onError?: (error: Error) => void;
35
+ }
36
+ export interface UseChatReturn {
37
+ /** Chat messages */
38
+ messages: ChatMessage[];
39
+ /** Current input value */
40
+ input: string;
41
+ /** Set input value */
42
+ setInput: (value: string) => void;
43
+ /** Send a message (uses current input) */
44
+ handleSubmit: (e?: React.FormEvent) => Promise<void>;
45
+ /** Send an arbitrary message */
46
+ sendMessage: (content: string) => Promise<void>;
47
+ /** Whether a response is being generated */
48
+ isLoading: boolean;
49
+ /** Whether streaming is in progress */
50
+ isStreaming: boolean;
51
+ /** Current error (if any) */
52
+ error: Error | null;
53
+ /** Abort the current request */
54
+ stop: () => void;
55
+ /** Clear all messages */
56
+ clear: () => void;
57
+ /** Retry the last message */
58
+ retry: () => Promise<void>;
59
+ /** Total tokens used */
60
+ totalTokens: number;
61
+ /** Total cost */
62
+ totalCost: number;
63
+ }
64
+ /**
65
+ * useChat — streaming chat hook for React.
66
+ *
67
+ * @example
68
+ * ```tsx
69
+ * function Chat() {
70
+ * const { messages, input, setInput, handleSubmit, isLoading } = useChat({
71
+ * provider: "openai",
72
+ * model: "gpt-4o",
73
+ * });
74
+ *
75
+ * return (
76
+ * <div>
77
+ * {messages.map(m => <div key={m.id}>{m.content}</div>)}
78
+ * <input value={input} onChange={e => setInput(e.target.value)} />
79
+ * <button onClick={handleSubmit} disabled={isLoading}>Send</button>
80
+ * </div>
81
+ * );
82
+ * }
83
+ * ```
84
+ */
85
+ export declare function useChat(options: UseChatOptions): UseChatReturn;
@@ -0,0 +1,202 @@
1
+ "use client";
2
+ import { useState, useCallback, useRef, useEffect } from "react";
3
+ import { useHilbrasClient } from "./provider.js";
4
+ let _idCounter = 0;
5
+ function nextId() {
6
+ return `msg_${Date.now()}_${++_idCounter}`;
7
+ }
8
+ /**
9
+ * useChat — streaming chat hook for React.
10
+ *
11
+ * @example
12
+ * ```tsx
13
+ * function Chat() {
14
+ * const { messages, input, setInput, handleSubmit, isLoading } = useChat({
15
+ * provider: "openai",
16
+ * model: "gpt-4o",
17
+ * });
18
+ *
19
+ * return (
20
+ * <div>
21
+ * {messages.map(m => <div key={m.id}>{m.content}</div>)}
22
+ * <input value={input} onChange={e => setInput(e.target.value)} />
23
+ * <button onClick={handleSubmit} disabled={isLoading}>Send</button>
24
+ * </div>
25
+ * );
26
+ * }
27
+ * ```
28
+ */
29
+ export function useChat(options) {
30
+ const { provider, model, systemPrompt, initialMessages, maxContextMessages = 50, onChunk, onComplete, onError } = options;
31
+ const client = useHilbrasClient();
32
+ const [messages, setMessages] = useState(initialMessages ?? []);
33
+ const [input, setInput] = useState("");
34
+ const [isLoading, setIsLoading] = useState(false);
35
+ const [isStreaming, setIsStreaming] = useState(false);
36
+ const [error, setError] = useState(null);
37
+ const [totalTokens, setTotalTokens] = useState(0);
38
+ const [totalCost, setTotalCost] = useState(0);
39
+ const abortRef = useRef(null);
40
+ const lastUserMessageRef = useRef("");
41
+ // Cleanup on unmount
42
+ useEffect(() => {
43
+ return () => {
44
+ abortRef.current?.abort();
45
+ };
46
+ }, []);
47
+ const stop = useCallback(() => {
48
+ abortRef.current?.abort();
49
+ abortRef.current = null;
50
+ setIsLoading(false);
51
+ setIsStreaming(false);
52
+ }, []);
53
+ const clear = useCallback(() => {
54
+ stop();
55
+ setMessages([]);
56
+ setError(null);
57
+ setTotalTokens(0);
58
+ setTotalCost(0);
59
+ }, [stop]);
60
+ const sendMessage = useCallback(async (content) => {
61
+ if (!content.trim() || isLoading)
62
+ return;
63
+ const userMessage = {
64
+ id: nextId(),
65
+ role: "user",
66
+ content: content.trim(),
67
+ timestamp: Date.now(),
68
+ };
69
+ lastUserMessageRef.current = content.trim();
70
+ setMessages((prev) => {
71
+ const updated = [...prev, userMessage];
72
+ // Trim context window
73
+ if (updated.length > maxContextMessages + 1) {
74
+ return updated.slice(-maxContextMessages);
75
+ }
76
+ return updated;
77
+ });
78
+ setInput("");
79
+ setIsLoading(true);
80
+ setIsStreaming(true);
81
+ setError(null);
82
+ const controller = new AbortController();
83
+ abortRef.current = controller;
84
+ try {
85
+ // Build message array for the API
86
+ const apiMessages = [];
87
+ if (systemPrompt) {
88
+ apiMessages.push({ role: "system", content: systemPrompt });
89
+ }
90
+ // Add context messages (all except the latest user message)
91
+ const contextMessages = messages.slice(-maxContextMessages);
92
+ for (const msg of contextMessages) {
93
+ apiMessages.push({ role: msg.role, content: msg.content });
94
+ }
95
+ apiMessages.push({ role: "user", content: userMessage.content });
96
+ let assistantContent = "";
97
+ let inputTokens = 0;
98
+ let outputTokens = 0;
99
+ for await (const chunk of client.stream({
100
+ messages: apiMessages,
101
+ model,
102
+ provider,
103
+ signal: controller.signal,
104
+ })) {
105
+ if (chunk.type === "text") {
106
+ assistantContent += chunk.text;
107
+ setMessages((prev) => {
108
+ const updated = [...prev];
109
+ const last = updated[updated.length - 1];
110
+ if (last && last.role === "assistant") {
111
+ updated[updated.length - 1] = { ...last, content: assistantContent };
112
+ }
113
+ else {
114
+ updated.push({
115
+ id: nextId(),
116
+ role: "assistant",
117
+ content: assistantContent,
118
+ timestamp: Date.now(),
119
+ provider,
120
+ model,
121
+ });
122
+ }
123
+ return updated;
124
+ });
125
+ onChunk?.({ text: chunk.text, accumulated: assistantContent });
126
+ }
127
+ if (chunk.type === "usage") {
128
+ inputTokens = chunk.inputTokens ?? 0;
129
+ outputTokens = chunk.outputTokens ?? 0;
130
+ }
131
+ }
132
+ // Finalize message with token counts
133
+ const finalMessage = {
134
+ id: nextId(),
135
+ role: "assistant",
136
+ content: assistantContent,
137
+ timestamp: Date.now(),
138
+ provider,
139
+ model,
140
+ tokens: { input: inputTokens, output: outputTokens, total: inputTokens + outputTokens },
141
+ };
142
+ setMessages((prev) => {
143
+ const updated = [...prev];
144
+ // Replace the streaming message with the final one
145
+ const lastIdx = updated.findIndex((m) => m.role === "assistant" && m.content === assistantContent);
146
+ if (lastIdx >= 0) {
147
+ updated[lastIdx] = finalMessage;
148
+ }
149
+ else {
150
+ updated.push(finalMessage);
151
+ }
152
+ return updated;
153
+ });
154
+ setTotalTokens((prev) => prev + inputTokens + outputTokens);
155
+ onComplete?.(finalMessage);
156
+ }
157
+ catch (err) {
158
+ if (err instanceof Error && err.name === "AbortError")
159
+ return;
160
+ const error = err instanceof Error ? err : new Error(String(err));
161
+ setError(error);
162
+ onError?.(error);
163
+ }
164
+ finally {
165
+ setIsLoading(false);
166
+ setIsStreaming(false);
167
+ abortRef.current = null;
168
+ }
169
+ }, [client, messages, provider, model, systemPrompt, maxContextMessages, isLoading, onChunk, onComplete, onError]);
170
+ const handleSubmit = useCallback(async (e) => {
171
+ e?.preventDefault();
172
+ await sendMessage(input);
173
+ }, [input, sendMessage]);
174
+ const retry = useCallback(async () => {
175
+ if (!lastUserMessageRef.current || isLoading)
176
+ return;
177
+ // Remove last assistant message
178
+ setMessages((prev) => {
179
+ const lastIdx = prev.length - 1;
180
+ if (lastIdx >= 0 && prev[lastIdx].role === "assistant") {
181
+ return prev.slice(0, -1);
182
+ }
183
+ return prev;
184
+ });
185
+ await sendMessage(lastUserMessageRef.current);
186
+ }, [isLoading, sendMessage]);
187
+ return {
188
+ messages,
189
+ input,
190
+ setInput,
191
+ handleSubmit,
192
+ sendMessage,
193
+ isLoading,
194
+ isStreaming,
195
+ error,
196
+ stop,
197
+ clear,
198
+ retry,
199
+ totalTokens,
200
+ totalCost,
201
+ };
202
+ }
@@ -0,0 +1,66 @@
1
+ export interface UseCompletionOptions {
2
+ /** Provider name */
3
+ provider: string;
4
+ /** Model ID */
5
+ model: string;
6
+ /** System prompt */
7
+ systemPrompt?: string;
8
+ /** Called on each text chunk during streaming */
9
+ onChunk?: (chunk: {
10
+ text: string;
11
+ accumulated: string;
12
+ }) => void;
13
+ /** Called when completion finishes */
14
+ onComplete?: (text: string) => void;
15
+ /** Called on error */
16
+ onError?: (error: Error) => void;
17
+ }
18
+ export interface UseCompletionReturn {
19
+ /** Current completion text */
20
+ completion: string;
21
+ /** The full prompt sent */
22
+ prompt: string;
23
+ /** Set the prompt */
24
+ setPrompt: (value: string) => void;
25
+ /** Generate completion from current prompt */
26
+ complete: (promptOverride?: string) => Promise<string>;
27
+ /** Whether generating */
28
+ isLoading: boolean;
29
+ /** Whether streaming */
30
+ isStreaming: boolean;
31
+ /** Current error */
32
+ error: Error | null;
33
+ /** Abort current generation */
34
+ stop: () => void;
35
+ /** Clear completion */
36
+ clear: () => void;
37
+ /** Token count */
38
+ tokens: {
39
+ input: number;
40
+ output: number;
41
+ total: number;
42
+ };
43
+ }
44
+ /**
45
+ * useCompletion — text completion hook for React.
46
+ *
47
+ * @example
48
+ * ```tsx
49
+ * function AutoComplete() {
50
+ * const { completion, prompt, setPrompt, complete, isLoading } = useCompletion({
51
+ * provider: "openai",
52
+ * model: "gpt-4o",
53
+ * systemPrompt: "Complete the following text:",
54
+ * });
55
+ *
56
+ * return (
57
+ * <div>
58
+ * <textarea value={prompt} onChange={e => setPrompt(e.target.value)} />
59
+ * <button onClick={() => complete()} disabled={isLoading}>Complete</button>
60
+ * {completion && <div>{completion}</div>}
61
+ * </div>
62
+ * );
63
+ * }
64
+ * ```
65
+ */
66
+ export declare function useCompletion(options: UseCompletionOptions): UseCompletionReturn;
@@ -0,0 +1,117 @@
1
+ "use client";
2
+ import { useState, useCallback, useRef, useEffect } from "react";
3
+ import { useHilbrasClient } from "./provider.js";
4
+ /**
5
+ * useCompletion — text completion hook for React.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * function AutoComplete() {
10
+ * const { completion, prompt, setPrompt, complete, isLoading } = useCompletion({
11
+ * provider: "openai",
12
+ * model: "gpt-4o",
13
+ * systemPrompt: "Complete the following text:",
14
+ * });
15
+ *
16
+ * return (
17
+ * <div>
18
+ * <textarea value={prompt} onChange={e => setPrompt(e.target.value)} />
19
+ * <button onClick={() => complete()} disabled={isLoading}>Complete</button>
20
+ * {completion && <div>{completion}</div>}
21
+ * </div>
22
+ * );
23
+ * }
24
+ * ```
25
+ */
26
+ export function useCompletion(options) {
27
+ const { provider, model, systemPrompt, onChunk, onComplete, onError } = options;
28
+ const client = useHilbrasClient();
29
+ const [completion, setCompletion] = useState("");
30
+ const [prompt, setPrompt] = useState("");
31
+ const [isLoading, setIsLoading] = useState(false);
32
+ const [isStreaming, setIsStreaming] = useState(false);
33
+ const [error, setError] = useState(null);
34
+ const [tokens, setTokens] = useState({ input: 0, output: 0, total: 0 });
35
+ const abortRef = useRef(null);
36
+ useEffect(() => {
37
+ return () => {
38
+ abortRef.current?.abort();
39
+ };
40
+ }, []);
41
+ const stop = useCallback(() => {
42
+ abortRef.current?.abort();
43
+ abortRef.current = null;
44
+ setIsLoading(false);
45
+ setIsStreaming(false);
46
+ }, []);
47
+ const clear = useCallback(() => {
48
+ stop();
49
+ setCompletion("");
50
+ setError(null);
51
+ setTokens({ input: 0, output: 0, total: 0 });
52
+ }, [stop]);
53
+ const complete = useCallback(async (promptOverride) => {
54
+ const promptText = promptOverride ?? prompt;
55
+ if (!promptText.trim() || isLoading)
56
+ return "";
57
+ setIsLoading(true);
58
+ setIsStreaming(true);
59
+ setError(null);
60
+ const controller = new AbortController();
61
+ abortRef.current = controller;
62
+ try {
63
+ const apiMessages = [];
64
+ if (systemPrompt) {
65
+ apiMessages.push({ role: "system", content: systemPrompt });
66
+ }
67
+ apiMessages.push({ role: "user", content: promptText });
68
+ let text = "";
69
+ let inputTokens = 0;
70
+ let outputTokens = 0;
71
+ for await (const chunk of client.stream({
72
+ messages: apiMessages,
73
+ model,
74
+ provider,
75
+ signal: controller.signal,
76
+ })) {
77
+ if (chunk.type === "text") {
78
+ text += chunk.text;
79
+ setCompletion(text);
80
+ onChunk?.({ text: chunk.text, accumulated: text });
81
+ }
82
+ if (chunk.type === "usage") {
83
+ inputTokens = chunk.inputTokens ?? 0;
84
+ outputTokens = chunk.outputTokens ?? 0;
85
+ }
86
+ }
87
+ setTokens({ input: inputTokens, output: outputTokens, total: inputTokens + outputTokens });
88
+ onComplete?.(text);
89
+ return text;
90
+ }
91
+ catch (err) {
92
+ if (err instanceof Error && err.name === "AbortError")
93
+ return completion;
94
+ const error = err instanceof Error ? err : new Error(String(err));
95
+ setError(error);
96
+ onError?.(error);
97
+ return completion;
98
+ }
99
+ finally {
100
+ setIsLoading(false);
101
+ setIsStreaming(false);
102
+ abortRef.current = null;
103
+ }
104
+ }, [client, prompt, provider, model, systemPrompt, isLoading, completion, onChunk, onComplete, onError]);
105
+ return {
106
+ completion,
107
+ prompt,
108
+ setPrompt,
109
+ complete,
110
+ isLoading,
111
+ isStreaming,
112
+ error,
113
+ stop,
114
+ clear,
115
+ tokens,
116
+ };
117
+ }
@@ -0,0 +1,62 @@
1
+ export interface CostSnapshot {
2
+ /** Total cost in dollars */
3
+ totalCost: number;
4
+ /** Total tokens used */
5
+ totalTokens: number;
6
+ /** Total requests made */
7
+ totalRequests: number;
8
+ /** Average cost per request */
9
+ avgCostPerRequest: number;
10
+ /** Average tokens per request */
11
+ avgTokensPerRequest: number;
12
+ /** Cost breakdown by provider */
13
+ byProvider: Record<string, {
14
+ cost: number;
15
+ tokens: number;
16
+ requests: number;
17
+ }>;
18
+ /** Cost breakdown by model */
19
+ byModel: Record<string, {
20
+ cost: number;
21
+ tokens: number;
22
+ requests: number;
23
+ }>;
24
+ /** Remaining budget (null if no budget set) */
25
+ remainingBudget: number | null;
26
+ /** Budget exceeded flag */
27
+ budgetExceeded: boolean;
28
+ }
29
+ export interface UseCostOptions {
30
+ /** Poll interval in ms (default: 1000) */
31
+ pollIntervalMs?: number;
32
+ /** Whether to auto-poll (default: true) */
33
+ enabled?: boolean;
34
+ }
35
+ export interface UseCostReturn {
36
+ /** Current cost snapshot */
37
+ snapshot: CostSnapshot;
38
+ /** Manually refresh the snapshot */
39
+ refresh: () => void;
40
+ /** Whether budget is low (< 20% remaining) */
41
+ isBudgetLow: boolean;
42
+ /** Whether budget is exceeded */
43
+ isBudgetExceeded: boolean;
44
+ }
45
+ /**
46
+ * useCost — real-time cost tracking hook.
47
+ *
48
+ * @example
49
+ * ```tsx
50
+ * function CostDisplay() {
51
+ * const { snapshot, isBudgetLow } = useCost();
52
+ *
53
+ * return (
54
+ * <div style={{ color: isBudgetLow ? "red" : "green" }}>
55
+ * Cost: ${snapshot.totalCost.toFixed(4)} | Tokens: {snapshot.totalTokens}
56
+ * {snapshot.remainingBudget != null && ` | Remaining: $${snapshot.remainingBudget.toFixed(2)}`}
57
+ * </div>
58
+ * );
59
+ * }
60
+ * ```
61
+ */
62
+ export declare function useCost(options?: UseCostOptions): UseCostReturn;
@@ -0,0 +1,68 @@
1
+ "use client";
2
+ import { useState, useCallback, useEffect } from "react";
3
+ import { useHilbrasClient } from "./provider.js";
4
+ /**
5
+ * useCost — real-time cost tracking hook.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * function CostDisplay() {
10
+ * const { snapshot, isBudgetLow } = useCost();
11
+ *
12
+ * return (
13
+ * <div style={{ color: isBudgetLow ? "red" : "green" }}>
14
+ * Cost: ${snapshot.totalCost.toFixed(4)} | Tokens: {snapshot.totalTokens}
15
+ * {snapshot.remainingBudget != null && ` | Remaining: $${snapshot.remainingBudget.toFixed(2)}`}
16
+ * </div>
17
+ * );
18
+ * }
19
+ * ```
20
+ */
21
+ export function useCost(options = {}) {
22
+ const { pollIntervalMs = 1000, enabled = true } = options;
23
+ const client = useHilbrasClient();
24
+ const [snapshot, setSnapshot] = useState({
25
+ totalCost: 0,
26
+ totalTokens: 0,
27
+ totalRequests: 0,
28
+ avgCostPerRequest: 0,
29
+ avgTokensPerRequest: 0,
30
+ byProvider: {},
31
+ byModel: {},
32
+ remainingBudget: null,
33
+ budgetExceeded: false,
34
+ });
35
+ const refresh = useCallback(() => {
36
+ try {
37
+ const report = client.costReport();
38
+ const byProvider = Object.fromEntries(Object.entries(report.byProvider).map(([provider, metrics]) => [
39
+ provider,
40
+ { cost: metrics.actual, tokens: 0, requests: metrics.requests },
41
+ ]));
42
+ setSnapshot({
43
+ totalCost: report.totalActual,
44
+ totalTokens: 0, // Will be filled from hooks if available
45
+ totalRequests: report.requestCount,
46
+ avgCostPerRequest: report.requestCount > 0 ? report.totalActual / report.requestCount : 0,
47
+ avgTokensPerRequest: 0,
48
+ byProvider,
49
+ byModel: {},
50
+ remainingBudget: report.remainingBudget,
51
+ budgetExceeded: report.budgetExceeded,
52
+ });
53
+ }
54
+ catch {
55
+ // Client may not have cost tracking enabled
56
+ }
57
+ }, [client]);
58
+ useEffect(() => {
59
+ if (!enabled)
60
+ return;
61
+ refresh();
62
+ const interval = setInterval(refresh, pollIntervalMs);
63
+ return () => clearInterval(interval);
64
+ }, [enabled, pollIntervalMs, refresh]);
65
+ const isBudgetLow = snapshot.remainingBudget != null && snapshot.remainingBudget < 1.0;
66
+ const isBudgetExceeded = snapshot.budgetExceeded;
67
+ return { snapshot, refresh, isBudgetLow, isBudgetExceeded };
68
+ }