mitra-interactions-sdk 1.0.60-beta.21 → 1.0.60-beta.23

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.mjs CHANGED
@@ -220,15 +220,11 @@ var OAUTH_RESULT_TYPE = "mitra-oauth-result";
220
220
  var POPUP_W = 480;
221
221
  var POPUP_H = 600;
222
222
  var POPUP_TIMEOUT_MS = 5 * 60 * 1e3;
223
- var SSO_AUTH_PAGE_URL = "https://stg.mitralab.io/sdk-auth.html";
224
- async function fetchSsoAuthPageUrl(gatewayUrl) {
223
+ var SSO_AUTH_PAGE_URL = "https://beta.infusion.cloud/sdk-auth.html";
224
+ async function fetchSsoAuthPageUrl(_baseURL) {
225
225
  const config = isConfigured() ? getConfig() : null;
226
226
  if (config == null ? void 0 : config.authPageUrl) return config.authPageUrl;
227
- try {
228
- return `${new URL(gatewayUrl).origin}/sdk-auth.html`;
229
- } catch (e) {
230
- return SSO_AUTH_PAGE_URL;
231
- }
227
+ return SSO_AUTH_PAGE_URL;
232
228
  }
233
229
  var SSO_ENABLED_PROVIDERS = ["google"];
234
230
  function providerLabel(provider) {
@@ -405,7 +401,7 @@ async function startSsoRedirect(provider, options) {
405
401
  const { authUrl, projectId } = resolveLoginOptions2(options);
406
402
  const state = generateState();
407
403
  const appId = String(projectId);
408
- const authPageUrl = await fetchSsoAuthPageUrl(authUrl);
404
+ const authPageUrl = await fetchSsoAuthPageUrl();
409
405
  const redirectUri = stripToOriginPath(authPageUrl);
410
406
  persistRedirectContext({ state, provider, authUrl, projectId: appId, redirectUri });
411
407
  const startUrl = buildStartUrl(authPageUrl, provider, state, appId, authUrl, window.location.href);
@@ -498,6 +494,712 @@ async function exchangeSsoCodeMitra2(options) {
498
494
  return exchangeSsoCodeMitra(options);
499
495
  }
500
496
 
497
+ // src/agent-task-session.ts
498
+ var QUEUE_MAX = 10;
499
+ var TURN_STARTED_SAFETY_MS = 3e4;
500
+ var sessionCounter = 0;
501
+ var AgentTaskSession = class {
502
+ constructor(init, transport2) {
503
+ // ── Identidade ────────────────────────
504
+ this._taskId = null;
505
+ this._task = null;
506
+ // ── Estado ────────────────────────────
507
+ this._status = "opening";
508
+ this._history = [];
509
+ this._content = "";
510
+ this._queue = [];
511
+ // ── Cancel state ──────────────────────
512
+ this._cancelled = false;
513
+ this._awaitingTurnStarted = false;
514
+ this._turnStartedTimer = null;
515
+ this._pendingCancelResolve = null;
516
+ // ── Listeners ─────────────────────────
517
+ this._listeners = /* @__PURE__ */ new Map();
518
+ this._wsUnsubscribe = null;
519
+ this._wsUnsubscribePending = null;
520
+ this._transport = transport2;
521
+ this._sessionId = `sess-${++sessionCounter}-${Date.now()}`;
522
+ this._isNew = init.kind === "new";
523
+ if (init.kind === "new") {
524
+ this._projectId = init.projectId;
525
+ this._agentType = init.agentType;
526
+ this._modelId = init.modelId;
527
+ this._initialName = init.name;
528
+ this._agentId = init.agentId;
529
+ this._setStatus("idle");
530
+ this._wsUnsubscribePending = this._transport.subscribePending(
531
+ this._sessionId,
532
+ (msg) => this._handleMessage(msg)
533
+ );
534
+ } else {
535
+ this._taskId = init.taskId;
536
+ this._transport.register(init.taskId, this);
537
+ this._wsUnsubscribe = this._transport.subscribe(
538
+ init.taskId,
539
+ (msg) => this._handleMessage(msg)
540
+ );
541
+ this._initExisting(init.taskId);
542
+ }
543
+ }
544
+ // ── Properties públicas ────────────────────────────
545
+ get taskId() {
546
+ return this._taskId;
547
+ }
548
+ get task() {
549
+ return this._task;
550
+ }
551
+ get isNew() {
552
+ return this._isNew;
553
+ }
554
+ get status() {
555
+ return this._status;
556
+ }
557
+ get history() {
558
+ return this._history;
559
+ }
560
+ get content() {
561
+ return this._content;
562
+ }
563
+ get queue() {
564
+ return this._queue;
565
+ }
566
+ // ── Lifecycle ──────────────────────────────────────
567
+ async _initExisting(taskId) {
568
+ try {
569
+ await this._transport.ensureConnected();
570
+ if (this._status === "closed") return;
571
+ if (this._transport.isStreaming(taskId)) {
572
+ this._setStatus("streaming");
573
+ } else {
574
+ this._setStatus("idle");
575
+ }
576
+ } catch (err) {
577
+ this._emitError(err instanceof Error ? err.message : String(err));
578
+ }
579
+ }
580
+ async loadHistory(options) {
581
+ if (this._status === "closed") {
582
+ throw new Error("AgentTaskSession: session fechada.");
583
+ }
584
+ if (!this._taskId) {
585
+ this._history = [];
586
+ this._emit("historyLoaded", []);
587
+ return [];
588
+ }
589
+ await this._transport.ensureConnected();
590
+ const payload = { taskId: this._taskId };
591
+ if ((options == null ? void 0 : options.limit) != null) payload.limit = options.limit;
592
+ const msgs = await this._transport.request("get_history", payload);
593
+ this._history = msgs;
594
+ this._emit("historyLoaded", msgs);
595
+ return msgs;
596
+ }
597
+ close() {
598
+ if (this._status === "closed") return;
599
+ this._setStatus("closed");
600
+ if (this._turnStartedTimer) {
601
+ clearTimeout(this._turnStartedTimer);
602
+ this._turnStartedTimer = null;
603
+ }
604
+ if (this._wsUnsubscribe) {
605
+ this._wsUnsubscribe();
606
+ this._wsUnsubscribe = null;
607
+ }
608
+ if (this._wsUnsubscribePending) {
609
+ this._wsUnsubscribePending();
610
+ this._wsUnsubscribePending = null;
611
+ }
612
+ this._transport.unregister(this._taskId, this._sessionId);
613
+ this._listeners.clear();
614
+ }
615
+ // ── Comandos ───────────────────────────────────────
616
+ send(prompt, options) {
617
+ var _a, _b, _c;
618
+ if (this._status === "closed") {
619
+ throw new Error("AgentTaskSession: session fechada.");
620
+ }
621
+ if (!prompt.trim()) return;
622
+ const agentType = (_b = (_a = options == null ? void 0 : options.agentType) != null ? _a : this._agentType) != null ? _b : "claudecode";
623
+ const modelId = (_c = options == null ? void 0 : options.modelId) != null ? _c : this._modelId;
624
+ this._dispatchSend(prompt, agentType, modelId);
625
+ }
626
+ _dispatchSend(prompt, agentType, modelId) {
627
+ var _a;
628
+ if (this._status === "streaming") {
629
+ this._enqueue(prompt, agentType);
630
+ if (this._taskId) {
631
+ this._transport.send(
632
+ "send_prompt",
633
+ {
634
+ prompt,
635
+ taskId: this._taskId,
636
+ projectId: this._projectId,
637
+ agentType,
638
+ ...modelId ? { modelId } : {},
639
+ midSession: true
640
+ },
641
+ this._taskId
642
+ );
643
+ }
644
+ return;
645
+ }
646
+ if (this._status === "cancelled") {
647
+ this._awaitingTurnStarted = true;
648
+ if (this._turnStartedTimer) clearTimeout(this._turnStartedTimer);
649
+ this._turnStartedTimer = setTimeout(() => {
650
+ this._turnStartedTimer = null;
651
+ if (this._awaitingTurnStarted) {
652
+ this._cancelled = false;
653
+ this._awaitingTurnStarted = false;
654
+ this._setStatus("idle");
655
+ }
656
+ }, TURN_STARTED_SAFETY_MS);
657
+ }
658
+ this._setStatus("streaming");
659
+ this._content = "";
660
+ const payload = {
661
+ prompt,
662
+ projectId: this._projectId,
663
+ agentType
664
+ };
665
+ if (modelId) payload.modelId = modelId;
666
+ if (this._taskId) payload.taskId = this._taskId;
667
+ if (this._initialName && !this._taskId) {
668
+ payload.name = this._initialName;
669
+ }
670
+ if (this._agentId && !this._taskId) {
671
+ payload.agentId = this._agentId;
672
+ }
673
+ this._transport.send("send_prompt", payload, (_a = this._taskId) != null ? _a : void 0);
674
+ }
675
+ async cancel() {
676
+ if (this._status === "closed") return;
677
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
678
+ this._cancelled = true;
679
+ this._clearQueue();
680
+ if (this._taskId) {
681
+ this._transport.send(
682
+ "task_cancel",
683
+ { source: "sdk_cancel" },
684
+ this._taskId
685
+ );
686
+ }
687
+ this._setStatus("cancelled");
688
+ this._emit("cancelled", void 0);
689
+ return new Promise((resolve) => {
690
+ const previousResolve = this._pendingCancelResolve;
691
+ this._pendingCancelResolve = () => {
692
+ resolve();
693
+ if (previousResolve) previousResolve();
694
+ };
695
+ setTimeout(() => {
696
+ if (this._pendingCancelResolve) {
697
+ this._pendingCancelResolve = null;
698
+ resolve();
699
+ }
700
+ }, TURN_STARTED_SAFETY_MS);
701
+ });
702
+ }
703
+ // ── Manipulação de fila ────────────────────────────
704
+ editQueueItem(itemId, newText) {
705
+ const idx = this._queue.findIndex((q) => q.id === itemId);
706
+ if (idx < 0 || this._queue[idx].status !== "pending") return false;
707
+ this._queue = [
708
+ ...this._queue.slice(0, idx),
709
+ { ...this._queue[idx], text: newText },
710
+ ...this._queue.slice(idx + 1)
711
+ ];
712
+ this._emitQueueChange();
713
+ return true;
714
+ }
715
+ removeQueueItem(itemId) {
716
+ const before = this._queue.length;
717
+ this._queue = this._queue.filter((q) => q.id !== itemId);
718
+ if (this._queue.length === before) return false;
719
+ this._emitQueueChange();
720
+ return true;
721
+ }
722
+ clearQueue() {
723
+ if (this._queue.length === 0) return;
724
+ this._clearQueue();
725
+ }
726
+ // ── Eventos ────────────────────────────────────────
727
+ on(event, handler) {
728
+ if (!this._listeners.has(event)) {
729
+ this._listeners.set(event, /* @__PURE__ */ new Set());
730
+ }
731
+ this._listeners.get(event).add(handler);
732
+ return () => {
733
+ var _a;
734
+ (_a = this._listeners.get(event)) == null ? void 0 : _a.delete(handler);
735
+ };
736
+ }
737
+ // ── Internals: routing de mensagens WS ─────────────
738
+ _handleMessage(msg) {
739
+ var _a, _b, _c, _d, _e, _f;
740
+ if (!(msg == null ? void 0 : msg.type)) return;
741
+ if (this._cancelled && msg.type !== "turn_started" && msg.type !== "error" && msg.type !== "task_update") {
742
+ return;
743
+ }
744
+ const payload = (_a = msg.payload) != null ? _a : {};
745
+ switch (msg.type) {
746
+ case "task_update": {
747
+ if (payload.action !== "created") return;
748
+ const task = payload.task;
749
+ if (!task) return;
750
+ if (!this._taskId) {
751
+ this._taskId = task.id;
752
+ this._task = task;
753
+ this._transport.register(task.id, this);
754
+ if (this._wsUnsubscribePending) {
755
+ this._wsUnsubscribePending();
756
+ this._wsUnsubscribePending = null;
757
+ }
758
+ this._wsUnsubscribe = this._transport.subscribe(
759
+ task.id,
760
+ (m) => this._handleMessage(m)
761
+ );
762
+ this._emit("taskCreated", { task });
763
+ } else if (this._taskId === task.id) {
764
+ this._task = task;
765
+ }
766
+ break;
767
+ }
768
+ case "turn_started": {
769
+ if (this._cancelled) {
770
+ this._cancelled = false;
771
+ this._awaitingTurnStarted = false;
772
+ if (this._turnStartedTimer) {
773
+ clearTimeout(this._turnStartedTimer);
774
+ this._turnStartedTimer = null;
775
+ }
776
+ if (this._pendingCancelResolve) {
777
+ this._pendingCancelResolve();
778
+ this._pendingCancelResolve = null;
779
+ }
780
+ }
781
+ if (this._status !== "streaming") {
782
+ this._setStatus("streaming");
783
+ this._content = "";
784
+ }
785
+ this._emit("turnStart", void 0);
786
+ break;
787
+ }
788
+ case "stream_delta": {
789
+ const kind = payload.subtype === "thinking" ? "tool" : "text";
790
+ const delta = String((_b = payload.delta) != null ? _b : "");
791
+ if (kind === "text") this._content += delta;
792
+ this._emit("delta", { delta, kind });
793
+ break;
794
+ }
795
+ case "stream_tool_activity": {
796
+ this._emit("tool", {
797
+ tool: String((_c = payload.tool) != null ? _c : ""),
798
+ input: payload.input,
799
+ content: payload.content,
800
+ timestamp: Number((_d = msg.timestamp) != null ? _d : Date.now())
801
+ });
802
+ break;
803
+ }
804
+ case "stream_end": {
805
+ const finalContent = this._content;
806
+ this._emit("turnEnd", { content: finalContent });
807
+ this._setStatus("idle");
808
+ this._shiftQueueAndSend();
809
+ break;
810
+ }
811
+ case "error": {
812
+ const error = String((_f = (_e = payload.error) != null ? _e : msg.error) != null ? _f : "Erro desconhecido");
813
+ this._emitError(error);
814
+ break;
815
+ }
816
+ }
817
+ }
818
+ // ── Fila interna ───────────────────────────────────
819
+ _enqueue(text, agentType) {
820
+ if (this._queue.length >= QUEUE_MAX) return;
821
+ const trimmed = text.trim();
822
+ if (this._queue.some((q) => q.text.trim() === trimmed)) return;
823
+ const item = {
824
+ id: `q-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
825
+ text,
826
+ agentType,
827
+ seq: this._transport.nextSeq(),
828
+ createdAt: Date.now(),
829
+ status: "pending"
830
+ };
831
+ this._queue = [...this._queue, item];
832
+ this._emitQueueChange();
833
+ }
834
+ _shiftQueueAndSend() {
835
+ if (this._queue.length === 0) return;
836
+ const [next, ...rest] = this._queue;
837
+ this._queue = rest;
838
+ this._emitQueueChange();
839
+ this.send(next.text, { agentType: next.agentType });
840
+ }
841
+ _clearQueue() {
842
+ if (this._queue.length === 0) return;
843
+ this._queue = [];
844
+ this._emitQueueChange();
845
+ }
846
+ // ── Helpers de emissão ─────────────────────────────
847
+ _emit(event, payload) {
848
+ const set = this._listeners.get(event);
849
+ if (!set) return;
850
+ for (const handler of set) {
851
+ try {
852
+ handler(payload);
853
+ } catch (err) {
854
+ console.error(`[AgentTaskSession] handler de '${event}' lan\xE7ou:`, err);
855
+ }
856
+ }
857
+ }
858
+ _emitError(error) {
859
+ this._emit("error", { error });
860
+ this._setStatus("error");
861
+ }
862
+ _emitQueueChange() {
863
+ this._emit("queueChange", { queue: this._queue });
864
+ }
865
+ _setStatus(next) {
866
+ if (this._status === next) return;
867
+ const previous = this._status;
868
+ this._status = next;
869
+ this._emit("statusChange", { status: next, previous });
870
+ }
871
+ };
872
+
873
+ // src/agent-chat.ts
874
+ var ws = null;
875
+ var connectPromise = null;
876
+ var requestSeq = 0;
877
+ var queueSeq = 0;
878
+ var pendingRequests = /* @__PURE__ */ new Map();
879
+ var sessionsByTaskId = /* @__PURE__ */ new Map();
880
+ var handlersByTaskId = /* @__PURE__ */ new Map();
881
+ var pendingHandlers = /* @__PURE__ */ new Map();
882
+ var streamingTaskIds = /* @__PURE__ */ new Set();
883
+ function nextRequestId() {
884
+ return `req-${Date.now()}-${++requestSeq}`;
885
+ }
886
+ function nextQueueSeq() {
887
+ return ++queueSeq;
888
+ }
889
+ function getRawToken() {
890
+ const config = getConfig();
891
+ if (!config.token) {
892
+ throw new Error("Agent Chat: token n\xE3o configurado. Fa\xE7a login primeiro ou passe token em configureSdkMitra.");
893
+ }
894
+ return stripBearer(config.token);
895
+ }
896
+ function resolveProjectId(override) {
897
+ const config = getConfig();
898
+ const pid = override != null ? override : config.projectId;
899
+ if (pid == null) {
900
+ throw new Error("Agent Chat: projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
901
+ }
902
+ return pid;
903
+ }
904
+ function getWsUrl() {
905
+ const config = getConfig();
906
+ if (!config.baseURL) {
907
+ throw new Error("Agent Chat: baseURL n\xE3o configurada. Configure via configureSdkMitra({ baseURL }).");
908
+ }
909
+ const base = config.baseURL.replace(/\/+$/, "");
910
+ return base.replace(/^http/, "ws") + "/sdk-ws";
911
+ }
912
+ function connect() {
913
+ if (ws && ws.readyState === WebSocket.OPEN) {
914
+ return Promise.resolve(ws);
915
+ }
916
+ if (connectPromise) return connectPromise;
917
+ const baseUrl = getWsUrl();
918
+ const token = getRawToken();
919
+ const separator = baseUrl.includes("?") ? "&" : "?";
920
+ const url = `${baseUrl}${separator}token=${encodeURIComponent(token)}`;
921
+ connectPromise = new Promise((resolve, reject) => {
922
+ const socket = new WebSocket(url);
923
+ let opened = false;
924
+ const timer = setTimeout(() => {
925
+ if (!opened) {
926
+ try {
927
+ socket.close();
928
+ } catch (e) {
929
+ }
930
+ connectPromise = null;
931
+ reject(new Error("Agent Chat: timeout ao conectar no WebSocket"));
932
+ }
933
+ }, 15e3);
934
+ socket.onopen = () => {
935
+ opened = true;
936
+ clearTimeout(timer);
937
+ ws = socket;
938
+ connectPromise = null;
939
+ resolve(socket);
940
+ };
941
+ socket.onerror = () => {
942
+ if (!opened) {
943
+ clearTimeout(timer);
944
+ connectPromise = null;
945
+ reject(new Error("Agent Chat: erro ao conectar no WebSocket"));
946
+ }
947
+ };
948
+ socket.onclose = () => {
949
+ if (ws === socket) ws = null;
950
+ for (const [id, pending] of pendingRequests) {
951
+ pending.reject(new Error("Agent Chat: conex\xE3o fechada"));
952
+ pendingRequests.delete(id);
953
+ }
954
+ streamingTaskIds.clear();
955
+ };
956
+ socket.onmessage = (event) => routeMessage(event.data);
957
+ });
958
+ return connectPromise;
959
+ }
960
+ function routeMessage(raw) {
961
+ var _a, _b;
962
+ let msg;
963
+ try {
964
+ msg = typeof raw === "string" ? JSON.parse(raw) : raw;
965
+ } catch (e) {
966
+ return;
967
+ }
968
+ if (!(msg == null ? void 0 : msg.type)) return;
969
+ if (msg.type === "response" && msg.requestId) {
970
+ const pending = pendingRequests.get(msg.requestId);
971
+ if (!pending) return;
972
+ pendingRequests.delete(msg.requestId);
973
+ if (msg.ok) pending.resolve(msg.data);
974
+ else pending.reject(new Error(msg.error || "Erro desconhecido"));
975
+ return;
976
+ }
977
+ if (msg.type === "streaming_state") {
978
+ streamingTaskIds.clear();
979
+ const ids = (_b = (_a = msg.payload) == null ? void 0 : _a.streamingTaskIds) != null ? _b : [];
980
+ for (const id of ids) streamingTaskIds.add(id);
981
+ return;
982
+ }
983
+ if (msg.type === "turn_started" && msg.taskId) {
984
+ streamingTaskIds.add(msg.taskId);
985
+ } else if (msg.type === "stream_end" && msg.taskId) {
986
+ streamingTaskIds.delete(msg.taskId);
987
+ }
988
+ if (msg.taskId) {
989
+ const set = handlersByTaskId.get(msg.taskId);
990
+ if (set) {
991
+ for (const handler of set) handler(msg);
992
+ }
993
+ }
994
+ if (msg.type === "task_update") {
995
+ for (const handler of pendingHandlers.values()) handler(msg);
996
+ }
997
+ }
998
+ var transport = {
999
+ async ensureConnected() {
1000
+ await connect();
1001
+ },
1002
+ async request(type, payload) {
1003
+ const socket = await connect();
1004
+ const requestId = nextRequestId();
1005
+ return new Promise((resolve, reject) => {
1006
+ pendingRequests.set(requestId, {
1007
+ resolve: (data) => resolve(data),
1008
+ reject
1009
+ });
1010
+ try {
1011
+ socket.send(JSON.stringify({ type, requestId, payload }));
1012
+ } catch (err) {
1013
+ pendingRequests.delete(requestId);
1014
+ reject(err instanceof Error ? err : new Error(String(err)));
1015
+ }
1016
+ });
1017
+ },
1018
+ send(type, payload, taskId) {
1019
+ connect().then((socket) => {
1020
+ const requestId = nextRequestId();
1021
+ socket.send(JSON.stringify({ type, requestId, payload, taskId }));
1022
+ }).catch((err) => {
1023
+ console.error("[agent-chat] send falhou:", err);
1024
+ });
1025
+ },
1026
+ resolveProjectId(override) {
1027
+ return resolveProjectId(override);
1028
+ },
1029
+ nextSeq() {
1030
+ return nextQueueSeq();
1031
+ },
1032
+ subscribe(taskId, handler) {
1033
+ if (!handlersByTaskId.has(taskId)) {
1034
+ handlersByTaskId.set(taskId, /* @__PURE__ */ new Set());
1035
+ }
1036
+ handlersByTaskId.get(taskId).add(handler);
1037
+ return () => {
1038
+ const set = handlersByTaskId.get(taskId);
1039
+ if (!set) return;
1040
+ set.delete(handler);
1041
+ if (set.size === 0) handlersByTaskId.delete(taskId);
1042
+ };
1043
+ },
1044
+ subscribePending(sessionId, handler) {
1045
+ pendingHandlers.set(sessionId, handler);
1046
+ return () => {
1047
+ pendingHandlers.delete(sessionId);
1048
+ };
1049
+ },
1050
+ isStreaming(taskId) {
1051
+ return streamingTaskIds.has(taskId);
1052
+ },
1053
+ register(taskId, session) {
1054
+ sessionsByTaskId.set(taskId, session);
1055
+ },
1056
+ unregister(taskId, _sessionId) {
1057
+ if (taskId) sessionsByTaskId.delete(taskId);
1058
+ }
1059
+ };
1060
+ function getTransport() {
1061
+ return transport;
1062
+ }
1063
+ function manageAgentChatMitra(options) {
1064
+ var _a;
1065
+ if (options.action === "list") {
1066
+ const projectId = resolveProjectId(options.projectId);
1067
+ const payload = { action: "list", projectId };
1068
+ if (options.agentId) payload.agentId = options.agentId;
1069
+ return transport.request("chats", payload);
1070
+ }
1071
+ if (options.action === "rename") {
1072
+ if (!options.taskId) throw new Error("manageAgentChatMitra(rename): taskId obrigat\xF3rio.");
1073
+ if (!((_a = options.name) == null ? void 0 : _a.trim())) throw new Error("manageAgentChatMitra(rename): name obrigat\xF3rio.");
1074
+ return transport.request("chats", { action: "rename", taskId: options.taskId, name: options.name.trim() });
1075
+ }
1076
+ if (options.action === "delete") {
1077
+ if (!options.taskId) throw new Error("manageAgentChatMitra(delete): taskId obrigat\xF3rio.");
1078
+ return transport.request("chats", { action: "delete", taskId: options.taskId });
1079
+ }
1080
+ throw new Error(`manageAgentChatMitra: action inv\xE1lida (${options.action}).`);
1081
+ }
1082
+ function getAgentTaskMitra(options) {
1083
+ if ("taskId" in options && options.taskId) {
1084
+ const cached = sessionsByTaskId.get(options.taskId);
1085
+ if (cached) return cached;
1086
+ return new AgentTaskSession(
1087
+ { kind: "existing", taskId: options.taskId },
1088
+ transport
1089
+ );
1090
+ }
1091
+ if ("create" in options && options.create) {
1092
+ return new AgentTaskSession(
1093
+ {
1094
+ kind: "new",
1095
+ projectId: options.projectId,
1096
+ agentType: options.agentType,
1097
+ modelId: options.modelId,
1098
+ name: options.name,
1099
+ agentId: options.agentId
1100
+ },
1101
+ transport
1102
+ );
1103
+ }
1104
+ throw new Error("getAgentTaskMitra: passe { create: true } ou { taskId }.");
1105
+ }
1106
+
1107
+ // src/agent-credentials.ts
1108
+ var pendingVerifiers = /* @__PURE__ */ new Map();
1109
+ function manageAgentCredentialMitra(options) {
1110
+ if (options.action === "auth") return authSubscription(options);
1111
+ if (options.action === "connect") return connectSubscription(options);
1112
+ return rpc(options);
1113
+ }
1114
+ function rpc(options) {
1115
+ const transport2 = getTransport();
1116
+ const { action, target, ...rest } = options;
1117
+ const data = {};
1118
+ for (const [k, v] of Object.entries(rest)) {
1119
+ if (v !== void 0) data[k] = v;
1120
+ }
1121
+ return transport2.request("credentials", { action, target, data });
1122
+ }
1123
+ async function authSubscription(options) {
1124
+ const { target } = options;
1125
+ if (target === "claude") {
1126
+ const start = await rpc({
1127
+ action: "oauth_start",
1128
+ target: "claude"
1129
+ });
1130
+ pendingVerifiers.set(start.state, start.codeVerifier);
1131
+ return { target: "claude", authUrl: start.authUrl, state: start.state };
1132
+ }
1133
+ if (target === "codex") {
1134
+ const start = await rpc({
1135
+ action: "device_start",
1136
+ target: "codex"
1137
+ });
1138
+ return {
1139
+ target: "codex",
1140
+ userCode: start.userCode,
1141
+ verificationUrl: start.verificationUrl,
1142
+ pollId: start.pollId
1143
+ };
1144
+ }
1145
+ throw new Error(`manageAgentCredentialMitra(auth): target inv\xE1lido (${target}). Use 'claude' ou 'codex'.`);
1146
+ }
1147
+ function connectSubscription(options) {
1148
+ const { target } = options;
1149
+ if (target === "claude") return connectClaude(options);
1150
+ if (target === "codex") return connectCodex(options);
1151
+ throw new Error(`manageAgentCredentialMitra(connect): target inv\xE1lido (${target}). Use 'claude' ou 'codex'.`);
1152
+ }
1153
+ async function connectClaude(options) {
1154
+ var _a;
1155
+ const { code, state } = options;
1156
+ if (!code || !state) {
1157
+ throw new Error("manageAgentCredentialMitra(connect, claude): code e state s\xE3o obrigat\xF3rios (state vem de auth).");
1158
+ }
1159
+ const codeVerifier = pendingVerifiers.get(state);
1160
+ const exchange = await rpc({
1161
+ action: "oauth_exchange",
1162
+ target: "claude",
1163
+ code,
1164
+ state,
1165
+ // Se a SDK ainda tem o verifier (mesmo runtime), envia; senão o backend
1166
+ // resolve via state (pkceStore). Cobre os dois caminhos.
1167
+ ...codeVerifier ? { codeVerifier } : {}
1168
+ });
1169
+ pendingVerifiers.delete(state);
1170
+ return {
1171
+ target: "claude",
1172
+ success: exchange.success === true,
1173
+ expiresAt: exchange.expiresAt,
1174
+ account: (_a = exchange.account) != null ? _a : null
1175
+ };
1176
+ }
1177
+ async function connectCodex(options) {
1178
+ var _a, _b;
1179
+ const { pollId } = options;
1180
+ if (!pollId) {
1181
+ throw new Error("manageAgentCredentialMitra(connect, codex): pollId \xE9 obrigat\xF3rio (vem de auth).");
1182
+ }
1183
+ const pollInterval = (_a = options.pollIntervalMs) != null ? _a : 2e3;
1184
+ const deadline = Date.now() + ((_b = options.deviceTimeoutMs) != null ? _b : 15 * 6e4);
1185
+ while (Date.now() < deadline) {
1186
+ const result = await rpc({ action: "device_poll", target: "codex", pollId });
1187
+ if (result.status === "completed") {
1188
+ return { target: "codex", success: true };
1189
+ }
1190
+ if (result.status === "failed" || result.status === "expired" || result.status === "not_found") {
1191
+ throw new Error(`manageAgentCredentialMitra(connect, codex): ${result.status}${result.error ? ` \u2014 ${result.error}` : ""}`);
1192
+ }
1193
+ await sleep(pollInterval);
1194
+ }
1195
+ await rpc({ action: "device_cancel", target: "codex", pollId }).catch(() => {
1196
+ });
1197
+ throw new Error("manageAgentCredentialMitra(connect, codex): timeout.");
1198
+ }
1199
+ function sleep(ms) {
1200
+ return new Promise((r) => setTimeout(r, ms));
1201
+ }
1202
+
501
1203
  // src/instance.ts
502
1204
  function formatToken(token) {
503
1205
  return `Bearer ${stripBearer(token)}`;
@@ -519,7 +1221,7 @@ function createMitraInstance(initialConfig) {
519
1221
  authUrl: initialConfig.authUrl,
520
1222
  projectId: initialConfig.projectId
521
1223
  };
522
- function resolveProjectId2(projectId) {
1224
+ function resolveProjectId3(projectId) {
523
1225
  if (projectId != null) return projectId;
524
1226
  if (_config.projectId != null) return _config.projectId;
525
1227
  throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
@@ -632,12 +1334,12 @@ function createMitraInstance(initialConfig) {
632
1334
  },
633
1335
  // Services
634
1336
  async executeServerFunction(options) {
635
- const body = { projectId: resolveProjectId2(options.projectId), serverFunctionId: options.serverFunctionId };
1337
+ const body = { projectId: resolveProjectId3(options.projectId), serverFunctionId: options.serverFunctionId };
636
1338
  if (options.input !== void 0) body.input = options.input;
637
1339
  return request("POST", "/interactions/executeServerFunction", { body });
638
1340
  },
639
1341
  async executeServerFunctionAsync(options) {
640
- const body = { projectId: resolveProjectId2(options.projectId), serverFunctionId: options.serverFunctionId };
1342
+ const body = { projectId: resolveProjectId3(options.projectId), serverFunctionId: options.serverFunctionId };
641
1343
  if (options.input !== void 0) body.input = options.input;
642
1344
  return request("POST", "/interactions/executeServerFunctionAsync", { body });
643
1345
  },
@@ -675,17 +1377,17 @@ function createMitraInstance(initialConfig) {
675
1377
  },
676
1378
  async stopServerFunctionExecution(options) {
677
1379
  return request("POST", "/interactions/stopServerFunctionExecution", {
678
- body: { projectId: resolveProjectId2(options.projectId), executionId: options.executionId }
1380
+ body: { projectId: resolveProjectId3(options.projectId), executionId: options.executionId }
679
1381
  });
680
1382
  },
681
1383
  // Integrations
682
1384
  async listIntegrations(options = {}) {
683
- return request("GET", "/interactions/integrations", { params: { projectId: resolveProjectId2(options.projectId) } });
1385
+ return request("GET", "/interactions/integrations", { params: { projectId: resolveProjectId3(options.projectId) } });
684
1386
  },
685
1387
  async callIntegration(options) {
686
1388
  const body = {
687
1389
  integrationSlug: options.connection,
688
- projectId: resolveProjectId2(options.projectId),
1390
+ projectId: resolveProjectId3(options.projectId),
689
1391
  method: options.method
690
1392
  };
691
1393
  if (options.endpoint !== void 0) body.endpoint = options.endpoint;
@@ -696,38 +1398,48 @@ function createMitraInstance(initialConfig) {
696
1398
  // Dynamic Schema CRUD
697
1399
  async listRecords(options) {
698
1400
  const { tableName, page, size, filters, jdbcConnectionConfigId } = options;
699
- const pid = resolveProjectId2(options.projectId);
1401
+ const pid = resolveProjectId3(options.projectId);
700
1402
  return requestTenant("GET", `/interactions/records/${tableName}`, pid, { params: { page, size, jdbcConnectionConfigId, ...filters } });
701
1403
  },
702
1404
  async getRecord(options) {
703
1405
  const { tableName, id, jdbcConnectionConfigId } = options;
704
- const pid = resolveProjectId2(options.projectId);
1406
+ const pid = resolveProjectId3(options.projectId);
705
1407
  return requestTenant("GET", `/interactions/records/${tableName}/${id}`, pid, { params: { jdbcConnectionConfigId } });
706
1408
  },
707
1409
  async createRecord(options) {
708
1410
  const { tableName, data, jdbcConnectionConfigId } = options;
709
- const pid = resolveProjectId2(options.projectId);
1411
+ const pid = resolveProjectId3(options.projectId);
710
1412
  return requestTenant("POST", `/interactions/records/${tableName}`, pid, { body: data, params: { jdbcConnectionConfigId } });
711
1413
  },
712
1414
  async updateRecord(options) {
713
1415
  const { tableName, id, data, jdbcConnectionConfigId } = options;
714
- const pid = resolveProjectId2(options.projectId);
1416
+ const pid = resolveProjectId3(options.projectId);
715
1417
  return requestTenant("PUT", `/interactions/records/${tableName}/${id}`, pid, { body: data, params: { jdbcConnectionConfigId } });
716
1418
  },
717
1419
  async patchRecord(options) {
718
1420
  const { tableName, id, data, jdbcConnectionConfigId } = options;
719
- const pid = resolveProjectId2(options.projectId);
1421
+ const pid = resolveProjectId3(options.projectId);
720
1422
  return requestTenant("PATCH", `/interactions/records/${tableName}/${id}`, pid, { body: data, params: { jdbcConnectionConfigId } });
721
1423
  },
722
1424
  async deleteRecord(options) {
723
1425
  const { tableName, id, jdbcConnectionConfigId } = options;
724
- const pid = resolveProjectId2(options.projectId);
1426
+ const pid = resolveProjectId3(options.projectId);
725
1427
  return requestTenant("DELETE", `/interactions/records/${tableName}/${id}`, pid, { params: { jdbcConnectionConfigId } });
726
1428
  },
727
1429
  async createRecordsBatch(options) {
728
1430
  const { tableName, records, jdbcConnectionConfigId } = options;
729
- const pid = resolveProjectId2(options.projectId);
1431
+ const pid = resolveProjectId3(options.projectId);
730
1432
  return requestTenant("POST", `/interactions/records/${tableName}/batch`, pid, { body: records, params: { jdbcConnectionConfigId } });
1433
+ },
1434
+ // Agent Chat (embedded)
1435
+ getAgentTask(options) {
1436
+ return getAgentTaskMitra(options);
1437
+ },
1438
+ manageAgentChat(options) {
1439
+ return manageAgentChatMitra(options);
1440
+ },
1441
+ manageAgentCredential(options) {
1442
+ return manageAgentCredentialMitra(options);
731
1443
  }
732
1444
  };
733
1445
  return instance;
@@ -830,7 +1542,7 @@ function updateGlobalToken(token, refreshToken) {
830
1542
  if (refreshToken) persistRefreshToken(refreshToken);
831
1543
  }
832
1544
  }
833
- function resolveProjectId(projectId) {
1545
+ function resolveProjectId2(projectId) {
834
1546
  if (projectId != null) return projectId;
835
1547
  if ((globalConfig == null ? void 0 : globalConfig.projectId) != null) return globalConfig.projectId;
836
1548
  throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
@@ -1011,7 +1723,7 @@ var httpTenant = {
1011
1723
  // src/services.ts
1012
1724
  async function executeServerFunctionMitra(options) {
1013
1725
  const body = {
1014
- projectId: resolveProjectId(options.projectId),
1726
+ projectId: resolveProjectId2(options.projectId),
1015
1727
  serverFunctionId: options.serverFunctionId
1016
1728
  };
1017
1729
  if (options.input !== void 0) {
@@ -1021,7 +1733,7 @@ async function executeServerFunctionMitra(options) {
1021
1733
  }
1022
1734
  async function executeServerFunctionAsyncMitra(options) {
1023
1735
  const body = {
1024
- projectId: resolveProjectId(options.projectId),
1736
+ projectId: resolveProjectId2(options.projectId),
1025
1737
  serverFunctionId: options.serverFunctionId
1026
1738
  };
1027
1739
  if (options.input !== void 0) {
@@ -1078,13 +1790,13 @@ async function getPublicServerFunctionExecutionMitra(options) {
1078
1790
  }
1079
1791
  async function listIntegrationsMitra(options = {}) {
1080
1792
  return http.get("/interactions/integrations", {
1081
- projectId: resolveProjectId(options.projectId)
1793
+ projectId: resolveProjectId2(options.projectId)
1082
1794
  });
1083
1795
  }
1084
1796
  async function callIntegrationMitra(options) {
1085
1797
  const body = {
1086
1798
  integrationSlug: options.connection,
1087
- projectId: resolveProjectId(options.projectId),
1799
+ projectId: resolveProjectId2(options.projectId),
1088
1800
  method: options.method
1089
1801
  };
1090
1802
  if (options.endpoint !== void 0) {
@@ -1100,46 +1812,46 @@ async function callIntegrationMitra(options) {
1100
1812
  }
1101
1813
  async function stopServerFunctionExecutionMitra(options) {
1102
1814
  return http.post("/interactions/stopServerFunctionExecution", {
1103
- projectId: resolveProjectId(options.projectId),
1815
+ projectId: resolveProjectId2(options.projectId),
1104
1816
  executionId: options.executionId
1105
1817
  });
1106
1818
  }
1107
1819
  async function listRecordsMitra(options) {
1108
1820
  const { tableName, page, size, filters, jdbcConnectionConfigId } = options;
1109
- const pid = resolveProjectId(options.projectId);
1821
+ const pid = resolveProjectId2(options.projectId);
1110
1822
  return httpTenant.get(`/interactions/records/${tableName}`, pid, { page, size, jdbcConnectionConfigId, ...filters });
1111
1823
  }
1112
1824
  async function getRecordMitra(options) {
1113
1825
  const { tableName, id, jdbcConnectionConfigId } = options;
1114
- const pid = resolveProjectId(options.projectId);
1826
+ const pid = resolveProjectId2(options.projectId);
1115
1827
  return httpTenant.get(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1116
1828
  }
1117
1829
  async function createRecordMitra(options) {
1118
1830
  const { tableName, data, jdbcConnectionConfigId } = options;
1119
- const pid = resolveProjectId(options.projectId);
1831
+ const pid = resolveProjectId2(options.projectId);
1120
1832
  return httpTenant.post(`/interactions/records/${tableName}`, pid, data, { jdbcConnectionConfigId });
1121
1833
  }
1122
1834
  async function updateRecordMitra(options) {
1123
1835
  const { tableName, id, data, jdbcConnectionConfigId } = options;
1124
- const pid = resolveProjectId(options.projectId);
1836
+ const pid = resolveProjectId2(options.projectId);
1125
1837
  return httpTenant.put(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1126
1838
  }
1127
1839
  async function patchRecordMitra(options) {
1128
1840
  const { tableName, id, data, jdbcConnectionConfigId } = options;
1129
- const pid = resolveProjectId(options.projectId);
1841
+ const pid = resolveProjectId2(options.projectId);
1130
1842
  return httpTenant.patch(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1131
1843
  }
1132
1844
  async function deleteRecordMitra(options) {
1133
1845
  const { tableName, id, jdbcConnectionConfigId } = options;
1134
- const pid = resolveProjectId(options.projectId);
1846
+ const pid = resolveProjectId2(options.projectId);
1135
1847
  return httpTenant.del(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1136
1848
  }
1137
1849
  async function createRecordsBatchMitra(options) {
1138
1850
  const { tableName, records, jdbcConnectionConfigId } = options;
1139
- const pid = resolveProjectId(options.projectId);
1851
+ const pid = resolveProjectId2(options.projectId);
1140
1852
  return httpTenant.post(`/interactions/records/${tableName}/batch`, pid, records, { jdbcConnectionConfigId });
1141
1853
  }
1142
1854
 
1143
- export { callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, exchangeSsoCodeMitra2 as exchangeSsoCodeMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getConfig, getPublicServerFunctionExecutionMitra, getRecordMitra, listIntegrationsMitra, listRecordsMitra, loginMitra3 as loginMitra, loginWithGoogleMitra3 as loginWithGoogleMitra, loginWithMicrosoftMitra3 as loginWithMicrosoftMitra, patchRecordMitra, refreshTokenSilently3 as refreshTokenSilently, resolveProjectId, stopServerFunctionExecutionMitra, updateRecordMitra };
1855
+ export { callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, exchangeSsoCodeMitra2 as exchangeSsoCodeMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getPublicServerFunctionExecutionMitra, getRecordMitra, listIntegrationsMitra, listRecordsMitra, loginMitra3 as loginMitra, loginWithGoogleMitra3 as loginWithGoogleMitra, loginWithMicrosoftMitra3 as loginWithMicrosoftMitra, manageAgentChatMitra, manageAgentCredentialMitra, patchRecordMitra, refreshTokenSilently3 as refreshTokenSilently, resolveProjectId2 as resolveProjectId, stopServerFunctionExecutionMitra, updateRecordMitra };
1144
1856
  //# sourceMappingURL=index.mjs.map
1145
1857
  //# sourceMappingURL=index.mjs.map