Skip to main content

Client SDK Reference

Complete API reference for the Diosc Assistant Kit.

Installation

NPM

npm install @diosc-ai/assistant-kit

Yarn

yarn add @diosc-ai/assistant-kit

pnpm

pnpm add @diosc-ai/assistant-kit

CDN

<!-- ESM (recommended) -->
<script type="module" src="https://unpkg.com/@diosc-ai/assistant-kit@latest/dist/assistant-kit/assistant-kit.esm.js"></script>

<!-- UMD (legacy browsers) -->
<script src="https://unpkg.com/@diosc-ai/assistant-kit@latest/dist/assistant-kit/assistant-kit.js"></script>

Components

<diosc-chat>

Full-featured chat interface with streaming responses, tool execution visualization, and approval dialogs.

Description

The main chat component provides a complete conversational AI interface with:

  • Real-time message streaming
  • Tool execution status visualization
  • User approval dialogs for sensitive operations
  • Error handling and recovery
  • Persistent conversation history
  • Responsive design

Usage

<diosc-chat
backend-url="https://your-hub.example.com"
api-key="your-api-key">
</diosc-chat>

Props

PropertyAttributeTypeDefaultDescription
apiKeyapi-keystringundefinedAPI key for initialization. Optional if set via diosc('config')
backendUrlbackend-urlstringundefinedBackend WebSocket/REST URL. Optional if set via diosc('config')

CSS Custom Properties

PropertyDefaultDescription
--primary-color#0891b2Primary theme color
--background-color#ffffffBackground color
--text-color#000000Text color
--border-radius8pxBorder radius for UI elements
--font-familySystem font stackFont family
--message-spacing12pxSpacing between messages
--input-height48pxHeight of input field
--chat-width400pxWidth of chat container (desktop)
--chat-max-height600pxMaximum height of chat

Example with Styling

<style>
diosc-chat {
--primary-color: #6366f1;
--background-color: #f9fafb;
--text-color: #111827;
--border-radius: 12px;
--font-family: 'Inter', sans-serif;
}

@media (prefers-color-scheme: dark) {
diosc-chat {
--background-color: #1f2937;
--text-color: #f9fafb;
}
}
</style>

<diosc-chat
backend-url="https://hub.example.com"
api-key="ast_abc123">
</diosc-chat>

<diosc-button>

AI-powered action button for quick operations without opening the chat interface.

Description

The button component allows users to trigger AI operations with a single click. Useful for:

  • Quick actions (summarize, translate, etc.)
  • Context-aware operations
  • Inline AI features

Usage

<!-- Static prompt -->
<diosc-button
prompt="Summarize this page"
response-type="modal">
Summarize
</diosc-button>

<!-- Dynamic prompt from function -->
<diosc-button
prompt-builder="buildPrompt"
response-type="toast">
Analyze
</diosc-button>

<script>
window.buildPrompt = () => {
const selection = window.getSelection().toString();
return `Analyze this text: ${selection}`;
};
</script>

Props

PropertyAttributeTypeDefaultDescription
promptpromptstringundefinedStatic prompt to send when clicked
promptBuilderprompt-builderstringundefinedName of global function that returns prompt dynamically
responseTyperesponse-type'modal' | 'toast' | 'target' | 'custom''modal'How to display the AI response
targetSelectortarget-selectorstringundefinedCSS selector for target element (when responseType='target')
disableddisabledbooleanfalseDisable the button

Events

EventPayload TypeDescription
dioscResponseanyEmitted when AI responds successfully. Payload is the response data.
dioscErrorErrorEmitted when an error occurs during invocation.

Response Types

modal (default) Opens a modal dialog with the response.

<diosc-button prompt="Summarize" response-type="modal">
Summarize
</diosc-button>

toast Shows a temporary toast notification.

<diosc-button prompt="Quick fact check" response-type="toast">
Fact Check
</diosc-button>

target Injects response into a target element.

<div id="summary-output"></div>

<diosc-button
prompt="Summarize this article"
response-type="target"
target-selector="#summary-output">
Summarize
</diosc-button>

custom Emit event only, handle response yourself.

<diosc-button prompt="Analyze" response-type="custom">
Analyze
</diosc-button>

