@distri/core 0.2.8 → 0.3.1

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
@@ -860,29 +860,21 @@ var _DistriClient = class _DistriClient {
860
860
  this.tokenRefreshSkewMs = config.tokenRefreshSkewMs ?? 6e4;
861
861
  this.onTokenRefresh = config.onTokenRefresh;
862
862
  this.config = {
863
- baseUrl: config.baseUrl?.replace(/\/$/, "") || DEFAULT_BASE_URL,
863
+ baseUrl: config.baseUrl.replace(/\/$/, ""),
864
864
  apiVersion: config.apiVersion || "v1",
865
- timeout: config.timeout ?? 3e4,
866
- retryAttempts: config.retryAttempts ?? 3,
867
- retryDelay: config.retryDelay ?? 1e3,
868
- debug: config.debug ?? false,
865
+ timeout: config.timeout || 3e4,
866
+ retryAttempts: config.retryAttempts || 3,
867
+ retryDelay: config.retryDelay || 1e3,
868
+ debug: config.debug || false,
869
869
  headers,
870
- interceptor: config.interceptor ?? (async (init) => Promise.resolve(init)),
871
- onTokenRefresh: config.onTokenRefresh,
872
- clientId: config.clientId
870
+ interceptor: config.interceptor || ((init) => Promise.resolve(init))
873
871
  };
874
- }
875
- /**
876
- * Get the configured client ID.
877
- */
878
- get clientId() {
879
- return this.config.clientId;
880
- }
881
- /**
882
- * Set the client ID for embed token issuance.
883
- */
884
- set clientId(value) {
885
- this.config.clientId = value;
872
+ this.debug("DistriClient initialized with config:", {
873
+ baseUrl: this.config.baseUrl,
874
+ hasAccessToken: !!this.accessToken,
875
+ hasRefreshToken: !!this.refreshToken,
876
+ timeout: this.config.timeout
877
+ });
886
878
  }
887
879
  /**
888
880
  * Create a client with default cloud configuration.
@@ -915,7 +907,7 @@ var _DistriClient = class _DistriClient {
915
907
  if (expiry) {
916
908
  body.expiry = typeof expiry === "string" ? expiry : expiry.toISOString();
917
909
  }
918
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values`, {
910
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values`, {
919
911
  method: "POST",
920
912
  headers: {
921
913
  "Content-Type": "application/json",
@@ -932,7 +924,7 @@ var _DistriClient = class _DistriClient {
932
924
  * Session store: get a single value
933
925
  */
