mitra-interactions-sdk 1.0.60-beta.43 → 1.0.60-beta.45

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/README.md CHANGED
@@ -301,7 +301,7 @@ const existing = getAgentTaskMitra({ taskId: 'uuid-da-task' });
301
301
  await existing.loadHistory({ limit: 50 });
302
302
  ```
303
303
 
304
- `getAgentTaskMitra({ create: true, agentType?, name?, agentId?, reasoningEffort?, transport?, userId? })` ou `getAgentTaskMitra({ taskId, transport?, userId? })`.
304
+ `getAgentTaskMitra({ create: true, agentType?, name?, agentId?, reasoningEffort?, transport?, userId? })` ou `getAgentTaskMitra({ taskId, transport? })`.
305
305
 
306
306
  **Agente autônomo**: a autonomia é **propriedade do AGENTE** (`autonomous` em `createAgentMitra`/`updateAgentMitra`, no `mitra-sdk`) — não existe flag na criação do chat. Ao criar um chat contra um agente autônomo (`getAgentTaskMitra({ create: true, agentId })`), o copilot deriva a autonomia do agente e o chat já nasce **sem dono** (`user_id NULL` — a dona é o agente), usando a connection anexada ao agente como credencial. Exige auth `AGENT_WRITE` (chave de SF ou token de app EDIT) — usuário business comum não abre chat autônomo. Depois de criado, dirigir/listar é igual ao chat normal (`getAgentTaskMitra({ taskId })`, `send`, `manageAgentChatMitra({ list, agentId })`).
307
307
 
@@ -313,11 +313,11 @@ await existing.loadHistory({ limit: 50 });
313
313
  ```typescript
314
314
  // SF reagindo a webhook: continua a thread da pessoa atendida
315
315
  const task = getAgentTaskMitra({ create: true, agentId, userId: 'uuid-do-usuario' }); // chat nasce DELE