<script>
document.querySelector('diosc-button').addEventListener('dioscResponse', (e) => {
console.log('Custom handling:', e.detail);
// Your custom logic
});
</script>

Example: Context-Aware Button

<article id="blog-post">
<h1>Article Title</h1>
<p>Article content...</p>
</article>

<diosc-button
prompt-builder="summarizeArticle"
response-type="target"
target-selector="#summary">
Generate Summary
</diosc-button>

<div id="summary"></div>

<script>
window.summarizeArticle = () => {
const article = document.getElementById('blog-post');
const title = article.querySelector('h1').textContent;
const content = article.querySelector('p').textContent;
return `Summarize this article titled "${title}": ${content}`;
};
</script>

<diosc-form>

AI-enhanced form wrapper that processes submissions through the AI assistant.

Description

Wraps standard HTML forms to process submissions via AI. The AI can:

  • Validate form data
  • Process natural language input
  • Transform data before submission
  • Provide intelligent feedback

Usage

<diosc-form
prompt-builder="buildFormPrompt"
response-type="redirect"
success-redirect="/confirmation"
clear-on-success>

<form>
<label>
Email:
<input name="email" type="email" required>
</label>

<label>
Message:
<textarea name="message" required></textarea>
</label>

<button type="submit">Submit</button>
</form>
</diosc-form>

<script>
window.buildFormPrompt = (formData) => {
const email = formData.get('email');
const message = formData.get('message');
return `Process contact form submission from ${email}: "${message}"`;
};
</script>

Props

PropertyAttributeTypeDefaultDescription
promptBuilderprompt-builderstringrequiredName of global function that builds prompt from FormData
responseTyperesponse-type'modal' | 'redirect' | 'target' | 'custom''modal'How to handle AI response
successRedirectsuccess-redirectstringundefinedURL to redirect to on success (when responseType='redirect')
targetSelectortarget-selectorstringundefinedCSS selector for target element (when responseType='target')
validateBeforeSubmitvalidate-before-submitbooleantrueRun HTML5 validation before submission
clearOnSuccessclear-on-successbooleanfalseClear form fields after successful submission

Events

EventPayload TypeDescription
dioscFormSubmitting{ formData: FormData }Emitted when form is being submitted
dioscFormSuccess{ response: any, formData: FormData }Emitted when AI responds successfully
dioscFormError{ error: Error, formData: FormData }Emitted when an error occurs

Prompt Builder Function

The promptBuilder function receives FormData and should return a string prompt:

function buildFormPrompt(formData: FormData): string {
// Access form fields
const name = formData.get('name');
const email = formData.get('email');

// Access multiple values (checkboxes, etc.)
const interests = formData.getAll('interests');

// Build prompt
return `Create user profile: name=${name}, email=${email}, interests=${interests.join(', ')}`;
}

Example: Smart Contact Form

<diosc-form
prompt-builder="processContact"
response-type="modal"
clear-on-success
validate-before-submit>

<form>
<h2>Contact Us</h2>

<input
name="name"
placeholder="Your name"
required>

<input
name="email"
type="email"
placeholder="your@email.com"
required>

<select name="topic" required>
<option value="">Select topic...</option>
<option value="sales">Sales</option>
<option value="support">Support</option>
<option value="other">Other</option>
</select>

<textarea
name="message"
placeholder="Your message"
required>
</textarea>

<button type="submit">Send Message</button>
</form>
</diosc-form>

<script>
window.processContact = (formData) => {
return `Process contact form:
Name: ${formData.get('name')}
Email: ${formData.get('email')}
Topic: ${formData.get('topic')}
Message: ${formData.get('message')}

Please validate the information and create a support ticket.`;
};

// Listen for events
const form = document.querySelector('diosc-form');

form.addEventListener('dioscFormSubmitting', () => {
console.log('Submitting to AI...');
});

form.addEventListener('dioscFormSuccess', (e) => {
console.log('Success:', e.detail.response);
});

form.addEventListener('dioscFormError', (e) => {
console.error('Error:', e.detail.error);
});
</script>

Core API

diosc(...args)

Main entry point for the command-queue API. Follows the gtag/dataLayer pattern.

function diosc(command: string, ...args: any[]): any

Example

import { diosc } from '@diosc-ai/assistant-kit';

