@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.js CHANGED
@@ -29,7 +29,6 @@ __export(index_exports, {
29
29
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
30
30
  DistriClient: () => DistriClient,
31
31
  DistriError: () => DistriError,
32
- ExternalToolValidationError: () => ExternalToolValidationError,
33
32
  convertA2AMessageToDistri: () => convertA2AMessageToDistri,
34
33
  convertA2APartToDistri: () => convertA2APartToDistri,
35
34
  convertA2AStatusUpdateToDistri: () => convertA2AStatusUpdateToDistri,
@@ -909,29 +908,21 @@ var _DistriClient = class _DistriClient {
909
908
  this.tokenRefreshSkewMs = config.tokenRefreshSkewMs ?? 6e4;
910
909
  this.onTokenRefresh = config.onTokenRefresh;
911
910
  this.config = {
912
- baseUrl: config.baseUrl?.replace(/\/$/, "") || DEFAULT_BASE_URL,
911
+ baseUrl: config.baseUrl.replace(/\/$/, ""),
913
912
  apiVersion: config.apiVersion || "v1",
914
- timeout: config.timeout ?? 3e4,
915
- retryAttempts: config.retryAttempts ?? 3,
916
- retryDelay: config.retryDelay ?? 1e3,
917
- debug: config.debug ?? false,
913
+ timeout: config.timeout || 3e4,
914
+ retryAttempts: config.retryAttempts || 3,
915
+ retryDelay: config.retryDelay || 1e3,
916
+ debug: config.debug || false,
918
917
  headers,
919
- interceptor: config.interceptor ?? (async (init) => Promise.resolve(init)),
920
- onTokenRefresh: config.onTokenRefresh,
921
- clientId: config.clientId
918
+ interceptor: config.interceptor || ((init) => Promise.resolve(init))
922
919
  };
923
- }
924
- /**
925
- * Get the configured client ID.
926
- */
927
- get clientId() {
928
- return this.config.clientId;
929
- }
930
- /**
931
- * Set the client ID for embed token issuance.
932
- */
933
- set clientId(value) {
934
- this.config.clientId = value;
920
+ this.debug("DistriClient initialized with config:", {
921
+ baseUrl: this.config.baseUrl,
922
+ hasAccessToken: !!this.accessToken,
923
+ hasRefreshToken: !!this.refreshToken,
924
+ timeout: this.config.timeout
925
+ });
935
926
  }
936
927
  /**
937
928
  * Create a client with default cloud configuration.
@@ -964,7 +955,7 @@ var _DistriClient = class _DistriClient {
964
955
  if (expiry) {
965
956
  body.expiry = typeof expiry === "string" ? expiry : expiry.toISOString();
966
957
  }
967
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values`, {
958
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values`, {
968
959
  method: "POST",
969
960
  headers: {
970
961
  "Content-Type": "application/json",
@@ -981,7 +972,7 @@ var _DistriClient = class _DistriClient {
981
972
  * Session store: get a single value
982
973
  */
983
974
  async getSessionValue(sessionId, key) {
984
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
975
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
985
976
  method: "GET",
986
977
  headers: {
987
978
  ...this.config.headers
@@ -998,7 +989,7 @@ var _DistriClient = class _DistriClient {
998
989
  * Session store: get all values in a session
999
990
  */
1000
991
  async getSessionValues(sessionId) {
1001
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values`, {
992
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values`, {
1002
993
  method: "GET",
1003
994
  headers: {
1004
995
  ...this.config.headers
@@ -1015,7 +1006,7 @@ var _DistriClient = class _DistriClient {
1015
1006
  * Session store: delete a single key
1016
1007
  */
1017
1008
  async deleteSessionValue(sessionId, key) {
1018
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
1009
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
1019
1010
  method: "DELETE",
1020
1011
  headers: {
1021
1012
  ...this.config.headers
@@ -1030,7 +1021,7 @@ var _DistriClient = class _DistriClient {
1030
1021
  * Session store: clear all keys in a session
1031
1022
  */
1032
1023
  async clearSession(sessionId) {
1033
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}`, {
1024
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}`, {
1034
1025
  method: "DELETE",
1035
1026
  headers: {
1036
1027
  ...this.config.headers
@@ -1041,6 +1032,30 @@ var _DistriClient = class _DistriClient {
1041
1032
  throw new ApiError(errorData.error || "Failed to clear session", resp.status);
1042
1033
  }
1043
1034
  }
1035
+ /**
1036
+ * Set additional user message parts for the next agent iteration.
1037
+ * These parts will be appended to the user message in the prompt.
1038
+ * @param sessionId - The thread/session ID
1039
+ * @param parts - Array of DistriPart objects to append to user message
1040
+ */
1041
+ async setAdditionalUserParts(sessionId, parts) {
1042
+ await this.setSessionValue(sessionId, _DistriClient.ADDITIONAL_PARTS_KEY, parts);
1043
+ }
1044
+ /**
1045
+ * Get the current additional user message parts.
1046
+ * @param sessionId - The thread/session ID
1047
+ * @returns Array of DistriPart objects or null if not set
1048
+ */
1049
+ async getAdditionalUserParts(sessionId) {
1050
+ return this.getSessionValue(sessionId, _DistriClient.ADDITIONAL_PARTS_KEY);
1051
+ }
1052
+ /**
1053
+ * Clear/delete the additional user message parts.
1054
+ * @param sessionId - The thread/session ID
1055
+ */
1056
+ async clearAdditionalUserParts(sessionId) {
1057
+ await this.deleteSessionValue(sessionId, _DistriClient.ADDITIONAL_PARTS_KEY);
1058
+ }
1044
1059
  /**
1045
1060
  * Issue an access token + refresh token for temporary authentication.
1046
1061
  * Requires an existing authenticated session (bearer token).
@@ -1070,7 +1085,7 @@ var _DistriClient = class _DistriClient {
1070
1085
  if (!tokens?.access_token || !tokens?.refresh_token || typeof tokens?.expires_at !== "number") {
1071
1086
  throw new ApiError("Invalid token response", response.status);
1072
1087
  }
1073
- this.applyTokens(tokens.access_token, tokens.refresh_token);
1088
+ this.applyTokens(tokens.access_token, tokens.refresh_token, false);
1074
1089
  return tokens;
1075
1090
  }
1076
1091
  /**
@@ -1083,18 +1098,13 @@ var _DistriClient = class _DistriClient {
1083
1098
  * Update the access/refresh tokens in memory.
1084
1099
  */
1085
1100
  setTokens(tokens) {
1086
- this.accessToken = tokens.accessToken;
1087
- if (tokens.refreshToken) {
1101
+ if (tokens.accessToken !== void 0) {
1102
+ this.accessToken = tokens.accessToken;
1103
+ }
1104
+ if (tokens.refreshToken !== void 0) {
1088
1105
  this.refreshToken = tokens.refreshToken;
1089
1106
  }
1090
1107
  }
1091
- /**
1092
- * Reset all authentication tokens.
1093
- */
1094
- resetTokens() {
1095
- this.accessToken = void 0;
1096
- this.refreshToken = void 0;
1097
- }
1098
1108
  /**
1099
1109
  * Start streaming speech-to-text transcription via WebSocket
1100
1110
  */
@@ -1510,17 +1520,15 @@ var _DistriClient = class _DistriClient {
1510
1520
  get baseUrl() {
1511
1521
  return this.config.baseUrl;
1512
1522
  }
1513
- applyTokens(accessToken, refreshToken) {
1523
+ applyTokens(accessToken, refreshToken, notify) {
1514
1524
  this.accessToken = accessToken;
1515
- if (refreshToken) {
1516
- this.refreshToken = refreshToken;
1525
+ this.refreshToken = refreshToken;
1526
+ if (notify && this.onTokenRefresh) {
1527
+ this.onTokenRefresh({ accessToken, refreshToken });
1517
1528
  }
1518
1529
  }
1519
- /**
1520
- * Ensure access token is valid, refreshing if necessary
1521
- */
1522
1530
  async ensureAccessToken() {
1523
- if (!this.refreshToken && !this.onTokenRefresh) {
1531
+ if (!this.refreshToken) {
1524
1532
  return;
1525
1533
  }
1526
1534
  if (!this.accessToken || this.isTokenExpiring(this.accessToken)) {
@@ -1532,7 +1540,7 @@ var _DistriClient = class _DistriClient {
1532
1540
  }
1533
1541
  }
1534
1542
  async refreshTokens() {
1535
- if (!this.refreshToken && !this.onTokenRefresh) {
1543
+ if (!this.refreshToken) {
1536
1544
  return;
1537
1545
  }
1538
1546
  if (!this.refreshPromise) {
@@ -1543,17 +1551,6 @@ var _DistriClient = class _DistriClient {
1543
1551
  return this.refreshPromise;
1544
1552
  }
1545
1553
  async performTokenRefresh() {
1546
- if (this.onTokenRefresh) {
1547
- this.accessToken = void 0;
1548
- const newToken = await this.onTokenRefresh();
1549
- if (newToken) {
1550
- this.applyTokens(newToken);
1551
- return;
1552
- }
1553
- }
1554
- if (!this.refreshToken) {
1555
- return;
1556
- }
1557
1554
  const response = await this.fetchAbsolute(
1558
1555
  `${this.config.baseUrl}/token`,
1559
1556
  {
@@ -1577,7 +1574,7 @@ var _DistriClient = class _DistriClient {
1577
1574
  if (!tokens?.access_token || !tokens?.refresh_token) {
1578
1575
  throw new ApiError("Invalid token response", response.status);
1579
1576
  }
1580
- this.applyTokens(tokens.access_token, tokens.refresh_token);
1577
+ this.applyTokens(tokens.access_token, tokens.refresh_token, true);
1581
1578
  }
1582
1579
  isTokenExpiring(token) {
1583
1580
  const expiresAt = this.getTokenExpiry(token);
@@ -1672,7 +1669,7 @@ var _DistriClient = class _DistriClient {
1672
1669
  headers
1673
1670
  });
1674
1671
  clearTimeout(timeoutId);
1675
- if (!skipAuth && retryOnAuth && response.status === 401 && (this.refreshToken || this.onTokenRefresh)) {
1672
+ if (!skipAuth && retryOnAuth && response.status === 401 && this.refreshToken) {
1676
1673
  const refreshed = await this.refreshTokens().then(() => true).catch(() => false);
1677
1674
  if (refreshed) {
1678
1675
  return this.fetchAbsolute(url, initialInit, { skipAuth, retryOnAuth: false });
@@ -1690,8 +1687,7 @@ var _DistriClient = class _DistriClient {
1690
1687
  throw lastError;
1691
1688
  }
1692
1689
  /**
1693
- * Enhanced fetch with retry logic and auth headers.
1694
- * Exposed publicly for extensions like DistriHomeClient.
1690
+ * Enhanced fetch with retry logic
1695
1691
  */
1696
1692
  async fetch(input, initialInit) {
1697
1693
  const url = `${this.config.baseUrl}${input}`;
@@ -1764,6 +1760,13 @@ var _DistriClient = class _DistriClient {
1764
1760
  }
1765
1761
  };
1766
1762
  // ============================================================
1763
+ // Additional User Message Parts API
1764
+ // ============================================================
1765
+ // These methods allow external tools to append parts (text, images)
1766
+ // to the user message in the next agent iteration.
1767
+ // The parts are stored under the key "__additional_user_parts".
1768
+ _DistriClient.ADDITIONAL_PARTS_KEY = "__additional_user_parts";
1769
+ // ============================================================
1767
1770
  // Token API
1768
1771
  // ============================================================
1769
1772
  // Issue access + refresh tokens for temporary authentication (e.g., frontend use)
@@ -1789,25 +1792,6 @@ function uuidv4() {
1789
1792
  }
1790
1793
 
1791
1794
  // src/agent.ts
1792
- var ExternalToolValidationError = class extends DistriError {
1793
- constructor(agentName, result) {
1794
- super(
1795
- result.message || "Missing required external tools for agent invocation.",
1796
- "EXTERNAL_TOOL_VALIDATION_ERROR",
1797
- {
1798
- agentName,
1799
- missingTools: result.missingTools,
1800
- requiredTools: result.requiredTools,
1801
- providedTools: result.providedTools
1802
- }
1803
- );
1804
- this.name = "ExternalToolValidationError";
1805
- this.agentName = agentName;
1806
- this.missingTools = result.missingTools;
1807
- this.requiredTools = result.requiredTools;
1808
- this.providedTools = result.providedTools;
1809
- }
1810
- };
1811
1795
  var Agent = class _Agent {
1812
1796
  constructor(agentDefinition, client) {
1813
1797
  this.hookHandlers = /* @__PURE__ */ new Map();
@@ -1828,7 +1812,7 @@ var Agent = class _Agent {
1828
1812
  return this.agentDefinition.description;
1829
1813
  }
1830
1814
  get agentType() {
1831
- return this.agentDefinition.agent_type;
1815
+ return this.agentDefinition.agent_type ?? this.agentDefinition.agentType;
1832
1816
  }
1833
1817
  get iconUrl() {
1834
1818
  return this.agentDefinition.icon_url;
@@ -1865,7 +1849,7 @@ var Agent = class _Agent {
1865
1849
  const enhancedParams = this.enhanceParamsWithTools(params, tools);
1866
1850
  const a2aStream = this.client.sendMessageStream(this.agentDefinition.id, enhancedParams);
1867
1851
  const self = this;
1868
- return async function* () {
1852
+ return (async function* () {
1869
1853
  for await (const event of a2aStream) {
1870
1854
  const converted = decodeA2AStreamEvent(event);
1871
1855
  if (converted && converted.type === "inline_hook_requested") {
@@ -1886,38 +1870,12 @@ var Agent = class _Agent {
1886
1870
  yield converted;
1887
1871
  }
1888
1872
  }
1889
- }();
1890
- }
1891
- /**
1892
- * Validate that required external tools are registered before invoking.
1893
- */
1894
- validateExternalTools(tools = []) {
1895
- const requiredTools = this.getRequiredExternalTools();
1896
- const providedTools = tools.map((tool) => tool.name);
1897
- if (requiredTools.length === 0) {
1898
- return {
1899
- isValid: true,
1900
- requiredTools: [],
1901
- providedTools,
1902
- missingTools: []
1903
- };
1904
- }
1905
- const providedSet = new Set(providedTools);
1906
- const missingTools = requiredTools.filter((tool) => !providedSet.has(tool));
1907
- const isValid = missingTools.length === 0;
1908
- return {
1909
- isValid,
1910
- requiredTools,
1911
- providedTools,
1912
- missingTools,
1913
- message: isValid ? void 0 : this.formatExternalToolValidationMessage(requiredTools, missingTools)
1914
- };
1873
+ })();
1915
1874
  }
1916
1875
  /**
1917
1876
  * Enhance message params with tool definitions
1918
1877
  */
1919
1878
  enhanceParamsWithTools(params, tools) {
1920
- this.assertExternalTools(tools);
1921
1879
  const metadata = {
1922
1880
  ...params.metadata,
1923
1881
  external_tools: tools?.map((tool) => ({
@@ -1932,36 +1890,6 @@ var Agent = class _Agent {
1932
1890
  metadata
1933
1891
  };
1934
1892
  }
1935
- assertExternalTools(tools) {
1936
- const result = this.validateExternalTools(tools ?? []);
1937
- if (!result.isValid) {
1938
- throw new ExternalToolValidationError(this.agentDefinition.name || this.agentDefinition.id, result);
1939
- }
1940
- }
1941
- getRequiredExternalTools() {
1942
- const toolConfig = this.resolveToolConfig();
1943
- if (!toolConfig?.external || !Array.isArray(toolConfig.external)) {
1944
- return [];
1945
- }
1946
- return toolConfig.external.filter((tool) => typeof tool === "string" && tool.trim().length > 0);
1947
- }
1948
- resolveToolConfig() {
1949
- const root = this.agentDefinition;
1950
- return this.extractToolConfig(root) || this.extractToolConfig(root?.agent) || this.extractToolConfig(root?.definition);
1951
- }
1952
- extractToolConfig(candidate) {
1953
- if (!candidate) return null;
1954
- const tools = candidate.tools;
1955
- if (!tools || Array.isArray(tools) || typeof tools !== "object") {
1956
- return null;
1957
- }
1958
- return tools;
1959
- }
1960
- formatExternalToolValidationMessage(requiredTools, missingTools) {
1961
- const requiredList = requiredTools.join(", ");
1962
- const missingList = missingTools.join(", ");
1963
- 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}.`;
1964
- }
1965
1893
  /**
1966
1894
  * Register multiple hooks at once.
1967
1895
  */
@@ -1978,13 +1906,12 @@ var Agent = class _Agent {
1978
1906
  */
1979
1907
  static async create(agentIdOrDef, client) {
1980
1908
  const agentDefinition = typeof agentIdOrDef === "string" ? await client.getAgent(agentIdOrDef) : agentIdOrDef;
1981
- const tools = agentDefinition?.resolved_tools || [];
1982
1909
  console.log("\u{1F916} Agent definition loaded:", {
1983
1910
  id: agentDefinition.id,
1984
1911
  name: agentDefinition.name,
1985
- tools: tools.map((t) => ({
1912
+ tools: agentDefinition.tools?.map((t) => ({
1986
1913
  name: t.name,
1987
- type: "function"
1914
+ type: t.type || "function"
1988
1915
  })) || [],
1989
1916
  toolCount: agentDefinition.tools?.length || 0
1990
1917
  });
@@ -2013,7 +1940,6 @@ var Agent = class _Agent {
2013
1940
  DEFAULT_BASE_URL,
2014
1941
  DistriClient,
2015
1942
  DistriError,
2016
- ExternalToolValidationError,
2017
1943
  convertA2AMessageToDistri,
2018
1944
  convertA2APartToDistri,
2019
1945
  convertA2AStatusUpdateToDistri,