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