// Configure
diosc('config', { backendUrl: '...', apiKey: '...' });

// Send message
diosc('invoke', 'Hello!');

// Listen for events
diosc('on', 'message', (msg) => console.log(msg));

diosc('config', options)

Configure the Diosc core.

Signature

diosc('config', options: DioscConfig): void

Parameters

DioscConfig:

PropertyTypeDefaultDescription
backendUrlstringundefinedBackend WebSocket/REST URL
apiKeystringundefinedAPI key for authentication
autoConnectbooleanfalseAutomatically connect on initialization
autoObserveNavigationbooleantrueAutomatically observe navigation changes
verbosebooleanfalseEnable verbose logging
reconnectAttemptsnumber5Number of reconnection attempts
reconnectDelaynumber1000Initial reconnection delay (ms)
reconnectDelayMaxnumber5000Maximum reconnection delay (ms)
connectionTimeoutnumber20000Connection timeout (ms)

Example

diosc('config', {
backendUrl: 'https://hub.example.com',
apiKey: 'ast_abc123',
autoConnect: true,
verbose: true,
reconnectAttempts: 10,
reconnectDelay: 2000
});

diosc('auth', provider)

Set authentication provider for BYOA (Bring Your Own Auth).

Signature

diosc('auth', provider: AuthProvider): void

type AuthProvider = () => AuthContext | Promise<AuthContext>

interface AuthContext {
headers?: Record<string, string>;
cookies?: Record<string, string>;
userId?: string;
tenantId?: string;
userMetadata?: Record<string, any>;
expiresAt?: number;
}

Parameters

AuthProvider: Function that returns authentication context. Can be sync or async.

Examples

Simple static token:

diosc('auth', () => ({
headers: {
'Authorization': 'Bearer my-token'
}
}));

Dynamic token with refresh:

diosc('auth', async () => {
// Refresh if needed
if (isTokenExpiringSoon()) {
await refreshToken();
}

return {
headers: {
'Authorization': `Bearer ${getAccessToken()}`
},
userId: getCurrentUserId(),
tenantId: getCurrentTenantId(),
expiresAt: getTokenExpiry()
};
});

With cookies:

diosc('auth', () => ({
headers: {
'X-CSRF-Token': getCsrfToken()
},
cookies: {
'session_id': getSessionId()
}
}));

See the Authentication Guide for complete patterns.


diosc('invoke', message, options?)

Send a message to the AI assistant.

Signature

diosc('invoke', message: string, options?: InvokeOptions): Promise<DioscResponse>

// Or with callback
diosc('invoke', message: string, callback: (response: DioscResponse) => void): void

interface InvokeOptions {
threadId?: string;
createThread?: boolean;
context?: Record<string, any>;
metadata?: Record<string, any>;
timeout?: number;
}

interface DioscResponse {
content: string;
threadId: string;
messageId: string;
metadata?: Record<string, any>;
}

Examples

Simple invocation:

const response = await diosc('invoke', 'Hello, AI!');
console.log(response.content);

With options:

const response = await diosc('invoke', 'Analyze this data', {
threadId: 'existing-thread-id',
timeout: 30000,
context: {
pageType: 'analytics-dashboard',
dataSource: 'postgres'
}
});

With callback (legacy style):

diosc('invoke', 'Hello!', (response) => {
console.log('Got response:', response.content);
});

Create new thread:

const response = await diosc('invoke', 'Start new conversation', {
createThread: true
});
console.log('New thread ID:', response.threadId);

diosc('on', event, handler)

Subscribe to events.

Signature

diosc('on', event: DioscEvent, handler: EventHandler): () => void

type EventHandler<T = any> = (data: T) => void

Returns

Unsubscribe function.

Available Events

