-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
214 lines (196 loc) · 6.14 KB
/
Copy pathapi.py
File metadata and controls
214 lines (196 loc) · 6.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import asyncio
import json
import sqlite3
import struct
import sys
import termios
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from pydantic import BaseModel
import os
import pty
import signal
import fcntl
from fastapi.middleware.cors import CORSMiddleware
shell_pids = set()
class TelemetryE(BaseModel):
timestamp: int
cmd: str
exit_code: int
cwd: str
duration_ms: int
def init_db():
db_path = os.path.join(os.environ.get("HOME", "."), ".myshell_data.db")
con = sqlite3.connect(db_path)
cur = con.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS telemetry(
id INTEGER PRIMARY KEY,
timestamp INTEGER,
cmd TEXT,
cwd TEXT,
exit_code INTEGER,
duration_ms INTEGER);""")
con.commit()
con.close()
def get_transition():
transitions={}
db_path = os.path.join(os.environ.get("HOME", "."), ".myshell_data.db")
con = sqlite3.connect(db_path)
cur= con.cursor()
cur.execute(""" SELECT cmd
FROM telemetry
ORDER BY timestamp ASC;
""")
rows = cur.fetchall()
for i in range(len(rows)-1):
cmd_a = rows[i][0]
cmd_b = rows[i+1][0]
if cmd_a not in transitions:
transitions[cmd_a] = {}
if cmd_b not in transitions[cmd_a]:
transitions[cmd_a][cmd_b] = 0
transitions[cmd_a][cmd_b] += 1
return transitions
def stats_query():
db_path = os.path.join(os.environ.get("HOME", "."), ".myshell_data.db")
con = sqlite3.connect(db_path)
cur= con.cursor()
cur.execute("""SELECT cmd, COUNT(*) as count
FROM telemetry
GROUP BY cmd
ORDER BY count DESC
LIMIT 5;""")
rows= cur.fetchall()
con.close()
return [{"cmd": r[0], "count": r[1]} for r in rows]
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://cloud-shell-sigma.vercel.app"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
def startup():
init_db()
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/log")
def log_command(entry: TelemetryE):
log_data = entry.model_dump()
db_path = os.path.join(os.environ.get("HOME", "."), ".myshell_data.db")
con = sqlite3.connect(db_path)
cur= con.cursor()
cur.execute("""
INSERT INTO telemetry (timestamp, cmd, cwd, exit_code, duration_ms)
VALUES (?, ?, ?, ?, ?)
""", (
log_data["timestamp"],
log_data["cmd"],
log_data["cwd"],
log_data["exit_code"],
log_data["duration_ms"]
))
con.commit()
con.close()
return {"status": "success", "message": "Command logged successfully"}
@app.get("/stats")
def stats():
return stats_query()
@app.post("/predict")
def predict_next_command(current_context: TelemetryE):
data = get_transition()
print(data)
next_cmds = data.get(current_context.cmd, {})
if next_cmds:
prediction = max(next_cmds, key=next_cmds.get)
else:
prediction = "ls"
return {
"current_cwd": current_context.cwd,
"predicted_next_cmd": prediction
}
@app.websocket("/terminal")
async def terminal(websocket: WebSocket):
origin = websocket.headers.get("origin", "")
allowed = ["https://cloud-shell-sigma.vercel.app", "http://localhost:3000"]
if origin not in allowed:
await websocket.close(code=1008)
return
await websocket.accept()
pid, fd = pty.fork()
if pid == 0:
try:
shell_path = os.environ.get("MOCK_SHELL_PATH", "/bin/bash")
os.execv(shell_path, [shell_path])
except:
os._exit(1)
shell_pids.add(pid)
fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)
async def read_pty():
while True:
try:
data = os.read(fd, 1024)
if data:
await websocket.send_text(
data.decode(errors="ignore")
)
else:
break
except BlockingIOError:
await asyncio.sleep(0.01)
except:
break
reader = asyncio.create_task(read_pty())
try:
while True:
receive_task = asyncio.create_task(websocket.receive_text())
done, pending = await asyncio.wait({reader, receive_task}, return_when=asyncio.FIRST_COMPLETED)
if reader in done:
receive_task.cancel()
break
message = receive_task.result()
try:
msg = json.loads(message)
if isinstance(msg, dict) and msg.get("type") == "resize":
try:
fcntl.ioctl(fd,
termios.TIOCSWINSZ,
struct.pack("HHHH",msg["rows"],msg["cols"],0,0))
except:
pass
else:
os.write(fd, message.encode())
except json.JSONDecodeError:
try:
os.write(fd, message.encode())
except:
break
except WebSocketDisconnect:
print("Client disconnected")
finally:
reader.cancel()
try:
os.kill(pid, signal.SIGKILL)
except:
pass
try:
os.close(fd)
except:
pass
try:
shell_pids.discard(pid)
except:
pass
try:
await websocket.close()
except:
pass
@app.on_event("shutdown")
def shutdown():
for pid in list(shell_pids):
try:
os.kill(pid, signal.SIGKILL)
except:
pass