@ziggy-ai/client-sdk 1.2.6 → 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.
Files changed (72) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE +21 -21
  3. package/README.md +416 -398
  4. package/dist/agents.d.ts +0 -1
  5. package/dist/analytics.d.ts +0 -1
  6. package/dist/app-intel.d.ts +0 -1
  7. package/dist/app.d.ts +53 -4
  8. package/dist/auth.d.ts +0 -1
  9. package/dist/callback-handler.d.ts +48 -6
  10. package/dist/chat.d.ts +8 -9
  11. package/dist/connection.d.ts +0 -1
  12. package/dist/context.d.ts +0 -1
  13. package/dist/conversations.d.ts +9 -1
  14. package/dist/element-registry.d.ts +0 -1
  15. package/dist/errors.d.ts +0 -1
  16. package/dist/feedback.d.ts +0 -1
  17. package/dist/hooks.d.ts +0 -1
  18. package/dist/index.d.ts +3 -4
  19. package/dist/index.js +147 -4
  20. package/dist/notifications.d.ts +0 -1
  21. package/dist/observer.d.ts +0 -1
  22. package/dist/persistence.d.ts +0 -1
  23. package/dist/product-memory.d.ts +0 -1
  24. package/dist/quests.d.ts +0 -1
  25. package/dist/screenshot-uploader.d.ts +0 -1
  26. package/dist/screenshot.d.ts +0 -1
  27. package/dist/session.d.ts +0 -1
  28. package/dist/signals.d.ts +0 -1
  29. package/dist/storage.d.ts +0 -1
  30. package/dist/stream-parser.d.ts +0 -1
  31. package/dist/styles/ziggy-highlights.css +37 -37
  32. package/dist/testing.d.ts +0 -1
  33. package/dist/tickets.d.ts +0 -1
  34. package/dist/tools.d.ts +0 -1
  35. package/dist/triggers.d.ts +0 -1
  36. package/dist/types.d.ts +219 -2
  37. package/dist/ui-actions.d.ts +0 -1
  38. package/dist/voice.d.ts +0 -1
  39. package/package.json +3 -2
  40. package/dist/agents.d.ts.map +0 -1
  41. package/dist/analytics.d.ts.map +0 -1
  42. package/dist/app-intel.d.ts.map +0 -1
  43. package/dist/app.d.ts.map +0 -1
  44. package/dist/auth.d.ts.map +0 -1
  45. package/dist/callback-handler.d.ts.map +0 -1
  46. package/dist/chat.d.ts.map +0 -1
  47. package/dist/connection.d.ts.map +0 -1
  48. package/dist/context.d.ts.map +0 -1
  49. package/dist/conversations.d.ts.map +0 -1
  50. package/dist/element-registry.d.ts.map +0 -1
  51. package/dist/errors.d.ts.map +0 -1
  52. package/dist/feedback.d.ts.map +0 -1
  53. package/dist/hooks.d.ts.map +0 -1
  54. package/dist/index.d.ts.map +0 -1
  55. package/dist/notifications.d.ts.map +0 -1
  56. package/dist/observer.d.ts.map +0 -1
  57. package/dist/persistence.d.ts.map +0 -1
  58. package/dist/product-memory.d.ts.map +0 -1
  59. package/dist/quests.d.ts.map +0 -1
  60. package/dist/screenshot-uploader.d.ts.map +0 -1
  61. package/dist/screenshot.d.ts.map +0 -1
  62. package/dist/session.d.ts.map +0 -1
  63. package/dist/signals.d.ts.map +0 -1
  64. package/dist/storage.d.ts.map +0 -1
  65. package/dist/stream-parser.d.ts.map +0 -1
  66. package/dist/testing.d.ts.map +0 -1
  67. package/dist/tickets.d.ts.map +0 -1
  68. package/dist/tools.d.ts.map +0 -1
  69. package/dist/triggers.d.ts.map +0 -1
  70. package/dist/types.d.ts.map +0 -1
  71. package/dist/ui-actions.d.ts.map +0 -1
  72. package/dist/voice.d.ts.map +0 -1