EventPayload TypeDescription
readyvoidCore initialized and ready
connectedvoidWebSocket connected
disconnectedvoidWebSocket disconnected
connectingvoidWebSocket connecting
reconnectingvoidWebSocket reconnecting
authenticatedAuthenticatedEventWebSocket authenticated
assistant_config_loadedAssistantPublicConfigAssistant config fetched
session_startedSessionStartedEventNew session started
session_joinedSessionJoinedEventJoined existing session
messageMessageNew message received
message_sentMessageMessage sent
tokenTokenEventStreaming token received
stream_start{ runId: string }Streaming started
stream_end{ runId: string }Streaming ended
thread_createdThreadMetadataNew thread created
thread_joinedThreadJoinedEventJoined thread
thread_switched{ threadId: string }Switched to different thread
approval_requiredApprovalRequestUser approval needed for tool
approval_decidedApprovalDecisionRecordedApproval decision made
tool_requestToolRequestTool execution requested
tool_execution_startToolExecutionTool execution started
tool_execution_completeToolExecutionTool execution completed
tool_execution_errorToolExecutionTool execution failed
tool_rejectedToolRejectedEventTool execution rejected
context_switchContextSwitchEventNavigation context changed
auth_refresh_requiredAuthRefreshRequiredEventAuth refresh needed
auth_refreshedvoidAuth successfully refreshed
auth_failedDioscErrorAuth failed
errorDioscErrorError occurred
navigationNavigationDataPage navigation detected
path_changedPathChangedEventPath changed on server
state_changedDioscStateCore state changed

Examples

Listen for messages:

const unsubscribe = diosc('on', 'message', (message) => {
console.log(`${message.role}: ${message.content}`);
});

// Later: unsubscribe()

Listen for streaming tokens:

diosc('on', 'token', ({ token, runId, type }) => {
if (type === 'content') {
process.stdout.write(token); // Live streaming display
}
});

Listen for errors:

diosc('on', 'error', (error) => {
console.error('Diosc error:', {
code: error.code,
message: error.message,
recoverable: error.recoverable,
suggestedAction: error.suggestedAction
});

if (!error.recoverable) {
// Handle fatal error
showErrorModal(error.message);
}
});

Listen for tool execution:

diosc('on', 'tool_execution_start', (execution) => {
console.log(`Tool started: ${execution.toolName}`);
showToolSpinner(execution.id);
});

diosc('on', 'tool_execution_complete', (execution) => {
console.log(`Tool completed in ${execution.durationMs}ms`);
hideToolSpinner(execution.id);
showToolResult(execution.result);
});

Listen for connection changes:

diosc('on', 'connected', () => {
console.log('Connected to Diosc Hub');
showConnectionStatus('online');
});

diosc('on', 'disconnected', () => {
console.log('Disconnected from Diosc Hub');
showConnectionStatus('offline');
});

diosc('on', 'reconnecting', () => {
console.log('Reconnecting...');
showConnectionStatus('reconnecting');
});

diosc('tool', toolName, handler)

Register custom tool handler for browser-side execution.

Signature

diosc('tool', toolName: string, handler: ToolHandler): void

type ToolHandler = (
params: Record<string, unknown>,
context: ToolExecutionContext
) => Promise<ToolResult> | ToolResult

interface ToolExecutionContext {
toolCallId: string;
threadId: string;
runId: string;
userId: string;
pageContext: PageContext;
abort: () => void;
}

interface ToolResult {
success: boolean;
data?: any;
error?: string;
metadata?: Record<string, any>;
}

Examples

Simple tool:

diosc('tool', 'get_page_title', () => ({
success: true,
data: { title: document.title }
}));

Async tool:

diosc('tool', 'get_current_location', async () => {
return new Promise((resolve) => {
navigator.geolocation.getCurrentPosition(
(pos) => resolve({
success: true,
data: {
lat: pos.coords.latitude,
lng: pos.coords.longitude
}
}),
(err) => resolve({
success: false,
error: err.message
})
);
});
});

Tool with parameters:

diosc('tool', 'highlight_text', async (params) => {
const { text, color } = params;

try {
const selection = window.getSelection();
const range = document.createRange();
// ... highlighting logic

return {
success: true,
data: { highlighted: true, text }
};
} catch (error) {
return {
success: false,
error: error.message
};
}
});

Tool with context:

diosc('tool', 'save_user_preference', async (params, context) => {
const { key, value } = params;
const { userId } = context;

// Save to localStorage with user scoping
const storageKey = `pref_${userId}_${key}`;
localStorage.setItem(storageKey, JSON.stringify(value));

return {
success: true,
data: { saved: true, userId, key },
metadata: { timestamp: Date.now() }
};
});

diosc('observe', type, observer)

Register custom navigation observer for SPA frameworks.

