Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { getAccessToken } from "./utils/auth-utils.js";
import { createFunctionsModule } from "./modules/functions.js";
import { createAgentsModule } from "./modules/agents.js";
import { createSuperagentModule } from "./modules/superagent.js";
import { createAiGatewayModule } from "./modules/ai-gateway.js";
import { createAppLogsModule } from "./modules/app-logs.js";
import { createUsersModule } from "./modules/users.js";
Expand Down Expand Up @@ -200,8 +201,16 @@ export function createClient(config: CreateClientConfig): Base44Client {
appId,
userAuthModule,
}),
// Deliberately not given the host app's token: superagent access is
// always anonymous against the sibling superagent app.
superagent: createSuperagentModule({
serverUrl,
headers: optionalHeaders,
onError: options?.onError,
}),
cleanup: () => {
userModules.analytics.cleanup();
userModules.superagent.cleanup();
if (socket) {
socket.disconnect();
}
Expand Down
3 changes: 3 additions & 0 deletions src/client.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
} from "./modules/connectors.types.js";
import type { FunctionsModule } from "./modules/functions.types.js";
import type { AgentsModule } from "./modules/agents.types.js";
import type { SuperagentModule } from "./modules/superagent.types.js";
import type { AiGatewayModule } from "./modules/ai-gateway.types.js";
import type { AppLogsModule } from "./modules/app-logs.types.js";
import type { AnalyticsModule } from "./modules/analytics.types.js";
Expand Down Expand Up @@ -104,6 +105,8 @@ export interface Base44Client {
functions: FunctionsModule;
/** {@link IntegrationsModule | Integrations module} for calling pre-built integration endpoints. */
integrations: IntegrationsModule;
/** {@link SuperagentModule | Superagent module} for anonymous chat with the app's linked public superagent. */
superagent: SuperagentModule;
/** Cleanup function to disconnect WebSocket connections. Call when you're done with the client. */
cleanup: () => void;

Expand Down
6 changes: 6 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,12 @@ export type {
CreateConversationParams,
} from "./modules/agents.types.js";

export type {
SuperagentModule,
SuperagentHandle,
CreateSuperagentConversationParams,
} from "./modules/superagent.types.js";

export type {
AiGatewayModule,
AiGatewayConnection,
Expand Down
162 changes: 162 additions & 0 deletions src/modules/superagent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { createAxiosClient } from "../utils/axios-client.js";
import { RoomsSocket } from "../utils/socket-utils.js";
import { ModelFilterParams } from "../types.js";
import { AgentConversation, AgentMessage } from "./agents.types.js";
import {
CreateSuperagentConversationParams,
SuperagentHandle,
SuperagentModule,
SuperagentModuleConfig,
} from "./superagent.types.js";

// A public superagent app always exposes its agent under this fixed name.
const SUPERAGENT_AGENT_NAME = "your_agent";

export function createSuperagentModule({
serverUrl,
headers,
onError,
}: SuperagentModuleConfig): SuperagentModule {
const handles: Record<string, SuperagentHandle> = {};
const sockets: Record<string, RoomsSocket> = {};

const createHandle = (appId: string): SuperagentHandle => {
const baseURL = `/apps/${appId}/agents`;

// Dedicated anonymous client for the superagent app: no Authorization
// token, so the request interceptor attaches X-Base44-Anonymous-Id and
// the backend serves the caller as an anonymous visitor of the sibling
// superagent app.
const axios = createAxiosClient({
baseURL: `${serverUrl}/api`,
headers: {
...headers,
"X-App-Id": String(appId),
},
onError,
});

const getSocket = () => {
if (!sockets[appId]) {
sockets[appId] = RoomsSocket({
config: {
serverUrl,
mountPath: "/ws-user-apps/socket.io/",
transports: ["websocket"],
appId,
anonymous: true,
},
});
}
return sockets[appId];
};

// Track active conversations
const currentConversations: Record<string, AgentConversation | undefined> =
{};

const createConversation = (
params: CreateSuperagentConversationParams = {}
) => {
return axios.post<any, AgentConversation>(`${baseURL}/conversations`, {
agent_name: SUPERAGENT_AGENT_NAME,
...params,
});
};

const listConversations = (filterParams: ModelFilterParams = {}) => {
return axios.get<any, AgentConversation[]>(`${baseURL}/conversations`, {
params: filterParams,
});
};

const getConversation = (conversationId: string) => {
return axios.get<any, AgentConversation | undefined>(
`${baseURL}/conversations/${conversationId}`
);
};

const addMessage = async (
conversation: AgentConversation,
message: Partial<AgentMessage>
) => {
return axios.post<any, AgentMessage>(
`${baseURL}/conversations/v2/${conversation.id}/messages`,
message
);
};

const subscribeToConversation = (
conversationId: string,
onUpdate?: (conversation: AgentConversation) => void
) => {
const room = `/agent-conversations/${conversationId}`;
const socket = getSocket();

// Store the promise for initial conversation state
const conversationPromise = getConversation(conversationId).then(
(conv) => {
currentConversations[conversationId] = conv;
return conv;
}
);

return socket.subscribeToRoom(room, {
connect: () => {},
update_model: async ({ data: jsonStr }) => {
const data = JSON.parse(jsonStr);

if (data._message) {
// Wait for initial conversation to be loaded
await conversationPromise;
const message = data._message as AgentMessage;

// Update shared conversation state
const currentConversation = currentConversations[conversationId];
if (currentConversation) {
const messages = currentConversation.messages || [];
const existingIndex = messages.findIndex(
(m) => m.id === message.id
);

const updatedMessages =
existingIndex !== -1
? messages.map((m, i) => (i === existingIndex ? message : m))
: [...messages, message];

currentConversations[conversationId] = {
...currentConversation,
messages: updatedMessages,
};
onUpdate?.(currentConversations[conversationId]!);
}
}
},
});
};

return {
createConversation,
listConversations,
getConversation,
addMessage,
subscribeToConversation,
};
};

const forApp = (appId: string) => {
if (!handles[appId]) {
handles[appId] = createHandle(appId);
}
return handles[appId];
};

const cleanup = () => {
Object.values(sockets).forEach((socket) => socket.disconnect());
};

return {
forApp,
cleanup,
};
}
Loading
Loading