@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/dist/index.js ADDED
@@ -0,0 +1,766 @@
1
+ "use client";
2
+
3
+ // src/provider.tsx
4
+ import { createBaseeraClient, createChatController, createImmersiveController, createTrailBatcher } from "@baseera/core";
5
+
6
+ // src/page-context.ts
7
+ import { LIMITS } from "@baseera/core";
8
+ var MAX_TEXT = 200;
9
+ function isProduction() {
10
+ try {
11
+ return process.env.NODE_ENV === "production";
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+ function merge(layers) {
17
+ const out = {};
18
+ for (const layer of layers) {
19
+ if (!layer) continue;
20
+ if (layer.page !== void 0) out.page = layer.page;
21
+ if (layer.entity !== void 0) out.entity = layer.entity;
22
+ if (layer.data !== void 0) out.data = { ...out.data, ...layer.data };
23
+ }
24
+ return out;
25
+ }
26
+ var byteLength = (text) => new TextEncoder().encode(text).length;
27
+ function createContextStore() {
28
+ const entries = /* @__PURE__ */ new Map();
29
+ let nextOrder = 0;
30
+ const warned = /* @__PURE__ */ new Set();
31
+ const warnOnce = (key, message) => {
32
+ if (isProduction() || warned.has(key)) return;
33
+ warned.add(key);
34
+ console.warn(message);
35
+ };
36
+ return {
37
+ claim: () => ({ order: nextOrder++ }),
38
+ set: (id, input) => void entries.set(id, input),
39
+ remove: (id) => void entries.delete(id),
40
+ resolve(override) {
41
+ const merged = merge([...[...entries].sort((a, b) => a[0].order - b[0].order).map(([, v]) => v), override]);
42
+ const out = {};
43
+ if (merged.page !== void 0) out.page = merged.page.slice(0, MAX_TEXT);
44
+ if (merged.entity !== void 0) {
45
+ const { type, ref, title } = merged.entity;
46
+ out.entity = {
47
+ type: type.slice(0, MAX_TEXT),
48
+ ref: ref.slice(0, MAX_TEXT),
49
+ ...title !== void 0 ? { title: title.slice(0, MAX_TEXT) } : {}
50
+ };
51
+ }
52
+ if (merged.data !== void 0) {
53
+ let size = null;
54
+ try {
55
+ size = byteLength(JSON.stringify(merged.data));
56
+ } catch {
57
+ warnOnce("unserializable", "[baseera] Context data could not be serialized to JSON, so it was left out of the turn.");
58
+ }
59
+ if (size !== null && size <= LIMITS.contextDataBytes) out.data = merged.data;
60
+ else if (size !== null) {
61
+ warnOnce(
62
+ `size:${size}`,
63
+ `[baseera] Context data is ${size} bytes serialized, over the ${LIMITS.contextDataBytes} byte limit, so it was left out of the turn. Send less in \`data\`.`
64
+ );
65
+ }
66
+ }
67
+ return Object.keys(out).length > 0 ? out : void 0;
68
+ }
69
+ };
70
+ }
71
+
72
+ // src/provider.tsx
73
+ import { createContext, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
74
+
75
+ // src/ui-tools.ts
76
+ import { BaseeraRejection, LIMITS as LIMITS2 } from "@baseera/core";
77
+ var FOCUS_FIELD_TOOL = "ui.focusField";
78
+ var PREFILL_DRAFT_TOOL = "ui.prefillDraft";
79
+ var MAX_REASON = 500;
80
+ var NOT_ON_SCREEN = "That field isn't on the screen";
81
+ var DRAFT_CANCELLED_REASON = "the request was cancelled";
82
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
83
+ function readField(input) {
84
+ if (!isRecord(input)) return { ok: false, error: "input must be an object." };
85
+ const { field } = input;
86
+ if (typeof field !== "string" || field === "" || field.length > LIMITS2.immersiveIdChars) return { ok: false, error: "`field` must be the name of a field." };
87
+ return { ok: true, field, rest: input };
88
+ }
89
+ function createUiTools(immersive) {
90
+ const focusField = {
91
+ spec: {
92
+ name: FOCUS_FIELD_TOOL,
93
+ kind: "read",
94
+ description: "Points the user at one field of the record they have open: scrolls it into view, moves the cursor into it and highlights it for a moment. Use it when your answer is about a field, so the user sees which one. It changes nothing in the record.",
95
+ inputSchema: {
96
+ type: "object",
97
+ properties: { field: { type: "string", description: "The name of a field, as listed in the record." } },
98
+ required: ["field"],
99
+ additionalProperties: false
100
+ }
101
+ },
102
+ validate(input) {
103
+ const read = readField(input);
104
+ return read.ok ? { ok: true, value: { field: read.field } } : read;
105
+ },
106
+ run(input) {
107
+ const { field } = input;
108
+ if (immersive.focusField(field) === "not_bound") throw new Error(NOT_ON_SCREEN);
109
+ return { ok: true };
110
+ }
111
+ };
112
+ const prefillDraft = {
113
+ spec: {
114
+ name: PREFILL_DRAFT_TOOL,
115
+ kind: "draft",
116
+ description: "Proposes a value for one field of the record the user has open. It appears next to the field, marked as a Baseera draft, with Approve and Reject buttons. Nothing is written until the user approves; the result tells you whether they approved, or rejected and why. Use it for a field that is empty or wrong when you know the right value, and say where it came from in `reason`. Do not propose again for a field the user rejected unless they ask.",
117
+ inputSchema: {
118
+ type: "object",
119
+ properties: {
120
+ field: { type: "string", description: "The name of a field, as listed in the record." },
121
+ value: { description: `The proposed value as JSON (text, number, boolean, null, ...), at most ${LIMITS2.immersiveFieldValueBytes / 1024} KB serialized. Match the field's kind.` },
122
+ reason: { type: "string", maxLength: MAX_REASON, description: "One short sentence for the user: where the value comes from." }
123
+ },
124
+ required: ["field", "value"],
125
+ additionalProperties: false
126
+ }
127
+ },
128
+ inlineApproval: true,
129
+ validate(input) {
130
+ const read = readField(input);
131
+ if (!read.ok) return read;
132
+ const { field, rest } = read;
133
+ const snap = immersive.getSnapshot();
134
+ if (!snap.fieldNames.includes(field)) return { ok: false, error: `"${field}" is not a field of this record.` };
135
+ if (!snap.boundFields.includes(field)) return { ok: false, error: NOT_ON_SCREEN + "." };
136
+ let json;
137
+ try {
138
+ json = JSON.stringify(rest.value);
139
+ } catch {
140
+ json = void 0;
141
+ }
142
+ if (json === void 0) return { ok: false, error: "`value` must be JSON." };
143
+ const bytes = new TextEncoder().encode(json).length;
144
+ if (bytes > LIMITS2.immersiveFieldValueBytes) return { ok: false, error: `\`value\` is ${bytes} bytes; the limit is ${LIMITS2.immersiveFieldValueBytes}.` };
145
+ const { reason } = rest;
146
+ if (reason !== void 0 && typeof reason !== "string") return { ok: false, error: "`reason` must be text." };
147
+ return { ok: true, value: { field, value: JSON.parse(json), ...reason ? { reason: reason.trim().slice(0, MAX_REASON) } : {} } };
148
+ },
149
+ describe: (input) => `Draft a value for ${input.field}`,
150
+ async run(input, context) {
151
+ const { field, value, reason } = input;
152
+ const decision = immersive.proposeDraft({ field, value, ...reason ? { reason } : {}, source: "model" });
153
+ const mine = immersive.getSnapshot().pendingDrafts.find((d) => d.field === field);
154
+ context?.signal.addEventListener(
155
+ "abort",
156
+ () => {
157
+ if (immersive.getSnapshot().pendingDrafts.find((d) => d.field === field) === mine) immersive.resolveDraft(field, { approved: false, reason: DRAFT_CANCELLED_REASON });
158
+ },
159
+ { once: true }
160
+ );
161
+ const result = await decision;
162
+ if (!result.approved) throw new BaseeraRejection(result.reason);
163
+ return { ok: true, field, written: true };
164
+ }
165
+ };
166
+ return [focusField, prefillDraft];
167
+ }
168
+
169
+ // src/provider.tsx
170
+ import { jsx, jsxs } from "react/jsx-runtime";
171
+ var BaseeraContext = createContext(null);
172
+ function useBaseeraInternals() {
173
+ const value = useContext(BaseeraContext);
174
+ if (!value) throw new Error("useBaseeraChat and useBaseeraTool must be used inside <BaseeraProvider>.");
175
+ return value;
176
+ }
177
+ function useBaseeraTheme() {
178
+ return useBaseeraInternals().theme;
179
+ }
180
+ function useBaseeraAgentTheme() {
181
+ return useBaseeraInternals().agentLook;
182
+ }
183
+ function createToolRegistry() {
184
+ const stacks = /* @__PURE__ */ new Map();
185
+ return {
186
+ register(tool) {
187
+ const name = tool.spec.name;
188
+ const stack = stacks.get(name) ?? [];
189
+ if (stack.length > 0) console.warn(`[baseera] Tool "${name}" is registered more than once. The latest registration wins.`);
190
+ stack.push(tool);
191
+ stacks.set(name, stack);
192
+ return () => {
193
+ const current = stacks.get(name);
194
+ if (!current) return;
195
+ const index = current.lastIndexOf(tool);
196
+ if (index === -1) return;
197
+ current.splice(index, 1);
198
+ if (current.length === 0) stacks.delete(name);
199
+ };
200
+ },
201
+ list: () => [...stacks.values()].map((stack) => stack[stack.length - 1])
202
+ };
203
+ }
204
+ var sessionStorageSafe = {
205
+ get(key) {
206
+ try {
207
+ return window.sessionStorage.getItem(key);
208
+ } catch {
209
+ return null;
210
+ }
211
+ },
212
+ set(key, value) {
213
+ try {
214
+ window.sessionStorage.setItem(key, value);
215
+ } catch {
216
+ }
217
+ },
218
+ remove(key) {
219
+ try {
220
+ window.sessionStorage.removeItem(key);
221
+ } catch {
222
+ }
223
+ }
224
+ };
225
+ function BuiltInUiTools() {
226
+ const { immersive, registry } = useBaseeraInternals();
227
+ const snap = useSyncExternalStore(immersive.subscribe, immersive.getSnapshot, immersive.getSnapshot);
228
+ const enabled = snap.active && snap.boundFields.length > 0;
229
+ useEffect(() => {
230
+ if (!enabled) return;
231
+ const offs = createUiTools(immersive).map((tool) => registry.register(tool));
232
+ return () => {
233
+ for (const off of offs) off();
234
+ };
235
+ }, [enabled, immersive, registry]);
236
+ return null;
237
+ }
238
+ function BaseeraProvider(props) {
239
+ const { publishableKey, baseUrl, theme, children } = props;
240
+ const getUserTokenRef = useRef(props.getUserToken);
241
+ getUserTokenRef.current = props.getUserToken;
242
+ const onErrorRef = useRef(props.onError);
243
+ onErrorRef.current = props.onError;
244
+ const [core] = useState(() => {
245
+ const registry = createToolRegistry();
246
+ const make = props.createClient ?? createBaseeraClient;
247
+ const client = make({
248
+ publishableKey,
249
+ baseUrl,
250
+ ...props.getUserToken ? { getUserToken: () => getUserTokenRef.current() } : {}
251
+ });
252
+ const contextStore = createContextStore();
253
+ const immersiveSlot = { owner: null, nextOrder: 0 };
254
+ let base;
255
+ const trail = createTrailBatcher({
256
+ ensureSession: () => base.ensureSession(),
257
+ currentSessionId: () => base.getSnapshot().sessionId,
258
+ send: (sessionId, events, options) => client.appendImmersiveEvents(sessionId, events, options)
259
+ });
260
+ const immersive = createImmersiveController({
261
+ recordFinish: async (request) => client.recordFinish(await base.ensureSession(), request),
262
+ // AI checks (GNA-82) run against the same session, starting one if needed.
263
+ runAiChecks: async (wire) => client.runAiChecks(await base.ensureSession(), wire),
264
+ trail
265
+ });
266
+ base = createChatController({
267
+ client,
268
+ getTools: registry.list,
269
+ storage: sessionStorageSafe,
270
+ publishableKey,
271
+ getContext: () => contextStore.resolve(),
272
+ getImmersive: () => immersive.toWire(),
273
+ onImmersiveEvent: (event) => immersive.handleEvent(event),
274
+ onError: (error) => onErrorRef.current?.(error)
275
+ });
276
+ const controller = {
277
+ ...base,
278
+ send: (text, options) => base.send(text, { context: contextStore.resolve(options?.context) })
279
+ };
280
+ return { registry, client, contextStore, controller, immersive, immersiveSlot };
281
+ });
282
+ useEffect(() => {
283
+ void core.controller.hydrate();
284
+ }, [core]);
285
+ const [agentTheme, setAgentTheme] = useState(null);
286
+ const [logoUrl, setLogoUrl] = useState(null);
287
+ useEffect(() => {
288
+ let cancelled = false;
289
+ let objectUrl = null;
290
+ void (async () => {
291
+ try {
292
+ const published = await core.client.getTheme?.() ?? null;
293
+ if (cancelled) return;
294
+ setAgentTheme(published);
295
+ if (published?.logo && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") {
296
+ const blob = await core.client.getLogo?.(published.logo);
297
+ if (!blob) return;
298
+ if (cancelled) return;
299
+ objectUrl = URL.createObjectURL(blob);
300
+ setLogoUrl(objectUrl);
301
+ }
302
+ } catch {
303
+ }
304
+ })();
305
+ return () => {
306
+ cancelled = true;
307
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
308
+ };
309
+ }, [core]);
310
+ const agentLook = useMemo(() => ({ theme: agentTheme, logoUrl }), [agentTheme, logoUrl]);
311
+ const value = useMemo(() => ({ ...core, theme, agentLook, connection: { publishableKey, baseUrl } }), [core, theme, agentLook, publishableKey, baseUrl]);
312
+ return /* @__PURE__ */ jsxs(BaseeraContext.Provider, { value, children: [
313
+ /* @__PURE__ */ jsx(BuiltInUiTools, {}),
314
+ children
315
+ ] });
316
+ }
317
+
318
+ // src/use-chat.ts
319
+ import { useMemo as useMemo2, useSyncExternalStore as useSyncExternalStore2 } from "react";
320
+ var SERVER_STATE = { sessionId: null, messages: [], status: "idle", error: null, pendingApprovals: [] };
321
+ var getServerSnapshot = () => SERVER_STATE;
322
+ function useBaseeraChat() {
323
+ const { controller, client } = useBaseeraInternals();
324
+ const state = useSyncExternalStore2(controller.subscribe, controller.getSnapshot, getServerSnapshot);
325
+ return useMemo2(
326
+ () => ({
327
+ messages: state.messages,
328
+ status: state.status,
329
+ error: state.error,
330
+ pendingApprovals: state.pendingApprovals,
331
+ send: controller.send,
332
+ stop: controller.stop,
333
+ reset: controller.reset,
334
+ approve: controller.approve,
335
+ reject: controller.reject,
336
+ undo: controller.undo,
337
+ openSource: async (source) => {
338
+ if (typeof window === "undefined") return false;
339
+ const tab = window.open("about:blank", "_blank");
340
+ if (tab) tab.opener = null;
341
+ try {
342
+ const link = await client.getSourceLink(source);
343
+ if (!tab) return false;
344
+ tab.location.href = link.url;
345
+ return true;
346
+ } catch {
347
+ tab?.close();
348
+ return false;
349
+ }
350
+ }
351
+ }),
352
+ [controller, client, state]
353
+ );
354
+ }
355
+
356
+ // src/use-feedback.ts
357
+ import { useCallback, useMemo as useMemo3, useState as useState2 } from "react";
358
+ function useBaseeraFeedback() {
359
+ const { controller, client } = useBaseeraInternals();
360
+ const [ratings, setRatings] = useState2({});
361
+ const rate = useCallback(
362
+ async (messageId, rating, reason) => {
363
+ const sessionId = controller.getSnapshot().sessionId;
364
+ if (!sessionId) return false;
365
+ try {
366
+ await client.sendFeedback(sessionId, messageId, rating, reason);
367
+ } catch {
368
+ return false;
369
+ }
370
+ setRatings((r) => ({ ...r, [messageId]: rating }));
371
+ return true;
372
+ },
373
+ [controller, client]
374
+ );
375
+ return useMemo3(() => ({ rate, ratings }), [rate, ratings]);
376
+ }
377
+
378
+ // src/use-context.ts
379
+ import { useEffect as useEffect2, useRef as useRef2 } from "react";
380
+ function useBaseeraContext(input) {
381
+ const { contextStore } = useBaseeraInternals();
382
+ const idRef = useRef2(null);
383
+ idRef.current ??= contextStore.claim();
384
+ const id = idRef.current;
385
+ const inputRef = useRef2(input);
386
+ inputRef.current = input;
387
+ let key;
388
+ try {
389
+ key = JSON.stringify(input) ?? "";
390
+ } catch {
391
+ key = String(Math.random());
392
+ }
393
+ useEffect2(() => {
394
+ contextStore.set(id, inputRef.current);
395
+ }, [contextStore, id, key]);
396
+ useEffect2(() => () => contextStore.remove(id), [contextStore, id]);
397
+ }
398
+
399
+ // src/use-approvals.ts
400
+ import { useMemo as useMemo4, useSyncExternalStore as useSyncExternalStore3 } from "react";
401
+ var EMPTY = { sessionId: null, messages: [], status: "idle", error: null, pendingApprovals: [] };
402
+ var getServerSnapshot2 = () => EMPTY;
403
+ function useBaseeraApprovals() {
404
+ const { controller } = useBaseeraInternals();
405
+ const state = useSyncExternalStore3(controller.subscribe, controller.getSnapshot, getServerSnapshot2);
406
+ return useMemo4(
407
+ () => ({
408
+ pending: state.pendingApprovals,
409
+ approve: controller.approve,
410
+ reject: controller.reject,
411
+ approveAll: () => {
412
+ for (const a of controller.getSnapshot().pendingApprovals) controller.approve(a.callId);
413
+ },
414
+ rejectAll: (reason) => {
415
+ for (const a of controller.getSnapshot().pendingApprovals) controller.reject(a.callId, reason);
416
+ }
417
+ }),
418
+ [controller, state.pendingApprovals]
419
+ );
420
+ }
421
+
422
+ // src/use-immersive.ts
423
+ import { createImmersiveController as createImmersiveController2 } from "@baseera/core";
424
+ import { useEffect as useEffect3, useMemo as useMemo5, useRef as useRef3, useSyncExternalStore as useSyncExternalStore4 } from "react";
425
+ function isProduction2() {
426
+ try {
427
+ return process.env.NODE_ENV === "production";
428
+ } catch {
429
+ return false;
430
+ }
431
+ }
432
+ function valuesKey(def) {
433
+ const parts = def.fields.map((field) => {
434
+ let json;
435
+ try {
436
+ json = JSON.stringify(field.get());
437
+ } catch {
438
+ json = "[unserializable]";
439
+ }
440
+ return `${JSON.stringify(field.name)}:${json ?? "undefined"}`;
441
+ });
442
+ return parts.join(",");
443
+ }
444
+ function useBaseeraImmersive(def) {
445
+ const { immersive, immersiveSlot } = useBaseeraInternals();
446
+ const claimRef = useRef3(null);
447
+ claimRef.current ??= { order: immersiveSlot.nextOrder++, entity: null };
448
+ const claim = claimRef.current;
449
+ const defRef = useRef3(def);
450
+ defRef.current = def;
451
+ const key = valuesKey(def);
452
+ const lastKey = useRef3(key);
453
+ useEffect3(() => {
454
+ const latest = defRef.current;
455
+ claim.entity = { type: latest.entity.type, ref: latest.entity.ref };
456
+ const current = immersiveSlot.owner;
457
+ if (current && current !== claim) {
458
+ const [replaced, by] = current.order > claim.order ? [claim, current] : [current, claim];
459
+ if (!isProduction2()) {
460
+ console.warn(
461
+ `[baseera] Immersive mode was on for ${replaced.entity?.type} ${replaced.entity?.ref} and is replaced by ${by.entity?.type} ${by.entity?.ref}. Only one record can be in immersive mode at a time.`
462
+ );
463
+ }
464
+ if (current.order > claim.order) return;
465
+ }
466
+ immersiveSlot.owner = claim;
467
+ immersive.start(latest);
468
+ return () => {
469
+ if (immersiveSlot.owner !== claim) return;
470
+ immersiveSlot.owner = null;
471
+ immersive.stop();
472
+ };
473
+ }, [immersive, immersiveSlot, claim]);
474
+ useEffect3(() => {
475
+ if (immersiveSlot.owner === claim) immersive.update(def);
476
+ });
477
+ useEffect3(() => {
478
+ if (lastKey.current === key) return;
479
+ lastKey.current = key;
480
+ if (immersiveSlot.owner === claim) immersive.recheck();
481
+ }, [key, immersive, immersiveSlot, claim]);
482
+ }
483
+ var SERVER_SNAPSHOT = createImmersiveController2().getSnapshot();
484
+ var getServerSnapshot3 = () => SERVER_SNAPSHOT;
485
+ function useImmersiveSnapshot() {
486
+ const { immersive } = useBaseeraInternals();
487
+ return useSyncExternalStore4(immersive.subscribe, immersive.getSnapshot, getServerSnapshot3);
488
+ }
489
+ function useBaseeraImmersiveState() {
490
+ const { immersive } = useBaseeraInternals();
491
+ const snap = useSyncExternalStore4(immersive.subscribe, immersive.getSnapshot, getServerSnapshot3);
492
+ return useMemo5(() => {
493
+ const open = snap.results.filter((r) => r.status === "open");
494
+ return {
495
+ active: snap.active,
496
+ entity: snap.entity,
497
+ openChecks: {
498
+ blocking: open.filter((r) => r.severity === "blocking"),
499
+ warning: open.filter((r) => r.severity === "warning"),
500
+ info: open.filter((r) => r.severity === "info")
501
+ },
502
+ results: snap.results,
503
+ counts: snap.counts,
504
+ canFinish: snap.canFinish,
505
+ canOverride: snap.canOverride,
506
+ openBlocking: snap.openBlocking,
507
+ checksFailed: snap.checksFailed,
508
+ finishStatus: snap.finishStatus,
509
+ finishError: snap.finishError,
510
+ finishLabel: snap.finishLabel,
511
+ pendingDrafts: snap.pendingDrafts,
512
+ aiChecks: snap.aiChecks,
513
+ fieldLabels: snap.fieldLabels,
514
+ boundFields: snap.boundFields,
515
+ lastApplied: snap.lastApplied,
516
+ lastRunAt: snap.lastRunAt,
517
+ recheck: immersive.recheck,
518
+ acknowledge: immersive.acknowledge,
519
+ applyCheckFix: immersive.applyCheckFix,
520
+ focusField: immersive.focusField,
521
+ undoLastDraft: immersive.undoLastDraft,
522
+ finish: immersive.finish
523
+ };
524
+ }, [immersive, snap]);
525
+ }
526
+ function useBaseeraSignal() {
527
+ const { immersive } = useBaseeraInternals();
528
+ return immersive.signal;
529
+ }
530
+
531
+ // src/use-knowledge-upload.ts
532
+ import { createTenantUploadController } from "@baseera/core";
533
+ import { useEffect as useEffect4, useMemo as useMemo6, useRef as useRef4, useState as useState3, useSyncExternalStore as useSyncExternalStore5 } from "react";
534
+ var SERVER_STATE2 = { sources: null, uploads: [], loading: true, error: null, disabled: false };
535
+ function useBaseeraKnowledgeUpload(options) {
536
+ const { connection } = useBaseeraInternals();
537
+ const tokenRef = useRef4(options.getUploadToken);
538
+ tokenRef.current = options.getUploadToken;
539
+ const [controller] = useState3(
540
+ () => createTenantUploadController({ publishableKey: connection.publishableKey, baseUrl: connection.baseUrl, getUploadToken: () => tokenRef.current(), ...options.pollMs ? { pollMs: options.pollMs } : {} })
541
+ );
542
+ const state = useSyncExternalStore5(controller.subscribe, controller.getSnapshot, () => SERVER_STATE2);
543
+ useEffect4(() => {
544
+ controller.start();
545
+ return () => controller.stop();
546
+ }, [controller]);
547
+ return useMemo6(
548
+ () => ({
549
+ ...state,
550
+ upload: (files) => controller.upload(Array.from(files)),
551
+ remove: controller.remove,
552
+ refresh: controller.refresh
553
+ }),
554
+ [controller, state]
555
+ );
556
+ }
557
+
558
+ // src/use-field.ts
559
+ import { useCallback as useCallback2, useEffect as useEffect5, useMemo as useMemo7, useRef as useRef5 } from "react";
560
+ var MAX_REASON2 = 500;
561
+ var FOCUSABLE = 'input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), a[href], [contenteditable="true"], [tabindex]:not([tabindex="-1"])';
562
+ var SEVERITY_RANK = { info: 1, warning: 2, blocking: 3 };
563
+ function firstControl(root) {
564
+ for (const el of root.querySelectorAll(FOCUSABLE)) if (!el.closest("[data-baseera-ui]")) return el;
565
+ return null;
566
+ }
567
+ function prefersReducedMotion() {
568
+ try {
569
+ return typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
570
+ } catch {
571
+ return false;
572
+ }
573
+ }
574
+ function useBaseeraField(name, options) {
575
+ const { immersive } = useBaseeraInternals();
576
+ const snap = useImmersiveSnapshot();
577
+ const elementRef = useRef5(null);
578
+ const onChangeRef = useRef5(options.onChange);
579
+ onChangeRef.current = options.onChange;
580
+ const focusControl = useCallback2(() => {
581
+ const el = elementRef.current;
582
+ if (el) firstControl(el)?.focus({ preventScroll: true });
583
+ }, []);
584
+ useEffect5(
585
+ () => immersive.bindField(name, {
586
+ write(value) {
587
+ onChangeRef.current(value);
588
+ },
589
+ focus() {
590
+ const el = elementRef.current;
591
+ if (!el) return;
592
+ if (typeof el.scrollIntoView === "function") el.scrollIntoView({ block: "center", behavior: prefersReducedMotion() ? "auto" : "smooth" });
593
+ firstControl(el)?.focus({ preventScroll: true });
594
+ }
595
+ }),
596
+ [immersive, name]
597
+ );
598
+ const bindRef = useCallback2((element) => {
599
+ elementRef.current = element;
600
+ }, []);
601
+ const pending = snap.pendingDrafts.find((d) => d.field === name);
602
+ const draft = useMemo7(() => pending ? { value: pending.value, reason: pending.reason, source: pending.source } : null, [pending]);
603
+ const flag = useMemo7(() => {
604
+ let best = null;
605
+ for (const r of snap.results) {
606
+ if (r.status !== "open" || !r.fields.includes(name)) continue;
607
+ if (!best || SEVERITY_RANK[r.severity] > SEVERITY_RANK[best.severity]) best = { severity: r.severity, message: r.message, checkId: r.id };
608
+ }
609
+ return best;
610
+ }, [snap.results, name]);
611
+ const focusedAt = snap.focused?.field === name ? snap.focused.at : null;
612
+ const focused = useMemo7(() => focusedAt === null ? null : { at: focusedAt }, [focusedAt]);
613
+ const approve = useCallback2(() => {
614
+ const current = immersive.getSnapshot().pendingDrafts.find((d) => d.field === name);
615
+ if (!current) return;
616
+ const previous = immersive.readField(name);
617
+ onChangeRef.current(current.value);
618
+ immersive.resolveDraft(name, { approved: true }, { previous });
619
+ }, [immersive, name]);
620
+ const reject = useCallback2(
621
+ (reason) => {
622
+ const text = reason?.trim().slice(0, MAX_REASON2);
623
+ immersive.resolveDraft(name, { approved: false, ...text ? { reason: text } : {} });
624
+ },
625
+ [immersive, name]
626
+ );
627
+ return useMemo7(() => ({ draft, flag, focused, approve, reject, bindRef, focusControl }), [draft, flag, focused, approve, reject, bindRef, focusControl]);
628
+ }
629
+
630
+ // src/index.ts
631
+ import { BaseeraRejection as BaseeraRejection2, CHECK_FAILED_MESSAGE } from "@baseera/core";
632
+
633
+ // src/use-tool.ts
634
+ import { useEffect as useEffect6, useMemo as useMemo8, useRef as useRef6 } from "react";
635
+ import { z } from "zod";
636
+ var NAME_PATTERN = /^[a-zA-Z0-9_.-]{1,64}$/;
637
+ var MAX_DESCRIPTION = 2e3;
638
+ var MAX_SCHEMA_BYTES = 16e3;
639
+ var MAX_ERROR = 1e3;
640
+ function useBaseeraToolDefinition(tool) {
641
+ const latest = useRef6(tool);
642
+ latest.current = tool;
643
+ useRegistration(tool.spec.name, latest);
644
+ }
645
+ function useRegistration(key, latest) {
646
+ const { registry } = useBaseeraInternals();
647
+ useEffect6(() => {
648
+ const registered = {
649
+ get spec() {
650
+ return latest.current.spec;
651
+ },
652
+ run: (input, context) => latest.current.run(input, context),
653
+ get inlineApproval() {
654
+ return latest.current.inlineApproval;
655
+ },
656
+ validate: (input) => latest.current.validate ? latest.current.validate(input) : { ok: true, value: input },
657
+ describe: (input) => latest.current.describe?.(input) ?? "",
658
+ // Present only while the latest registration has one: the controller offers Undo from this.
659
+ get undo() {
660
+ const undo = latest.current.undo;
661
+ return undo ? (input, output) => latest.current.undo?.(input, output) : void 0;
662
+ }
663
+ };
664
+ return registry.register(registered);
665
+ }, [registry, key, latest]);
666
+ }
667
+ var schemaCache = /* @__PURE__ */ new WeakMap();
668
+ function toWireSchema(name, input) {
669
+ const def = input?._zod?.def;
670
+ if (!input || typeof input !== "object" || def?.type !== "object") {
671
+ throw new Error(`useBaseeraTool("${name}"): \`input\` must be a z.object(...) schema.`);
672
+ }
673
+ const cached = schemaCache.get(input);
674
+ if (cached) return cached;
675
+ let json;
676
+ try {
677
+ json = { ...z.toJSONSchema(input) };
678
+ } catch (error) {
679
+ throw new Error(`useBaseeraTool("${name}"): the input schema cannot be converted to JSON Schema (${error instanceof Error ? error.message : "unknown error"}).`);
680
+ }
681
+ delete json.$schema;
682
+ json.type = "object";
683
+ const bytes = new TextEncoder().encode(JSON.stringify(json)).length;
684
+ if (bytes > MAX_SCHEMA_BYTES) {
685
+ throw new Error(`useBaseeraTool("${name}"): the input schema is ${bytes} bytes as JSON Schema; the limit is ${MAX_SCHEMA_BYTES}.`);
686
+ }
687
+ schemaCache.set(input, json);
688
+ return json;
689
+ }
690
+ function summarize(error) {
691
+ let text;
692
+ try {
693
+ text = typeof z.prettifyError === "function" ? z.prettifyError(error) : "";
694
+ } catch {
695
+ text = "";
696
+ }
697
+ if (!text) text = error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; ");
698
+ return text.slice(0, MAX_ERROR);
699
+ }
700
+ function useBaseeraTool(options) {
701
+ const { name, description, input, kind } = options;
702
+ const spec = useMemo8(() => {
703
+ if (typeof name !== "string" || !NAME_PATTERN.test(name)) {
704
+ throw new Error(`useBaseeraTool: invalid name ${JSON.stringify(name)}. Use 1 to 64 letters, digits, "_", "." or "-".`);
705
+ }
706
+ if (typeof description !== "string" || description.trim() === "" || description.length > MAX_DESCRIPTION) {
707
+ throw new Error(`useBaseeraTool("${name}"): \`description\` must be 1 to ${MAX_DESCRIPTION} characters.`);
708
+ }
709
+ return { name, description, kind, inputSchema: toWireSchema(name, input) };
710
+ }, [name, description, kind, input]);
711
+ const optionsRef = useRef6(options);
712
+ optionsRef.current = options;
713
+ const specRef = useRef6(spec);
714
+ specRef.current = spec;
715
+ const latest = useRef6(null);
716
+ latest.current ??= {
717
+ get spec() {
718
+ return specRef.current;
719
+ },
720
+ run: (value) => optionsRef.current.run(value),
721
+ validate: (value) => {
722
+ const parsed = optionsRef.current.input.safeParse(value);
723
+ return parsed.success ? { ok: true, value: parsed.data } : { ok: false, error: summarize(parsed.error) };
724
+ },
725
+ describe: (value) => optionsRef.current.describe?.(value) ?? "",
726
+ get undo() {
727
+ return optionsRef.current.undo ? (value, output) => optionsRef.current.undo?.(value, output) : void 0;
728
+ }
729
+ };
730
+ const key = useMemo8(() => JSON.stringify([spec.name, spec.kind, spec.description]), [spec]);
731
+ useRegistration(`${key}:${schemaId(input)}`, latest);
732
+ }
733
+ var ids = /* @__PURE__ */ new WeakMap();
734
+ var nextId = 0;
735
+ function schemaId(schema) {
736
+ let id = ids.get(schema);
737
+ if (id === void 0) ids.set(schema, id = ++nextId);
738
+ return id;
739
+ }
740
+
741
+ // src/index.ts
742
+ import { FEEDBACK_REASON_MAX, PROTOCOL_VERSION } from "@baseera/core";
743
+ export {
744
+ BaseeraProvider,
745
+ BaseeraRejection2 as BaseeraRejection,
746
+ CHECK_FAILED_MESSAGE,
747
+ FEEDBACK_REASON_MAX,
748
+ FOCUS_FIELD_TOOL,
749
+ PREFILL_DRAFT_TOOL,
750
+ PROTOCOL_VERSION,
751
+ firstControl,
752
+ useBaseeraAgentTheme,
753
+ useBaseeraApprovals,
754
+ useBaseeraChat,
755
+ useBaseeraContext,
756
+ useBaseeraFeedback,
757
+ useBaseeraField,
758
+ useBaseeraImmersive,
759
+ useBaseeraImmersiveState,
760
+ useBaseeraKnowledgeUpload,
761
+ useBaseeraSignal,
762
+ useBaseeraTheme,
763
+ useBaseeraTool,
764
+ useBaseeraToolDefinition
765
+ };
766
+ //# sourceMappingURL=index.js.map