Quick Start
Add Coign to any HTML page in two lines:
<script>
window.Coign = window.Coign || function() {
(window.Coign.q = window.Coign.q || []).push(arguments);
};
Coign('init', { preset: 'coign-balanced' });
</script>
<script src="https://your-cdn.com/coign-sdk.iife.js"></script>
The window.Coign stub queues calls before the SDK loads. Once loaded, the real API replays the queue automatically.
Installation
CDN (Recommended)
Use the IIFE bundle with the queue-loader pattern shown above. This works on any plain HTML site with no build step.
ESM (npm)
npm install coign-sdk
import { init, config } from 'coign-sdk';
init({ preset: 'coign-balanced' });
config({ theme: { accent: '#6366f1' } });
Configuration
The config function accepts a flat object of options:
| Option | Type | Description |
|---|---|---|
apiKey | string | API key if using a cloud proxy (optional) |
endpoint | string | Custom LLM endpoint (optional) |
model | string | Model identifier or preset name |
theme | object | Accent, text, bg, radius colors |
position | string | Widget position: bottom-right or inline |
inlineMount | string | CSS selector for inline mount target |
systemPrompt | string | Custom system prompt override |
contextWindowSize | number | Max tokens in context |
temperature | number | Sampling temperature (0–1) |
maxTokens | number | Max response tokens |
onDownloadProgress | function | Callback on model download progress |
onDownloadComplete | function | Callback when model download finishes |
onDownloadError | function | Callback when model download fails |
maxRetries | number | Max retry attempts for init (default 0) |
retryDelayMs | number | Delay between retry attempts in ms (default 1000) |
API Reference
init(options)
Initializes the SDK with a model preset or custom configuration. Must be called before other API methods.
init({ preset: 'coign-balanced' });
init({ model: 'Llama-3.1-8B-Instruct-q4f32_1-MLC' });
config(options)
Updates configuration after init. Merges with existing config.
config({ theme: { accent: '#10b981' } });
ask(message)
Sends a message to the agent and returns a Promise that resolves with the response string.
const answer = await Coign.ask('Summarize this page');
createWidget()
Creates and mounts the chat widget into the page. The widget is a singleton — calling this again returns the same instance.
Coign.createWidget();
Coign.showWidget(); // open panel
Coign.hideWidget(); // close panel
Coign.destroyWidget(); // remove from DOM
showConfirmDialog(message, risk, confirmationValue?)
Shows a native <dialog> for risky operations. Returns Promise<boolean>.
const allowed = await Coign.showConfirmDialog(
'Delete all user data?',
'destructive',
'DELETE'
);
Browser Check
Use checkSupport() to verify WebGPU and estimate available VRAM before calling init():
const check = await Coign.checkSupport();
if (!check.supported) {
alert('Coign requires WebGPU. Reason: ' + check.reason);
}
Returns an object with:
supported— boolean, true if browser can run Coignreason— human-readable explanation when unsupportedwebgpu— boolean, true if navigator.gpu existsbrowser— detected browser nameestimatedVramMb— rough VRAM estimate from GPU adapter
Download Progress
Model downloads are large (400 MB–4.5 GB). You can track progress with callbacks or events:
init({
preset: 'coign-balanced',
onDownloadProgress: (p) => {
console.log(p.stage, p.progress); // 'downloading', 0.42
},
onDownloadComplete: () => console.log('Done!'),
onDownloadError: (err) => console.error(err.message),
});
The built-in widget also shows a progress overlay automatically. You can cancel a slow download:
Coign.cancelEngineInit(); // or click Cancel in the widget overlay
Lifecycle
Check SDK state at any time:
Coign.isInitialized(); // true after init() resolves
Coign.isReady(); // true when model is loaded and engine is ready
Retry a failed init with exponential backoff:
Coign.retryInit({ preset: 'coign-balanced', maxRetries: 3, retryDelayMs: 2000 });
Swap models without destroying history or tools:
await Coign.swapModel('coign-code');
Architecture
Coign is designed as a set of layered modules:
- Core (
src/core/) — Configuration, preset resolution, and model initialization - LLM (
src/llm/) — WebLLM engine wrapper, chat engine, tool loop (manual and native) - Tools (
src/tools/) — Built-in tools (searchPage,getPageOutline,getElement) and host tool registration - Store (
src/store/) — Page outline store and MiniSearch index for in-page search - UI (
src/ui/) — Shadow DOM chat widget, theming, inline mount, focus trap, and modal dialog - Events (
src/events.ts) — Typed event bus for loose coupling between modules - Queue Loader (
src/queue-loader.ts) — IIFE stub/replay for CDN loading
All modules are pure ESM with .js extensions. Browser-only code guards with typeof window !== 'undefined' so it can be imported in Node/Vitest contexts.
Model Presets
| Preset | Model | Description |
|---|---|---|
coign-balanced | Llama-3.1-8B Instruct q4f32_1 | Fast, capable, good default |
coign-creative | Qwen2.5-7B Instruct q4f16_1 | Best for creative writing |
coign-code | DeepSeek-Coder-V2-Lite q4f16_1 | Code generation and review |
coign-local | Phi-3.5-mini-instruct q4f16_1 | Smallest, fastest on low-end devices |
Custom Tools
Register custom tools with Coign.registerTool:
Coign.registerTool({
name: 'sendAnalytics',
description: 'Send a page-view event to analytics',
parameters: {
type: 'object',
properties: {
page: { type: 'string', description: 'Page path' }
},
required: ['page']
},
execute: async ({ page }) => {
gtag('event', 'page_view', { page });
return { sent: true };
}
});
Tools are called via an XML-based manual loop by default. The LLM generates <tool> tags, the SDK parses them, executes the matching tool, and feeds the result back into the conversation.
Theming
Pass a theme object to config():
Coign.config({
theme: {
accent: '#6366f1',
text: '#1e293b',
bg: '#ffffff',
radius: '0.5rem'
}
});
Risk Tiers
Operations that modify state or access sensitive data require user confirmation:
| Tier | Behavior | Example |
|---|---|---|
read | Silent | Reading page content |
write | Modal confirmation | Clicking a submit button |
destructive | Modal + typed confirmation | Deleting data |