@paymanai/payman-typescript-ask-sdk 4.0.26 → 4.0.28

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.js CHANGED
@@ -1148,6 +1148,9 @@ function isUserActionExpired(prompt) {
1148
1148
 
1149
1149
  // src/hooks/useChatV2.ts
1150
1150
  var EMPTY_USER_ACTION_STATE2 = { prompts: [], notifications: [] };
1151
+ function promptSlotKey(p) {
1152
+ return p.toolCallId || p.userActionId;
1153
+ }
1151
1154
  function upsertPrompt(prompts, req) {
1152
1155
  const idx = prompts.findIndex(
1153
1156
  (p) => req.toolCallId ? p.toolCallId === req.toolCallId : p.userActionId === req.userActionId
@@ -1194,6 +1197,7 @@ function useChatV2(config, callbacks = {}) {
1194
1197
  configRef.current = config;
1195
1198
  const messagesRef = react.useRef(messages);
1196
1199
  messagesRef.current = messages;
1200
+ const pendingSubmissionsRef = react.useRef(/* @__PURE__ */ new Map());
1197
1201
  const storeAwareSetMessages = react.useCallback(
1198
1202
  (updater) => {
1199
1203
  const streamUserId = streamUserIdRef.current;
@@ -1228,6 +1232,8 @@ function useChatV2(config, callbacks = {}) {
1228
1232
  if (!config.userId) return EMPTY_USER_ACTION_STATE2;
1229
1233
  return activeStreamStore.get(config.userId)?.userActionState ?? EMPTY_USER_ACTION_STATE2;
1230
1234
  });
1235
+ const userActionStateRef = react.useRef(userActionState);
1236
+ userActionStateRef.current = userActionState;
1231
1237
  const storeAwareSetUserActionState = react.useCallback(
1232
1238
  (updater) => {
1233
1239
  const streamUserId = streamUserIdRef.current;
@@ -1255,6 +1261,12 @@ function useChatV2(config, callbacks = {}) {
1255
1261
  onExecutionTraceClick: (data) => callbacksRef.current.onExecutionTraceClick?.(data),
1256
1262
  onSessionIdChange: (sessionId) => callbacksRef.current.onSessionIdChange?.(sessionId),
1257
1263
  onUserActionRequired: (request) => {
1264
+ const requestSlotKey = promptSlotKey(request);
1265
+ for (const [pendingId, slotKey] of pendingSubmissionsRef.current) {
1266
+ if (slotKey === requestSlotKey) {
1267
+ pendingSubmissionsRef.current.delete(pendingId);
1268
+ }
1269
+ }
1258
1270
  storeAwareSetUserActionState((prev) => ({
1259
1271
  ...prev,
1260
1272
  prompts: upsertPrompt(prev.prompts, request)
@@ -1266,6 +1278,28 @@ function useChatV2(config, callbacks = {}) {
1266
1278
  (prev) => prev.notifications.some((n) => n.id === notification.id) ? prev : { ...prev, notifications: [...prev.notifications, notification] }
1267
1279
  );
1268
1280
  callbacksRef.current.onUserNotification?.(notification);
1281
+ },
1282
+ // A submitted-but-unconfirmed prompt (see `submitUserAction`) is only
1283
+ // safe to drop once the stream has demonstrably moved on. `onEvent`
1284
+ // in useStreamManagerV2 calls `onStepsUpdate` for *every* processed
1285
+ // stream event, unconditionally — so the first time this fires
1286
+ // after a submission, the event in hand is either the rejection
1287
+ // retry (a fresh `USER_ACTION_REQUIRED`, which the handler above
1288
+ // already deleted this pending entry for, earlier in the very same
1289
+ // event) or genuine forward progress (RUN_IN_PROGRESS, a tool call,
1290
+ // content deltas, RUN_COMPLETED, ...). Anything still pending by
1291
+ // the time we get here therefore means the run resumed normally —
1292
+ // clear it.
1293
+ onStepsUpdate: (steps) => {
1294
+ if (pendingSubmissionsRef.current.size > 0) {
1295
+ const resolved = [...pendingSubmissionsRef.current.keys()];
1296
+ pendingSubmissionsRef.current.clear();
1297
+ storeAwareSetUserActionState((prev) => ({
1298
+ ...prev,
1299
+ prompts: prev.prompts.filter((p) => !resolved.includes(p.userActionId))
1300
+ }));
1301
+ }
1302
+ callbacksRef.current.onStepsUpdate?.(steps);
1269
1303
  }
1270
1304
  // eslint-disable-next-line react-hooks/exhaustive-deps
1271
1305
  }), []);
@@ -1401,6 +1435,7 @@ function useChatV2(config, callbacks = {}) {
1401
1435
  [storeAwareSetUserActionState]
1402
1436
  );
1403
1437
  const removePrompt = react.useCallback((userActionId) => {
1438
+ pendingSubmissionsRef.current.delete(userActionId);
1404
1439
  storeAwareSetUserActionState((prev) => ({
1405
1440
  ...prev,
1406
1441
  prompts: prev.prompts.filter((p) => p.userActionId !== userActionId)
@@ -1411,7 +1446,10 @@ function useChatV2(config, callbacks = {}) {
1411
1446
  setPromptStatus(userActionId, "submitting");
1412
1447
  try {
1413
1448
  await submitUserAction(configRef.current, userActionId, content);
1414
- removePrompt(userActionId);
1449
+ const prompt = userActionStateRef.current.prompts.find(
1450
+ (p) => p.userActionId === userActionId
1451
+ );
1452
+ pendingSubmissionsRef.current.set(userActionId, prompt ? promptSlotKey(prompt) : userActionId);
1415
1453
  } catch (error) {
1416
1454
  if (error instanceof UserActionStaleError) {
1417
1455
  setPromptStatus(userActionId, "stale");
@@ -1422,7 +1460,7 @@ function useChatV2(config, callbacks = {}) {
1422
1460
  throw error;
1423
1461
  }
1424
1462
  },
1425
- [removePrompt, setPromptStatus]
1463
+ [setPromptStatus]
1426
1464
  );
1427
1465
  const cancelUserAction2 = react.useCallback(
1428
1466
  async (userActionId) => {
@@ -1776,6 +1814,284 @@ function useVoice(config = {}, callbacks = {}) {
1776
1814
  reset
1777
1815
  };
1778
1816
  }
1817
+ var DEFAULT_PAGE_SIZE = 20;
1818
+ var DEFAULT_MESSAGES_PAGE_SIZE = 100;
1819
+ function defaultParseSessions(json) {
1820
+ const body = json;
1821
+ const rows = Array.isArray(body?.data) ? body.data : [];
1822
+ const data = rows.map((row) => ({ ...row, title: row.title ?? row.sessionTitle ?? null }));
1823
+ return { data, total: body?.total };
1824
+ }
1825
+ function defaultParseMessages(json) {
1826
+ const body = json;
1827
+ return { data: Array.isArray(body?.data) ? body.data : [] };
1828
+ }
1829
+ function withQuery(path, params) {
1830
+ const qs = Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
1831
+ if (!qs) return path;
1832
+ return `${path}${path.includes("?") ? "&" : "?"}${qs}`;
1833
+ }
1834
+ function toFeedbackState(feedback) {
1835
+ const value = feedback?.feedback;
1836
+ if (!value) return null;
1837
+ return value === "POSITIVE" ? "up" : "down";
1838
+ }
1839
+ function toMessageDisplay(rows, sessionId) {
1840
+ return rows.flatMap((row) => {
1841
+ const timestamp = row.startTime || row.endTime || (/* @__PURE__ */ new Date()).toISOString();
1842
+ const out = [
1843
+ {
1844
+ id: `${row.id}:user`,
1845
+ sessionId,
1846
+ role: "user",
1847
+ content: row.sessionUserIntent,
1848
+ timestamp
1849
+ }
1850
+ ];
1851
+ if (row.agentResponse) {
1852
+ out.push({
1853
+ id: `${row.id}:assistant`,
1854
+ sessionId,
1855
+ role: "assistant",
1856
+ content: row.agentResponse,
1857
+ timestamp: row.endTime || timestamp,
1858
+ executionId: row.id,
1859
+ isError: row.status === "FAILED",
1860
+ feedback: toFeedbackState(row.feedback)
1861
+ });
1862
+ }
1863
+ return out;
1864
+ });
1865
+ }
1866
+ function useChatSessions({
1867
+ api,
1868
+ sessions,
1869
+ initialSessionId
1870
+ }) {
1871
+ const enabled = sessions?.enabled === true;
1872
+ const listEndpoint = sessions?.listEndpoint ?? "/api/conversations/sessions";
1873
+ const messagesEndpointTemplate = sessions?.messagesEndpoint ?? "/api/conversations/sessions/{sessionId}/messages";
1874
+ const pageSize = sessions?.pageSize ?? DEFAULT_PAGE_SIZE;
1875
+ const messagesPageSize = sessions?.messagesPageSize ?? DEFAULT_MESSAGES_PAGE_SIZE;
1876
+ const parseSessionsResponse = sessions?.parseSessionsResponse ?? defaultParseSessions;
1877
+ const parseMessagesResponse = sessions?.parseMessagesResponse ?? defaultParseMessages;
1878
+ const [sessionsList, setSessionsList] = react.useState([]);
1879
+ const [isLoadingList, setIsLoadingList] = react.useState(enabled);
1880
+ const [isLoadingMore, setIsLoadingMore] = react.useState(false);
1881
+ const [listError, setListError] = react.useState(null);
1882
+ const hasLoadedOnceRef = react.useRef(false);
1883
+ const [page, setPage] = react.useState(0);
1884
+ const [total, setTotal] = react.useState(null);
1885
+ const [lastPageFull, setLastPageFull] = react.useState(false);
1886
+ const [selectedSessionId, setSelectedSessionId] = react.useState(
1887
+ initialSessionId ?? null
1888
+ );
1889
+ const [draftSessionId, setDraftSessionId] = react.useState(generateId);
1890
+ const [selectedMessages, setSelectedMessages] = react.useState([]);
1891
+ const [isLoadingMessages, setIsLoadingMessages] = react.useState(
1892
+ enabled && initialSessionId != null
1893
+ );
1894
+ const [messagesError, setMessagesError] = react.useState(null);
1895
+ const [refetchTick, setRefetchTick] = react.useState(0);
1896
+ const baseUrl = (api.baseUrl || "").replace(/\/+$/, "");
1897
+ const apiHeaders = api.headers;
1898
+ const authToken = api.authToken;
1899
+ const headersKey = JSON.stringify(apiHeaders ?? {});
1900
+ const requestHeaders = react.useMemo(() => {
1901
+ const headers = { Accept: "application/json", ...apiHeaders ?? {} };
1902
+ if (authToken && !headers.Authorization) headers.Authorization = `Bearer ${authToken}`;
1903
+ return headers;
1904
+ }, [headersKey, authToken]);
1905
+ const hasMore = total != null ? sessionsList.length < total : lastPageFull;
1906
+ react.useEffect(() => {
1907
+ setPage(0);
1908
+ hasLoadedOnceRef.current = false;
1909
+ }, [enabled, baseUrl, listEndpoint, pageSize, requestHeaders]);
1910
+ react.useEffect(() => {
1911
+ setPage(0);
1912
+ }, [refetchTick]);
1913
+ react.useEffect(() => {
1914
+ if (!enabled) return;
1915
+ const ctrl = new AbortController();
1916
+ const isFirstPage = page === 0;
1917
+ if (isFirstPage && !hasLoadedOnceRef.current) setIsLoadingList(true);
1918
+ else if (!isFirstPage) setIsLoadingMore(true);
1919
+ setListError(null);
1920
+ fetch(withQuery(`${baseUrl}${listEndpoint}`, { page, limit: pageSize }), {
1921
+ method: "GET",
1922
+ headers: requestHeaders,
1923
+ signal: ctrl.signal
1924
+ }).then(async (res) => {
1925
+ if (!res.ok) throw new Error(`Failed to load chats (${res.status})`);
1926
+ return res.json();
1927
+ }).then((json) => {
1928
+ const parsed = parseSessionsResponse(json);
1929
+ setSessionsList((prev) => isFirstPage ? parsed.data : [...prev, ...parsed.data]);
1930
+ setTotal(parsed.total ?? null);
1931
+ setLastPageFull(parsed.data.length >= pageSize);
1932
+ hasLoadedOnceRef.current = true;
1933
+ }).catch((e) => {
1934
+ if (e.name === "AbortError") return;
1935
+ setListError(e instanceof Error ? e.message : "Failed to load chats");
1936
+ }).finally(() => {
1937
+ setIsLoadingList(false);
1938
+ setIsLoadingMore(false);
1939
+ });
1940
+ return () => ctrl.abort();
1941
+ }, [enabled, baseUrl, listEndpoint, pageSize, requestHeaders, refetchTick, page]);
1942
+ react.useEffect(() => {
1943
+ if (!enabled || !selectedSessionId) {
1944
+ setSelectedMessages([]);
1945
+ return;
1946
+ }
1947
+ const ctrl = new AbortController();
1948
+ setIsLoadingMessages(true);
1949
+ setMessagesError(null);
1950
+ const path = messagesEndpointTemplate.replace(
1951
+ "{sessionId}",
1952
+ encodeURIComponent(selectedSessionId)
1953
+ );
1954
+ fetch(withQuery(`${baseUrl}${path}`, { limit: messagesPageSize }), {
1955
+ method: "GET",
1956
+ headers: requestHeaders,
1957
+ signal: ctrl.signal
1958
+ }).then(async (res) => {
1959
+ if (!res.ok) throw new Error(`Failed to load messages (${res.status})`);
1960
+ return res.json();
1961
+ }).then(
1962
+ (json) => setSelectedMessages(
1963
+ toMessageDisplay(parseMessagesResponse(json).data, selectedSessionId)
1964
+ )
1965
+ ).catch((e) => {
1966
+ if (e.name === "AbortError") return;
1967
+ setMessagesError(e instanceof Error ? e.message : "Failed to load messages");
1968
+ setSelectedMessages([]);
1969
+ }).finally(() => setIsLoadingMessages(false));
1970
+ return () => ctrl.abort();
1971
+ }, [enabled, selectedSessionId, baseUrl, messagesEndpointTemplate, messagesPageSize, requestHeaders]);
1972
+ const loadMore = react.useCallback(() => {
1973
+ setPage((prev) => {
1974
+ if (isLoadingList || isLoadingMore || !hasMore) return prev;
1975
+ return prev + 1;
1976
+ });
1977
+ }, [isLoadingList, isLoadingMore, hasMore]);
1978
+ const selectSession = react.useCallback((sessionId) => {
1979
+ setSelectedSessionId(sessionId);
1980
+ setSelectedMessages([]);
1981
+ }, []);
1982
+ const startNewSession = react.useCallback(() => {
1983
+ setSelectedSessionId(null);
1984
+ setDraftSessionId(generateId());
1985
+ setSelectedMessages([]);
1986
+ }, []);
1987
+ const refetch = react.useCallback(() => setRefetchTick((tick) => tick + 1), []);
1988
+ const noteSentMessage = react.useCallback(
1989
+ (text) => {
1990
+ const id = selectedSessionId ?? draftSessionId;
1991
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1992
+ const trimmed = text.trim();
1993
+ setSessionsList((prev) => {
1994
+ const idx = prev.findIndex((s) => s.sessionId === id);
1995
+ if (idx >= 0) {
1996
+ const existing = prev[idx];
1997
+ const bumped = {
1998
+ ...existing,
1999
+ lastMessageAt: now,
2000
+ messageCount: (existing.messageCount ?? 0) + 1,
2001
+ title: existing.title?.trim() ? existing.title : trimmed
2002
+ };
2003
+ return [bumped, ...prev.slice(0, idx), ...prev.slice(idx + 1)];
2004
+ }
2005
+ const fresh = {
2006
+ sessionId: id,
2007
+ title: trimmed,
2008
+ messageCount: 1,
2009
+ lastMessageAt: now,
2010
+ status: "PROCESSING"
2011
+ };
2012
+ return [fresh, ...prev];
2013
+ });
2014
+ },
2015
+ [selectedSessionId, draftSessionId]
2016
+ );
2017
+ return {
2018
+ enabled,
2019
+ sessionsList,
2020
+ isLoadingList,
2021
+ listError,
2022
+ total,
2023
+ hasMore,
2024
+ isLoadingMore,
2025
+ loadMore,
2026
+ noteSentMessage,
2027
+ selectedSessionId,
2028
+ activeSessionId: selectedSessionId ?? draftSessionId,
2029
+ selectSession,
2030
+ startNewSession,
2031
+ selectedMessages,
2032
+ isLoadingMessages,
2033
+ messagesError,
2034
+ refetch
2035
+ };
2036
+ }
2037
+ function deriveStatus(enabled, blocked) {
2038
+ if (blocked === true) return "blocked";
2039
+ if (enabled === false) return "disabled";
2040
+ if (enabled === true) return "available";
2041
+ return "unknown";
2042
+ }
2043
+ function defaultParse(json) {
2044
+ const body = json;
2045
+ return {
2046
+ available: body?.enabled === true && body?.blocked !== true,
2047
+ status: deriveStatus(body?.enabled, body?.blocked),
2048
+ config: body ?? void 0
2049
+ };
2050
+ }
2051
+ function useAgentConfig({ api, availability }) {
2052
+ const enabled = availability?.enabled === true;
2053
+ const endpoint = availability?.endpoint ?? "/api/agent/config";
2054
+ const parseResponse = availability?.parseResponse ?? defaultParse;
2055
+ const [available, setAvailable] = react.useState(null);
2056
+ const [status, setStatus] = react.useState("unknown");
2057
+ const [config, setConfig] = react.useState(void 0);
2058
+ const [isLoading, setIsLoading] = react.useState(enabled);
2059
+ const [error, setError] = react.useState(null);
2060
+ const [refetchTick, setRefetchTick] = react.useState(0);
2061
+ const baseUrl = (api.baseUrl || "").replace(/\/+$/, "");
2062
+ const apiHeaders = api.headers;
2063
+ const authToken = api.authToken;
2064
+ const requestHeaders = react.useMemo(() => {
2065
+ const headers = { Accept: "application/json", ...apiHeaders ?? {} };
2066
+ if (authToken && !headers.Authorization) headers.Authorization = `Bearer ${authToken}`;
2067
+ return headers;
2068
+ }, [apiHeaders, authToken]);
2069
+ react.useEffect(() => {
2070
+ if (!enabled) return;
2071
+ const ctrl = new AbortController();
2072
+ setIsLoading(true);
2073
+ setError(null);
2074
+ fetch(`${baseUrl}${endpoint}`, {
2075
+ method: "GET",
2076
+ headers: requestHeaders,
2077
+ signal: ctrl.signal
2078
+ }).then(async (res) => {
2079
+ if (!res.ok) throw new Error(`Failed to check availability (${res.status})`);
2080
+ return res.json();
2081
+ }).then((json) => {
2082
+ const parsed = parseResponse(json);
2083
+ setAvailable(parsed.available);
2084
+ setStatus(parsed.status ?? deriveStatus(parsed.available, void 0));
2085
+ setConfig(parsed.config);
2086
+ }).catch((e) => {
2087
+ if (e.name === "AbortError") return;
2088
+ setError(e instanceof Error ? e.message : "Failed to check availability");
2089
+ }).finally(() => setIsLoading(false));
2090
+ return () => ctrl.abort();
2091
+ }, [enabled, baseUrl, endpoint, requestHeaders, refetchTick]);
2092
+ const refetch = react.useCallback(() => setRefetchTick((tick) => tick + 1), []);
2093
+ return { enabled, available, status, config, isLoading, error, refetch };
2094
+ }
1779
2095
 
1780
2096
  // src/utils/jsonSchemaForm.ts
1781
2097
  function classifyField(field) {
@@ -1922,6 +2238,8 @@ exports.resendUserAction = resendUserAction;
1922
2238
  exports.resolveUserActionExpiresAt = resolveUserActionExpiresAt;
1923
2239
  exports.streamWorkflowEvents = streamWorkflowEvents;
1924
2240
  exports.submitUserAction = submitUserAction;
2241
+ exports.useAgentConfig = useAgentConfig;
2242
+ exports.useChatSessions = useChatSessions;
1925
2243
  exports.useChatV2 = useChatV2;
1926
2244
  exports.useVoice = useVoice;
1927
2245
  exports.validateField = validateField;