-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheggshell.ts
220 lines (179 loc) · 5.65 KB
/
eggshell.ts
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
215
216
217
218
219
220
import { writeText } from "https://deno.land/x/[email protected]/mod.ts";
import { stripColor } from "https://deno.land/[email protected]/fmt/colors.ts";
const apiKey = Deno.env.get("OPENAI_API_KEY");
async function fetchGeneratedCommand(
prompt: string,
recording: string | null
): Promise<string> {
const messages = [
{
role: "system",
content:
"You are the AI backend for an AI powered terminal. You receive a recording of a shell and additionall a natural language request and you must figure out an executable bash command that gets the request done. It is extremely important that the response is always and executable command for the ubuntu terminal.",
},
];
if (recording) {
messages.push({ role: "user", content: recording });
}
messages.push({ role: "user", content: prompt });
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
messages,
max_tokens: 1000,
n: 1,
stop: null,
temperature: 0.5,
model: "gpt-4",
}),
});
const data = await response.json();
if (data.choices && data.choices.length > 0) {
return data.choices[0].message.content;
} else {
console.log(data);
throw new Error("No generated command found");
}
}
// RECORDING MANAGEMENT
async function getParentPid(pid: number): Promise<number | null> {
try {
// deno-lint-ignore no-deprecated-deno-api
const process = Deno.run({
cmd: ["ps", "-o", "ppid=", "-p", `${pid}`],
stdout: "piped",
stderr: "piped",
});
const output = await process.output();
const error = await process.stderrOutput();
if (error.length > 0) {
throw new TextDecoder().decode(error);
}
const parentPid = parseInt(new TextDecoder().decode(output).trim());
return isNaN(parentPid) ? null : parentPid;
} catch (error) {
console.error(`Error getting parent PID: ${error}`);
return null;
}
}
async function getAllAncestorPids(pid: number): Promise<number[]> {
const ancestorPids: number[] = [];
let parentPid = await getParentPid(pid);
while (parentPid) {
ancestorPids.push(parentPid);
parentPid = await getParentPid(parentPid);
}
return ancestorPids;
}
const exists = async (filename: string): Promise<boolean> => {
try {
await Deno.stat(filename);
// successful, file or directory must exist
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
// file or directory does not exist
return false;
} else {
// unexpected error, maybe permissions, pass it along
throw error;
}
}
};
async function findRecording(pids: number[]): Promise<string | null> {
for (const pid of pids) {
// checks if $HOME/eggshell/.recordings/$pids exists
const recordingPath = `${Deno.env.get(
"EGGSHELL_PATH"
)}/.recordings/${pid}.txt`;
if (await exists(recordingPath)) {
return recordingPath;
}
}
return Promise.resolve(null);
}
function pidFromRecording(recording: string): string | null {
const pid = recording.split("/").pop()?.split(".")[0];
return pid ?? null;
}
async function recordingFromPath(recordingPath: string) {
const text = await Deno.readTextFile(recordingPath);
return stripColor(text);
}
// SESSION MANAGEMENT
async function getSession(recordingPath: string) {
const pid = pidFromRecording(recordingPath);
if (!pid) {
return;
}
const sessionPath = `${Deno.env.get(
"EGGSHELL_PATH"
)}/.recordings/.session_${pid}`;
const sessionExists = await exists(sessionPath);
if (!sessionExists) {
await Deno.create(sessionPath);
await Deno.writeTextFile(sessionPath, JSON.stringify({ anchor: 0 }), {
create: true,
});
}
const sessionFile = await Deno.readTextFile(sessionPath);
const session = JSON.parse(sessionFile);
const recording = await recordingFromPath(recordingPath);
const recordingLines = recording.split("\n");
return {
anchor: session.anchor,
lines: recordingLines.slice(session.anchor),
};
}
async function forgetSession(recordingPath: string) {
const pid = pidFromRecording(recordingPath);
if (!pid) {
return;
}
const sessionPath = `${Deno.env.get(
"EGGSHELL_PATH"
)}/.recordings/.session_${pid}`;
const sessionExists = await exists(sessionPath);
if (!sessionExists) {
await Deno.create(sessionPath);
await Deno.writeTextFile(sessionPath, JSON.stringify({ anchor: 0 }), {
create: true,
});
}
//set anchor to be the index of the last line of the session
const sessionFile = await Deno.readTextFile(sessionPath);
const session = JSON.parse(sessionFile);
const recording = await Deno.readTextFile(recordingPath);
const recordingLines = recording.split("\n");
session.anchor = recordingLines.length;
await Deno.writeTextFile(sessionPath, JSON.stringify(session));
}
async function handler() {
const currentPid = Deno.pid;
const ancestorPids = await getAllAncestorPids(currentPid);
const recordingPath = await findRecording(ancestorPids);
if (!recordingPath) {
return;
}
const isReset = Deno.args[0] === "-c" && Deno.args.length === 1;
if (isReset) {
await forgetSession(recordingPath);
return;
}
const session = await getSession(recordingPath);
const prompt = Deno.args.join(" ");
const generatedCommand = await fetchGeneratedCommand(
prompt,
session?.lines.join("\n") ?? ""
);
if (generatedCommand.length > 120 && !generatedCommand.startsWith("echo")) {
console.log(generatedCommand);
} else {
writeText(generatedCommand);
}
}
handler();