@paymanai/payman-typescript-ask-sdk 2.0.2 → 4.0.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/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import React from 'react';
2
+
1
3
  type VoiceState = "idle" | "listening" | "processing" | "error";
2
4
  type VoiceConfig = {
3
5
  /** Language for speech recognition (default: "en-US") */
@@ -68,7 +70,8 @@ type UseVoiceReturn = {
68
70
 
69
71
  type MessageRole = "user" | "assistant" | "system";
70
72
  type StreamProgress = "started" | "processing" | "completed" | "error";
71
- type WorkflowStage = "DEV" | "SANDBOX" | "PROD" | "ARCHIVED";
73
+ /** Stage values accepted by the k2 playground API. */
74
+ type AgentStage = "DEVELOPMENT" | "QA" | "PROD";
72
75
  type UserActionType = "PAYMENT_APPROVAL" | "PAYEE_APPROVAL";
73
76
  type UserActionRequest = {
74
77
  userActionId: string;
@@ -87,11 +90,21 @@ type StreamingStep = {
87
90
  id: string;
88
91
  eventType: string;
89
92
  message: string;
90
- status: "in_progress" | "completed" | "error" | "pending";
93
+ status: "in_progress" | "completed" | "error" | "pending" | "skipped";
91
94
  timestamp: number;
92
95
  elapsedMs?: number;
93
96
  thinkingText?: string;
94
97
  isThinking?: boolean;
98
+ /**
99
+ * Pipeline stage key this step was minted for (e.g. "analyzer",
100
+ * "execution"). Only set for steps that originated from a K2
101
+ * STAGE_STARTED event. Used by the STAGE_COMPLETED/FAILED/SKIPPED
102
+ * handlers to find the matching in-progress step by stage key
103
+ * rather than by label — the label can be rewritten mid-run when
104
+ * the server sends a dynamic `message` (e.g. the Analyzer's
105
+ * LLM-generated status), so label-equality matching breaks.
106
+ */
107
+ stage?: string;
95
108
  };
96
109
  type ChunkDisplay = {
97
110
  id?: string;
@@ -118,118 +131,183 @@ type MessageDisplay = {
118
131
  steps?: StreamingStep[];
119
132
  isCancelled?: boolean;
120
133
  currentExecutingStepId?: string;
134
+ /** Result of user action (OTP approval/rejection) */
121
135
  userActionResult?: UserActionResult;
136
+ /** Current thinking block text (live, resets per block) */
122
137
  activeThinkingText?: string;
138
+ /** All thinking accumulated across blocks (for post-stream display) */
123
139
  allThinkingText?: string;
140
+ /** Pre-formatted thinking text built from steps + allThinkingText (v2 streaming format, matches demo) */
124
141
  formattedThinkingText?: string;
142
+ /** True while RAG image URLs are being resolved after the final response is shown */
125
143
  isResolvingImages?: boolean;
126
- /** Elapsed thinking time in seconds, captured at stream completion and persisted. */
127
- thinkingDurationSec?: number;
128
- /** History row loaded via loadSession(). Renderers skip streaming/step UI. */
129
- isHistorical?: boolean;
144
+ /**
145
+ * Server-computed wall-clock duration of the run. Set from the
146
+ * RUN_COMPLETED event's `totalTimeMs`. Authoritative clients
147
+ * should prefer this over deriving an elapsed value from the
148
+ * `steps` timestamp/elapsedMs span.
149
+ */
150
+ totalElapsedMs?: number;
130
151
  };
131
- type SessionOwner = {
132
- /** Sent as sessionOwnerId in the request body. */
152
+ type SessionParams = {
133
153
  id?: string;
134
- /** Sent as sessionOwnerLabel in the request body. */
135
154
  name?: string;
136
- /** Sent as sessionAttributes in the request body. */
137
155
  attributes?: Record<string, string>;
138
156
  };
139
157
  type APIConfig = {
158
+ /** Base API URL */
140
159
  baseUrl: string;
160
+ /** Auth token */
141
161
  authToken?: string;
162
+ /** Custom headers */
142
163
  headers?: Record<string, string>;
143
- /** Default: /api/workflows/ask/stream */
164
+ /** API endpoint for streaming (default: /api/playground/ask/stream) */
144
165
  streamEndpoint?: string;
145
- /** Derived from streamEndpoint when omitted. */
166
+ /** API endpoint for resolving RAG image URLs (default derived from stream endpoint) */
146
167
  resolveImagesEndpoint?: string;
147
- /** Default: "stage". Davis overrides to "workflowStage". */
148
- stageQueryParam?: string;
149
168
  };
150
- type BaseChatConfig = {
169
+ type ChatConfig = {
170
+ /** API configuration - required for the library to make calls */
151
171
  api: APIConfig;
152
- workflow: {
153
- /** Workflow uuid. Required when ui.sessionHistory is enabled. Contributes to the state-scope key. */
154
- id?: string;
155
- name: string;
156
- version?: number;
157
- stage?: WorkflowStage;
158
- };
159
- session?: {
160
- /** Client-side chatStore scoping (not sent to API). Clear on logout. */
161
- userId?: string;
162
- owner?: SessionOwner;
163
- /** Default true. */
164
- autoGenerateId?: boolean;
165
- initialId?: string;
166
- initialMessages?: MessageDisplay[];
167
- };
168
- };
169
- type SessionSummary = {
170
- userId: string;
171
- userLabel: string;
172
- sessionId: string;
173
- workflowId: string;
174
- workflowName: string;
175
- workflowVersion: number;
176
- lastMessageAt: string;
177
- messageCount: number;
178
- sessionTitle: string;
179
- };
180
- type ConversationEntry = {
181
- query: string;
182
- response: string;
183
- userId: string;
184
- userLabel: string;
185
- executionId: string;
186
- createdAt: string;
187
- inputTokens?: number;
188
- outputTokens?: number;
189
- totalTokens?: number;
190
- };
191
- type PageInfo = {
192
- page: number;
193
- size: number;
194
- totalElements: number;
195
- totalPages: number;
196
- first: boolean;
197
- last: boolean;
198
- hasNext: boolean;
199
- hasPrevious: boolean;
200
- };
201
- type SessionListResponse = {
202
- success: boolean;
203
- message: string;
204
- data: SessionSummary[];
205
- pageInfo: PageInfo;
206
- };
207
- type ConversationListResponse = {
208
- success: boolean;
209
- message: string;
210
- data: ConversationEntry[];
211
- pageInfo: PageInfo;
172
+ /** Agent ID to run against the k2 playground endpoint */
173
+ agentId: string;
174
+ /** User ID for chatStore and activeStreamStore — required for context store messages management. Set to undefined on logout to clear stored messages. */
175
+ userId?: string;
176
+ /** Stage/Environment */
177
+ stage?: AgentStage;
178
+ /** Query param name for stage (default: "stage"). */
179
+ stageQueryParam?: string;
180
+ /** Session params */
181
+ sessionParams?: SessionParams;
182
+ /** Custom placeholder text */
183
+ placeholder?: string;
184
+ /** Empty state text */
185
+ emptyStateText?: string;
186
+ /** Show icon in empty state */
187
+ showEmptyStateIcon?: boolean;
188
+ /** Show agent name */
189
+ showAgentName?: boolean;
190
+ /** Agent name */
191
+ agentName?: string;
192
+ /** Show avatars for user and assistant messages */
193
+ showAvatars?: boolean;
194
+ /** Show user avatar only (overrides showAvatars for user messages) */
195
+ showUserAvatar?: boolean;
196
+ /** Show assistant avatar only (overrides showAvatars for assistant messages) */
197
+ showAssistantAvatar?: boolean;
198
+ /** Show execution steps section with "Completed in X.Xs" */
199
+ showExecutionSteps?: boolean;
200
+ /** Show animated dot indicator during streaming */
201
+ showStreamingDot?: boolean;
202
+ /** Custom text format for streaming steps button. Use {count} for step count. Default: "View progress ({count} steps)" */
203
+ streamingStepsText?: string;
204
+ /** Custom text format for completed steps button. Use {count} for step count, {time} for elapsed time. Default: "Completed in {time}s ({count} steps)" */
205
+ completedStepsText?: string;
206
+ /** Input style variant: "rounded" (yaak style) or "flat" (paygent-central style). Default: "rounded" */
207
+ inputStyle?: "rounded" | "flat";
208
+ /** Layout style: "centered" (durango style) or "full-width" (default). Default: "full-width" */
209
+ layout?: "centered" | "full-width";
210
+ /** Show timestamps on messages */
211
+ showTimestamps?: boolean;
212
+ /** Enable animations */
213
+ animated?: boolean;
214
+ /** Disable input */
215
+ disableInput?: boolean;
216
+ /** Has permission to ask */
217
+ hasAskPermission?: boolean;
218
+ /** Auto-generate session ID */
219
+ autoGenerateSessionId?: boolean;
220
+ /** Disable the entire chat and show disabled state */
221
+ isChatDisabled?: boolean;
222
+ /** Custom component to render when chat is disabled. If not provided, default disabled UI will be shown */
223
+ disabledComponent?: React.ReactNode;
224
+ /** Pre-populate the chat with messages (e.g. loaded conversation history) */
225
+ initialMessages?: MessageDisplay[];
226
+ /** Resume an existing session by providing its ID */
227
+ initialSessionId?: string;
212
228
  };
213
229
  type ChatCallbacks = {
230
+ /** Called when a message is sent (before API call) */
214
231
  onMessageSent?: (message: string) => void;
232
+ /** Called when streaming starts */
215
233
  onStreamStart?: () => void;
234
+ /** Called when streaming completes */
216
235
  onStreamComplete?: (message: MessageDisplay) => void;
236
+ /** Called when an error occurs */
217
237
  onError?: (error: Error) => void;
238
+ /** Called when execution trace is clicked - provides data instead of UI */
218
239
  onExecutionTraceClick?: (data: {
219
240
  message: MessageDisplay;
220
241
  tracingData?: unknown;
221
242
  executionId?: string;
222
243
  }) => void;
244
+ /** Called when session ID changes */
223
245
  onSessionIdChange?: (sessionId: string) => void;
246
+ /** Called when a user action (e.g. OTP) is required */
224
247
  onUserActionRequired?: (request: UserActionRequest) => void;
248
+ /** Called on user action events (SUCCESS, INVALID, EXPIRED, REJECTED, RESENT, FAILED) */
225
249
  onUserActionEvent?: (eventType: string, message: string) => void;
250
+ /**
251
+ * Fires whenever the current streaming "status message" changes —
252
+ * the user-facing label for whatever stage is running right now
253
+ * (e.g. "Understanding your request…", "Pulling those up for you
254
+ * now.", "Executing…"). Consumers can use this to surface the
255
+ * status somewhere outside the chat bubble (e.g. a pipeline
256
+ * sidebar, an agent-avatar label).
257
+ *
258
+ * Called with `null` when no run is in flight — use that as the
259
+ * signal to revert any UI you had tied to the status.
260
+ */
261
+ onStatusMessage?: (message: string | null) => void;
262
+ /**
263
+ * Fires on every streaming event that updates the steps array —
264
+ * i.e. whenever a pipeline stage starts, completes, fails, or is
265
+ * skipped. Gives the host app the full steps snapshot so it can
266
+ * derive per-stage status (idle / running / completed / error)
267
+ * for UIs like a pipeline sidebar that animates stage progression.
268
+ *
269
+ * Each [StreamingStep] carries a `stage` field with the pipeline
270
+ * stage key (e.g. "sanitizer", "analyzer", "planner", "execution",
271
+ * "formatter") and a `status` field ("in_progress", "completed",
272
+ * "error"). The host derives the visual state by scanning the
273
+ * array — no reverse label-to-stage mapping required.
274
+ *
275
+ * Called with an empty array (`[]`) when the run ends so the host
276
+ * can reset all stages back to idle.
277
+ */
278
+ onStepsUpdate?: (steps: StreamingStep[]) => void;
226
279
  };
227
280
 
281
+ /**
282
+ * Latency-vs-precision toggle surfaced in the chat widget. "fast"
283
+ * (default) lets the server cap list-tool fetches and answer
284
+ * quickly; "deep" runs a full analytical pass. The value is
285
+ * forwarded verbatim to the server, which normalizes it — any
286
+ * other string collapses to "fast" server-side. See
287
+ * `ExecutionRequest.analysisMode` on the k2 backend for the
288
+ * authoritative semantics.
289
+ */
290
+ type AnalysisMode = "fast" | "deep";
291
+
292
+ type SendMessageOptions = {
293
+ /**
294
+ * Latency-vs-precision toggle surfaced in the chat widget.
295
+ * `"fast"` (default) — the server caps list-tool fetches and
296
+ * returns a quick, directionally correct answer with a sampling
297
+ * caveat. `"deep"` — the server runs a full analytical pass,
298
+ * no row caps, full rankings.
299
+ *
300
+ * Undefined / omitted means "don't set — let the server use its
301
+ * default", which is `"fast"` today. Callers that want explicit
302
+ * control should always pass this; callers that don't care can
303
+ * skip it and inherit the server default.
304
+ */
305
+ analysisMode?: AnalysisMode;
306
+ };
228
307
  type UseChatV2Return = {
229
308
  messages: MessageDisplay[];
230
- sendMessage: (userMessage: string) => Promise<void>;
309
+ sendMessage: (userMessage: string, options?: SendMessageOptions) => Promise<void>;
231
310
  clearMessages: () => void;
232
- /** Prepend older messages (e.g. loaded from history pagination). */
233
311
  prependMessages: (messages: MessageDisplay[]) => void;
234
312
  cancelStream: () => void;
235
313
  resetSession: () => void;
@@ -241,20 +319,8 @@ type UseChatV2Return = {
241
319
  approveUserAction: (otp: string) => Promise<void>;
242
320
  rejectUserAction: () => Promise<void>;
243
321
  resendOtp: () => Promise<void>;
244
- /**
245
- * Replace the active chat with a prior session's conversation history.
246
- * Cancels any in-flight stream, clears current messages, fetches page 0 of
247
- * conversations for `sessionId`, and renders them as historical rows.
248
- */
249
- loadSession: (sessionId: string) => Promise<void>;
250
- /**
251
- * The session id whose conversation history is currently being fetched
252
- * via `loadSession`. `undefined` while idle. Use to render an activity
253
- * indicator in the messages area / on the matching sidebar row.
254
- */
255
- loadingSessionId: string | undefined;
256
322
  };
257
- declare function useChatV2(config: BaseChatConfig, callbacks?: ChatCallbacks): UseChatV2Return;
323
+ declare function useChatV2(config: ChatConfig, callbacks?: ChatCallbacks): UseChatV2Return;
258
324
 
259
325
  interface SpeechRecognitionEvent extends Event {
260
326
  results: SpeechRecognitionResultList;
@@ -308,6 +374,33 @@ type StreamEvent = {
308
374
  inputTokens?: number;
309
375
  outputTokens?: number;
310
376
  elapsedMs?: number;
377
+ /**
378
+ * Server-computed wall-clock duration from RunStarted to RunCompleted.
379
+ * Carried on RUN_COMPLETED only — prefer this over client-side
380
+ * step-span heuristics when present.
381
+ */
382
+ totalTimeMs?: number;
383
+ /**
384
+ * User-facing progress label. Attached to:
385
+ * - TOOL_CALL_STARTED / TOOL_CALL_COMPLETED — derived from the tool
386
+ * name and (on completion) the row-count of the result, e.g.
387
+ * "Pulling your transactions" / "Got 437 transactions".
388
+ * - LLM_CALL_STARTED — an in-voice "what's about to happen" line.
389
+ * - KEEP_ALIVE — a rotating phrase the server sends during silent-
390
+ * think gaps so the chat-bubble status changes every few seconds
391
+ * instead of staying frozen on "Thinking…".
392
+ *
393
+ * Clients should prefer this over raw type identifiers when
394
+ * rendering a progress row.
395
+ */
396
+ description?: string;
397
+ /**
398
+ * Carried on `THINKING_DELTA` events — Anthropic extended-thinking
399
+ * content streamed live from the upstream model. Distinct from
400
+ * `partialText` (the user-facing answer); routes into a separate
401
+ * "Thinking…" panel rather than the chat bubble.
402
+ */
403
+ text?: string;
311
404
  userActionRequest?: {
312
405
  userActionId: string;
313
406
  userActionType?: string;
@@ -339,11 +432,6 @@ declare function streamWorkflowEvents(url: string, body: Record<string, unknown>
339
432
  */
340
433
  declare function buildFormattedThinking(steps: StreamingStep[] | undefined, allThinkingText: string): string;
341
434
 
342
- /**
343
- * Orchestrator completion often includes "Identified N task(s) to execute", which is redundant in the UI.
344
- */
345
- declare function workingPhaseDetailForDisplay(raw: string): string;
346
-
347
435
  type V2EventProcessorState = {
348
436
  formattedThinkingText: string;
349
437
  finalResponse: string;
@@ -360,9 +448,11 @@ type V2EventProcessorState = {
360
448
  steps: StreamingStep[];
361
449
  stepCounter: number;
362
450
  currentExecutingStepId?: string;
451
+ /** Server-computed wall-clock duration captured from RUN_COMPLETED's `totalTimeMs`. */
452
+ totalElapsedMs?: number;
363
453
  };
364
454
  declare function createInitialV2State(): V2EventProcessorState;
365
- declare function processStreamEventV2(event: StreamEvent, state: V2EventProcessorState): V2EventProcessorState;
455
+ declare function processStreamEventV2(rawEvent: StreamEvent, state: V2EventProcessorState): V2EventProcessorState;
366
456
 
367
457
  type UserActionResponse = {
368
458
  success: boolean;
@@ -371,62 +461,14 @@ type UserActionResponse = {
371
461
  /**
372
462
  * Submit a user action (e.g. OTP verification)
373
463
  */
374
- declare function submitUserAction(config: BaseChatConfig, userActionId: string, data?: Record<string, unknown>): Promise<UserActionResponse>;
464
+ declare function submitUserAction(config: ChatConfig, userActionId: string, data?: Record<string, unknown>): Promise<UserActionResponse>;
375
465
  /**
376
466
  * Cancel / reject a user action
377
467
  */
378
- declare function cancelUserAction(config: BaseChatConfig, userActionId: string): Promise<UserActionResponse>;
468
+ declare function cancelUserAction(config: ChatConfig, userActionId: string): Promise<UserActionResponse>;
379
469
  /**
380
470
  * Resend a user action (e.g. request a new OTP)
381
471
  */
382
- declare function resendUserAction(config: BaseChatConfig, userActionId: string): Promise<UserActionResponse>;
383
-
384
- type ListSessionsOptions = {
385
- page?: number;
386
- size?: number;
387
- signal?: AbortSignal;
388
- };
389
- type ListConversationsOptions = {
390
- sessionId: string;
391
- page?: number;
392
- size?: number;
393
- signal?: AbortSignal;
394
- };
395
- /**
396
- * List the recent sessions for the current `session.owner.id` within a workflow.
397
- *
398
- * Two variants, selected by auth mode:
399
- *
400
- * 1. Authenticated user (api.authToken present, or any auth mode that isn't
401
- * yaak-api-key playground):
402
- * GET {baseUrl}/api/workflow-users/{ownerId}/sessions
403
- * ?workflowId={workflow.id}&{stageParam}={stage}&page=&size=
404
- *
405
- * 2. Playground / yaak-api-key (no authToken, yaak-api-key header present):
406
- * GET {baseUrl}/api/workflows/ask/sessions
407
- * ?workflowUserId={ownerId}&workflowName={workflow.name}&{stageParam}={stage}&page=&size=
408
- */
409
- declare function listSessions(config: BaseChatConfig, opts?: ListSessionsOptions): Promise<SessionListResponse>;
410
- /**
411
- * List the conversation history for a single session.
412
- *
413
- * Two variants, selected by auth mode (mirrors `listSessions`):
414
- *
415
- * 1. Authenticated user (api.authToken present, or no yaak-api-key header):
416
- * GET {baseUrl}/api/workflow-users/{ownerId}/conversations
417
- * ?sessionId={sessionId}&{stageParam}={stage}&page=&size=
418
- *
419
- * 2. Playground / yaak-api-key (no authToken, x-yaak-api-key header present):
420
- * GET {baseUrl}/api/workflows/ask/conversations
421
- * ?workflowUserId={ownerId}&workflowName={workflow.name}&sessionId={sessionId}
422
- * &{stageParam}={stage}&page=&size=
423
- */
424
- declare function listConversations(config: BaseChatConfig, opts: ListConversationsOptions): Promise<ConversationListResponse>;
425
-
426
- /**
427
- * Composite scope key for chatStore / activeStreamStore.
428
- * Same (userId, workflow id, version, stage) → same state across unmount/remount.
429
- */
430
- declare function buildScopeKey(config: BaseChatConfig): string;
472
+ declare function resendUserAction(config: ChatConfig, userActionId: string): Promise<UserActionResponse>;
431
473
 
432
- export { type APIConfig, type BaseChatConfig, type ChatCallbacks, type ChunkDisplay, type ConversationEntry, type ConversationListResponse, type MessageDisplay, type MessageRole, type PageInfo, type SessionListResponse, type SessionOwner, type SessionSummary, type StreamEvent, type StreamOptions, type StreamProgress, type StreamingStep, type UseChatV2Return, type UseVoiceReturn, type UserActionRequest, type UserActionResult, type UserActionState, type UserActionType, type V2EventProcessorState, type VoiceCallbacks, type VoiceConfig, type VoicePermissions, type VoiceResult, type VoiceState, type WorkflowStage, buildFormattedThinking, buildScopeKey, cancelUserAction, createInitialV2State, generateId, listConversations, listSessions, processStreamEventV2, resendUserAction, streamWorkflowEvents, submitUserAction, useChatV2, useVoice, workingPhaseDetailForDisplay };
474
+ export { type APIConfig, type AgentStage, type AnalysisMode, type ChatCallbacks, type ChatConfig, type ChunkDisplay, type MessageDisplay, type MessageRole, type SendMessageOptions, type SessionParams, type StreamEvent, type StreamOptions, type StreamProgress, type StreamingStep, type UseChatV2Return, type UseVoiceReturn, type UserActionRequest, type UserActionResult, type UserActionState, type UserActionType, type V2EventProcessorState, type VoiceCallbacks, type VoiceConfig, type VoicePermissions, type VoiceResult, type VoiceState, buildFormattedThinking, cancelUserAction, createInitialV2State, generateId, processStreamEventV2, resendUserAction, streamWorkflowEvents, submitUserAction, useChatV2, useVoice };