@ziggy-ai/client-sdk 1.5.0 → 1.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @ziggy-ai/client-sdk changelog
2
2
 
3
+ ## 1.7.0
4
+
5
+ ### Added
6
+ - `getQueryParams` in the client config: an optional hook that adds query parameters to API requests (for example `perspective` and `sessionId` when an owner previews the chat as a customer). Parameters already on the path win and are never overwritten.
7
+ - `feeling` on the `metadata` stream event, and the `ReplyFeeling` type: what the assistant's reply felt like (`plain`, `glad`, `curious`, `unsure`, `caring`, `handoff`), for a host that shows it. Optional; absent on older servers. Ignore values you do not know.
8
+
9
+ ## 1.6.0
10
+
11
+ ### Added
12
+ - `getVisitorToken` in the client config, and `createVisitorToken({ appId, ziggyUrl })` to make it. For an app whose own server calls Ziggy (a self-host proxy): the browser gets a token from Ziggy, the SDK sends it as `X-Ziggy-Visitor-Token`, and your proxy passes it on. With it the assistant can be shown a person's own earlier exchanges; without it your app works as before. Nothing is fetched or stored unless you set it. Update your proxy to forward the header (docs/guides/easy-integrate.md). A proxy on another origin must also allow the header in its CORS answer.
13
+
3
14
  ## 1.5.0
4
15
 
5
16
  Includes the unpublished 1.4.0 changes: `client.app.getAvailability()` and the `plan` field on `VerifyResponse`.
package/README.md CHANGED
@@ -56,9 +56,24 @@ const ziggy = new ZiggyClient({
56
56
  appId: string; // Your app identifier
57
57
  apiKey: string; // API key (from App node in Ziggy)
58
58
  timeout?: number; // Request timeout in ms (default: 30000)
59
+ getVisitorToken?: () => Promise<string | null>; // Self-host proxies only, see below
59
60
  });
60
61
  ```
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
+
62
77
  #### Lifecycle
63
78
 
64
79
  ```typescript
@@ -6,7 +6,11 @@
6
6
  import type { ZiggyClientConfig } from './types.js';
