Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
368 lines (306 loc) · 11 KB
/
Copy pathmain.py
File metadata and controls
368 lines (306 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
from pathlib import Path
from agent.agent import Agent
from agent.store import SessionStore
from config.config import Config
from config.loader import load_config
from config.credentials import (
clear_credentials,
get_credentials_path,
load_credentials,
save_credentials,
)
from config.oauth import OAuthError, login_with_oauth
from ui import TUI, Repl, get_console, stream_turn
import asyncio
import click
import json
import shutil
import subprocess
import sys
from importlib.metadata import PackageNotFoundError, version as installed_version
from urllib.error import URLError
from urllib.request import urlopen
from packaging.version import InvalidVersion, Version
DEFAULT_BASE_URL = "https://openrouter.ai/api/v1"
console = get_console()
def _latest_version() -> Version:
with urlopen("https://pypi.org/pypi/postalcli/json", timeout=5) as response:
data = json.load(response)
return Version(data["info"]["version"])
def _upgrade_notice() -> str | None:
try:
current = Version(installed_version("postalcli"))
latest = _latest_version()
except (
PackageNotFoundError,
InvalidVersion,
KeyError,
TypeError,
URLError,
TimeoutError,
OSError,
ValueError,
):
return None
if latest > current:
return f"Postal {latest} is available (you have {current}). Use `postal upgrade` to update."
return None
def _upgrade_command() -> list[str]:
"""Use pipx for its macOS environments, otherwise this interpreter's pip."""
environment = Path(sys.prefix)
if sys.platform == "darwin" and (environment / "pipx_metadata.json").is_file():
pipx = shutil.which("pipx")
if pipx is None:
raise click.ClickException(
"This installation is managed by pipx, but pipx is not on PATH. "
"Restore pipx to PATH, then run postal upgrade again."
)
# The environment name includes any suffix used at installation time.
return [pipx, "upgrade", environment.name]
return [sys.executable, "-m", "pip", "install", "--upgrade", "postalcli"]
async def run_once(config: Config, message: str, resume: str | None = None) -> str | None:
tui = TUI(config)
async with Agent(
config, confirmation_callback=tui.confirm_tool, resume=resume
) as agent:
tui.render_approval_mode()
if resume and agent.resumed is None:
console.print(f"[warning]No saved session matched '{resume}'.[/warning]")
return await stream_turn(tui, agent, message)
def _resolve_resume(
config: Config,
resume: str | None,
continue_last: bool,
) -> str | None:
"""Turn --resume / --continue into a session id, or None to start fresh."""
if resume:
return resume
if not continue_last:
return None
latest = SessionStore().latest(config.cwd)
if latest is None:
console.print("[warning]No saved session for this directory, starting a new one.[/warning]")
return None
return latest.session_id
class DefaultGroup(click.Group):
def resolve_command(self, ctx, args):
try:
return super().resolve_command(ctx, args)
except click.UsageError:
return "run", self.get_command(ctx, "run"), args
@click.group(
cls=DefaultGroup,
invoke_without_command=True,
epilog="""\b
Examples:
postal Start the interactive TUI
postal "fix the bug" Run a single prompt and exit
postal --continue Resume the last session in this directory
postal --resume 123456 Resume a specific session by ID
"""
)
@click.version_option(package_name="postalcli", prog_name="postal")
@click.option(
'--cwd',
'-c',
type=click.Path(
exists=True,
file_okay=False,
path_type=Path,
),
help='Current Working Directory'
)
@click.option(
"--resume",
"-r",
"resume",
default=None,
metavar="SESSION",
help="Resume a saved session by id (a prefix is enough).",
)
@click.option(
"--continue",
"-C",
"continue_last",
is_flag=True,
help="Resume the most recent session for this directory.",
)
@click.pass_context
def main(ctx: click.Context, cwd: Path | None, resume: str | None, continue_last: bool):
ctx.obj = {"cwd": cwd, "resume": resume, "continue": continue_last}
# Bare `postal` with no subcommand launches the interactive TUI.
if ctx.invoked_subcommand is None:
ctx.invoke(run, prompt=None)
@main.command(
epilog="""\b
Examples:
postal run Launch the interactive TUI (same as just `postal`)
postal run "write a hello world" Run a one-shot prompt
"""
)
@click.argument("prompt", required=False)
@click.pass_context
def run(ctx: click.Context, prompt: str | None):
"""Run a one-shot prompt, or launch the TUI when no prompt is given."""
cwd = ctx.obj.get("cwd") if ctx.obj else None
try:
config = load_config(cwd=cwd)
except Exception as e:
console.print(f"[error]Config Error: {e}[/error]")
sys.exit(1)
errors = config.validate()
if errors:
for error in errors:
console.print(f'[error]Config Error: {error}[/error]')
sys.exit(1)
resume = _resolve_resume(
config,
ctx.obj.get("resume") if ctx.obj else None,
bool(ctx.obj.get("continue")) if ctx.obj else False,
)
if prompt:
result = asyncio.run(run_once(config, prompt, resume=resume))
if result is None:
sys.exit(1)
else:
try:
asyncio.run(Repl(config, resume=resume, upgrade_notice=_upgrade_notice()).run())
except RuntimeError as exc:
raise click.ClickException(str(exc)) from exc
@main.command(
epilog="""\b
Examples:
postal login Open your browser to securely authorize with OpenRouter
postal login --paste Paste an API key directly in the terminal
"""
)
@click.option(
"--base-url",
default=None,
help=f"API base URL to save (default: {DEFAULT_BASE_URL})",
)
@click.option(
"--paste",
is_flag=True,
help="Paste an API key manually instead of authorizing in the browser.",
)
def login(base_url: str | None, paste: bool):
"""Log in to OpenRouter via your browser (or --paste an API key)."""
if load_credentials().get("api_key"):
if not click.confirm("You're already logged in. Overwrite the saved key?", default=False):
console.print("[warning]Login cancelled.[/warning]")
return
resolved_base_url = base_url or DEFAULT_BASE_URL
if paste:
api_key = click.prompt("Paste your OpenRouter API key", hide_input=True).strip()
if not api_key:
console.print("[error]No key entered, nothing saved.[/error]")
sys.exit(1)
else:
console.print("Opening your browser to authorize postal with OpenRouter...")
try:
api_key = login_with_oauth(resolved_base_url)
except OAuthError as e:
console.print(f"[error]Login failed:[/error] {e}")
console.print("[warning]You can retry, or run `postal login --paste` to enter a key manually.[/warning]")
sys.exit(1)
path = save_credentials(api_key, resolved_base_url)
console.print(f"[success]Logged in.[/success] Key saved to {path}")
console.print("[warning]The API_KEY environment variable, if set, still takes precedence.[/warning]")
@main.group(
invoke_without_command=True,
epilog="""\b
Examples:
postal sessions List all saved sessions for the current directory
postal sessions --all List all saved sessions across all directories
"""
)
@click.option(
"--all",
"all_projects",
is_flag=True,
help="List sessions from every directory, not just this one.",
)
@click.pass_context
def sessions(ctx: click.Context, all_projects: bool):
"""List saved sessions."""
if ctx.invoked_subcommand is not None:
return
cwd = (ctx.obj.get("cwd") if ctx.obj else None) or Path.cwd()
saved = SessionStore().list(None if all_projects else cwd)
if not saved:
scope = "" if all_projects else f" for {cwd}"
console.print(f"[warning]No saved sessions{scope}.[/warning]")
return
for meta in saved:
turns = f"{meta.turns} turn{'s' if meta.turns != 1 else ''}"
console.print(
f"[info]{meta.short_id}[/info] "
f"{meta.updated_at:%Y-%m-%d %H:%M} "
f"{turns:>9} {meta.title}"
)
if all_projects:
console.print(f"[muted]{' ' * 10}{meta.cwd}[/muted]")
console.print()
console.print("[muted]Resume one with postal --resume <id>[/muted]")
@sessions.command(
"rm",
epilog="""\b
Examples:
postal sessions rm 123456 Delete the session matching the ID prefix
"""
)
@click.argument("session_id")
def sessions_rm(session_id: str):
"""Delete a saved session."""
store = SessionStore()
resolved = store.resolve(session_id)
if resolved is None:
console.print(f"[error]No saved session matching '{session_id}'.[/error]")
sys.exit(1)
meta = store.read_meta(resolved)
if store.delete(resolved):
title = f" - {meta.title}" if meta else ""
console.print(f"[success]Deleted session {resolved[:8]}[/success]{title}")
else:
console.print(f"[error]Could not delete {resolved[:8]}.[/error]")
sys.exit(1)
@main.command()
def logout():
"""Remove the saved OpenRouter API key."""
if clear_credentials():
console.print(f"[success]Logged out.[/success] Removed {get_credentials_path()}")
else:
console.print("[warning]No saved credentials to remove.[/warning]")
@main.command()
def upgrade():
"""Upgrade Postal using the installer for its current environment."""
try:
current = Version(installed_version("postalcli"))
except PackageNotFoundError as error:
raise click.ClickException(
"Could not determine the installed postal version; install postalcli before upgrading."
) from error
try:
latest = _latest_version()
except (InvalidVersion, KeyError, TypeError, URLError, TimeoutError, OSError, ValueError) as error:
raise click.ClickException(f"Could not check for updates: {error}") from error
if latest <= current:
console.print(f"[success]Postal is already up to date ({current}).[/success]")
return
command = _upgrade_command()
console.print(f"Updating postal from {current} to {latest}...")
try:
result = subprocess.run(command, check=False)
except OSError as error:
raise click.ClickException(f"Could not start the upgrade: {error}") from error
if result.returncode:
raise click.ClickException("postal upgrade failed")
console.print("[success]Upgrade command completed. Restart Postal to load any updates.[/success]")
@main.command("/help")
@click.pass_context
def cli_help(ctx: click.Context):
"""Alias for --help."""
click.echo(ctx.parent.get_help())
if __name__ == "__main__": # better than just main() ngl
main()