mitra-interactions-sdk 1.0.62 → 1.0.63

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.d.mts CHANGED
@@ -931,6 +931,13 @@ interface MitraConfig {
931
931
  * (ex: MitraSDK em Node) passe aqui — config explícito tem prioridade sobre o window.
932
932
  */
933
933
  agentWsUrl?: string;
934
+ /**
935
+ * Agent Chat via HTTP em vez de WebSocket (opt-in). Default: false (usa WS).
936
+ * Quando true, gerência (list/rename/delete/history/credentials) e o prompt
937
+ * vão por HTTP (resposta completa de uma vez, sem streaming). Requer que o
938
+ * servidor do agente exponha as rotas HTTP (ver spec). NÃO quebra quem usa WS.
939
+ */
940
+ httpEnable?: boolean;
934
941
  /** ID do projeto (usado como fallback nos métodos de login e serviços) */
935
942
  projectId?: number;
936
943
  /** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
package/dist/index.d.ts CHANGED
@@ -931,6 +931,13 @@ interface MitraConfig {
931
931
  * (ex: MitraSDK em Node) passe aqui — config explícito tem prioridade sobre o window.
932
932
  */
933
933
  agentWsUrl?: string;
934
+ /**
935
+ * Agent Chat via HTTP em vez de WebSocket (opt-in). Default: false (usa WS).
936
+ * Quando true, gerência (list/rename/delete/history/credentials) e o prompt
937
+ * vão por HTTP (resposta completa de uma vez, sem streaming). Requer que o
938
+ * servidor do agente exponha as rotas HTTP (ver spec). NÃO quebra quem usa WS.
939
+ */
940
+ httpEnable?: boolean;
934
941
  /** ID do projeto (usado como fallback nos métodos de login e serviços) */
935
942
  projectId?: number;
936
943
  /** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
package/dist/index.js CHANGED
@@ -389,7 +389,7 @@ function buildUrl(endpoint, params) {
389
389
  async function tryRefreshToken() {
390
390
  var _a, _b;
391
391
  const config = getConfig();
392
- if (!config.token || config.projectId == null) return false;
392
+ if (!config.token || config.projectId == null || !config.baseURL) return false;
393
393
  try {
394
394
  const baseURL = config.baseURL.replace(/\/+$/, "");
395
395
  const resp = await getFetch2()(`${baseURL}/mitraspace/project/refreshedToken/${config.projectId}`, {
@@ -1366,6 +1366,46 @@ function getWsUrl() {
1366
1366
  }
1367
1367
  throw new Error("Agent Chat: agentWsUrl indispon\xEDvel. Passe em configureSdkMitra({ agentWsUrl }) ou rode em uma app publicada pelo Mitra (build-proxy injeta window.__mitraEnv.agentWsUrl).");
1368
1368
  }
1369
+ function isHttpEnabled() {
1370
+ return getConfig().httpEnable === true;
1371
+ }
1372
+ function getAgentHttpBase() {
1373
+ return getWsUrl().split("?")[0].replace(/^ws/i, "http").replace(/\/+$/, "");
1374
+ }
1375
+ async function agentHttpPost(path, body) {
1376
+ const fetchFn = globalThis.fetch;
1377
+ if (typeof fetchFn !== "function") {
1378
+ throw new Error("Agent Chat (HTTP): fetch indispon\xEDvel. Use Node 18+ ou um browser.");
1379
+ }
1380
+ const resp = await fetchFn(`${getAgentHttpBase()}${path}`, {
1381
+ method: "POST",
1382
+ headers: {
1383
+ "Content-Type": "application/json",
1384
+ "Authorization": `Bearer ${getRawToken()}`
1385
+ },
1386
+ body: JSON.stringify(body)
1387
+ });
1388
+ const text = await resp.text().catch(() => "");
1389
+ const data = text ? JSON.parse(text) : null;
1390
+ if (!resp.ok) {
1391
+ throw new Error((data == null ? void 0 : data.error) || (data == null ? void 0 : data.message) || `Agent Chat (HTTP ${resp.status})`);
1392
+ }
1393
+ return data;
1394
+ }
1395
+ async function httpSendPrompt(payload, taskId) {
1396
+ var _a;
1397
+ const data = await agentHttpPost("/prompt", { ...payload, ...taskId ? { taskId } : {} });
1398
+ const resolvedTaskId = (data == null ? void 0 : data.taskId) || taskId || "";
1399
+ const content = (_a = data == null ? void 0 : data.content) != null ? _a : "";
1400
+ if (data == null ? void 0 : data.task) {
1401
+ routeMessage({ type: "task_update", payload: { action: "created", task: data.task } });
1402
+ }
1403
+ if (resolvedTaskId) {
1404
+ routeMessage({ type: "turn_started", taskId: resolvedTaskId });
1405
+ routeMessage({ type: "stream_delta", taskId: resolvedTaskId, payload: { delta: content } });
1406
+ routeMessage({ type: "stream_end", taskId: resolvedTaskId });
1407
+ }
1408
+ }
1369
1409
  function connect() {
1370
1410
  if (ws && ws.readyState === WebSocket.OPEN) {
1371
1411
  return Promise.resolve(ws);
@@ -1454,9 +1494,16 @@ function routeMessage(raw) {
1454
1494
  }
1455
1495
  var transport = {
1456
1496
  async ensureConnected() {
1497
+ if (isHttpEnabled()) return;
1457
1498
  await connect();
1458
1499
  },
1459
1500
  async request(type, payload) {
1501
+ var _a;
1502
+ if (isHttpEnabled()) {
1503
+ const data = await agentHttpPost("/request", { type, payload });
1504
+ if (data && data.ok === false) throw new Error(data.error || "Erro desconhecido");
1505
+ return (_a = data == null ? void 0 : data.data) != null ? _a : data;
1506
+ }
1460
1507
  const socket = await connect();
1461
1508
  const requestId = nextRequestId();
1462
1509
  return new Promise((resolve, reject) => {
@@ -1473,6 +1520,16 @@ var transport = {
1473
1520
  });
1474
1521
  },
1475
1522
  send(type, payload, taskId) {
1523
+ if (isHttpEnabled()) {
1524
+ if (type === "send_prompt") {
1525
+ httpSendPrompt(payload, taskId).catch((err) => {
1526
+ const tid = taskId || "";
1527
+ if (tid) routeMessage({ type: "error", taskId: tid, payload: { error: (err == null ? void 0 : err.message) || String(err) } });
1528
+ else console.error("[agent-chat] httpSendPrompt falhou:", err);
1529
+ });
1530
+ }
1531
+ return;
1532
+ }
1476
1533
  connect().then((socket) => {
1477
1534
  const requestId = nextRequestId();
1478
1535
  socket.send(JSON.stringify({ type, requestId, payload, taskId }));