@smartfront/core
v0.2.2
Published
Framework-independent TypeScript SDK for conversational application operations, live context and headless chat.
Maintainers
Readme
@smartfront/core
Add conversational controls to your application's existing operations.
Smartfront connects natural-language requests to functions you explicitly expose. Your application keeps its state and business logic; Smartfront supplies operation metadata, argument validation, chat state and execution controls.
This is the framework-independent TypeScript SDK. It is ESM-only, includes type declarations and is safe to import during server-side rendering.
Install
npm install @smartfront/coreWhat you can build
- A chat interface that calls existing services, store operations or use cases.
- A completely custom UI using observable chat state and typed events.
- Operations with typed parameters, live context and optional confirmations.
- Parameter forms for requests that still need user input.
- Application-authored answers and conversation data without a model request.
Each client owns its state and registrations. Core mounts no UI and injects no styles. React, Vue and Angular integrations are available separately below.
Quick start
You need a backend endpoint that implements Smartfront's chat protocol, such as
one built with @smartfront/server.
The /v1/chat URL below is your application's backend route. Keep model API keys
on that server; installing core alone does not provide a model connection.
Define an operation and the selected application state it can use:
import {
SmartClient,
defineSmartModule,
defineSmartfront,
freeText,
} from '@smartfront/core';
// Replace this example state with your existing store or service.
const tasks = [
{ id: 'T-1', title: 'Draft release notes', status: 'active' },
];
const taskModule = defineSmartModule({
name: 'tasks',
actions: {
archiveTask: {
description: 'Archive an existing task without deleting it',
examples: ['Archive task T-1'],
params: {
taskId: {
type: 'string',
description: 'ID of the task to archive',
source: 'board.tasks.id',
},
},
execute: ({ taskId }) => {
const task = tasks.find((item) => item.id === taskId);
if (!task) throw new Error('Task not found');
task.status = 'archived';
return { id: task.id, status: task.status };
},
},
},
contexts: {
board: {
get: () => ({
tasks: tasks.map(({ id, title, status }) => ({
id,
title: freeText(title),
status,
})),
}),
},
},
});Create the client and send a request:
const config = defineSmartfront({
endpoint: '/v1/chat',
guard: 'strict',
modules: [taskModule],
});
const client = new SmartClient(config);
await client.send('Archive task T-1');
// Read messages, operation results, pending forms and activity.
console.log(client.getState());The backend interprets the request using your operation metadata and selected
context. Core validates the returned arguments before calling execute in your
application. The source constraint above checks the task ID against live state.
Write clear operation and parameter descriptions and representative examples.
Smartfront learns the capabilities you declare; it does not discover your source
code or business rules automatically.
Build your own chat UI
Use the same client with a headless controller. Render its state with your own components and connect your controls to its bound methods:
import { createChatController } from '@smartfront/core';
const chat = createChatController(client);
// Read once for the initial render; subscribe to subsequent changes.
console.log(chat.getState());
const unsubscribe = chat.subscribe(() => {
console.log(chat.getState());
});
const unsubscribeEvents = chat.subscribeEvents((event) => {
console.log(event.type, event);
});Snapshots are cached and frozen. Typed events cover messages, operations, activity, parameter forms, context estimates, usage, conversation data and resets.
| Controller method | Purpose |
| --- | --- |
| send(text) | Send a user message. |
| cancel() | Cancel the active turn. |
| reset() | Reset the conversation. |
| confirm(id, approved, word?) | Approve or reject a pending operation. |
| submitParameters(id, values) | Submit a pending parameter form. |
| cancelParameters(id) | Dismiss a pending parameter form. |
| previewContext(draft?) | Estimate request size without calling a model. |
Validation, free text and confirmations
- Parameter schemas: declare types, enums, defaults and optional fields.
Operation handlers and previews infer their argument types from
params. - Live context: getters read selected state when needed. Use
sourcepaths such asboard.tasks.idto constrain arguments to existing values. - Free text: wrap user-written names, titles, comments and similar values
with
freeText()in contexts and handler results. In the defaultstrictguard mode, these values are hidden from the model. Refer to IDs or expose a local filtering operation when users need to find items by their text. - Missing parameters: a confidently identified single operation can open a
typed form for values still missing or ambiguous after interpretation. Render
getState().parameterFormand submit it throughsubmitParameters. - Confirmations: add
confirmation: { type: 'confirm' }to an operation definition to request approval before execution. Dangerous operations can useconfirmation: { type: 'danger', word: 'DELETE', wait: 3 }to require a typed word and a waiting period in seconds. Your UI supplies the user's decision throughconfirm; core checks the pending item ID, deadline and word.
Schema validation and confirmations complement your application's security. Enforce authentication and authorization at the application API boundary.
Add application answers and data
These methods update the conversation without making a model request:
client.appendAnswer('Task archived.', {
data: { taskId: 'T-1', status: 'archived' },
});
client.provideData('selection', { taskId: 'T-1' });
client.removeData('selection');Set includeInHistory: false in appendAnswer options for display-only output.
Operation handlers can also receive (args, calledBySmartFront, execution):
Smartfront supplies true as the second argument, while the optional third
argument provides scoped execution.chat methods and a cancellation signal.
The origin flag stays outside the operation's schema and business arguments.
Configuration
Pass these options to defineSmartfront() or directly to new SmartClient():
| Option | Purpose |
| --- | --- |
| endpoint | Required backend chat URL. |
| modules | Operation/context modules or factories resolved per client. |
| guard | Defaults to 'strict'; 'no-guard' sends marked free text. |
| headers | Request headers or a function returning them; supports async. |
| credentials | Fetch credentials policy for your backend. |
| persist | 'local', 'session' or false for browser persistence. |
| persistKey | Storage key for persisted conversations. |
| autoParameterForms | Defaults to true; set false to collect through chat. |
| contextWarningTokens | Heuristic context warning threshold; defaults to 8000. |
Chat state exposes activity, redacted request-size estimates and provider-reported usage. Context estimates are heuristic; they are not the provider's exact token count or a billing guarantee.
Dynamic registration and lifecycle
For component-local or dynamic integrations, use defineOperation(),
client.registerOperation() and client.registerContext() directly.
client.registerModules() supports adding modules after initialization.
Registrations and subscriptions return cleanup functions; duplicate names throw.
Clean up the subscriptions above and destroy the client when its owner is disposed:
unsubscribe();
unsubscribeEvents();
client.destroy();For SSR, keep clients and application dependencies separate for each request and destroy request-owned clients during teardown. Module factories resolve dependencies per client.
Related packages
| Package | Use it for |
| --- | --- |
| @smartfront/server | Backend routing, model integration and protocol handlers. |
| @smartfront/react | React providers, hooks and optional chat UI. |
| @smartfront/vue | Vue plugin, composables and optional chat UI. |
| @smartfront/angular | Angular service, Signals and optional chat UI. |
| @smartfront/vite | Optional extraction of @operation comment metadata. |
Framework adapters expose the same headless behavior. Their SmartChat component
is an unstyled input; choose SmartChatPanel for the complete supplied interface.
License
MIT.
