@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 +21 -0
- package/README.md +456 -2
- package/dist/index.cjs +812 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +283 -0
- package/dist/index.d.ts +283 -0
- package/dist/index.js +766 -0
- package/dist/index.js.map +1 -0
- package/package.json +81 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/provider.tsx","../src/page-context.ts","../src/ui-tools.ts","../src/use-chat.ts","../src/use-feedback.ts","../src/use-context.ts","../src/use-approvals.ts","../src/use-immersive.ts","../src/use-knowledge-upload.ts","../src/use-field.ts","../src/use-tool.ts"],"sourcesContent":["/**\n * @baseera/react: BaseeraProvider, useBaseeraChat (GNA-22), useBaseeraTool (Zod schemas, GNA-23).\n */\nexport { BaseeraProvider, useBaseeraAgentTheme, useBaseeraTheme } from \"./provider\";\nexport type { BaseeraProviderProps, BaseeraTheme } from \"./provider\";\nexport { useBaseeraChat } from \"./use-chat\";\nexport type { BaseeraChat } from \"./use-chat\";\nexport { useBaseeraFeedback } from \"./use-feedback\";\nexport type { BaseeraFeedback } from \"./use-feedback\";\nexport { useBaseeraContext } from \"./use-context\";\nexport type { BaseeraContextInput } from \"./page-context\";\nexport { useBaseeraApprovals } from \"./use-approvals\";\nexport type { BaseeraApprovals } from \"./use-approvals\";\nexport { useBaseeraImmersive, useBaseeraImmersiveState, useBaseeraSignal } from \"./use-immersive\";\nexport type { BaseeraImmersiveInput, BaseeraImmersiveState } from \"./use-immersive\";\nexport { useBaseeraKnowledgeUpload } from \"./use-knowledge-upload\";\nexport type { BaseeraKnowledgeUpload, BaseeraKnowledgeUploadOptions } from \"./use-knowledge-upload\";\nexport { useBaseeraField, firstControl } from \"./use-field\";\nexport type { BaseeraFieldDraft, BaseeraFieldFlag, BaseeraFieldOptions, BaseeraFieldState } from \"./use-field\";\nexport { FOCUS_FIELD_TOOL, PREFILL_DRAFT_TOOL } from \"./ui-tools\";\nexport { BaseeraRejection, CHECK_FAILED_MESSAGE } from \"@baseera/core\";\nexport { useBaseeraTool, useBaseeraToolDefinition } from \"./use-tool\";\nexport type { BaseeraToolOptions } from \"./use-tool\";\nexport type {\n ChatMessage,\n ChatState,\n ChatStatus,\n ChatToolCall,\n CheckContext,\n CheckOutcome,\n AppliedDraft,\n CheckResult,\n ClientOptions,\n DraftDecision,\n DraftSource,\n FeedbackRating,\n ImmersiveCheckDef,\n ImmersiveContext,\n ImmersiveDraft,\n FinishActionInput,\n FinishErrorCode,\n FinishRequestOptions,\n FinishStatus,\n ImmersiveFieldDef,\n ImmersiveFinishDef,\n ImmersiveFix,\n ImmersiveLabel,\n ImmersiveRecord,\n ImmersiveSeverity,\n Message,\n PendingApproval,\n RegisteredTool,\n ToolDefinition,\n ToolKind,\n TenantSource,\n TenantUploadErrorCode,\n TenantUploadState,\n UploadItem,\n UploadItemState,\n UploadableFile,\n TurnContext,\n} from \"@baseera/core\";\nexport { FEEDBACK_REASON_MAX, PROTOCOL_VERSION } from \"@baseera/core\";\n","import { createBaseeraClient, createChatController, createImmersiveController, createTrailBatcher } from \"@baseera/core\";\nimport type { AgentTheme, BaseeraClient, BaseeraErrorEvent, BaseeraClientOptions, ChatController, ChatStorage, ImmersiveController, RegisteredTool } from \"@baseera/core\";\nimport { createContextStore } from \"./page-context\";\nimport type { ContextStore } from \"./page-context\";\nimport { createContext, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { createUiTools } from \"./ui-tools\";\nimport type { ReactNode } from \"react\";\n\nexport type BaseeraTheme = \"light\" | \"dark\" | \"system\" | Record<string, string>;\n\nexport interface BaseeraProviderProps {\n /** `pk_…` from the platform. Safe in browser code. */\n publishableKey: string;\n /** Returns a signed user token from your server. Called lazily, and again when the token is about to expire. */\n getUserToken?: () => Promise<string>;\n /** The runtime's URL. */\n baseUrl: string;\n /** Carried to the UI kit. The hooks don't use it. */\n theme?: BaseeraTheme;\n /**\n * Called when a turn or request fails, with the error code (e.g. `provider_out_of_credit`, `rate_limited`) and\n * `retryAfterMs` for rate limits. The chat panel already shows a short message; this is for your own logging or UI.\n */\n onError?: (error: BaseeraErrorEvent) => void;\n children?: ReactNode;\n /** Internal, for tests: replaces the client. Not part of the public API. */\n createClient?: (options: BaseeraClientOptions) => BaseeraClient;\n}\n\nexport interface ToolRegistry {\n register(tool: RegisteredTool): () => void;\n list(): RegisteredTool[];\n}\n\n/** `order` is taken at a component's first render, so a nested or later call sorts after the one it replaces. */\nexport interface ImmersiveClaim {\n order: number;\n entity: { type: string; ref: string } | null;\n}\n\nexport interface ImmersiveSlot {\n owner: ImmersiveClaim | null;\n nextOrder: number;\n}\n\nexport interface BaseeraContextValue {\n controller: ChatController;\n client: BaseeraClient;\n registry: ToolRegistry;\n contextStore: ContextStore;\n immersive: ImmersiveController;\n /** Which `useBaseeraImmersive` call owns the immersive controller right now. */\n immersiveSlot: ImmersiveSlot;\n theme: BaseeraTheme | undefined;\n /** The theme the agent's owner published and its logo as a `blob:` URL, once fetched (GNA-132). Null while loading or when there is none. */\n agentLook: { theme: AgentTheme | null; logoUrl: string | null };\n /** What the provider was given, for hooks that talk to the runtime themselves (the tenant upload, GNA-66). */\n connection: { publishableKey: string; baseUrl: string };\n}\n\nconst BaseeraContext = createContext<BaseeraContextValue | null>(null);\n\nexport function useBaseeraInternals(): BaseeraContextValue {\n const value = useContext(BaseeraContext);\n if (!value) throw new Error(\"useBaseeraChat and useBaseeraTool must be used inside <BaseeraProvider>.\");\n return value;\n}\n\nexport function useBaseeraTheme(): BaseeraTheme | undefined {\n return useBaseeraInternals().theme;\n}\n\n/** 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. */\nexport function useBaseeraAgentTheme(): { theme: AgentTheme | null; logoUrl: string | null } {\n return useBaseeraInternals().agentLook;\n}\n\n/** Tools by name. A second registration of a name wins until it unregisters, then the first is back. */\nfunction createToolRegistry(): ToolRegistry {\n const stacks = new Map<string, RegisteredTool[]>();\n return {\n register(tool) {\n const name = tool.spec.name;\n const stack = stacks.get(name) ?? [];\n if (stack.length > 0) console.warn(`[baseera] Tool \"${name}\" is registered more than once. The latest registration wins.`);\n stack.push(tool);\n stacks.set(name, stack);\n return () => {\n const current = stacks.get(name);\n if (!current) return;\n const index = current.lastIndexOf(tool);\n if (index === -1) return;\n current.splice(index, 1);\n if (current.length === 0) stacks.delete(name);\n };\n },\n list: () => [...stacks.values()].map((stack) => stack[stack.length - 1]!),\n };\n}\n\n/** sessionStorage behind try/catch, touched only when a method is called (never during render or at import). */\nconst sessionStorageSafe: ChatStorage = {\n get(key) {\n try {\n return window.sessionStorage.getItem(key);\n } catch {\n return null;\n }\n },\n set(key, value) {\n try {\n window.sessionStorage.setItem(key, value);\n } catch {\n /* storage blocked or full */\n }\n },\n remove(key) {\n try {\n window.sessionStorage.removeItem(key);\n } catch {\n /* storage blocked */\n }\n },\n};\n\n/** Registers `ui.focusField` and `ui.prefillDraft` while a record is in immersive mode and a field is on the screen. */\nfunction BuiltInUiTools() {\n const { immersive, registry } = useBaseeraInternals();\n const snap = useSyncExternalStore(immersive.subscribe, immersive.getSnapshot, immersive.getSnapshot);\n const enabled = snap.active && snap.boundFields.length > 0;\n useEffect(() => {\n if (!enabled) return;\n const offs = createUiTools(immersive).map((tool) => registry.register(tool));\n return () => {\n for (const off of offs) off();\n };\n }, [enabled, immersive, registry]);\n return null;\n}\n\nexport function BaseeraProvider(props: BaseeraProviderProps) {\n const { publishableKey, baseUrl, theme, children } = props;\n const getUserTokenRef = useRef(props.getUserToken);\n getUserTokenRef.current = props.getUserToken;\n const onErrorRef = useRef(props.onError);\n onErrorRef.current = props.onError;\n\n const [core] = useState(() => {\n const registry = createToolRegistry();\n const make = props.createClient ?? createBaseeraClient;\n const client = make({\n publishableKey,\n baseUrl,\n ...(props.getUserToken ? { getUserToken: () => getUserTokenRef.current!() } : {}),\n });\n const contextStore = createContextStore();\n const immersiveSlot: ImmersiveSlot = { owner: null, nextOrder: 0 };\n // The finish guard (GNA-85): a finish is recorded against the chat's session first, starting one if needed.\n // `base` is assigned below; recordFinish only runs on a click, long after.\n let base: ChatController;\n // The immersive trail (GNA-86): events are batched and sent against the same session, starting one if needed.\n const trail = createTrailBatcher({\n ensureSession: () => base.ensureSession(),\n currentSessionId: () => base.getSnapshot().sessionId,\n send: (sessionId, events, options) => client.appendImmersiveEvents(sessionId, events, options),\n });\n const immersive = createImmersiveController({\n recordFinish: async (request) => client.recordFinish(await base.ensureSession(), request),\n // AI checks (GNA-82) run against the same session, starting one if needed.\n runAiChecks: async (wire) => client.runAiChecks(await base.ensureSession(), wire),\n trail,\n });\n base = createChatController({\n client,\n getTools: registry.list,\n storage: sessionStorageSafe,\n publishableKey,\n getContext: () => contextStore.resolve(),\n getImmersive: () => immersive.toWire(),\n onImmersiveEvent: (event) => immersive.handleEvent(event),\n onError: (error) => onErrorRef.current?.(error),\n });\n const controller: ChatController = {\n ...base,\n send: (text, options) => base.send(text, { context: contextStore.resolve(options?.context) }),\n };\n return { registry, client, contextStore, controller, immersive, immersiveSlot };\n });\n\n useEffect(() => {\n void core.controller.hydrate();\n }, [core]);\n\n // The published theme and logo (GNA-132): fetched with the publishable key like any request. A failure leaves the SDK's own look.\n const [agentTheme, setAgentTheme] = useState<AgentTheme | null>(null);\n const [logoUrl, setLogoUrl] = useState<string | null>(null);\n useEffect(() => {\n let cancelled = false;\n let objectUrl: string | null = null;\n void (async () => {\n try {\n const published = (await core.client.getTheme?.()) ?? null;\n if (cancelled) return;\n setAgentTheme(published);\n if (published?.logo && typeof URL !== \"undefined\" && typeof URL.createObjectURL === \"function\") {\n const blob = await core.client.getLogo?.(published.logo);\n if (!blob) return;\n if (cancelled) return;\n objectUrl = URL.createObjectURL(blob);\n setLogoUrl(objectUrl);\n }\n } catch {\n /* no published theme, or it could not be read: the default look */\n }\n })();\n return () => {\n cancelled = true;\n if (objectUrl) URL.revokeObjectURL(objectUrl);\n };\n }, [core]);\n const agentLook = useMemo(() => ({ theme: agentTheme, logoUrl }), [agentTheme, logoUrl]);\n\n const value = useMemo<BaseeraContextValue>(() => ({ ...core, theme, agentLook, connection: { publishableKey, baseUrl } }), [core, theme, agentLook, publishableKey, baseUrl]);\n\n return (\n <BaseeraContext.Provider value={value}>\n <BuiltInUiTools />\n {children}\n </BaseeraContext.Provider>\n );\n}\n","import { LIMITS } from \"@baseera/core\";\nimport type { TurnContext } from \"@baseera/core\";\n\n/** What a page tells the agent about where the user is. Same shape as the protocol's `TurnContext`. */\nexport type BaseeraContextInput = TurnContext;\n\nconst MAX_TEXT = 200;\n\ndeclare const process: { env: { NODE_ENV?: string } };\n\n/** Bundlers replace `process.env.NODE_ENV` textually; the guard covers runtimes where `process` is missing. */\nfunction isProduction(): boolean {\n try {\n return process.env.NODE_ENV === \"production\";\n } catch {\n return false;\n }\n}\n\n/** Identifies one `useBaseeraContext` call. `order` is taken at first render, which runs outer components first. */\nexport interface ContextEntryId {\n order: number;\n}\n\nexport interface ContextStore {\n /** A new id that sorts after every earlier one. */\n claim(): ContextEntryId;\n /** Adds an entry, or replaces its value. Entries merge in `order`, outer first. */\n set(id: ContextEntryId, input: BaseeraContextInput): void;\n remove(id: ContextEntryId): void;\n /** Merged entries, with `override` on top, trimmed to the protocol limits. `undefined` when empty. */\n resolve(override?: TurnContext): TurnContext | undefined;\n}\n\nfunction merge(layers: Array<TurnContext | undefined>): TurnContext {\n const out: TurnContext = {};\n for (const layer of layers) {\n if (!layer) continue;\n if (layer.page !== undefined) out.page = layer.page;\n if (layer.entity !== undefined) out.entity = layer.entity;\n if (layer.data !== undefined) out.data = { ...out.data, ...layer.data };\n }\n return out;\n}\n\nconst byteLength = (text: string) => new TextEncoder().encode(text).length;\n\nexport function createContextStore(): ContextStore {\n const entries = new Map<ContextEntryId, BaseeraContextInput>();\n let nextOrder = 0;\n const warned = new Set<string>();\n\n const warnOnce = (key: string, message: string) => {\n if (isProduction() || warned.has(key)) return;\n warned.add(key);\n console.warn(message);\n };\n\n return {\n claim: () => ({ order: nextOrder++ }),\n set: (id, input) => void entries.set(id, input),\n remove: (id) => void entries.delete(id),\n resolve(override) {\n const merged = merge([...[...entries].sort((a, b) => a[0].order - b[0].order).map(([, v]) => v), override]);\n const out: TurnContext = {};\n if (merged.page !== undefined) out.page = merged.page.slice(0, MAX_TEXT);\n if (merged.entity !== undefined) {\n const { type, ref, title } = merged.entity;\n out.entity = {\n type: type.slice(0, MAX_TEXT),\n ref: ref.slice(0, MAX_TEXT),\n ...(title !== undefined ? { title: title.slice(0, MAX_TEXT) } : {}),\n };\n }\n if (merged.data !== undefined) {\n let size: number | null = null;\n try {\n size = byteLength(JSON.stringify(merged.data));\n } catch {\n warnOnce(\"unserializable\", \"[baseera] Context data could not be serialized to JSON, so it was left out of the turn.\");\n }\n if (size !== null && size <= LIMITS.contextDataBytes) out.data = merged.data;\n else if (size !== null) {\n warnOnce(\n `size:${size}`,\n `[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\\`.`,\n );\n }\n }\n return Object.keys(out).length > 0 ? out : undefined;\n },\n };\n}\n","import { BaseeraRejection, LIMITS } from \"@baseera/core\";\nimport type { ImmersiveController, RegisteredTool } from \"@baseera/core\";\n\n/** The tools Baseera gets while a record is in immersive mode and at least one `<BaseeraField>` is on the screen. */\nexport const FOCUS_FIELD_TOOL = \"ui.focusField\";\nexport const PREFILL_DRAFT_TOOL = \"ui.prefillDraft\";\n\nconst MAX_REASON = 500;\nconst NOT_ON_SCREEN = \"That field isn't on the screen\";\nexport const DRAFT_CANCELLED_REASON = \"the request was cancelled\";\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nfunction readField(input: unknown): { ok: true; field: string; rest: Record<string, unknown> } | { ok: false; error: string } {\n if (!isRecord(input)) return { ok: false, error: \"input must be an object.\" };\n const { field } = input;\n if (typeof field !== \"string\" || field === \"\" || field.length > LIMITS.immersiveIdChars) return { ok: false, error: \"`field` must be the name of a field.\" };\n return { ok: true, field, rest: input };\n}\n\nexport function createUiTools(immersive: ImmersiveController): RegisteredTool[] {\n const focusField: RegisteredTool = {\n spec: {\n name: FOCUS_FIELD_TOOL,\n kind: \"read\",\n description:\n \"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.\",\n inputSchema: {\n type: \"object\",\n properties: { field: { type: \"string\", description: \"The name of a field, as listed in the record.\" } },\n required: [\"field\"],\n additionalProperties: false,\n },\n },\n validate(input) {\n const read = readField(input);\n return read.ok ? { ok: true, value: { field: read.field } } : read;\n },\n run(input) {\n const { field } = input as { field: string };\n if (immersive.focusField(field) === \"not_bound\") throw new Error(NOT_ON_SCREEN);\n return { ok: true };\n },\n };\n\n const prefillDraft: RegisteredTool = {\n spec: {\n name: PREFILL_DRAFT_TOOL,\n kind: \"draft\",\n description:\n \"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.\",\n inputSchema: {\n type: \"object\",\n properties: {\n field: { type: \"string\", description: \"The name of a field, as listed in the record.\" },\n value: { description: `The proposed value as JSON (text, number, boolean, null, ...), at most ${LIMITS.immersiveFieldValueBytes / 1024} KB serialized. Match the field's kind.` },\n reason: { type: \"string\", maxLength: MAX_REASON, description: \"One short sentence for the user: where the value comes from.\" },\n },\n required: [\"field\", \"value\"],\n additionalProperties: false,\n },\n },\n inlineApproval: true,\n validate(input) {\n const read = readField(input);\n if (!read.ok) return read;\n const { field, rest } = read;\n const snap = immersive.getSnapshot();\n if (!snap.fieldNames.includes(field)) return { ok: false, error: `\"${field}\" is not a field of this record.` };\n if (!snap.boundFields.includes(field)) return { ok: false, error: NOT_ON_SCREEN + \".\" };\n let json: string | undefined;\n try {\n json = JSON.stringify(rest.value);\n } catch {\n json = undefined;\n }\n if (json === undefined) return { ok: false, error: \"`value` must be JSON.\" };\n const bytes = new TextEncoder().encode(json).length;\n if (bytes > LIMITS.immersiveFieldValueBytes) return { ok: false, error: `\\`value\\` is ${bytes} bytes; the limit is ${LIMITS.immersiveFieldValueBytes}.` };\n const { reason } = rest;\n if (reason !== undefined && typeof reason !== \"string\") return { ok: false, error: \"`reason` must be text.\" };\n return { ok: true, value: { field, value: JSON.parse(json) as unknown, ...(reason ? { reason: reason.trim().slice(0, MAX_REASON) } : {}) } };\n },\n describe: (input) => `Draft a value for ${(input as { field: string }).field}`,\n async run(input, context) {\n const { field, value, reason } = input as { field: string; value: unknown; reason?: string };\n const decision = immersive.proposeDraft({ field, value, ...(reason ? { reason } : {}), source: \"model\" });\n // The user stopped the turn: the draft is no longer wanted. Only touch it if it is still this one.\n const mine = immersive.getSnapshot().pendingDrafts.find((d) => d.field === field);\n context?.signal.addEventListener(\n \"abort\",\n () => {\n if (immersive.getSnapshot().pendingDrafts.find((d) => d.field === field) === mine) immersive.resolveDraft(field, { approved: false, reason: DRAFT_CANCELLED_REASON });\n },\n { once: true },\n );\n const result = await decision;\n if (!result.approved) throw new BaseeraRejection(result.reason);\n return { ok: true, field, written: true };\n },\n };\n\n return [focusField, prefillDraft];\n}\n","import type { ChatController, ChatState, Source } from \"@baseera/core\";\nimport { useMemo, useSyncExternalStore } from \"react\";\nimport { useBaseeraInternals } from \"./provider\";\n\nexport interface BaseeraChat extends Pick<ChatState, \"messages\" | \"status\" | \"error\" | \"pendingApprovals\"> {\n send: ChatController[\"send\"];\n stop: ChatController[\"stop\"];\n reset: ChatController[\"reset\"];\n approve: ChatController[\"approve\"];\n reject: ChatController[\"reject\"];\n /** Reverses a done call with `undoable: true`. See `ChatController.undo`. */\n undo: ChatController[\"undo\"];\n /**\n * Opens the original of a cited source in a new tab (GNA-64). Only for a source with a `url`: the runtime checks\n * everything again and signs a link that lasts 5 minutes. Resolves to false (and opens nothing) when it can't be opened.\n */\n openSource: (source: Source) => Promise<boolean>;\n}\n\nconst SERVER_STATE: ChatState = { sessionId: null, messages: [], status: \"idle\", error: null, pendingApprovals: [] };\nconst getServerSnapshot = () => SERVER_STATE;\n\nexport function useBaseeraChat(): BaseeraChat {\n const { controller, client } = useBaseeraInternals();\n const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot, getServerSnapshot);\n return useMemo(\n () => ({\n messages: state.messages,\n status: state.status,\n error: state.error,\n pendingApprovals: state.pendingApprovals,\n send: controller.send,\n stop: controller.stop,\n reset: controller.reset,\n approve: controller.approve,\n reject: controller.reject,\n undo: controller.undo,\n openSource: async (source) => {\n if (typeof window === \"undefined\") return false;\n // The tab opens now, inside the click, so a popup blocker allows it; it is pointed at the link once it is signed.\n const tab = window.open(\"about:blank\", \"_blank\");\n if (tab) tab.opener = null;\n try {\n const link = await client.getSourceLink(source);\n if (!tab) return false;\n tab.location.href = link.url;\n return true;\n } catch {\n tab?.close();\n return false;\n }\n },\n }),\n [controller, client, state],\n );\n}\n","import type { FeedbackRating } from \"@baseera/core\";\nimport { useCallback, useMemo, useState } from \"react\";\nimport { useBaseeraInternals } from \"./provider\";\n\nexport interface BaseeraFeedback {\n /**\n * Rates an assistant message (GNA-53): `up` or `down`, with an optional reason for `down` (cut to 500 characters, shown to\n * your team as untrusted text and never given to the model). One rating per turn: rating again replaces it. Resolves\n * true when it was recorded and false when it was not (no session yet, a rate limit, a network error). Needs a user token.\n */\n rate: (messageId: string, rating: FeedbackRating, reason?: string) => Promise<boolean>;\n /** The ratings recorded from this hook in this page session, by message id. */\n ratings: Readonly<Record<string, FeedbackRating>>;\n}\n\n/** For hosts with their own rating UI. Inside `<BaseeraProvider>`. `<BaseeraSurface>` already has thumbs. */\nexport function useBaseeraFeedback(): BaseeraFeedback {\n const { controller, client } = useBaseeraInternals();\n const [ratings, setRatings] = useState<Record<string, FeedbackRating>>({});\n const rate = useCallback(\n async (messageId: string, rating: FeedbackRating, reason?: string) => {\n const sessionId = controller.getSnapshot().sessionId;\n if (!sessionId) return false;\n try {\n await client.sendFeedback(sessionId, messageId, rating, reason);\n } catch {\n return false;\n }\n setRatings((r) => ({ ...r, [messageId]: rating }));\n return true;\n },\n [controller, client],\n );\n return useMemo(() => ({ rate, ratings }), [rate, ratings]);\n}\n","import { useEffect, useRef } from \"react\";\nimport { useBaseeraInternals } from \"./provider\";\nimport type { BaseeraContextInput, ContextEntryId } from \"./page-context\";\n\n/**\n * Tells the agent where the user is. The context goes with every turn while the calling component is mounted.\n * Nested calls merge: the innermost `page` and `entity` win, `data` is shallow-merged with inner keys winning.\n * Values are compared by content, so passing a fresh object each render is fine.\n */\nexport function useBaseeraContext(input: BaseeraContextInput): void {\n const { contextStore } = useBaseeraInternals();\n const idRef = useRef<ContextEntryId | null>(null);\n idRef.current ??= contextStore.claim();\n const id = idRef.current;\n const inputRef = useRef(input);\n inputRef.current = input;\n let key: string;\n try {\n key = JSON.stringify(input) ?? \"\";\n } catch {\n key = String(Math.random());\n }\n\n useEffect(() => {\n contextStore.set(id, inputRef.current);\n }, [contextStore, id, key]);\n\n useEffect(() => () => contextStore.remove(id), [contextStore, id]);\n}\n","import type { ChatState, PendingApproval } from \"@baseera/core\";\nimport { useMemo, useSyncExternalStore } from \"react\";\nimport { useBaseeraInternals } from \"./provider\";\n\nexport interface BaseeraApprovals {\n /**\n * Draft and write calls waiting for the user, in the order the model made them. Each has `callId`,\n * `name`, `kind`, `input` and `description` (the tool's `describe(input)`, else its name and input as JSON).\n * An entry leaves the list as soon as it is approved or rejected. Empty when nothing is waiting.\n */\n pending: PendingApproval[];\n /** Lets the tool run. Tools run in call order once every pending call is decided. */\n approve(callId: string): void;\n /** Declines the call. The short `reason` (at most 500 characters) goes back to the model. */\n reject(callId: string, reason?: string): void;\n /** Approves everything pending right now. */\n approveAll(): void;\n /** Rejects everything pending right now, with the same optional reason. */\n rejectAll(reason?: string): void;\n}\n\nconst EMPTY: ChatState = { sessionId: null, messages: [], status: \"idle\", error: null, pendingApprovals: [] };\nconst getServerSnapshot = () => EMPTY;\n\n/**\n * For hosts that render their own approval UI. The default UI comes with the UI kit.\n * `useBaseeraChat()` exposes the same list as `pendingApprovals`.\n */\nexport function useBaseeraApprovals(): BaseeraApprovals {\n const { controller } = useBaseeraInternals();\n const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot, getServerSnapshot);\n return useMemo(\n () => ({\n pending: state.pendingApprovals,\n approve: controller.approve,\n reject: controller.reject,\n approveAll: () => {\n for (const a of controller.getSnapshot().pendingApprovals) controller.approve(a.callId);\n },\n rejectAll: (reason) => {\n for (const a of controller.getSnapshot().pendingApprovals) controller.reject(a.callId, reason);\n },\n }),\n [controller, state.pendingApprovals],\n );\n}\n","import type { CheckResult, ImmersiveController, ImmersiveDefinition, ImmersiveSnapshot } from \"@baseera/core\";\nimport { createImmersiveController } from \"@baseera/core\";\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport { useBaseeraInternals } from \"./provider\";\nimport type { ImmersiveClaim } from \"./provider\";\n\n/** What a record screen declares. Same shape as core's `ImmersiveDefinition`. */\nexport type BaseeraImmersiveInput = ImmersiveDefinition;\n\ndeclare const process: { env: { NODE_ENV?: string } };\n\nfunction isProduction(): boolean {\n try {\n return process.env.NODE_ENV === \"production\";\n } catch {\n return false;\n }\n}\n\n/** The current field values as one comparable string. A value that can't be serialized counts as unchanged. */\nfunction valuesKey(def: ImmersiveDefinition): string {\n const parts = def.fields.map((field) => {\n let json: string | undefined;\n try {\n json = JSON.stringify(field.get());\n } catch {\n json = \"[unserializable]\";\n }\n return `${JSON.stringify(field.name)}:${json ?? \"undefined\"}`;\n });\n return parts.join(\",\");\n}\n\n/**\n * Starts immersive mode on the record this screen shows, and ends it when the component unmounts.\n * The agent then sees the fields and the results of your checks with every turn.\n *\n * Only one record is in immersive mode at a time. The call that rendered last (a nested one, or one mounted\n * later) replaces the other, with a console warning in development that names the record types and refs only.\n * When the replacing component unmounts, the replaced one is not restored automatically: immersive mode ends.\n *\n * Pass fresh closures every render, nothing restarts: the latest `fields`, `checks` and `finish` are used.\n * When a field's value (compared as JSON) changes, the checks run again after 250 ms. Field values must be\n * JSON-serializable; a change a field can't show in JSON isn't noticed. Call `recheck()` from\n * `useBaseeraImmersiveState()` after anything else changes. A different `entity.type` or `entity.ref`\n * starts over as a new record.\n */\nexport function useBaseeraImmersive(def: BaseeraImmersiveInput): void {\n const { immersive, immersiveSlot } = useBaseeraInternals();\n const claimRef = useRef<ImmersiveClaim>(null);\n claimRef.current ??= { order: immersiveSlot.nextOrder++, entity: null };\n const claim = claimRef.current;\n const defRef = useRef(def);\n defRef.current = def;\n const key = valuesKey(def);\n const lastKey = useRef(key);\n\n useEffect(() => {\n const latest = defRef.current;\n claim.entity = { type: latest.entity.type, ref: latest.entity.ref };\n const current = immersiveSlot.owner;\n if (current && current !== claim) {\n // The later call (nested, or mounted after) wins, whichever effect happens to run first.\n const [replaced, by] = current.order > claim.order ? [claim, current] : [current, claim];\n if (!isProduction()) {\n console.warn(\n `[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.`,\n );\n }\n if (current.order > claim.order) return;\n }\n immersiveSlot.owner = claim;\n immersive.start(latest);\n return () => {\n if (immersiveSlot.owner !== claim) return;\n immersiveSlot.owner = null;\n immersive.stop();\n };\n }, [immersive, immersiveSlot, claim]);\n\n // Every render: the controller gets the latest closures (and a changed entity restarts it).\n useEffect(() => {\n if (immersiveSlot.owner === claim) immersive.update(def);\n });\n\n useEffect(() => {\n if (lastKey.current === key) return;\n lastKey.current = key;\n if (immersiveSlot.owner === claim) immersive.recheck();\n }, [key, immersive, immersiveSlot, claim]);\n}\n\nexport interface BaseeraImmersiveState {\n active: boolean;\n entity: ImmersiveSnapshot[\"entity\"];\n /** Failing checks by severity, hiding acknowledged and just-resolved ones. */\n openChecks: { blocking: CheckResult[]; warning: CheckResult[]; info: CheckResult[] };\n /** Open, resolved (for 3 s after they pass) and acknowledged results. */\n results: CheckResult[];\n counts: ImmersiveSnapshot[\"counts\"];\n /** No open blocking check (and no open warning when the finish blocks on warnings). Fails closed. */\n canFinish: boolean;\n /** Blocking checks are open, and the person could finish anyway with a written reason: `finish({ override: { reason } })`. */\n canOverride: boolean;\n /** Ids of the open blocking checks. An override covers all of them. */\n openBlocking: string[];\n /** A blocking check threw: finish and override stay unavailable until it runs. */\n checksFailed: boolean;\n /** `busy` while recording or running the action; `error` after a failed attempt (see `finishError`); `closed` when `finish.closed` is true. */\n finishStatus: ImmersiveSnapshot[\"finishStatus\"];\n finishError: ImmersiveSnapshot[\"finishError\"];\n finishLabel: ImmersiveSnapshot[\"finishLabel\"];\n /** Values proposed for fields (by the agent or by `applyCheckFix`), waiting for the user. At most one per field. */\n pendingDrafts: ImmersiveSnapshot[\"pendingDrafts\"];\n aiChecks: ImmersiveSnapshot[\"aiChecks\"];\n /** Field name to its label (a string, or `{ ar, en }`). */\n fieldLabels: ImmersiveSnapshot[\"fieldLabels\"];\n /** Names of the fields on the screen now (`<BaseeraField>` mounted). */\n boundFields: string[];\n /** The last approved draft, until it is undone or the record closes. Its `id` changes with every approval. */\n lastApplied: ImmersiveSnapshot[\"lastApplied\"];\n lastRunAt: number | null;\n recheck: ImmersiveController[\"recheck\"];\n /** Hides an open warning or info until its result changes. Blocking checks can't be acknowledged. */\n acknowledge: ImmersiveController[\"acknowledge\"];\n /**\n * Proposes the open check's `fix` (`{ field, value }`) as a draft in the field, for an \"Apply fix\" button. The user\n * still approves it in the field (`<BaseeraField>`). Resolves with their decision, or null when there is nothing to\n * show: no open check with that id, no field fix, or the field isn't on the screen.\n */\n applyCheckFix: ImmersiveController[\"applyCheckFix\"];\n /** Scrolls a bound field into view, focuses it and highlights it. Returns \"not_bound\" when it isn't on the screen. */\n focusField: ImmersiveController[\"focusField\"];\n /** Puts back what the last approved draft replaced, through the field's own `onChange`. False when there is nothing to undo. */\n undoLastDraft: ImmersiveController[\"undoLastDraft\"];\n /**\n * The finish guard (GNA-85): records the finish with Baseera, and only if that worked runs your `finish.action({ receipt,\n * override })`. Send the receipt to your finish route, which must call `verifyFinish` from `@baseera/node`. Resolves to\n * whether the action ran. Pass `{ override: { reason } }` to finish with blocking checks open. Never runs the action\n * when recording fails, when a blocking check could not run, or when `finish.closed` is true.\n */\n finish: ImmersiveController[\"finish\"];\n}\n\nconst SERVER_SNAPSHOT: ImmersiveSnapshot = createImmersiveController().getSnapshot();\nconst getServerSnapshot = () => SERVER_SNAPSHOT;\n\n/** The controller's snapshot as React state. Internal: the hooks and built-in tools of this package share it. */\nexport function useImmersiveSnapshot(): ImmersiveSnapshot {\n const { immersive } = useBaseeraInternals();\n return useSyncExternalStore(immersive.subscribe, immersive.getSnapshot, getServerSnapshot);\n}\n\n/** The immersive state, for the UI around the record (check list, finish button). Works anywhere under `<BaseeraProvider>`. */\nexport function useBaseeraImmersiveState(): BaseeraImmersiveState {\n const { immersive } = useBaseeraInternals();\n const snap = useSyncExternalStore(immersive.subscribe, immersive.getSnapshot, getServerSnapshot);\n return useMemo(() => {\n const open = snap.results.filter((r) => r.status === \"open\");\n return {\n active: snap.active,\n entity: snap.entity,\n openChecks: {\n blocking: open.filter((r) => r.severity === \"blocking\"),\n warning: open.filter((r) => r.severity === \"warning\"),\n info: open.filter((r) => r.severity === \"info\"),\n },\n results: snap.results,\n counts: snap.counts,\n canFinish: snap.canFinish,\n canOverride: snap.canOverride,\n openBlocking: snap.openBlocking,\n checksFailed: snap.checksFailed,\n finishStatus: snap.finishStatus,\n finishError: snap.finishError,\n finishLabel: snap.finishLabel,\n pendingDrafts: snap.pendingDrafts,\n aiChecks: snap.aiChecks,\n fieldLabels: snap.fieldLabels,\n boundFields: snap.boundFields,\n lastApplied: snap.lastApplied,\n lastRunAt: snap.lastRunAt,\n recheck: immersive.recheck,\n acknowledge: immersive.acknowledge,\n applyCheckFix: immersive.applyCheckFix,\n focusField: immersive.focusField,\n undoLastDraft: immersive.undoLastDraft,\n finish: immersive.finish,\n };\n }, [immersive, snap]);\n}\n\n/**\n * Returns `signal(name, data?)` (GNA-87): tell Baseera something happened in your UI that a check may depend on, such\n * as `signal(\"document.uploaded\", { name })`. While a record is in immersive mode the checks run again right away, each\n * check receives the latest signals as `run(record, { signals })`, and the signal is added to the record's trail\n * (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\n * record is open, the signal is ignored with a console warning in development. The function is stable.\n */\nexport function useBaseeraSignal(): (name: string, data?: unknown) => void {\n const { immersive } = useBaseeraInternals();\n return immersive.signal;\n}\n","import { createTenantUploadController, type TenantUploadController, type TenantUploadState, type UploadableFile } from \"@baseera/core\";\nimport { useEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { useBaseeraInternals } from \"./provider\";\n\nexport interface BaseeraKnowledgeUploadOptions {\n /**\n * Returns an upload token from YOUR server, which must first check that the signed-in user may manage this tenant's\n * documents, then sign the token with `signTenantUploadToken` from `@baseera/node` (it names the knowledge base, the tenant\n * and the user). Called when there is no token and again before the last one expires. Never sign it in the browser.\n */\n getUploadToken: () => Promise<string>;\n /** Milliseconds between refreshes while a document is being processed. Default 3000. */\n pollMs?: number;\n}\n\nexport interface BaseeraKnowledgeUpload extends TenantUploadState {\n /** Uploads files (the ones that pass the checks: PDF, DOCX, Markdown, TXT, HTML, CSV, up to 25 MB). */\n upload: (files: FileList | readonly UploadableFile[]) => Promise<void>;\n /** Deletes one of the tenant's own documents. Resolves true when it was deleted. */\n remove: (sourceId: string) => Promise<boolean>;\n refresh: () => Promise<void>;\n}\n\nconst SERVER_STATE: TenantUploadState = { sources: null, uploads: [], loading: true, error: null, disabled: false };\n\n/**\n * The tenant knowledge upload (GNA-66): the tenant's own documents with their status, and the upload flow. Inside\n * `<BaseeraProvider>` (it uses the provider's publishable key and URL). The tenant, knowledge base and user are not\n * arguments: they are in the token your server signs, so this component can never act for another tenant.\n */\nexport function useBaseeraKnowledgeUpload(options: BaseeraKnowledgeUploadOptions): BaseeraKnowledgeUpload {\n const { connection } = useBaseeraInternals();\n const tokenRef = useRef(options.getUploadToken);\n tokenRef.current = options.getUploadToken;\n const [controller] = useState<TenantUploadController>(() =>\n createTenantUploadController({ publishableKey: connection.publishableKey, baseUrl: connection.baseUrl, getUploadToken: () => tokenRef.current(), ...(options.pollMs ? { pollMs: options.pollMs } : {}) }),\n );\n const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot, () => SERVER_STATE);\n\n useEffect(() => {\n controller.start();\n return () => controller.stop();\n }, [controller]);\n\n return useMemo(\n () => ({\n ...state,\n upload: (files) => controller.upload(Array.from(files)),\n remove: controller.remove,\n refresh: controller.refresh,\n }),\n [controller, state],\n );\n}\n","import type { DraftSource, ImmersiveSeverity } from \"@baseera/core\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { useBaseeraInternals } from \"./provider\";\nimport { useImmersiveSnapshot } from \"./use-immersive\";\n\nconst MAX_REASON = 500;\nconst FOCUSABLE = 'input:not([type=\"hidden\"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), a[href], [contenteditable=\"true\"], [tabindex]:not([tabindex=\"-1\"])';\nconst SEVERITY_RANK: Record<ImmersiveSeverity, number> = { info: 1, warning: 2, blocking: 3 };\n\nexport interface BaseeraFieldOptions {\n /** The host's own change handler (`setValue`, React Hook Form's `field.onChange`). An approved draft is written through it, and nowhere else. */\n onChange: (value: unknown) => void;\n}\n\nexport interface BaseeraFieldDraft {\n value: unknown;\n reason: string;\n source: DraftSource;\n}\n\nexport interface BaseeraFieldFlag {\n /** The highest severity among the open checks that read this field. */\n severity: ImmersiveSeverity;\n /** The message of the first open check at that severity. */\n message: string;\n checkId: string;\n}\n\nexport interface BaseeraFieldState {\n /** A value proposed for this field, waiting for the user. It is a suggestion: the field's value is not touched until `approve()`. */\n draft: BaseeraFieldDraft | null;\n /** The worst open check on this field, or null. */\n flag: BaseeraFieldFlag | null;\n /** Set for 2 seconds after Baseera focused the field (`at` is when). Draw a highlight while it is set. */\n focused: { at: number } | null;\n /** Writes the draft's value through the host's `onChange`, then tells Baseera it was approved. */\n approve: () => void;\n /** Drops the draft and tells the model, with the user's reason if there is one. The field's value was never changed. */\n reject: (reason?: string) => void;\n /** Ref for the element that wraps the field. Baseera scrolls to it and focuses the first control inside it. */\n bindRef: (element: HTMLElement | null) => void;\n /** Moves keyboard focus to the first control in the wrapper, without scrolling. */\n focusControl: () => void;\n}\n\n/** The first control inside `root` that isn't part of Baseera's own UI (elements marked `data-baseera-ui`). */\nexport function firstControl(root: HTMLElement): HTMLElement | null {\n for (const el of root.querySelectorAll<HTMLElement>(FOCUSABLE)) if (!el.closest(\"[data-baseera-ui]\")) return el;\n return null;\n}\n\nfunction prefersReducedMotion(): boolean {\n try {\n return typeof window.matchMedia === \"function\" && window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n } catch {\n return false;\n }\n}\n\n/**\n * Headless binding of one host input to Baseera. Wrap the input in an element with `bindRef`, pass the host's\n * `onChange`, and draw `draft`, `flag` and `focused` however you like. `<BaseeraField>` in `@baseera/ui/connected` does that.\n *\n * While mounted, the field counts as \"on the screen\": Baseera can point at it (`ui.focusField`) and propose a value\n * for it (`ui.prefillDraft`) once the screen has called `useBaseeraImmersive` with a field of the same name.\n */\nexport function useBaseeraField(name: string, options: BaseeraFieldOptions): BaseeraFieldState {\n const { immersive } = useBaseeraInternals();\n const snap = useImmersiveSnapshot();\n const elementRef = useRef<HTMLElement | null>(null);\n const onChangeRef = useRef(options.onChange);\n onChangeRef.current = options.onChange;\n\n const focusControl = useCallback(() => {\n const el = elementRef.current;\n if (el) firstControl(el)?.focus({ preventScroll: true });\n }, []);\n\n useEffect(\n () =>\n immersive.bindField(name, {\n write(value) {\n onChangeRef.current(value);\n },\n focus() {\n const el = elementRef.current;\n if (!el) return;\n if (typeof el.scrollIntoView === \"function\") el.scrollIntoView({ block: \"center\", behavior: prefersReducedMotion() ? \"auto\" : \"smooth\" });\n firstControl(el)?.focus({ preventScroll: true });\n },\n }),\n [immersive, name],\n );\n\n const bindRef = useCallback((element: HTMLElement | null) => {\n elementRef.current = element;\n }, []);\n\n const pending = snap.pendingDrafts.find((d) => d.field === name);\n const draft = useMemo<BaseeraFieldDraft | null>(() => (pending ? { value: pending.value, reason: pending.reason, source: pending.source } : null), [pending]);\n\n const flag = useMemo<BaseeraFieldFlag | null>(() => {\n let best: BaseeraFieldFlag | null = null;\n for (const r of snap.results) {\n if (r.status !== \"open\" || !r.fields.includes(name)) continue;\n if (!best || SEVERITY_RANK[r.severity] > SEVERITY_RANK[best.severity]) best = { severity: r.severity, message: r.message, checkId: r.id };\n }\n return best;\n }, [snap.results, name]);\n\n const focusedAt = snap.focused?.field === name ? snap.focused.at : null;\n const focused = useMemo(() => (focusedAt === null ? null : { at: focusedAt }), [focusedAt]);\n\n const approve = useCallback(() => {\n const current = immersive.getSnapshot().pendingDrafts.find((d) => d.field === name);\n if (!current) return;\n const previous = immersive.readField(name);\n onChangeRef.current(current.value);\n immersive.resolveDraft(name, { approved: true }, { previous });\n }, [immersive, name]);\n\n const reject = useCallback(\n (reason?: string) => {\n const text = reason?.trim().slice(0, MAX_REASON);\n immersive.resolveDraft(name, { approved: false, ...(text ? { reason: text } : {}) });\n },\n [immersive, name],\n );\n\n return useMemo(() => ({ draft, flag, focused, approve, reject, bindRef, focusControl }), [draft, flag, focused, approve, reject, bindRef, focusControl]);\n}\n","import type { RegisteredTool, ToolKind } from \"@baseera/core\";\nimport { useEffect, useMemo, useRef } from \"react\";\nimport { z } from \"zod\";\nimport { useBaseeraInternals } from \"./provider\";\n\nconst NAME_PATTERN = /^[a-zA-Z0-9_.-]{1,64}$/;\nconst MAX_DESCRIPTION = 2000;\nconst MAX_SCHEMA_BYTES = 16_000;\nconst MAX_ERROR = 1000;\n\n/**\n * Registers a tool while the component is mounted. Re-renders don't re-register: the latest\n * `run`, `validate` and `describe` are read when a turn needs them. Only a change of `spec.name` re-registers.\n * Low-level: most apps want `useBaseeraTool`, which builds the tool from a Zod schema.\n */\nexport function useBaseeraToolDefinition(tool: RegisteredTool): void {\n const latest = useRef(tool);\n latest.current = tool;\n useRegistration(tool.spec.name, latest);\n}\n\nfunction useRegistration(key: string, latest: { current: RegisteredTool }): void {\n const { registry } = useBaseeraInternals();\n useEffect(() => {\n const registered: RegisteredTool = {\n get spec() {\n return latest.current.spec;\n },\n run: (input, context) => latest.current.run(input, context),\n get inlineApproval() {\n return latest.current.inlineApproval;\n },\n validate: (input) => (latest.current.validate ? latest.current.validate(input) : { ok: true, value: input }),\n describe: (input) => latest.current.describe?.(input) ?? \"\",\n // Present only while the latest registration has one: the controller offers Undo from this.\n get undo() {\n const undo = latest.current.undo;\n return undo ? (input: unknown, output: unknown) => latest.current.undo?.(input, output) : undefined;\n },\n };\n return registry.register(registered);\n }, [registry, key, latest]);\n}\n\nexport interface BaseeraToolOptions<S extends z.ZodObject> {\n /** Letters, digits, `_`, `.` and `-`, at most 64 characters. */\n name: string;\n /** Tells the model when to use the tool. 1 to 2,000 characters. */\n description: string;\n /** A `z.object(...)`. Sent to the model as JSON Schema; the model's input is validated against it. */\n input: S;\n /** `read` runs at once; `draft` and `write` wait for the user's approval. */\n kind: ToolKind;\n /** Gets the validated (parsed) input. Anything JSON-serializable can be returned; a thrown error goes to the model as a tool error. */\n run: (input: z.output<S>) => unknown | Promise<unknown>;\n /** A short sentence for the approval prompt (draft and write tools). */\n describe?: (input: z.output<S>) => string;\n /**\n * Reverses a done `draft` or `write` call. Gets the validated input and what `run` returned. With it, the\n * approval card offers Undo after the call is done. It is kept in memory for the page session only, and\n * the model is not told about an undo. Read through a ref, like `run`.\n */\n undo?: (input: z.output<S>, output: unknown) => void | Promise<void>;\n}\n\nconst schemaCache = new WeakMap<object, Record<string, unknown>>();\n\nfunction toWireSchema(name: string, input: unknown): Record<string, unknown> {\n const def = (input as { _zod?: { def?: { type?: string } } } | null)?._zod?.def;\n if (!input || typeof input !== \"object\" || def?.type !== \"object\") {\n throw new Error(`useBaseeraTool(\"${name}\"): \\`input\\` must be a z.object(...) schema.`);\n }\n const cached = schemaCache.get(input);\n if (cached) return cached;\n let json: Record<string, unknown>;\n try {\n json = { ...(z.toJSONSchema(input as z.ZodType) as Record<string, unknown>) };\n } catch (error) {\n throw new Error(`useBaseeraTool(\"${name}\"): the input schema cannot be converted to JSON Schema (${error instanceof Error ? error.message : \"unknown error\"}).`);\n }\n delete json.$schema;\n json.type = \"object\";\n const bytes = new TextEncoder().encode(JSON.stringify(json)).length;\n if (bytes > MAX_SCHEMA_BYTES) {\n throw new Error(`useBaseeraTool(\"${name}\"): the input schema is ${bytes} bytes as JSON Schema; the limit is ${MAX_SCHEMA_BYTES}.`);\n }\n schemaCache.set(input, json);\n return json;\n}\n\nfunction summarize(error: z.ZodError): string {\n let text: string;\n try {\n text = typeof z.prettifyError === \"function\" ? z.prettifyError(error) : \"\";\n } catch {\n text = \"\";\n }\n if (!text) text = error.issues.map((i) => `${i.path.join(\".\") || \"input\"}: ${i.message}`).join(\"; \");\n return text.slice(0, MAX_ERROR);\n}\n\n/**\n * Defines a tool the model can call, backed by this component's data and handlers. It is registered while the\n * component is mounted and sent with every turn. Invalid model input is rejected before `run`.\n */\nexport function useBaseeraTool<S extends z.ZodObject>(options: BaseeraToolOptions<S>): void {\n const { name, description, input, kind } = options;\n\n const spec = useMemo(() => {\n if (typeof name !== \"string\" || !NAME_PATTERN.test(name)) {\n throw new Error(`useBaseeraTool: invalid name ${JSON.stringify(name)}. Use 1 to 64 letters, digits, \"_\", \".\" or \"-\".`);\n }\n if (typeof description !== \"string\" || description.trim() === \"\" || description.length > MAX_DESCRIPTION) {\n throw new Error(`useBaseeraTool(\"${name}\"): \\`description\\` must be 1 to ${MAX_DESCRIPTION} characters.`);\n }\n return { name, description, kind, inputSchema: toWireSchema(name, input) };\n }, [name, description, kind, input]);\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const specRef = useRef(spec);\n specRef.current = spec;\n\n const latest = useRef<RegisteredTool | null>(null);\n latest.current ??= {\n get spec() {\n return specRef.current;\n },\n run: (value) => optionsRef.current.run(value as z.output<S>),\n validate: (value) => {\n const parsed = optionsRef.current.input.safeParse(value);\n return parsed.success ? { ok: true, value: parsed.data } : { ok: false, error: summarize(parsed.error) };\n },\n describe: (value) => optionsRef.current.describe?.(value as z.output<S>) ?? \"\",\n get undo() {\n return optionsRef.current.undo ? (value: unknown, output: unknown) => optionsRef.current.undo?.(value as z.output<S>, output) : undefined;\n },\n };\n\n const key = useMemo(() => JSON.stringify([spec.name, spec.kind, spec.description]), [spec]);\n useRegistration(`${key}:${schemaId(input)}`, latest as { current: RegisteredTool });\n}\n\nconst ids = new WeakMap<object, number>();\nlet nextId = 0;\nfunction schemaId(schema: object): number {\n let id = ids.get(schema);\n if (id === undefined) ids.set(schema, (id = ++nextId));\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAAyG;;;ACAzG,kBAAuB;AAMvB,IAAM,WAAW;AAKjB,SAAS,eAAwB;AAC/B,MAAI;AACF,WAAO,QAAQ,IAAI,aAAa;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAiBA,SAAS,MAAM,QAAqD;AAClE,QAAM,MAAmB,CAAC;AAC1B,aAAW,SAAS,QAAQ;AAC1B,QAAI,CAAC,MAAO;AACZ,QAAI,MAAM,SAAS,OAAW,KAAI,OAAO,MAAM;AAC/C,QAAI,MAAM,WAAW,OAAW,KAAI,SAAS,MAAM;AACnD,QAAI,MAAM,SAA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,KAAI,IAAI,QAAS,KAAK,EAAE,MAAO;AACrD,SAAO;AACT;;;AXvFA,IAAAC,eAAsD;","names":["import_core","import_core","import_react","import_react","import_react","import_react","getServerSnapshot","import_core","import_react","isProduction","getServerSnapshot","import_core","import_react","SERVER_STATE","import_react","MAX_REASON","import_core","import_react","import_core"]}
|
package/dist/index.d.cts
ADDED
|
@@ -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 };
|