mitra-interactions-sdk 1.0.61 → 1.0.63-beta.0

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
@@ -925,6 +925,19 @@ interface MitraConfig {
925
925
  integrationURL?: string;
926
926
  /** URL da página de autenticação Mitra (ex: https://coder.mitralab.io/sdk-auth/) */
927
927
  authUrl?: string;
928
+ /**
929
+ * URL do WebSocket do agente (Agent Chat). Opcional: em apps publicadas pela
930
+ * plataforma vem de window.__mitraEnv.agentWsUrl (build-proxy). Fora do browser
931
+ * (ex: MitraSDK em Node) passe aqui — config explícito tem prioridade sobre o window.
932
+ */
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;
928
941
  /** ID do projeto (usado como fallback nos métodos de login e serviços) */
929
942
  projectId?: number;
930
943
  /** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
package/dist/index.d.ts CHANGED
@@ -925,6 +925,19 @@ interface MitraConfig {
925
925
  integrationURL?: string;
926
926
  /** URL da página de autenticação Mitra (ex: https://coder.mitralab.io/sdk-auth/) */
927
927
  authUrl?: string;
928
+ /**
929
+ * URL do WebSocket do agente (Agent Chat). Opcional: em apps publicadas pela
930
+ * plataforma vem de window.__mitraEnv.agentWsUrl (build-proxy). Fora do browser
931
+ * (ex: MitraSDK em Node) passe aqui — config explícito tem prioridade sobre o window.
932
+ */
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;
928
941
  /** ID do projeto (usado como fallback nos métodos de login e serviços) */
929
942
  projectId?: number;
930
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}`, {
@@ -1358,11 +1358,53 @@ function resolveProjectId3(override) {
1358
1358
  }
1359
1359
  function getWsUrl() {
1360
1360
  var _a;
1361
+ const configured = getConfig().agentWsUrl;
1362
+ if (typeof configured === "string" && configured) return configured;
1361
1363
  if (typeof window !== "undefined") {
1362
1364
  const injected = (_a = window.__mitraEnv) == null ? void 0 : _a.agentWsUrl;
1363
1365
  if (typeof injected === "string" && injected) return injected;
1364
1366
  }
1365
- throw new Error("Agent Chat: window.__mitraEnv.agentWsUrl indispon\xEDvel. A SDK precisa rodar em uma app publicada pelo Mitra (build-proxy injeta __mitraEnv).");
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
+ }
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
+ }
1366
1408
  }
1367
1409
  function connect() {
1368
1410
  if (ws && ws.readyState === WebSocket.OPEN) {
@@ -1452,9 +1494,16 @@ function routeMessage(raw) {
1452
1494
  }
1453
1495
  var transport = {
1454
1496
  async ensureConnected() {
1497
+ if (isHttpEnabled()) return;
1455
1498
  await connect();
1456
1499
  },
1457
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
+ }
1458
1507
  const socket = await connect();
1459
1508
  const requestId = nextRequestId();
1460
1509
  return new Promise((resolve, reject) => {
@@ -1471,6 +1520,16 @@ var transport = {
1471
1520
  });
1472
1521
  },
1473
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
+ }
1474
1533
  connect().then((socket) => {
1475
1534
  const requestId = nextRequestId();
1476
1535
  socket.send(JSON.stringify({ type, requestId, payload, taskId }));
@@ -2038,6 +2097,7 @@ function readInjectedEnv() {
2038
2097
  if (typeof env.apiBaseURL === "string" && env.apiBaseURL) out.baseURL = env.apiBaseURL;
2039
2098
  if (typeof env.integrationURL === "string" && env.integrationURL) out.integrationURL = env.integrationURL;
2040
2099
  if (typeof env.authUrl === "string" && env.authUrl) out.authUrl = env.authUrl;
2100
+ if (typeof env.agentWsUrl === "string" && env.agentWsUrl) out.agentWsUrl = env.agentWsUrl;
2041
2101
  return out;
2042
2102
  }
2043
2103
  function configureSdkMitra(config = {}) {