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