likhonsheikh commited on
Commit
ab44170
·
verified ·
1 Parent(s): dc8a130

Create server.js

Browse files
Files changed (1) hide show
  1. server.js +96 -0
server.js ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import cors from "cors";
3
+ import { listTools, executeTool } from "./agent.js";
4
+
5
+ const app = express();
6
+ app.use(cors());
7
+ app.use(express.json({ limit: "1mb" }));
8
+
9
+ // Health + welcome
10
+ app.get("/", (_req, res) => {
11
+ res.status(200).json({
12
+ status: "ok",
13
+ service: "hf-ubuntu-agent-sse",
14
+ tools: listTools().tools.map((t) => t.name)
15
+ });
16
+ });
17
+
18
+ /**
19
+ * SSE helper
20
+ */
21
+ function openSSE(res) {
22
+ res.setHeader("Content-Type", "text/event-stream");
23
+ res.setHeader("Cache-Control", "no-cache, no-transform");
24
+ res.setHeader("Connection", "keep-alive");
25
+ res.flushHeaders?.();
26
+
27
+ const send = (event, data) => {
28
+ res.write(`event: ${event}\n`);
29
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
30
+ };
31
+
32
+ const keepAlive = setInterval(() => {
33
+ res.write(`event: ping\ndata: "ok"\n\n`);
34
+ }, 15000);
35
+
36
+ const close = () => clearInterval(keepAlive);
37
+
38
+ return { send, close };
39
+ }
40
+
41
+ /**
42
+ * List available tools (simple JSON)
43
+ */
44
+ app.get("/tools", (_req, res) => {
45
+ res.json(listTools());
46
+ });
47
+
48
+ /**
49
+ * MCP-like SSE execution endpoint:
50
+ * GET /exec?tool=shell&command=ls%20-la
51
+ * GET /exec?tool=python&code=print('hi')
52
+ *
53
+ * Body POST alternative also supported: { tool, args }
54
+ */
55
+ app.get("/exec", (req, res) => {
56
+ const { send, close } = openSSE(res);
57
+ const tool = String(req.query.tool || "");
58
+ let args = {};
59
+
60
+ if (tool === "shell") {
61
+ args = { command: String(req.query.command || "") };
62
+ } else if (tool === "python") {
63
+ args = { code: String(req.query.code || "") };
64
+ }
65
+
66
+ send("tools", listTools());
67
+
68
+ executeTool(tool, args, send);
69
+
70
+ req.on("close", () => {
71
+ close();
72
+ });
73
+ });
74
+
75
+ /**
76
+ * JSON -> SSE execution (POST), useful for programmatic clients.
77
+ * Body: { tool: "shell", args: { command: "ls -la" } }
78
+ */
79
+ app.post("/run", (req, res) => {
80
+ const { tool, args } = req.body || {};
81
+ const { send, close } = openSSE(res);
82
+
83
+ send("tools", listTools());
84
+
85
+ executeTool(tool, args, send);
86
+
87
+ req.on("close", () => {
88
+ close();
89
+ });
90
+ });
91
+
92
+ // IMPORTANT: honor HF Spaces $PORT
93
+ const PORT = process.env.PORT || 7860;
94
+ app.listen(PORT, "0.0.0.0", () => {
95
+ console.log(`Ubuntu agent running on http://0.0.0.0:${PORT}`);
96
+ });