@distri/core 0.3.0 → 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,
@@ -730,17 +729,6 @@ function convertA2AStatusUpdateToDistri(statusUpdate) {
730
729
  };
731
730
  return hookRequested;
732
731
  }
733
- case "browser_session_started": {
734
- const browserSessionStarted = {
735
- type: "browser_session_started",
736
- data: {
737
- session_id: metadata.session_id || "",
738
- viewer_url: metadata.viewer_url,
739
- stream_url: metadata.stream_url
740
- }
741
- };
742
- return browserSessionStarted;
743
- }
744
732
  default: {
745
733
  console.warn(`Unhandled status update metadata type: ${metadata.type}`, metadata);
746
734
  const defaultResult = {
@@ -920,29 +908,21 @@ var _DistriClient = class _DistriClient {
920
908
  this.tokenRefreshSkewMs = config.tokenRefreshSkewMs ?? 6e4;
921
909
  this.onTokenRefresh = config.onTokenRefresh;
922
910
  this.config = {
923
- baseUrl: config.baseUrl?.replace(/\/$/, "") || DEFAULT_BASE_URL,
911
+ baseUrl: config.baseUrl.replace(/\/$/, ""),
924
912
  apiVersion: config.apiVersion || "v1",
925
- timeout: config.timeout ?? 3e4,
926
- retryAttempts: config.retryAttempts ?? 3,
927
- retryDelay: config.retryDelay ?? 1e3,
928
- debug: config.debug ?? false,
913
+ timeout: config.timeout || 3e4,
914
+ retryAttempts: config.retryAttempts || 3,
915
+ retryDelay: config.retryDelay || 1e3,
916
+ debug: config.debug || false,
929
917
  headers,
930
- interceptor: config.interceptor ?? (async (init) => Promise.resolve(init)),
931
- onTokenRefresh: config.onTokenRefresh,
932
- clientId: config.clientId
918
+ interceptor: config.interceptor || ((init) => Promise.resolve(init))
933
919
  };
934
- }
935
- /**
936
- * Get the configured client ID.
937
- */
938
- get clientId() {
939
- return this.config.clientId;
940
- }
941
- /**
942
- * Set the client ID for embed token issuance.
943
- */
944
- set clientId(value) {
945
- 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
+ });
946
926
  }
947
927
  /**
948
928
  * Create a client with default cloud configuration.
@@ -975,7 +955,7 @@ var _DistriClient = class _DistriClient {
975
955
  if (expiry) {
976
956
  body.expiry = typeof expiry === "string" ? expiry : expiry.toISOString();
977
957
  }
978
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values`, {
958
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values`, {
979
959
  method: "POST",
980
960
  headers: {
981
961
  "Content-Type": "application/json",
@@ -992,7 +972,7 @@ var _DistriClient = class _DistriClient {
992
972
  * Session store: get a single value
993
973
  */
