@baseera/react 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GrayNest
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,457 @@
1
- # Temporary Holding Version
1
+ # @baseera/react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React bindings for Baseera: `<BaseeraProvider>`, `useBaseeraChat()` and `useBaseeraTool()`. They work in React 18 and 19, in Next.js App Router and in Vite. The built files start with `"use client"`, so they can be imported from a client component in the App Router, as below.
4
+
5
+ ```sh
6
+ pnpm add @baseera/react
7
+ ```
8
+
9
+ ## Quick start: Next.js App Router
10
+
11
+ Your server signs the user token (`signUserToken` from `@baseera/node`) in a route handler such as `app/api/baseera-token/route.ts`. Then wrap the app in a client component:
12
+
13
+ ```tsx
14
+ // app/providers.tsx
15
+ "use client";
16
+ import { BaseeraProvider } from "@baseera/react";
17
+
18
+ export function Providers({ children }: { children: React.ReactNode }) {
19
+ return (
20
+ <BaseeraProvider
21
+ publishableKey={process.env.NEXT_PUBLIC_BASEERA_KEY!}
22
+ baseUrl={process.env.NEXT_PUBLIC_BASEERA_URL!}
23
+ getUserToken={() => fetch("/api/baseera-token").then((r) => r.text())}
24
+ theme="system"
25
+ >
26
+ {children}
27
+ </BaseeraProvider>
28
+ );
29
+ }
30
+ ```
31
+
32
+ ```tsx
33
+ // app/layout.tsx (a server component)
34
+ import { Providers } from "./providers";
35
+
36
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
37
+ return (
38
+ <html lang="en">
39
+ <body><Providers>{children}</Providers></body>
40
+ </html>
41
+ );
42
+ }
43
+ ```
44
+
45
+ ## Quick start: Vite
46
+
47
+ ```tsx
48
+ // src/main.tsx
49
+ import { createRoot } from "react-dom/client";
50
+ import { BaseeraProvider } from "@baseera/react";
51
+ import { App } from "./App";
52
+
53
+ createRoot(document.getElementById("root")!).render(
54
+ <BaseeraProvider
55
+ publishableKey={import.meta.env.VITE_BASEERA_KEY}
56
+ baseUrl={import.meta.env.VITE_BASEERA_URL}
57
+ getUserToken={() => fetch("/api/baseera-token").then((r) => r.text())}
58
+ >
59
+ <App />
60
+ </BaseeraProvider>,
61
+ );
62
+ ```
63
+
64
+ Only a publishable key (`pk_…`) belongs in browser code. `baseUrl` is required until a hosted runtime exists. `getUserToken` can be omitted only for dev-mode agents on localhost. Nothing touches `window` during render, so server rendering is safe; the session id lives in `sessionStorage` (when it is available) so a reload resumes the conversation.
65
+
66
+ ## useBaseeraChat
67
+
68
+ ```tsx
69
+ import { useBaseeraChat } from "@baseera/react";
70
+
71
+ export function Chat() {
72
+ const { messages, status, error, send, stop, pendingApprovals, approve, reject } = useBaseeraChat();
73
+
74
+ return (
75
+ <div>
76
+ {messages.map((m) =>
77
+ m.role === "user" ? (
78
+ <p key={m.id}><b>You:</b> {m.text}</p>
79
+ ) : (
80
+ <div key={m.id}>
81
+ {m.toolCalls.map((c) => c.status === "running" && <em key={c.callId}>Checking {c.name}…</em>)}
82
+ <p>{m.text}</p>
83
+ </div>
84
+ ),
85
+ )}
86
+
87
+ {pendingApprovals.map((a) => (
88
+ <div key={a.callId} role="group" aria-label="Approval needed">
89
+ <p>{a.description}</p>
90
+ <button onClick={() => approve(a.callId)}>Approve</button>
91
+ <button onClick={() => reject(a.callId, "Not now")}>Reject</button>
92
+ </div>
93
+ ))}
94
+
95
+ {status === "error" && <p role="alert">Something went wrong ({error?.code}).</p>}
96
+ {status !== "idle" && status !== "error" && <button onClick={stop}>Stop</button>}
97
+ <form onSubmit={(e) => { e.preventDefault(); const input = e.currentTarget.elements.namedItem("q") as HTMLInputElement; void send(input.value); input.value = ""; }}>
98
+ <input name="q" /> <button disabled={status !== "idle" && status !== "error"}>Send</button>
99
+ </form>
100
+ </div>
101
+ );
102
+ }
103
+ ```
104
+
105
+ It returns `{ messages, status, error, pendingApprovals, send, stop, reset, approve, reject, undo }`.
106
+
107
+ - `status`: `idle`, `streaming`, `awaiting_approval`, `running_tool` or `error`. `send` is ignored while it is anything but `idle` or `error`.
108
+ - Assistant messages have `toolCalls`. A call's `status` is `pending`, `awaiting_approval`, `running`, `done`, `failed`, `rejected` or `timed_out`, so the UI can show "Checking invoices…" while one is `running`.
109
+ - Draft and write tools wait in `pendingApprovals` (`{ callId, name, kind, input, description }`) until `approve` or `reject`. `description` comes from the tool's `describe(input)`, else the name and the input as JSON, cut at 300 characters.
110
+ - `error` is a `BaseeraError` with a stable `code`; show your own text to end users.
111
+
112
+ ## useBaseeraTool
113
+
114
+ Defines a tool the model can call, backed by your component's data and handlers. `zod` (v4) is a peer dependency: `pnpm add zod`.
115
+
116
+ ```tsx
117
+ import { useBaseeraTool } from "@baseera/react";
118
+ import { z } from "zod";
119
+
120
+ function InvoicePage({ invoice, api }: Props) {
121
+ // read: runs at once
122
+ useBaseeraTool({
123
+ name: "getInvoice",
124
+ description: "Get an invoice by its number",
125
+ kind: "read",
126
+ input: z.object({ number: z.string() }),
127
+ run: ({ number }) => api.getInvoice(number),
128
+ });
129
+
130
+ // draft: waits for the user's approval
131
+ useBaseeraTool({
132
+ name: "draftReminder",
133
+ description: "Draft a payment reminder email for an invoice",
134
+ kind: "draft",
135
+ input: z.object({ number: z.string(), tone: z.enum(["friendly", "firm"]).default("friendly") }),
136
+ describe: ({ number, tone }) => `Draft a ${tone} reminder for invoice ${number}`,
137
+ run: ({ number, tone }) => api.draftReminder(number, tone),
138
+ });
139
+
140
+ // write: waits for the user's approval
141
+ useBaseeraTool({
142
+ name: "markInvoicePaid",
143
+ description: "Mark an invoice as paid",
144
+ kind: "write",
145
+ input: z.object({ number: z.string(), paidOn: z.string().date() }),
146
+ describe: ({ number, paidOn }) => `Mark invoice ${number} as paid on ${paidOn}`,
147
+ run: async ({ number, paidOn }) => {
148
+ await api.markPaid(number, paidOn);
149
+ return { ok: true };
150
+ },
151
+ });
152
+ return null;
153
+ }
154
+ ```
155
+
156
+ - `input` must be a `z.object(...)`. It is converted to JSON Schema for the model (the top-level `$schema` key is dropped) and must stay under 16,000 bytes.
157
+ - `name` is 1 to 64 letters, digits, `_`, `.` or `-`; `description` is 1 to 2,000 characters. A bad definition throws when the component renders.
158
+ - The model's input is checked with the schema before `run` (and before an approval is asked). If it is invalid, `run` is not called and the model gets a short error listing what is wrong, so it can correct itself. `run` receives the parsed value, so defaults and coercions are applied.
159
+ - `run` can return anything JSON-serializable. A thrown error goes back to the model as a tool error.
160
+ - `describe(input)` is the sentence the user sees when approving a `draft` or `write` call (`pendingApprovals[].description`, see GNA-24).
161
+ - The tool is registered while the component is mounted and sent with every turn. The latest `run` and `describe` are used, so re-renders don't re-register; changing `name`, `kind`, `description` or the schema does. Define the schema outside the component (or memoize it) so it keeps its identity.
162
+ - Registering a name twice logs a `console.warn` with the name; the latest registration wins, and when it unmounts the earlier one is back.
163
+
164
+ ### useBaseeraToolDefinition (low-level)
165
+
166
+ The primitive under `useBaseeraTool`, for tools that don't use Zod. It takes a `RegisteredTool` (`{ spec, run, validate?, describe? }`, where `spec.inputSchema` is JSON Schema) and re-registers only when `spec.name` changes.
167
+
168
+ ## useBaseeraContext
169
+
170
+ Tells the agent where the user is, so "mark this paid" means the invoice on screen. The context goes with every turn (the message and the tool results that continue it) and fills the `{{page}}` and `{{entity.*}}` variables in the agent's prompt.
171
+
172
+ ```tsx
173
+ import { useBaseeraContext } from "@baseera/react";
174
+
175
+ function InvoicePage({ invoice }: { invoice: Invoice }) {
176
+ useBaseeraContext({
177
+ page: `/invoices/${invoice.id}`,
178
+ entity: { type: "invoice", ref: invoice.id, title: invoice.number },
179
+ data: { status: invoice.status, total: invoice.total, currency: invoice.currency },
180
+ });
181
+ return <InvoiceView invoice={invoice} />;
182
+ }
183
+ ```
184
+
185
+ - The context applies while the component is mounted and is removed on unmount. Values are compared by content, so inline objects are fine.
186
+ - Nested calls merge, outer first. The innermost `page` wins. The innermost `entity` wins as a whole (fields of two entities are never mixed). `data` is shallow-merged, inner keys win.
187
+ - `send(text, { context })` overrides for one call, merged on top of the page context.
188
+ - Limits (the runtime refuses a turn that breaks them, so the SDK enforces them first): `page`, `entity.type`, `entity.ref` and `entity.title` are cut to 200 characters. `data` is at most 4096 bytes serialized; if it is larger, `data` is left out of that turn and a warning (byte size and limit, never the data) is logged once in development.
189
+ - Everything in `data` is sent to the model provider. Send only what the agent needs, and never secrets.
190
+
191
+ ## Immersive mode
192
+
193
+ Immersive mode is for the one record your users spend their day in, such as an invoice. While the screen is mounted, the agent sees the record's fields and the results of your checks with every turn, and your UI can block the finish button while something serious is open. The checks run in your app; nothing is sent to the agent except their results.
194
+
195
+ ```tsx
196
+ import { useBaseeraImmersive, useBaseeraImmersiveState } from "@baseera/react";
197
+
198
+ const ok = () => ({ ok: true }) as const;
199
+
200
+ function InvoiceScreen({ invoice, form }: { invoice: Invoice; form: InvoiceForm }) {
201
+ useBaseeraImmersive({
202
+ entity: { type: "invoice", ref: invoice.id, title: invoice.number },
203
+ fields: [
204
+ { name: "customer", label: { ar: "العميل", en: "Customer" }, kind: "text", get: () => form.customer },
205
+ { name: "dueDate", label: { ar: "تاريخ الاستحقاق", en: "Due date" }, kind: "date", get: () => form.dueDate },
206
+ { name: "taxId", label: { ar: "الرقم الضريبي", en: "Tax ID" }, kind: "text", get: () => form.taxId },
207
+ { name: "total", label: { ar: "المجموع", en: "Total" }, kind: "number", get: () => form.total },
208
+ ],
209
+ checks: [
210
+ {
211
+ id: "tax-id-missing",
212
+ severity: "blocking",
213
+ fields: ["taxId"],
214
+ run: (r) =>
215
+ r.taxId
216
+ ? ok()
217
+ : {
218
+ ok: false,
219
+ message: "الرقم الضريبي مفقود",
220
+ // A draft the model may propose. The user approves it before it reaches the form.
221
+ fix: { field: "taxId", value: lookupTaxId(r.customer as string), reason: "من سجل العميل" },
222
+ },
223
+ },
224
+ {
225
+ id: "due-date-past",
226
+ severity: "warning",
227
+ fields: ["dueDate"],
228
+ run: (r) => (new Date(r.dueDate as string) >= new Date() ? ok() : { ok: false, message: "تاريخ الاستحقاق في الماضي" }),
229
+ },
230
+ ],
231
+ // AI checks defined on the agent in the platform, by id: the ones this screen opts into.
232
+ aiChecks: ["policy-conflict"],
233
+ finish: {
234
+ label: "إرسال الفاتورة",
235
+ closed: invoice.status === "closed", // no finish button on closed records
236
+ action: ({ receipt }) => sendInvoice(invoice.id, receipt), // your route calls verifyFinish() from @baseera/node
237
+ blockOnWarnings: false,
238
+ },
239
+ });
240
+ return <InvoiceForm form={form} />;
241
+ }
242
+
243
+ function FinishBar() {
244
+ const { openChecks, canFinish, finishLabel, finish, acknowledge } = useBaseeraImmersiveState();
245
+ return (
246
+ <footer>
247
+ {openChecks.warning.map((c) => (
248
+ <p key={c.id}>{c.message} <button onClick={() => acknowledge(c.id)}>Dismiss</button></p>
249
+ ))}
250
+ <button disabled={!canFinish} onClick={() => void finish()}>{typeof finishLabel === "string" ? finishLabel : finishLabel?.ar}</button>
251
+ </footer>
252
+ );
253
+ }
254
+ ```
255
+
256
+ - **Fields.** `name`, `label` (a string, or `{ ar, en }`), `kind` (`text`, `number`, `date`, `select`) and `get`, which returns the current value. The `record` your checks receive is `{ [name]: get() }`, read when they run. Values must be JSON-serializable.
257
+ - **Checks.** `run(record, { signals })` returns `{ ok: true }` or `{ ok: false, message, fix? }`. `severity` is `blocking`, `warning` or `info`. `fix` is a draft value for a field (`{ field, value, reason? }`) or a tool call the model may propose (`{ tool, input }`). `run` is synchronous. If it throws, the check counts as failed with a generic message, so a blocking check that throws keeps `canFinish` false.
258
+ - **When checks run.** When immersive mode starts, and 250 ms after a field's value changes (values are compared as JSON on each render). Call `recheck()` from `useBaseeraImmersiveState()` after anything else changes. A result that turns passing shows as `resolved` in `results` for 3 seconds, then drops.
259
+ - **Acknowledge.** `acknowledge(id)` hides a warning or info for this record until its result changes (same check id and message). Blocking checks can't be acknowledged: the call is ignored, with a development warning.
260
+ - **Finish.** `canFinish` is false while a blocking check is open (or could not run), while a warning is open if `blockOnWarnings` is true, and when `finish.closed` is true. `finish()` first records the finish with Baseera (a single-use receipt with the open blocking checks and the override reason), and only if that worked runs your `finish.action({ receipt, override })`. If recording fails, the action does not run and `finishError` is `"record_failed"`. With blocking checks open the person can still finish with a written reason: `finish({ override: { reason } })` (10 to 1,000 characters; `canOverride` tells you when). The built-in surface shows this as a "Finish anyway" button. Your route must call `verifyFinish` from `@baseera/node` with the receipt; without it nothing is enforced on your server. See the `@baseera/node` README for what the guard does and doesn't prove.
261
+ - **AI checks.** List the ids of the agent's AI checks in `aiChecks`. The SDK asks the runtime to run them when the record opens and, after a 1.5 s pause, when a field changes (one request at a time). Results are labelled as AI in the review panel, with the knowledge sources they relied on, and never block a finish unless the agent allows it for a blocking check (`blocksFinish`); then the failing check counts in `openBlocking` and needs an override, and the runtime enforces that itself. The runtime caches results until the field values change and caps the runs per record.
262
+ - **State.** `useBaseeraImmersiveState()` returns `openChecks` by severity, `results` (with `open`, `resolved` and `acknowledged` statuses), `counts`, `canFinish`, `canOverride`, `openBlocking`, `finishStatus` (`idle`, `busy`, `error`, `closed`), `finishError`, `finishLabel`, `pendingDrafts` (values waiting for the user in a field, see [Fields](#fields-focus-flag-and-draft)) and `aiChecks` (the latest result of each AI check this screen opted into: `{ id, ok, message, fields, sources, severity, blocksFinish }`). It works in any component under `<BaseeraProvider>`.
263
+ - **One record at a time.** A second call replaces the first, whether it is nested or mounted later, and logs a warning in development (record types and refs only). When the replacing component unmounts, the replaced one is not restored: immersive mode ends. A different `entity.type` or `entity.ref` on the same component starts over as a new record.
264
+ - **What is sent.** Each turn carries the entity, the fields (label, kind, value) and every check's severity, pass or fail, message and fields. Values over 2 KB are cut, at most 50 fields and 100 checks are sent, and the whole object stays under 16 KB (field values are dropped first). Everything sent goes to the model provider, so don't declare fields holding secrets. See `PROTOCOL.md`.
265
+ - `applyCheckFix(checkId)` (from `useBaseeraImmersiveState()`) proposes an open check's `fix: { field, value }` as a draft in the field, for an "Apply fix" button. It resolves with the user's decision, or `null` when there is nothing to show (no open check with a field fix, or the field isn't on the screen).
266
+ - The state machine lives in `@baseera/core` (`createImmersiveController`), so other frameworks can reuse it.
267
+
268
+ ### Signals
269
+
270
+ `useBaseeraSignal()` returns `signal(name, data?)`. Call it when something happens in your UI that a check may depend on, such as a document being uploaded:
271
+
272
+ ```tsx
273
+ import { useBaseeraImmersive, useBaseeraSignal } from "@baseera/react";
274
+
275
+ function InvoiceScreen({ invoice }: { invoice: Invoice }) {
276
+ const signal = useBaseeraSignal();
277
+ useBaseeraImmersive({
278
+ entity: { type: "invoice", ref: invoice.id },
279
+ fields: [],
280
+ checks: [
281
+ {
282
+ id: "contract-missing",
283
+ severity: "blocking",
284
+ fields: [],
285
+ // `signals` maps each signal's name to the data it last carried.
286
+ run: (_record, { signals }) => ("document.uploaded" in signals ? { ok: true } : { ok: false, message: "Upload the signed contract" }),
287
+ },
288
+ ],
289
+ finish: { label: "Send", action: ({ receipt }) => sendInvoice(invoice.id, receipt) },
290
+ });
291
+ return <Uploader onUploaded={(file) => signal("document.uploaded", { name: file.name })} />;
292
+ }
293
+ ```
294
+
295
+ - With a record open, a signal re-runs the checks at once (not after the 250 ms debounce) and the usual notice logic speaks up if a check newly fails. It is also added to the record's trail with its name and data.
296
+ - `name` matches `^[a-z0-9_.-]{1,64}$`; `data` is JSON of at most 2 KB. Otherwise the signal is ignored, with a console warning in development. So is a signal with no record open.
297
+ - Signals live as long as the record is open: they are cleared when it closes or another record starts.
298
+
299
+ ### The trail
300
+
301
+ While a record is in immersive mode the SDK keeps a trail of what happened to it and sends it to Baseera in the background: mode started, checks raised and resolved, drafts proposed, approved or rejected, acknowledgements, signals, and, when the person finishes, the override reason and the finish itself. The platform shows it as a timeline per record and exports it as JSON.
302
+
303
+ - Batched: queued events are sent about every 2 seconds, and always just before a finish is recorded, so the trail reaches Baseera before the finish does. When the page is hidden or closed, a last request goes out with `keepalive`.
304
+ - Best effort: a failing request is retried twice and then dropped, and the SDK never logs the events. A trail problem never blocks the person's work or a finish.
305
+ - A session is started for the trail only when there is something to send; starting immersive mode on a record counts.
306
+ - `finish()` from `useBaseeraImmersiveState()` records the finish as coming from your own UI (`source: "host"`). The built-in review panel's finish bar records it as coming from the panel (`source: "panel"`). Pass `finish({ source: "panel" })` from your own panel to say so.
307
+ - If the agent has "don't store tool data" on, Baseera removes draft values, previous values and signal data before storing the trail (names, ids, severities, messages and override reasons are kept).
308
+
309
+ ### Fields: focus, flag and draft
310
+
311
+ Wrap the host's inputs so Baseera can work in them where the user can see it. `<BaseeraField>` is in `@baseera/ui/connected`; `useBaseeraField(name, { onChange })` is the headless version.
312
+
313
+ ```tsx
314
+ import { BaseeraField } from "@baseera/ui/connected";
315
+
316
+ <BaseeraField name="taxId" value={taxId} onChange={setTaxId}>
317
+ <input value={taxId} onChange={(e) => setTaxId(e.target.value)} />
318
+ </BaseeraField>
319
+ ```
320
+
321
+ `name` is the name of a field in `useBaseeraImmersive({ fields })`. The input is rendered unchanged inside a `position: relative; display: block` wrapper (`data-baseera-field="taxId"`); nothing is styled on it. While a record is in immersive mode and at least one field is on the screen, the provider gives the model two tools (and takes them away when either stops being true):
322
+
323
+ - `ui.focusField` (`read`, input `{ field }`): scrolls the field to the middle of the screen (smooth, instant under `prefers-reduced-motion`), moves keyboard focus into it and highlights it for 2 seconds. An unbound field is an error result: "That field isn't on the screen".
324
+ - `ui.prefillDraft` (`draft`, input `{ field, value, reason? }`): proposes a value. The field must be declared in `useBaseeraImmersive` and be on the screen, and `value` must be JSON of at most 2 KB, or the model gets an error. The proposal appears under the field as a **Baseera draft** with Approve and Reject; it is approved there, not on an approval card. The model gets `approved: true`, or `{ rejected: true, reason }` with the reason the user typed. A newer draft for the same field replaces the older (which comes back rejected, "replaced by a newer draft"); closing the record, or stopping the turn, rejects what is pending.
325
+
326
+ A draft never touches the input. It is a suggestion shown beside it, so **Reject needs no restore**: the value is exactly what it was. **Approve** calls the `onChange` you passed to `BaseeraField` with the draft's value, so the write goes through your own state (or form library) and nothing else.
327
+
328
+ Flags: while a check that lists the field in `fields` is open, the field gets a ring in the severity colour and a badge with the check's message (the worst severity wins). The badge is added to the input's `aria-describedby`, so screen readers read it with the field.
329
+
330
+ Accessibility: the draft sits right after the input, so Tab reaches Approve and then Reject. Reject opens an optional reason field; Escape closes it. The panel is in an `aria-live="polite"` region. After a decision, focus returns to the input.
331
+
332
+ **React Hook Form:** pass `field.onChange` and use `Controller`, so an approved draft goes through the form's state:
333
+
334
+ ```tsx
335
+ <Controller
336
+ name="taxId"
337
+ control={control}
338
+ render={({ field }) => (
339
+ <BaseeraField name="taxId" value={field.value} onChange={field.onChange}>
340
+ <Input {...field} />
341
+ </BaseeraField>
342
+ )}
343
+ />
344
+ ```
345
+
346
+ **Headless:** `useBaseeraField(name, { onChange })` returns `{ draft, flag, focused, approve, reject, bindRef, focusControl }`. Put `bindRef` on your wrapper element; `draft` is `{ value, reason, source }`, `flag` is `{ severity, message, checkId }`, `focused` is `{ at }` for 2 seconds after a focus. `approve()` calls your `onChange` then settles the draft; `reject(reason?)` settles it with the reason and writes nothing. Wrap the part of your own UI that is not the input in `data-baseera-ui` so focus skips it.
347
+
348
+ **Custom tools:** a tool that asks the user inside your own UI can set `inlineApproval: true` on its definition (`useBaseeraToolDefinition`). It runs at once with status `awaiting_approval` instead of an approval card, gets `{ signal }` as a second argument (aborted when the turn is stopped), and throws `BaseeraRejection(reason?)` when the user declines (the model gets `{ rejected: true, reason }`). An approved call is marked `approved: true`.
349
+
350
+ ## Approvals
351
+
352
+ `read` tools run at once. `draft` and `write` tools pause (status `awaiting_approval`) until the user decides, and every approval or rejection is reported to the runtime for the trace. A ready-made approval UI comes with the UI kit; to build your own, use `useBaseeraApprovals()`:
353
+
354
+ ```tsx
355
+ import { useBaseeraApprovals } from "@baseera/react";
356
+
357
+ export function ApprovalBar() {
358
+ const { pending, approve, reject, approveAll, rejectAll } = useBaseeraApprovals();
359
+ if (pending.length === 0) return null;
360
+
361
+ return (
362
+ <section role="group" aria-label="Approval needed">
363
+ {pending.map((a, i) => (
364
+ <div key={a.callId}>
365
+ <small>{i + 1} of {pending.length}</small>
366
+ <p>{a.description}</p> {/* the tool's describe(input), else its name and input */}
367
+ <button onClick={() => approve(a.callId)}>Approve</button>
368
+ <button onClick={() => reject(a.callId, "Not now")}>Reject</button>
369
+ </div>
370
+ ))}
371
+ {pending.length > 1 && (
372
+ <>
373
+ <button onClick={approveAll}>Approve all</button>
374
+ <button onClick={() => rejectAll()}>Reject all</button>
375
+ </>
376
+ )}
377
+ </section>
378
+ );
379
+ }
380
+ ```
381
+
382
+ - `pending` lists the waiting calls in the order the model made them (`{ callId, name, kind, input, description }`). A call leaves the list as soon as you decide it, so "i of n" counts what is still open.
383
+ - `reject(callId, reason?)` sends a short reason (up to 500 characters) to the model, which sees `The user declined: {reason}`.
384
+ - Once every call in a turn is decided, the approved tools run in call order. A result for an approved call carries `approved: true` even if the tool then failed, so the trace shows the approval.
385
+ - Write `describe` for each `draft` and `write` tool, so the user sees what will happen in plain words.
386
+
387
+ ### Undo
388
+
389
+ A `draft` or `write` tool can take `undo: (input, output) => void | Promise<void>`. Once a call of that tool is `done`, the call has `undoable: true`, and `undo(callId)` (from `useBaseeraChat`) runs the tool's `undo` with the validated input and what `run` returned. Afterwards the call has `undone: true` and no `undoable`.
390
+
391
+ - The input and output are kept in memory only (never in the chat state or storage) for the life of the page, and are dropped on `reset()`. After a reload, earlier calls are no longer undoable.
392
+ - The model is not told about an undo. Its next turn does not know the change was reversed.
393
+ - `undo` never throws to your UI: if the tool's `undo` fails, the call stays `undoable` so the user can try again. Handle and show your own errors inside `undo`.
394
+ - Only calls that finished `done` are undoable (not failed or rejected ones), and only for tools that provide `undo`.
395
+ - `undo` is read from the latest render, like `run`.
396
+
397
+ ## useBaseeraKnowledgeUpload
398
+
399
+ The logic of the tenant upload (GNA-66): the tenant's own documents with their status, uploading, deleting. Inside `<BaseeraProvider>`; the tenant, knowledge base and user are not arguments, they are in the token your server signs.
400
+
401
+ ```tsx
402
+ const { sources, uploads, upload, remove, disabled, error } = useBaseeraKnowledgeUpload({
403
+ getUploadToken: () => fetch("/api/baseera/upload-token", { method: "POST" }).then((r) => r.json()).then((b) => b.token),
404
+ });
405
+ // upload(fileList) reserves a signed upload, sends the bytes straight to storage and confirms; sources refresh while documents are processed.
406
+ // disabled: the agent has tenant uploads off. error: a code (`quota`, `rate_limited`, `token`, ...).
407
+ ```
408
+
409
+ The token comes from `createBaseera(...).kb.createTenantUploadToken` in `@baseera/node` on your server. The ready-made component is `<BaseeraKnowledgeUpload>` in `@baseera/ui/connected`.
410
+
411
+ ## useBaseeraFeedback
412
+
413
+ Lets your own UI collect thumbs up and down on assistant replies (GNA-53). `<BaseeraSurface>` already shows thumbs; use the hook when you draw the chat yourself. Inside `<BaseeraProvider>`.
414
+
415
+ ```tsx
416
+ const { messages } = useBaseeraChat();
417
+ const { rate, ratings } = useBaseeraFeedback();
418
+ // On a finished assistant message:
419
+ const ok = await rate(message.id, "down", "The total is wrong"); // true when recorded
420
+ // ratings[message.id] is "up" or "down" once recorded in this page session.
421
+ ```
422
+
423
+ - The rating needs a verified user token (`getUserToken`); a dev-mode anonymous session can't rate. It is one per turn: rating again replaces it.
424
+ - `reason` is optional, for `"down"` only, and is cut to `FEEDBACK_REASON_MAX` (500) characters. It is shown to your team as untrusted text and is never given to the model.
425
+ - `rate` resolves `false` (and records nothing) when there is no session yet, the message is not a finished assistant reply, you hit the rate limit (30 a minute per user) or the network fails. Hold the UI's own error text; the SDK shows none.
426
+
427
+ ## Ready-made UI
428
+
429
+ `@baseera/ui/connected` has `BaseeraApprovals` (every draft and write call of the latest assistant message as a card, with "1 of 3", Done / Rejected / Failed after the decision, and Undo) and `BaseeraToolActivity` (a status line for each read-tool call of a message). Both take `locale`, `labels` (partial override) and `dir`. They live in the UI kit rather than here so this package stays free of UI.
430
+
431
+ ## Testing
432
+
433
+ `BaseeraProvider` accepts an internal `createClient` prop that replaces the client with a fake. It is not a public API and can change.
434
+
435
+ ## Peer dependencies
436
+
437
+ `react` >= 18 and `zod` ^4. Works with React 18 and 19.
438
+
439
+ ## Bundle size
440
+
441
+ `@baseera/react` with `@baseera/core`: about 20.3 kB minified and gzipped (CI budget 20.4 kB). `react` and `zod` are not counted; you already ship them.
442
+
443
+ ## Right to left and Arabic
444
+
445
+ Pass `locale: "ar"` and the agent answers in Arabic. Immersive field and check labels take `{ ar, en }`. Direction, digits and plurals are handled by `@baseera/ui`.
446
+
447
+ ## Security
448
+
449
+ Only a publishable key (`pk_…`) belongs in browser code. Keep `sk_…` keys out of the browser, bundles and public environment variables (`NEXT_PUBLIC_*`, `VITE_*`). See [SECURITY.md](https://github.com/Graynest-net/aeris/blob/main/SECURITY.md) for how to report a vulnerability.
450
+
451
+ ## Documentation
452
+
453
+ Docs: https://docs.baseera.dev. The wire protocol is in [PROTOCOL.md](https://github.com/Graynest-net/aeris/blob/main/PROTOCOL.md).
454
+
455
+ ## License
456
+
457
+ MIT, Copyright (c) 2026 GrayNest. See [LICENSE](./LICENSE).