@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/dist/app.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * (resolved server-side by auth middleware), so no appId is needed here.
6
6
  */
7
7
  import type { Connection } from './connection.js';
8
- import type { RegisterTriggersRequest, RegisterTriggersResponse, ListTriggersResponse, DeleteResponse, RegisterQuickActionsRequest, RegisterQuickActionsResponse, ListQuickActionsResponse, RegisterHostActionsRequest, RegisterHostActionsResponse, ListHostActionsResponse, RegisterBrandRequest, OwnerProfileFields, SetProfileResponse, AddDomainConceptRequest, AddDomainConceptResponse, GetBrandResponse, SpokenVoiceRecommendationsResponse, SpokenVoiceConfig, SetCredentialsRequest, SetCredentialsResponse, GetCredentialsResponse, AppCallbackResponse, AppStatus, VerifyResponse, YoloConfig, SetYoloConfigRequest, DeploymentSettings, UpdateDeploymentSettingsRequest, TriageConfig, SetTriageConfigRequest, ToolConfig, SetToolConfigRequest, AuditTriggerResponse, ObserverConfigResponse, DesignSystemResponse, DesignTokensResponse, ComponentSpecResponse } from './types.js';
8
+ import type { RegisterTriggersRequest, RegisterTriggersResponse, ListTriggersResponse, DeleteResponse, RegisterQuickActionsRequest, RegisterQuickActionsResponse, ListQuickActionsResponse, RegisterHostActionsRequest, RegisterHostActionsResponse, ListHostActionsResponse, RegisterBrandRequest, OwnerProfileFields, SetProfileResponse, AddDomainConceptRequest, AddDomainConceptResponse, GetBrandResponse, PublicBrandResponse, SpokenVoiceRecommendationsResponse, SpokenVoiceConfig, SetCredentialsRequest, SetCredentialsResponse, GetCredentialsResponse, AppCallbackResponse, AppStatus, VerifyResponse, AppAvailabilityResponse, YoloConfig, SetYoloConfigRequest, DeploymentSettings, UpdateDeploymentSettingsRequest, TriageConfig, SetTriageConfigRequest, ToolConfig, SetToolConfigRequest, AuditTriggerResponse, ObserverConfigResponse, DesignSystemResponse, DesignTokensResponse, ComponentSpecResponse } from './types.js';
9
9
  export declare class AppClient {
10
10
  getConversationPolicy(): Promise<{
11
11
  mode: 'support_led' | 'visible_team';
@@ -61,9 +61,17 @@ export declare class AppClient {
61
61
  updated: boolean;
62
62
  }>;
63
63
  /**
64
- * Get brand configuration.
64
+ * The public part of the brand profile: the name, the avatar and the main colour. It is what a chat panel
65
+ * draws and all this read answers, for every caller. Safe to call from a browser.
65
66
  */
66
- getBrand(): Promise<GetBrandResponse>;
67
+ getBrand(): Promise<PublicBrandResponse>;
68
+ /**
69
+ * The whole brand profile, as `setBrand` wrote it and the Brand Designer filled it in. For your server only:
70
+ * a request that comes through a browser proxy is refused. Read this one before you change the profile and
71
+ * write it back: `setBrand` replaces the profile with what it is given, and refuses the short answer of
72
+ * `getBrand` (409 `brand_partial_write`) because saving it would remove the rest.
73
+ */
74
+ getFullBrand(): Promise<GetBrandResponse>;
67
75
  /**
68
76
  * Brand-informed top spoken-voice recommendations for chat TTS.
69
77
  */
@@ -88,6 +96,8 @@ export declare class AppClient {
88
96
  /**
89
97
  * Get the full design system (tokens + component specs).
90
98
  * Requires brand extraction to have completed first.
99
+ * Through the managed browser proxy the answer is the tokens only: `components` is empty and the record's
100
+ * ids are left out.
91
101
  */
92
102
  getDesignSystem(): Promise<DesignSystemResponse>;
93
103
  /**
@@ -155,6 +165,12 @@ export declare class AppClient {
155
165
  * Use this as a pre-flight check to confirm the SDK is configured correctly.
156
166
  */
157
167
  verify(): Promise<VerifyResponse>;
168
+ /**
169
+ * Whether this app's chat answers. When it does not (the app's account has no
170
+ * active plan), `chat.fallback` holds what to show visitors instead. Safe to
171
+ * call from a browser through the managed proxy before any user is known.
172
+ */
173
+ getAvailability(): Promise<AppAvailabilityResponse>;
158
174
  /**
159
175
  * Get YOLO mode configuration.
160
176
  */
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, 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, 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, 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,8 +97,27 @@ 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 {
@@ -1067,11 +1153,21 @@ var AppClient = class {
1067
1153
  return this.connection.request("PUT", "/apps/brand", brand);
1068
1154
  }
1069
1155
  /**
1070
- * Get brand configuration.
1156
+ * The public part of the brand profile: the name, the avatar and the main colour. It is what a chat panel
1157
+ * draws and all this read answers, for every caller. Safe to call from a browser.
1071
1158
  */
1072
1159
  async getBrand() {
1073
1160
  return this.connection.request("GET", "/apps/brand");
1074
1161
  }
1162
+ /**
1163
+ * The whole brand profile, as `setBrand` wrote it and the Brand Designer filled it in. For your server only:
1164
+ * a request that comes through a browser proxy is refused. Read this one before you change the profile and
1165
+ * write it back: `setBrand` replaces the profile with what it is given, and refuses the short answer of
1166
+ * `getBrand` (409 `brand_partial_write`) because saving it would remove the rest.
1167
+ */
1168
+ async getFullBrand() {
1169
+ return this.connection.request("GET", "/apps/brand/full");
1170
+ }
1075
1171
  /**
1076
1172
  * Brand-informed top spoken-voice recommendations for chat TTS.
1077
1173
  */
@@ -1105,6 +1201,8 @@ var AppClient = class {
1105
1201
  /**
1106
1202
  * Get the full design system (tokens + component specs).
1107
1203
  * Requires brand extraction to have completed first.
1204
+ * Through the managed browser proxy the answer is the tokens only: `components` is empty and the record's
1205
+ * ids are left out.
1108
1206
  */
1109
1207
  async getDesignSystem() {
1110
1208
  return this.connection.request("GET", "/branding/design-system");
@@ -1196,6 +1294,14 @@ var AppClient = class {
1196
1294
  async verify() {
1197
1295
  return this.connection.request("GET", "/apps/verify");
1198
1296
  }
1297
+ /**
1298
+ * Whether this app's chat answers. When it does not (the app's account has no
1299
+ * active plan), `chat.fallback` holds what to show visitors instead. Safe to
1300
+ * call from a browser through the managed proxy before any user is known.
1301
+ */
1302
+ async getAvailability() {
1303
+ return this.connection.request("GET", "/apps/availability");
1304
+ }
1199
1305
  // ─── YOLO Mode ──────────────────────────────────────────────────────────────
1200
1306
  /**
1201
1307
  * Get YOLO mode configuration.
@@ -2605,6 +2711,7 @@ export {
2605
2711
  ZiggyConnectionError,
2606
2712
  ZiggyError,
2607
2713
  captureAndUpload,
2714
+ createVisitorToken,
2608
2715
  isProductMemoryEventType,
2609
2716
  parseNdjsonStream,
2610
2717
  verifyCallbackSignature
@@ -1,37 +1,37 @@
1
- /**
2
- * Ziggy Agent UI Highlights
3
- *
4
- * CSS classes applied by the agent's UI interaction tools
5
- * (highlight_element, click_element, type_into, etc.)
6
- * to visually indicate elements the agent is interacting with.
7
- *
8
- * Import via: import '@ziggy-ai/client-sdk/styles';
9
- */
10
-
11
- @keyframes ziggy-pulse {
12
- 0%, 100% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.5); }
13
- 50% { box-shadow: 0 0 0 8px rgba(99, 102, 241, 0); }
14
- }
15
-
16
- .ziggy-highlight-pulse {
17
- animation: ziggy-pulse 1.5s ease-in-out infinite;
18
- outline: 2px solid rgb(99, 102, 241);
19
- outline-offset: 2px;
20
- border-radius: 4px;
21
- z-index: 10;
22
- position: relative;
23
- }
24
-
25
- .ziggy-highlight-outline {
26
- outline: 3px solid rgb(99, 102, 241);
27
- outline-offset: 2px;
28
- border-radius: 4px;
29
- transition: outline 0.2s ease;
30
- }
31
-
32
- .ziggy-highlight-overlay {
33
- background-color: rgba(99, 102, 241, 0.1) !important;
34
- outline: 2px solid rgb(99, 102, 241);
35
- outline-offset: 2px;
36
- border-radius: 4px;
37
- }
1
+ /**
2
+ * Ziggy Agent UI Highlights
3
+ *
4
+ * CSS classes applied by the agent's UI interaction tools
5
+ * (highlight_element, click_element, type_into, etc.)
6
+ * to visually indicate elements the agent is interacting with.
7
+ *
8
+ * Import via: import '@ziggy-ai/client-sdk/styles';
9
+ */
10
+
11
+ @keyframes ziggy-pulse {
12
+ 0%, 100% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.5); }
13
+ 50% { box-shadow: 0 0 0 8px rgba(99, 102, 241, 0); }
14
+ }
15
+
16
+ .ziggy-highlight-pulse {
17
+ animation: ziggy-pulse 1.5s ease-in-out infinite;
18
+ outline: 2px solid rgb(99, 102, 241);
19
+ outline-offset: 2px;
20
+ border-radius: 4px;
21
+ z-index: 10;
22
+ position: relative;
23
+ }
24
+
25
+ .ziggy-highlight-outline {
26
+ outline: 3px solid rgb(99, 102, 241);
27
+ outline-offset: 2px;
28
+ border-radius: 4px;
29
+ transition: outline 0.2s ease;
30
+ }
31
+
32
+ .ziggy-highlight-overlay {
33
+ background-color: rgba(99, 102, 241, 0.1) !important;
34
+ outline: 2px solid rgb(99, 102, 241);
35
+ outline-offset: 2px;
36
+ border-radius: 4px;
37
+ }
package/dist/types.d.ts CHANGED
@@ -14,6 +14,12 @@ 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
@@ -738,6 +744,8 @@ export interface HostActionDefinition {
738
744
  sideEffects: 'read' | 'write' | 'destructive';
739
745
  preferredSurface?: ChatSurfaceMode;
740
746
  executor: 'browser' | 'http';
747
+ /** Who is told of the action and may run it: your team; also your signed-in users; or everyone, visitors to your site included. */
748
+ audience?: 'everyone' | 'users' | 'team';
741
749
  uiHints?: Record<string, unknown>;
742
750
  }
743
751
  export interface RegisterHostActionsRequest {
@@ -750,11 +758,20 @@ export interface RegisterHostActionsRequest {
750
758
  sideEffects?: 'read' | 'write' | 'destructive';
751
759
  preferredSurface?: ChatSurfaceMode;
752
760
  executor?: 'browser' | 'http';
761
+ /** Defaults to `team`. `users`: also the signed-in users your app vouches for. `everyone`: also an anonymous visitor on
762
+ * your site. A destructive action with executor `http` must be `team`. An action for everyone must never return the
763
+ * caller's own text as its answer. */
764
+ audience?: 'everyone' | 'users' | 'team';
753
765
  uiHints?: Record<string, unknown>;
754
766
  }>;
755
767
  }
756
768
  export interface RegisterHostActionsResponse {
757
769
  registered: number;
770
+ /** Actions that were stored but will not be offered in chat, and why (for example, too long to describe in full). */
771
+ warnings?: Array<{
772
+ actionId: string;
773
+ problem: string;
774
+ }>;
758
775
  }
759
776
  export interface ListHostActionsResponse {
760
777
  actions: HostActionDefinition[];
@@ -1360,6 +1377,19 @@ export interface RegisterBrandRequest {
1360
1377
  chatPosition?: 'bottom-right' | 'bottom-left' | 'side-panel';
1361
1378
  };
1362
1379
  }
1380
+ /** GET /v1/apps/brand: the part of the brand profile anyone may see. A missing field was never set. */
1381
+ export interface PublicBrandResponse {
1382
+ /** Always true: this is not the whole profile. `setBrand` refuses an object that carries it (409). */
1383
+ partial: true;
1384
+ identity: {
1385
+ name?: string;
1386
+ avatar?: string;
1387
+ };
1388
+ theme: {
1389
+ primaryColor?: string;
1390
+ };
1391
+ }
1392
+ /** GET /v1/apps/brand/full: the whole brand profile, for the app's own server. */
1363
1393
  export interface GetBrandResponse extends RegisterBrandRequest {
1364
1394
  updatedAt: string;
1365
1395
  spokenVoice?: SpokenVoiceConfig | null;
@@ -1741,7 +1771,7 @@ export interface LiveSessionCreateResponse {
1741
1771
  /** Response from GET /v1/voice/live/status */
1742
1772
  export interface LiveSessionStatus {
1743
1773
  available: boolean;
1744
- /** disabled | missing_api_key | app_disabled | config_unavailable | usage_unavailable | capacity | app_capacity | daily_minutes, or null when available */
1774
+ /** disabled | missing_api_key | app_disabled | config_unavailable | usage_unavailable | capacity | app_capacity | daily_minutes | chat_unavailable, or null when available */
1745
1775
  reason: string | null;
1746
1776
  voice: string;
1747
1777
  activeSessions: number;
@@ -2459,6 +2489,25 @@ export interface AppStatus {
2459
2489
  /** @deprecated Use setup.agents.linked */
2460
2490
  agentCount?: number;
2461
2491
  }
2492
+ /** What visitors see in place of the conversation when an app's chat does not answer. */
2493
+ export interface ChatFallback {
2494
+ /** The owner's own message, or Ziggy's default when they set none. */
2495
+ message: string;
2496
+ /** Another way to reach the owner: an `https:` page or a `mailto:` address. Null when they set none. */
2497
+ contactUrl: string | null;
2498
+ }
2499
+ /** Whether an app's chat answers. It does not while the app's account has no active plan. */
2500
+ export interface ChatAvailability {
2501
+ available: boolean;
2502
+ /** Present only when `available` is false. */
2503
+ fallback: ChatFallback | null;
2504
+ }
2505
+ /** Response from GET /v1/apps/availability. */
2506
+ export interface AppAvailabilityResponse {
2507
+ chat: ChatAvailability;
2508
+ }
2509
+ /** The plan state of the account that owns an app. */
2510
+ export type AppPlanState = 'trialing' | 'active' | 'past_due' | 'locked';
2462
2511
  /** Response from GET /v1/apps/verify — lightweight SDK connection check. */
2463
2512
  export interface VerifyResponse {
2464
2513
  valid: true;
@@ -2471,6 +2520,14 @@ export interface VerifyResponse {
2471
2520
  agents: number;
2472
2521
  integrations: number;
2473
2522
  };
2523
+ /**
2524
+ * The owning account's plan state, and whether chat answers. `state` is null
2525
+ * for an app no account owns. Absent from servers older than this field.
2526
+ */
2527
+ plan?: {
2528
+ state: AppPlanState | null;
2529
+ chatAvailable: boolean;
2530
+ };
2474
2531
  }
2475
2532
  export interface DeploymentSettings {
2476
2533
  deploymentPolicy: string;
@@ -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,49 +1,49 @@
1
- {
2
- "name": "@ziggy-ai/client-sdk",
3
- "version": "1.3.0",
4
- "description": "Client SDK for integrating with Ziggy's v1 API",
5
- "type": "module",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
12
- },
13
- "./styles": "./dist/styles/ziggy-highlights.css"
14
- },
15
- "files": [
16
- "dist",
17
- "README.md",
18
- "LICENSE",
19
- "CHANGELOG.md"
20
- ],
21
- "scripts": {
22
- "build": "tsup src/index.ts --format esm --clean --external driver.js --external html2canvas && tsc --emitDeclarationOnly && node -e \"const fs=require('fs');fs.mkdirSync('dist/styles',{recursive:true});fs.copyFileSync('src/styles/ziggy-highlights.css','dist/styles/ziggy-highlights.css')\"",
23
- "dev": "tsup src/index.ts --format esm --watch",
24
- "typecheck": "tsc --noEmit",
25
- "test": "vitest",
26
- "prepublishOnly": "npm run build"
27
- },
28
- "devDependencies": {
29
- "@types/node": "^20.11.0",
30
- "tsup": "^8.0.0",
31
- "typescript": "^5.3.3",
32
- "vitest": "^1.2.2"
33
- },
34
- "keywords": [
35
- "ziggy",
36
- "client",
37
- "sdk",
38
- "chat",
39
- "streaming",
40
- "ndjson"
41
- ],
42
- "license": "MIT",
43
- "repository": {
44
- "type": "git",
45
- "url": "https://github.com/alchemyagentic/Ziggy.git",
46
- "directory": "packages/client-sdk"
47
- },
48
- "dependencies": {}
49
- }
1
+ {
2
+ "name": "@ziggy-ai/client-sdk",
3
+ "version": "1.6.0",
4
+ "description": "Client SDK for integrating with Ziggy's v1 API",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./styles": "./dist/styles/ziggy-highlights.css"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsup src/index.ts --format esm --clean --external driver.js --external html2canvas && tsc --emitDeclarationOnly && node -e \"const fs=require('fs');fs.mkdirSync('dist/styles',{recursive:true});fs.copyFileSync('src/styles/ziggy-highlights.css','dist/styles/ziggy-highlights.css')\"",
23
+ "dev": "tsup src/index.ts --format esm --watch",
24
+ "typecheck": "tsc --noEmit",
25
+ "test": "vitest",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^20.11.0",
30
+ "tsup": "^8.0.0",
31
+ "typescript": "^5.3.3",
32
+ "vitest": "^1.2.2"
33
+ },
34
+ "keywords": [
35
+ "ziggy",
36
+ "client",
37
+ "sdk",
38
+ "chat",
39
+ "streaming",
40
+ "ndjson"
41
+ ],
42
+ "license": "MIT",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "https://github.com/alchemyagentic/Ziggy.git",
46
+ "directory": "packages/client-sdk"
47
+ },
48
+ "dependencies": {}
49
+ }