package/README.md CHANGED
@@ -1,398 +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, etc.), it POSTs to your registered callback URL.
180
-
181
- ```typescript
182
- import { CallbackHandler } from '@ziggy-ai/client-sdk';
183
-
184
- const handler = new CallbackHandler();
185
-
186
- handler
187
- .on('support.navigate', async (params) => {
188
- router.push(params.path as string);
189
- return { navigated: true };
190
- })
191
- .on('support.retry_process', async (params) => {
192
- await processes.retry(params.processId as string);
193
- return { retried: true };
194
- });
195
-
196
- // Mount in your API framework
197
- app.post('/api/ziggy/callback', async (req, res) => {
198
- const result = await handler.handle(req.body);
199
- res.json(result);
200
- });
201
- ```
202
-
203
- ---
204
-
205
- ### Tools
206
-
207
- Invoke tools directly (e.g., from quick action buttons).
208
-
209
- ```typescript
210
- const result = await ziggy.tools.invoke('support.navigate', { path: '/settings' });
211
-
212
- // Streaming tool invocation
213
- for await (const event of ziggy.tools.invokeStream('support.respond', { message: 'Hi' })) {
214
- // event.type: 'tool.start' | 'tool.result'
215
- }
216
- ```
217
-
218
- ---
219
-
220
- ### Feedback
221
-
222
- ```typescript
223
- // Quick reaction
224
- await ziggy.feedback.react('msg-1', 'helpful');
225
- // reaction: 'helpful' | 'not_helpful' | 'wrong' | 'perfect'
226
-
227
- // Detailed feedback
228
- await ziggy.feedback.submit({
229
- conversationId: 'conv-1',
230
- type: 'accuracy', // 'accuracy' | 'helpfulness' | 'tone' | 'action' | 'correction'
231
- rating: 4,
232
- comment: 'Good answer but missed one detail',
233
- userId: 'user-1',
234
- });
235
-
236
- // Record coordination outcome (for learning loop)
237
- await ziggy.feedback.recordOutcome({
238
- coordinationId: 'coord-1',
239
- success: true,
240
- agentIds: ['knuckles'],
241
- });
242
- ```
243
-
244
- ---
245
-
246
- ### Quests
247
-
248
- Track multi-step workflows.
249
-
250
- ```typescript
251
- const { quest } = await ziggy.quests.create({
252
- title: 'Investigate transform failure',
253
- sessionId: session.sessionId,
254
- initiatorId: 'knuckles',
255
- steps: [
256
- { label: 'Check logs', agentId: 'ziggy' },
257
- { label: 'Analyze error' },
258
- ],
259
- });
260
-
261
- await ziggy.quests.updateStep(quest.id, quest.steps[0].id, {
262
- status: 'complete',
263
- update: { message: 'Found 3 errors in logs' },
264
- });
265
-
266
- // Stream quest updates
267
- for await (const event of ziggy.quests.stream(quest.id)) {
268
- // event.type: 'quest.status' | 'quest.step_update' | 'quest.complete'
269
- }
270
- ```
271
-
272
- ---
273
-
274
- ### Analytics
275
-
276
- Events are auto-batched every 30 seconds and flushed on disconnect.
277
-
278
- ```typescript
279
- ziggy.analytics.track('feature_used', { feature: 'dark-mode' });
280
- ziggy.analytics.track('page_viewed', { path: '/settings' });
281
- ```
282
-
283
- ---
284
-
285
- ## Stream Events
286
-
287
- All streaming endpoints use ndjson (newline-delimited JSON) with sequence numbers for resumption.
288
-
289
- | Event Type | Key Fields | Description |
290
- |------------|------------|-------------|
291
- | `stream.start` | `streamId`, `messageId` | Always first |
292
- | `agent.start` | `agentId`, `agentRole` | Routed agent begins |
293
- | `agent.switch` | `fromAgentId`, `toAgentId` | Agent handoff |
294
- | `content.delta` | `content` | Partial text |
295
- | `content.done` | `fullContent` | Complete text |
296
- | `tool.start` | `toolId`, `toolName` | Tool invoked |
297
- | `tool.progress` | `toolId`, `progress` | Tool progress (0-1) |
298
- | `tool.result` | `toolId`, `success` | Tool completed |
299
- | `metadata` | `confidence`, `quickActions` | Response metadata |
300
- | `stream.end` | `messageId`, `durationMs` | Always last |
301
- | `error` | `code`, `message`, `retryable` | Error during stream |
302
-
303
- ### Stream Resumption
304
-
305
- ```typescript
306
- import { SequenceTracker } from '@ziggy-ai/client-sdk';
307
-
308
- const tracker = new SequenceTracker();
309
-
310
- for await (const event of ziggy.chat.stream({ message: 'Hello' })) {
311
- tracker.update(event);
312
- // ... process event
313
- }
314
-
315
- // If disconnected, resume:
316
- if (tracker.streamId) {
317
- for await (const event of ziggy.chat.resume(tracker.streamId, tracker.lastSeq)) {
318
- // Picks up from where you left off
319
- }
320
- }
321
- ```
322
-
323
- ---
324
-
325
- ## Error Handling
326
-
327
- ```typescript
328
- import { ZiggyError, ZiggyConnectionError } from '@ziggy-ai/client-sdk';
329
-
330
- try {
331
- for await (const event of ziggy.chat.stream({ message: 'Hello' })) { /* ... */ }
332
- } catch (error) {
333
- if (error instanceof ZiggyConnectionError) {
334
- // Network/timeout — error.retryable is true
335
- console.log('Connection failed, will retry');
336
- } else if (error instanceof ZiggyError) {
337
- // API error — check error.status
338
- console.log(`API error ${error.status}: ${error.message}`);
339
- }
340
- }
341
- ```
342
-
343
- ### Retry Utility
344
-
345
- ```typescript
346
- import { withRetry } from '@ziggy-ai/client-sdk';
347
-
348
- const result = await withRetry(
349
- () => ziggy.chat.action({ actionId: 'support.explain_limits' }),
350
- { maxRetries: 3, baseDelayMs: 1000, maxDelayMs: 30000 },
351
- );
352
- // Retries with exponential backoff + jitter. Skips retry for 4xx errors.
353
- ```
354
-
355
- ---
356
-
357
- ## Architecture
358
-
359
- The SDK is a thin client that maps to Ziggy's v1 REST API:
360
-
361
- ```
362
- ZiggyClient
363
- ├── sessions → POST/DELETE /v1/sessions
364
- ├── chat → POST /v1/chat/stream, POST /v1/chat/action/stream
365
- ├── context → POST /v1/sessions/:id/context (auto-batched)
366
- ├── tools → POST /v1/tools/invoke
367
- ├── feedback → POST /v1/feedback/*
368
- ├── quests → /v1/quests/*
369
- ├── analytics → POST /v1/feedback/analytics/events (auto-batched)
370
- ├── app → /v1/apps/* (triggers, quick actions, brand, credentials)
371
- └── callbacks → CallbackHandler (host-side, receives Ziggy tool requests)
372
- ```
373
-
374
- **Key design decisions:**
375
-
376
- - **Auto-batching** — Context (10s) and analytics (30s) are batched to reduce API calls. Important context changes flush immediately.
377
- - **Streaming** — Uses Streamable HTTP with ndjson (MCP 2025-03-26 standard). Sequence numbers enable reconnection.
378
- - **Composition** — Each API area is a separate module composed by `ZiggyClient`.
379
- - **Zero dependencies** — Uses only `fetch` (built into Node 18+ and all modern browsers).
380
-
381
- ---
382
-
383
- ## Development
384
-
385
- ```bash
386
- npm run build # Build with tsup (ESM + .d.ts)
387
- npm run dev # Watch mode
388
- npm run typecheck # Type check without emit
389
- npm test # Run tests (vitest)
390
- ```
391
-
392
- ## Publishing (from repo root)
393
-
394
- ```bash
395
- npm version patch # in packages/client-sdk and/or packages/react
396
- npm run sdk:publish # builds both, prints npm publish commands
397
- npm run sdk:sync-consumers # after publish: bump console + examples
398
- ```
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
+ ```