@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.
@@ -0,0 +1,283 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { TurnContext, BaseeraErrorEvent, BaseeraClientOptions, BaseeraClient, AgentTheme, ChatState, ChatController, Source, FeedbackRating, PendingApproval, ImmersiveDefinition, ImmersiveSnapshot, CheckResult, ImmersiveController, TenantUploadState, UploadableFile, DraftSource, ImmersiveSeverity, ToolKind, RegisteredTool } from '@baseera/core';
3
+ export { AppliedDraft, BaseeraRejection, CHECK_FAILED_MESSAGE, ChatMessage, ChatState, ChatStatus, ChatToolCall, CheckContext, CheckOutcome, CheckResult, ClientOptions, DraftDecision, DraftSource, FEEDBACK_REASON_MAX, FeedbackRating, FinishActionInput, FinishErrorCode, FinishRequestOptions, FinishStatus, ImmersiveCheckDef, ImmersiveContext, ImmersiveDraft, ImmersiveFieldDef, ImmersiveFinishDef, ImmersiveFix, ImmersiveLabel, ImmersiveRecord, ImmersiveSeverity, Message, PROTOCOL_VERSION, PendingApproval, RegisteredTool, TenantSource, TenantUploadErrorCode, TenantUploadState, ToolDefinition, ToolKind, TurnContext, UploadItem, UploadItemState, UploadableFile } from '@baseera/core';
4
+ import { ReactNode } from 'react';
5
+ import { z } from 'zod';
6
+
7
+ /** What a page tells the agent about where the user is. Same shape as the protocol's `TurnContext`. */
8
+ type BaseeraContextInput = TurnContext;
9
+
10
+ type BaseeraTheme = "light" | "dark" | "system" | Record<string, string>;
11
+ interface BaseeraProviderProps {
12
+ /** `pk_…` from the platform. Safe in browser code. */
13
+ publishableKey: string;
14
+ /** Returns a signed user token from your server. Called lazily, and again when the token is about to expire. */
15
+ getUserToken?: () => Promise<string>;
16
+ /** The runtime's URL. */
17
+ baseUrl: string;
18
+ /** Carried to the UI kit. The hooks don't use it. */
19
+ theme?: BaseeraTheme;
20
+ /**
21
+ * Called when a turn or request fails, with the error code (e.g. `provider_out_of_credit`, `rate_limited`) and
22
+ * `retryAfterMs` for rate limits. The chat panel already shows a short message; this is for your own logging or UI.
23
+ */
24
+ onError?: (error: BaseeraErrorEvent) => void;
25
+ children?: ReactNode;
26
+ /** Internal, for tests: replaces the client. Not part of the public API. */
27
+ createClient?: (options: BaseeraClientOptions) => BaseeraClient;
28
+ }
29
+ declare function useBaseeraTheme(): BaseeraTheme | undefined;
30
+ /** The look the owner set on the platform (GNA-132): `theme` (validated) and `logoUrl` (a `blob:` URL of the PNG or WebP). Both null until loaded, and when the agent has none. */
31
+ declare function useBaseeraAgentTheme(): {
32
+ theme: AgentTheme | null;
33
+ logoUrl: string | null;
34
+ };
35
+ declare function BaseeraProvider(props: BaseeraProviderProps): react_jsx_runtime.JSX.Element;
36
+
37
+ interface BaseeraChat extends Pick<ChatState, "messages" | "status" | "error" | "pendingApprovals"> {
38
+ send: ChatController["send"];
39
+ stop: ChatController["stop"];
40
+ reset: ChatController["reset"];
41
+ approve: ChatController["approve"];
42
+ reject: ChatController["reject"];
43
+ /** Reverses a done call with `undoable: true`. See `ChatController.undo`. */
44
+ undo: ChatController["undo"];
45
+ /**
46
+ * Opens the original of a cited source in a new tab (GNA-64). Only for a source with a `url`: the runtime checks
47
+ * everything again and signs a link that lasts 5 minutes. Resolves to false (and opens nothing) when it can't be opened.
48
+ */
49
+ openSource: (source: Source) => Promise<boolean>;
50
+ }
51
+ declare function useBaseeraChat(): BaseeraChat;
52
+
53
+ interface BaseeraFeedback {
54
+ /**
55
+ * Rates an assistant message (GNA-53): `up` or `down`, with an optional reason for `down` (cut to 500 characters, shown to
56
+ * your team as untrusted text and never given to the model). One rating per turn: rating again replaces it. Resolves
57
+ * true when it was recorded and false when it was not (no session yet, a rate limit, a network error). Needs a user token.
58
+ */
59
+ rate: (messageId: string, rating: FeedbackRating, reason?: string) => Promise<boolean>;
60
+ /** The ratings recorded from this hook in this page session, by message id. */
61
+ ratings: Readonly<Record<string, FeedbackRating>>;
62
+ }
63
+ /** For hosts with their own rating UI. Inside `<BaseeraProvider>`. `<BaseeraSurface>` already has thumbs. */
64
+ declare function useBaseeraFeedback(): BaseeraFeedback;
65
+
66
+ /**
67
+ * Tells the agent where the user is. The context goes with every turn while the calling component is mounted.
68
+ * Nested calls merge: the innermost `page` and `entity` win, `data` is shallow-merged with inner keys winning.
69
+ * Values are compared by content, so passing a fresh object each render is fine.
70
+ */
71
+ declare function useBaseeraContext(input: BaseeraContextInput): void;
72
+
73
+ interface BaseeraApprovals {
74
+ /**
75
+ * Draft and write calls waiting for the user, in the order the model made them. Each has `callId`,
76
+ * `name`, `kind`, `input` and `description` (the tool's `describe(input)`, else its name and input as JSON).
77
+ * An entry leaves the list as soon as it is approved or rejected. Empty when nothing is waiting.
78
+ */
79
+ pending: PendingApproval[];
80
+ /** Lets the tool run. Tools run in call order once every pending call is decided. */
81
+ approve(callId: string): void;
82
+ /** Declines the call. The short `reason` (at most 500 characters) goes back to the model. */
83
+ reject(callId: string, reason?: string): void;
84
+ /** Approves everything pending right now. */
85
+ approveAll(): void;
86
+ /** Rejects everything pending right now, with the same optional reason. */
87
+ rejectAll(reason?: string): void;
88
+ }
89
+ /**
90
+ * For hosts that render their own approval UI. The default UI comes with the UI kit.
91
+ * `useBaseeraChat()` exposes the same list as `pendingApprovals`.
92
+ */
93
+ declare function useBaseeraApprovals(): BaseeraApprovals;
94
+
95
+ /** What a record screen declares. Same shape as core's `ImmersiveDefinition`. */
96
+ type BaseeraImmersiveInput = ImmersiveDefinition;
97
+ /**
98
+ * Starts immersive mode on the record this screen shows, and ends it when the component unmounts.
99
+ * The agent then sees the fields and the results of your checks with every turn.
100
+ *
101
+ * Only one record is in immersive mode at a time. The call that rendered last (a nested one, or one mounted
102
+ * later) replaces the other, with a console warning in development that names the record types and refs only.
103
+ * When the replacing component unmounts, the replaced one is not restored automatically: immersive mode ends.
104
+ *
105
+ * Pass fresh closures every render, nothing restarts: the latest `fields`, `checks` and `finish` are used.
106
+ * When a field's value (compared as JSON) changes, the checks run again after 250 ms. Field values must be
107
+ * JSON-serializable; a change a field can't show in JSON isn't noticed. Call `recheck()` from
108
+ * `useBaseeraImmersiveState()` after anything else changes. A different `entity.type` or `entity.ref`
109
+ * starts over as a new record.
110
+ */
111
+ declare function useBaseeraImmersive(def: BaseeraImmersiveInput): void;
112
+ interface BaseeraImmersiveState {
113
+ active: boolean;
114
+ entity: ImmersiveSnapshot["entity"];
115
+ /** Failing checks by severity, hiding acknowledged and just-resolved ones. */
116
+ openChecks: {
117
+ blocking: CheckResult[];
118
+ warning: CheckResult[];
119
+ info: CheckResult[];
120
+ };
121
+ /** Open, resolved (for 3 s after they pass) and acknowledged results. */
122
+ results: CheckResult[];
123
+ counts: ImmersiveSnapshot["counts"];
124
+ /** No open blocking check (and no open warning when the finish blocks on warnings). Fails closed. */
125
+ canFinish: boolean;
126
+ /** Blocking checks are open, and the person could finish anyway with a written reason: `finish({ override: { reason } })`. */
127
+ canOverride: boolean;
128
+ /** Ids of the open blocking checks. An override covers all of them. */
129
+ openBlocking: string[];
130
+ /** A blocking check threw: finish and override stay unavailable until it runs. */
131
+ checksFailed: boolean;
132
+ /** `busy` while recording or running the action; `error` after a failed attempt (see `finishError`); `closed` when `finish.closed` is true. */
133
+ finishStatus: ImmersiveSnapshot["finishStatus"];
134
+ finishError: ImmersiveSnapshot["finishError"];
135
+ finishLabel: ImmersiveSnapshot["finishLabel"];
136
+ /** Values proposed for fields (by the agent or by `applyCheckFix`), waiting for the user. At most one per field. */
137
+ pendingDrafts: ImmersiveSnapshot["pendingDrafts"];
138
+ aiChecks: ImmersiveSnapshot["aiChecks"];
139
+ /** Field name to its label (a string, or `{ ar, en }`). */
140
+ fieldLabels: ImmersiveSnapshot["fieldLabels"];
141
+ /** Names of the fields on the screen now (`<BaseeraField>` mounted). */
142
+ boundFields: string[];
143
+ /** The last approved draft, until it is undone or the record closes. Its `id` changes with every approval. */
144
+ lastApplied: ImmersiveSnapshot["lastApplied"];
145
+ lastRunAt: number | null;
146
+ recheck: ImmersiveController["recheck"];
147
+ /** Hides an open warning or info until its result changes. Blocking checks can't be acknowledged. */
148
+ acknowledge: ImmersiveController["acknowledge"];
149
+ /**
150
+ * Proposes the open check's `fix` (`{ field, value }`) as a draft in the field, for an "Apply fix" button. The user
151
+ * still approves it in the field (`<BaseeraField>`). Resolves with their decision, or null when there is nothing to
152
+ * show: no open check with that id, no field fix, or the field isn't on the screen.
153
+ */
154
+ applyCheckFix: ImmersiveController["applyCheckFix"];
155
+ /** Scrolls a bound field into view, focuses it and highlights it. Returns "not_bound" when it isn't on the screen. */
156
+ focusField: ImmersiveController["focusField"];
157
+ /** Puts back what the last approved draft replaced, through the field's own `onChange`. False when there is nothing to undo. */
158
+ undoLastDraft: ImmersiveController["undoLastDraft"];
159
+ /**
160
+ * The finish guard (GNA-85): records the finish with Baseera, and only if that worked runs your `finish.action({ receipt,
161
+ * override })`. Send the receipt to your finish route, which must call `verifyFinish` from `@baseera/node`. Resolves to
162
+ * whether the action ran. Pass `{ override: { reason } }` to finish with blocking checks open. Never runs the action
163
+ * when recording fails, when a blocking check could not run, or when `finish.closed` is true.
164
+ */
165
+ finish: ImmersiveController["finish"];
166
+ }
167
+ /** The immersive state, for the UI around the record (check list, finish button). Works anywhere under `<BaseeraProvider>`. */
168
+ declare function useBaseeraImmersiveState(): BaseeraImmersiveState;
169
+ /**
170
+ * Returns `signal(name, data?)` (GNA-87): tell Baseera something happened in your UI that a check may depend on, such
171
+ * as `signal("document.uploaded", { name })`. While a record is in immersive mode the checks run again right away, each
172
+ * check receives the latest signals as `run(record, { signals })`, and the signal is added to the record's trail
173
+ * (name and data). The name matches `^[a-z0-9_.-]{1,64}$` and the data is JSON of at most 2 KB; otherwise, and when no
174
+ * record is open, the signal is ignored with a console warning in development. The function is stable.
175
+ */
176
+ declare function useBaseeraSignal(): (name: string, data?: unknown) => void;
177
+
178
+ interface BaseeraKnowledgeUploadOptions {
179
+ /**
180
+ * Returns an upload token from YOUR server, which must first check that the signed-in user may manage this tenant's
181
+ * documents, then sign the token with `signTenantUploadToken` from `@baseera/node` (it names the knowledge base, the tenant
182
+ * and the user). Called when there is no token and again before the last one expires. Never sign it in the browser.
183
+ */
184
+ getUploadToken: () => Promise<string>;
185
+ /** Milliseconds between refreshes while a document is being processed. Default 3000. */
186
+ pollMs?: number;
187
+ }
188
+ interface BaseeraKnowledgeUpload extends TenantUploadState {
189
+ /** Uploads files (the ones that pass the checks: PDF, DOCX, Markdown, TXT, HTML, CSV, up to 25 MB). */
190
+ upload: (files: FileList | readonly UploadableFile[]) => Promise<void>;
191
+ /** Deletes one of the tenant's own documents. Resolves true when it was deleted. */
192
+ remove: (sourceId: string) => Promise<boolean>;
193
+ refresh: () => Promise<void>;
194
+ }
195
+ /**
196
+ * The tenant knowledge upload (GNA-66): the tenant's own documents with their status, and the upload flow. Inside
197
+ * `<BaseeraProvider>` (it uses the provider's publishable key and URL). The tenant, knowledge base and user are not
198
+ * arguments: they are in the token your server signs, so this component can never act for another tenant.
199
+ */
200
+ declare function useBaseeraKnowledgeUpload(options: BaseeraKnowledgeUploadOptions): BaseeraKnowledgeUpload;
201
+
202
+ interface BaseeraFieldOptions {
203
+ /** The host's own change handler (`setValue`, React Hook Form's `field.onChange`). An approved draft is written through it, and nowhere else. */
204
+ onChange: (value: unknown) => void;
205
+ }
206
+ interface BaseeraFieldDraft {
207
+ value: unknown;
208
+ reason: string;
209
+ source: DraftSource;
210
+ }
211
+ interface BaseeraFieldFlag {
212
+ /** The highest severity among the open checks that read this field. */
213
+ severity: ImmersiveSeverity;
214
+ /** The message of the first open check at that severity. */
215
+ message: string;
216
+ checkId: string;
217
+ }
218
+ interface BaseeraFieldState {
219
+ /** A value proposed for this field, waiting for the user. It is a suggestion: the field's value is not touched until `approve()`. */
220
+ draft: BaseeraFieldDraft | null;
221
+ /** The worst open check on this field, or null. */
222
+ flag: BaseeraFieldFlag | null;
223
+ /** Set for 2 seconds after Baseera focused the field (`at` is when). Draw a highlight while it is set. */
224
+ focused: {
225
+ at: number;
226
+ } | null;
227
+ /** Writes the draft's value through the host's `onChange`, then tells Baseera it was approved. */
228
+ approve: () => void;
229
+ /** Drops the draft and tells the model, with the user's reason if there is one. The field's value was never changed. */
230
+ reject: (reason?: string) => void;
231
+ /** Ref for the element that wraps the field. Baseera scrolls to it and focuses the first control inside it. */
232
+ bindRef: (element: HTMLElement | null) => void;
233
+ /** Moves keyboard focus to the first control in the wrapper, without scrolling. */
234
+ focusControl: () => void;
235
+ }
236
+ /** The first control inside `root` that isn't part of Baseera's own UI (elements marked `data-baseera-ui`). */
237
+ declare function firstControl(root: HTMLElement): HTMLElement | null;
238
+ /**
239
+ * Headless binding of one host input to Baseera. Wrap the input in an element with `bindRef`, pass the host's
240
+ * `onChange`, and draw `draft`, `flag` and `focused` however you like. `<BaseeraField>` in `@baseera/ui/connected` does that.
241
+ *
242
+ * While mounted, the field counts as "on the screen": Baseera can point at it (`ui.focusField`) and propose a value
243
+ * for it (`ui.prefillDraft`) once the screen has called `useBaseeraImmersive` with a field of the same name.
244
+ */
245
+ declare function useBaseeraField(name: string, options: BaseeraFieldOptions): BaseeraFieldState;
246
+
247
+ /** The tools Baseera gets while a record is in immersive mode and at least one `<BaseeraField>` is on the screen. */
248
+ declare const FOCUS_FIELD_TOOL = "ui.focusField";
249
+ declare const PREFILL_DRAFT_TOOL = "ui.prefillDraft";
250
+
251
+ /**
252
+ * Registers a tool while the component is mounted. Re-renders don't re-register: the latest
253
+ * `run`, `validate` and `describe` are read when a turn needs them. Only a change of `spec.name` re-registers.
254
+ * Low-level: most apps want `useBaseeraTool`, which builds the tool from a Zod schema.
255
+ */
256
+ declare function useBaseeraToolDefinition(tool: RegisteredTool): void;
257
+ interface BaseeraToolOptions<S extends z.ZodObject> {
258
+ /** Letters, digits, `_`, `.` and `-`, at most 64 characters. */
259
+ name: string;
260
+ /** Tells the model when to use the tool. 1 to 2,000 characters. */
261
+ description: string;
262
+ /** A `z.object(...)`. Sent to the model as JSON Schema; the model's input is validated against it. */
263
+ input: S;
264
+ /** `read` runs at once; `draft` and `write` wait for the user's approval. */
265
+ kind: ToolKind;
266
+ /** Gets the validated (parsed) input. Anything JSON-serializable can be returned; a thrown error goes to the model as a tool error. */
267
+ run: (input: z.output<S>) => unknown | Promise<unknown>;
268
+ /** A short sentence for the approval prompt (draft and write tools). */
269
+ describe?: (input: z.output<S>) => string;
270
+ /**
271
+ * Reverses a done `draft` or `write` call. Gets the validated input and what `run` returned. With it, the
272
+ * approval card offers Undo after the call is done. It is kept in memory for the page session only, and
273
+ * the model is not told about an undo. Read through a ref, like `run`.
274
+ */
275
+ undo?: (input: z.output<S>, output: unknown) => void | Promise<void>;
276
+ }
277
+ /**
278
+ * Defines a tool the model can call, backed by this component's data and handlers. It is registered while the
279
+ * component is mounted and sent with every turn. Invalid model input is rejected before `run`.
280
+ */
281
+ declare function useBaseeraTool<S extends z.ZodObject>(options: BaseeraToolOptions<S>): void;
282
+
283
+ export { type BaseeraApprovals, type BaseeraChat, type BaseeraContextInput, type BaseeraFeedback, type BaseeraFieldDraft, type BaseeraFieldFlag, type BaseeraFieldOptions, type BaseeraFieldState, type BaseeraImmersiveInput, type BaseeraImmersiveState, type BaseeraKnowledgeUpload, type BaseeraKnowledgeUploadOptions, BaseeraProvider, type BaseeraProviderProps, type BaseeraTheme, type BaseeraToolOptions, FOCUS_FIELD_TOOL, PREFILL_DRAFT_TOOL, firstControl, useBaseeraAgentTheme, useBaseeraApprovals, useBaseeraChat, useBaseeraContext, useBaseeraFeedback, useBaseeraField, useBaseeraImmersive, useBaseeraImmersiveState, useBaseeraKnowledgeUpload, useBaseeraSignal, useBaseeraTheme, useBaseeraTool, useBaseeraToolDefinition };