316
- const dela = await manageAgentChatMitra({ action: 'list', userId: 'uuid-do-usuario' }); // chats DELA
317
- const mesma = getAgentTaskMitra({ taskId, userId: 'uuid-do-usuario' }); // defensivo: 404 se o chat não for dela
316
+ const dela = await manageAgentChatMitra({ action: 'list', userId: 'uuid-do-usuario' }); // chats DELA (debug/observabilidade)
317
+ const mesma = getAgentTaskMitra({ taskId }); // depois do create, SÓ taskId — o dono é inferido dele
318
318
  ```
319
319
 
320
- Erros nomeados: `403` sem `AGENT_WRITE`; `400 AUTONOMOUS_TASK_HAS_NO_OWNER` (userId + agente autônomo é contradição); `404` quando o `userId` defensivo não bate com o dono real. Nunca invente `userId` de texto do usuário — use o id do vínculo canal→usuário da sua aplicação.
320
+ **`userId` é atributo do CHAT, não argumento das operações**: só o `create` (e o `list`, pra observabilidade) aceitam — prompt, histórico, eventos e `readChat` continuam só com `taskId`, e o backend não aceita `userId` neles. Erros nomeados: `403` sem `AGENT_WRITE`; `400 AUTONOMOUS_TASK_HAS_NO_OWNER` (userId + agente autônomo é contradição); `400 ANONYMOUS_CALLER_REQUIRES_OWNER` (contexto anônimo criando chat de agente normal exige userId). Nunca invente `userId` de texto do usuário — use o id do vínculo canal→usuário da sua aplicação.
321
321
 
322
322
  #### Propriedades (somente leitura)
323
323
 
package/dist/index.d.mts CHANGED
@@ -327,6 +327,10 @@ interface GetAgentTaskCreateOptions {
327
327
  * texto — use o id que a aplicação já tem no vínculo canal→usuário.
328
328
  * Omitido = chat do caller, byte a byte como sempre.
329
329
  * Com agente AUTÔNOMO é contradição: 400 AUTONOMOUS_TASK_HAS_NO_OWNER.
330
+ * Em contexto ANÔNIMO (SF sem identidade própria, ex.: SF pública), criar
331
+ * chat de agente NORMAL EXIGE userId: 400 ANONYMOUS_CALLER_REQUIRES_OWNER
332
+ * sem ele — a execução anônima não tem identidade própria, nomeie por quem
333
+ * ela age.
330
334
  */
331
335
  userId?: string;
332
336
  /** Transporte do prompt (default 'ws'). */
@@ -339,12 +343,6 @@ interface GetAgentTaskOpenOptions {
339
343
  projectId?: number | string;
340
344
  /** Transporte do prompt (default 'ws'). */
341
345
  transport?: AgentTaskTransport;
342
- /**
343
- * Validação defensiva ao agir em nome do dono (AGENT_WRITE): viaja no
344
- * readChat e nos inputs — o backend devolve 404 se o chat não pertencer a
345
- * esse usuário. Omitido = contexto do caller.
346
- */
347
- userId?: string;
348
346
  }
349
347
  type GetAgentTaskOptions = GetAgentTaskCreateOptions | GetAgentTaskOpenOptions;
350
348
  type AgentTaskStatus = 'opening' | 'idle' | 'streaming' | 'cancelled' | 'error' | 'closed';
package/dist/index.d.ts CHANGED
@@ -327,6 +327,10 @@ interface GetAgentTaskCreateOptions {
327
327
  * texto — use o id que a aplicação já tem no vínculo canal→usuário.
328
328
  * Omitido = chat do caller, byte a byte como sempre.
329
329
  * Com agente AUTÔNOMO é contradição: 400 AUTONOMOUS_TASK_HAS_NO_OWNER.
330
+ * Em contexto ANÔNIMO (SF sem identidade própria, ex.: SF pública), criar
331
+ * chat de agente NORMAL EXIGE userId: 400 ANONYMOUS_CALLER_REQUIRES_OWNER
332
+ * sem ele — a execução anônima não tem identidade própria, nomeie por quem
333
+ * ela age.
330
334
  */
331
335
  userId?: string;
332
336
  /** Transporte do prompt (default 'ws'). */
@@ -339,12 +343,6 @@ interface GetAgentTaskOpenOptions {
339
343
  projectId?: number | string;
340
344
  /** Transporte do prompt (default 'ws'). */
341
345
  transport?: AgentTaskTransport;
342
- /**
343
- * Validação defensiva ao agir em nome do dono (AGENT_WRITE): viaja no
344
- * readChat e nos inputs — o backend devolve 404 se o chat não pertencer a
345
- * esse usuário. Omitido = contexto do caller.
346
- */
347
- userId?: string;
348
346
  }
349
347
  type GetAgentTaskOptions = GetAgentTaskCreateOptions | GetAgentTaskOpenOptions;
350
348
  type AgentTaskStatus = 'opening' | 'idle' | 'streaming' | 'cancelled' | 'error' | 'closed';
package/dist/index.js CHANGED
@@ -360,14 +360,15 @@ async function tryRefreshToken() {
360
360
  }
361
361
  }
362
362
  async function handleResponse(response) {
363
- var _a, _b, _c, _d;
363
+ var _a, _b, _c, _d, _e;
364
364
  const text = await response.text();
365
365
  const { data, isJson } = parseBody(text);
366
366
  if (!response.ok) {
367
367
  const fallback = !isJson && text ? `HTTP ${response.status} \u2014 ${text}` : `HTTP ${response.status}`;
368
- const base = isJson && ((data == null ? void 0 : data.message) || ((_a = data == null ? void 0 : data.error) == null ? void 0 : _a.message) || (data == null ? void 0 : data.error)) || fallback;
368
+ const rawMsg = data == null ? void 0 : data.message;
369
+ const base = isJson && (typeof rawMsg === "string" && rawMsg || rawMsg && typeof rawMsg === "object" && typeof rawMsg.message === "string" && rawMsg.message || typeof ((_a = data == null ? void 0 : data.error) == null ? void 0 : _a.message) === "string" && data.error.message || typeof (data == null ? void 0 : data.error) === "string" && data.error) || fallback;
369
370
  const msg = isJson && (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
370
- const code = isJson && ((_d = (_c = data == null ? void 0 : data.error_code) != null ? _c : (_b = data == null ? void 0 : data.error) == null ? void 0 : _b.code) != null ? _d : data == null ? void 0 : data.code) || void 0;
371
+ const code = isJson && ((_e = (_d = (_c = data == null ? void 0 : data.error_code) != null ? _c : (_b = data == null ? void 0 : data.error) == null ? void 0 : _b.code) != null ? _d : data == null ? void 0 : data.code) != null ? _e : rawMsg && typeof rawMsg === "object" ? rawMsg.code : void 0) || void 0;
371
372
  throw {
372
373
  message: typeof msg === "string" ? msg : fallback,
373
374
  status: response.status,
@@ -504,8 +505,8 @@ var AgentTaskSession = class {
504
505
  this._isNew = init.kind === "new";
505
506
  this._transport = (_a = init.transport) != null ? _a : "ws";
506
507
  this._projectId = init.projectId;
507
- this._userId = init.userId;
508
508
  if (init.kind === "new") {
509
+ this._userId = init.userId;
509
510
  this._agentType = (_b = init.agentType) != null ? _b : DEFAULT_AGENT_TYPE;
510
511
  this._initialName = init.name;
511
512
  this._agentId = init.agentId;
@@ -543,14 +544,14 @@ var AgentTaskSession = class {
543
544
  // ── Abertura de chat existente ─────────
544
545
  async _openExisting(taskId) {
545
546
  try {
546
- const t = await readChatTask(taskId, this._projectId, this._userId);
547
+ const t = await readChatTask(taskId, this._projectId);
547
548
  this._task = toAgentChat(t);
548
549
  this._agentType = this._task.agentType;
549
550
  if (this._status === "opening") this._setStatus("idle");
550
551
  if (this._transport === "http") await this._ensureSse();
551
552
  else await this._ensureWs();
552
553
  } catch (err) {
553
- this._emit("error", { error: `Falha ao abrir chat: ${errMsg(err)}` });
554
+ this._emit("error", { ...errCode(err) ? { code: errCode(err) } : {}, error: `Falha ao abrir chat: ${errMsg(err)}` });
554
555
  this._setStatus("error");
555
556
  }
556
557
  }
@@ -624,7 +625,7 @@ var AgentTaskSession = class {
624
625
  ws.send(JSON.stringify(input));
625
626
  }
626
627
  } catch (err) {
627
- this._emit("error", { error: `Falha ao enviar prompt: ${errMsg(err)}` });
628
+ this._emit("error", { ...errCode(err) ? { code: errCode(err) } : {}, error: `Falha ao enviar prompt: ${errMsg(err)}` });
628
629
  if (this._status === "streaming") this._setStatus("idle");
629
630
  }
630
631
  }
@@ -645,13 +646,13 @@ var AgentTaskSession = class {
645
646
  if (this._status === "cancelled") this._setStatus("idle");
646
647
  }, CANCEL_SAFETY_MS);
647
648
  } catch (err) {
648
- this._emit("error", { error: `Falha ao cancelar: ${errMsg(err)}` });
649
+ this._emit("error", { ...errCode(err) ? { code: errCode(err) } : {}, error: `Falha ao cancelar: ${errMsg(err)}` });
649
650
  }
650
651
  }
651
652
  respondApproval(approved) {
652
653
  if (this._transport === "http") {
653
654
  void this._postInput({ type: "approval_response", approved }).catch((err) => {
654
- this._emit("error", { error: `Falha ao aprovar: ${errMsg(err)}` });
655
+ this._emit("error", { ...errCode(err) ? { code: errCode(err) } : {}, error: `Falha ao aprovar: ${errMsg(err)}` });
655
656
  });
656
657
  return;
657
658
  }
@@ -747,7 +748,6 @@ var AgentTaskSession = class {
747
748
  throw new Error("AgentTaskSession: sem taskId \u2014 task ainda n\xE3o criada.");
748
749
  }
749
750
  if (isTokenExpiring()) await tryRefreshToken();
750
- const payload = this._userId ? { ...body, userId: this._userId } : body;
751
751
  const doPost = async () => fetch(
752
752
  `${getTaskHttpBase()}/${encodeURIComponent(this._taskId)}/inputs`,
753
753
  {
@@ -756,7 +756,7 @@ var AgentTaskSession = class {
756
756
  "Content-Type": "application/json",
757
757
  Authorization: `Bearer ${getRawToken()}`
758
758
  },
759
- body: JSON.stringify(payload)
759
+ body: JSON.stringify(body)
760
760
  }
761
761
  );
762
762
  let res = await doPost();
@@ -997,9 +997,27 @@ var AgentTaskSession = class {
997
997
  };
998
998
  function errMsg(err) {
999
999
  if (err instanceof Error) return err.message;
1000
- if (err && typeof err === "object" && "message" in err) return String(err.message);
1000
+ if (err && typeof err === "object" && "message" in err) {
1001
+ const m = err.message;
1002
+ if (typeof m === "string") return m;
1003
+ if (m && typeof m === "object") {
1004
+ if (typeof m.message === "string") return m.code ? `${m.code}: ${m.message}` : m.message;
1005
+ try {
1006
+ return JSON.stringify(m);
1007
+ } catch (e) {
1008
+ return String(m);
1009
+ }
1010
+ }
1011
+ return String(m);
1012
+ }
1001
1013
  return String(err);
1002
1014
  }
1015
+ function errCode(err) {
1016
+ var _a, _b, _c, _d, _e, _f, _g;
1017
+ if (!err || typeof err !== "object") return void 0;
1018
+ const e = err;
1019
+ return (_g = (_f = (_d = (_b = e.code) != null ? _b : (_a = e.message) == null ? void 0 : _a.code) != null ? _d : (_c = e.details) == null ? void 0 : _c.code) != null ? _f : (_e = e.details) == null ? void 0 : _e.error_code) != null ? _g : void 0;
1020
+ }
1003
1021
  function toTimelineItem(message) {
1004
1022
  const tool = message.type === "TOOL_USE" ? toToolEvent(message) : null;
1005
1023
  if (tool) return { id: message.id, kind: "tool", tool, at: message.createdAt };
@@ -1088,13 +1106,10 @@ async function createChatTask(options) {
1088
1106
  });
1089
1107
  return env.result;
1090
1108
  }
1091
- async function readChatTask(taskId, projectId, userId) {
1109
+ async function readChatTask(taskId, projectId) {
1092
1110
  const env = await http.get("/agentAiShortcut/readChat", {
1093
1111
  projectId: resolveProjectId(projectId),
1094
- taskId,
1095
- // Validação defensiva: com userId, o backend devolve 404 se o chat não
1096
- // pertencer àquele dono.
1097
- ...userId ? { userId } : {}
1112
+ taskId
1098
1113
  });
1099
1114
  return env.result;
1100
1115
  }
@@ -1159,8 +1174,7 @@ function getAgentTaskMitra(options) {
1159
1174
  kind: "existing",
1160
1175
  taskId: options.taskId,
1161
1176
  projectId: options.projectId,
1162
- transport: options.transport,
1163
- userId: options.userId
1177
+ transport: options.transport
1164
1178
  });
1165
1179
  }
1166
1180
  if ("create" in options && options.create) {