Signature

diosc('observe', type: 'navigation', observer: NavigationObserverCallback): () => void

type NavigationObserverCallback = (
notify: (data: NavigationData) => void
) => void | (() => void)

interface NavigationData {
path: string;
search?: string;
hash?: string;
state?: any;
previousPath?: string;
}

Returns

Unsubscribe function.

Examples

React Router v6:

import { useLocation } from 'react-router-dom';
import { diosc } from '@diosc-ai/assistant-kit';

function App() {
const location = useLocation();

useEffect(() => {
const unsubscribe = diosc('observe', 'navigation', (notify) => {
notify({
path: location.pathname,
search: location.search,
hash: location.hash,
state: location.state
});
});

return unsubscribe;
}, [location]);

return <div>...</div>;
}

Vue Router:

import { watch } from 'vue';
import { useRoute } from 'vue-router';
import { diosc } from '@diosc-ai/assistant-kit';

export default {
setup() {
const route = useRoute();

onMounted(() => {
const unwatch = diosc('observe', 'navigation', (notify) => {
const stopWatch = watch(
() => route.path,
(path) => {
notify({
path,
search: route.query ? '?' + new URLSearchParams(route.query).toString() : '',
hash: route.hash
});
}
);

return stopWatch; // Return cleanup function
});
});
}
};

Helper Functions:

import {
createReactRouterObserver,
createVueRouterObserver,
createNextJsObserver
} from '@diosc-ai/assistant-kit';

// React Router
const unsubscribe = createReactRouterObserver();

// Vue Router
const unsubscribe = createVueRouterObserver();

// Next.js
const unsubscribe = createNextJsObserver();

Other Commands

diosc('connect')

Manually connect to WebSocket.

diosc('connect'): Promise<void>

diosc('disconnect')

Disconnect from WebSocket.

diosc('disconnect'): void

diosc('open') / diosc('close') / diosc('toggle')

Control chat UI visibility.

diosc('open'): void
diosc('close'): void
diosc('toggle'): void

diosc('setThread', threadId)

Switch to a specific thread.

diosc('setThread', threadId: string): void

diosc('newThread', metadata?)

Create a new thread.

diosc('newThread', metadata?: Record<string, unknown>): Promise<ThreadMetadata>

diosc('approve', approvalId) / diosc('reject', approvalId, reason?)

Respond to approval requests.

diosc('approve', approvalId: string): void
diosc('reject', approvalId: string, reason?: string): void

Factory Functions

Advanced users can create instances of core managers directly.

getDioscCore()

Get the singleton DioscCore instance.

import { getDioscCore } from '@diosc-ai/assistant-kit';

const core = getDioscCore();
const state = core.getState();
console.log('Connected:', state.connected);

createStateStore()

Create a state store instance.

import { createStateStore, DioscConfig } from '@diosc-ai/assistant-kit';

const config: DioscConfig = { ... };
const store = createStateStore(config);

Other Factory Functions

import {
createEventBus,
createAuthManager,
createContextProvider,
createToolExecutor,
createNavigationObserver,
createWebSocketManager
} from '@diosc-ai/assistant-kit';

Types

Core Types

DioscState

Central state managed by the core.

interface DioscState {
// Core status
ready: boolean;
config: DioscConfig;

// Assistant
assistantInfo: AssistantInfo | null;
assistantConfig?: AssistantPublicConfig;

// Session
currentSessionId?: string;
sessionType?: 'chat' | 'action';

// Connection
connected: boolean;
connecting: boolean;
connectionError: Error | null;

// Auth & User
auth: AuthContext | null;
user: UserInfo | null;

// Context
context: PageContext;

// Thread & Messages
currentThreadId: string | null;
currentRunId: string | null;
threads: Map<string, ThreadMetadata>;
messages: Map<string, Message[]>;
streamingMessage: StreamingMessage | null;

// Approvals
pendingApprovals: ApprovalRequest[];

// Tools
availableTools: ToolDefinition[];
executingTools: Map<string, ToolExecution>;

// UI State
isOpen: boolean;
isLoading: boolean;

// Errors
lastError: DioscError | null;
}

Message

Message structure.