7
7
  export declare class Connection {
8
8
  private config;
9
+ private sessionIdGetter;
9
10
  constructor(config: ZiggyClientConfig);
11
+ /** Provide the live active session id for request-level query parameter hooks. */
12
+ setSessionIdGetter(getter: () => string | null): void;
13
+ private buildUrl;
10
14
  /**
11
15
  * Make an authenticated JSON request.
12
16
  */
package/dist/index.d.ts CHANGED
@@ -134,10 +134,12 @@ export declare class ZiggyClient {
134
134
  */
135
135
  disconnect(): Promise<void>;
136
136
  }
137
- export type { RecommendationDiscussionReference, BrowserReviewDiscussionReference, ZiggyClientConfig, CreateSessionRequest, SessionResponse, SessionExperiences, ExperienceKey, ExperienceWalkthroughStep, SessionConfig, AgentSummary, CatalogAgent, AgentListResponse, CatalogTool, AgentDetailResponse, PageContext, ProcessContext, ContentContext, UserContext, ErrorEntry, SupportContext, ContextPushRequest, ContextPushResponse, ContextEvent, ChatRequest, ChatResponse, ChatAttachment, ActionRequest, ActionResponse, Confidence, Source, ToolUsage, StreamEvent, StreamStartEvent, AgentStartEvent, AgentSwitchEvent, ToolStartEvent, ToolProgressEvent, ToolResultEvent, ContentDeltaEvent, ContentDoneEvent, MetadataEvent, StreamEndEvent, StreamErrorEvent, ToolErrorEvent, ReturnHandoffEvent, ActivityEvent, QuestStatusEvent, QuestStepUpdateEvent, QuestCompleteEvent, WalkthroughStep, UIHighlightEvent, UIScrollEvent, UIClickEvent, UITypeEvent, UIWalkthroughEvent, UINavigateEvent, UIScreenshotAnalysisEvent, UISurfaceEvent, HostActionEvent, ChatSurfaceMode, HostActionDefinition, RegisterHostActionsRequest, RegisterHostActionsResponse, ListHostActionsResponse, ScreenshotAnnotation, WalkthroughResult, BrandConfig, SpokenVoiceConfig, SpokenVoiceRecommendation, SpokenVoiceRecommendationsResponse, ProactiveTrigger, QuickAction, ToolInvokeRequest, ToolInvokeResponse, ReactionRequest, FeedbackRequest, Quest, QuestStep, TriggerCondition, TriggerRegistration, RegisterTriggersRequest, RegisterTriggersResponse, ListTriggersResponse, DeleteResponse, QuickActionSetConditions, QuickActionSet, RegisterQuickActionsRequest, RegisterQuickActionsResponse, ListQuickActionsResponse, RegisterBrandRequest, OwnerProfileFields, SetProfileResponse, AddDomainConceptRequest, AddDomainConceptResponse, GetBrandResponse, PublicBrandResponse, SetCredentialsRequest, SetCredentialsResponse, GetCredentialsResponse, AppCallbackResponse, Ticket, CreateTicketRequest, CreateTicketResponse, UpdateTicketRequest, TicketFilters, TicketResponse, CreateTicketResponseRequest, TicketAnalysis, TimelineEvent, TicketTimeline, TicketConversation, TriageTicket, TicketPattern, MediaAttachment, RequestUploadRequest, RequestUploadResponse, ConfirmUploadResponse, UploadMediaRequest, UploadMediaResponse, VoiceTokenResponse, VoiceTtsResult, VoiceTtsAudio, VoiceTtsFallback, LiveConversationState, LiveSessionCreateRequest, LiveSessionCreateResponse, LiveSessionCloseResponse, LiveInterruptResponse, LiveSessionStatus, LiveStateEvent, LiveTranscriptEvent, LiveTurnEvent, LiveCommentaryEvent, LiveUsageEvent, LiveClosedEvent, DiscoveryJobStatus, PageType, DiscoveryJob, DiscoveredPage, AnalysisType, AnalysisIssue, AnalysisResult, SpecialistAnalysis, AppPersona, TestScenario, TestStrategy, ChangeEvent, ScreenshotConfig, ScreencastConfig, ScreencastFrame, TestRunStatus, TestResultStatus, TestRun, TestResult, StepResult, TestInsight, TriggerDiscoveryRequest, TriggerAnalysisRequest, GeneratePersonasRequest, GenerateTestScenariosRequest, GenerateTestStrategyRequest, DetectChangesRequest, CaptureScreenshotsRequest, StartTestRunRequest, AnalyzeTestRunRequest, ConversationPartnerState, ConversationPartnerCommand, ConversationMessage, ConversationSummary, ConversationDetail, ConversationMessagesPage, AppStatus, VerifyResponse, AppAvailabilityResponse, AppPlanState, ChatAvailability, ChatFallback, YoloConfig, SetYoloConfigRequest, DeploymentSettings, UpdateDeploymentSettingsRequest, TriageConfig, SetTriageConfigRequest, ToolConfig, SetToolConfigRequest, ObservationCycle, ObservationCycleDetail, Observation, HealthScore, HealthScoreResponse, SignalsResponse, SelfTestCycle, SelfTestCycleDetail, SuiteResult, SelfTestResult, TestingBrainReport, SelfTestTrend, TriggerResponse, EngineeringJob, EngineeringProposal, ProposalDeployment, TriggerEngineeringRequest, UpdateProposalRequest, TriggerDeploymentRequest, UpdateDeploymentRequest, AuditTriggerResponse, ObserverConfigResponse, DesignTokens, ComponentSpec, DesignSystemResponse, DesignTokensResponse, ComponentSpecResponse, Notification, NotificationType, NotificationSeverity, NotificationStatus, NotificationsResponse, NotificationCountResponse, CodeChangeEvent, SignificanceLevel, StreamCollectingEvent, StreamQueuedEvent, StreamSteeringEvent, StreamInterruptedEvent, CoalesceResponse, TurnMetrics, TurnStartedEvent, TurnMetricsEvent, TurnCompletedEvent, SpanStartedEvent, SpanCompletedEvent, SpanErrorEvent, UICaptureScreenshotEvent, CrewPlanEvent, AgentDispatchedEvent, AgentProgressEvent, AgentFindingEvent, AgentCompleteEvent, CrewSynthesisEvent, CrewCompleteEvent, CrewAwaitingApprovalEvent, CrewApprovedEvent, CrewCancelledEvent, CrewStoppedEvent, AgentHandoffEvent, HookName, HookStyle, WebhookHook, CreateHookRequest, UpdateHookRequest, ListHooksResponse, InboundSignalStatus, InboundSignalOutcome, InboundSignalEnvironment, InboundSignalPriority, InboundSignalRelease, InboundSignal, CreateInboundSignalRequest, CreateInboundSignalResponse, InboundSignalFilters, InboundSignalDetailResponse, SignalAutomationMode, AutomationPolicy, SetAutomationPolicyRequest, SignalWebhookEventType, SignalWebhookSubscription, CreateSignalWebhookSubscriptionRequest, UpdateSignalWebhookSubscriptionRequest, CreateSignalWebhookSubscriptionResponse, SignalWebhookDeliveryStatus, SignalWebhookDelivery, RoomParticipantKind, RoomParticipantRole, RoomParticipantMode, RoomPresenceState, Participant, RoomEventType, RoomEvent, RoutingSignal, ReclaimSignal, RoutingEvent, RoomParticipantsResponse, InviteHumanRequest, InviteHumanResponse, } from './types.js';
137
+ export type { RecommendationDiscussionReference, BrowserReviewDiscussionReference, ZiggyClientConfig, CreateSessionRequest, SessionResponse, SessionExperiences, ExperienceKey, ExperienceWalkthroughStep, SessionConfig, AgentSummary, CatalogAgent, AgentListResponse, CatalogTool, AgentDetailResponse, PageContext, ProcessContext, ContentContext, UserContext, ErrorEntry, SupportContext, ContextPushRequest, ContextPushResponse, ContextEvent, ChatRequest, ChatResponse, ChatAttachment, ActionRequest, ActionResponse, Confidence, Source, ToolUsage, StreamEvent, StreamStartEvent, AgentStartEvent, AgentSwitchEvent, ToolStartEvent, ToolProgressEvent, ToolResultEvent, ContentDeltaEvent, ContentDoneEvent, MetadataEvent, ReplyFeeling, StreamEndEvent, StreamErrorEvent, ToolErrorEvent, ReturnHandoffEvent, ActivityEvent, QuestStatusEvent, QuestStepUpdateEvent, QuestCompleteEvent, WalkthroughStep, UIHighlightEvent, UIScrollEvent, UIClickEvent, UITypeEvent, UIWalkthroughEvent, UINavigateEvent, UIScreenshotAnalysisEvent, UISurfaceEvent, HostActionEvent, ChatSurfaceMode, HostActionDefinition, RegisterHostActionsRequest, RegisterHostActionsResponse, ListHostActionsResponse, ScreenshotAnnotation, WalkthroughResult, BrandConfig, SpokenVoiceConfig, SpokenVoiceRecommendation, SpokenVoiceRecommendationsResponse, ProactiveTrigger, QuickAction, ToolInvokeRequest, ToolInvokeResponse, ReactionRequest, FeedbackRequest, Quest, QuestStep, TriggerCondition, TriggerRegistration, RegisterTriggersRequest, RegisterTriggersResponse, ListTriggersResponse, DeleteResponse, QuickActionSetConditions, QuickActionSet, RegisterQuickActionsRequest, RegisterQuickActionsResponse, ListQuickActionsResponse, RegisterBrandRequest, OwnerProfileFields, SetProfileResponse, AddDomainConceptRequest, AddDomainConceptResponse, GetBrandResponse, PublicBrandResponse, SetCredentialsRequest, SetCredentialsResponse, GetCredentialsResponse, AppCallbackResponse, Ticket, CreateTicketRequest, CreateTicketResponse, UpdateTicketRequest, TicketFilters, TicketResponse, CreateTicketResponseRequest, TicketAnalysis, TimelineEvent, TicketTimeline, TicketConversation, TriageTicket, TicketPattern, MediaAttachment, RequestUploadRequest, RequestUploadResponse, ConfirmUploadResponse, UploadMediaRequest, UploadMediaResponse, VoiceTokenResponse, VoiceTtsResult, VoiceTtsAudio, VoiceTtsFallback, LiveConversationState, LiveSessionCreateRequest, LiveSessionCreateResponse, LiveSessionCloseResponse, LiveInterruptResponse, LiveSessionStatus, LiveStateEvent, LiveTranscriptEvent, LiveTurnEvent, LiveCommentaryEvent, LiveUsageEvent, LiveClosedEvent, DiscoveryJobStatus, PageType, DiscoveryJob, DiscoveredPage, AnalysisType, AnalysisIssue, AnalysisResult, SpecialistAnalysis, AppPersona, TestScenario, TestStrategy, ChangeEvent, ScreenshotConfig, ScreencastConfig, ScreencastFrame, TestRunStatus, TestResultStatus, TestRun, TestResult, StepResult, TestInsight, TriggerDiscoveryRequest, TriggerAnalysisRequest, GeneratePersonasRequest, GenerateTestScenariosRequest, GenerateTestStrategyRequest, DetectChangesRequest, CaptureScreenshotsRequest, StartTestRunRequest, AnalyzeTestRunRequest, ConversationPartnerState, ConversationPartnerCommand, ConversationMessage, ConversationSummary, ConversationDetail, ConversationMessagesPage, AppStatus, VerifyResponse, AppAvailabilityResponse, AppPlanState, ChatAvailability, ChatFallback, YoloConfig, SetYoloConfigRequest, DeploymentSettings, UpdateDeploymentSettingsRequest, TriageConfig, SetTriageConfigRequest, ToolConfig, SetToolConfigRequest, ObservationCycle, ObservationCycleDetail, Observation, HealthScore, HealthScoreResponse, SignalsResponse, SelfTestCycle, SelfTestCycleDetail, SuiteResult, SelfTestResult, TestingBrainReport, SelfTestTrend, TriggerResponse, EngineeringJob, EngineeringProposal, ProposalDeployment, TriggerEngineeringRequest, UpdateProposalRequest, TriggerDeploymentRequest, UpdateDeploymentRequest, AuditTriggerResponse, ObserverConfigResponse, DesignTokens, ComponentSpec, DesignSystemResponse, DesignTokensResponse, ComponentSpecResponse, Notification, NotificationType, NotificationSeverity, NotificationStatus, NotificationsResponse, NotificationCountResponse, CodeChangeEvent, SignificanceLevel, StreamCollectingEvent, StreamQueuedEvent, StreamSteeringEvent, StreamInterruptedEvent, CoalesceResponse, TurnMetrics, TurnStartedEvent, TurnMetricsEvent, TurnCompletedEvent, SpanStartedEvent, SpanCompletedEvent, SpanErrorEvent, UICaptureScreenshotEvent, CrewPlanEvent, AgentDispatchedEvent, AgentProgressEvent, AgentFindingEvent, AgentCompleteEvent, CrewSynthesisEvent, CrewCompleteEvent, CrewAwaitingApprovalEvent, CrewApprovedEvent, CrewCancelledEvent, CrewStoppedEvent, AgentHandoffEvent, HookName, HookStyle, WebhookHook, CreateHookRequest, UpdateHookRequest, ListHooksResponse, InboundSignalStatus, InboundSignalOutcome, InboundSignalEnvironment, InboundSignalPriority, InboundSignalRelease, InboundSignal, CreateInboundSignalRequest, CreateInboundSignalResponse, InboundSignalFilters, InboundSignalDetailResponse, SignalAutomationMode, AutomationPolicy, SetAutomationPolicyRequest, SignalWebhookEventType, SignalWebhookSubscription, CreateSignalWebhookSubscriptionRequest, UpdateSignalWebhookSubscriptionRequest, CreateSignalWebhookSubscriptionResponse, SignalWebhookDeliveryStatus, SignalWebhookDelivery, RoomParticipantKind, RoomParticipantRole, RoomParticipantMode, RoomPresenceState, Participant, RoomEventType, RoomEvent, RoutingSignal, ReclaimSignal, RoutingEvent, RoomParticipantsResponse, InviteHumanRequest, InviteHumanResponse, } from './types.js';
138
138
  export { ZiggyError, ZiggyConnectionError } from './errors.js';
139
139
  export { LocalStoragePersistence } from './persistence.js';
140
140
  export type { PersistenceAdapter } from './persistence.js';
141
+ export { createVisitorToken } from './visitor-token.js';
142
+ export type { VisitorTokenOptions } from './visitor-token.js';
141
143
  export { parseNdjsonStream, SequenceTracker } from './stream-parser.js';
142
144
  export { CallbackHandler, verifyCallbackSignature, DEFAULT_CALLBACK_TOLERANCE_MS } from './callback-handler.js';
143
145
  export { ObserverClient } from './observer.js';
package/dist/index.js CHANGED
@@ -16,7 +16,74 @@ var ZiggyConnectionError = class extends ZiggyError {
16
16
  }
17
17
  };
