aiwe 0.0.1__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.
Files changed (100) hide show
  1. aiwe/__init__.py +1 -0
  2. aiwe/__main__.py +96 -0
  3. aiwe/agent_commands.py +86 -0
  4. aiwe/config.py +73 -0
  5. aiwe/core/__init__.py +0 -0
  6. aiwe/core/api.py +805 -0
  7. aiwe/core/core.py +102 -0
  8. aiwe/core/db/__init__.py +0 -0
  9. aiwe/core/db/db.py +116 -0
  10. aiwe/core/db/migrations.py +122 -0
  11. aiwe/core/db/models.py +269 -0
  12. aiwe/core/db/schema.py +196 -0
  13. aiwe/core/errors.py +21 -0
  14. aiwe/core/features/__init__.py +0 -0
  15. aiwe/core/features/agent/__init__.py +0 -0
  16. aiwe/core/features/agent/adapters/__init__.py +0 -0
  17. aiwe/core/features/agent/adapters/claude_cli.py +228 -0
  18. aiwe/core/features/agent/adapters/codex_cli.py +318 -0
  19. aiwe/core/features/agent/cli_process.py +229 -0
  20. aiwe/core/features/agent/contract.py +107 -0
  21. aiwe/core/features/agent/service.py +330 -0
  22. aiwe/core/features/agent/software.py +27 -0
  23. aiwe/core/features/chat/__init__.py +0 -0
  24. aiwe/core/features/chat/service.py +146 -0
  25. aiwe/core/features/dictation/__init__.py +0 -0
  26. aiwe/core/features/dictation/service.py +76 -0
  27. aiwe/core/features/dictation/state.py +10 -0
  28. aiwe/core/features/dictation/voxo.py +9 -0
  29. aiwe/core/features/file/__init__.py +0 -0
  30. aiwe/core/features/file/folder.py +170 -0
  31. aiwe/core/features/file/service.py +37 -0
  32. aiwe/core/features/git/__init__.py +0 -0
  33. aiwe/core/features/git/service.py +79 -0
  34. aiwe/core/features/message/__init__.py +0 -0
  35. aiwe/core/features/message/chat_text.py +49 -0
  36. aiwe/core/features/message/prompt.py +52 -0
  37. aiwe/core/features/message/service.py +490 -0
  38. aiwe/core/features/message/writing.py +26 -0
  39. aiwe/core/features/project/AGENTS.template.md +180 -0
  40. aiwe/core/features/project/__init__.py +0 -0
  41. aiwe/core/features/project/service.py +173 -0
  42. aiwe/core/features/user/__init__.py +0 -0
  43. aiwe/core/features/user/passwords.py +31 -0
  44. aiwe/core/features/user/service.py +164 -0
  45. aiwe/core/service.py +17 -0
  46. aiwe/daemon.py +69 -0
  47. aiwe/web/__init__.py +0 -0
  48. aiwe/web/app.py +132 -0
  49. aiwe/web/cloudflare_access.py +49 -0
  50. aiwe/web/form.py +28 -0
  51. aiwe/web/project_frame.py +33 -0
  52. aiwe/web/routers/__init__.py +0 -0
  53. aiwe/web/routers/admin.py +114 -0
  54. aiwe/web/routers/agent_api.py +65 -0
  55. aiwe/web/routers/chat.py +145 -0
  56. aiwe/web/routers/chat_list.py +77 -0
  57. aiwe/web/routers/dictation.py +33 -0
  58. aiwe/web/routers/file.py +53 -0
  59. aiwe/web/routers/project.py +89 -0
  60. aiwe/web/routers/user.py +80 -0
  61. aiwe/web/static/chat.js +240 -0
  62. aiwe/web/static/files.js +17 -0
  63. aiwe/web/static/htmx-4.0.0.min.js +1 -0
  64. aiwe/web/static/model_setting.js +12 -0
  65. aiwe/web/static/panes.js +51 -0
  66. aiwe/web/static/styles.css +1361 -0
  67. aiwe/web/templates/admin/agent.html +44 -0
  68. aiwe/web/templates/admin/agent_check.html +11 -0
  69. aiwe/web/templates/admin/agent_new.html +26 -0
  70. aiwe/web/templates/admin/agents.html +34 -0
  71. aiwe/web/templates/admin/base.html +20 -0
  72. aiwe/web/templates/admin/software.html +40 -0
  73. aiwe/web/templates/admin/users.html +56 -0
  74. aiwe/web/templates/base.html +67 -0
  75. aiwe/web/templates/chat/chat.html +70 -0
  76. aiwe/web/templates/chat/crumb.html +3 -0
  77. aiwe/web/templates/chat/message.html +86 -0
  78. aiwe/web/templates/chat/messages.html +11 -0
  79. aiwe/web/templates/chat/models.html +24 -0
  80. aiwe/web/templates/chat/title.html +3 -0
  81. aiwe/web/templates/file/file.html +19 -0
  82. aiwe/web/templates/model_setting.html +46 -0
  83. aiwe/web/templates/project/access.html +32 -0
  84. aiwe/web/templates/project/agents.html +48 -0
  85. aiwe/web/templates/project/base.html +49 -0
  86. aiwe/web/templates/project/chats.html +83 -0
  87. aiwe/web/templates/project/project.html +7 -0
  88. aiwe/web/templates/project/project_new.html +11 -0
  89. aiwe/web/templates/project/projects.html +29 -0
  90. aiwe/web/templates/project/settings.html +25 -0
  91. aiwe/web/templates/project/tree.html +22 -0
  92. aiwe/web/templates/user/login.html +10 -0
  93. aiwe/web/templates/user/password.html +13 -0
  94. aiwe/web/templates/user/setup.html +12 -0
  95. aiwe/web/templating.py +71 -0
  96. aiwe-0.0.1.dist-info/METADATA +174 -0
  97. aiwe-0.0.1.dist-info/RECORD +100 -0
  98. aiwe-0.0.1.dist-info/WHEEL +4 -0
  99. aiwe-0.0.1.dist-info/entry_points.txt +3 -0
  100. aiwe-0.0.1.dist-info/licenses/LICENSE +21 -0