994
974
  async getSessionValue(sessionId, key) {
995
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
975
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
996
976
  method: "GET",
997
977
  headers: {
998
978
  ...this.config.headers
@@ -1009,7 +989,7 @@ var _DistriClient = class _DistriClient {
1009
989
  * Session store: get all values in a session
1010
990
  */
1011
991
  async getSessionValues(sessionId) {
1012
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values`, {
992
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values`, {
1013
993
  method: "GET",
1014
994
  headers: {
1015
995
  ...this.config.headers
@@ -1026,7 +1006,7 @@ var _DistriClient = class _DistriClient {
1026
1006
  * Session store: delete a single key
1027
1007
  */
1028
1008
  async deleteSessionValue(sessionId, key) {
1029
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
1009
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}/values/${encodeURIComponent(key)}`, {
1030
1010
  method: "DELETE",
1031
1011
  headers: {
1032
1012
  ...this.config.headers
@@ -1041,7 +1021,7 @@ var _DistriClient = class _DistriClient {
1041
1021
  * Session store: clear all keys in a session
1042
1022
  */
1043
1023
  async clearSession(sessionId) {
1044
- const resp = await this.fetch(`/sessions/${encodeURIComponent(sessionId)}`, {
1024
+ const resp = await this.fetch(`/session/${encodeURIComponent(sessionId)}`, {
1045
1025
  method: "DELETE",
1046
1026
  headers: {
1047
1027
  ...this.config.headers
@@ -1052,6 +1032,30 @@ var _DistriClient = class _DistriClient {
1052
1032
  throw new ApiError(errorData.error || "Failed to clear session", resp.status);
1053
1033
  }
1054
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
+ }
1055
1059
  /**
1056
1060
  * Issue an access token + refresh token for temporary authentication.
1057
1061
  * Requires an existing authenticated session (bearer token).
@@ -1081,7 +1085,7 @@ var _DistriClient = class _DistriClient {
1081
1085
  if (!tokens?.access_token || !tokens?.refresh_token || typeof tokens?.expires_at !== "number") {
1082
1086
  throw new ApiError("Invalid token response", response.status);
1083
1087
  }
1084
- this.applyTokens(tokens.access_token, tokens.refresh_token);
1088
+ this.applyTokens(tokens.access_token, tokens.refresh_token, false);
1085
1089
  return tokens;
1086
1090
  }
1087
1091
  /**
@@ -1094,18 +1098,13 @@ var _DistriClient = class _DistriClient {
1094
1098
  * Update the access/refresh tokens in memory.
1095
1099
  */
1096
1100
  setTokens(tokens) {
1097
- this.accessToken = tokens.accessToken;
1098
- if (tokens.refreshToken) {
1101
+ if (tokens.accessToken !== void 0) {
1102
+ this.accessToken = tokens.accessToken;
1103
+ }
1104
+ if (tokens.refreshToken !== void 0) {
1099
1105
  this.refreshToken = tokens.refreshToken;
1100
1106
  }
1101
1107
  }
1102
- /**
1103
- * Reset all authentication tokens.
1104
- */
1105
- resetTokens() {
1106
- this.accessToken = void 0;
1107
- this.refreshToken = void 0;
1108
- }
1109
1108
  /**
1110
1109
  * Start streaming speech-to-text transcription via WebSocket
1111
1110
  */
@@ -1323,31 +1322,6 @@ var _DistriClient = class _DistriClient {
1323
1322
  throw new DistriError(`Failed to fetch agent ${agentId}`, "FETCH_ERROR", error);
1324
1323
  }
1325
1324
  }
1326
- /**
1327
- * Update an agent's definition (markdown only)
1328
- */
1329
- async updateAgent(agentId, update) {
1330
- try {
1331
- const response = await this.fetch(`/agents/${agentId}`, {
1332
- method: "PUT",
1333
- headers: {
1334
- "Content-Type": "application/json",
1335
- ...this.config.headers
1336
- },
1337
- body: JSON.stringify(update)
1338
- });
1339
- if (!response.ok) {
1340
- if (response.status === 404) {
1341
- throw new ApiError(`Agent not found: ${agentId}`, 404);
1342
- }
1343
- throw new ApiError(`Failed to update agent: ${response.statusText}`, response.status);
1344
- }
1345
- return await response.json();
1346
- } catch (error) {
1347
- if (error instanceof ApiError) throw error;
1348
- throw new DistriError(`Failed to update agent ${agentId}`, "UPDATE_ERROR", error);
1349
- }
1350
- }
1351
1325
  /**
1352
1326
  * Get or create A2AClient for an agent
1353
1327
  */
@@ -1433,22 +1407,11 @@ var _DistriClient = class _DistriClient {
1433
1407
  }
1434
1408
  }
1435
1409
  /**
1436
- * Get threads from Distri server with filtering and pagination
1410
+ * Get threads from Distri server
1437
1411
  */
1438
- async getThreads(params = {}) {
1412
+ async getThreads() {
1439
1413
  try {
1440
- const searchParams = new URLSearchParams();
1441
- if (params.agent_id) searchParams.set("agent_id", params.agent_id);
1442
- if (params.external_id) searchParams.set("external_id", params.external_id);
1443
- if (params.search) searchParams.set("search", params.search);
1444
- if (params.from_date) searchParams.set("from_date", params.from_date);
1445
- if (params.to_date) searchParams.set("to_date", params.to_date);
1446
- if (params.tags?.length) searchParams.set("tags", params.tags.join(","));
1447
- if (params.limit !== void 0) searchParams.set("limit", params.limit.toString());
1448
- if (params.offset !== void 0) searchParams.set("offset", params.offset.toString());
1449
- const queryString = searchParams.toString();
1450
- const url = queryString ? `/threads?${queryString}` : "/threads";
1451
- const response = await this.fetch(url);
1414
+ const response = await this.fetch(`/threads`);
1452
1415
  if (!response.ok) {
1453
1416
  throw new ApiError(`Failed to fetch threads: ${response.statusText}`, response.status);
1454
1417
  }
@@ -1458,39 +1421,6 @@ var _DistriClient = class _DistriClient {
1458
1421
  throw new DistriError("Failed to fetch threads", "FETCH_ERROR", error);
1459
1422
  }
1460
1423
  }
1461
- /**
1462
- * Get agents sorted by thread count (most active first)
1463
- */
1464
- async getAgentsByUsage() {
1465
- try {
1466
- const response = await this.fetch("/threads/agents");
1467
- if (!response.ok) {
1468
- throw new ApiError(`Failed to fetch agents by usage: ${response.statusText}`, response.status);
1469
- }
1470
- return await response.json();
1471
- } catch (error) {
1472
- if (error instanceof ApiError) throw error;
1473
- throw new DistriError("Failed to fetch agents by usage", "FETCH_ERROR", error);
1474
- }
1475
- }
1476
- /**
1477
- * Create a new browser session
1478
- * Returns session info including viewer_url and stream_url from browsr
1479
- */
1480
- async createBrowserSession() {
1481
- try {
1482
- const response = await this.fetch("/browser/session", {
1483
- method: "POST"
1484
- });
1485
- if (!response.ok) {
1486
- throw new ApiError(`Failed to create browser session: ${response.statusText}`, response.status);
1487
- }
1488
- return await response.json();
1489
- } catch (error) {
1490
- if (error instanceof ApiError) throw error;
1491
- throw new DistriError("Failed to create browser session", "FETCH_ERROR", error);
1492
- }
1493
- }
1494
1424
  async getThread(threadId) {
1495
1425
  try {
1496
1426
  const response = await this.fetch(`/threads/${threadId}`);
@@ -1590,17 +1520,15 @@ var _DistriClient = class _DistriClient {
1590
1520
  get baseUrl() {
1591
1521
  return this.config.baseUrl;
1592
1522
  }
1593
- applyTokens(accessToken, refreshToken) {
1523
+ applyTokens(accessToken, refreshToken, notify) {
1594
1524
  this.accessToken = accessToken;
1595
- if (refreshToken) {
1596
- this.refreshToken = refreshToken;
1525
+ this.refreshToken = refreshToken;
1526
+ if (notify && this.onTokenRefresh) {
1527
+ this.onTokenRefresh({ accessToken, refreshToken });
1597
1528
  }
1598
1529
  }
1599
- /**
1600
- * Ensure access token is valid, refreshing if necessary
1601
- */
1602
1530
  async ensureAccessToken() {
1603
- if (!this.refreshToken && !this.onTokenRefresh) {
1531
+ if (!this.refreshToken) {
1604
1532
  return;
1605
1533
  }
1606
1534
  if (!this.accessToken || this.isTokenExpiring(this.accessToken)) {
@@ -1612,7 +1540,7 @@ var _DistriClient = class _DistriClient {
1612
1540
  }
1613
1541
  }
1614
1542
  async refreshTokens() {
1615
- if (!this.refreshToken && !this.onTokenRefresh) {
1543
+ if (!this.refreshToken) {
1616
1544
  return;
1617
1545
  }
1618
1546
  if (!this.refreshPromise) {
@@ -1623,17 +1551,6 @@ var _DistriClient = class _DistriClient {
1623
1551
  return this.refreshPromise;
1624
1552
  }
1625
1553
  async performTokenRefresh() {
1626
- if (this.onTokenRefresh) {
1627
- this.accessToken = void 0;
1628
- const newToken = await this.onTokenRefresh();
1629
- if (newToken) {
1630
- this.applyTokens(newToken);
1631
- return;
1632
- }
1633
- }
1634
- if (!this.refreshToken) {
1635
- return;
1636
- }
1637
1554
  const response = await this.fetchAbsolute(
1638
1555
  `${this.config.baseUrl}/token`,
1639
1556
  {
@@ -1657,7 +1574,7 @@ var _DistriClient = class _DistriClient {
1657
1574
  if (!tokens?.access_token || !tokens?.refresh_token) {
1658
1575
  throw new ApiError("Invalid token response", response.status);
1659
1576
  }
1660
- this.applyTokens(tokens.access_token, tokens.refresh_token);
1577
+ this.applyTokens(tokens.access_token, tokens.refresh_token, true);
1661
1578
  }
1662
1579
  isTokenExpiring(token) {
1663
1580
  const expiresAt = this.getTokenExpiry(token);
@@ -1752,7 +1669,7 @@ var _DistriClient = class _DistriClient {
1752
1669
  headers
1753
1670
  });
1754
1671
  clearTimeout(timeoutId);
1755
- if (!skipAuth && retryOnAuth && response.status === 401 && (this.refreshToken || this.onTokenRefresh)) {
1672
+ if (!skipAuth && retryOnAuth && response.status === 401 && this.refreshToken) {
1756
1673
  const refreshed = await this.refreshTokens().then(() => true).catch(() => false);
1757
1674
  if (refreshed) {
1758
1675
  return this.fetchAbsolute(url, initialInit, { skipAuth, retryOnAuth: false });
@@ -1770,8 +1687,7 @@ var _DistriClient = class _DistriClient {
1770
1687
  throw lastError;
1771
1688
  }
1772
1689
  /**
1773
- * Enhanced fetch with retry logic and auth headers.
1774
- * Exposed publicly for extensions like DistriHomeClient.
1690
+ * Enhanced fetch with retry logic
1775
1691
  */
1776
1692
  async fetch(input, initialInit) {
1777
1693
  const url = `${this.config.baseUrl}${input}`;
@@ -1844,6 +1760,13 @@ var _DistriClient = class _DistriClient {
1844
1760
  }
1845
1761
  };
1846
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
+ // ============================================================
1847
1770
  // Token API
1848
1771
  // ============================================================
1849
1772
  // Issue access + refresh tokens for temporary authentication (e.g., frontend use)
@@ -1869,25 +1792,6 @@ function uuidv4() {
1869
1792
  }
1870
1793
 
1871
1794
  // src/agent.ts
1872
- var ExternalToolValidationError = class extends DistriError {
1873
- constructor(agentName, result) {
1874
- super(
1875
- result.message || "Missing required external tools for agent invocation.",
1876
- "EXTERNAL_TOOL_VALIDATION_ERROR",
1877
- {
1878
- agentName,
1879
- missingTools: result.missingTools,
1880
- requiredTools: result.requiredTools,
1881
- providedTools: result.providedTools
1882
- }
1883
- );
1884
- this.name = "ExternalToolValidationError";
1885
- this.agentName = agentName;
1886
- this.missingTools = result.missingTools;
1887
- this.requiredTools = result.requiredTools;
1888
- this.providedTools = result.providedTools;
1889
- }
1890
- };
1891
1795
  var Agent = class _Agent {
1892
1796
  constructor(agentDefinition, client) {
1893
1797
  this.hookHandlers = /* @__PURE__ */ new Map();
@@ -1908,7 +1812,7 @@ var Agent = class _Agent {
1908
1812
  return this.agentDefinition.description;
1909
1813
  }
1910
1814
  get agentType() {
1911
- return this.agentDefinition.agent_type;
1815
+ return this.agentDefinition.agent_type ?? this.agentDefinition.agentType;
1912
1816
  }
1913
1817
  get iconUrl() {
1914
1818
  return this.agentDefinition.icon_url;
@@ -1968,36 +1872,10 @@ var Agent = class _Agent {
1968
1872
  }
1969
1873
  })();
1970
1874
  }
1971
- /**
1972
- * Validate that required external tools are registered before invoking.
1973
- */
1974
- validateExternalTools(tools = []) {
1975
- const requiredTools = this.getRequiredExternalTools();
1976
- const providedTools = tools.map((tool) => tool.name);
1977
- if (requiredTools.length === 0) {
1978
- return {
1979
- isValid: true,
1980
- requiredTools: [],
1981
- providedTools,
1982
- missingTools: []
1983
- };
1984
- }
1985
- const providedSet = new Set(providedTools);
1986
- const missingTools = requiredTools.filter((tool) => !providedSet.has(tool));
1987
- const isValid = missingTools.length === 0;
1988
- return {
1989
- isValid,
1990
- requiredTools,
1991
- providedTools,
1992
- missingTools,
1993
- message: isValid ? void 0 : this.formatExternalToolValidationMessage(requiredTools, missingTools)
1994
- };
1995
- }
1996
1875
  /**
1997
1876
  * Enhance message params with tool definitions
1998
1877
  */
1999
1878
  enhanceParamsWithTools(params, tools) {
2000
- this.assertExternalTools(tools);
2001
1879
  const metadata = {
2002
1880
  ...params.metadata,
2003
1881
  external_tools: tools?.map((tool) => ({
@@ -2012,36 +1890,6 @@ var Agent = class _Agent {
2012
1890
  metadata
2013
1891
  };
2014
1892
  }
2015
- assertExternalTools(tools) {
2016
- const result = this.validateExternalTools(tools ?? []);
2017
- if (!result.isValid) {
2018
- throw new ExternalToolValidationError(this.agentDefinition.name || this.agentDefinition.id, result);
2019
- }
2020
- }
2021
- getRequiredExternalTools() {
2022
- const toolConfig = this.resolveToolConfig();
2023
- if (!toolConfig?.external || !Array.isArray(toolConfig.external)) {
2024
- return [];
2025
- }
2026
- return toolConfig.external.filter((tool) => typeof tool === "string" && tool.trim().length > 0);
2027
- }
2028
- resolveToolConfig() {
2029
- const root = this.agentDefinition;
2030
- return this.extractToolConfig(root) || this.extractToolConfig(root?.agent) || this.extractToolConfig(root?.definition);
2031
- }
2032
- extractToolConfig(candidate) {
2033
- if (!candidate) return null;
2034
- const tools = candidate.tools;
2035
- if (!tools || Array.isArray(tools) || typeof tools !== "object") {
2036
- return null;
2037
- }
2038
- return tools;
2039
- }
2040
- formatExternalToolValidationMessage(requiredTools, missingTools) {
2041
- const requiredList = requiredTools.join(", ");
2042
- const missingList = missingTools.join(", ");
2043
- 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}.`;
2044
- }
2045
1893
  /**
2046
1894
  * Register multiple hooks at once.
2047
1895
  */
@@ -2058,13 +1906,12 @@ var Agent = class _Agent {
2058
1906
  */
2059
1907
  static async create(agentIdOrDef, client) {
2060
1908
  const agentDefinition = typeof agentIdOrDef === "string" ? await client.getAgent(agentIdOrDef) : agentIdOrDef;
2061
- const tools = agentDefinition?.resolved_tools || [];
2062
1909
  console.log("\u{1F916} Agent definition loaded:", {
2063
1910
  id: agentDefinition.id,
2064
1911
  name: agentDefinition.name,
2065
- tools: tools.map((t) => ({
1912
+ tools: agentDefinition.tools?.map((t) => ({
2066
1913
  name: t.name,
2067
- type: "function"
1914
+ type: t.type || "function"
2068
1915
  })) || [],
2069
1916
  toolCount: agentDefinition.tools?.length || 0
2070
1917
  });
@@ -2093,7 +1940,6 @@ var Agent = class _Agent {
2093
1940
  DEFAULT_BASE_URL,
2094
1941
  DistriClient,
2095
1942
  DistriError,
2096
- ExternalToolValidationError,
2097
1943
  convertA2AMessageToDistri,
2098
1944
  convertA2APartToDistri,
2099
1945
  convertA2AStatusUpdateToDistri,