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