wcgw 0.2.0__py3-none-any.whl → 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of wcgw might be problematic. Click here for more details.
- wcgw/__init__.py +2 -2
- wcgw/client/__main__.py +3 -0
- wcgw/{basic.py → client/basic.py} +16 -12
- wcgw/{tools.py → client/tools.py} +243 -132
- wcgw/relay/serve.py +326 -0
- wcgw/relay/static/privacy.txt +7 -0
- wcgw/types_.py +37 -0
- {wcgw-0.2.0.dist-info → wcgw-1.0.0.dist-info}/METADATA +6 -3
- wcgw-1.0.0.dist-info/RECORD +15 -0
- {wcgw-0.2.0.dist-info → wcgw-1.0.0.dist-info}/entry_points.txt +1 -0
- wcgw/__main__.py +0 -3
- wcgw-0.2.0.dist-info/RECORD +0 -12
- /wcgw/{claude.py → client/claude.py} +0 -0
- /wcgw/{common.py → client/common.py} +0 -0
- /wcgw/{openai_adapters.py → client/openai_adapters.py} +0 -0
- /wcgw/{openai_utils.py → client/openai_utils.py} +0 -0
- {wcgw-0.2.0.dist-info → wcgw-1.0.0.dist-info}/WHEEL +0 -0
wcgw/__init__.py
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
from .basic import app, loop
|
|
2
|
-
from .tools import run as listen
|
|
1
|
+
from .client.basic import app, loop
|
|
2
|
+
from .client.tools import run as listen
|
wcgw/client/__main__.py
ADDED
|
@@ -20,16 +20,15 @@ import petname # type: ignore[import-untyped]
|
|
|
20
20
|
from typer import Typer
|
|
21
21
|
import uuid
|
|
22
22
|
|
|
23
|
+
from ..types_ import BashCommand, BashInteraction, ReadImage, Writefile, ResetShell
|
|
24
|
+
|
|
23
25
|
from .common import Models, discard_input
|
|
24
26
|
from .common import CostData, History
|
|
25
27
|
from .openai_utils import get_input_cost, get_output_cost
|
|
26
|
-
from .tools import
|
|
28
|
+
from .tools import ImageData
|
|
27
29
|
|
|
28
30
|
from .tools import (
|
|
29
|
-
BASH_CLF_OUTPUT,
|
|
30
|
-
Confirmation,
|
|
31
31
|
DoneFlag,
|
|
32
|
-
Writefile,
|
|
33
32
|
get_tool_output,
|
|
34
33
|
SHELL,
|
|
35
34
|
start_shell,
|
|
@@ -156,27 +155,32 @@ def loop(
|
|
|
156
155
|
|
|
157
156
|
tools = [
|
|
158
157
|
openai.pydantic_function_tool(
|
|
159
|
-
|
|
158
|
+
BashCommand,
|
|
160
159
|
description="""
|
|
161
|
-
- Execute a bash
|
|
162
|
-
- Execute commands using `execute_command` attribute. You can run python/node/other REPL code lines using `execute_command` too.
|
|
160
|
+
- Execute a bash command. This is stateful (beware with subsequent calls).
|
|
163
161
|
- Do not use interactive commands like nano. Prefer writing simpler commands.
|
|
164
|
-
-
|
|
165
|
-
- The last line is `(pending)` if the program is still running or waiting for your input. You can then send input using `send_ascii` attributes. You get status by sending new line `send_ascii: ["Enter"]` or `send_ascii: [10]`.
|
|
166
|
-
- Optionally the last line is `(won't exit)` in which case you need to kill the process if you want to run a new command.
|
|
162
|
+
- Status of the command and the current working directory will always be returned at the end.
|
|
167
163
|
- Optionally `exit shell has restarted` is the output, in which case environment resets, you can run fresh commands.
|
|
168
164
|
- The first line might be `(...truncated)` if the output is too long.
|
|
169
165
|
- Always run `pwd` if you get any file or directory not found error to make sure you're not lost.
|
|
170
|
-
- You can run python/node/other REPL code lines using `execute_command` too. NOTE: `execute_command` doesn't create a new shell, it uses the same shell.
|
|
171
166
|
""",
|
|
167
|
+
),
|
|
168
|
+
openai.pydantic_function_tool(
|
|
169
|
+
BashInteraction,
|
|
170
|
+
description="""
|
|
171
|
+
- Interact with running program using this tool.""",
|
|
172
172
|
),
|
|
173
173
|
openai.pydantic_function_tool(
|
|
174
174
|
Writefile,
|
|
175
|
-
description="Write content to a file. Provide file path and content. Use this instead of
|
|
175
|
+
description="Write content to a file. Provide file path and content. Use this instead of BashCommand for writing files.",
|
|
176
176
|
),
|
|
177
177
|
openai.pydantic_function_tool(
|
|
178
178
|
ReadImage, description="Read an image from the shell."
|
|
179
179
|
),
|
|
180
|
+
openai.pydantic_function_tool(
|
|
181
|
+
ResetShell,
|
|
182
|
+
description="Resets the shell. Use only if all interrupts and prompt reset attempts have failed repeatedly.",
|
|
183
|
+
),
|
|
180
184
|
]
|
|
181
185
|
uname_sysname = os.uname().sysname
|
|
182
186
|
uname_machine = os.uname().machine
|
|
@@ -5,6 +5,7 @@ import mimetypes
|
|
|
5
5
|
import re
|
|
6
6
|
import sys
|
|
7
7
|
import threading
|
|
8
|
+
import importlib.metadata
|
|
8
9
|
import traceback
|
|
9
10
|
from typing import (
|
|
10
11
|
Callable,
|
|
@@ -12,12 +13,12 @@ from typing import (
|
|
|
12
13
|
NewType,
|
|
13
14
|
Optional,
|
|
14
15
|
ParamSpec,
|
|
15
|
-
Sequence,
|
|
16
16
|
TypeVar,
|
|
17
17
|
TypedDict,
|
|
18
18
|
)
|
|
19
19
|
import uuid
|
|
20
20
|
from pydantic import BaseModel, TypeAdapter
|
|
21
|
+
import typer
|
|
21
22
|
from websockets.sync.client import connect as syncconnect
|
|
22
23
|
|
|
23
24
|
import os
|
|
@@ -39,6 +40,14 @@ from openai.types.chat import (
|
|
|
39
40
|
ChatCompletionMessage,
|
|
40
41
|
ParsedChatCompletionMessage,
|
|
41
42
|
)
|
|
43
|
+
from nltk.metrics.distance import edit_distance
|
|
44
|
+
from ..types_ import FileEditFindReplace, ResetShell, Writefile
|
|
45
|
+
|
|
46
|
+
from ..types_ import BashCommand
|
|
47
|
+
|
|
48
|
+
from ..types_ import BashInteraction
|
|
49
|
+
|
|
50
|
+
from ..types_ import ReadImage
|
|
42
51
|
|
|
43
52
|
from .common import CostData, Models, discard_input
|
|
44
53
|
|
|
@@ -73,15 +82,10 @@ def ask_confirmation(prompt: Confirmation) -> str:
|
|
|
73
82
|
return "Yes" if response.lower() == "y" else "No"
|
|
74
83
|
|
|
75
84
|
|
|
76
|
-
class Writefile(BaseModel):
|
|
77
|
-
file_path: str
|
|
78
|
-
file_content: str
|
|
79
|
-
|
|
80
|
-
|
|
81
85
|
PROMPT = "#@@"
|
|
82
86
|
|
|
83
87
|
|
|
84
|
-
def start_shell() -> pexpect.spawn:
|
|
88
|
+
def start_shell() -> pexpect.spawn: # type: ignore
|
|
85
89
|
SHELL = pexpect.spawn(
|
|
86
90
|
"/bin/bash --noprofile --norc",
|
|
87
91
|
env={**os.environ, **{"PS1": PROMPT}}, # type: ignore[arg-type]
|
|
@@ -133,22 +137,26 @@ def _get_exit_code() -> int:
|
|
|
133
137
|
raise ValueError(f"Malformed output: {before}")
|
|
134
138
|
|
|
135
139
|
|
|
136
|
-
|
|
137
|
-
|
|
140
|
+
BASH_CLF_OUTPUT = Literal["repl", "pending"]
|
|
141
|
+
BASH_STATE: BASH_CLF_OUTPUT = "repl"
|
|
142
|
+
CWD = os.getcwd()
|
|
138
143
|
|
|
139
|
-
class ExecuteBash(BaseModel):
|
|
140
|
-
execute_command: Optional[str] = None
|
|
141
|
-
send_ascii: Optional[Sequence[int | Specials]] = None
|
|
142
144
|
|
|
145
|
+
def reset_shell() -> str:
|
|
146
|
+
global SHELL, BASH_STATE, CWD
|
|
147
|
+
SHELL.close(True)
|
|
148
|
+
SHELL = start_shell()
|
|
149
|
+
BASH_STATE = "repl"
|
|
150
|
+
CWD = os.getcwd()
|
|
151
|
+
return "Reset successful" + get_status()
|
|
143
152
|
|
|
144
|
-
BASH_CLF_OUTPUT = Literal["running", "waiting_for_input", "wont_exit"]
|
|
145
|
-
BASH_STATE: BASH_CLF_OUTPUT = "running"
|
|
146
153
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
154
|
+
WAITING_INPUT_MESSAGE = """A command is already running. NOTE: You can't run multiple shell sessions, likely a previous program hasn't exited.
|
|
155
|
+
1. Get its output using `send_ascii: [10] or send_specials: ["Enter"]`
|
|
156
|
+
2. Use `send_ascii` or `send_specials` to give inputs to the running program, don't use `BashCommand` OR
|
|
157
|
+
3. kill the previous program by sending ctrl+c first using `send_ascii` or `send_specials`
|
|
158
|
+
4. Send the process in background using `send_specials: ["Ctrl-z"]` followed by BashCommand: `bg`
|
|
159
|
+
"""
|
|
152
160
|
|
|
153
161
|
|
|
154
162
|
def update_repl_prompt(command: str) -> bool:
|
|
@@ -173,45 +181,66 @@ def update_repl_prompt(command: str) -> bool:
|
|
|
173
181
|
return False
|
|
174
182
|
|
|
175
183
|
|
|
184
|
+
def get_cwd() -> str:
|
|
185
|
+
SHELL.sendline("pwd")
|
|
186
|
+
SHELL.expect(PROMPT)
|
|
187
|
+
assert isinstance(SHELL.before, str)
|
|
188
|
+
current_dir = render_terminal_output(SHELL.before).strip()
|
|
189
|
+
return current_dir
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def get_status() -> str:
|
|
193
|
+
global CWD
|
|
194
|
+
exit_code: Optional[int] = None
|
|
195
|
+
|
|
196
|
+
status = "\n\n---\n\n"
|
|
197
|
+
if BASH_STATE == "pending":
|
|
198
|
+
status += "status = still running\n"
|
|
199
|
+
status += "cwd = " + CWD + "\n"
|
|
200
|
+
else:
|
|
201
|
+
exit_code = _get_exit_code()
|
|
202
|
+
status += f"status = exited with code {exit_code}\n"
|
|
203
|
+
CWD = get_cwd()
|
|
204
|
+
status += "cwd = " + CWD + "\n"
|
|
205
|
+
|
|
206
|
+
return status.rstrip()
|
|
207
|
+
|
|
208
|
+
|
|
176
209
|
def execute_bash(
|
|
177
|
-
enc: tiktoken.Encoding,
|
|
210
|
+
enc: tiktoken.Encoding,
|
|
211
|
+
bash_arg: BashCommand | BashInteraction,
|
|
212
|
+
max_tokens: Optional[int],
|
|
178
213
|
) -> tuple[str, float]:
|
|
179
|
-
global SHELL, BASH_STATE
|
|
214
|
+
global SHELL, BASH_STATE, CWD
|
|
180
215
|
try:
|
|
181
216
|
is_interrupt = False
|
|
182
|
-
if bash_arg
|
|
183
|
-
updated_repl_mode = update_repl_prompt(bash_arg.
|
|
217
|
+
if isinstance(bash_arg, BashCommand):
|
|
218
|
+
updated_repl_mode = update_repl_prompt(bash_arg.command)
|
|
184
219
|
if updated_repl_mode:
|
|
185
|
-
BASH_STATE = "
|
|
186
|
-
response =
|
|
220
|
+
BASH_STATE = "repl"
|
|
221
|
+
response = (
|
|
222
|
+
"Prompt updated, you can execute REPL lines using BashCommand now"
|
|
223
|
+
)
|
|
187
224
|
console.print(response)
|
|
188
225
|
return (
|
|
189
226
|
response,
|
|
190
227
|
0,
|
|
191
228
|
)
|
|
192
229
|
|
|
193
|
-
console.print(f"$ {bash_arg.
|
|
194
|
-
if BASH_STATE == "
|
|
230
|
+
console.print(f"$ {bash_arg.command}")
|
|
231
|
+
if BASH_STATE == "pending":
|
|
195
232
|
raise ValueError(WAITING_INPUT_MESSAGE)
|
|
196
|
-
|
|
197
|
-
raise ValueError(
|
|
198
|
-
"""A command is already running that hasn't exited. NOTE: You can't run multiple shell sessions, likely a previous program is in infinite loop.
|
|
199
|
-
Kill the previous program by sending ctrl+c first using `send_ascii`"""
|
|
200
|
-
)
|
|
201
|
-
command = bash_arg.execute_command.strip()
|
|
233
|
+
command = bash_arg.command.strip()
|
|
202
234
|
|
|
203
235
|
if "\n" in command:
|
|
204
236
|
raise ValueError(
|
|
205
237
|
"Command should not contain newline character in middle. Run only one command at a time."
|
|
206
238
|
)
|
|
239
|
+
|
|
207
240
|
SHELL.sendline(command)
|
|
208
|
-
elif bash_arg.
|
|
209
|
-
console.print(f"Sending
|
|
210
|
-
for char in bash_arg.
|
|
211
|
-
if isinstance(char, int):
|
|
212
|
-
SHELL.send(chr(char))
|
|
213
|
-
if char == 3:
|
|
214
|
-
is_interrupt = True
|
|
241
|
+
elif bash_arg.send_specials:
|
|
242
|
+
console.print(f"Sending special sequence: {bash_arg.send_specials}")
|
|
243
|
+
for char in bash_arg.send_specials:
|
|
215
244
|
if char == "Key-up":
|
|
216
245
|
SHELL.send("\033[A")
|
|
217
246
|
elif char == "Key-down":
|
|
@@ -225,21 +254,52 @@ def execute_bash(
|
|
|
225
254
|
elif char == "Ctrl-c":
|
|
226
255
|
SHELL.sendintr()
|
|
227
256
|
is_interrupt = True
|
|
257
|
+
elif char == "Ctrl-d":
|
|
258
|
+
SHELL.sendintr()
|
|
259
|
+
is_interrupt = True
|
|
260
|
+
elif char == "Ctrl-z":
|
|
261
|
+
SHELL.send("\x1a")
|
|
262
|
+
else:
|
|
263
|
+
raise Exception(f"Unknown special character: {char}")
|
|
264
|
+
elif bash_arg.send_ascii:
|
|
265
|
+
console.print(f"Sending ASCII sequence: {bash_arg.send_ascii}")
|
|
266
|
+
for ascii_char in bash_arg.send_ascii:
|
|
267
|
+
SHELL.send(chr(ascii_char))
|
|
268
|
+
if ascii_char == 3:
|
|
269
|
+
is_interrupt = True
|
|
228
270
|
else:
|
|
229
|
-
|
|
230
|
-
|
|
271
|
+
if bash_arg.send_text is None:
|
|
272
|
+
return (
|
|
273
|
+
"Failure: at least one of send_text, send_specials or send_ascii should be provided",
|
|
274
|
+
0.0,
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
updated_repl_mode = update_repl_prompt(bash_arg.send_text)
|
|
278
|
+
if updated_repl_mode:
|
|
279
|
+
BASH_STATE = "repl"
|
|
280
|
+
response = (
|
|
281
|
+
"Prompt updated, you can execute REPL lines using BashCommand now"
|
|
282
|
+
)
|
|
283
|
+
console.print(response)
|
|
284
|
+
return (
|
|
285
|
+
response,
|
|
286
|
+
0,
|
|
287
|
+
)
|
|
288
|
+
console.print(f"Interact text: {bash_arg.send_text}")
|
|
289
|
+
SHELL.sendline(bash_arg.send_text)
|
|
290
|
+
|
|
291
|
+
BASH_STATE = "repl"
|
|
231
292
|
|
|
232
293
|
except KeyboardInterrupt:
|
|
233
|
-
SHELL.
|
|
234
|
-
SHELL
|
|
235
|
-
|
|
294
|
+
SHELL.sendintr()
|
|
295
|
+
SHELL.expect(PROMPT)
|
|
296
|
+
return "---\n\nFailure: user interrupted the execution", 0.0
|
|
236
297
|
|
|
237
298
|
wait = 5
|
|
238
299
|
index = SHELL.expect([PROMPT, pexpect.TIMEOUT], timeout=wait)
|
|
239
300
|
if index == 1:
|
|
240
|
-
BASH_STATE = "
|
|
301
|
+
BASH_STATE = "pending"
|
|
241
302
|
text = SHELL.before or ""
|
|
242
|
-
print(text)
|
|
243
303
|
|
|
244
304
|
text = render_terminal_output(text)
|
|
245
305
|
tokens = enc.encode(text)
|
|
@@ -247,23 +307,26 @@ def execute_bash(
|
|
|
247
307
|
if max_tokens and len(tokens) >= max_tokens:
|
|
248
308
|
text = "...(truncated)\n" + enc.decode(tokens[-(max_tokens - 1) :])
|
|
249
309
|
|
|
250
|
-
last_line = "(pending)"
|
|
251
|
-
text = text + f"\n{last_line}"
|
|
252
|
-
|
|
253
310
|
if is_interrupt:
|
|
254
311
|
text = (
|
|
255
312
|
text
|
|
256
|
-
+ """
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
313
|
+
+ """---
|
|
314
|
+
----
|
|
315
|
+
Failure interrupting.
|
|
316
|
+
If any REPL session was previously running or if bashrc was sourced, or if there is issue to other REPL related reasons:
|
|
317
|
+
Run BashCommand: "wcgw_update_prompt()" to reset the PS1 prompt.
|
|
318
|
+
Otherwise, you may want to try Ctrl-c again or program specific exit interactive commands.
|
|
262
319
|
"""
|
|
263
320
|
)
|
|
264
321
|
|
|
322
|
+
exit_status = get_status()
|
|
323
|
+
text += exit_status
|
|
324
|
+
|
|
265
325
|
return text, 0
|
|
266
326
|
|
|
327
|
+
if is_interrupt:
|
|
328
|
+
return "Interrupt successful", 0.0
|
|
329
|
+
|
|
267
330
|
assert isinstance(SHELL.before, str)
|
|
268
331
|
output = render_terminal_output(SHELL.before)
|
|
269
332
|
|
|
@@ -272,9 +335,8 @@ If no:
|
|
|
272
335
|
output = "...(truncated)\n" + enc.decode(tokens[-(max_tokens - 1) :])
|
|
273
336
|
|
|
274
337
|
try:
|
|
275
|
-
|
|
276
|
-
output +=
|
|
277
|
-
|
|
338
|
+
exit_status = get_status()
|
|
339
|
+
output += exit_status
|
|
278
340
|
except ValueError as e:
|
|
279
341
|
console.print(output)
|
|
280
342
|
traceback.print_exc()
|
|
@@ -286,11 +348,6 @@ If no:
|
|
|
286
348
|
return output, 0
|
|
287
349
|
|
|
288
350
|
|
|
289
|
-
class ReadImage(BaseModel):
|
|
290
|
-
file_path: str
|
|
291
|
-
type: Literal["ReadImage"] = "ReadImage"
|
|
292
|
-
|
|
293
|
-
|
|
294
351
|
def serve_image_in_bg(file_path: str, client_uuid: str, name: str) -> None:
|
|
295
352
|
if not client_uuid:
|
|
296
353
|
client_uuid = str(uuid.uuid4())
|
|
@@ -323,25 +380,17 @@ T = TypeVar("T")
|
|
|
323
380
|
def ensure_no_previous_output(func: Callable[Param, T]) -> Callable[Param, T]:
|
|
324
381
|
def wrapper(*args: Param.args, **kwargs: Param.kwargs) -> T:
|
|
325
382
|
global BASH_STATE
|
|
326
|
-
if BASH_STATE == "
|
|
383
|
+
if BASH_STATE == "pending":
|
|
327
384
|
raise ValueError(WAITING_INPUT_MESSAGE)
|
|
328
|
-
|
|
329
|
-
raise ValueError(
|
|
330
|
-
"A command is already running that hasn't exited. NOTE: You can't run multiple shell sessions, likely the previous program is in infinite loop. Please kill the previous program by sending ctrl+c first."
|
|
331
|
-
)
|
|
385
|
+
|
|
332
386
|
return func(*args, **kwargs)
|
|
333
387
|
|
|
334
388
|
return wrapper
|
|
335
389
|
|
|
336
390
|
|
|
337
|
-
@ensure_no_previous_output
|
|
338
391
|
def read_image_from_shell(file_path: str) -> ImageData:
|
|
339
392
|
if not os.path.isabs(file_path):
|
|
340
|
-
|
|
341
|
-
SHELL.expect(PROMPT)
|
|
342
|
-
assert isinstance(SHELL.before, str)
|
|
343
|
-
current_dir = render_terminal_output(SHELL.before).strip()
|
|
344
|
-
file_path = os.path.join(current_dir, file_path)
|
|
393
|
+
file_path = os.path.join(CWD, file_path)
|
|
345
394
|
|
|
346
395
|
if not os.path.exists(file_path):
|
|
347
396
|
raise ValueError(f"File {file_path} does not exist")
|
|
@@ -353,22 +402,65 @@ def read_image_from_shell(file_path: str) -> ImageData:
|
|
|
353
402
|
return ImageData(dataurl=f"data:{image_type};base64,{image_b64}")
|
|
354
403
|
|
|
355
404
|
|
|
356
|
-
@ensure_no_previous_output
|
|
357
405
|
def write_file(writefile: Writefile) -> str:
|
|
358
406
|
if not os.path.isabs(writefile.file_path):
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
current_dir = render_terminal_output(SHELL.before).strip()
|
|
363
|
-
return f"Failure: Use absolute path only. FYI current working directory is '{current_dir}'"
|
|
364
|
-
os.makedirs(os.path.dirname(writefile.file_path), exist_ok=True)
|
|
407
|
+
path_ = os.path.join(CWD, writefile.file_path)
|
|
408
|
+
else:
|
|
409
|
+
path_ = writefile.file_path
|
|
365
410
|
try:
|
|
366
|
-
with open(
|
|
411
|
+
with open(path_, "w") as f:
|
|
367
412
|
f.write(writefile.file_content)
|
|
368
413
|
except OSError as e:
|
|
369
|
-
console.print(f"Error: {e}", style="red")
|
|
370
414
|
return f"Error: {e}"
|
|
371
|
-
console.print(f"File written to {
|
|
415
|
+
console.print(f"File written to {path_}")
|
|
416
|
+
return "Success"
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def find_least_edit_distance_substring(content: str, find_str: str) -> str:
|
|
420
|
+
content_lines = content.split("\n")
|
|
421
|
+
find_lines = find_str.split("\n")
|
|
422
|
+
# Slide window and find one with sum of edit distance least
|
|
423
|
+
min_edit_distance = float("inf")
|
|
424
|
+
min_edit_distance_lines = []
|
|
425
|
+
for i in range(len(content_lines) - len(find_lines) + 1):
|
|
426
|
+
edit_distance_sum = 0
|
|
427
|
+
for j in range(len(find_lines)):
|
|
428
|
+
edit_distance_sum += edit_distance(content_lines[i + j], find_lines[j])
|
|
429
|
+
if edit_distance_sum < min_edit_distance:
|
|
430
|
+
min_edit_distance = edit_distance_sum
|
|
431
|
+
min_edit_distance_lines = content_lines[i : i + len(find_lines)]
|
|
432
|
+
return "\n".join(min_edit_distance_lines)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def file_edit(file_edit: FileEditFindReplace) -> str:
|
|
436
|
+
if not os.path.isabs(file_edit.file_path):
|
|
437
|
+
path_ = os.path.join(CWD, file_edit.file_path)
|
|
438
|
+
else:
|
|
439
|
+
path_ = file_edit.file_path
|
|
440
|
+
|
|
441
|
+
out_string = "\n".join("> " + line for line in file_edit.find_lines.split("\n"))
|
|
442
|
+
in_string = "\n".join(
|
|
443
|
+
"< " + line for line in file_edit.replace_with_lines.split("\n")
|
|
444
|
+
)
|
|
445
|
+
console.log(f"Editing file: {path_}\n---\n{out_string}\n---\n{in_string}\n---")
|
|
446
|
+
try:
|
|
447
|
+
with open(path_) as f:
|
|
448
|
+
content = f.read()
|
|
449
|
+
# First find counts
|
|
450
|
+
count = content.count(file_edit.find_lines)
|
|
451
|
+
|
|
452
|
+
if count == 0:
|
|
453
|
+
closest_match = find_least_edit_distance_substring(
|
|
454
|
+
content, file_edit.find_lines
|
|
455
|
+
)
|
|
456
|
+
return f"Error: no match found for the provided `find_lines` in the file. Closest match:\n---\n{closest_match}\n---\nFile not edited"
|
|
457
|
+
|
|
458
|
+
content = content.replace(file_edit.find_lines, file_edit.replace_with_lines)
|
|
459
|
+
with open(path_, "w") as f:
|
|
460
|
+
f.write(content)
|
|
461
|
+
except OSError as e:
|
|
462
|
+
return f"Error: {e}"
|
|
463
|
+
console.print(f"File written to {path_}")
|
|
372
464
|
return "Success"
|
|
373
465
|
|
|
374
466
|
|
|
@@ -396,16 +488,37 @@ def take_help_of_ai_assistant(
|
|
|
396
488
|
|
|
397
489
|
def which_tool(args: str) -> BaseModel:
|
|
398
490
|
adapter = TypeAdapter[
|
|
399
|
-
Confirmation
|
|
400
|
-
|
|
491
|
+
Confirmation
|
|
492
|
+
| BashCommand
|
|
493
|
+
| BashInteraction
|
|
494
|
+
| ResetShell
|
|
495
|
+
| Writefile
|
|
496
|
+
| FileEditFindReplace
|
|
497
|
+
| AIAssistant
|
|
498
|
+
| DoneFlag
|
|
499
|
+
| ReadImage
|
|
500
|
+
](
|
|
501
|
+
Confirmation
|
|
502
|
+
| BashCommand
|
|
503
|
+
| BashInteraction
|
|
504
|
+
| ResetShell
|
|
505
|
+
| Writefile
|
|
506
|
+
| FileEditFindReplace
|
|
507
|
+
| AIAssistant
|
|
508
|
+
| DoneFlag
|
|
509
|
+
| ReadImage
|
|
510
|
+
)
|
|
401
511
|
return adapter.validate_python(json.loads(args))
|
|
402
512
|
|
|
403
513
|
|
|
404
514
|
def get_tool_output(
|
|
405
515
|
args: dict[object, object]
|
|
406
516
|
| Confirmation
|
|
407
|
-
|
|
|
517
|
+
| BashCommand
|
|
518
|
+
| BashInteraction
|
|
519
|
+
| ResetShell
|
|
408
520
|
| Writefile
|
|
521
|
+
| FileEditFindReplace
|
|
409
522
|
| AIAssistant
|
|
410
523
|
| DoneFlag
|
|
411
524
|
| ReadImage,
|
|
@@ -416,8 +529,26 @@ def get_tool_output(
|
|
|
416
529
|
) -> tuple[str | ImageData | DoneFlag, float]:
|
|
417
530
|
if isinstance(args, dict):
|
|
418
531
|
adapter = TypeAdapter[
|
|
419
|
-
Confirmation
|
|
420
|
-
|
|
532
|
+
Confirmation
|
|
533
|
+
| BashCommand
|
|
534
|
+
| BashInteraction
|
|
535
|
+
| ResetShell
|
|
536
|
+
| Writefile
|
|
537
|
+
| FileEditFindReplace
|
|
538
|
+
| AIAssistant
|
|
539
|
+
| DoneFlag
|
|
540
|
+
| ReadImage
|
|
541
|
+
](
|
|
542
|
+
Confirmation
|
|
543
|
+
| BashCommand
|
|
544
|
+
| BashInteraction
|
|
545
|
+
| ResetShell
|
|
546
|
+
| Writefile
|
|
547
|
+
| FileEditFindReplace
|
|
548
|
+
| AIAssistant
|
|
549
|
+
| DoneFlag
|
|
550
|
+
| ReadImage
|
|
551
|
+
)
|
|
421
552
|
arg = adapter.validate_python(args)
|
|
422
553
|
else:
|
|
423
554
|
arg = args
|
|
@@ -425,12 +556,15 @@ def get_tool_output(
|
|
|
425
556
|
if isinstance(arg, Confirmation):
|
|
426
557
|
console.print("Calling ask confirmation tool")
|
|
427
558
|
output = ask_confirmation(arg), 0.0
|
|
428
|
-
elif isinstance(arg,
|
|
559
|
+
elif isinstance(arg, (BashCommand | BashInteraction)):
|
|
429
560
|
console.print("Calling execute bash tool")
|
|
430
561
|
output = execute_bash(enc, arg, max_tokens)
|
|
431
562
|
elif isinstance(arg, Writefile):
|
|
432
563
|
console.print("Calling write file tool")
|
|
433
564
|
output = write_file(arg), 0
|
|
565
|
+
elif isinstance(arg, FileEditFindReplace):
|
|
566
|
+
console.print("Calling file edit tool")
|
|
567
|
+
output = file_edit(arg), 0.0
|
|
434
568
|
elif isinstance(arg, DoneFlag):
|
|
435
569
|
console.print("Calling mark finish tool")
|
|
436
570
|
output = mark_finish(arg), 0.0
|
|
@@ -440,6 +574,9 @@ def get_tool_output(
|
|
|
440
574
|
elif isinstance(arg, ReadImage):
|
|
441
575
|
console.print("Calling read image tool")
|
|
442
576
|
output = read_image_from_shell(arg.file_path), 0.0
|
|
577
|
+
elif isinstance(arg, ResetShell):
|
|
578
|
+
console.print("Calling reset shell tool")
|
|
579
|
+
output = reset_shell(), 0.0
|
|
443
580
|
else:
|
|
444
581
|
raise ValueError(f"Unknown tool: {arg}")
|
|
445
582
|
|
|
@@ -449,44 +586,6 @@ def get_tool_output(
|
|
|
449
586
|
|
|
450
587
|
History = list[ChatCompletionMessageParam]
|
|
451
588
|
|
|
452
|
-
|
|
453
|
-
def get_is_waiting_user_input(
|
|
454
|
-
model: Models, cost_data: CostData
|
|
455
|
-
) -> Callable[[str], tuple[BASH_CLF_OUTPUT, float]]:
|
|
456
|
-
enc = tiktoken.encoding_for_model(model if not model.startswith("o1") else "gpt-4o")
|
|
457
|
-
system_prompt = """You need to classify if a bash program is waiting for user input based on its stdout, or if it won't exit. You'll be given the output of any program.
|
|
458
|
-
Return `waiting_for_input` if the program is waiting for INTERACTIVE input only, Return 'running' if it's waiting for external resources or just waiting to finish.
|
|
459
|
-
Return `wont_exit` if the program won't exit, for example if it's a server.
|
|
460
|
-
Return `running` otherwise.
|
|
461
|
-
"""
|
|
462
|
-
history: History = [{"role": "system", "content": system_prompt}]
|
|
463
|
-
client = OpenAI()
|
|
464
|
-
|
|
465
|
-
class ExpectedOutput(BaseModel):
|
|
466
|
-
output_classified: BASH_CLF_OUTPUT
|
|
467
|
-
|
|
468
|
-
def is_waiting_user_input(output: str) -> tuple[BASH_CLF_OUTPUT, float]:
|
|
469
|
-
# Send only last 30 lines
|
|
470
|
-
output = "\n".join(output.split("\n")[-30:])
|
|
471
|
-
# Send only max last 200 tokens
|
|
472
|
-
output = enc.decode(enc.encode(output)[-200:])
|
|
473
|
-
|
|
474
|
-
history.append({"role": "user", "content": output})
|
|
475
|
-
response = client.beta.chat.completions.parse(
|
|
476
|
-
model=model, messages=history, response_format=ExpectedOutput
|
|
477
|
-
)
|
|
478
|
-
parsed = response.choices[0].message.parsed
|
|
479
|
-
if parsed is None:
|
|
480
|
-
raise ValueError("No parsed output")
|
|
481
|
-
cost = (
|
|
482
|
-
get_input_cost(cost_data, enc, history)[0]
|
|
483
|
-
+ get_output_cost(cost_data, enc, response.choices[0].message)[0]
|
|
484
|
-
)
|
|
485
|
-
return parsed.output_classified, cost
|
|
486
|
-
|
|
487
|
-
return is_waiting_user_input
|
|
488
|
-
|
|
489
|
-
|
|
490
589
|
default_enc = tiktoken.encoding_for_model("gpt-4o")
|
|
491
590
|
default_model: Models = "gpt-4o-2024-08-06"
|
|
492
591
|
default_cost = CostData(cost_per_1m_input_tokens=0.15, cost_per_1m_output_tokens=0.6)
|
|
@@ -494,7 +593,7 @@ curr_cost = 0.0
|
|
|
494
593
|
|
|
495
594
|
|
|
496
595
|
class Mdata(BaseModel):
|
|
497
|
-
data:
|
|
596
|
+
data: BashCommand | BashInteraction | Writefile | ResetShell | FileEditFindReplace
|
|
498
597
|
|
|
499
598
|
|
|
500
599
|
execution_lock = threading.Lock()
|
|
@@ -509,7 +608,7 @@ def execute_user_input() -> None:
|
|
|
509
608
|
console.log(
|
|
510
609
|
execute_bash(
|
|
511
610
|
default_enc,
|
|
512
|
-
|
|
611
|
+
BashInteraction(
|
|
513
612
|
send_ascii=[ord(x) for x in user_input] + [ord("\n")]
|
|
514
613
|
),
|
|
515
614
|
max_tokens=None,
|
|
@@ -528,6 +627,11 @@ async def register_client(server_url: str, client_uuid: str = "") -> None:
|
|
|
528
627
|
|
|
529
628
|
# Create the WebSocket connection
|
|
530
629
|
async with websockets.connect(f"{server_url}/{client_uuid}") as websocket:
|
|
630
|
+
server_version = str(await websocket.recv())
|
|
631
|
+
print(f"Server version: {server_version}")
|
|
632
|
+
client_version = importlib.metadata.version("wcgw")
|
|
633
|
+
await websocket.send(client_version)
|
|
634
|
+
|
|
531
635
|
print(
|
|
532
636
|
f"Connected. Share this user id with the chatbot: {client_uuid} \nLink: https://chatgpt.com/g/g-Us0AAXkRh-wcgw-giving-shell-access"
|
|
533
637
|
)
|
|
@@ -559,8 +663,15 @@ run = Typer(pretty_exceptions_show_locals=False, no_args_is_help=True)
|
|
|
559
663
|
|
|
560
664
|
@run.command()
|
|
561
665
|
def app(
|
|
562
|
-
server_url: str = "wss://wcgw.arcfu.com/register",
|
|
666
|
+
server_url: str = "wss://wcgw.arcfu.com/v1/register",
|
|
667
|
+
client_uuid: Optional[str] = None,
|
|
668
|
+
version: bool = typer.Option(False, "--version", "-v"),
|
|
563
669
|
) -> None:
|
|
670
|
+
if version:
|
|
671
|
+
version_ = importlib.metadata.version("wcgw")
|
|
672
|
+
print(f"wcgw version: {version_}")
|
|
673
|
+
exit()
|
|
674
|
+
|
|
564
675
|
thread1 = threading.Thread(target=execute_user_input)
|
|
565
676
|
thread2 = threading.Thread(
|
|
566
677
|
target=asyncio.run, args=(register_client(server_url, client_uuid or ""),)
|
wcgw/relay/serve.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import base64
|
|
3
|
+
from importlib import metadata
|
|
4
|
+
import semantic_version # type: ignore[import-untyped]
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Callable, Coroutine, DefaultDict, Literal, Optional, Sequence
|
|
8
|
+
from uuid import UUID
|
|
9
|
+
import fastapi
|
|
10
|
+
from fastapi import Response, WebSocket, WebSocketDisconnect
|
|
11
|
+
from pydantic import BaseModel
|
|
12
|
+
import uvicorn
|
|
13
|
+
from fastapi.staticfiles import StaticFiles
|
|
14
|
+
|
|
15
|
+
from dotenv import load_dotenv
|
|
16
|
+
|
|
17
|
+
from ..types_ import (
|
|
18
|
+
BashCommand,
|
|
19
|
+
BashInteraction,
|
|
20
|
+
FileEditFindReplace,
|
|
21
|
+
ResetShell,
|
|
22
|
+
Writefile,
|
|
23
|
+
Specials,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Mdata(BaseModel):
|
|
28
|
+
data: BashCommand | BashInteraction | Writefile | ResetShell | FileEditFindReplace
|
|
29
|
+
user_id: UUID
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
app = fastapi.FastAPI()
|
|
33
|
+
|
|
34
|
+
clients: dict[UUID, Callable[[Mdata], Coroutine[None, None, None]]] = {}
|
|
35
|
+
websockets: dict[UUID, WebSocket] = {}
|
|
36
|
+
gpts: dict[UUID, Callable[[str], None]] = {}
|
|
37
|
+
|
|
38
|
+
images: DefaultDict[UUID, dict[str, dict[str, Any]]] = DefaultDict(dict)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@app.websocket("/register_serve_image/{uuid}")
|
|
42
|
+
async def register_serve_image(websocket: WebSocket, uuid: UUID) -> None:
|
|
43
|
+
raise Exception("Disabled")
|
|
44
|
+
await websocket.accept()
|
|
45
|
+
received_data = await websocket.receive_json()
|
|
46
|
+
name = received_data["name"]
|
|
47
|
+
image_b64 = received_data["image_b64"]
|
|
48
|
+
image_bytes = base64.b64decode(image_b64)
|
|
49
|
+
images[uuid][name] = {
|
|
50
|
+
"content": image_bytes,
|
|
51
|
+
"media_type": received_data["media_type"],
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@app.get("/get_image/{uuid}/{name}")
|
|
56
|
+
async def get_image(uuid: UUID, name: str) -> fastapi.responses.Response:
|
|
57
|
+
return fastapi.responses.Response(
|
|
58
|
+
content=images[uuid][name]["content"],
|
|
59
|
+
media_type=images[uuid][name]["media_type"],
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@app.websocket("/register/{uuid}")
|
|
64
|
+
async def register_websocket_deprecated(websocket: WebSocket, uuid: UUID) -> None:
|
|
65
|
+
await websocket.accept()
|
|
66
|
+
await websocket.send_text(
|
|
67
|
+
"Outdated client used. Deprecated api is being used. Upgrade the wcgw app."
|
|
68
|
+
)
|
|
69
|
+
await websocket.close(
|
|
70
|
+
reason="This endpoint is deprecated. Please use /v1/register/{uuid}", code=1002
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
CLIENT_VERSION_MINIMUM = "1.0.0"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@app.websocket("/v1/register/{uuid}")
|
|
78
|
+
async def register_websocket(websocket: WebSocket, uuid: UUID) -> None:
|
|
79
|
+
await websocket.accept()
|
|
80
|
+
|
|
81
|
+
# send server version
|
|
82
|
+
version = metadata.version("wcgw")
|
|
83
|
+
await websocket.send_text(version)
|
|
84
|
+
|
|
85
|
+
# receive client version
|
|
86
|
+
client_version = await websocket.receive_text()
|
|
87
|
+
sem_version_client = semantic_version.Version.coerce(client_version)
|
|
88
|
+
sem_version_server = semantic_version.Version.coerce(CLIENT_VERSION_MINIMUM)
|
|
89
|
+
if sem_version_client < sem_version_server:
|
|
90
|
+
await websocket.send_text(
|
|
91
|
+
f"Client version {client_version} is outdated. Please upgrade to {CLIENT_VERSION_MINIMUM} or higher."
|
|
92
|
+
)
|
|
93
|
+
await websocket.close(
|
|
94
|
+
reason="Client version outdated. Please upgrade to the latest version.",
|
|
95
|
+
code=1002,
|
|
96
|
+
)
|
|
97
|
+
return
|
|
98
|
+
|
|
99
|
+
# Register the callback for this client UUID
|
|
100
|
+
async def send_data_callback(data: Mdata) -> None:
|
|
101
|
+
await websocket.send_text(data.model_dump_json())
|
|
102
|
+
|
|
103
|
+
clients[uuid] = send_data_callback
|
|
104
|
+
websockets[uuid] = websocket
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
while True:
|
|
108
|
+
received_data = await websocket.receive_text()
|
|
109
|
+
if uuid not in gpts:
|
|
110
|
+
raise fastapi.HTTPException(status_code=400, detail="No call made")
|
|
111
|
+
gpts[uuid](received_data)
|
|
112
|
+
except WebSocketDisconnect:
|
|
113
|
+
# Remove the client if the WebSocket is disconnected
|
|
114
|
+
del clients[uuid]
|
|
115
|
+
del websockets[uuid]
|
|
116
|
+
print(f"Client {uuid} disconnected")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@app.post("/write_file")
|
|
120
|
+
async def write_file_deprecated(write_file_data: Writefile, user_id: UUID) -> Response:
|
|
121
|
+
return Response(
|
|
122
|
+
content="This version of the API is deprecated. Please upgrade your client.",
|
|
123
|
+
status_code=400,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class WritefileWithUUID(Writefile):
|
|
128
|
+
user_id: UUID
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@app.post("/v1/write_file")
|
|
132
|
+
async def write_file(write_file_data: WritefileWithUUID) -> str:
|
|
133
|
+
user_id = write_file_data.user_id
|
|
134
|
+
if user_id not in clients:
|
|
135
|
+
raise fastapi.HTTPException(
|
|
136
|
+
status_code=404, detail="User with the provided id not found"
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
results: Optional[str] = None
|
|
140
|
+
|
|
141
|
+
def put_results(result: str) -> None:
|
|
142
|
+
nonlocal results
|
|
143
|
+
results = result
|
|
144
|
+
|
|
145
|
+
gpts[user_id] = put_results
|
|
146
|
+
|
|
147
|
+
await clients[user_id](Mdata(data=write_file_data, user_id=user_id))
|
|
148
|
+
|
|
149
|
+
start_time = time.time()
|
|
150
|
+
while time.time() - start_time < 30:
|
|
151
|
+
if results is not None:
|
|
152
|
+
return results
|
|
153
|
+
await asyncio.sleep(0.1)
|
|
154
|
+
|
|
155
|
+
raise fastapi.HTTPException(status_code=500, detail="Timeout error")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class FileEditFindReplaceWithUUID(FileEditFindReplace):
|
|
159
|
+
user_id: UUID
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@app.post("/v1/file_edit_find_replace")
|
|
163
|
+
async def file_edit_find_replace(
|
|
164
|
+
file_edit_find_replace: FileEditFindReplaceWithUUID,
|
|
165
|
+
) -> str:
|
|
166
|
+
user_id = file_edit_find_replace.user_id
|
|
167
|
+
if user_id not in clients:
|
|
168
|
+
raise fastapi.HTTPException(
|
|
169
|
+
status_code=404, detail="User with the provided id not found"
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
results: Optional[str] = None
|
|
173
|
+
|
|
174
|
+
def put_results(result: str) -> None:
|
|
175
|
+
nonlocal results
|
|
176
|
+
results = result
|
|
177
|
+
|
|
178
|
+
gpts[user_id] = put_results
|
|
179
|
+
|
|
180
|
+
await clients[user_id](
|
|
181
|
+
Mdata(
|
|
182
|
+
data=file_edit_find_replace,
|
|
183
|
+
user_id=user_id,
|
|
184
|
+
)
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
start_time = time.time()
|
|
188
|
+
while time.time() - start_time < 30:
|
|
189
|
+
if results is not None:
|
|
190
|
+
return results
|
|
191
|
+
await asyncio.sleep(0.1)
|
|
192
|
+
|
|
193
|
+
raise fastapi.HTTPException(status_code=500, detail="Timeout error")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class ResetShellWithUUID(ResetShell):
|
|
197
|
+
user_id: UUID
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@app.post("/v1/reset_shell")
|
|
201
|
+
async def reset_shell(reset_shell: ResetShellWithUUID) -> str:
|
|
202
|
+
user_id = reset_shell.user_id
|
|
203
|
+
if user_id not in clients:
|
|
204
|
+
raise fastapi.HTTPException(
|
|
205
|
+
status_code=404, detail="User with the provided id not found"
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
results: Optional[str] = None
|
|
209
|
+
|
|
210
|
+
def put_results(result: str) -> None:
|
|
211
|
+
nonlocal results
|
|
212
|
+
results = result
|
|
213
|
+
|
|
214
|
+
gpts[user_id] = put_results
|
|
215
|
+
|
|
216
|
+
await clients[user_id](Mdata(data=reset_shell, user_id=user_id))
|
|
217
|
+
|
|
218
|
+
start_time = time.time()
|
|
219
|
+
while time.time() - start_time < 30:
|
|
220
|
+
if results is not None:
|
|
221
|
+
return results
|
|
222
|
+
await asyncio.sleep(0.1)
|
|
223
|
+
|
|
224
|
+
raise fastapi.HTTPException(status_code=500, detail="Timeout error")
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@app.post("/execute_bash")
|
|
228
|
+
async def execute_bash_deprecated(excute_bash_data: Any, user_id: UUID) -> Response:
|
|
229
|
+
return Response(
|
|
230
|
+
content="This version of the API is deprecated. Please upgrade your client.",
|
|
231
|
+
status_code=400,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class CommandWithUUID(BaseModel):
|
|
236
|
+
command: str
|
|
237
|
+
user_id: UUID
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@app.post("/v1/bash_command")
|
|
241
|
+
async def bash_command(command: CommandWithUUID) -> str:
|
|
242
|
+
user_id = command.user_id
|
|
243
|
+
if user_id not in clients:
|
|
244
|
+
raise fastapi.HTTPException(
|
|
245
|
+
status_code=404, detail="User with the provided id not found"
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
results: Optional[str] = None
|
|
249
|
+
|
|
250
|
+
def put_results(result: str) -> None:
|
|
251
|
+
nonlocal results
|
|
252
|
+
results = result
|
|
253
|
+
|
|
254
|
+
gpts[user_id] = put_results
|
|
255
|
+
|
|
256
|
+
await clients[user_id](
|
|
257
|
+
Mdata(data=BashCommand(command=command.command), user_id=user_id)
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
start_time = time.time()
|
|
261
|
+
while time.time() - start_time < 30:
|
|
262
|
+
if results is not None:
|
|
263
|
+
return results
|
|
264
|
+
await asyncio.sleep(0.1)
|
|
265
|
+
|
|
266
|
+
raise fastapi.HTTPException(status_code=500, detail="Timeout error")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class BashInteractionWithUUID(BashInteraction):
|
|
270
|
+
user_id: UUID
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
@app.post("/v1/bash_interaction")
|
|
274
|
+
async def bash_interaction(bash_interaction: BashInteractionWithUUID) -> str:
|
|
275
|
+
user_id = bash_interaction.user_id
|
|
276
|
+
if user_id not in clients:
|
|
277
|
+
raise fastapi.HTTPException(
|
|
278
|
+
status_code=404, detail="User with the provided id not found"
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
results: Optional[str] = None
|
|
282
|
+
|
|
283
|
+
def put_results(result: str) -> None:
|
|
284
|
+
nonlocal results
|
|
285
|
+
results = result
|
|
286
|
+
|
|
287
|
+
gpts[user_id] = put_results
|
|
288
|
+
|
|
289
|
+
await clients[user_id](
|
|
290
|
+
Mdata(
|
|
291
|
+
data=bash_interaction,
|
|
292
|
+
user_id=user_id,
|
|
293
|
+
)
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
start_time = time.time()
|
|
297
|
+
while time.time() - start_time < 30:
|
|
298
|
+
if results is not None:
|
|
299
|
+
return results
|
|
300
|
+
await asyncio.sleep(0.1)
|
|
301
|
+
|
|
302
|
+
raise fastapi.HTTPException(status_code=500, detail="Timeout error")
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def run() -> None:
|
|
309
|
+
load_dotenv()
|
|
310
|
+
|
|
311
|
+
uvicorn_thread = threading.Thread(
|
|
312
|
+
target=uvicorn.run,
|
|
313
|
+
args=(app,),
|
|
314
|
+
kwargs={
|
|
315
|
+
"host": "0.0.0.0",
|
|
316
|
+
"port": 8000,
|
|
317
|
+
"log_level": "info",
|
|
318
|
+
"access_log": True,
|
|
319
|
+
},
|
|
320
|
+
)
|
|
321
|
+
uvicorn_thread.start()
|
|
322
|
+
uvicorn_thread.join()
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
if __name__ == "__main__":
|
|
326
|
+
run()
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Privacy Policy
|
|
2
|
+
I do not collect, store, or share any personal data.
|
|
3
|
+
The data from your terminal is not stored anywhere and it's not logged or collected in any form.
|
|
4
|
+
There is a relay webserver for connecting your terminal to chatgpt the source code for which is open at https://github.com/rusiaaman/wcgw/tree/main/src/relay that you can run on your own.
|
|
5
|
+
Other than the relay webserver there is no further involvement of my servers or services.
|
|
6
|
+
Feel free to me contact at info@arcfu.com for questions on privacy or anything else.
|
|
7
|
+
|
wcgw/types_.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from typing import Literal, Optional, Sequence
|
|
2
|
+
from pydantic import BaseModel
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class BashCommand(BaseModel):
|
|
6
|
+
command: str
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
Specials = Literal[
|
|
10
|
+
"Key-up", "Key-down", "Key-left", "Key-right", "Enter", "Ctrl-c", "Ctrl-d", "Ctrl-z"
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class BashInteraction(BaseModel):
|
|
15
|
+
send_text: Optional[str] = None
|
|
16
|
+
send_specials: Optional[Sequence[Specials]] = None
|
|
17
|
+
send_ascii: Optional[Sequence[int]] = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ReadImage(BaseModel):
|
|
21
|
+
file_path: str
|
|
22
|
+
type: Literal["ReadImage"] = "ReadImage"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Writefile(BaseModel):
|
|
26
|
+
file_path: str
|
|
27
|
+
file_content: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class FileEditFindReplace(BaseModel):
|
|
31
|
+
file_path: str
|
|
32
|
+
find_lines: str
|
|
33
|
+
replace_with_lines: str
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ResetShell(BaseModel):
|
|
37
|
+
should_reset: Literal[True] = True
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: wcgw
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 1.0.0
|
|
4
4
|
Summary: What could go wrong giving full shell access to chatgpt?
|
|
5
5
|
Project-URL: Homepage, https://github.com/rusiaaman/wcgw
|
|
6
6
|
Author-email: Aman Rusia <gapypi@arcfu.com>
|
|
7
7
|
Requires-Python: <3.13,>=3.10
|
|
8
8
|
Requires-Dist: fastapi>=0.115.0
|
|
9
9
|
Requires-Dist: mypy>=1.11.2
|
|
10
|
+
Requires-Dist: nltk>=3.9.1
|
|
10
11
|
Requires-Dist: openai>=1.46.0
|
|
11
12
|
Requires-Dist: petname>=2.6
|
|
12
13
|
Requires-Dist: pexpect>=4.9.0
|
|
@@ -14,6 +15,7 @@ Requires-Dist: pydantic>=2.9.2
|
|
|
14
15
|
Requires-Dist: pyte>=0.8.2
|
|
15
16
|
Requires-Dist: python-dotenv>=1.0.1
|
|
16
17
|
Requires-Dist: rich>=13.8.1
|
|
18
|
+
Requires-Dist: semantic-version>=2.10.0
|
|
17
19
|
Requires-Dist: shell>=1.0.1
|
|
18
20
|
Requires-Dist: tiktoken==0.7.0
|
|
19
21
|
Requires-Dist: toml>=0.10.2
|
|
@@ -32,7 +34,8 @@ A custom gpt on chatgpt web app to interact with your local shell.
|
|
|
32
34
|
### 🚀 Highlights
|
|
33
35
|
- ⚡ **Full Shell Access**: No restrictions, complete control.
|
|
34
36
|
- ⚡ **Create, Execute, Iterate**: Ask the gpt to keep running compiler checks till all errors are fixed, or ask it to keep checking for the status of a long running command till it's done.
|
|
35
|
-
- ⚡ **Interactive Command Handling**:
|
|
37
|
+
- ⚡ **Interactive Command Handling**: Supports interactive commands using arrow keys, interrupt, and ansi escape sequences.
|
|
38
|
+
- ⚡ **REPL support**: [beta] Supports python/node and other REPL execution.
|
|
36
39
|
|
|
37
40
|
### 🪜 Steps:
|
|
38
41
|
1. Run the [cli client](https://github.com/rusiaaman/wcgw?tab=readme-ov-file#client) in any directory of choice.
|
|
@@ -103,7 +106,7 @@ Run the server
|
|
|
103
106
|
If you don't have public ip and domain name, you can use `ngrok` or similar services to get a https address to the api.
|
|
104
107
|
|
|
105
108
|
The specify the server url in the `wcgw` command like so
|
|
106
|
-
`wcgw --server-url https://your-url/register`
|
|
109
|
+
`wcgw --server-url https://your-url/v1/register`
|
|
107
110
|
|
|
108
111
|
# [Optional] Local shell access with openai API key
|
|
109
112
|
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
wcgw/__init__.py,sha256=VMi3gCAN_4_Ft8v5dY74u6bt5X-H1QhFJqTMZRd4fvk,76
|
|
2
|
+
wcgw/types_.py,sha256=qpMRh1y136GkjIONIFowLy56v5p0OcdNqEH2mTmHPqU,756
|
|
3
|
+
wcgw/client/__main__.py,sha256=ngI_vBcLAv7fJgmS4w4U7tuWtalGB8c7W5qebuT6Z6o,30
|
|
4
|
+
wcgw/client/basic.py,sha256=2rY5pKm9dBBRuku0uIBUeLWjNc3iXjTSK9CmfuTxoS8,16196
|
|
5
|
+
wcgw/client/claude.py,sha256=Bp45-UMBIJd-4tzX618nu-SpRbVtkTb1Es6c_gW6xy0,14861
|
|
6
|
+
wcgw/client/common.py,sha256=grH-yV_4tnTQZ29xExn4YicGLxEq98z-HkEZwH0ReSg,1410
|
|
7
|
+
wcgw/client/openai_adapters.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
wcgw/client/openai_utils.py,sha256=YNwCsA-Wqq7jWrxP0rfQmBTb1dI0s7dWXzQqyTzOZT4,2629
|
|
9
|
+
wcgw/client/tools.py,sha256=UHPbpaQ70sFzE5_TYYyhV2FAE6BcbEgyRrTexaIpT6Y,21108
|
|
10
|
+
wcgw/relay/serve.py,sha256=y2jGbZ0vKKONOD8TkJjSAaH8N6qGLa-rFtj5DxjUFIw,8916
|
|
11
|
+
wcgw/relay/static/privacy.txt,sha256=s9qBdbx2SexCpC_z33sg16TptmAwDEehMCLz4L50JLc,529
|
|
12
|
+
wcgw-1.0.0.dist-info/METADATA,sha256=8OScNwT6aecVULmjuk2oEPNIYGrhhMaAdybsdm57kYM,5217
|
|
13
|
+
wcgw-1.0.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
14
|
+
wcgw-1.0.0.dist-info/entry_points.txt,sha256=WlIB825-Vm9ZtNzgENQsbHj4DRMkbpVR7uSkQyBlaPA,93
|
|
15
|
+
wcgw-1.0.0.dist-info/RECORD,,
|
wcgw/__main__.py
DELETED
wcgw-0.2.0.dist-info/RECORD
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
wcgw/__init__.py,sha256=okSsOWpTKDjEQzgOin3Kdpx4Mc3MFX1RunjopHQSIWE,62
|
|
2
|
-
wcgw/__main__.py,sha256=MjJnFwfYzA1rW47xuSP1EVsi53DTHeEGqESkQwsELFQ,34
|
|
3
|
-
wcgw/basic.py,sha256=aTos3c0URl-ufgXfQ1bkg-5oFCR_SxG_VI5qckBtex0,16426
|
|
4
|
-
wcgw/claude.py,sha256=Bp45-UMBIJd-4tzX618nu-SpRbVtkTb1Es6c_gW6xy0,14861
|
|
5
|
-
wcgw/common.py,sha256=grH-yV_4tnTQZ29xExn4YicGLxEq98z-HkEZwH0ReSg,1410
|
|
6
|
-
wcgw/openai_adapters.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
-
wcgw/openai_utils.py,sha256=YNwCsA-Wqq7jWrxP0rfQmBTb1dI0s7dWXzQqyTzOZT4,2629
|
|
8
|
-
wcgw/tools.py,sha256=UdSU6lAbOGNdG2wiM5x8YTosBDlphiMEo7MHtMjGvRk,18618
|
|
9
|
-
wcgw-0.2.0.dist-info/METADATA,sha256=X4vyv9Oaq8JtD301hk8jObC3bHggqtyWcxNvUssG-I4,5076
|
|
10
|
-
wcgw-0.2.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
11
|
-
wcgw-0.2.0.dist-info/entry_points.txt,sha256=T-IH7w6Vc650hr8xksC8kJfbJR4uwN8HDudejwDwrNM,59
|
|
12
|
-
wcgw-0.2.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|