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
- File upload and management
- Session history with search
- Token quota tracking
- Error handling and recovery
- Responsive design
Usage
<diosc-chat
backend-url="https://your-hub.example.com"
api-key="your-api-key">
</diosc-chat>
Props
| Property | Attribute | Type | Default | Description |
|---|---|---|---|---|
apiKey | api-key | string | undefined | API key for initialization. Optional if set via diosc('config') |
backendUrl | backend-url | string | undefined | Backend WebSocket/REST URL. Optional if set via diosc('config') |
CSS Custom Properties
| Property | Default | Description |
|---|---|---|
--primary-color | #0891b2 | Primary theme color |
--background-color | #ffffff | Background color |
--text-color | #000000 | Text color |
--border-radius | 8px | Border radius for UI elements |
--font-family | System font stack | Font family |
--message-spacing | 12px | Spacing between messages |
--input-height | 48px | Height of input field |
--chat-width | 400px | Width of chat container (desktop) |
--chat-max-height | 600px | Maximum 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
| Property | Attribute | Type | Default | Description |
|---|---|---|---|---|
prompt | prompt | string | undefined | Static prompt to send when clicked |
promptBuilder | prompt-builder | string | undefined | Name of global function that returns prompt dynamically |
responseType | response-type | 'modal' | 'toast' | 'target' | 'custom' | 'modal' | How to display the AI response |
targetSelector | target-selector | string | undefined | CSS selector for target element (when responseType='target') |
disabled | disabled | boolean | false | Disable the button |
Events
| Event | Payload Type | Description |
|---|---|---|
dioscResponse | any | Emitted when AI responds successfully. Payload is the response data. |
dioscError | Error | Emitted 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>
<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
| Property | Attribute | Type | Default | Description |
|---|---|---|---|---|
promptBuilder | prompt-builder | string | required | Name of global function that builds prompt from FormData |
responseType | response-type | 'modal' | 'redirect' | 'target' | 'custom' | 'modal' | How to handle AI response |
successRedirect | success-redirect | string | undefined | URL to redirect to on success (when responseType='redirect') |
targetSelector | target-selector | string | undefined | CSS selector for target element (when responseType='target') |
validateBeforeSubmit | validate-before-submit | boolean | true | Run HTML5 validation before submission |
clearOnSuccess | clear-on-success | boolean | false | Clear form fields after successful submission |
Events
| Event | Payload Type | Description |
|---|---|---|
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(', ')}`;
}
<diosc-file-upload>
File upload component with progress tracking and validation.
Description
Allows users to upload files to a session or user context. Supports:
- Multi-file upload
- File type validation
- Size validation
- Upload progress tracking
- Multiple display variants
Usage
<diosc-file-upload
api-url="https://hub.example.com"
auth-token="Bearer my-token"
assistant-id="ast_123"
session-id="sess_456">
</diosc-file-upload>
Props
| Property | Attribute | Type | Default | Description |
|---|---|---|---|---|
apiUrl | api-url | string | required | Backend API base URL |
assistantId | assistant-id | string | undefined | Assistant ID for upload context |
sessionId | session-id | string | undefined | Session ID for upload context |
authToken | auth-token | string | required | Authorization token |
accept | accept | string | .pdf,.xlsx,.xls,.csv,.docx,.txt,.md,.json,.png,.jpg,.jpeg | Accepted file types |
maxSize | max-size | number | 104857600 (100 MB) | Maximum file size in bytes |
multiple | multiple | boolean | true | Allow multiple file selection |
variant | variant | 'icon' | 'button' | 'text' | 'icon' | Button display variant |
Events
| Event | Payload Type | Description |
|---|---|---|
fileSelected | File[] | Files selected by user |
uploadStarted | { fileId: string, filename: string } | Upload initiated |
uploadProgress | { fileId: string, progress: number } | Upload progress (0-100) |
uploadComplete | { fileId: string, file: FileMetadata } | Upload finished successfully |
uploadError | { fileId: string, error: string } | Upload failed |
<ai-intent>
Declares a section of UI as an AI-invokable action. Enables the assistant to interact with your application's UI through structured intents.
Description
Wrap UI elements with <ai-intent> to expose them as actions the AI can invoke. Useful for:
- Letting the AI fill forms on behalf of the user
- Navigating the application
- Triggering UI actions with confirmation
Usage
<ai-intent
name="fill-search"
description="Fill the search box with a query"
params="query">
<input id="search" type="text" data-param="query">
</ai-intent>
Props
| Property | Attribute | Type | Default | Description |
|---|---|---|---|---|
name | name | string | required | Unique intent identifier |
description | description | string | required | Human-readable description of what this intent does |
params | params | string | undefined | Comma-separated parameter names |
mapping | mapping | string (JSON) | undefined | Explicit selector/action mapping (JSON) |
confirm | confirm | boolean | false | Require user confirmation before execution |
disabled | disabled | boolean | false | Mark intent as unavailable |
Methods
| Method | Signature | Description |
|---|---|---|
setExecuteHandler | (handler: (params) => Promise<any>) => void | Set a custom execution handler |
execute | (params: Record<string, any>) => Promise<any> | Execute the intent programmatically |
Auto-Mapping
Child elements with data-param attributes are automatically mapped to intent parameters:
<ai-intent name="create-order" description="Create a new order" params="product,quantity">
<input data-param="product" placeholder="Product name">
<input data-param="quantity" type="number" placeholder="Quantity">
<button data-action="submit">Create</button>
</ai-intent>
Explicit Mapping
For complex UIs, use the mapping prop with JSON:
<ai-intent
name="update-settings"
description="Update user settings"
params="theme,language"
mapping='{"theme": {"selector": "#theme-select", "action": "select"}, "language": {"selector": "#lang-select", "action": "select"}}'>
<select id="theme-select">...</select>
<select id="lang-select">...</select>
</ai-intent>
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
// Configure
diosc('config', { backendUrl: '...', apiKey: '...' });
// Set auth context
diosc('auth', { headers: { Authorization: 'Bearer token' }, userId: 'user-1' });
// Listen for events
diosc('on', 'stream:chunk', (data) => console.log(data.content));
diosc('config', options)
Configure the Diosc engine.
Signature
diosc('config', options: EngineConfig): void
Parameters
EngineConfig:
| Property | Type | Default | Description |
|---|---|---|---|
backendUrl | string | undefined | Backend WebSocket/REST URL |
apiKey | string | undefined | API key for authentication |
assistantId | string | undefined | Specific assistant ID to connect to |
verbose | boolean | false | Enable verbose logging |
autoConnect | boolean | false | Automatically connect when auth is provided |
reconnectAttempts | number | 5 | Number of reconnection attempts |
reconnectDelay | number | 1000 | Initial reconnection delay (ms) |
reconnectDelayMax | number | 5000 | Maximum reconnection delay (ms) |
connectionTimeout | number | 20000 | Connection timeout (ms) |
Example
diosc('config', {
backendUrl: 'https://hub.example.com',
apiKey: 'ast_abc123',
verbose: true,
reconnectAttempts: 10,
reconnectDelay: 2000
});
diosc('auth', context)
Push authentication context for BYOA (Bring Your Own Auth). This is a reactive, value-based API — push the current auth context directly, or null to log out.
The engine derives lifecycle transitions automatically:
null→ context = login (connects WebSocket, starts session)- context →
null= logout (disconnects, clears state) - context → different userId = user switch (full teardown + reconnect)
- context → same userId, new token = token refresh (updates in-place)
Signature
diosc('auth', context: AuthContext | null): void
interface AuthContext {
headers?: Record<string, string>;
cookies?: Record<string, string>;
userId?: string;
tenantId?: string;
userMetadata?: Record<string, any>;
expiresAt?: number; // ms since epoch
}
Examples
Login with a bearer token:
diosc('auth', {
headers: {
'Authorization': 'Bearer my-token'
},
userId: 'user-123',
tenantId: 'acme-corp'
});
Logout:
diosc('auth', null);
Token refresh (same userId, new token):
diosc('auth', {
headers: {
'Authorization': `Bearer ${newToken}`
},
userId: 'user-123', // same user — engine detects TOKEN_REFRESH
expiresAt: Date.now() + 3600000
});
With cookies:
diosc('auth', {
headers: {
'X-CSRF-Token': getCsrfToken()
},
cookies: {
'session_id': getSessionId()
},
userId: 'user-456'
});
Auth headers are forwarded opaquely through Diosc Hub to your MCP servers and user-resolver webhooks. Diosc never inspects, decodes, or stores your tokens. See BYOA and Credential-Blind Architecture for details.
diosc('invoke', message, options?)
Send a message to the AI assistant.
Signature
diosc('invoke', message: string, options?: { pageContext?: any }): void
Examples
Simple message:
diosc('invoke', 'Hello, AI!');
With page context:
diosc('invoke', 'Analyze this page', {
pageContext: {
path: '/dashboard',
pageType: 'analytics',
data: { reportId: '123' }
}
});
Messages are sent through the active WebSocket session. The response arrives as streaming events (stream:start, stream:chunk, stream:end) — subscribe with diosc('on', ...) to receive them. The <diosc-chat> component handles this automatically.
diosc('on', event, handler)
Subscribe to events.
Signature
diosc('on', event: string, handler: (data: any) => void): () => void
Returns
Unsubscribe function.
Available Events
Connection lifecycle:
| Event | Payload | Description |
|---|---|---|
authenticated | { assistantId } | WebSocket authenticated with hub |
disconnected | { reason } | WebSocket disconnected |
reconnected | {} | WebSocket reconnected after drop |
rate_limited | { retryAfterMs, code?, message? } | Rate limited by server |
Session lifecycle:
| Event | Payload | Description |
|---|---|---|
session:started | { session, token } | New session created |
session:joined | { session, messages? } | Joined existing session |
session:restored | { session, messages?, token?, files? } | Session restored from token |
session:restore_failed | { code, message } | Session restore failed |
session:error | { code, message, recoverable?, suggestedAction? } | Session error |
session:renamed | { sessionId, name } | Session renamed |
session:pinned | { sessionId, isPinned } | Session pinned/unpinned |
Streaming:
| Event | Payload | Description |
|---|---|---|
stream:start | { messageId? } | AI started streaming a response |
stream:chunk | { content } | Streaming content chunk |
stream:end | { messageId?, error? } | Streaming completed |
Tool execution:
| Event | Payload | Description |
|---|---|---|
tool:started | { toolCallId, toolName, toolParameters?, description? } | Tool execution started |
tool:completed | { toolCallId, toolName, success?, resultSummary?, durationMs? } | Tool execution completed |
tool:failed | { toolCallId, toolName, errorMessage?, durationMs? } | Tool execution failed |
Approvals:
| Event | Payload | Description |
|---|---|---|
approval:request | { toolCalls, approvalConfig?, proposedChanges?, entityContext? } | User approval required for tool(s) |
Files:
| Event | Payload | Description |
|---|---|---|
files:updated | { fileId?, files? } | Session files updated |
Auth:
| Event | Payload | Description |
|---|---|---|
auth:refresh_required | { reason } | Token refresh needed |
auth:refresh_success | {} | Token refreshed |
auth:refresh_failed | { reason } | Token refresh failed |
Content moderation:
| Event | Payload | Description |
|---|---|---|
content_blocked | { reason, category? } | Content blocked by moderation |
Quota:
| Event | Payload | Description |
|---|---|---|
quota:status | { used, limit, percentUsed, blocked, warning, windowExpiresAt } | Quota status update |
quota:exceeded | { used, limit, percentUsed, blocked, warning, windowExpiresAt } | Quota limit exceeded |
Examples
Listen for streaming content:
diosc('on', 'stream:chunk', ({ content }) => {
process.stdout.write(content);
});
diosc('on', 'stream:end', () => {
console.log('\n--- Stream complete ---');
});
Listen for tool execution:
diosc('on', 'tool:started', ({ toolName, toolCallId }) => {
console.log(`Tool started: ${toolName}`);
showToolSpinner(toolCallId);
});
diosc('on', 'tool:completed', ({ toolName, durationMs }) => {
console.log(`Tool completed: ${toolName} (${durationMs}ms)`);
});
Listen for approval requests:
diosc('on', 'approval:request', ({ toolCalls, proposedChanges }) => {
console.log('Approval needed for:', toolCalls.map(t => t.name));
// The <diosc-chat> component handles this UI automatically
});
Listen for errors:
diosc('on', 'session:error', ({ code, message, recoverable }) => {
console.error(`[${code}] ${message}`);
if (!recoverable) {
showFatalErrorModal(message);
}
});
diosc('onAny', handler)
Subscribe to all events. Useful for logging and debugging.
Signature
diosc('onAny', handler: (event: string, data: any) => void): () => void
Example
const unsubscribe = diosc('onAny', (event, data) => {
console.log(`[diosc] ${event}`, data);
});
diosc('tool', toolName, handler)
Register custom tool handler for browser-side execution. When the AI invokes this tool, the handler runs in the browser.
Signature
diosc('tool', toolName: string, handler: BrowserToolHandler): void
type BrowserToolHandler = (params: any) => Promise<any> | any
Examples
Simple tool:
diosc('tool', 'get_page_title', () => ({
title: document.title,
url: window.location.href
}));
Async tool:
diosc('tool', 'get_current_location', async () => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(pos) => resolve({
lat: pos.coords.latitude,
lng: pos.coords.longitude
}),
(err) => reject(new Error(err.message))
);
});
});
Navigation tool:
diosc('tool', 'navigate', async ({ path }) => {
window.history.pushState(null, '', path);
return { navigated: true, path };
});
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;
}
Returns
Unsubscribe function.
Examples
React Router v6:
import { useLocation } from 'react-router-dom';
function App() {
const location = useLocation();
useEffect(() => {
const unsubscribe = diosc('observe', 'navigation', (notify) => {
notify({
path: location.pathname,
search: location.search,
hash: location.hash
});
});
return unsubscribe;
}, [location]);
return <div>...</div>;
}
Vue Router:
import { watch } from 'vue';
import { useRoute } from 'vue-router';
export default {
setup() {
const route = useRoute();
onMounted(() => {
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
});
});
}
};
Session Management Commands
diosc('startNewSession')
Start a new chat session. Ends the current session and begins a fresh one.
diosc('startNewSession'): void
diosc('loadSession', sessionId)
Load an existing session by ID. Restores messages and state.
diosc('loadSession', sessionId: string): void
diosc('fetchSessionList', options?)
Fetch the user's session history via WebSocket.
diosc('fetchSessionList', options?: { limit?: number; cursor?: string }): void
diosc('searchSessions', options)
Search session history semantically.
diosc('searchSessions', options: { query: string; limit?: number; status?: string }): void
diosc('clearSessionSearch')
Clear search results and return to the full session list.
diosc('clearSessionSearch'): void
diosc('renameSession', sessionId, name)
Rename a session.
diosc('renameSession', sessionId: string, name: string): void
diosc('pinSession', sessionId, isPinned)
Pin or unpin a session to keep it at the top of the list.
diosc('pinSession', sessionId: string, isPinned: boolean): void
Approval Commands
When the AI attempts a tool execution that requires approval, the approval:request event fires. Respond with one of these commands:
diosc('approve')
Approve the pending tool execution.
diosc('approve'): void
diosc('reject', reason?)
Reject the pending tool execution with an optional reason.
diosc('reject', reason?: string): void
diosc('editAndApprove', modifiedArgs)
Edit the tool parameters and approve with the modified values.
diosc('editAndApprove', modifiedArgs: Record<string, unknown>): void
There is one pending approval per session. The <diosc-chat> component provides a built-in approval dialog with diff view, parameter editing, and severity badges — you only need these commands if building a custom UI.
Stream Control
diosc('cancelStream')
Cancel the current streaming response.
diosc('cancelStream'): void
UI Control
diosc('open') / diosc('close') / diosc('toggle')
Control chat widget visibility programmatically.
diosc('open'): void
diosc('close'): void
diosc('toggle'): void
Example
// Open chat when user clicks a custom button
document.getElementById('help-btn').addEventListener('click', () => {
diosc('open');
});
diosc('fetchAssistantConfig')
Fetch the assistant's public configuration (name, greeting, avatar, branding) before connecting.
diosc('fetchAssistantConfig'): Promise<AssistantPublicConfig | null>
Client Package (@diosc-ai/client)
For framework integrations, use the @diosc-ai/client package which provides a loader and TypeScript types.
Installation
npm install @diosc-ai/client
loadDiosc(options?)
Loads the assistant kit script and returns a reference to the diosc() function.
import { loadDiosc } from '@diosc-ai/client';
const diosc = await loadDiosc({
backendUrl: 'https://hub.example.com',
apiKey: 'ast_abc123'
});
// Now use diosc() with full type safety
diosc('auth', { headers: { Authorization: 'Bearer token' }, userId: 'user-1' });
Exported Types
import type {
DioscConfig,
AuthContext,
DioscEvent,
EventHandler,
DioscCommand,
InvokeOptions,
DioscResponse,
NavigationData,
NavigationObserverCallback,
ToolExecutionContext,
ToolResult,
ToolHandler,
UserInfo,
PageContext,
} from '@diosc-ai/client';
Types
AuthContext
Authentication context pushed via diosc('auth', context).
interface AuthContext {
headers?: Record<string, string>;
cookies?: Record<string, string>;
userId?: string;
tenantId?: string;
userMetadata?: Record<string, any>;
expiresAt?: number; // ms since epoch
}
EngineConfig
Configuration passed to diosc('config', options).
interface EngineConfig {
backendUrl: string;
apiKey: string;
assistantId?: string;
verbose?: boolean;
autoConnect?: boolean;
reconnectAttempts?: number;
reconnectDelay?: number;
reconnectDelayMax?: number;
connectionTimeout?: number;
}
ProcessedMessage
A chat message in a session. This is the type you'll encounter when subscribing to message events or reading session history.
interface ProcessedMessage {
id: string;
threadId: string;
role: 'human' | 'ai' | 'tool' | 'system';
content: string;
timestamp: string;
toolCalls?: ProcessedToolCall[];
attachments?: FileAttachment[];
metadata?: Record<string, unknown>;
}
ApprovalRequest
Approval request for tool execution. Supports multi-tool approval — a single request may contain multiple tool calls.
interface ApprovalRequest {
approvalId: string;
toolCalls: Array<{
id: string;
name: string;
args: Record<string, unknown>;
}>;
requestedAt: Date;
approvalConfig?: any;
proposedChanges?: any;
entityContext?: any;
}
SessionSummary
Session list item.
interface SessionSummary {
id: string;
name: string | null;
firstMessagePreview: string | null;
messageCount: number;
createdAt: string;
lastMessageAt: string;
status: string;
isPinned: boolean;
similarity?: number; // Present in search results
}
AssistantPublicConfig
Lightweight assistant configuration returned by diosc('fetchAssistantConfig').
interface AssistantPublicConfig {
id: string;
name: string;
greeting: string;
avatar?: string;
branding?: string;
primaryColor?: string;
styles?: Record<string, unknown>;
}
ToolExecution
Tracks a tool's execution lifecycle.
interface ToolExecution {
id: string;
toolName: string;
parameters: Record<string, unknown>;
status: 'running' | 'complete' | 'error';
startTime: number;
endTime?: number;
durationMs?: number;
description?: string;
resultSummary?: string;
errorMessage?: string;
}
Error Handling
Common Error Codes
| Code | Description | Recoverable | Suggested Action |
|---|---|---|---|
AUTH_EXPIRED | Authentication token expired | Yes | Push new auth context |
AUTH_INVALID | Invalid credentials | No | Redirect to login |
AUTH_FAILED | Authentication failed | No | Show error, redirect to login |
TOOL_EXECUTION_FAILED | Tool execution error | Yes | Retry or show error |
TIMEOUT | Request timeout | Yes | Retry |
SESSION_NOT_FOUND | Session doesn't exist | Yes | Start new session |
Error Handling Pattern
diosc('on', 'session:error', ({ code, message, recoverable, suggestedAction }) => {
console.error(`[${code}] ${message}`);
switch (code) {
case 'AUTH_EXPIRED':
// Push fresh auth
const newToken = await refreshToken();
diosc('auth', {
headers: { Authorization: `Bearer ${newToken}` },
userId: currentUserId
});
break;
case 'AUTH_FAILED':
case 'AUTH_INVALID':
diosc('auth', null); // Logout
window.location.href = '/login';
break;
default:
if (!recoverable) {
showFatalErrorModal(message);
} else {
showErrorToast(message);
}
}
});
Best Practices
1. Configure Before Authenticating
// 1. Configure
diosc('config', {
backendUrl: process.env.HUB_URL,
apiKey: process.env.API_KEY
});
// 2. Set up event listeners
diosc('on', 'session:error', handleError);
diosc('on', 'auth:refresh_required', handleTokenRefresh);
// 3. Push auth (triggers connection automatically)
diosc('auth', {
headers: { Authorization: `Bearer ${token}` },
userId: user.id
});
2. Clean Up Event Listeners
const unsubscribe = diosc('on', 'stream:chunk', handler);
// On component unmount or cleanup
unsubscribe();
3. Logout on App Teardown
// Push null to cleanly disconnect
diosc('auth', null);
4. Enable Verbose Mode in Development
diosc('config', {
verbose: process.env.NODE_ENV === 'development',
backendUrl: process.env.HUB_URL,
apiKey: process.env.API_KEY
});
Migration from v1.x
Auth API Change
The authentication API changed from a provider function to direct value push:
Before (v1.x):
// Provider function — called by engine when needed
diosc('auth', async () => ({
headers: { Authorization: `Bearer ${getToken()}` },
userId: getUserId()
}));
diosc('connect');
After (v2.0):
// Direct value push — reactive lifecycle
diosc('auth', {
headers: { Authorization: `Bearer ${token}` },
userId: user.id
});
// To logout:
diosc('auth', null);
Threads Replaced by Sessions
Thread management commands have been replaced by session management:
| v1.x Command | v2.0 Command |
|---|---|
diosc('setThread', threadId) | diosc('loadSession', sessionId) |
diosc('newThread') | diosc('startNewSession') |
diosc('connect') | diosc('auth', context) |
diosc('disconnect') | diosc('auth', null) |
Event Name Changes
Events now use colon-delimited names:
| v1.x Event | v2.0 Event |
|---|---|
session_started | session:started |
session_joined | session:joined |
stream_start | stream:start |
stream_end | stream:end |
tool_execution_start | tool:started |
tool_execution_complete | tool:completed |
approval_required | approval:request |
thread_created | Removed |
thread_joined | Removed |
thread_switched | Removed |
Approval API Change
Approvals no longer require an approvalId parameter — there is one pending approval per session:
Before (v1.x):
diosc('approve', approvalId);
diosc('reject', approvalId, 'reason');
After (v2.0):
diosc('approve');
diosc('reject', 'reason');
diosc('editAndApprove', { modifiedParam: 'newValue' });
For more information, see: