elan-cli 0.1.3__tar.gz → 0.1.4__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.
Files changed (32) hide show
  1. elan_cli-0.1.4/CHANGELOG.md +109 -0
  2. {elan_cli-0.1.3 → elan_cli-0.1.4}/PKG-INFO +1 -1
  3. {elan_cli-0.1.3 → elan_cli-0.1.4}/pyproject.toml +1 -1
  4. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/adk.py +4 -2
  5. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/auth.py +71 -13
  6. elan_cli-0.1.4/src/elan_cli/child.py +88 -0
  7. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/client.py +35 -1
  8. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/deploy.py +26 -0
  9. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/destroy.py +6 -2
  10. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/env.py +33 -7
  11. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/files.py +9 -1
  12. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/invoke.py +34 -4
  13. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/main.py +48 -4
  14. elan_cli-0.1.4/src/elan_cli/prompt.py +35 -0
  15. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/rollback.py +6 -1
  16. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/stream.py +64 -3
  17. elan_cli-0.1.3/CHANGELOG.md +0 -53
  18. {elan_cli-0.1.3 → elan_cli-0.1.4}/.gitignore +0 -0
  19. {elan_cli-0.1.3 → elan_cli-0.1.4}/LICENSE +0 -0
  20. {elan_cli-0.1.3 → elan_cli-0.1.4}/README.md +0 -0
  21. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/__init__.py +0 -0
  22. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/config.py +0 -0
  23. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/doctor.py +0 -0
  24. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/logs.py +0 -0
  25. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/manifests.py +0 -0
  26. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/project.py +0 -0
  27. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/projects.py +0 -0
  28. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/scaffold.py +0 -0
  29. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/secret.py +0 -0
  30. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/tenant.py +0 -0
  31. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/validate.py +0 -0
  32. {elan_cli-0.1.3 → elan_cli-0.1.4}/src/elan_cli/wallet.py +0 -0
@@ -0,0 +1,109 @@
1
+ # Changelog
2
+
3
+ Versions follow the tag that published them — `cli/v*`. A version with no date
4
+ has not been published yet.
5
+
6
+ ## 0.1.4 — unreleased
7
+
8
+ ### Added
9
+ - A refusal that names a page to fix it now prints that page. `elan project
10
+ create` and `elan deploy` are refused when the tenant has no card on file and
11
+ no credit, and the refusal ends with the console URL where a tenant admin adds
12
+ one, on its own line.
13
+
14
+ ### Fixed
15
+ - **Ctrl+C no longer prints a traceback.** Every command exited an interrupt
16
+ with a stack trace through `main.py` and `subprocess.py` — the two places the
17
+ problem never is. The exit status is unchanged at 130 (128 + SIGINT), which is
18
+ what a shell already reported; what is gone is the noise.
19
+ - **`elan adk web` shuts down cleanly.** Ctrl+C reaches both `elan` and the
20
+ `adk` child, because they share the terminal's process group. `subprocess.run`
21
+ then SIGKILLed the child a quarter of a second into uvicorn's own graceful
22
+ shutdown, truncating its output mid-line. The child is now waited for; a
23
+ second Ctrl+C still kills it. The same fix covers `elan env`'s and
24
+ `elan init`'s `uv` install, which is minutes long and worth interrupting.
25
+ - **A command that left work running says so.** An interrupted `elan deploy`
26
+ prints `elan status <id>` and that the build is still going in the cluster; an
27
+ interrupted `elan invoke` points at `GET /v1/runs/<id>`; an interrupted
28
+ `elan login` says nothing was signed in and the code simply expires; an
29
+ interrupted install says the `.venv` is unfinished and `elan env` continues
30
+ it. A bare "interrupted" implied the opposite of all four.
31
+ - **A confirmation nobody can answer is a refusal, not a crash.** `elan destroy`
32
+ and `elan rollback` called `input()` bare, so Ctrl+D — or any non-interactive
33
+ context such as CI or a pipe — raised `EOFError`. Both now decline.
34
+ - **A child killed by a signal reports the shell's own exit status.** A negative
35
+ return code was passed to `sys.exit` unchanged, so a SIGTERMed child produced
36
+ status 241. It is now `128 + signal`: 130, 137, 143.
37
+ - **The event stream explains its own failures.** A rejected handshake was a raw
38
+ `websockets.exceptions.InvalidStatus`; a 401 now says to run `elan login`. A
39
+ server that goes away mid-run was a raw `ConnectionClosedError` and now names
40
+ `GET /v1/runs/<id>`, because nothing buffers a stream for a closed socket. The
41
+ ticket is never printed in either message.
42
+ - **`elan invoke --timeout` works.** The deadline was checked at the end of the
43
+ event loop, after the branch that prints, so every `continue` above it skipped
44
+ the clock — on an agent that emitted events without answering, the flag could
45
+ not fire at all and Ctrl+C was the only way out.
46
+ - **`elan files` works without `--project`.** The documented default — the
47
+ project of the `elan.yaml` you are standing in — read a field that does not
48
+ exist, so it raised `AttributeError` rather than resolving anything.
49
+ - **A redirect is refused instead of being parsed as the answer.** Every status
50
+ check was `>= 400`, so a 3xx fell through to `response.json()` and the CLI
51
+ died on the redirector's HTML with a `JSONDecodeError` about line 1 column 1
52
+ — a message about JSON, for a wrong `--api`. Measured against np, where a
53
+ request to the wrong base path answers `308` from nginx. The redirect is not
54
+ followed, deliberately: every request carries a bearer token, and a redirect
55
+ is a server-supplied instruction about where to send it.
56
+ - **A locked or absent system keyring is explained.** `NoKeyringError` on a
57
+ headless machine was a traceback from `elan login`, `logout`, `whoami` and
58
+ from every authenticated command, since each one reads the stored token. A
59
+ dropped connection or a non-JSON reply while waiting for the browser during
60
+ `elan login` was likewise unhandled.
61
+
62
+ ## 0.1.3 — 2026-11-10
63
+
64
+ ### Added
65
+ - `elan init` makes the repository ready for an AI coding assistant. It writes
66
+ a `CLAUDE.md` naming the rules a deploy enforces — bump `MANIFEST.version`,
67
+ add targets with `elan new`, push before deploying, never put a secret in a
68
+ file — and linking this platform's docs and its `llms-full.txt`. It also
69
+ writes a `.claude/settings.json` that lets an assistant run read-only
70
+ commands unasked, asks before anything that deploys, spends, deletes or
71
+ pushes, and refuses to read `.env`. Neither file is overwritten if it exists,
72
+ and `.claude/settings.local.json` is git-ignored.
73
+
74
+ ## 0.1.2 — 2026-11-10
75
+
76
+ ### Changed
77
+ - `elan login` reaches the production API with no arguments. `--api` is now the
78
+ override for anything else, which is what this README has said since the
79
+ first release. Precedence, highest first: `--api` (which is written down and
80
+ therefore remembered), then `ELAN_API`, then the stored `config.json`, then
81
+ production.
82
+
83
+ It used to refuse to run without one, on the reasoning that a client aimed at
84
+ a staging environment deploys somebody's first agent there without saying so.
85
+ That was sound while there was no production to point at, and stopped being
86
+ sound once there was — a developer who had just installed the CLI was asked
87
+ for a URL that appears nowhere in the package they installed.
88
+
89
+ ### Fixed
90
+ - The CLI reference documented `ELAN_CONFIG_HOME`, which nothing read; the
91
+ variable is and always was `ELAN_HOME`.
92
+
93
+ ## 0.1.1 — 2026-11-09
94
+
95
+ ### Added
96
+ - `elan --version`, which also names the `elan-sdk` version it is running
97
+ against. The two publish independently, so a current-looking CLI can be
98
+ sitting on an older SDK. Nothing sends either number to the platform, so this
99
+ answers "which one have I got" and not "is mine too old".
100
+
101
+ ## 0.1.0 — 2026-11-09
102
+
103
+ First public release.
104
+
105
+ `uv tool install elan-cli` — the install five documents had described since
106
+ before it was possible. Sign in with a device-code flow whose refresh token
107
+ goes to the OS keyring and never to a file; scaffold a project; build the local
108
+ environment; validate your manifests against your deploy file; deploy, invoke,
109
+ tail logs, roll back and tear down.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: elan-cli
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Summary: The command line a developer deploys an agent with
5
5
  Project-URL: Homepage, https://openelan.ai
6
6
  Project-URL: Documentation, https://openelan.ai/app/docs
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "elan-cli"
3
- version = "0.1.3"
3
+ version = "0.1.4"
4
4
  description = "The command line a developer deploys an agent with"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -28,9 +28,9 @@ from __future__ import annotations
28
28
 
29
29
  import os
30
30
  import shutil
31
- import subprocess
32
31
  from pathlib import Path
33
32
 
33
+ from elan_cli.child import supervise
34
34
  from elan_cli.manifests import ManifestError, interpreter
35
35
  from elan_cli.manifests import read as read_manifests
36
36
  from elan_cli.project import Project, ProjectError, find
@@ -181,7 +181,9 @@ def run(args: list[str], start: Path | None = None,
181
181
  argv = [str(adk), *argv_for(args, root, slugs)]
182
182
  print(f"running {' '.join(argv[1:])}")
183
183
  print(flush=True)
184
- return subprocess.run(argv, cwd=project.root, env=_environment()).returncode
184
+ # SUPERVISED RATHER THAN `subprocess.run`, because `adk web` is the one
185
+ # child here with a graceful shutdown worth protecting — see `child.py`.
186
+ return supervise(argv, cwd=project.root, env=_environment())
185
187
 
186
188
 
187
189
  def _environment() -> dict[str, str]:
@@ -21,6 +21,7 @@ from __future__ import annotations
21
21
  import json
22
22
  import logging
23
23
  import time
24
+ from contextlib import contextmanager
24
25
  from dataclasses import dataclass
25
26
 
26
27
  import httpx
@@ -82,6 +83,37 @@ def _keyring():
82
83
  return keyring
83
84
 
84
85
 
86
+ @contextmanager
87
+ def _keyring_errors(doing: str):
88
+ """Turn a keyring fault into an `AuthError` naming what to do (ADR-0231).
89
+
90
+ THE CREDENTIAL'S OWN READS WERE THE UNPROTECTED ONES, which is the wrong
91
+ way round. `NoKeyringError` on a headless Linux box and `KeyringLocked` on
92
+ a locked login keychain were raw tracebacks — from `elan login`, `logout`,
93
+ `whoami`, and from `client.py`'s `auth.stored(...)` on EVERY authenticated
94
+ command. The ACCESS-TOKEN CACHE below is already defensive on purpose
95
+ (`# noqa: BLE001`), and that asymmetry stays: a cache that cannot be read
96
+ is a slow command, while a credential that cannot be read is a stuck one.
97
+
98
+ BROADLY, BECAUSE THE BACKEND DECIDES THE EXCEPTION. `keyring` dispatches to
99
+ a platform backend and each raises its own class; naming them would mean
100
+ importing `keyring.errors` at module scope, which is exactly what
101
+ `_keyring()` defers. `AuthError` is already in `main.py`'s `REFUSALS`.
102
+ """
103
+ try:
104
+ yield
105
+ except AuthError:
106
+ # `_keyring()`'s own refusal about a missing package. Already phrased.
107
+ raise
108
+ except Exception as exc: # noqa: BLE001 - see the docstring
109
+ raise AuthError(
110
+ f"the system keyring could not be {doing} ({exc}).\n\n"
111
+ "This is the OS credential store rather than anything about your "
112
+ "account. On a headless machine there may be none running; on a "
113
+ "desktop the login keychain may be locked."
114
+ ) from exc
115
+
116
+
85
117
  def store(issuer: str, refresh_token: str) -> None:
86
118
  """Keep the refresh token, and DROP ANY CACHED ACCESS TOKEN WITH IT.
87
119
 
@@ -90,12 +122,14 @@ def store(issuer: str, refresh_token: str) -> None:
90
122
  expired. Writing one without clearing the other is how a cache outlives
91
123
  the thing it was derived from.
92
124
  """
93
- _keyring().set_password(KEYRING_SERVICE, issuer, refresh_token)
125
+ with _keyring_errors("written to"):
126
+ _keyring().set_password(KEYRING_SERVICE, issuer, refresh_token)
94
127
  _forget_access(issuer)
95
128
 
96
129
 
97
130
  def stored(issuer: str) -> str | None:
98
- return _keyring().get_password(KEYRING_SERVICE, issuer)
131
+ with _keyring_errors("read"):
132
+ return _keyring().get_password(KEYRING_SERVICE, issuer)
99
133
 
100
134
 
101
135
  # ── THE ACCESS TOKEN IS CACHED TOO, AND THAT IS A LATENCY FIX ──────────────
@@ -166,11 +200,12 @@ def forget(issuer: str) -> bool:
166
200
  """`elan logout`. BOTH CREDENTIALS, or the session outlives the logout:
167
201
  a cached access token keeps working until it expires, which is the one
168
202
  thing somebody signing out is asking not to happen."""
169
- keyring = _keyring()
170
- _forget_access(issuer)
171
- if keyring.get_password(KEYRING_SERVICE, issuer) is None:
172
- return False
173
- keyring.delete_password(KEYRING_SERVICE, issuer)
203
+ with _keyring_errors("read"):
204
+ keyring = _keyring()
205
+ _forget_access(issuer)
206
+ if keyring.get_password(KEYRING_SERVICE, issuer) is None:
207
+ return False
208
+ keyring.delete_password(KEYRING_SERVICE, issuer)
174
209
  return True
175
210
 
176
211
 
@@ -291,12 +326,35 @@ def poll(config: Config, device: dict, *, client: httpx.Client | None = None,
291
326
  try:
292
327
  while now() < deadline:
293
328
  sleep(interval)
294
- response = client.post(device["_token_endpoint"], data={
295
- "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
296
- "device_code": device["device_code"],
297
- "client_id": config.client_id,
298
- })
299
- payload = response.json() if response.content else {}
329
+ try:
330
+ response = client.post(device["_token_endpoint"], data={
331
+ "grant_type":
332
+ "urn:ietf:params:oauth:grant-type:device_code",
333
+ "device_code": device["device_code"],
334
+ "client_id": config.client_id,
335
+ })
336
+ except httpx.HTTPError as exc:
337
+ # THE ONE SIBLING THAT DID NOT DO THIS (ADR-0231).
338
+ # `platform_auth`, `discover`, `begin` and `refresh` all wrap
339
+ # `httpx.HTTPError`; this did not, so a wifi blip while a
340
+ # developer was approving in the browser was a raw
341
+ # `httpx.ConnectError` from the middle of a sign-in.
342
+ raise AuthError(
343
+ f"lost contact with the issuer while waiting for the "
344
+ f"browser ({exc}). The code is still valid until it "
345
+ f"expires — run `elan login` again."
346
+ ) from exc
347
+ try:
348
+ payload = response.json() if response.content else {}
349
+ except ValueError:
350
+ # A NON-JSON ERROR BODY — a gateway's HTML 502, typically.
351
+ # `response.json()` was unguarded, so that arrived as a
352
+ # `json.JSONDecodeError` naming a column number.
353
+ raise AuthError(
354
+ f"the issuer answered {response.status_code} with "
355
+ f"something that is not JSON, which usually means a proxy "
356
+ f"rather than the issuer. Run `elan login` again."
357
+ ) from None
300
358
  if response.status_code == 200:
301
359
  return _tokens(payload)
302
360
 
@@ -0,0 +1,88 @@
1
+ """Running another program and surviving a Ctrl+C (ADR-0231).
2
+
3
+ `subprocess.run` IS WRONG FOR A LONG-LIVED CHILD, AND THAT IS THE BUG THIS
4
+ MODULE EXISTS FOR. Ctrl+C in a terminal goes to the whole foreground process
5
+ GROUP, and a child started without `start_new_session` is in ours. So both
6
+ processes get the SIGINT at once: `adk web` runs uvicorn, which installs its
7
+ own handler and begins a graceful shutdown, while `subprocess.run` raises
8
+ `KeyboardInterrupt`, waits `_sigint_wait_secs` (0.25s) and then calls
9
+ `process.kill()`. The child is SIGKILLed mid-shutdown — usually with its
10
+ banner half-written — and the traceback that follows names `subprocess.py`,
11
+ which is the one place the problem is not.
12
+
13
+ MEASURED, against a child that catches SIGINT and takes 0.6s to shut down —
14
+ `adk web`'s shape. The parent was put in its own process group and the group
15
+ was sent SIGINT, which is what a terminal's Ctrl+C does.
16
+
17
+ subprocess.run child: serving
18
+ child: shutting down
19
+ <nothing: SIGKILLed 0.25s in>
20
+ Traceback ... in subprocess.py ... KeyboardInterrupt
21
+ status -2
22
+
23
+ supervise child: serving
24
+ child: shutting down
25
+ child: shutdown complete
26
+ status 0
27
+
28
+ Both halves of the report are in that first column: the child's output cut off
29
+ mid-shutdown, and a traceback about none of it.
30
+
31
+ ONE SPELLING, BECAUSE THE RULE IS NOT THE TRANSPORT. Three places in this CLI
32
+ start a child and two of them want this; a copy per call site passes its own
33
+ tests against its own copy and nothing compares the copies (ADR-0116).
34
+
35
+ `manifests.py` DELIBERATELY DOES NOT USE THIS. It captures output, so it needs
36
+ `communicate()` rather than `wait()`, and its child is a manifest export that
37
+ takes a second or two — there is no graceful shutdown to protect, and the only
38
+ symptom of a Ctrl+C there was the traceback, which the boundary in `main.py`
39
+ now handles. Adding a captured variant here would be a second code path to
40
+ keep correct for a case that does not need it.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import subprocess
46
+ from pathlib import Path
47
+
48
+
49
+ def exit_status(code: int) -> int:
50
+ """A process's exit status from a `Popen` return code.
51
+
52
+ A RETURNCODE IS NEGATIVE WHEN A CHILD DIES BY A SIGNAL, and `sys.exit(-15)`
53
+ produces status **241** — a number that means nothing to anybody. The shell
54
+ convention is `128 + signal`, so `-2` (SIGINT) becomes 130 and `-15`
55
+ (SIGTERM) becomes 143, which is what a developer's `$?` and any CI step
56
+ already expect to see.
57
+ """
58
+ return 128 - code if code < 0 else code
59
+
60
+
61
+ def supervise(argv: list[str], *, cwd: Path | str | None = None,
62
+ env: dict[str, str] | None = None) -> int:
63
+ """Run a child to completion, INCLUDING through a Ctrl+C.
64
+
65
+ THE FIX IS TO WAIT, NOT TO SIGNAL. The child already has the SIGINT — it
66
+ shares our process group — so the second `wait()` lets it finish the
67
+ shutdown it performs correctly on its own. Nothing is printed here on that
68
+ path, because the child has already said it: one more "interrupted" after
69
+ ADK's own shutdown banner is the noise this change exists to remove.
70
+
71
+ KEEPING THE CHILD IN OUR PROCESS GROUP IS DELIBERATE AND LOOKS LIKE THE
72
+ BUG. The tempting one-line "fix" is `start_new_session=True` to isolate it,
73
+ which would stop the SIGINT reaching the child at all — and then its
74
+ graceful shutdown becomes something this function has to implement.
75
+
76
+ A SECOND Ctrl+C IS A WAY OUT RATHER THAN AN ERROR. A child ignoring the
77
+ first is the only case where killing it is the right answer, and a
78
+ developer who presses it twice means it.
79
+ """
80
+ child = subprocess.Popen(argv, cwd=cwd, env=env)
81
+ try:
82
+ return exit_status(child.wait())
83
+ except KeyboardInterrupt:
84
+ try:
85
+ return exit_status(child.wait())
86
+ except KeyboardInterrupt:
87
+ child.kill()
88
+ return exit_status(child.wait())
@@ -85,6 +85,29 @@ class Api:
85
85
  raise ApiError(f"no such thing: {path}")
86
86
  if response.status_code >= 400:
87
87
  raise ApiError(_refusal(response))
88
+ if response.is_redirect:
89
+ # A REDIRECT IS NOT A SUCCESS, AND IT WAS BEING READ AS ONE. Every
90
+ # check above is `>= 400`, so a 3xx fell through to `response.json()`
91
+ # and the CLI died on the redirector's HTML with a
92
+ # `JSONDecodeError` naming line 1 column 1 — a message about JSON,
93
+ # for a wrong base URL. Measured against np: a POST to
94
+ # `https://np.openelan.ai/api/v1/projects` answers
95
+ # `308 -> /app` from nginx, because `/api` is not the API's path
96
+ # there.
97
+ #
98
+ # AND IT IS NOT FOLLOWED, DELIBERATELY. httpx does not follow by
99
+ # default and must not start here: every request carries a bearer
100
+ # token, and a redirect is a server-supplied instruction about
101
+ # where to send it. `Location` on this one pointed at the console.
102
+ # Refusing names the one thing that is actually wrong.
103
+ where = response.headers.get("location", "")
104
+ raise ApiError(
105
+ f"{self.config.api} redirected {method} {path}"
106
+ + (f" to {where}" if where else "")
107
+ + ".\n\nThat is usually the wrong --api for this platform: the "
108
+ "redirect means something other than the API answers there. "
109
+ "`elan login --api <url>` sets it, and `elan doctor` prints "
110
+ "what is configured now.")
88
111
  return response.json() if response.content else {}
89
112
 
90
113
  def close(self) -> None:
@@ -112,4 +135,15 @@ def _refusal(response: httpx.Response) -> str:
112
135
  lines.append(f" {line}")
113
136
  lines.append("")
114
137
  return "\n".join(lines).rstrip()
115
- return payload.get("error") or f"HTTP {response.status_code}"
138
+
139
+ written = payload.get("error") or f"HTTP {response.status_code}"
140
+ # A REFUSAL MAY NAME A PAGE THAT FIXES IT, and here it has to arrive as
141
+ # text. The console renders that URL as a real link beside the sentence, so
142
+ # the service sends the two separately — which would silently drop the link
143
+ # on this side if nothing read it (ADR-0230). There are no hyperlinks in
144
+ # this CLI at all, so an indented line of its own is the whole mechanism;
145
+ # most terminals make it clickable anyway.
146
+ page = payload.get("billing_url")
147
+ if page:
148
+ written = f"{written}\n add one and try again:\n {page}"
149
+ return written
@@ -14,6 +14,7 @@ project; building a subset of a repo is not a thing that exists.
14
14
  from __future__ import annotations
15
15
 
16
16
  import subprocess
17
+ import sys
17
18
  import time
18
19
  from pathlib import Path
19
20
 
@@ -156,6 +157,31 @@ def _watch(api: Api, deployment_id: str, *, sleep=time.sleep) -> int:
156
157
  one phase that mattered; a spinner would hide which phase is slow. So a
157
158
  phase prints when it is entered and not again.
158
159
  """
160
+ try:
161
+ return _follow(api, deployment_id, sleep=sleep)
162
+ except KeyboardInterrupt:
163
+ # CTRL+C STOPS WATCHING AND DOES NOT STOP THE DEPLOY, and saying so is
164
+ # the whole point of catching it here (ADR-0231). The build was accepted
165
+ # before this loop started and is running in the cluster; the boundary's
166
+ # bare "interrupted." would imply the opposite, and a developer who
167
+ # believes it redeploys on top of a live deploy and gets `ProjectBusy`
168
+ # for a reason that looks unrelated.
169
+ #
170
+ # THE WAY BACK IS PRINTED HERE because it is printed nowhere else:
171
+ # `elan status <id>` appears only on the `--no-wait` path, so an
172
+ # interrupted wait otherwise leaves the id on screen with no verb.
173
+ #
174
+ # AROUND THE WHOLE LOOP RATHER THAN EACH CALL IN IT. Nearly every
175
+ # second of a ten-minute build is spent in the `sleep`, not in the
176
+ # request, so guarding only the request would catch almost no real
177
+ # interrupt — and two copies of this message is how they come to differ.
178
+ print(f"\nstopped watching. The deploy was accepted and is still "
179
+ f"running:\n\n elan status {deployment_id}", file=sys.stderr)
180
+ return 130
181
+
182
+
183
+ def _follow(api: Api, deployment_id: str, *, sleep=time.sleep) -> int:
184
+ """The poll loop itself. See `_watch` for what wraps it and why."""
159
185
  seen: str | None = None
160
186
  while True:
161
187
  try:
@@ -18,6 +18,7 @@ import sys
18
18
 
19
19
  from elan_cli.client import Api, ApiError
20
20
  from elan_cli.project import find
21
+ from elan_cli.prompt import ask
21
22
 
22
23
 
23
24
  def run(api: Api, agent: str = "", *, whole_project: bool = False,
@@ -42,8 +43,11 @@ def run(api: Api, agent: str = "", *, whole_project: bool = False,
42
43
  # THE NAME, NOT A y/N. A yes is a keystroke somebody makes while
43
44
  # reading the next line; typing the name is the one confirmation that
44
45
  # cannot be given to the wrong thing by accident.
45
- typed = input(f"\nType {what!r} to confirm: ").strip()
46
- if typed != what:
46
+ # `ask` AND NOT `input`: EOF and Ctrl+C are both "no" rather than a
47
+ # traceback, which is what `elan destroy` in CI or behind a pipe used
48
+ # to be (ADR-0231). `None` is a declined confirmation like any other.
49
+ typed = ask(f"\nType {what!r} to confirm: ")
50
+ if typed is None or typed.strip() != what:
47
51
  print("Nothing was destroyed.")
48
52
  return 1
49
53
 
@@ -39,9 +39,9 @@ builder reads.
39
39
  from __future__ import annotations
40
40
 
41
41
  import shutil
42
- import subprocess
43
42
  from pathlib import Path
44
43
 
44
+ from elan_cli.child import supervise
45
45
  from elan_cli.project import ProjectError, find
46
46
 
47
47
  #: What `elan validate` and `elan adk` import the repo's agents through.
@@ -74,23 +74,49 @@ def run(start: Path | None = None) -> int:
74
74
  print(f"runtime {RUNTIME_PACKAGE}", flush=True)
75
75
 
76
76
  if not python.exists():
77
- if _uv(["venv", str(venv)], project.root) != 0:
78
- return 1
77
+ if (code := _uv(["venv", str(venv)], project.root)) != 0:
78
+ return _refused(code, venv)
79
79
 
80
- if _uv(["pip", "install", "--python", str(python), RUNTIME_PACKAGE],
81
- project.root) != 0:
82
- return 1
80
+ if (code := _uv(["pip", "install", "--python", str(python),
81
+ RUNTIME_PACKAGE], project.root)) != 0:
82
+ return _refused(code, venv)
83
83
 
84
84
  print()
85
85
  print("ok — `elan validate` will find this automatically.")
86
86
  return 0
87
87
 
88
88
 
89
+ def _refused(code: int, venv: Path) -> int:
90
+ """An install that did not finish, told apart from one that failed.
91
+
92
+ AN INTERRUPTED INSTALL LOOKED IDENTICAL TO A BROKEN MACHINE (ADR-0231).
93
+ uv prints its own diagnosis when it fails, which is why nothing is repeated
94
+ here — but on a Ctrl+C it prints nothing and this returned a bare 1, so a
95
+ developer who stopped a slow download got the same silence as one whose
96
+ compiler is missing. `elan init` then printed `Next:` over the top of it.
97
+
98
+ 130 IS THE SIGNAL, from `child.supervise`: 128 + SIGINT. The partial `.venv`
99
+ is left where it is on purpose — `uv` is incremental, so re-running
100
+ continues rather than starting over, and deleting it would throw away
101
+ whatever did download.
102
+ """
103
+ if code == 130:
104
+ print(f"\nstopped. {venv} is unfinished — `elan env` continues from "
105
+ f"where this got to.")
106
+ return 1
107
+
108
+
89
109
  def _uv(args: list[str], cwd: Path) -> int:
90
110
  """Run uv, letting its own output through.
91
111
 
92
112
  NOT CAPTURED. A resolution failure here is about the developer's machine —
93
113
  a Python version, a compiler, a network — and uv says all of that far
94
114
  better than a wrapper repeating "install failed" would.
115
+
116
+ SUPERVISED, BECAUSE AN INSTALL IS LONG AND INTERRUPTIBLE (ADR-0231). This
117
+ is minutes of downloading and compiling, so Ctrl+C is a thing a developer
118
+ will actually do — and `subprocess.run` would SIGKILL uv a quarter of a
119
+ second in, mid-write, then traceback. uv cleans up its own cache on a
120
+ signal if it is allowed to finish; `child.supervise` is what allows it.
95
121
  """
96
- return subprocess.run(["uv", *args], cwd=cwd).returncode
122
+ return supervise(["uv", *args], cwd=cwd)
@@ -47,7 +47,15 @@ def _project(api: Api, given: str) -> str:
47
47
  if given:
48
48
  return given
49
49
  try:
50
- return find().project
50
+ # `.spec.project` AND NOT `.project`. `Project` has no `project`
51
+ # attribute — its fields are `root`, `spec_path` and `spec` — and it is
52
+ # a frozen slots dataclass, so the mistake was an `AttributeError`
53
+ # rather than the `ProjectError` caught below: a raw traceback, and the
54
+ # documented default never worked at all. Every case in
55
+ # `test_elan_cli_files.py` passed `--project` explicitly, which is why
56
+ # nothing found it; a fixture that always supplies the optional
57
+ # argument cannot test the default.
58
+ return find().spec.project
51
59
  except ProjectError as exc:
52
60
  raise FilesError(
53
61
  "which project? Run this inside a project directory, or pass "
@@ -96,8 +96,25 @@ def run(api: Api, target: str, text: str, *, session: str = "",
96
96
  print(f"invocation {invocation}")
97
97
  print(f"session {session_id}")
98
98
  print()
99
- return _follow(socket, invocation, target, session_id,
100
- timeout, now)
99
+ try:
100
+ return _follow(socket, invocation, target, session_id,
101
+ timeout, now)
102
+ except KeyboardInterrupt:
103
+ # CTRL+C STOPS LISTENING AND DOES NOT STOP THE RUN (ADR-0231).
104
+ # The invocation was accepted before this socket was read from,
105
+ # and the agent keeps going; the boundary's bare "interrupted."
106
+ # would say the opposite.
107
+ #
108
+ # THE SAME SENTENCE `_follow`'s TIMEOUT BRANCH ALREADY ENDS
109
+ # WITH, and for the same reason: nothing buffers an event
110
+ # stream for a socket that is not open, so reconnecting would
111
+ # show only what happens NEXT. The read path is what reads
112
+ # what already happened.
113
+ print(f"\nstopped listening. The invocation was accepted and "
114
+ f"may still be running — `elan.runs.get({invocation!r})`"
115
+ f", or GET /v1/runs/{invocation}, reads what it has done "
116
+ f"so far.", file=sys.stderr)
117
+ return 130
101
118
  except StreamError as exc:
102
119
  print(f"error: {exc}", file=sys.stderr)
103
120
  return 1
@@ -117,6 +134,21 @@ def _follow(socket, invocation: str, target: str, session_id: str,
117
134
  #: for ever on a run that was sitting there asking a question (ADR-0116).
118
135
  waiting_on = ""
119
136
  for event in replies(socket, invocation):
137
+ # ── THE DEADLINE IS CHECKED AT THE TOP, AND THAT IS A FIX ──────────
138
+ #
139
+ # It used to sit at the END of this body, after `said = True`, so every
140
+ # `continue` above it skipped the clock — a `queued` event, an
141
+ # unshown kind, an empty body. On an agent that emits those and never
142
+ # answers, `--timeout` could not fire at all and the "No reply within"
143
+ # message below was unreachable: the only way out was Ctrl+C.
144
+ #
145
+ # IT STILL CANNOT INTERRUPT A BLOCKED `recv()`, which is the honest
146
+ # limit. `websockets.sync` has no default read timeout, so a socket
147
+ # that goes quiet entirely is bounded by the SERVER closing it — this
148
+ # bounds a socket that is chatty and unhelpful, which is the case that
149
+ # was measured.
150
+ if now() > deadline:
151
+ break
120
152
  if ends_the_run(event):
121
153
  # ASKED OF THE SDK, which is the only place the rule is spelled —
122
154
  # `finished`, `error`, OR the engine's terminal pause.
@@ -146,8 +178,6 @@ def _follow(socket, invocation: str, target: str, session_id: str,
146
178
  who = author_of(event) or target
147
179
  print(f"{who}: {body}" if not said else body)
148
180
  said = True
149
- if now() > deadline:
150
- break
151
181
  # ── PAUSED IS NOT FINISHED, AND IT IS NOT SILENCE EITHER ───────────────
152
182
  #
153
183
  # It is the third outcome, and the one this command cannot act on. Said
@@ -40,11 +40,30 @@ from elan_cli import projects as projects_cmd
40
40
  from elan_cli.auth import AuthError
41
41
  from elan_cli.client import Api, ApiError
42
42
  from elan_cli.config import Config, ConfigError
43
- from elan_cli.files import FilesError # noqa: F401 — re-exported for tests
43
+ from elan_cli.files import FilesError
44
+ from elan_cli.manifests import ManifestError
44
45
  from elan_cli.project import ProjectError, find
45
46
  from elan_cli.secret import SecretError
47
+ from elan_cli.stream import StreamError
46
48
  from elan_cli.wallet import WalletError
47
49
 
50
+ #: Every exception this CLI raises on purpose, caught at the boundary below.
51
+ #:
52
+ #: COMPLETE RATHER THAN THE ONES THAT HAPPEN TO ESCAPE (ADR-0231). This used to
53
+ #: name six classes, and four more existed: `FilesError`, `StreamError`,
54
+ #: `ManifestError` and its subclass `NoRuntime`. None of them tracebacked,
55
+ #: because each was caught at its single call site — which is not a property
56
+ #: anybody maintains. "It is handled everywhere it is raised" is true until
57
+ #: somebody raises it somewhere else, and the symptom then is a stack trace in
58
+ #: front of a developer rather than the sentence the exception already carries.
59
+ #:
60
+ #: A TUPLE AND NOT A LITERAL IN THE `except`, so a test can read it.
61
+ #: `test_every_refusal_reaches_the_boundary` walks this package for `Exception`
62
+ #: subclasses and asserts each one appears here — guilty until named, because a
63
+ #: positive predicate over an open set is a sampling method rather than a guard.
64
+ REFUSALS = (ProjectError, ConfigError, AuthError, ApiError, SecretError,
65
+ WalletError, FilesError, ManifestError, StreamError)
66
+
48
67
 
49
68
  def version_line() -> str:
50
69
  """What `--version` prints, read back out of the INSTALLED distributions.
@@ -360,13 +379,27 @@ def run(argv: list[str] | None = None) -> int:
360
379
 
361
380
  try:
362
381
  return _dispatch(args, parser)
363
- except (ProjectError, ConfigError, AuthError, ApiError, SecretError,
364
- WalletError) as exc:
382
+ except REFUSALS as exc:
365
383
  # EVERY ONE OF THESE IS ALREADY PHRASED FOR THE DEVELOPER, and none is
366
384
  # about this file. A traceback here would name the one place the
367
385
  # problem is not.
368
386
  print(f"error: {exc}", file=sys.stderr)
369
387
  return 2
388
+ except KeyboardInterrupt:
389
+ # 130 IS WHAT A SHELL ALREADY REPORTS for a command killed by SIGINT
390
+ # (128 + 2), because CPython re-raises an unhandled `KeyboardInterrupt`
391
+ # through the default handler. So the STATUS does not change here and
392
+ # nobody's CI starts seeing a different number — what changes is the
393
+ # traceback, which named `main.py` and `subprocess.py`: the two places
394
+ # the problem never is (ADR-0231).
395
+ #
396
+ # COMMANDS THAT LEFT WORK RUNNING SAY SO THEMSELVES, before this.
397
+ # `deploy`, `invoke`, `init` and `login` each catch their own
398
+ # interrupt, because a bare "interrupted" implies nothing happened —
399
+ # and for a deploy that was already accepted, that is the opposite of
400
+ # the truth.
401
+ print("\ninterrupted.", file=sys.stderr)
402
+ return 130
370
403
 
371
404
 
372
405
  def _dispatch(args, parser) -> int:
@@ -634,7 +667,18 @@ def _login(config: Config) -> int:
634
667
  print(f"(the code, if asked: {device['user_code']})\n")
635
668
  print("Waiting...")
636
669
 
637
- tokens = auth.poll(config, device)
670
+ try:
671
+ tokens = auth.poll(config, device)
672
+ except KeyboardInterrupt:
673
+ # NOTHING IS LEFT BEHIND, AND SAYING SO IS THE POINT (ADR-0231). This
674
+ # loop only polls; the device code sits unredeemed at the issuer until
675
+ # it expires on its own, and no credential was written here. A bare
676
+ # "interrupted." leaves somebody wondering whether a half-finished
677
+ # sign-in is now sitting somewhere.
678
+ print(f"\nstopped waiting. Nothing was signed in and the code "
679
+ f"{device['user_code']} simply expires — run `elan login` again "
680
+ f"when you are ready.", file=sys.stderr)
681
+ return 130
638
682
  if not tokens.refresh_token:
639
683
  # WORTH SAYING RATHER THAN SILENTLY DEGRADING. Without a refresh token
640
684
  # every command in an hour needs a browser again, and the developer
@@ -0,0 +1,35 @@
1
+ """Asking a developer to confirm something destructive (ADR-0231).
2
+
3
+ A CONFIRMATION THAT CANNOT BE READ IS A REFUSAL, and that is the only rule
4
+ here. `input()` raises `EOFError` when stdin is closed and `KeyboardInterrupt`
5
+ on a Ctrl+C, and both were uncaught — so `elan destroy` in CI, in a pipe, or
6
+ anywhere stdin is not a terminal exited with a traceback instead of declining.
7
+ A destructive command that crashes when nobody can answer it is the right
8
+ OUTCOME reached the wrong way; this makes it the right outcome on purpose.
9
+
10
+ ONE SPELLING, BECAUSE THE RULE IS THE PART THAT MATTERS. Two call sites read a
11
+ confirmation and they compare their answers differently — `destroy` wants the
12
+ name typed back, `rollback` wants a yes — so what is shared is the READ and not
13
+ the comparison. A copy each is how one of them comes to treat an empty stdin as
14
+ agreement.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+
20
+ def ask(question: str) -> str | None:
21
+ """The answer, or `None` if there was nobody to answer.
22
+
23
+ `None` MEANS "DECLINE", AND THE CALLER SPELLS THAT ITSELF rather than this
24
+ returning a bool. The two callers compare differently and neither
25
+ comparison belongs in here; what belongs in here is that EOF and Ctrl+C are
26
+ the same answer as "no".
27
+ """
28
+ try:
29
+ return input(question)
30
+ except (EOFError, KeyboardInterrupt):
31
+ # NEWLINE FIRST. A Ctrl+C or a Ctrl+D leaves the cursor at the end of
32
+ # the prompt, so whatever is printed next lands on the same line as the
33
+ # question and reads as part of it.
34
+ print()
35
+ return None
@@ -19,6 +19,7 @@ import sys
19
19
  from elan_cli.client import Api, ApiError
20
20
  from elan_cli.deploy import _watch
21
21
  from elan_cli.project import find
22
+ from elan_cli.prompt import ask
22
23
 
23
24
 
24
25
  def run(api: Api, to: str, *, wait: bool = True, assume_yes: bool = False) -> int:
@@ -48,7 +49,11 @@ def run(api: Api, to: str, *, wait: bool = True, assume_yes: bool = False) -> in
48
49
  # confirmation is about the CONSEQUENCE, not about spelling.
49
50
  print("\nEvery target above moves at once — a rollback is not staged "
50
51
  "the way a deploy is.")
51
- if input("Continue? [y/N] ").strip().lower() not in {"y", "yes"}:
52
+ # `ask` AND NOT `input`, so EOF and Ctrl+C decline rather than
53
+ # tracebacking — see `prompt.ask` (ADR-0231). The default is already no,
54
+ # which is what makes "unanswerable" and "declined" the same outcome.
55
+ answer = ask("Continue? [y/N] ")
56
+ if answer is None or answer.strip().lower() not in {"y", "yes"}:
52
57
  print("Nothing was changed.")
53
58
  return 1
54
59
 
@@ -130,7 +130,30 @@ def replies(socket, invocation_id: str) -> Iterator[dict]:
130
130
  client's own tests pass against its own copy and nothing compares them.
131
131
  """
132
132
  while True:
133
- raw = socket.recv()
133
+ try:
134
+ raw = socket.recv()
135
+ except KeyboardInterrupt:
136
+ # NOT OURS TO EXPLAIN. `invoke` knows the invocation id and says
137
+ # what is still running; re-raising keeps this module free of a
138
+ # message it would have to keep in step with that one.
139
+ raise
140
+ except Exception as exc:
141
+ # THE SERVER WENT AWAY MID-RUN, which was a raw
142
+ # `websockets.exceptions.ConnectionClosedError` (ADR-0231). Nothing
143
+ # caught it here or anywhere above, so an rt-service rollout during
144
+ # an `elan invoke` ended in a stack trace.
145
+ #
146
+ # IT POINTS AT THE READ PATH RATHER THAN SUGGESTING A RETRY.
147
+ # Nothing buffers an event stream for a socket that is not open —
148
+ # there is no `retain_acked_messages`, no snapshot and no seek — so
149
+ # reconnecting would show only what happens NEXT. What already
150
+ # happened is in observability's record.
151
+ raise StreamError(
152
+ f"the event stream closed before the run ended ({exc}). "
153
+ f"Nothing buffers it for a closed socket, so reconnecting "
154
+ f"would only show what happens next — "
155
+ f"GET /v1/runs/{invocation_id} reads what it has done so far."
156
+ ) from exc
134
157
  try:
135
158
  event = json.loads(raw)
136
159
  except ValueError:
@@ -158,5 +181,43 @@ def _connect(url: str):
158
181
  # ONLY FOR `wss://`. Passing a context to a plain ws:// connection is an
159
182
  # error rather than a no-op, and local development uses ws://.
160
183
  context = _trust() if url.startswith("wss://") else None
161
- return connect(url, ssl=context, open_timeout=30,
162
- max_size=4 * 1024 * 1024)
184
+ try:
185
+ return connect(url, ssl=context, open_timeout=30,
186
+ max_size=4 * 1024 * 1024)
187
+ except Exception as exc:
188
+ # EVERY HANDSHAKE FAILURE WAS A RAW TRACEBACK (ADR-0231). Only
189
+ # `ImportError` was converted, so `InvalidStatus` (a 401 or 403 on the
190
+ # handshake), `InvalidURI`, a `TimeoutError` after `open_timeout`,
191
+ # `ConnectionRefusedError` and `SSLCertVerificationError` all escaped
192
+ # as themselves — and none is in `main.py`'s `REFUSALS`, so a developer
193
+ # whose token had expired got `websockets.exceptions.InvalidStatus`
194
+ # rather than being told to sign in again.
195
+ #
196
+ # CAUGHT BROADLY ON PURPOSE. The alternative is naming the exception
197
+ # classes of a third-party library in a CLI that imports it lazily, and
198
+ # the set is version-dependent: `websockets` renamed `InvalidStatusCode`
199
+ # to `InvalidStatus` in 14.0. A failure to open a socket has exactly one
200
+ # meaning to this caller whatever its type, and `StreamError` says it.
201
+ raise StreamError(_opening_failed(url, exc)) from exc
202
+
203
+
204
+ def _opening_failed(url: str, exc: Exception) -> str:
205
+ """Why the socket would not open, in the developer's terms.
206
+
207
+ THE STATUS IS WORTH READING BECAUSE IT NAMES THE FIX. `client.py` does the
208
+ same for HTTP: a 401 means the token, a 403 means the tenant, and anything
209
+ else is about reachability. Guessing wrong sends somebody to re-run
210
+ `elan login` over a firewall, or to their network over an expired token.
211
+ """
212
+ status = getattr(getattr(exc, "response", None), "status_code", None)
213
+ if status in (401, 403):
214
+ return ("the event stream rejected your token. Run `elan login` "
215
+ "again.")
216
+ if isinstance(exc, TimeoutError):
217
+ return (f"the event stream at {url.split('?')[0]} did not answer "
218
+ f"within 30s. That is the platform's address or your network "
219
+ f"rather than your credentials.")
220
+ # THE URL IS PRINTED WITHOUT ITS QUERY STRING, because the ticket rides
221
+ # there (ADR-0163) and a short-lived credential in a terminal scrollback,
222
+ # a CI log or a pasted bug report is still a credential.
223
+ return f"could not open the event stream at {url.split('?')[0]}: {exc}"
@@ -1,53 +0,0 @@
1
- # Changelog
2
-
3
- Versions follow the tag that published them — `cli/v*`. A version with no date
4
- has not been published yet.
5
-
6
- ## 0.1.3 — unreleased
7
-
8
- ### Added
9
- - `elan init` makes the repository ready for an AI coding assistant. It writes
10
- a `CLAUDE.md` naming the rules a deploy enforces — bump `MANIFEST.version`,
11
- add targets with `elan new`, push before deploying, never put a secret in a
12
- file — and linking this platform's docs and its `llms-full.txt`. It also
13
- writes a `.claude/settings.json` that lets an assistant run read-only
14
- commands unasked, asks before anything that deploys, spends, deletes or
15
- pushes, and refuses to read `.env`. Neither file is overwritten if it exists,
16
- and `.claude/settings.local.json` is git-ignored.
17
-
18
- ## 0.1.2 — 2026-11-10
19
-
20
- ### Changed
21
- - `elan login` reaches the production API with no arguments. `--api` is now the
22
- override for anything else, which is what this README has said since the
23
- first release. Precedence, highest first: `--api` (which is written down and
24
- therefore remembered), then `ELAN_API`, then the stored `config.json`, then
25
- production.
26
-
27
- It used to refuse to run without one, on the reasoning that a client aimed at
28
- a staging environment deploys somebody's first agent there without saying so.
29
- That was sound while there was no production to point at, and stopped being
30
- sound once there was — a developer who had just installed the CLI was asked
31
- for a URL that appears nowhere in the package they installed.
32
-
33
- ### Fixed
34
- - The CLI reference documented `ELAN_CONFIG_HOME`, which nothing read; the
35
- variable is and always was `ELAN_HOME`.
36
-
37
- ## 0.1.1 — 2026-11-09
38
-
39
- ### Added
40
- - `elan --version`, which also names the `elan-sdk` version it is running
41
- against. The two publish independently, so a current-looking CLI can be
42
- sitting on an older SDK. Nothing sends either number to the platform, so this
43
- answers "which one have I got" and not "is mine too old".
44
-
45
- ## 0.1.0 — 2026-11-09
46
-
47
- First public release.
48
-
49
- `uv tool install elan-cli` — the install five documents had described since
50
- before it was possible. Sign in with a device-code flow whose refresh token
51
- goes to the OS keyring and never to a file; scaffold a project; build the local
52
- environment; validate your manifests against your deploy file; deploy, invoke,
53
- tail logs, roll back and tear down.
File without changes
File without changes
File without changes
File without changes