18
18
 
19
+ // src/visitor-token.ts
20
+ var VISITOR_ID = /^visitor_[a-f0-9]{32}$/;
21
+ var FIRST_TOKEN_WAIT_MS = 2e3;
22
+ var RETRY_AFTER_MS = 5 * 6e4;
23
+ function createVisitorToken(options) {
24
+ const storageKey = `ziggy:visitor-proof:${options.appId}`;
25
+ const url = `${options.ziggyUrl.replace(/\/+$/, "")}/browser/${encodeURIComponent(options.appId)}/visitor`;
26
+ let token = null;
27
+ let renewing = null;
28
+ let askAt = 0;
29
+ const renew = async () => {
30
+ askAt = Date.now() + RETRY_AFTER_MS;
31
+ const controller = new AbortController();
32
+ const timer = setTimeout(() => controller.abort(), 1e4);
33
+ try {
34
+ const res = await fetch(url, {
35
+ method: "POST",
36
+ headers: token ? { Authorization: `Bearer ${token}` } : {},
37
+ signal: controller.signal
38
+ });
39
+ if (!res.ok) {
40
+ if (res.status === 403 || res.status === 404 || res.status === 409) askAt = Infinity;
41
+ return;
42
+ }
43
+ const issued = tokenIn(await res.json());
44
+ if (!issued) return;
45
+ token = issued;
46
+ askAt = Infinity;
47
+ try {
48
+ window.localStorage.setItem(storageKey, issued);
49
+ } catch {
50
+ }
51
+ } catch {
52
+ } finally {
53
+ clearTimeout(timer);
54
+ }
55
+ };
56
+ return async () => {
57
+ if (typeof window === "undefined") return null;
58
+ if (!token) {
59
+ try {
60
+ const kept = window.localStorage.getItem(storageKey);
61
+ if (isVisitorToken(kept)) token = kept;
62
+ } catch {
63
+ }
64
+ }
65
+ if (!renewing && Date.now() >= askAt) {
66
+ renewing = renew().finally(() => {
67
+ renewing = null;
68
+ });
69
+ }
70
+ if (!token && renewing) {
71
+ await Promise.race([renewing, new Promise((done) => setTimeout(done, FIRST_TOKEN_WAIT_MS))]);
72
+ }
73
+ return token;
74
+ };
75
+ }
76
+ function isVisitorToken(value) {
77
+ return typeof value === "string" && /^[A-Za-z0-9._~+/=-]{1,512}$/.test(value);
78
+ }
79
+ function tokenIn(value) {
80
+ if (!value || typeof value !== "object") return null;
81
+ const { userId, token } = value;
82
+ return typeof userId === "string" && VISITOR_ID.test(userId) && isVisitorToken(token) ? token : null;
83
+ }
84
+
19
85
  // src/auth.ts
86
+ var VISITOR_TOKEN_WAIT_MS = 3e3;
20
87
  async function buildHeaders(config, extra) {
21
88
  const headers = {
22
89
  "Content-Type": "application/json",
@@ -30,20 +97,69 @@ async function buildHeaders(config, extra) {
30
97
  headers["Authorization"] = `Bearer ${token}`;
31
98
  }
32
99
  }
100
+ const visitorToken = await visitorTokenOf(config);
101
+ if (visitorToken) headers["X-Ziggy-Visitor-Token"] = visitorToken;
33
102
  return headers;
34
103
  }
104
+ async function visitorTokenOf(config) {
105
+ if (!config.getVisitorToken) return null;
106
+ let timer;
107
+ try {
108
+ const token = await Promise.race([
109
+ config.getVisitorToken(),
110
+ new Promise((done) => {
111
+ timer = setTimeout(() => done(null), VISITOR_TOKEN_WAIT_MS);
112
+ })
113
+ ]);
114
+ return isVisitorToken(token) ? token : null;
115
+ } catch {
116
+ return null;
117
+ } finally {
118
+ clearTimeout(timer);
119
+ }
120
+ }
35
121
 
36
122
  // src/connection.ts
37
123
  var Connection = class {
38
124
  config;
125
+ sessionIdGetter = () => null;
39
126
  constructor(config) {
40
127
  this.config = config;
41
128
  }
129
+ /** Provide the live active session id for request-level query parameter hooks. */
130
+ setSessionIdGetter(getter) {
131
+ this.sessionIdGetter = getter;
132
+ }
133
+ buildUrl(method, path) {
134
+ const extra = this.config.getQueryParams?.({
135
+ method,
136
+ path,
137
+ sessionId: this.sessionIdGetter()
138
+ });
139
+ if (!extra) {
140
+ return `${this.config.baseUrl}/v1${path}`;
141
+ }
142
+ const qIdx = path.indexOf("?");
143
+ const pathname = qIdx === -1 ? path : path.slice(0, qIdx);
144
+ const params = new URLSearchParams(qIdx === -1 ? "" : path.slice(qIdx + 1));
145
+ let changed = false;
146
+ for (const [key, value] of Object.entries(extra)) {
147
+ if (typeof value === "string" && value.length > 0 && !params.has(key)) {
148
+ params.set(key, value);
149
+ changed = true;
150
+ }
151
+ }
152
+ if (!changed) {
153
+ return `${this.config.baseUrl}/v1${path}`;
154
+ }
155
+ const qs = params.toString();
156
+ return `${this.config.baseUrl}/v1${pathname}${qs ? `?${qs}` : ""}`;
157
+ }
42
158
  /**
43
159
  * Make an authenticated JSON request.
44
160
  */
45
161
  async request(method, path, body, extraHeaders) {
46
- const url = `${this.config.baseUrl}/v1${path}`;
162
+ const url = this.buildUrl(method, path);
47
163
  const headers = await buildHeaders(this.config, extraHeaders);
48
164
  const timeout = this.config.timeout ?? 3e4;
49
165
  const controller = new AbortController();
@@ -83,7 +199,7 @@ var Connection = class {
83
199
  * Make an authenticated request that returns a ReadableStream (for ndjson).
84
200
  */
85
201
  async streamRequest(method, path, body, signal) {
86
- const url = `${this.config.baseUrl}/v1${path}`;
202
+ const url = this.buildUrl(method, path);
87
203
  const headers = await buildHeaders(this.config);
88
204
  try {
89
205
  const response = await fetch(url, {
@@ -2543,6 +2659,7 @@ var ZiggyClient = class {
2543
2659
  this.config = config;
2544
2660
  this.connection = new Connection(config);
2545
2661
  this.sessions = new SessionManager(this.connection, config);
2662
+ this.connection.setSessionIdGetter(() => this.sessions.sessionId);
2546
2663
  this.chat = new ChatClient(this.connection, this.sessions);
2547
2664
  this.context = new ContextManager(this.sessions);
2548
2665
  this.tools = new ToolClient(this.connection, this.sessions);
@@ -2625,6 +2742,7 @@ export {
2625
2742
  ZiggyConnectionError,
2626
2743
  ZiggyError,
2627
2744
  captureAndUpload,
2745
+ createVisitorToken,
2628
2746
  isProductMemoryEventType,
2629
2747
  parseNdjsonStream,
2630
2748
  verifyCallbackSignature
package/dist/types.d.ts CHANGED
@@ -14,12 +14,28 @@ export interface ZiggyClientConfig {
14
14
  timeout?: number;
15
15
  /** Optional async token getter for proxy auth (e.g., Clerk JWT) */
16
16
  getAuthToken?: () => Promise<string | null>;
17
+ /**
18
+ * For an app whose own server calls Ziggy (a self-host proxy): the browser's visitor token, from
19
+ * `createVisitorToken`. Sent as `X-Ziggy-Visitor-Token`, which your proxy passes on. Not used with
20
+ * the managed proxy, which verifies the person itself.
21
+ */
22
+ getVisitorToken?: () => Promise<string | null>;
17
23
  /**
18
24
  * Optional persistence adapter for conversation continuity across page reloads.
19
25
  * When configured, the SDK stores conversationId + sessionId and auto-restores
20
26
  * on the next `connect()` call.
21
27
  */
22
28
  persistence?: import('./persistence.js').PersistenceAdapter;
29
+ /**
30
+ * Optional hook to append query parameters to v1 API requests (for example,
31
+ * `?perspective=end_user&sessionId=...` during operator customer preview).
32
+ * Existing parameters on the path take precedence and are not overwritten.
33
+ */
34
+ getQueryParams?: (request: {
35
+ method: string;
36
+ path: string;
37
+ sessionId: string | null;
38
+ }) => Record<string, string | undefined> | undefined;
23
39
  }
24
40
  export interface CreateSessionRequest {
25
41
  userId: string;
@@ -588,11 +604,15 @@ export interface ContentDoneEvent {
588
604
  fullContent: string;
589
605
  seq: number;
590
606
  }
607
+ /** What the assistant's reply felt like, for a host that shows it (the chat character). Unknown values are ignored. */
608
+ export type ReplyFeeling = 'plain' | 'glad' | 'curious' | 'unsure' | 'caring' | 'handoff';
591
609
  export interface MetadataEvent {
592
610
  type: 'metadata';
593
611
  confidence: Confidence;
594
612
  sources?: Source[];
595
613
  quickActions?: QuickAction[];
614
+ /** Present on replies from a server that judges them; absent on older servers and short paths. */
615
+ feeling?: ReplyFeeling;
596
616
  seq: number;
597
617
  }
598
618
  export interface StreamEndEvent {
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The token that proves "the same browser as before", for an app whose own
3
+ * server calls Ziggy (a self-host proxy).
4
+ *
5
+ * Ziggy takes such a server's word for the user id, so it cannot tell two
6
+ * people sent under one id apart. The browser gets this token from Ziggy
7
+ * itself, the SDK sends it along, and the app's proxy passes it on. Ziggy uses
8
+ * it only to decide which of a person's own earlier exchanges the assistant may
9
+ * be shown. It is not a sign-in and changes nothing the person can see or do.
10
+ *
11
+ * Only ever in a browser: on a server it would be one token for everybody.
12
+ */
13
+ export interface VisitorTokenOptions {
14
+ /** Your app's id. */
15
+ appId: string;
16
+ /** Ziggy's API, e.g. `https://ziggy-production-e3be.up.railway.app`. Not your own proxy: the browser asks Ziggy itself. */
17
+ ziggyUrl: string;
18
+ }
19
+ /**
20
+ * Returns the function to give `ZiggyClient` or `ZiggyProvider` as
21
+ * `getVisitorToken`. Create it once, outside render.
22
+ *
23
+ * The site's address must be one of the app's allowed origins. Any failure
24
+ * means no token, and requests go on without it.
25
+ */
26
+ export declare function createVisitorToken(options: VisitorTokenOptions): () => Promise<string | null>;
27
+ /** Whether a value can be a visitor token, and so can be sent as a header: setting one that cannot throws. */
28
+ export declare function isVisitorToken(value: unknown): value is string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ziggy-ai/client-sdk",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "Client SDK for integrating with Ziggy's v1 API",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",