934
926
  async getSessionValue(sessionId, key) {
935
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
927
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
936
928
  method: "GET",
937
929
  headers: {
938
930
  ...this.config.headers
@@ -949,7 +941,7 @@ var _DistriClient = class _DistriClient {
949
941
  * Session store: get all values in a session
950
942
  */
951
943
  async getSessionValues(sessionId) {
952
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values`, {
944
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values`, {
953
945
  method: "GET",
954
946
  headers: {
955
947
  ...this.config.headers
@@ -966,7 +958,7 @@ var _DistriClient = class _DistriClient {
966
958
  * Session store: delete a single key
967
959
  */
968
960
  async deleteSessionValue(sessionId, key) {
969
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
961
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
970
962
  method: "DELETE",
971
963
  headers: {
972
964
  ...this.config.headers
@@ -981,7 +973,7 @@ var _DistriClient = class _DistriClient {
981
973
  * Session store: clear all keys in a session
982
974
  */
983
975
  async clearSession(sessionId) {
984
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}`, {
976
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}`, {
985
977
  method: "DELETE",
986
978
  headers: {
987
979
  ...this.config.headers
@@ -992,6 +984,30 @@ var _DistriClient = class _DistriClient {
992
984
  throw new ApiError(errorData.error || "Failed to clear session", resp.status);
993
985
  }
994
986
  }
987
+ /**
988
+ * Set additional user message parts for the next agent iteration.
989
+ * These parts will be appended to the user message in the prompt.
990
+ * @param sessionId - The thread/session ID
991
+ * @param parts - Array of DistriPart objects to append to user message
992
+ */
993
+ async setAdditionalUserParts(sessionId, parts) {
994
+ await this.setSessionValue(sessionId, _DistriClient.ADDITIONAL_PARTS_KEY, parts);
995
+ }
996
+ /**
997
+ * Get the current additional user message parts.
998
+ * @param sessionId - The thread/session ID
999
+ * @returns Array of DistriPart objects or null if not set
1000
+ */
1001
+ async getAdditionalUserParts(sessionId) {
1002
+ return this.getSessionValue(sessionId, _DistriClient.ADDITIONAL_PARTS_KEY);
1003
+ }
1004
+ /**
1005
+ * Clear/delete the additional user message parts.
1006
+ * @param sessionId - The thread/session ID
1007
+ */
1008
+ async clearAdditionalUserParts(sessionId) {
1009
+ await this.deleteSessionValue(sessionId, _DistriClient.ADDITIONAL_PARTS_KEY);
1010
+ }
995
1011
  /**
996
1012
  * Issue an access token + refresh token for temporary authentication.
997
1013
  * Requires an existing authenticated session (bearer token).
@@ -1021,7 +1037,7 @@ var _DistriClient = class _DistriClient {
1021
1037
  if (!tokens?.access_token || !tokens?.refresh_token || typeof tokens?.expires_at !== "number") {
1022
1038
  throw new ApiError("Invalid token response", response.status);
1023
1039
  }
1024
- this.applyTokens(tokens.access_token, tokens.refresh_token);
1040
+ this.applyTokens(tokens.access_token, tokens.refresh_token, false);
1025
1041
  return tokens;
1026
1042
  }
1027
1043
  /**
@@ -1034,18 +1050,13 @@ var _DistriClient = class _DistriClient {
1034
1050
  * Update the access/refresh tokens in memory.
1035
1051
  */
1036
1052
  setTokens(tokens) {
1037
- this.accessToken = tokens.accessToken;
1038
- if (tokens.refreshToken) {
1053
+ if (tokens.accessToken !== void 0) {
1054
+ this.accessToken = tokens.accessToken;
1055
+ }
1056
+ if (tokens.refreshToken !== void 0) {
1039
1057
  this.refreshToken = tokens.refreshToken;
1040
1058
  }
1041
1059
  }
1042
- /**
1043
- * Reset all authentication tokens.
1044
- */
1045
- resetTokens() {
1046
- this.accessToken = void 0;
1047
- this.refreshToken = void 0;
1048
- }
1049
1060
  /**
1050
1061
  * Start streaming speech-to-text transcription via WebSocket
1051
1062
  */
@@ -1461,17 +1472,15 @@ var _DistriClient = class _DistriClient {
1461
1472
  get baseUrl() {
1462
1473
  return this.config.baseUrl;
1463
1474
  }
1464
- applyTokens(accessToken, refreshToken) {
1475
+ applyTokens(accessToken, refreshToken, notify) {
1465
1476
  this.accessToken = accessToken;
1466
- if (refreshToken) {
1467
- this.refreshToken = refreshToken;
1477
+ this.refreshToken = refreshToken;
1478
+ if (notify && this.onTokenRefresh) {
1479
+ this.onTokenRefresh({ accessToken, refreshToken });
1468
1480
  }
1469
1481
  }
1470
- /**
1471
- * Ensure access token is valid, refreshing if necessary
1472
- */
1473
1482
  async ensureAccessToken() {
1474
- if (!this.refreshToken && !this.onTokenRefresh) {
1483
+ if (!this.refreshToken) {
1475
1484
  return;
1476
1485
  }
1477
1486
  if (!this.accessToken || this.isTokenExpiring(this.accessToken)) {
@@ -1483,7 +1492,7 @@ var _DistriClient = class _DistriClient {
1483
1492
  }
1484
1493
  }
1485
1494
  async refreshTokens() {
1486
- if (!this.refreshToken && !this.onTokenRefresh) {
1495
+ if (!this.refreshToken) {
1487
1496
  return;
1488
1497
  }
1489
1498
  if (!this.refreshPromise) {
@@ -1494,17 +1503,6 @@ var _DistriClient = class _DistriClient {
1494
1503
  return this.refreshPromise;
1495
1504
  }
1496
1505
  async performTokenRefresh() {
1497
- if (this.onTokenRefresh) {
1498
- this.accessToken = void 0;
1499
- const newToken = await this.onTokenRefresh();
1500
- if (newToken) {
1501
- this.applyTokens(newToken);
1502
- return;
1503
- }
1504
- }
1505
- if (!this.refreshToken) {
1506
- return;
1507
- }
1508
1506
  const response = await this.fetchAbsolute(
1509
1507
  `${this.config.baseUrl}/token`,
1510
1508
  {
@@ -1528,7 +1526,7 @@ var _DistriClient = class _DistriClient {
1528
1526
  if (!tokens?.access_token || !tokens?.refresh_token) {
1529
1527
  throw new ApiError("Invalid token response", response.status);
1530
1528
  }
1531
- this.applyTokens(tokens.access_token, tokens.refresh_token);
1529
+ this.applyTokens(tokens.access_token, tokens.refresh_token, true);
1532
1530
  }
1533
1531
  isTokenExpiring(token) {
1534
1532
  const expiresAt = this.getTokenExpiry(token);
@@ -1623,7 +1621,7 @@ var _DistriClient = class _DistriClient {
1623
1621
  headers
1624
1622
  });
1625
1623
  clearTimeout(timeoutId);
1626
- if (!skipAuth && retryOnAuth && response.status === 401 && (this.refreshToken || this.onTokenRefresh)) {
1624
+ if (!skipAuth && retryOnAuth && response.status === 401 && this.refreshToken) {
1627
1625
  const refreshed = await this.refreshTokens().then(() => true).catch(() => false);
1628
1626
  if (refreshed) {
1629
1627
  return this.fetchAbsolute(url, initialInit, { skipAuth, retryOnAuth: false });
@@ -1641,8 +1639,7 @@ var _DistriClient = class _DistriClient {
1641
1639
  throw lastError;
1642
1640
  }
1643
1641
  /**
1644
- * Enhanced fetch with retry logic and auth headers.
1645
- * Exposed publicly for extensions like DistriHomeClient.
1642
+ * Enhanced fetch with retry logic
1646
1643
  */
1647
1644
  async fetch(input, initialInit) {
1648
1645
  const url = `${this.config.baseUrl}${input}`;
@@ -1715,6 +1712,13 @@ var _DistriClient = class _DistriClient {
1715
1712
  }
1716
1713
  };
1717
1714
  // ============================================================
1715
+ // Additional User Message Parts API
1716
+ // ============================================================
1717
+ // These methods allow external tools to append parts (text, images)
1718
+ // to the user message in the next agent iteration.
1719
+ // The parts are stored under the key "__additional_user_parts".
1720
+ _DistriClient.ADDITIONAL_PARTS_KEY = "__additional_user_parts";
1721
+ // ============================================================
1718
1722
  // Token API
1719
1723
  // ============================================================
1720
1724
  // Issue access + refresh tokens for temporary authentication (e.g., frontend use)
@@ -1740,25 +1744,6 @@ function uuidv4() {
1740
1744
  }
1741
1745
 
1742
1746
  // src/agent.ts
1743
- var ExternalToolValidationError = class extends DistriError {
1744
- constructor(agentName, result) {
1745
- super(
1746
- result.message || "Missing required external tools for agent invocation.",
1747
- "EXTERNAL_TOOL_VALIDATION_ERROR",
1748
- {
1749
- agentName,
1750
- missingTools: result.missingTools,
1751
- requiredTools: result.requiredTools,
1752
- providedTools: result.providedTools
1753
- }
1754
- );
1755
- this.name = "ExternalToolValidationError";
1756
- this.agentName = agentName;
1757
- this.missingTools = result.missingTools;
1758
- this.requiredTools = result.requiredTools;
1759
- this.providedTools = result.providedTools;
1760
- }
1761
- };
1762
1747
  var Agent = class _Agent {
1763
1748
  constructor(agentDefinition, client) {
1764
1749
  this.hookHandlers = /* @__PURE__ */ new Map();
@@ -1779,7 +1764,7 @@ var Agent = class _Agent {
1779
1764
  return this.agentDefinition.description;
1780
1765
  }
1781
1766
  get agentType() {
1782
- return this.agentDefinition.agent_type;
1767
+ return this.agentDefinition.agent_type ?? this.agentDefinition.agentType;
1783
1768
  }
1784
1769
  get iconUrl() {
1785
1770
  return this.agentDefinition.icon_url;
@@ -1816,7 +1801,7 @@ var Agent = class _Agent {
1816
1801
  const enhancedParams = this.enhanceParamsWithTools(params, tools);
1817
1802
  const a2aStream = this.client.sendMessageStream(this.agentDefinition.id, enhancedParams);
1818
1803
  const self = this;
1819
- return async function* () {
1804
+ return (async function* () {
1820
1805
  for await (const event of a2aStream) {
1821
1806
  const converted = decodeA2AStreamEvent(event);
1822
1807
  if (converted && converted.type === "inline_hook_requested") {
@@ -1837,38 +1822,12 @@ var Agent = class _Agent {
1837
1822
  yield converted;
1838
1823
  }
1839
1824
  }
1840
- }();
1841
- }
1842
- /**
1843
- * Validate that required external tools are registered before invoking.
1844
- */
1845
- validateExternalTools(tools = []) {
1846
- const requiredTools = this.getRequiredExternalTools();
1847
- const providedTools = tools.map((tool) => tool.name);
1848
- if (requiredTools.length === 0) {
1849
- return {
1850
- isValid: true,
1851
- requiredTools: [],
1852
- providedTools,
1853
- missingTools: []
1854
- };
1855
- }
1856
- const providedSet = new Set(providedTools);
1857
- const missingTools = requiredTools.filter((tool) => !providedSet.has(tool));
1858
- const isValid = missingTools.length === 0;
1859
- return {
1860
- isValid,
1861
- requiredTools,
1862
- providedTools,
1863
- missingTools,
1864
- message: isValid ? void 0 : this.formatExternalToolValidationMessage(requiredTools, missingTools)
1865
- };
1825
+ })();
1866
1826
  }
1867
1827
  /**
1868
1828
  * Enhance message params with tool definitions
1869
1829
  */
1870
1830
  enhanceParamsWithTools(params, tools) {
1871
- this.assertExternalTools(tools);
1872
1831
  const metadata = {
1873
1832
  ...params.metadata,
1874
1833
  external_tools: tools?.map((tool) => ({
@@ -1883,36 +1842,6 @@ var Agent = class _Agent {
1883
1842
  metadata
1884
1843
  };
1885
1844
  }
1886
- assertExternalTools(tools) {
1887
- const result = this.validateExternalTools(tools ?? []);
1888
- if (!result.isValid) {
1889
- throw new ExternalToolValidationError(this.agentDefinition.name || this.agentDefinition.id, result);
1890
- }
1891
- }
1892
- getRequiredExternalTools() {
1893
- const toolConfig = this.resolveToolConfig();
1894
- if (!toolConfig?.external || !Array.isArray(toolConfig.external)) {
1895
- return [];
1896
- }
1897
- return toolConfig.external.filter((tool) => typeof tool === "string" && tool.trim().length > 0);
1898
- }
1899
- resolveToolConfig() {
1900
- const root = this.agentDefinition;
1901
- return this.extractToolConfig(root) || this.extractToolConfig(root?.agent) || this.extractToolConfig(root?.definition);
1902
- }
1903
- extractToolConfig(candidate) {
1904
- if (!candidate) return null;
1905
- const tools = candidate.tools;
1906
- if (!tools || Array.isArray(tools) || typeof tools !== "object") {
1907
- return null;
1908
- }
1909
- return tools;
1910
- }
1911
- formatExternalToolValidationMessage(requiredTools, missingTools) {
1912
- const requiredList = requiredTools.join(", ");
1913
- const missingList = missingTools.join(", ");
1914
- return `Agent has external tools that are not registered: ${missingList}. This is an embedded agent that can run within the parent application. Register DistriWidget for embedding the parent component. Required tools: ${requiredList}.`;
1915
- }
1916
1845
  /**
1917
1846
  * Register multiple hooks at once.
1918
1847
  */
@@ -1929,13 +1858,12 @@ var Agent = class _Agent {
1929
1858
  */
1930
1859
  static async create(agentIdOrDef, client) {
1931
1860
  const agentDefinition = typeof agentIdOrDef === "string" ? await client.getAgent(agentIdOrDef) : agentIdOrDef;
1932
- const tools = agentDefinition?.resolved_tools || [];
1933
1861
  console.log("\u{1F916} Agent definition loaded:", {
1934
1862
  id: agentDefinition.id,
1935
1863
  name: agentDefinition.name,
1936
- tools: tools.map((t) => ({
1864
+ tools: agentDefinition.tools?.map((t) => ({
1937
1865
  name: t.name,
1938
- type: "function"
1866
+ type: t.type || "function"
1939
1867
  })) || [],
1940
1868
  toolCount: agentDefinition.tools?.length || 0
1941
1869
  });
@@ -1963,7 +1891,6 @@ export {
1963
1891
  DEFAULT_BASE_URL,
1964
1892
  DistriClient,
1965
1893
  DistriError,
1966
- ExternalToolValidationError,
1967
1894
  convertA2AMessageToDistri,
1968
1895
  convertA2APartToDistri,
1969
1896
  convertA2AStatusUpdateToDistri,