weio-cli 0.1.0__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.
weio_cli-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 We I/O Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: weio-cli
3
+ Version: 0.1.0
4
+ Summary: Weio — an agentic coding assistant that routes inference through your Weio account.
5
+ Author: We I/O Labs
6
+ License: MIT
7
+ Project-URL: Homepage, https://weio.ai
8
+ Project-URL: Documentation, https://weio.ai/support
9
+ Keywords: weio,ai,cli,coding-assistant,llm
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Code Generators
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: httpx>=0.24
20
+ Dynamic: license-file
21
+
22
+ # weio-cli
23
+
24
+ An agentic coding assistant that runs on your machine and routes inference
25
+ through your [Weio](https://weio.ai) account.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install weio-cli # or: pipx install weio-cli
31
+ ```
32
+
33
+ Requires Python 3.9+.
34
+
35
+ ## Authenticate
36
+
37
+ Generate an API key in **Settings → API & CLI** on weio.ai, then:
38
+
39
+ ```bash
40
+ weio login # paste your weio_sk_… key (saved to ~/.weio/config.json)
41
+ # or, per-session:
42
+ export WEIO_API_KEY="weio_sk_…"
43
+ ```
44
+
45
+ ## Use
46
+
47
+ ```bash
48
+ # Run a coding task in the current directory (reads & edits files):
49
+ weio "add error handling to the fetch() in api.py"
50
+
51
+ # Add specific files to the context:
52
+ weio code "refactor to async" -f server.py -f db.py
53
+
54
+ # One-shot question (no file edits):
55
+ weio ask "what does a 502 from nginx usually mean?"
56
+
57
+ # Interactive chat:
58
+ weio chat
59
+
60
+ # Check connectivity and your key:
61
+ weio ping
62
+ ```
63
+
64
+ Edits are shown as a diff and require confirmation before anything is written
65
+ (use `-y`/`--yes` to apply automatically). New files are created as needed.
66
+
67
+ ## Configuration
68
+
69
+ | Setting | Flag | Env | Config file |
70
+ |---|---|---|---|
71
+ | API key | `--key` | `WEIO_API_KEY` | `~/.weio/config.json` |
72
+ | API base | `--base` | `WEIO_BASE` | `~/.weio/config.json` |
73
+ | Model | `--model` | — | — |
74
+
75
+ Self-hosted / LAN gateway? Point at it with `--base http://HOST:8901/v1`.
76
+
77
+ Output is billed against your Weio account usage.
@@ -0,0 +1,56 @@
1
+ # weio-cli
2
+
3
+ An agentic coding assistant that runs on your machine and routes inference
4
+ through your [Weio](https://weio.ai) account.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pip install weio-cli # or: pipx install weio-cli
10
+ ```
11
+
12
+ Requires Python 3.9+.
13
+
14
+ ## Authenticate
15
+
16
+ Generate an API key in **Settings → API & CLI** on weio.ai, then:
17
+
18
+ ```bash
19
+ weio login # paste your weio_sk_… key (saved to ~/.weio/config.json)
20
+ # or, per-session:
21
+ export WEIO_API_KEY="weio_sk_…"
22
+ ```
23
+
24
+ ## Use
25
+
26
+ ```bash
27
+ # Run a coding task in the current directory (reads & edits files):
28
+ weio "add error handling to the fetch() in api.py"
29
+
30
+ # Add specific files to the context:
31
+ weio code "refactor to async" -f server.py -f db.py
32
+
33
+ # One-shot question (no file edits):
34
+ weio ask "what does a 502 from nginx usually mean?"
35
+
36
+ # Interactive chat:
37
+ weio chat
38
+
39
+ # Check connectivity and your key:
40
+ weio ping
41
+ ```
42
+
43
+ Edits are shown as a diff and require confirmation before anything is written
44
+ (use `-y`/`--yes` to apply automatically). New files are created as needed.
45
+
46
+ ## Configuration
47
+
48
+ | Setting | Flag | Env | Config file |
49
+ |---|---|---|---|
50
+ | API key | `--key` | `WEIO_API_KEY` | `~/.weio/config.json` |
51
+ | API base | `--base` | `WEIO_BASE` | `~/.weio/config.json` |
52
+ | Model | `--model` | — | — |
53
+
54
+ Self-hosted / LAN gateway? Point at it with `--base http://HOST:8901/v1`.
55
+
56
+ Output is billed against your Weio account usage.
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "weio-cli"
7
+ version = "0.1.0"
8
+ description = "Weio — an agentic coding assistant that routes inference through your Weio account."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "We I/O Labs" }]
13
+ keywords = ["weio", "ai", "cli", "coding-assistant", "llm"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Software Development :: Code Generators",
21
+ ]
22
+ dependencies = ["httpx>=0.24"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://weio.ai"
26
+ Documentation = "https://weio.ai/support"
27
+
28
+ [project.scripts]
29
+ weio = "weio_cli.cli:main"
30
+
31
+ [tool.setuptools]
32
+ package-dir = { "" = "src" }
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Weio CLI — an agentic coding assistant that routes inference through your Weio account."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
@@ -0,0 +1,273 @@
1
+ """weio — command-line entry point.
2
+
3
+ Commands:
4
+ weio login Save your API key (and optional --base)
5
+ weio "do X" Run a coding task in the current directory (default)
6
+ weio code "do X" [-f ...] Same, explicit; -f adds files to the context
7
+ weio ask "question" One-shot chat answer (no file edits)
8
+ weio chat Interactive chat session
9
+ weio ping Check connectivity + key
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from . import __version__, config
18
+ from .client import WeioClient, WeioError
19
+ from . import coder
20
+
21
+
22
+ def _make_client(args) -> WeioClient:
23
+ key = config.resolve_key(getattr(args, "key", None))
24
+ base = config.resolve_base(getattr(args, "base", None))
25
+ model = getattr(args, "model", None) or "auto"
26
+ return WeioClient(key, base, model=model)
27
+
28
+
29
+ def _max_tokens(args) -> int:
30
+ return int(getattr(args, "max_tokens", 4096) or 4096)
31
+
32
+
33
+ def _c(text: str, code: str) -> str:
34
+ if not sys.stdout.isatty():
35
+ return text
36
+ return f"\033[{code}m{text}\033[0m"
37
+
38
+
39
+ # --------------------------------------------------------------------------- #
40
+ # Commands
41
+ # --------------------------------------------------------------------------- #
42
+
43
+ def cmd_login(args) -> int:
44
+ cli_key = getattr(args, "key", None)
45
+ cli_base = getattr(args, "base", None)
46
+ key = cli_key or input("Weio API key (weio_sk_…): ").strip()
47
+ if not key:
48
+ print("No key provided.", file=sys.stderr)
49
+ return 2
50
+ path = config.save(key=key, base=cli_base)
51
+ # Validate
52
+ try:
53
+ client = WeioClient(key, config.resolve_base(cli_base))
54
+ ok = client.ping()
55
+ except WeioError:
56
+ ok = False
57
+ print(f"Saved credentials to {path}")
58
+ print("Connection check:", _c("OK", "32") if ok else _c("could not verify (saved anyway)", "33"))
59
+ return 0
60
+
61
+
62
+ def cmd_ping(args) -> int:
63
+ try:
64
+ client = _make_client(args)
65
+ except WeioError as e:
66
+ print(_c(str(e), "31"), file=sys.stderr)
67
+ return 2
68
+ ok = client.ping()
69
+ print(f"base: {client.base}")
70
+ print("status:", _c("reachable, key valid", "32") if ok else _c("unreachable or invalid key", "31"))
71
+ return 0 if ok else 1
72
+
73
+
74
+ def cmd_ask(args) -> int:
75
+ try:
76
+ client = _make_client(args)
77
+ except WeioError as e:
78
+ print(_c(str(e), "31"), file=sys.stderr)
79
+ return 2
80
+ messages = [{"role": "user", "content": args.message}]
81
+ try:
82
+ if args.no_stream:
83
+ print(client.chat(messages, max_tokens=_max_tokens(args)))
84
+ else:
85
+ for delta in client.chat_stream(messages, max_tokens=_max_tokens(args)):
86
+ sys.stdout.write(delta)
87
+ sys.stdout.flush()
88
+ print()
89
+ except WeioError as e:
90
+ print("\n" + _c(str(e), "31"), file=sys.stderr)
91
+ return 1
92
+ return 0
93
+
94
+
95
+ def cmd_chat(args) -> int:
96
+ try:
97
+ client = _make_client(args)
98
+ except WeioError as e:
99
+ print(_c(str(e), "31"), file=sys.stderr)
100
+ return 2
101
+ print(_c("Weio interactive chat.", "36"), "Ctrl-C or 'exit' to quit.\n")
102
+ history: list[dict] = []
103
+ while True:
104
+ try:
105
+ q = input(_c("you> ", "36")).strip()
106
+ except (EOFError, KeyboardInterrupt):
107
+ print()
108
+ break
109
+ if not q:
110
+ continue
111
+ if q in ("exit", "quit"):
112
+ break
113
+ history.append({"role": "user", "content": q})
114
+ sys.stdout.write(_c("weio> ", "32"))
115
+ sys.stdout.flush()
116
+ acc = ""
117
+ try:
118
+ for delta in client.chat_stream(history, max_tokens=_max_tokens(args)):
119
+ acc += delta
120
+ sys.stdout.write(delta)
121
+ sys.stdout.flush()
122
+ print("\n")
123
+ except WeioError as e:
124
+ print("\n" + _c(str(e), "31"), file=sys.stderr)
125
+ history.pop()
126
+ continue
127
+ history.append({"role": "assistant", "content": acc})
128
+ return 0
129
+
130
+
131
+ def cmd_code(args) -> int:
132
+ try:
133
+ client = _make_client(args)
134
+ except WeioError as e:
135
+ print(_c(str(e), "31"), file=sys.stderr)
136
+ return 2
137
+ root = Path(args.dir).resolve()
138
+ if not root.is_dir():
139
+ print(_c(f"Not a directory: {root}", "31"), file=sys.stderr)
140
+ return 2
141
+
142
+ print(_c(f"weio coding in {root}", "36"))
143
+ print("Thinking…", flush=True)
144
+ try:
145
+ raw, edits = coder.run_coding_task(
146
+ client, args.message, root=root, files=args.file or [], max_tokens=_max_tokens(args)
147
+ )
148
+ except WeioError as e:
149
+ print(_c(str(e), "31"), file=sys.stderr)
150
+ return 1
151
+
152
+ if not edits:
153
+ # No edits — show the model's reply (it may be asking for files or explaining)
154
+ print(raw)
155
+ return 0
156
+
157
+ # Apply edits (preview + confirm unless --yes)
158
+ results, errors = [], []
159
+ for e in edits:
160
+ res, err = coder.apply_edit(e, root)
161
+ if err:
162
+ errors.append(err)
163
+ elif res:
164
+ results.append(res)
165
+
166
+ for res in results:
167
+ tag = _c("NEW", "32") if res.created else _c("EDIT", "33")
168
+ print(f"\n{tag} {res.path}")
169
+ if res.created:
170
+ preview = res.new_text if len(res.new_text) < 1500 else res.new_text[:1500] + "\n… [truncated preview]"
171
+ print(preview)
172
+ else:
173
+ print(coder.unified_diff(res.path, res.old_text, res.new_text) or "(no textual diff)")
174
+
175
+ for err in errors:
176
+ print(_c("SKIP " + err, "31"))
177
+
178
+ if not results:
179
+ print(_c("\nNo applicable edits.", "33"))
180
+ return 1
181
+
182
+ if not args.yes:
183
+ try:
184
+ ans = input(_c(f"\nApply {len(results)} change(s)? [y/N] ", "36")).strip().lower()
185
+ except (EOFError, KeyboardInterrupt):
186
+ print()
187
+ ans = "n"
188
+ if ans not in ("y", "yes"):
189
+ print("Aborted. No files written.")
190
+ return 0
191
+
192
+ written = 0
193
+ for res in results:
194
+ fp = root / res.path
195
+ fp.parent.mkdir(parents=True, exist_ok=True)
196
+ fp.write_text(res.new_text, encoding="utf-8")
197
+ written += 1
198
+ print(_c(f"\nApplied {written} change(s).", "32"))
199
+ return 0
200
+
201
+
202
+ # --------------------------------------------------------------------------- #
203
+ # Parser
204
+ # --------------------------------------------------------------------------- #
205
+
206
+ def build_parser() -> argparse.ArgumentParser:
207
+ # Shared auth/model flags — accepted both before AND after the subcommand,
208
+ # so `weio --key X ask "q"` and `weio ask "q" --key X` both work.
209
+ common = argparse.ArgumentParser(add_help=False)
210
+ # SUPPRESS defaults so a flag given before the subcommand isn't clobbered by
211
+ # the subparser's default (argparse parents + subparsers share dests).
212
+ common.add_argument("--key", "-k", default=argparse.SUPPRESS,
213
+ help="API key (or set WEIO_API_KEY / run `weio login`)")
214
+ common.add_argument("--base", default=argparse.SUPPRESS,
215
+ help="API base URL (default https://api.weio.ai/v1)")
216
+ common.add_argument("--model", "-m", default=argparse.SUPPRESS, help="Model id (default: auto)")
217
+ common.add_argument("--max-tokens", type=int, default=argparse.SUPPRESS, help="Max output tokens")
218
+
219
+ p = argparse.ArgumentParser(
220
+ prog="weio",
221
+ parents=[common],
222
+ description="Weio — an agentic coding assistant that routes inference through your Weio account.",
223
+ )
224
+ p.add_argument("--version", action="version", version=f"weio-cli {__version__}")
225
+
226
+ sub = p.add_subparsers(dest="command")
227
+
228
+ sp = sub.add_parser("login", parents=[common], help="Save your API key")
229
+ sp.set_defaults(func=cmd_login)
230
+
231
+ sp = sub.add_parser("ping", parents=[common], help="Check connectivity and key")
232
+ sp.set_defaults(func=cmd_ping)
233
+
234
+ sp = sub.add_parser("ask", parents=[common], help="One-shot question (no file edits)")
235
+ sp.add_argument("message")
236
+ sp.add_argument("--no-stream", action="store_true")
237
+ sp.set_defaults(func=cmd_ask)
238
+
239
+ sp = sub.add_parser("chat", parents=[common], help="Interactive chat")
240
+ sp.set_defaults(func=cmd_chat)
241
+
242
+ sp = sub.add_parser("code", parents=[common], help="Run a coding task in a directory")
243
+ sp.add_argument("message")
244
+ sp.add_argument("--file", "-f", action="append", help="Add a file to the context (repeatable)")
245
+ sp.add_argument("--dir", "-C", default=".", help="Project directory (default: cwd)")
246
+ sp.add_argument("--yes", "-y", action="store_true", help="Apply edits without confirmation")
247
+ sp.set_defaults(func=cmd_code)
248
+
249
+ return p
250
+
251
+
252
+ def main(argv=None) -> int:
253
+ argv = list(sys.argv[1:] if argv is None else argv)
254
+ parser = build_parser()
255
+
256
+ # Bare `weio "do something"` defaults to the `code` command.
257
+ known = {"login", "ping", "ask", "chat", "code"}
258
+ if argv and argv[0] not in known and not argv[0].startswith("-"):
259
+ argv = ["code", *argv]
260
+
261
+ args = parser.parse_args(argv)
262
+ if not getattr(args, "command", None):
263
+ parser.print_help()
264
+ return 1
265
+ try:
266
+ return args.func(args)
267
+ except KeyboardInterrupt:
268
+ print()
269
+ return 130
270
+
271
+
272
+ if __name__ == "__main__":
273
+ sys.exit(main())
@@ -0,0 +1,97 @@
1
+ """Thin client for the Weio OpenAI-compatible gateway."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from typing import Iterator, Optional
6
+
7
+ try:
8
+ import httpx
9
+ except ImportError: # pragma: no cover
10
+ raise SystemExit("weio-cli requires httpx. Install with: pip install httpx")
11
+
12
+ from . import __version__
13
+
14
+
15
+ class WeioError(RuntimeError):
16
+ pass
17
+
18
+
19
+ class WeioClient:
20
+ def __init__(self, api_key: str, base: str, *, model: str = "auto", timeout: float = 180.0):
21
+ if not api_key:
22
+ raise WeioError("No API key. Run `weio login` or pass --key / set WEIO_API_KEY.")
23
+ self.api_key = api_key
24
+ self.base = base.rstrip("/")
25
+ self.model = model
26
+ self.timeout = timeout
27
+
28
+ def _headers(self) -> dict:
29
+ return {
30
+ "Authorization": f"Bearer {self.api_key}",
31
+ "Content-Type": "application/json",
32
+ "User-Agent": f"weio-cli/{__version__}",
33
+ }
34
+
35
+ def chat(self, messages: list[dict], *, max_tokens: int = 2048,
36
+ temperature: float = 0.7, model: Optional[str] = None) -> str:
37
+ """Non-streaming completion. Returns the assistant text."""
38
+ payload = {
39
+ "model": model or self.model,
40
+ "messages": messages,
41
+ "max_tokens": max_tokens,
42
+ "temperature": temperature,
43
+ }
44
+ try:
45
+ r = httpx.post(f"{self.base}/chat/completions", headers=self._headers(),
46
+ json=payload, timeout=self.timeout)
47
+ except httpx.HTTPError as e:
48
+ raise WeioError(f"Network error talking to {self.base}: {e}") from e
49
+ if r.status_code == 401:
50
+ raise WeioError("Authentication failed (401). Check your API key.")
51
+ if r.status_code == 402 or r.status_code == 429:
52
+ raise WeioError(f"Usage limit or quota reached ({r.status_code}). {r.text[:200]}")
53
+ if r.status_code >= 400:
54
+ raise WeioError(f"Gateway error {r.status_code}: {r.text[:300]}")
55
+ try:
56
+ return r.json()["choices"][0]["message"]["content"]
57
+ except (KeyError, IndexError, json.JSONDecodeError) as e:
58
+ raise WeioError(f"Unexpected response shape: {r.text[:300]}") from e
59
+
60
+ def chat_stream(self, messages: list[dict], *, max_tokens: int = 2048,
61
+ temperature: float = 0.7, model: Optional[str] = None) -> Iterator[str]:
62
+ """Streaming completion. Yields text deltas. Falls back to non-stream on error."""
63
+ payload = {
64
+ "model": model or self.model,
65
+ "messages": messages,
66
+ "max_tokens": max_tokens,
67
+ "temperature": temperature,
68
+ "stream": True,
69
+ }
70
+ try:
71
+ with httpx.stream("POST", f"{self.base}/chat/completions",
72
+ headers=self._headers(), json=payload, timeout=self.timeout) as r:
73
+ if r.status_code >= 400:
74
+ body = r.read().decode("utf-8", "replace")
75
+ raise WeioError(f"Gateway error {r.status_code}: {body[:300]}")
76
+ for line in r.iter_lines():
77
+ if not line or not line.startswith("data:"):
78
+ continue
79
+ data = line[5:].strip()
80
+ if data == "[DONE]":
81
+ break
82
+ try:
83
+ delta = json.loads(data)["choices"][0].get("delta", {}).get("content")
84
+ if delta:
85
+ yield delta
86
+ except (KeyError, IndexError, json.JSONDecodeError):
87
+ continue
88
+ except httpx.HTTPError as e:
89
+ raise WeioError(f"Network error talking to {self.base}: {e}") from e
90
+
91
+ def ping(self) -> bool:
92
+ """Check the gateway is reachable and the key is valid (GET /models)."""
93
+ try:
94
+ r = httpx.get(f"{self.base}/models", headers=self._headers(), timeout=15.0)
95
+ return r.status_code == 200
96
+ except httpx.HTTPError:
97
+ return False
@@ -0,0 +1,160 @@
1
+ """Agentic coding: gather file context, ask the model for edits, apply them.
2
+
3
+ Edit protocol (the model is instructed to emit one or more blocks):
4
+
5
+ ```edit path/to/file.ext
6
+ <<<<<<< SEARCH
7
+ exact existing lines to find (empty for a new file)
8
+ =======
9
+ replacement lines
10
+ >>>>>>> REPLACE
11
+ ```
12
+
13
+ Multiple SEARCH/REPLACE pairs may appear under a single path. New files use an
14
+ empty SEARCH section.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import difflib
19
+ import re
20
+ from dataclasses import dataclass, field
21
+ from pathlib import Path
22
+ from typing import Optional
23
+
24
+ from .client import WeioClient, WeioError
25
+
26
+ CODER_SYSTEM = """You are Weio, an expert pair-programmer operating as a command-line coding agent on the user's machine.
27
+
28
+ You modify code by emitting EDIT BLOCKS. For every file you change, output a fenced block:
29
+
30
+ ```edit relative/path/to/file.ext
31
+ <<<<<<< SEARCH
32
+ <exact lines that currently exist in the file>
33
+ =======
34
+ <the replacement lines>
35
+ >>>>>>> REPLACE
36
+ ```
37
+
38
+ Rules:
39
+ - The SEARCH text must match the current file content EXACTLY (whitespace included).
40
+ - To create a NEW file, leave the SEARCH section empty and put the full contents in REPLACE.
41
+ - Keep edits minimal and focused; you may emit several blocks (including several per file).
42
+ - Only touch files needed for the task. Do not invent file contents you were not shown.
43
+ - After the edit blocks, add a one-paragraph summary of what you changed and why.
44
+ - If you need to see a file that was not provided, say so explicitly instead of guessing."""
45
+
46
+ _BLOCK_RE = re.compile(
47
+ r"```edit[ \t]+(?P<path>[^\n`]+)\n(?P<body>.*?)```",
48
+ re.DOTALL,
49
+ )
50
+ _SR_RE = re.compile(
51
+ r"<<<<<<< SEARCH\n(?P<search>.*?)\n?=======\n(?P<replace>.*?)\n?>>>>>>> REPLACE",
52
+ re.DOTALL,
53
+ )
54
+
55
+
56
+ @dataclass
57
+ class Edit:
58
+ path: str
59
+ search: str
60
+ replace: str
61
+
62
+
63
+ @dataclass
64
+ class FileResult:
65
+ path: str
66
+ created: bool = False
67
+ applied: int = 0
68
+ failed: list[str] = field(default_factory=list)
69
+ old_text: str = ""
70
+ new_text: str = ""
71
+
72
+
73
+ def parse_edits(text: str) -> list[Edit]:
74
+ edits: list[Edit] = []
75
+ for m in _BLOCK_RE.finditer(text):
76
+ path = m.group("path").strip()
77
+ body = m.group("body")
78
+ pairs = list(_SR_RE.finditer(body))
79
+ if not pairs:
80
+ continue
81
+ for sr in pairs:
82
+ edits.append(Edit(path=path, search=sr.group("search"), replace=sr.group("replace")))
83
+ return edits
84
+
85
+
86
+ def gather_context(instruction: str, explicit_files: list[str], root: Path,
87
+ max_bytes: int = 60_000) -> tuple[str, list[str]]:
88
+ """Collect file contents for the prompt. Returns (context_text, included_paths)."""
89
+ candidates: list[str] = list(explicit_files)
90
+ # Auto-detect path-like tokens in the instruction (e.g. src/app.py)
91
+ for tok in re.findall(r"[\w./-]+\.\w{1,6}", instruction):
92
+ if tok not in candidates and (root / tok).is_file():
93
+ candidates.append(tok)
94
+
95
+ included, blocks, total = [], [], 0
96
+ for rel in candidates:
97
+ fp = root / rel
98
+ if not fp.is_file():
99
+ continue
100
+ try:
101
+ content = fp.read_text(encoding="utf-8")
102
+ except (UnicodeDecodeError, OSError):
103
+ continue
104
+ if total + len(content) > max_bytes:
105
+ content = content[: max(0, max_bytes - total)] + "\n... [truncated]"
106
+ blocks.append(f"=== FILE: {rel} ===\n{content}")
107
+ included.append(rel)
108
+ total += len(content)
109
+ if total >= max_bytes:
110
+ break
111
+
112
+ if not blocks:
113
+ return "", []
114
+ return "\n\n".join(blocks), included
115
+
116
+
117
+ def apply_edit(edit: Edit, root: Path) -> tuple[Optional[FileResult], Optional[str]]:
118
+ """Apply a single edit. Returns (result, error)."""
119
+ fp = root / edit.path
120
+ if edit.search.strip() == "":
121
+ # New file (or full overwrite if it somehow exists)
122
+ return FileResult(path=edit.path, created=not fp.exists(), applied=1,
123
+ old_text="", new_text=edit.replace), None
124
+ if not fp.exists():
125
+ return None, f"{edit.path}: file not found for SEARCH/REPLACE"
126
+ try:
127
+ original = fp.read_text(encoding="utf-8")
128
+ except (UnicodeDecodeError, OSError) as e:
129
+ return None, f"{edit.path}: cannot read ({e})"
130
+ if edit.search not in original:
131
+ return None, f"{edit.path}: SEARCH block did not match current contents"
132
+ new_text = original.replace(edit.search, edit.replace, 1)
133
+ return FileResult(path=edit.path, created=False, applied=1,
134
+ old_text=original, new_text=new_text), None
135
+
136
+
137
+ def unified_diff(path: str, old: str, new: str) -> str:
138
+ diff = difflib.unified_diff(
139
+ old.splitlines(keepends=True), new.splitlines(keepends=True),
140
+ fromfile=f"a/{path}", tofile=f"b/{path}",
141
+ )
142
+ return "".join(diff)
143
+
144
+
145
+ def run_coding_task(client: WeioClient, instruction: str, *, root: Path,
146
+ files: list[str], max_tokens: int = 4096) -> tuple[str, list[Edit]]:
147
+ """Ask the model for edits. Returns (raw_response, parsed_edits)."""
148
+ context, included = gather_context(instruction, files, root)
149
+ user_parts = [f"TASK:\n{instruction}"]
150
+ if context:
151
+ user_parts.append(f"\nCURRENT FILES (for reference):\n{context}")
152
+ else:
153
+ user_parts.append("\n(No files were provided. If the task needs existing files, "
154
+ "ask for them by path. For new files, emit edit blocks with an empty SEARCH.)")
155
+ messages = [
156
+ {"role": "system", "content": CODER_SYSTEM},
157
+ {"role": "user", "content": "\n".join(user_parts)},
158
+ ]
159
+ raw = client.chat(messages, max_tokens=max_tokens, temperature=0.1)
160
+ return raw, parse_edits(raw)
@@ -0,0 +1,55 @@
1
+ """Configuration: API key + base URL resolution and persistence.
2
+
3
+ Resolution order (first hit wins):
4
+ 1. Explicit --key / --base CLI flags
5
+ 2. WEIO_API_KEY / WEIO_BASE environment variables
6
+ 3. ~/.weio/config.json (written by `weio login`)
7
+ 4. Built-in default base
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ from typing import Optional
15
+
16
+ DEFAULT_BASE = "https://api.weio.ai/v1"
17
+
18
+ CONFIG_DIR = Path(os.environ.get("WEIO_CONFIG_DIR", str(Path.home() / ".weio")))
19
+ CONFIG_FILE = CONFIG_DIR / "config.json"
20
+
21
+
22
+ def _read_file() -> dict:
23
+ try:
24
+ return json.loads(CONFIG_FILE.read_text())
25
+ except Exception:
26
+ return {}
27
+
28
+
29
+ def save(key: Optional[str] = None, base: Optional[str] = None) -> Path:
30
+ """Persist key/base to ~/.weio/config.json (0600)."""
31
+ data = _read_file()
32
+ if key is not None:
33
+ data["api_key"] = key
34
+ if base is not None:
35
+ data["base"] = base
36
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
37
+ CONFIG_FILE.write_text(json.dumps(data, indent=2))
38
+ try:
39
+ CONFIG_FILE.chmod(0o600)
40
+ except Exception:
41
+ pass
42
+ return CONFIG_FILE
43
+
44
+
45
+ def resolve_key(cli_key: Optional[str]) -> Optional[str]:
46
+ return cli_key or os.environ.get("WEIO_API_KEY") or _read_file().get("api_key")
47
+
48
+
49
+ def resolve_base(cli_base: Optional[str]) -> str:
50
+ return (
51
+ cli_base
52
+ or os.environ.get("WEIO_BASE")
53
+ or _read_file().get("base")
54
+ or DEFAULT_BASE
55
+ )
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: weio-cli
3
+ Version: 0.1.0
4
+ Summary: Weio — an agentic coding assistant that routes inference through your Weio account.
5
+ Author: We I/O Labs
6
+ License: MIT
7
+ Project-URL: Homepage, https://weio.ai
8
+ Project-URL: Documentation, https://weio.ai/support
9
+ Keywords: weio,ai,cli,coding-assistant,llm
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Code Generators
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: httpx>=0.24
20
+ Dynamic: license-file
21
+
22
+ # weio-cli
23
+
24
+ An agentic coding assistant that runs on your machine and routes inference
25
+ through your [Weio](https://weio.ai) account.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install weio-cli # or: pipx install weio-cli
31
+ ```
32
+
33
+ Requires Python 3.9+.
34
+
35
+ ## Authenticate
36
+
37
+ Generate an API key in **Settings → API & CLI** on weio.ai, then:
38
+
39
+ ```bash
40
+ weio login # paste your weio_sk_… key (saved to ~/.weio/config.json)
41
+ # or, per-session:
42
+ export WEIO_API_KEY="weio_sk_…"
43
+ ```
44
+
45
+ ## Use
46
+
47
+ ```bash
48
+ # Run a coding task in the current directory (reads & edits files):
49
+ weio "add error handling to the fetch() in api.py"
50
+
51
+ # Add specific files to the context:
52
+ weio code "refactor to async" -f server.py -f db.py
53
+
54
+ # One-shot question (no file edits):
55
+ weio ask "what does a 502 from nginx usually mean?"
56
+
57
+ # Interactive chat:
58
+ weio chat
59
+
60
+ # Check connectivity and your key:
61
+ weio ping
62
+ ```
63
+
64
+ Edits are shown as a diff and require confirmation before anything is written
65
+ (use `-y`/`--yes` to apply automatically). New files are created as needed.
66
+
67
+ ## Configuration
68
+
69
+ | Setting | Flag | Env | Config file |
70
+ |---|---|---|---|
71
+ | API key | `--key` | `WEIO_API_KEY` | `~/.weio/config.json` |
72
+ | API base | `--base` | `WEIO_BASE` | `~/.weio/config.json` |
73
+ | Model | `--model` | — | — |
74
+
75
+ Self-hosted / LAN gateway? Point at it with `--base http://HOST:8901/v1`.
76
+
77
+ Output is billed against your Weio account usage.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/weio_cli/__init__.py
5
+ src/weio_cli/__main__.py
6
+ src/weio_cli/cli.py
7
+ src/weio_cli/client.py
8
+ src/weio_cli/coder.py
9
+ src/weio_cli/config.py
10
+ src/weio_cli.egg-info/PKG-INFO
11
+ src/weio_cli.egg-info/SOURCES.txt
12
+ src/weio_cli.egg-info/dependency_links.txt
13
+ src/weio_cli.egg-info/entry_points.txt
14
+ src/weio_cli.egg-info/requires.txt
15
+ src/weio_cli.egg-info/top_level.txt
16
+ tests/test_coder.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ weio = weio_cli.cli:main
@@ -0,0 +1 @@
1
+ httpx>=0.24
@@ -0,0 +1 @@
1
+ weio_cli
@@ -0,0 +1,87 @@
1
+ """Unit tests for the edit-block parser and application logic."""
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
6
+
7
+ from weio_cli import coder # noqa: E402
8
+
9
+
10
+ def test_parse_single_edit():
11
+ text = """Here you go:
12
+ ```edit app.py
13
+ <<<<<<< SEARCH
14
+ def f():
15
+ return 1
16
+ =======
17
+ def f():
18
+ return 2
19
+ >>>>>>> REPLACE
20
+ ```
21
+ Done."""
22
+ edits = coder.parse_edits(text)
23
+ assert len(edits) == 1
24
+ assert edits[0].path == "app.py"
25
+ assert "return 1" in edits[0].search
26
+ assert "return 2" in edits[0].replace
27
+
28
+
29
+ def test_parse_new_file_empty_search():
30
+ text = """```edit new.py
31
+ <<<<<<< SEARCH
32
+ =======
33
+ print("hi")
34
+ >>>>>>> REPLACE
35
+ ```"""
36
+ edits = coder.parse_edits(text)
37
+ assert len(edits) == 1
38
+ assert edits[0].search.strip() == ""
39
+ assert 'print("hi")' in edits[0].replace
40
+
41
+
42
+ def test_parse_multiple_blocks():
43
+ text = """```edit a.py
44
+ <<<<<<< SEARCH
45
+ x = 1
46
+ =======
47
+ x = 2
48
+ >>>>>>> REPLACE
49
+ ```
50
+ ```edit b.py
51
+ <<<<<<< SEARCH
52
+ y = 1
53
+ =======
54
+ y = 2
55
+ >>>>>>> REPLACE
56
+ ```"""
57
+ edits = coder.parse_edits(text)
58
+ assert {e.path for e in edits} == {"a.py", "b.py"}
59
+
60
+
61
+ def test_apply_edit_match(tmp_path):
62
+ fp = tmp_path / "m.py"
63
+ fp.write_text("a = 1\nb = 2\n")
64
+ e = coder.Edit(path="m.py", search="a = 1", replace="a = 99")
65
+ res, err = coder.apply_edit(e, tmp_path)
66
+ assert err is None
67
+ assert "a = 99" in res.new_text and "b = 2" in res.new_text
68
+
69
+
70
+ def test_apply_edit_no_match(tmp_path):
71
+ fp = tmp_path / "m.py"
72
+ fp.write_text("a = 1\n")
73
+ e = coder.Edit(path="m.py", search="zzz", replace="qqq")
74
+ res, err = coder.apply_edit(e, tmp_path)
75
+ assert res is None and "did not match" in err
76
+
77
+
78
+ def test_apply_new_file(tmp_path):
79
+ e = coder.Edit(path="brand_new.py", search="", replace="print('new')\n")
80
+ res, err = coder.apply_edit(e, tmp_path)
81
+ assert err is None and res.created is True
82
+ assert "print('new')" in res.new_text
83
+
84
+
85
+ if __name__ == "__main__":
86
+ import subprocess
87
+ raise SystemExit(subprocess.call([sys.executable, "-m", "pytest", __file__, "-v"]))