You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.8 KiB

11 months ago
  1. const { Telemetry } = require("../models/telemetry");
  2. const {
  3. WorkspaceAgentInvocation,
  4. } = require("../models/workspaceAgentInvocation");
  5. const { AgentHandler } = require("../utils/agents");
  6. const {
  7. WEBSOCKET_BAIL_COMMANDS,
  8. } = require("../utils/agents/aibitat/plugins/websocket");
  9. const { safeJsonParse } = require("../utils/http");
  10. // Setup listener for incoming messages to relay to socket so it can be handled by agent plugin.
  11. function relayToSocket(message) {
  12. if (this.handleFeedback) return this?.handleFeedback?.(message);
  13. this.checkBailCommand(message);
  14. }
  15. function agentWebsocket(app) {
  16. if (!app) return;
  17. app.ws("/agent-invocation/:uuid", async function (socket, request) {
  18. try {
  19. const agentHandler = await new AgentHandler({
  20. uuid: String(request.params.uuid),
  21. }).init();
  22. if (!agentHandler.invocation) {
  23. socket.close();
  24. return;
  25. }
  26. socket.on("message", relayToSocket);
  27. socket.on("close", () => {
  28. agentHandler.closeAlert();
  29. WorkspaceAgentInvocation.close(String(request.params.uuid));
  30. return;
  31. });
  32. socket.checkBailCommand = (data) => {
  33. const content = safeJsonParse(data)?.feedback;
  34. if (WEBSOCKET_BAIL_COMMANDS.includes(content)) {
  35. agentHandler.log(
  36. `User invoked bail command while processing. Closing session now.`
  37. );
  38. agentHandler.aibitat.abort();
  39. socket.close();
  40. return;
  41. }
  42. };
  43. await Telemetry.sendTelemetry("agent_chat_started");
  44. await agentHandler.createAIbitat({ socket });
  45. await agentHandler.startAgentCluster();
  46. } catch (e) {
  47. console.error(e.message, e);
  48. socket?.send(JSON.stringify({ type: "wssFailure", content: e.message }));
  49. socket?.close();
  50. }
  51. });
  52. }
  53. module.exports = { agentWebsocket };