interface Message {
id: string;
threadId?: string;
role: 'human' | 'ai' | 'tool' | 'system' | 'execution_step' | 'context_switch';
content: string;
timestamp: string;
toolCalls?: ToolCall[];
metadata?: Record<string, any>;
}

ApprovalRequest

User approval request for sensitive tool execution.

interface ApprovalRequest {
approvalId: string;
runId: string;
toolCallId: string;
toolName: string;
toolParameters: Record<string, unknown>;
timeoutSeconds: number;
expiresAt: string;
policyDescription?: string;
requestedAt: Date;
severity?: 'low' | 'medium' | 'high' | 'critical';
icon?: string;
}

DioscError

Error structure.

interface DioscError {
code: string;
message: string;
recoverable: boolean;
timestamp: string;
suggestedAction?: string;
details?: any;
sessionId?: string;
runId?: string;
}

Complete Type Exports

All types are exported from the package:

import type {
// State types
DioscState,
StreamingMessage,
ToolExecution,
ApprovalRequest,
AssistantInfo,
DioscError,

// Config types
DioscConfig,
PageContext,

// Event types
DioscEvent,
EventHandler,
Unsubscribe,

// Tool types
ToolHandler,
ToolExecutionContext,
ToolResult,
ToolRequest,

// Navigation types
NavigationData,
NavigationObserverCallback,

// Message types
Message
} from '@diosc-ai/assistant-kit';

Error Handling

Common Error Codes

CodeDescriptionRecoverableSuggested Action
NOT_CONNECTEDWebSocket not connectedYesCall diosc('connect')
AUTH_EXPIREDAuthentication token expiredYesRefresh token
AUTH_INVALIDInvalid credentialsNoRedirect to login
AUTH_FAILEDAuthentication failedNoShow error, redirect to login
TOOL_EXECUTION_FAILEDTool execution errorYesRetry or show error
TIMEOUTRequest timeoutYesRetry
SESSION_NOT_FOUNDSession doesn't existYesCreate new session

Error Handling Pattern

diosc('on', 'error', (error: DioscError) => {
console.error(`[${error.code}] ${error.message}`);

switch (error.code) {
case 'AUTH_EXPIRED':
// Try to refresh
refreshTokenAndReconnect();
break;

case 'AUTH_FAILED':
case 'AUTH_INVALID':
// Redirect to login
window.location.href = '/login';
break;

case 'NOT_CONNECTED':
// Try to reconnect
diosc('connect');
break;

case 'TIMEOUT':
// Show retry option
showRetryDialog();
break;

default:
if (!error.recoverable) {
showFatalErrorModal(error.message);
} else {
showErrorToast(error.message);
}
}
});

Best Practices

1. Always Configure Before Using

// Configure first
diosc('config', {
backendUrl: process.env.HUB_URL,
apiKey: process.env.API_KEY,
autoConnect: true
});

// Then use
diosc('auth', authProvider);
diosc('invoke', 'Hello!');

2. Handle Errors Gracefully

diosc('on', 'error', handleError);
diosc('on', 'auth_failed', redirectToLogin);

3. Clean Up Event Listeners

const unsubscribe = diosc('on', 'message', handler);

// Later or on component unmount
unsubscribe();

4. Use TypeScript for Type Safety

import { DioscConfig, ToolHandler } from '@diosc-ai/assistant-kit';

const config: DioscConfig = { ... };
const handler: ToolHandler = async (params, context) => { ... };

5. Enable Verbose Mode in Development

diosc('config', {
verbose: process.env.NODE_ENV === 'development',
backendUrl: process.env.HUB_URL,
apiKey: process.env.API_KEY
});

Migration Guide

From v1.x to v2.0

The v2.0 release introduces the centralized core layer with the diosc() API.

Before (v1.x):

<diosc-agent
client-id="xxx"
api-key="yyy"
base-url="zzz">
</diosc-agent>

After (v2.0):

import { diosc } from '@diosc-ai/assistant-kit';

diosc('config', {
backendUrl: 'zzz',
apiKey: 'yyy',
autoConnect: true
});
<diosc-chat></diosc-chat>

Key Changes:

  1. diosc-agentdiosc-chat component
  2. Centralized configuration via diosc('config')
  3. Event-driven architecture via diosc('on', event, handler)
  4. New diosc-button and diosc-form components

For more information, see: