arvex.ai 0.1.2__tar.gz

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.
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ dist/
5
+ .aras/
6
+ tests/
7
+ Readme
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.5
2
+ Name: arvex.ai
3
+ Version: 0.1.2
4
+ Summary: A Python foundation for project-local AI agents
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: filelock<5,>=3.16
7
+ Requires-Dist: pyjwt[crypto]<3,>=2.10.1
8
+ Description-Content-Type: text/markdown
9
+
10
+ # arvex.ai
11
+
12
+ Arvex is a Python foundation for agents that live in your project.
13
+ It requires Python 3.11 or later. [Feature history](VERSIONS.md)
14
+
15
+ ## Install with uv
16
+
17
+ From the checkout, install the package and run the demos.
18
+
19
+ ```sh
20
+ uv sync
21
+ uv run python demo/1_chat.py
22
+ uv run python demo/2_setup.py
23
+ uv run python demo/3_create_agent.py
24
+ ```
25
+
26
+ `uv build` creates a source distribution and wheel in `dist/`. The version
27
+ comes from the latest version tag reachable from the checked-out commit. Tags
28
+ such as `0.1.1` and `v0.1.1` both produce version `0.1.1`. Later commits and
29
+ local edits use that same version until a new tag is reachable. A checkout
30
+ needs a version tag to build. The source distribution carries its resolved
31
+ version so it can be built without Git.
32
+
33
+ Install the resulting wheel into a virtual environment with
34
+ `uv pip install PATH_TO_WHEEL`, using the path printed by `uv build`.
35
+
36
+ ## Chat from Python
37
+
38
+ ```python
39
+ from arvex.ai import create_agent, load_agent, setup
40
+
41
+ setup()
42
+ agent = create_agent("aras", instructions="Be concise.")
43
+ print(agent.chat("Hello, Aras.", demo=True))
44
+
45
+ # In a later process in the same directory
46
+ agent = load_agent("aras")
47
+ print(agent.history())
48
+ ```
49
+
50
+ Pass a directory to `setup()` to use a custom location for shared settings.
51
+ Pass `api_key=` to record an OpenAI credential from Python.
52
+
53
+ ## Chat from the terminal
54
+
55
+ ```sh
56
+ uv run arvex setup
57
+ uv run arvex create-agent aras --instructions "Be concise."
58
+ uv run arvex chat aras --demo
59
+ ```
60
+
61
+ Use `/exit` to leave interactive chat or `-m "Hello"` to send one message.
62
+
63
+ ## Connect your ChatGPT account
64
+
65
+ ```sh
66
+ uv run arvex setup --chatgpt
67
+ uv run arvex chat aras -m "Hello"
68
+ ```
69
+
70
+ Complete the browser sign-in and approve use of your ChatGPT plan. Eligible
71
+ requests use that plan. Arvex picks an available model for the connected
72
+ account. Use `arvex setup --chatgpt --model MODEL` to choose another available
73
+ model or `arvex setup --chatgpt work` to connect under a separate account label.
74
+ Existing agents use the selected account and its model the next time you chat.
75
+ [OpenAI sign-in and plan usage](https://developers.openai.com/siwc/token-sharing-open-source)
76
+
77
+ In Python, use `setup(chatgpt=True)`. The
78
+ [live sign-in demo](demo/4_chatgpt.py) opens the browser and sends one request
79
+ using the connected plan.
80
+
81
+ To use API-key billing, set `OPENAI_API_KEY` and run
82
+ `uv run arvex setup --use-api-key`, or record a key with
83
+ `uv run arvex setup --prompt-key`. Agents use their own configured model in
84
+ API-key mode. The default for newly created agents is `gpt-4.1-mini`.
@@ -0,0 +1,75 @@
1
+ # arvex.ai
2
+
3
+ Arvex is a Python foundation for agents that live in your project.
4
+ It requires Python 3.11 or later. [Feature history](VERSIONS.md)
5
+
6
+ ## Install with uv
7
+
8
+ From the checkout, install the package and run the demos.
9
+
10
+ ```sh
11
+ uv sync
12
+ uv run python demo/1_chat.py
13
+ uv run python demo/2_setup.py
14
+ uv run python demo/3_create_agent.py
15
+ ```
16
+
17
+ `uv build` creates a source distribution and wheel in `dist/`. The version
18
+ comes from the latest version tag reachable from the checked-out commit. Tags
19
+ such as `0.1.1` and `v0.1.1` both produce version `0.1.1`. Later commits and
20
+ local edits use that same version until a new tag is reachable. A checkout
21
+ needs a version tag to build. The source distribution carries its resolved
22
+ version so it can be built without Git.
23
+
24
+ Install the resulting wheel into a virtual environment with
25
+ `uv pip install PATH_TO_WHEEL`, using the path printed by `uv build`.
26
+
27
+ ## Chat from Python
28
+
29
+ ```python
30
+ from arvex.ai import create_agent, load_agent, setup
31
+
32
+ setup()
33
+ agent = create_agent("aras", instructions="Be concise.")
34
+ print(agent.chat("Hello, Aras.", demo=True))
35
+
36
+ # In a later process in the same directory
37
+ agent = load_agent("aras")
38
+ print(agent.history())
39
+ ```
40
+
41
+ Pass a directory to `setup()` to use a custom location for shared settings.
42
+ Pass `api_key=` to record an OpenAI credential from Python.
43
+
44
+ ## Chat from the terminal
45
+
46
+ ```sh
47
+ uv run arvex setup
48
+ uv run arvex create-agent aras --instructions "Be concise."
49
+ uv run arvex chat aras --demo
50
+ ```
51
+
52
+ Use `/exit` to leave interactive chat or `-m "Hello"` to send one message.
53
+
54
+ ## Connect your ChatGPT account
55
+
56
+ ```sh
57
+ uv run arvex setup --chatgpt
58
+ uv run arvex chat aras -m "Hello"
59
+ ```
60
+
61
+ Complete the browser sign-in and approve use of your ChatGPT plan. Eligible
62
+ requests use that plan. Arvex picks an available model for the connected
63
+ account. Use `arvex setup --chatgpt --model MODEL` to choose another available
64
+ model or `arvex setup --chatgpt work` to connect under a separate account label.
65
+ Existing agents use the selected account and its model the next time you chat.
66
+ [OpenAI sign-in and plan usage](https://developers.openai.com/siwc/token-sharing-open-source)
67
+
68
+ In Python, use `setup(chatgpt=True)`. The
69
+ [live sign-in demo](demo/4_chatgpt.py) opens the browser and sends one request
70
+ using the connected plan.
71
+
72
+ To use API-key billing, set `OPENAI_API_KEY` and run
73
+ `uv run arvex setup --use-api-key`, or record a key with
74
+ `uv run arvex setup --prompt-key`. Agents use their own configured model in
75
+ API-key mode. The default for newly created agents is `gpt-4.1-mini`.
@@ -0,0 +1,26 @@
1
+ # Versions
2
+
3
+ ## 0.1.2
4
+
5
+ - Derive the package version during `uv build` from the latest reachable Git
6
+ version tag.
7
+
8
+ ## 0.1.1
9
+ - Add `arvex setup --chatgpt` and `setup(chatgpt=True)` for browser sign-in,
10
+ selectable ChatGPT accounts, and chat using the connected plan.
11
+ [Live sign-in demo](demo/4_chatgpt.py)
12
+
13
+ ## 0.1.0
14
+
15
+ - Add `setup()` and `load_credentials()` for shared configuration and OpenAI
16
+ credentials. Setup defaults to `~/.config/arvex/ai/config.json` and accepts a
17
+ custom directory. [Setup demo](demo/2_setup.py)
18
+ - Add `create_agent()` and `load_agent()` for local agent directories with
19
+ settings, memory, and a place to store skill files. For example,
20
+ `create_agent("aras")` creates `.aras/` in the current directory.
21
+ [Agent creation demo](demo/3_create_agent.py)
22
+ - Add Python and CLI chat with up to three model steps per turn, persistent
23
+ history, and an offline demo mode. Live chat uses the OpenAI Responses API.
24
+ [Chat demo](demo/1_chat.py) · [Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create)
25
+ - Build and install the `arvex.ai` package with uv.
26
+
@@ -0,0 +1,27 @@
1
+ """Chat from Python and the CLI using one temporary agent."""
2
+
3
+ from pathlib import Path
4
+ import subprocess
5
+ import sys
6
+ from tempfile import TemporaryDirectory
7
+
8
+ from arvex.ai import create_agent, load_agent, setup
9
+
10
+
11
+ with TemporaryDirectory() as directory:
12
+ project = Path(directory)
13
+ config = setup(project / "config")
14
+ agent = create_agent("aras", project, config_dir=config)
15
+ print(agent.chat("Hello from Python.", demo=True))
16
+
17
+ result = subprocess.run(
18
+ [sys.executable, "-m", "arvex.ai", "chat", "aras", "--demo", "-m", "Hello from the CLI."],
19
+ cwd=project, check=True, text=True, capture_output=True,
20
+ )
21
+ print(result.stdout.strip())
22
+
23
+ history = load_agent("aras", project).history()
24
+ assert [entry["content"] for entry in history if entry["role"] == "user"] == [
25
+ "Hello from Python.", "Hello from the CLI.",
26
+ ]
27
+ print(f"Reopened the agent with {len(history)} saved messages.")
@@ -0,0 +1,14 @@
1
+ """Save and reload temporary configuration with a dummy credential."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from tempfile import TemporaryDirectory
6
+
7
+ from arvex.ai import load_credentials, setup
8
+
9
+
10
+ with TemporaryDirectory() as directory:
11
+ config = setup(Path(directory) / "config", api_key="example-only")
12
+ setup(config, model="gpt-4.1-mini")
13
+ assert json.loads((config / "config.json").read_text())["credentials"]["openai_api_key"] == "example-only"
14
+ print("Shared config created and credential loaded:", bool(load_credentials(config).get("openai_api_key")))
@@ -0,0 +1,18 @@
1
+ """Create and reopen a named agent with separate config, memory, and skill files."""
2
+
3
+ from pathlib import Path
4
+ from tempfile import TemporaryDirectory
5
+
6
+ from arvex.ai import create_agent, load_agent, setup
7
+
8
+
9
+ with TemporaryDirectory() as directory:
10
+ project = Path(directory)
11
+ config = setup(project / "config")
12
+ agent = create_agent("aras", project, config_dir=config, instructions="Be concise.")
13
+ (agent.path / "skills" / "example.md").write_text("# Example skill\nSummarize the supplied text.\n", encoding="utf-8")
14
+ reopened = load_agent(directory=project)
15
+ assert reopened.instructions == "Be concise."
16
+ assert reopened.history() == []
17
+ for entry in sorted(reopened.path.rglob("*")):
18
+ print(entry.relative_to(project))
@@ -0,0 +1,12 @@
1
+ """Sign in with ChatGPT, then chat once using the connected account."""
2
+
3
+ from tempfile import TemporaryDirectory
4
+
5
+ from arvex.ai import create_agent, setup
6
+
7
+
8
+ if __name__ == "__main__":
9
+ config = setup(chatgpt=True)
10
+ with TemporaryDirectory() as project:
11
+ agent = create_agent("aras", project, config_dir=config)
12
+ print(agent.chat("Explain what a project-local agent is in one sentence."))
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27", "versioningit>=3.2,<4"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "arvex.ai"
7
+ dynamic = ["version"]
8
+ description = "A Python foundation for project-local AI agents"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = ["PyJWT[crypto]>=2.10.1,<3", "filelock>=3.16,<5"]
12
+
13
+ [project.scripts]
14
+ arvex = "arvex.ai.cli:main"
15
+
16
+ [tool.hatch.version]
17
+ source = "versioningit"
18
+
19
+ [tool.versioningit.vcs]
20
+ match = ["[0-9]*.[0-9]*.[0-9]*", "v[0-9]*.[0-9]*.[0-9]*"]
21
+
22
+ [tool.versioningit.format]
23
+ distance = "{base_version}"
24
+ dirty = "{base_version}"
25
+ distance-dirty = "{base_version}"
26
+
27
+ [tool.hatch.build.targets.wheel]
28
+ packages = ["src/arvex"]
29
+
30
+ [tool.hatch.build.targets.sdist]
31
+ include = ["/src/arvex", "/demo", "/README.md", "/VERSIONS.md"]
@@ -0,0 +1,6 @@
1
+ """Create, configure, and chat with project-local agents."""
2
+
3
+ from .agent import Agent, create_agent, load_agent
4
+ from .settings import ArvexError, load_credentials, setup
5
+
6
+ __all__ = ["Agent", "ArvexError", "create_agent", "load_agent", "load_credentials", "setup"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,171 @@
1
+ """Project-local agents, memory, and the shared chat loop."""
2
+
3
+ from contextlib import closing, suppress
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ import re
7
+ from shutil import rmtree
8
+ import sqlite3
9
+
10
+ from .provider import DemoProvider, OpenAIProvider
11
+ from .settings import ArvexError, config_directory, load_credentials, read_json, shared_settings, write_json
12
+
13
+
14
+ _TURN_LIMIT = 3
15
+ _MESSAGE_LIMIT = 12000
16
+ _INSTRUCTIONS = (
17
+ "Answer the latest user message using the conversation. Return status 'continue' with a short draft "
18
+ "when the answer needs another pass. Review and revise an existing draft when needed. Return status "
19
+ "'final' with the user-facing answer when ready. Ask a direct question if more information is needed. "
20
+ "Work with the information provided. You have no tools."
21
+ )
22
+
23
+
24
+ def validate_name(name):
25
+ if not isinstance(name, str) or re.fullmatch("[A-Za-z0-9][A-Za-z0-9_-]{0,47}", name) is None:
26
+ raise ArvexError("Agent names must contain 1–48 letters, digits, underscores, or hyphens.")
27
+
28
+
29
+ def project_directory(directory):
30
+ project = Path.cwd() if directory is None else Path(directory).expanduser().resolve()
31
+ if not project.is_dir():
32
+ raise ArvexError(f"Project directory does not exist: {project}")
33
+ return project
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Agent:
38
+ name: str
39
+ path: Path
40
+ model: str
41
+ instructions: str
42
+ config_dir: Path
43
+
44
+ def _connect(self):
45
+ database = (self.path / "memory" / "chat.sqlite3").as_uri()
46
+ return closing(sqlite3.connect(database + "?mode=rw", uri=True))
47
+
48
+ def history(self) -> list[dict[str, str]]:
49
+ """Return completed user and assistant messages in conversation order."""
50
+ with self._connect() as db:
51
+ turns = db.execute("SELECT message, answer FROM turns ORDER BY id").fetchall()
52
+ return conversation(turns)
53
+
54
+ def chat(self, message: str, *, demo: bool = False) -> str:
55
+ """Run one turn and store the user message and final answer together."""
56
+ if not isinstance(message, str) or not message.strip() or len(message) > _MESSAGE_LIMIT:
57
+ raise ArvexError(f"Enter a message of 1–{_MESSAGE_LIMIT:,} characters.")
58
+ message = message.strip()
59
+ if demo:
60
+ provider = DemoProvider()
61
+ elif account := shared_settings(self.config_dir).get("chatgpt_account"):
62
+ from .chatgpt import credentials
63
+
64
+ token, model = credentials(self.config_dir, account)
65
+ provider = OpenAIProvider(model, token, chatgpt=True)
66
+ else:
67
+ key = load_credentials(self.config_dir).get("openai_api_key", "").strip()
68
+ if not key:
69
+ raise ArvexError("Run arvex setup --chatgpt, run arvex setup --prompt-key, or set OPENAI_API_KEY.")
70
+ provider = OpenAIProvider(self.model, key)
71
+
72
+ with self._connect() as db, db:
73
+ # Serialize writers so CLI and Python turns see the same ordered history.
74
+ db.execute("BEGIN IMMEDIATE")
75
+ newest = db.execute("SELECT message, answer FROM turns ORDER BY id DESC LIMIT 10").fetchall()
76
+ recent = []
77
+ remaining = 20_000
78
+ for previous, answer in newest:
79
+ remaining -= len(previous) + len(answer)
80
+ if remaining < 0:
81
+ break
82
+ recent.append((previous, answer))
83
+ messages = [*conversation(reversed(recent)), {"role": "user", "content": message}]
84
+ answer = run_turn(provider, f"You are {self.name}.\n{self.instructions}\n{_INSTRUCTIONS}", messages)
85
+ db.execute("INSERT INTO turns(message, answer) VALUES (?, ?)", (message, answer))
86
+ return answer
87
+
88
+
89
+ def conversation(turns):
90
+ return [entry for message, answer in turns for entry in (
91
+ {"role": "user", "content": message}, {"role": "assistant", "content": answer},
92
+ )]
93
+
94
+
95
+ def run_turn(provider, instructions, messages):
96
+ draft = None
97
+ for _ in range(_TURN_LIMIT):
98
+ step = provider.step(instructions, messages, draft)
99
+ if (not isinstance(step, dict) or set(step) != {"status", "text"}
100
+ or step["status"] not in ("continue", "final")
101
+ or not isinstance(step["text"], str) or not step["text"].strip()
102
+ or len(step["text"]) > _MESSAGE_LIMIT):
103
+ raise ArvexError("The model returned an invalid chat step.")
104
+ if step["status"] == "final":
105
+ return step["text"].strip()
106
+ draft = step["text"]
107
+ raise ArvexError(f"The agent reached its {_TURN_LIMIT}-step limit before producing an answer.")
108
+
109
+
110
+ def create_agent(name: str, directory: str | Path | None = None, *,
111
+ config_dir: str | Path | None = None, model: str | None = None,
112
+ instructions: str = "Be helpful and clear.") -> Agent:
113
+ """Create an agent in .NAME under the current working directory or a given project."""
114
+ validate_name(name)
115
+ project = project_directory(directory)
116
+ destination = project / f".{name}"
117
+ root = config_directory(config_dir)
118
+ model = shared_settings(root)["model"] if model is None else model
119
+ for setting in (model, instructions):
120
+ if not isinstance(setting, str) or not setting.strip():
121
+ raise ArvexError("The agent's model and instructions must be nonempty strings.")
122
+ data = {"name": name, "model": model.strip(), "instructions": instructions,
123
+ "config_dir": str(root)}
124
+
125
+ try:
126
+ destination.mkdir(mode=0o700)
127
+ except FileExistsError:
128
+ raise ArvexError(f"{destination} already exists. Use load_agent() for an existing agent.") from None
129
+ try:
130
+ (destination / "skills").mkdir(mode=0o700)
131
+ memory = destination / "memory"
132
+ memory.mkdir(mode=0o700)
133
+ database = memory / "chat.sqlite3"
134
+ database.touch(mode=0o600, exist_ok=False)
135
+ with closing(sqlite3.connect(database)) as db:
136
+ db.execute("CREATE TABLE turns (id INTEGER PRIMARY KEY, message TEXT NOT NULL, answer TEXT NOT NULL)")
137
+ write_json(destination / "agent.json", data)
138
+ except BaseException:
139
+ with suppress(OSError):
140
+ rmtree(destination)
141
+ raise
142
+ return load_agent(name, project)
143
+
144
+
145
+ def load_agent(name: str | None = None, directory: str | Path | None = None) -> Agent:
146
+ """Load a project agent by name, or select it when the project has exactly one."""
147
+ project = project_directory(directory)
148
+ if name is None:
149
+ choices = sorted(path.name[1:] for path in project.glob(".*")
150
+ if not path.is_symlink() and (path / "agent.json").is_file())
151
+ if not choices:
152
+ raise ArvexError(f"No agents exist in {project}. Create one with create_agent().")
153
+ if len(choices) != 1:
154
+ raise ArvexError("Choose an agent by name. Available agents: " + ", ".join(choices))
155
+ name = choices[0]
156
+ validate_name(name)
157
+ path = project / f".{name}"
158
+ if path.is_symlink() or (path / "agent.json").is_symlink():
159
+ raise ArvexError("Agent directories and configuration files cannot be symbolic links.")
160
+ try:
161
+ data = read_json(path / "agent.json")
162
+ except FileNotFoundError:
163
+ raise ArvexError(f"No agent named {name} exists in {project}.") from None
164
+ if (data.get("name") != name
165
+ or any(not isinstance(data.get(key), str) or not data[key].strip()
166
+ for key in ("model", "instructions", "config_dir"))
167
+ or not Path(data["config_dir"]).is_absolute()):
168
+ raise ArvexError(f"Invalid agent configuration in {path}.")
169
+ if not (path / "memory" / "chat.sqlite3").is_file():
170
+ raise ArvexError(f"Agent memory is missing in {path}.")
171
+ return Agent(name, path, data["model"], data["instructions"], Path(data["config_dir"]))
@@ -0,0 +1,291 @@
1
+ """Sign in with ChatGPT and renew scoped credentials for Responses API requests."""
2
+
3
+ from base64 import urlsafe_b64encode
4
+ import hashlib
5
+ from http.server import BaseHTTPRequestHandler, HTTPServer
6
+ import json
7
+ import re
8
+ import secrets
9
+ import time
10
+ from urllib.error import HTTPError, URLError
11
+ from urllib.parse import parse_qs, urlencode, urlsplit
12
+ from urllib.request import Request, build_opener
13
+ import uuid
14
+ import webbrowser
15
+
16
+ from filelock import FileLock, Timeout
17
+ import jwt
18
+
19
+ from .provider import NoRedirect
20
+ from .settings import ArvexError, read_json, write_json
21
+
22
+
23
+ _ISSUER = "https://auth.openai.com"
24
+ _RESOURCE = "https://api.openai.com/v1"
25
+ _REGISTRATION_CLIENT = "dynamic_agent_client"
26
+ _CALLBACK = "/auth/callback"
27
+ _SCOPES = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct"
28
+ _PLAN_SCOPES = {"resource.invoke", "chatgpt.tokens.use.direct"}
29
+ _EXPIRED_REFRESH = {"invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_expired",
30
+ "refresh_token_invalidated", "refresh_token_reused"}
31
+
32
+
33
+ class OAuthError(ArvexError):
34
+ def __init__(self, status, code=None):
35
+ super().__init__(f"OpenAI rejected the ChatGPT request (HTTP {status}).")
36
+ self.code = code
37
+
38
+
39
+ def _json_request(url, *, form=None, token=None):
40
+ headers = {"Accept": "application/json"}
41
+ if token is not None:
42
+ headers["Authorization"] = "Bearer " + token
43
+ if form is not None:
44
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
45
+ try:
46
+ request = Request(url, data=urlencode(form).encode() if form is not None else None, headers=headers)
47
+ with build_opener(NoRedirect).open(request, timeout=25) as response:
48
+ body = response.read(1_000_001)
49
+ if len(body) <= 1_000_000 and isinstance(data := json.loads(body), dict):
50
+ return data
51
+ except HTTPError as error:
52
+ with error:
53
+ try:
54
+ value = json.loads(error.read(16_384))["error"]
55
+ code = value.get("code") if isinstance(value, dict) else value
56
+ except (KeyError, TypeError, ValueError, OSError):
57
+ code = None
58
+ raise OAuthError(error.code, code if isinstance(code, str) else None) from None
59
+ except (URLError, OSError):
60
+ raise ArvexError("Could not reach OpenAI for ChatGPT sign-in or token renewal.") from None
61
+ except (ValueError, TypeError):
62
+ pass
63
+ raise ArvexError("OpenAI returned an invalid ChatGPT response.")
64
+
65
+
66
+ def _exchange(**form):
67
+ return _json_request(_ISSUER + "/api/accounts/oauth/token", form={**form, "resource": _RESOURCE})
68
+
69
+
70
+ def _callback(query, state, client_id):
71
+ def field(name):
72
+ values = query.get(name, [])
73
+ return values[0] if len(values) == 1 else ""
74
+
75
+ if not secrets.compare_digest(field("state").encode(), state.encode()):
76
+ raise ArvexError("The ChatGPT sign-in state did not match.")
77
+ if "error" in query:
78
+ raise ArvexError("ChatGPT sign-in or consent was declined. Run setup again to reconnect.")
79
+ issued = field("client_id") if "client_id" in query else client_id
80
+ if not issued or issued == _REGISTRATION_CLIENT or (client_id and issued != client_id):
81
+ raise ArvexError("The ChatGPT callback did not return the expected client ID.")
82
+ if not (code := field("code")):
83
+ raise ArvexError("The ChatGPT callback did not contain an authorization code.")
84
+ return code, issued
85
+
86
+
87
+ def _authorize(host, previous, show, timeout=180):
88
+ state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
89
+ client_id = previous.get("client_id")
90
+ result = []
91
+
92
+ class Callback(BaseHTTPRequestHandler):
93
+ def setup(self):
94
+ self.request.settimeout(5)
95
+ super().setup()
96
+
97
+ def log_message(self, *args):
98
+ pass
99
+
100
+ def do_GET(self):
101
+ parsed = urlsplit(self.path)
102
+ if parsed.path != _CALLBACK:
103
+ self.send_error(404)
104
+ return
105
+ try:
106
+ query = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=20)
107
+ except ValueError:
108
+ self.send_error(400)
109
+ return
110
+ if query.get("state") != [state]:
111
+ self.send_error(400, "Invalid sign-in state")
112
+ return
113
+ try:
114
+ result.append(_callback(query, state, client_id))
115
+ except ArvexError as error:
116
+ result.append(error)
117
+ body = b"Return to Arvex to see your sign-in result."
118
+ self.send_response(200)
119
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
120
+ self.send_header("Cache-Control", "no-store")
121
+ self.send_header("Referrer-Policy", "no-referrer")
122
+ self.send_header("Content-Length", str(len(body)))
123
+ self.end_headers()
124
+ self.wfile.write(body)
125
+
126
+ with HTTPServer(("127.0.0.1", 0), Callback) as server:
127
+ redirect_uri = f"http://127.0.0.1:{server.server_port}{_CALLBACK}"
128
+ params = {
129
+ "client_id": client_id or _REGISTRATION_CLIENT,
130
+ "ext_agent_host_id": host, "response_type": "code", "redirect_uri": redirect_uri,
131
+ "scope": _SCOPES, "resource": _RESOURCE, "state": state, "nonce": nonce,
132
+ "code_challenge_method": "S256",
133
+ "code_challenge": urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("="),
134
+ }
135
+ if not client_id:
136
+ params["agent_name_hint"] = "Arvex"
137
+ elif not _PLAN_SCOPES.issubset(previous.get("scopes", [])):
138
+ params["prompt"] = "consent"
139
+ authorize = _ISSUER + "/api/accounts/authorize?"
140
+ show("Continue with ChatGPT in your browser. If it does not open, visit:\n" + authorize + urlencode(params))
141
+ if previous.get("id_token"):
142
+ params["id_token_hint"] = previous["id_token"]
143
+ webbrowser.open(authorize + urlencode(params))
144
+
145
+ deadline = time.monotonic() + timeout
146
+ while not result and (remaining := deadline - time.monotonic()) > 0:
147
+ server.timeout = remaining
148
+ server.handle_request()
149
+ if not result:
150
+ raise ArvexError("ChatGPT sign-in timed out. Run setup again to reconnect.")
151
+ if isinstance(result[0], ArvexError):
152
+ raise result[0]
153
+ code, issued = result[0]
154
+ return issued, nonce, _exchange(grant_type="authorization_code", client_id=issued, code=code,
155
+ code_verifier=verifier, redirect_uri=redirect_uri)
156
+
157
+
158
+ def _identity(token, client_id, nonce, previous_subject=None):
159
+ try:
160
+ key = jwt.PyJWKClient(_ISSUER + "/.well-known/jwks.json", timeout=15).get_signing_key_from_jwt(token)
161
+ claims = jwt.decode(token, key.key, algorithms=["RS256"], issuer=_ISSUER, audience=client_id,
162
+ leeway=5, options={"require": ["exp", "iat", "sub", "nonce"]})
163
+ audience = claims["aud"]
164
+ valid_audience = not isinstance(audience, list) or len(audience) == 1 or claims.get("azp") == client_id
165
+ if (claims["nonce"] == nonce and isinstance(claims["sub"], str) and claims["sub"] and valid_audience
166
+ and (previous_subject is None or claims["sub"] == previous_subject)):
167
+ return claims
168
+ except (jwt.PyJWTError, ValueError, TypeError):
169
+ pass
170
+ raise ArvexError("Could not verify the ChatGPT account identity.")
171
+
172
+
173
+ def _token_fields(tokens, previous=None):
174
+ scope = tokens.get("scope")
175
+ scopes = (previous or {}).get("scopes", [])
176
+ if scope is not None:
177
+ scopes = scope.split() if isinstance(scope, str) else []
178
+ record = {"scopes": scopes}
179
+ if not _PLAN_SCOPES.issubset(scopes):
180
+ return record
181
+ expiry = tokens.get("expires_in")
182
+ fields = ("access_token", "refresh_token")
183
+ if (str(tokens.get("token_type", "")).lower() != "bearer"
184
+ or type(expiry) is not int or expiry <= 0
185
+ or any(not isinstance(tokens.get(key), str) or not tokens[key].strip() for key in fields)):
186
+ raise ArvexError("OpenAI returned an incomplete ChatGPT token set.")
187
+ return {**record, **{key: tokens[key] for key in fields}, "expires_at": time.time() + expiry}
188
+
189
+
190
+ def _available_models(token):
191
+ models = _json_request(_RESOURCE + "/models", token=token).get("models")
192
+ if not isinstance(models, list):
193
+ raise ArvexError("OpenAI did not return a ChatGPT model list.")
194
+ available = [model["slug"] for model in models if isinstance(model, dict) and model.get("visibility") == "list"
195
+ and isinstance(model.get("slug"), str) and model["slug"]]
196
+ if not available:
197
+ raise ArvexError("No models are available for this ChatGPT account.")
198
+ return available
199
+
200
+
201
+ def _store(path):
202
+ try:
203
+ data = read_json(path)
204
+ except FileNotFoundError:
205
+ return {"host_id": "urn:uuid:" + str(uuid.uuid4()), "accounts": {}}
206
+ if not isinstance(data.get("host_id"), str) or not isinstance(data.get("accounts"), dict):
207
+ raise ArvexError("The saved ChatGPT connections could not be read.")
208
+ return data
209
+
210
+
211
+ def _lock(directory):
212
+ return FileLock(directory / "chatgpt.lock", timeout=30, mode=0o600)
213
+
214
+
215
+ def _save_connection(path, account, previous, record):
216
+ with _lock(path.parent):
217
+ store = _store(path)
218
+ current = store["accounts"].get(account, {})
219
+ if (current.get("client_id") != previous.get("client_id")
220
+ or current.get("subject") != previous.get("subject")):
221
+ raise ArvexError("The saved ChatGPT account changed during sign-in. Run setup again.")
222
+ store["accounts"][account] = record
223
+ write_json(path, store)
224
+
225
+
226
+ def connect(directory, account, model, show=print):
227
+ if not isinstance(account, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,47}", account):
228
+ raise ArvexError("Use a ChatGPT account label of 1–48 letters, digits, underscores, or hyphens.")
229
+ path = directory / "chatgpt.json"
230
+ try:
231
+ with _lock(directory):
232
+ store = _store(path)
233
+ if not path.exists():
234
+ write_json(path, store)
235
+ previous = store["accounts"].get(account, {})
236
+ client_id, nonce, tokens = _authorize(store["host_id"], previous, show)
237
+ claims = _identity(tokens.get("id_token"), client_id, nonce, previous.get("subject"))
238
+ record = {"client_id": client_id, "subject": claims["sub"], "id_token": tokens["id_token"],
239
+ **_token_fields(tokens)}
240
+ granted = "access_token" in record
241
+ if granted:
242
+ try:
243
+ models = _available_models(record["access_token"])
244
+ if model is not None and model not in models:
245
+ raise ArvexError("That model is unavailable for this ChatGPT account. Available: " + ", ".join(models))
246
+ except ArvexError:
247
+ if not previous:
248
+ _save_connection(path, account, previous, record)
249
+ raise
250
+ selected = model or previous.get("model")
251
+ record["model"] = selected if selected in models else models[0]
252
+ _save_connection(path, account, previous, record)
253
+ except Timeout:
254
+ raise ArvexError("The ChatGPT connection is busy. Try again shortly.") from None
255
+ if not granted:
256
+ raise ArvexError("ChatGPT plan usage was not granted. Rerun setup and approve plan usage in your browser.")
257
+ show(f"Connected ChatGPT account {account} using {record['model']}.")
258
+
259
+
260
+ def credentials(directory, account):
261
+ path = directory / "chatgpt.json"
262
+ reconnect = f"Reconnect with arvex setup --chatgpt {account}."
263
+ try:
264
+ with _lock(directory):
265
+ store = _store(path)
266
+ record = store["accounts"].get(account, {})
267
+ if "access_token" not in record or not _PLAN_SCOPES.issubset(record.get("scopes", [])):
268
+ raise ArvexError("ChatGPT plan usage is unavailable. " + reconnect)
269
+ if not record.get("model"):
270
+ raise ArvexError("No ChatGPT model is selected. " + reconnect)
271
+ if record["expires_at"] > time.time() + 60:
272
+ return record["access_token"], record["model"]
273
+ try:
274
+ tokens = _exchange(grant_type="refresh_token", client_id=record["client_id"],
275
+ refresh_token=record["refresh_token"])
276
+ except OAuthError as error:
277
+ if error.code not in _EXPIRED_REFRESH:
278
+ raise
279
+ renewed = {"scopes": []}
280
+ else:
281
+ renewed = _token_fields(tokens, record)
282
+ if "access_token" not in renewed:
283
+ for field in ("access_token", "refresh_token", "id_token", "expires_at"):
284
+ record.pop(field, None)
285
+ record.update(renewed)
286
+ write_json(path, store)
287
+ if "access_token" not in record:
288
+ raise ArvexError("The ChatGPT connection is no longer authorized. " + reconnect)
289
+ return record["access_token"], record["model"]
290
+ except Timeout:
291
+ raise ArvexError("The ChatGPT connection is busy. Try again shortly.") from None
@@ -0,0 +1,61 @@
1
+ """Terminal access to the public Python API."""
2
+
3
+ import argparse
4
+ import getpass
5
+ from importlib.metadata import version
6
+ import sqlite3
7
+ import sys
8
+
9
+ from . import ArvexError, create_agent, load_agent, setup
10
+
11
+
12
+ def main(argv=None):
13
+ parser = argparse.ArgumentParser(prog="arvex", description="Create and chat with a project-local agent.")
14
+ parser.add_argument("--version", action="version", version=version("arvex.ai"))
15
+ commands = parser.add_subparsers(dest="command", required=True)
16
+ configure = commands.add_parser("setup", help="Prepare shared settings and credentials")
17
+ configure.add_argument("--config-dir")
18
+ configure.add_argument("--model")
19
+ auth = configure.add_mutually_exclusive_group()
20
+ auth.add_argument("--prompt-key", action="store_true", help="Record an OpenAI API key using a hidden prompt")
21
+ auth.add_argument("--chatgpt", nargs="?", const="default", metavar="ACCOUNT",
22
+ help="Continue with ChatGPT and select its plan for inference")
23
+ auth.add_argument("--use-api-key", action="store_true", help="Use the configured or environment API key")
24
+ create = commands.add_parser("create-agent", help="Create an agent in the current directory")
25
+ create.add_argument("name")
26
+ create.add_argument("--config-dir")
27
+ create.add_argument("--model")
28
+ create.add_argument("--instructions", default="Be helpful and clear.")
29
+ chat = commands.add_parser("chat", help="Chat with an existing agent")
30
+ chat.add_argument("name", nargs="?")
31
+ chat.add_argument("--message", "-m", help="Send one message and exit")
32
+ chat.add_argument("--demo", action="store_true", help="Use the offline demo instead of a model API")
33
+ args = parser.parse_args(argv)
34
+
35
+ try:
36
+ if args.command == "setup":
37
+ key = getpass.getpass("OpenAI API key: ") if args.prompt_key else None
38
+ chatgpt = False if args.use_api_key else (True if args.chatgpt else None)
39
+ print(setup(args.config_dir, api_key=key, model=args.model, chatgpt=chatgpt,
40
+ account=args.chatgpt or "default"))
41
+ elif args.command == "create-agent":
42
+ agent = create_agent(args.name, config_dir=args.config_dir, model=args.model, instructions=args.instructions)
43
+ print(agent.path)
44
+ else:
45
+ agent = load_agent(args.name)
46
+ if args.message is not None:
47
+ print(agent.chat(args.message, demo=args.demo))
48
+ else:
49
+ print(f"Chat with {agent.name}. Type /exit to leave.")
50
+ while True:
51
+ message = input("you> ").strip()
52
+ if message == "/exit":
53
+ break
54
+ if message:
55
+ print(agent.chat(message, demo=args.demo))
56
+ except (ArvexError, OSError, sqlite3.Error) as error:
57
+ print(f"Error: {error}", file=sys.stderr)
58
+ return 1
59
+ except (EOFError, KeyboardInterrupt):
60
+ print()
61
+ return 0
@@ -0,0 +1,120 @@
1
+ """Model adapters for the bounded turn loop."""
2
+
3
+ import json
4
+ import time
5
+ from urllib.error import HTTPError, URLError
6
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
7
+
8
+ from .settings import ArvexError
9
+
10
+
11
+ STEP_SCHEMA = {
12
+ "type": "object",
13
+ "properties": {
14
+ "status": {"type": "string", "enum": ["continue", "final"]},
15
+ "text": {"type": "string"},
16
+ },
17
+ "required": ["status", "text"],
18
+ "additionalProperties": False,
19
+ }
20
+
21
+
22
+ class NoRedirect(HTTPRedirectHandler):
23
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
24
+ return None
25
+
26
+
27
+ class OpenAIProvider:
28
+ def __init__(self, model, token, *, chatgpt=False):
29
+ self.model = model
30
+ self._token = token
31
+ self._chatgpt = chatgpt
32
+
33
+ def step(self, instructions, messages, draft):
34
+ if draft is not None:
35
+ instructions += "\nReview the last assistant message as a draft for the latest user request."
36
+ messages = [*messages, {"role": "assistant", "content": draft}]
37
+ payload = {
38
+ "model": self.model,
39
+ "instructions": instructions,
40
+ "input": messages,
41
+ "store": False,
42
+ "text": {"format": {"type": "json_schema", "name": "arvex_step",
43
+ "strict": True, "schema": STEP_SCHEMA}},
44
+ }
45
+ if self._chatgpt:
46
+ payload["stream"] = True
47
+ else:
48
+ payload["max_output_tokens"] = 1000
49
+ try:
50
+ request = Request("https://api.openai.com/v1/responses", data=json.dumps(payload).encode(),
51
+ headers={"Content-Type": "application/json",
52
+ "Authorization": "Bearer " + self._token}, method="POST")
53
+ with build_opener(NoRedirect).open(request, timeout=45) as response:
54
+ data = _completed_stream(response) if self._chatgpt else _json_response(response)
55
+ except HTTPError as error:
56
+ error.close()
57
+ if self._chatgpt and error.code == 401:
58
+ raise ArvexError("OpenAI rejected the ChatGPT connection (HTTP 401). "
59
+ "Reconnect your selected account with arvex setup --chatgpt.") from None
60
+ if self._chatgpt and error.code == 429:
61
+ raise ArvexError("ChatGPT plan usage is limited (HTTP 429). Check ChatGPT Settings → Usage.") from None
62
+ raise ArvexError(f"OpenAI request failed (HTTP {error.code}).") from None
63
+ except (URLError, OSError, ValueError):
64
+ raise ArvexError("Could not complete the OpenAI request.") from None
65
+ try:
66
+ if data["status"] != "completed":
67
+ raise ArvexError("The model did not complete its response.")
68
+ parts = [part for item in data["output"] if item["type"] == "message" for part in item["content"]]
69
+ if any(part["type"] == "refusal" for part in parts):
70
+ raise ArvexError("The model declined the request.")
71
+ return json.loads("".join(part["text"] for part in parts if part["type"] == "output_text"))
72
+ except (KeyError, TypeError, ValueError):
73
+ raise ArvexError("The model returned an invalid response.") from None
74
+
75
+
76
+ def _json_response(response):
77
+ raw = response.read(1_000_001)
78
+ if len(raw) > 1_000_000:
79
+ raise ArvexError("The model response was too large.")
80
+ try:
81
+ return json.loads(raw)
82
+ except ValueError:
83
+ raise ArvexError("The model returned an invalid response.") from None
84
+
85
+
86
+ def _completed_stream(response):
87
+ deadline = time.monotonic() + 120
88
+ size = 0
89
+ fields = []
90
+ while line := response.readline(1_000_001):
91
+ size += len(line)
92
+ if len(line) > 1_000_000 or size > 4_000_000 or time.monotonic() >= deadline:
93
+ raise ArvexError("The ChatGPT stream exceeded its size or time limit.")
94
+ if line.startswith(b"data:"):
95
+ fields.append(line[5:].strip())
96
+ elif not line.strip() and fields:
97
+ body = b"\n".join(fields)
98
+ fields.clear()
99
+ try:
100
+ event = json.loads(body)
101
+ kind = event["type"]
102
+ if kind == "response.completed":
103
+ return event["response"]
104
+ if kind == "response.failed":
105
+ error = event["response"].get("error") or {}
106
+ if error.get("code") == "subscription_sharing_usage_limit_exceeded":
107
+ raise ArvexError("ChatGPT plan usage is limited. Check ChatGPT Settings → Usage.")
108
+ raise ArvexError("The ChatGPT model request failed.")
109
+ if kind in {"error", "response.incomplete"}:
110
+ raise ArvexError("The ChatGPT model did not complete its response.")
111
+ except (AttributeError, KeyError, TypeError, ValueError):
112
+ raise ArvexError("The ChatGPT stream contained an invalid event.") from None
113
+ raise ArvexError("The ChatGPT stream ended before the response completed.")
114
+
115
+
116
+ class DemoProvider:
117
+ def step(self, instructions, messages, draft):
118
+ if draft is None:
119
+ return {"status": "continue", "text": "Prepare an offline echo of the latest request."}
120
+ return {"status": "final", "text": f"Offline demo: {messages[-1]['content']}"}
@@ -0,0 +1,89 @@
1
+ """Shared settings and credentials kept outside project agent directories."""
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from tempfile import NamedTemporaryFile
7
+
8
+
9
+ DEFAULT_MODEL = "gpt-4.1-mini"
10
+
11
+
12
+ class ArvexError(Exception):
13
+ """An Arvex operation could not be completed."""
14
+
15
+
16
+ def config_directory(directory=None):
17
+ return (Path(directory).expanduser() if directory is not None
18
+ else Path.home() / ".config" / "arvex" / "ai").resolve()
19
+
20
+
21
+ def read_json(path):
22
+ try:
23
+ data = json.loads(path.read_text(encoding="utf-8"))
24
+ except ValueError:
25
+ raise ArvexError(f"Invalid JSON configuration in {path}.") from None
26
+ if not isinstance(data, dict):
27
+ raise ArvexError(f"Expected a JSON object in {path}.")
28
+ return data
29
+
30
+
31
+ def write_json(path, data):
32
+ with NamedTemporaryFile(dir=path.parent, mode="w", encoding="utf-8", delete=False) as stream:
33
+ temporary = Path(stream.name)
34
+ try:
35
+ json.dump(data, stream, ensure_ascii=False, indent=2)
36
+ stream.write("\n")
37
+ stream.close()
38
+ temporary.replace(path)
39
+ finally:
40
+ temporary.unlink(missing_ok=True)
41
+
42
+
43
+ def shared_settings(directory):
44
+ try:
45
+ data = read_json(directory / "config.json")
46
+ except FileNotFoundError:
47
+ return {"model": DEFAULT_MODEL, "credentials": {}}
48
+ if not isinstance(data.get("credentials"), dict) or not isinstance(data.get("model"), str):
49
+ raise ArvexError(f"Invalid shared settings in {directory / 'config.json'}.")
50
+ return data
51
+
52
+
53
+ def setup(directory: str | Path | None = None, *, api_key: str | None = None,
54
+ model: str | None = None, chatgpt: bool | None = None, account: str = "default") -> Path:
55
+ """Prepare the shared config directory and record any credentials supplied."""
56
+ for name, value in (("API key", api_key), ("Model name", model)):
57
+ if value is not None and (not isinstance(value, str) or not value.strip()):
58
+ raise ArvexError(f"{name} must be a nonempty string.")
59
+ if chatgpt and api_key is not None:
60
+ raise ArvexError("Choose either ChatGPT sign-in or an OpenAI API key.")
61
+ root = config_directory(directory)
62
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
63
+ data = shared_settings(root)
64
+ if chatgpt:
65
+ from .chatgpt import connect
66
+
67
+ connect(root, account, model.strip() if model is not None else None)
68
+ data = shared_settings(root)
69
+ data["chatgpt_account"] = account
70
+ write_json(root / "config.json", data)
71
+ return root
72
+ if api_key is not None or chatgpt is False:
73
+ data.pop("chatgpt_account", None)
74
+ if api_key is not None:
75
+ data["credentials"]["openai_api_key"] = api_key.strip()
76
+ if model is not None:
77
+ data["model"] = model.strip()
78
+ write_json(root / "config.json", data)
79
+ return root
80
+
81
+
82
+ def load_credentials(directory: str | Path | None = None) -> dict[str, str]:
83
+ """Load credentials from shared config, with an environment override for OpenAI."""
84
+ credentials = shared_settings(config_directory(directory))["credentials"]
85
+ if any(not isinstance(value, str) for value in credentials.values()):
86
+ raise ArvexError("Credential values must be strings.")
87
+ if key := os.environ.get("OPENAI_API_KEY", "").strip():
88
+ credentials["openai_api_key"] = key
89
+ return credentials