aiwe/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """A private web app for long-lived projects worked on with AI agents."""
aiwe/__main__.py ADDED
@@ -0,0 +1,96 @@
1
+ """The `aiwe` command line. The docstring of each command's function is its `--help`: write it for that reader."""
2
+
3
+ import argparse
4
+ import getpass
5
+ import inspect
6
+ import signal
7
+ import sys
8
+ from collections.abc import Callable
9
+ from importlib.metadata import version
10
+ from pathlib import Path
11
+
12
+ import uvicorn
13
+
14
+ from aiwe.agent_commands import ask, title
15
+ from aiwe.config import Config
16
+ from aiwe.core.api import Api
17
+ from aiwe.core.core import Core
18
+ from aiwe.core.errors import AiweError
19
+ from aiwe.daemon import start, stop
20
+ from aiwe.web.app import create_app
21
+
22
+
23
+ def main() -> None:
24
+ """Parse the command line of `aiwe` and run the command it names."""
25
+ parser = argparse.ArgumentParser(prog="aiwe", description="Work on long-lived projects with AI agents.")
26
+ parser.add_argument("--version", action="version", version=f"%(prog)s {version('aiwe')}")
27
+ data_dir = argparse.ArgumentParser(add_help=False)
28
+ data_dir.add_argument("--data-dir", type=Path, default=Path.home() / "aiwe", help="data root (default: ~/aiwe)")
29
+ port = argparse.ArgumentParser(add_help=False)
30
+ port.add_argument("--port", type=int, default=7788, help="port on 127.0.0.1 (default: 7788)")
31
+ commands = parser.add_subparsers(dest="command", required=True)
32
+
33
+ def command(handler: Callable[..., object], *parents: argparse.ArgumentParser) -> argparse.ArgumentParser:
34
+ doc = inspect.cleandoc(handler.__doc__ or "")
35
+ return commands.add_parser(handler.__name__, parents=parents, help=doc.split("\n")[0], description=doc)
36
+
37
+ command(serve, port, data_dir)
38
+ command(start, port, data_dir)
39
+ command(stop, data_dir)
40
+ command(password, data_dir).add_argument("username", help="the username of the user")
41
+ asking = command(ask)
42
+ asking.add_argument("agent", help="the name of the agent to ask")
43
+ asking.add_argument("text", help="the question; - reads it from the standard input")
44
+ command(title).add_argument("text", help="the title: a few words")
45
+ args = parser.parse_args()
46
+ if args.command == "serve":
47
+ serve(args.port, args.data_dir)
48
+ elif args.command == "start":
49
+ start(args.port, args.data_dir)
50
+ elif args.command == "stop":
51
+ stop(args.data_dir)
52
+ elif args.command == "password":
53
+ password(args.data_dir, args.username)
54
+ elif args.command == "ask":
55
+ sys.exit(ask(args.agent, sys.stdin.read() if args.text == "-" else args.text))
56
+ elif args.command == "title":
57
+ sys.exit(title(args.text))
58
+
59
+
60
+ def serve(port: int, data_dir: Path) -> None:
61
+ """Run the app in this terminal, until Ctrl+C."""
62
+ try:
63
+ config = Config.load(data_dir)
64
+ except ValueError as e:
65
+ sys.exit(str(e))
66
+ core = Core(data_dir, f"http://127.0.0.1:{port}", config.voxo)
67
+ # After its own clean stop, uvicorn sends itself the SIGTERM it got. The default action would end the process
68
+ # before `finally`, with the agents still running; an exit raised from a handler goes through it.
69
+ signal.signal(signal.SIGTERM, lambda *_: sys.exit())
70
+ try:
71
+ core.start()
72
+ uvicorn.run(create_app(Api(core), port, config), host="127.0.0.1", port=port)
73
+ finally:
74
+ core.stop()
75
+
76
+
77
+ def password(data_dir: Path, username: str) -> None:
78
+ """Ask for a new password and set it for a user, with no sign-in: for an admin who forgot theirs.
79
+
80
+ Ends every session of the user. Works while the app runs.
81
+ """
82
+ # Checked first: a Core built on a mistyped data dir would make an empty app there.
83
+ if not (data_dir / "aiwe.db").exists():
84
+ sys.exit(f"no aiwe data in {data_dir}")
85
+ new_password = getpass.getpass(f"New password for {username}: ")
86
+ if getpass.getpass("Again: ") != new_password:
87
+ sys.exit("the passwords differ")
88
+ try:
89
+ Core(data_dir).services.user.set_password(username, new_password)
90
+ except AiweError as e:
91
+ sys.exit(str(e))
92
+ sys.stdout.write(f"the password of {username} is set\n")
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
aiwe/agent_commands.py ADDED
@@ -0,0 +1,86 @@
1
+ """`aiwe ask` and `aiwe title`: the thin clients an agent runs in its shell to act on the app.
2
+
3
+ The docstring of each command's function is its `--help`.
4
+ """
5
+
6
+ import http.client
7
+ import json
8
+ import os
9
+ import sys
10
+ from urllib.parse import urlsplit
11
+
12
+
13
+ def ask(agent: str, text: str) -> int:
14
+ """Ask another agent a question, wait for its answer and print it.
15
+
16
+ Only the agent the user wrote to can ask, while it writes its answer. The app runs the asked agent; this command
17
+ only talks to the app, which it finds by AIWE_URL and AIWE_TOKEN in the environment of the agent that runs it.
18
+ Exit code 0: the answer is on stdout. 1: the asked agent failed: the reason is on stderr, and the part of the
19
+ answer it finished on stdout. 2: the app refused the question or gave no answer: stderr says why.
20
+ """
21
+ reply = _post("/api/ask", {"agent": agent, "text": text})
22
+ if reply is None:
23
+ return 2
24
+ status, body = reply
25
+ if status != 200:
26
+ sys.stderr.write(body + "\n")
27
+ return 2
28
+ try:
29
+ answer = json.loads(body)
30
+ except ValueError:
31
+ answer = None
32
+ match answer:
33
+ case {"text": str() | None as answer_text, "error": str() | None as error}:
34
+ if answer_text is not None:
35
+ sys.stdout.write(answer_text + "\n")
36
+ if error is not None:
37
+ sys.stderr.write(f"{agent} failed: {error}\n")
38
+ return 1
39
+ return 0
40
+ case _:
41
+ sys.stderr.write(f"the app gave an answer `aiwe ask` cannot read: {body}\n")
42
+ return 2
43
+
44
+
45
+ def title(text: str) -> int:
46
+ """Give the chat a title, while it has none.
47
+
48
+ Only the agent the user wrote to can name the chat, while it writes its answer, and only once: after that the
49
+ user alone changes the title. This command only talks to the app, which it finds by AIWE_URL and AIWE_TOKEN in
50
+ the environment of the agent that runs it. Exit code 0: the chat has the title. 2: the app refused the title or
51
+ gave no answer: stderr says why.
52
+ """
53
+ reply = _post("/api/title", {"title": text})
54
+ if reply is None:
55
+ return 2
56
+ status, body = reply
57
+ if status != 204:
58
+ sys.stderr.write(body + "\n")
59
+ return 2
60
+ sys.stdout.write("the chat has the title\n")
61
+ return 0
62
+
63
+
64
+ def _post(path: str, payload: dict[str, str]) -> tuple[int, str] | None:
65
+ """Post *payload* as JSON to *path* of the app, with the token of the agent; give the status and the body.
66
+
67
+ None when the app was not asked or gave no answer: stderr then says why.
68
+ """
69
+ url = urlsplit(os.environ.get("AIWE_URL", ""))
70
+ token = os.environ.get("AIWE_TOKEN")
71
+ if url.hostname is None or not token:
72
+ sys.stderr.write("only the agent the user wrote to can run this: AIWE_URL or AIWE_TOKEN is not set\n")
73
+ return None
74
+ # http.client, not urllib: it ignores HTTP_PROXY, which would send this local request elsewhere. No timeout: an
75
+ # asked agent may write for many minutes.
76
+ connection = http.client.HTTPConnection(url.hostname, url.port)
77
+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
78
+ try:
79
+ connection.request("POST", path, body=json.dumps(payload), headers=headers)
80
+ response = connection.getresponse()
81
+ return response.status, response.read().decode(errors="replace")
82
+ except (OSError, http.client.HTTPException) as e:
83
+ sys.stderr.write(f"cannot reach the app at {url.geturl()}: {e}\n")
84
+ return None
85
+ finally:
86
+ connection.close()
aiwe/config.py ADDED
@@ -0,0 +1,73 @@
1
+ """`config.toml` in the data dir: the settings of a server that only a person with the server itself may change."""
2
+
3
+ import re
4
+ import tomllib
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from aiwe.core.features.dictation.voxo import Voxo
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class CloudflareAccess:
13
+ """The Cloudflare Access application that guards the public host: the table `cloudflare_access` of the file."""
14
+
15
+ team_domain: str # the name that signs the tokens, such as myteam.cloudflareaccess.com
16
+ audience: str # the Application Audience (AUD) tag of the application
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Config:
21
+ """What `config.toml` in the data dir sets. The file is optional, and the server reads it once, at its start."""
22
+
23
+ public_host: str | None # the name a proxy serves the app by, with no scheme and no port; None = local names only
24
+ cloudflare_access: CloudflareAccess | None # None = a request under the public host needs no token of Access
25
+ voxo: Voxo | None # the table `voxo` of the file; None = the app has no dictation
26
+
27
+ @classmethod
28
+ def load(cls, data_dir: Path) -> Config:
29
+ """The config of the server on *data_dir*; with no file there, nothing is set.
30
+
31
+ ValueError that names the file: for a file that is not TOML, for a key the app does not know, for a value of
32
+ the wrong form, and for `cloudflare_access` with no public host. A mistyped key would otherwise leave its
33
+ setting off without a word, and the app open.
34
+ """
35
+ path = data_dir / "config.toml"
36
+ if not path.exists():
37
+ return cls(public_host=None, cloudflare_access=None, voxo=None)
38
+ try:
39
+ with path.open("rb") as f:
40
+ values = tomllib.load(f)
41
+ except tomllib.TOMLDecodeError as e:
42
+ raise ValueError(f"{path}: {e}") from e
43
+ if unknown := values.keys() - {"public_host", "cloudflare_access", "voxo"}:
44
+ raise ValueError(f"{path}: unknown key {', '.join(sorted(unknown))}")
45
+ public_host = values.get("public_host")
46
+ if public_host is not None and not _is_host_name(public_host):
47
+ raise ValueError(f"{path}: public_host is a name such as aiwe.example.com, in lowercase, with no scheme or port")
48
+ access = values.get("cloudflare_access")
49
+ if access is not None:
50
+ if public_host is None:
51
+ raise ValueError(f"{path}: cloudflare_access needs public_host")
52
+ if not isinstance(access, dict) or access.keys() != {"team_domain", "audience"}:
53
+ raise ValueError(f"{path}: cloudflare_access is a table of team_domain and audience, and nothing else")
54
+ if not _is_host_name(access["team_domain"]):
55
+ raise ValueError(f"{path}: team_domain is a name such as myteam.cloudflareaccess.com, with no scheme")
56
+ if not isinstance(access["audience"], str) or not access["audience"]:
57
+ raise ValueError(f"{path}: audience is the Application Audience (AUD) tag of the Access application")
58
+ access = CloudflareAccess(access["team_domain"], access["audience"])
59
+ voxo = values.get("voxo")
60
+ if voxo is not None:
61
+ if not isinstance(voxo, dict) or voxo.keys() != {"url", "token"}:
62
+ raise ValueError(f"{path}: voxo is a table of url and token, and nothing else")
63
+ if not isinstance(voxo["url"], str) or re.fullmatch(r"https?://[a-z0-9.-]+(:\d+)?", voxo["url"]) is None:
64
+ raise ValueError(f"{path}: url of voxo is an address such as http://127.0.0.1:7711, with no path")
65
+ if not isinstance(voxo["token"], str) or not voxo["token"]:
66
+ raise ValueError(f"{path}: token of voxo is what `voxo token` prints")
67
+ voxo = Voxo(voxo["url"], voxo["token"])
68
+ return cls(public_host, access, voxo)
69
+
70
+
71
+ def _is_host_name(value: object) -> bool:
72
+ """Whether *value* is a host name as the config takes one: lowercase, with a dot, and no scheme, port or path."""
73
+ return isinstance(value, str) and re.fullmatch(r"[a-z0-9-]+(\.[a-z0-9-]+)+", value) is not None
aiwe/core/__init__.py ADDED
File without changes