@ziggy-ai/client-sdk 1.3.0 → 1.5.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/README.md CHANGED
@@ -1,413 +1,416 @@
1
- # @ziggy-ai/client-sdk
2
-
3
- TypeScript SDK for integrating host applications with Ziggy's v1 API.
4
-
5
- ## Install
6
-
7
- ```bash
8
- npm install @ziggy-ai/client-sdk
9
- ```
10
-
11
- ## Quick Start
12
-
13
- ```typescript
14
- import { ZiggyClient } from '@ziggy-ai/client-sdk';
15
-
16
- const ziggy = new ZiggyClient({
17
- baseUrl: 'https://ziggy.example.com',
18
- appId: 'my-app',
19
- apiKey: 'pk_live_abc123',
20
- });
21
-
22
- // Connect (creates session, starts context batching + analytics)
23
- const session = await ziggy.connect({
24
- userId: 'user-1',
25
- context: {
26
- page: { path: '/dashboard', type: 'dashboard', title: 'Dashboard' },
27
- user: { id: 'user-1', tier: 'pro', sessionCount: 42 },
28
- },
29
- onTrigger: (response) => {
30
- if (response.trigger) showProactiveBubble(response.trigger);
31
- },
32
- });
33
-
34
- // Streaming chat
35
- for await (const event of ziggy.chat.stream({ message: 'Why did my transform fail?' })) {
36
- switch (event.type) {
37
- case 'content.delta': appendToUI(event.content); break;
38
- case 'tool.start': showToolIndicator(event.toolName); break;
39
- case 'metadata': renderActions(event.quickActions); break;
40
- }
41
- }
42
-
43
- // Disconnect (flushes analytics, stops batching, ends session)
44
- await ziggy.disconnect();
45
- ```
46
-
47
- ## API
48
-
49
- ### ZiggyClient
50
-
51
- The main entry point. Composes specialized sub-clients for each API area.
52
-
53
- ```typescript
54
- const ziggy = new ZiggyClient({
55
- baseUrl: string; // Ziggy API base URL
56
- appId: string; // Your app identifier
57
- apiKey: string; // API key (from App node in Ziggy)
58
- timeout?: number; // Request timeout in ms (default: 30000)
59
- });
60
- ```
61
-
62
- #### Lifecycle
63
-
64
- ```typescript
65
- // Connect — creates session, wires userId, starts batching
66
- const session = await ziggy.connect({
67
- userId: string;
68
- context: Record<string, unknown>;
69
- capabilities?: string[]; // default: ['streaming', 'actions']
70
- onTrigger?: (response: ContextPushResponse) => void;
71
- });
72
-
73
- // Disconnect — flush analytics, stop batching, destroy session
74
- await ziggy.disconnect();
75
- ```
76
-
77
- ---
78
-
79
- ### Chat
80
-
81
- ```typescript
82
- // Streaming (ndjson, MCP 2025-03-26 standard)
83
- for await (const event of ziggy.chat.stream({ message: 'Help me debug this' })) {
84
- // event.type: 'stream.start' | 'agent.start' | 'content.delta' |
85
- // 'content.done' | 'tool.start' | 'tool.result' |
86
- // 'metadata' | 'stream.end' | 'error'
87
- }
88
-
89
- // Resume interrupted stream
90
- for await (const event of ziggy.chat.resume(streamId, lastSeqNumber)) {
91
- // Pick up where you left off
92
- }
93
- ```
94
-
95
- **Chat request options:**
96
-
97
- ```typescript
98
- {
99
- message: string;
100
- attachments?: Array<{ type: 'screenshot' | 'file_reference'; id: string }>;
101
- context?: Record<string, unknown>; // Bundled context update
102
- requestId?: string; // Client-generated dedup ID
103
- }
104
- ```
105
-
106
- ---
107
-
108
- ### Context
109
-
110
- Context updates are auto-batched every 10 seconds. Important changes (page navigation, errors, process status) flush immediately.
111
-
112
- ```typescript
113
- // Queue a context update (merges with pending batch)
114
- ziggy.context.update({
115
- page: { path: '/settings', type: 'settings', title: 'Settings' },
116
- });
117
-
118
- // Queue an event
119
- ziggy.context.addEvent({
120
- type: 'button_click',
121
- timestamp: new Date().toISOString(),
122
- data: { buttonId: 'retry' },
123
- });
124
-
125
- // Force flush
126
- await ziggy.context.flush();
127
- ```
128
-
129
- ---
130
-
131
- ### App Configuration
132
-
133
- Register triggers, quick actions, brand identity, and credentials.
134
-
135
- ```typescript
136
- // Brand
137
- await ziggy.app.setBrand({
138
- identity: { name: 'Coach', tagline: 'Your training partner' },
139
- voice: { tone: ['motivational', 'knowledgeable'], formality: 'casual-professional' },
140
- theme: { primaryColor: '#2E7D32', chatPosition: 'bottom-right' },
141
- });
142
- const brand = await ziggy.app.getBrand();
143
-
144
- // Triggers (full sync — replaces all existing)
145
- await ziggy.app.registerTriggers({
146
- triggers: [{
147
- id: 'transform-error',
148
- name: 'Transform Error',
149
- condition: { type: 'process_status', value: 'error' },
150
- priority: 'critical',
151
- message: "That didn't work — want me to figure out why?",
152
- }],
153
- });
154
- const { triggers } = await ziggy.app.listTriggers();
155
- await ziggy.app.deleteTrigger('transform-error');
156
-
157
- // Quick Actions (full sync)
158
- await ziggy.app.registerQuickActions({
159
- sets: [{
160
- id: 'dashboard-empty',
161
- contextState: 'dashboard-empty',
162
- conditions: { pageTypes: ['dashboard'] },
163
- actions: [{ id: 'start', label: 'Get started', action: 'onboarding.start', priority: 1 }],
164
- }],
165
- });
166
- const { sets } = await ziggy.app.listQuickActions();
167
- await ziggy.app.deleteQuickActionSet('dashboard-empty');
168
-
169
- // Credentials (encrypted at rest, AES-256-GCM)
170
- await ziggy.app.setCredentials({ github_token: 'ghp_...', supabase_key: 'eyJ...' });
171
- const { credentials, updatedAt } = await ziggy.app.getCredentials(); // keys only, never values
172
- await ziggy.app.deleteCredentials();
173
- ```
174
-
175
- ---
176
-
177
- ### Callback Handler
178
-
179
- Handle tool execution requests from Ziggy. When Ziggy needs your app to do something (navigate, retry a process, run an `executor: 'http'` host action), it POSTs to your registered callback URL (`client.app.setCallbackUrl()`, HTTPS only).
180
-
181
- Every request is signed once your app has a callback secret (`POST /v1/apps/callback/secret`, or Console → Settings → Callback URL → Create signing secret). Verify it before you run anything: `handleRequest` answers `401` to a missing, wrong or stale (over 5 minutes) signature without calling any handler. It fails closed: if `secret` is empty or missing (say an unset Worker binding) it answers `500` and runs nothing. Pass `{ allowUnsigned: true }` only before your app has a secret.
182
-
183
- ```typescript
184
- import { CallbackHandler } from '@ziggy-ai/client-sdk';
185
-
186
- const handler = new CallbackHandler();
187
-
188
- handler
189
- .on('support.navigate', async (params) => {
190
- router.push(params.path as string);
191
- return { navigated: true };
192
- })
193
- .on('support.retry_process', async (params) => {
194
- await processes.retry(params.processId as string);
195
- return { retried: true };
196
- });
197
-
198
- // Fetch-style servers (Cloudflare Workers, Hono, Next.js route handlers, Deno, Bun):
199
- export default {
200
- fetch: (request: Request, env: { ZIGGY_CALLBACK_SECRET: string }) =>
201
- handler.handleRequest(request, { secret: env.ZIGGY_CALLBACK_SECRET }),
202
- };
203
- ```
204
-
205
- For other frameworks, verify with the raw body before parsing it:
206
-
207
- ```typescript
208
- import { verifyCallbackSignature } from '@ziggy-ai/client-sdk';
209
-
210
- const rawBody = await readRawBody(req); // exact bytes, not re-serialised JSON
211
- const check = await verifyCallbackSignature(req.headers, rawBody, { secret: process.env.ZIGGY_CALLBACK_SECRET! });
212
- if (!check.valid) return res.status(401).json({ error: check.reason });
213
- res.json(await handler.handle(JSON.parse(rawBody)));
214
- ```
215
-
216
- Headers: `X-Ziggy-Timestamp` (ISO 8601 UTC) and `X-Ziggy-Signature` = `v1=` + hex HMAC-SHA256 of `${timestamp}.${rawBody}` with your callback secret. `handler.handle(body)` on its own does not verify anything; only use it behind your own check.
217
-
218
- ---
219
-
220
- ### Tools
221
-
222
- Invoke tools directly (e.g., from quick action buttons).
223
-
224
- ```typescript
225
- const result = await ziggy.tools.invoke('support.navigate', { path: '/settings' });
226
-
227
- // Streaming tool invocation
228
- for await (const event of ziggy.tools.invokeStream('support.respond', { message: 'Hi' })) {
229
- // event.type: 'tool.start' | 'tool.result'
230
- }
231
- ```
232
-
233
- ---
234
-
235
- ### Feedback
236
-
237
- ```typescript
238
- // Quick reaction
239
- await ziggy.feedback.react('msg-1', 'helpful');
240
- // reaction: 'helpful' | 'not_helpful' | 'wrong' | 'perfect'
241
-
242
- // Detailed feedback
243
- await ziggy.feedback.submit({
244
- conversationId: 'conv-1',
245
- type: 'accuracy', // 'accuracy' | 'helpfulness' | 'tone' | 'action' | 'correction'
246
- rating: 4,
247
- comment: 'Good answer but missed one detail',
248
- userId: 'user-1',
249
- });
250
-
251
- // Record coordination outcome (for learning loop)
252
- await ziggy.feedback.recordOutcome({
253
- coordinationId: 'coord-1',
254
- success: true,
255
- agentIds: ['knuckles'],
256
- });
257
- ```
258
-
259
- ---
260
-
261
- ### Quests
262
-
263
- Track multi-step workflows.
264
-
265
- ```typescript
266
- const { quest } = await ziggy.quests.create({
267
- title: 'Investigate transform failure',
268
- sessionId: session.sessionId,
269
- initiatorId: 'knuckles',
270
- steps: [
271
- { label: 'Check logs', agentId: 'ziggy' },
272
- { label: 'Analyze error' },
273
- ],
274
- });
275
-
276
- await ziggy.quests.updateStep(quest.id, quest.steps[0].id, {
277
- status: 'complete',
278
- update: { message: 'Found 3 errors in logs' },
279
- });
280
-
281
- // Stream quest updates
282
- for await (const event of ziggy.quests.stream(quest.id)) {
283
- // event.type: 'quest.status' | 'quest.step_update' | 'quest.complete'
284
- }
285
- ```
286
-
287
- ---
288
-
289
- ### Analytics
290
-
291
- Events are auto-batched every 30 seconds and flushed on disconnect.
292
-
293
- ```typescript
294
- ziggy.analytics.track('feature_used', { feature: 'dark-mode' });
295
- ziggy.analytics.track('page_viewed', { path: '/settings' });
296
- ```
297
-
298
- ---
299
-
300
- ## Stream Events
301
-
302
- All streaming endpoints use ndjson (newline-delimited JSON) with sequence numbers for resumption.
303
-
304
- | Event Type | Key Fields | Description |
305
- |------------|------------|-------------|
306
- | `stream.start` | `streamId`, `messageId` | Always first |
307
- | `agent.start` | `agentId`, `agentRole` | Routed agent begins |
308
- | `agent.switch` | `fromAgentId`, `toAgentId` | Agent handoff |
309
- | `content.delta` | `content` | Partial text |
310
- | `content.done` | `fullContent` | Complete text |
311
- | `tool.start` | `toolId`, `toolName` | Tool invoked |
312
- | `tool.progress` | `toolId`, `progress` | Tool progress (0-1) |
313
- | `tool.result` | `toolId`, `success` | Tool completed |
314
- | `metadata` | `confidence`, `quickActions` | Response metadata |
315
- | `stream.end` | `messageId`, `durationMs` | Always last |
316
- | `error` | `code`, `message`, `retryable` | Error during stream |
317
-
318
- ### Stream Resumption
319
-
320
- ```typescript
321
- import { SequenceTracker } from '@ziggy-ai/client-sdk';
322
-
323
- const tracker = new SequenceTracker();
324
-
325
- for await (const event of ziggy.chat.stream({ message: 'Hello' })) {
326
- tracker.update(event);
327
- // ... process event
328
- }
329
-
330
- // If disconnected, resume:
331
- if (tracker.streamId) {
332
- for await (const event of ziggy.chat.resume(tracker.streamId, tracker.lastSeq)) {
333
- // Picks up from where you left off
334
- }
335
- }
336
- ```
337
-
338
- ---
339
-
340
- ## Error Handling
341
-
342
- ```typescript
343
- import { ZiggyError, ZiggyConnectionError } from '@ziggy-ai/client-sdk';
344
-
345
- try {
346
- for await (const event of ziggy.chat.stream({ message: 'Hello' })) { /* ... */ }
347
- } catch (error) {
348
- if (error instanceof ZiggyConnectionError) {
349
- // Network/timeout — error.retryable is true
350
- console.log('Connection failed, will retry');
351
- } else if (error instanceof ZiggyError) {
352
- // API error — check error.status
353
- console.log(`API error ${error.status}: ${error.message}`);
354
- }
355
- }
356
- ```
357
-
358
- ### Retry Utility
359
-
360
- ```typescript
361
- import { withRetry } from '@ziggy-ai/client-sdk';
362
-
363
- const result = await withRetry(
364
- () => ziggy.chat.action({ actionId: 'support.explain_limits' }),
365
- { maxRetries: 3, baseDelayMs: 1000, maxDelayMs: 30000 },
366
- );
367
- // Retries with exponential backoff + jitter. Skips retry for 4xx errors.
368
- ```
369
-
370
- ---
371
-
372
- ## Architecture
373
-
374
- The SDK is a thin client that maps to Ziggy's v1 REST API:
375
-
376
- ```
377
- ZiggyClient
378
- ├── sessions → POST/DELETE /v1/sessions
379
- ├── chat → POST /v1/chat/stream, POST /v1/chat/action/stream
380
- ├── context → POST /v1/sessions/:id/context (auto-batched)
381
- ├── tools → POST /v1/tools/invoke
382
- ├── feedback → POST /v1/feedback/*
383
- ├── quests → /v1/quests/*
384
- ├── analytics → POST /v1/feedback/analytics/events (auto-batched)
385
- ├── app → /v1/apps/* (triggers, quick actions, brand, credentials)
386
- └── callbacks → CallbackHandler (host-side, receives Ziggy tool requests)
387
- ```
388
-
389
- **Key design decisions:**
390
-
391
- - **Auto-batching** — Context (10s) and analytics (30s) are batched to reduce API calls. Important context changes flush immediately.
392
- - **Streaming** — Uses Streamable HTTP with ndjson (MCP 2025-03-26 standard). Sequence numbers enable reconnection.
393
- - **Composition** — Each API area is a separate module composed by `ZiggyClient`.
394
- - **Zero dependencies** — Uses only `fetch` (built into Node 18+ and all modern browsers).
395
-
396
- ---
397
-
398
- ## Development
399
-
400
- ```bash
401
- npm run build # Build with tsup (ESM + .d.ts)
402
- npm run dev # Watch mode
403
- npm run typecheck # Type check without emit
404
- npm test # Run tests (vitest)
405
- ```
406
-
407
- ## Publishing (from repo root)
408
-
409
- ```bash
410
- npm version patch # in packages/client-sdk and/or packages/react
411
- npm run sdk:publish # builds both, prints npm publish commands
412
- npm run sdk:sync-consumers # after publish: bump console + examples
413
- ```
1
+ # @ziggy-ai/client-sdk
2
+
3
+ TypeScript SDK for integrating host applications with Ziggy's v1 API.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @ziggy-ai/client-sdk
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { ZiggyClient } from '@ziggy-ai/client-sdk';
15
+
16
+ const ziggy = new ZiggyClient({
17
+ baseUrl: 'https://ziggy.example.com',
18
+ appId: 'my-app',
19
+ apiKey: 'pk_live_abc123',
20
+ });
21
+
22
+ // Connect (creates session, starts context batching + analytics)
23
+ const session = await ziggy.connect({
24
+ userId: 'user-1',
25
+ context: {
26
+ page: { path: '/dashboard', type: 'dashboard', title: 'Dashboard' },
27
+ user: { id: 'user-1', tier: 'pro', sessionCount: 42 },
28
+ },
29
+ onTrigger: (response) => {
30
+ if (response.trigger) showProactiveBubble(response.trigger);
31
+ },
32
+ });
33
+
34
+ // Streaming chat
35
+ for await (const event of ziggy.chat.stream({ message: 'Why did my transform fail?' })) {
36
+ switch (event.type) {
37
+ case 'content.delta': appendToUI(event.content); break;
38
+ case 'tool.start': showToolIndicator(event.toolName); break;
39
+ case 'metadata': renderActions(event.quickActions); break;
40
+ }
41
+ }
42
+
43
+ // Disconnect (flushes analytics, stops batching, ends session)
44
+ await ziggy.disconnect();
45
+ ```
46
+
47
+ ## API
48
+
49
+ ### ZiggyClient
50
+
51
+ The main entry point. Composes specialized sub-clients for each API area.
52
+
53
+ ```typescript
54
+ const ziggy = new ZiggyClient({
55
+ baseUrl: string; // Ziggy API base URL
56
+ appId: string; // Your app identifier
57
+ apiKey: string; // API key (from App node in Ziggy)
58
+ timeout?: number; // Request timeout in ms (default: 30000)
59
+ });
60
+ ```
61
+
62
+ #### Lifecycle
63
+
64
+ ```typescript
65
+ // Connect — creates session, wires userId, starts batching
66
+ const session = await ziggy.connect({
67
+ userId: string;
68
+ context: Record<string, unknown>;
69
+ capabilities?: string[]; // default: ['streaming', 'actions']
70
+ onTrigger?: (response: ContextPushResponse) => void;
71
+ });
72
+
73
+ // Disconnect — flush analytics, stop batching, destroy session
74
+ await ziggy.disconnect();
75
+ ```
76
+
77
+ ---
78
+
79
+ ### Chat
80
+
81
+ ```typescript
82
+ // Streaming (ndjson, MCP 2025-03-26 standard)
83
+ for await (const event of ziggy.chat.stream({ message: 'Help me debug this' })) {
84
+ // event.type: 'stream.start' | 'agent.start' | 'content.delta' |
85
+ // 'content.done' | 'tool.start' | 'tool.result' |
86
+ // 'metadata' | 'stream.end' | 'error'
87
+ }
88
+
89
+ // Resume interrupted stream
90
+ for await (const event of ziggy.chat.resume(streamId, lastSeqNumber)) {
91
+ // Pick up where you left off
92
+ }
93
+ ```
94
+
95
+ **Chat request options:**
96
+
97
+ ```typescript
98
+ {
99
+ message: string;
100
+ attachments?: Array<{ type: 'screenshot' | 'file_reference'; id: string }>;
101
+ context?: Record<string, unknown>; // Bundled context update
102
+ requestId?: string; // Client-generated dedup ID
103
+ }
104
+ ```
105
+
106
+ ---
107
+
108
+ ### Context
109
+
110
+ Context updates are auto-batched every 10 seconds. Important changes (page navigation, errors, process status) flush immediately.
111
+
112
+ ```typescript
113
+ // Queue a context update (merges with pending batch)
114
+ ziggy.context.update({
115
+ page: { path: '/settings', type: 'settings', title: 'Settings' },
116
+ });
117
+
118
+ // Queue an event
119
+ ziggy.context.addEvent({
120
+ type: 'button_click',
121
+ timestamp: new Date().toISOString(),
122
+ data: { buttonId: 'retry' },
123
+ });
124
+
125
+ // Force flush
126
+ await ziggy.context.flush();
127
+ ```
128
+
129
+ ---
130
+
131
+ ### App Configuration
132
+
133
+ Register triggers, quick actions, brand identity, and credentials.
134
+
135
+ ```typescript
136
+ // Brand
137
+ await ziggy.app.setBrand({
138
+ identity: { name: 'Coach', tagline: 'Your training partner' },
139
+ voice: { tone: ['motivational', 'knowledgeable'], formality: 'casual-professional' },
140
+ theme: { primaryColor: '#2E7D32', chatPosition: 'bottom-right' },
141
+ });
142
+ // The whole profile, for your server. A browser is refused it. To change the brand, change this and setBrand it back.
143
+ const profile = await ziggy.app.getFullBrand();
144
+ // The public part (name, avatar, main colour), which is all a browser is given. setBrand refuses it (409).
145
+ const brand = await ziggy.app.getBrand();
146
+
147
+ // Triggers (full sync — replaces all existing)
148
+ await ziggy.app.registerTriggers({
149
+ triggers: [{
150
+ id: 'transform-error',
151
+ name: 'Transform Error',
152
+ condition: { type: 'process_status', value: 'error' },
153
+ priority: 'critical',
154
+ message: "That didn't work — want me to figure out why?",
155
+ }],
156
+ });
157
+ const { triggers } = await ziggy.app.listTriggers();
158
+ await ziggy.app.deleteTrigger('transform-error');
159
+
160
+ // Quick Actions (full sync)
161
+ await ziggy.app.registerQuickActions({
162
+ sets: [{
163
+ id: 'dashboard-empty',
164
+ contextState: 'dashboard-empty',
165
+ conditions: { pageTypes: ['dashboard'] },
166
+ actions: [{ id: 'start', label: 'Get started', action: 'onboarding.start', priority: 1 }],
167
+ }],
168
+ });
169
+ const { sets } = await ziggy.app.listQuickActions();
170
+ await ziggy.app.deleteQuickActionSet('dashboard-empty');
171
+
172
+ // Credentials (encrypted at rest, AES-256-GCM)
173
+ await ziggy.app.setCredentials({ github_token: 'ghp_...', supabase_key: 'eyJ...' });
174
+ const { credentials, updatedAt } = await ziggy.app.getCredentials(); // keys only, never values
175
+ await ziggy.app.deleteCredentials();
176
+ ```
177
+
178
+ ---
179
+
180
+ ### Callback Handler
181
+
182
+ Handle tool execution requests from Ziggy. When Ziggy needs your app to do something (navigate, retry a process, run an `executor: 'http'` host action), it POSTs to your registered callback URL (`client.app.setCallbackUrl()`, HTTPS only).
183
+
184
+ Every request is signed once your app has a callback secret (`POST /v1/apps/callback/secret`, or Console → Settings → Callback URL → Create signing secret). Verify it before you run anything: `handleRequest` answers `401` to a missing, wrong or stale (over 5 minutes) signature without calling any handler. It fails closed: if `secret` is empty or missing (say an unset Worker binding) it answers `500` and runs nothing. Pass `{ allowUnsigned: true }` only before your app has a secret.
185
+
186
+ ```typescript
187
+ import { CallbackHandler } from '@ziggy-ai/client-sdk';
188
+
189
+ const handler = new CallbackHandler();
190
+
191
+ handler
192
+ .on('support.navigate', async (params) => {
193
+ router.push(params.path as string);
194
+ return { navigated: true };
195
+ })
196
+ .on('support.retry_process', async (params) => {
197
+ await processes.retry(params.processId as string);
198
+ return { retried: true };
199
+ });
200
+
201
+ // Fetch-style servers (Cloudflare Workers, Hono, Next.js route handlers, Deno, Bun):
202
+ export default {
203
+ fetch: (request: Request, env: { ZIGGY_CALLBACK_SECRET: string }) =>
204
+ handler.handleRequest(request, { secret: env.ZIGGY_CALLBACK_SECRET }),
205
+ };
206
+ ```
207
+
208
+ For other frameworks, verify with the raw body before parsing it:
209
+
210
+ ```typescript
211
+ import { verifyCallbackSignature } from '@ziggy-ai/client-sdk';
212
+
213
+ const rawBody = await readRawBody(req); // exact bytes, not re-serialised JSON
214
+ const check = await verifyCallbackSignature(req.headers, rawBody, { secret: process.env.ZIGGY_CALLBACK_SECRET! });
215
+ if (!check.valid) return res.status(401).json({ error: check.reason });
216
+ res.json(await handler.handle(JSON.parse(rawBody)));
217
+ ```
218
+
219
+ Headers: `X-Ziggy-Timestamp` (ISO 8601 UTC) and `X-Ziggy-Signature` = `v1=` + hex HMAC-SHA256 of `${timestamp}.${rawBody}` with your callback secret. `handler.handle(body)` on its own does not verify anything; only use it behind your own check.
220
+
221
+ ---
222
+
223
+ ### Tools
224
+
225
+ Invoke tools directly (e.g., from quick action buttons).
226
+
227
+ ```typescript
228
+ const result = await ziggy.tools.invoke('support.navigate', { path: '/settings' });
229
+
230
+ // Streaming tool invocation
231
+ for await (const event of ziggy.tools.invokeStream('support.respond', { message: 'Hi' })) {
232
+ // event.type: 'tool.start' | 'tool.result'
233
+ }
234
+ ```
235
+
236
+ ---
237
+
238
+ ### Feedback
239
+
240
+ ```typescript
241
+ // Quick reaction
242
+ await ziggy.feedback.react('msg-1', 'helpful');
243
+ // reaction: 'helpful' | 'not_helpful' | 'wrong' | 'perfect'
244
+
245
+ // Detailed feedback
246
+ await ziggy.feedback.submit({
247
+ conversationId: 'conv-1',
248
+ type: 'accuracy', // 'accuracy' | 'helpfulness' | 'tone' | 'action' | 'correction'
249
+ rating: 4,
250
+ comment: 'Good answer but missed one detail',
251
+ userId: 'user-1',
252
+ });
253
+
254
+ // Record coordination outcome (for learning loop)
255
+ await ziggy.feedback.recordOutcome({
256
+ coordinationId: 'coord-1',
257
+ success: true,
258
+ agentIds: ['knuckles'],
259
+ });
260
+ ```
261
+
262
+ ---
263
+
264
+ ### Quests
265
+
266
+ Track multi-step workflows.
267
+
268
+ ```typescript
269
+ const { quest } = await ziggy.quests.create({
270
+ title: 'Investigate transform failure',
271
+ sessionId: session.sessionId,
272
+ initiatorId: 'knuckles',
273
+ steps: [
274
+ { label: 'Check logs', agentId: 'ziggy' },
275
+ { label: 'Analyze error' },
276
+ ],
277
+ });
278
+
279
+ await ziggy.quests.updateStep(quest.id, quest.steps[0].id, {
280
+ status: 'complete',
281
+ update: { message: 'Found 3 errors in logs' },
282
+ });
283
+
284
+ // Stream quest updates
285
+ for await (const event of ziggy.quests.stream(quest.id)) {
286
+ // event.type: 'quest.status' | 'quest.step_update' | 'quest.complete'
287
+ }
288
+ ```
289
+
290
+ ---
291
+
292
+ ### Analytics
293
+
294
+ Events are auto-batched every 30 seconds and flushed on disconnect.
295
+
296
+ ```typescript
297
+ ziggy.analytics.track('feature_used', { feature: 'dark-mode' });
298
+ ziggy.analytics.track('page_viewed', { path: '/settings' });
299
+ ```
300
+
301
+ ---
302
+
303
+ ## Stream Events
304
+
305
+ All streaming endpoints use ndjson (newline-delimited JSON) with sequence numbers for resumption.
306
+
307
+ | Event Type | Key Fields | Description |
308
+ |------------|------------|-------------|
309
+ | `stream.start` | `streamId`, `messageId` | Always first |
310
+ | `agent.start` | `agentId`, `agentRole` | Routed agent begins |
311
+ | `agent.switch` | `fromAgentId`, `toAgentId` | Agent handoff |
312
+ | `content.delta` | `content` | Partial text |
313
+ | `content.done` | `fullContent` | Complete text |
314
+ | `tool.start` | `toolId`, `toolName` | Tool invoked |
315
+ | `tool.progress` | `toolId`, `progress` | Tool progress (0-1) |
316
+ | `tool.result` | `toolId`, `success` | Tool completed |
317
+ | `metadata` | `confidence`, `quickActions` | Response metadata |
318
+ | `stream.end` | `messageId`, `durationMs` | Always last |
319
+ | `error` | `code`, `message`, `retryable` | Error during stream |
320
+
321
+ ### Stream Resumption
322
+
323
+ ```typescript
324
+ import { SequenceTracker } from '@ziggy-ai/client-sdk';
325
+
326
+ const tracker = new SequenceTracker();
327
+
328
+ for await (const event of ziggy.chat.stream({ message: 'Hello' })) {
329
+ tracker.update(event);
330
+ // ... process event
331
+ }
332
+
333
+ // If disconnected, resume:
334
+ if (tracker.streamId) {
335
+ for await (const event of ziggy.chat.resume(tracker.streamId, tracker.lastSeq)) {
336
+ // Picks up from where you left off
337
+ }
338
+ }
339
+ ```
340
+
341
+ ---
342
+
343
+ ## Error Handling
344
+
345
+ ```typescript
346
+ import { ZiggyError, ZiggyConnectionError } from '@ziggy-ai/client-sdk';
347
+
348
+ try {
349
+ for await (const event of ziggy.chat.stream({ message: 'Hello' })) { /* ... */ }
350
+ } catch (error) {
351
+ if (error instanceof ZiggyConnectionError) {
352
+ // Network/timeout — error.retryable is true
353
+ console.log('Connection failed, will retry');
354
+ } else if (error instanceof ZiggyError) {
355
+ // API error — check error.status
356
+ console.log(`API error ${error.status}: ${error.message}`);
357
+ }
358
+ }
359
+ ```
360
+
361
+ ### Retry Utility
362
+
363
+ ```typescript
364
+ import { withRetry } from '@ziggy-ai/client-sdk';
365
+
366
+ const result = await withRetry(
367
+ () => ziggy.chat.action({ actionId: 'support.explain_limits' }),
368
+ { maxRetries: 3, baseDelayMs: 1000, maxDelayMs: 30000 },
369
+ );
370
+ // Retries with exponential backoff + jitter. Skips retry for 4xx errors.
371
+ ```
372
+
373
+ ---
374
+
375
+ ## Architecture
376
+
377
+ The SDK is a thin client that maps to Ziggy's v1 REST API:
378
+
379
+ ```
380
+ ZiggyClient
381
+ ├── sessions → POST/DELETE /v1/sessions
382
+ ├── chat → POST /v1/chat/stream, POST /v1/chat/action/stream
383
+ ├── context → POST /v1/sessions/:id/context (auto-batched)
384
+ ├── tools → POST /v1/tools/invoke
385
+ ├── feedback → POST /v1/feedback/*
386
+ ├── quests → /v1/quests/*
387
+ ├── analytics → POST /v1/feedback/analytics/events (auto-batched)
388
+ ├── app → /v1/apps/* (triggers, quick actions, brand, credentials)
389
+ └── callbacks → CallbackHandler (host-side, receives Ziggy tool requests)
390
+ ```
391
+
392
+ **Key design decisions:**
393
+
394
+ - **Auto-batching** — Context (10s) and analytics (30s) are batched to reduce API calls. Important context changes flush immediately.
395
+ - **Streaming** — Uses Streamable HTTP with ndjson (MCP 2025-03-26 standard). Sequence numbers enable reconnection.
396
+ - **Composition** — Each API area is a separate module composed by `ZiggyClient`.
397
+ - **Zero dependencies** — Uses only `fetch` (built into Node 18+ and all modern browsers).
398
+
399
+ ---
400
+
401
+ ## Development
402
+
403
+ ```bash
404
+ npm run build # Build with tsup (ESM + .d.ts)
405
+ npm run dev # Watch mode
406
+ npm run typecheck # Type check without emit
407
+ npm test # Run tests (vitest)
408
+ ```
409
+
410
+ ## Publishing (from repo root)
411
+
412
+ ```bash
413
+ npm version patch # in packages/client-sdk and/or packages/react
414
+ npm run sdk:publish # builds both, prints npm publish commands
415
+ npm run sdk:sync-consumers # after publish: bump console + examples
416
+ ```