canyonos 0.2.3.dev1__tar.gz → 0.2.3.dev2__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 (103) hide show
  1. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/PKG-INFO +2 -2
  2. canyonos-0.2.3.dev2/canyonos/auth.py +130 -0
  3. canyonos-0.2.3.dev2/canyonos/chat.py +355 -0
  4. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/constants.py +5 -5
  5. canyonos-0.2.3.dev2/canyonos/context.py +139 -0
  6. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/dashboard.compose.yml +5 -11
  7. canyonos-0.2.3.dev2/canyonos/dashboard.py +89 -0
  8. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/dashboard_registration.py +20 -40
  9. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/dashboard_stack.py +24 -40
  10. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/deploy.py +73 -70
  11. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/deployment.yaml +6 -0
  12. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/init.py +32 -8
  13. canyonos-0.2.3.dev2/canyonos/internal_ca.py +217 -0
  14. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/kubernetes_target.py +81 -110
  15. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/os_support/__init__.py +4 -0
  16. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/os_support/_posix.py +23 -1
  17. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/os_support/_windows.py +22 -2
  18. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/quickstart.py +43 -58
  19. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/serve.py +14 -35
  20. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/helloworld/README.md +13 -17
  21. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/helloworld/helloworld/agents/workflow.py.tmpl +4 -4
  22. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/agents/workflow.py.tmpl +3 -4
  23. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/status.py +2 -1
  24. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/stop.py +17 -4
  25. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/test.py +52 -84
  26. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/ui.py +1 -1
  27. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos.egg-info/PKG-INFO +2 -2
  28. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos.egg-info/SOURCES.txt +4 -0
  29. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos.egg-info/requires.txt +1 -1
  30. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/cli.py +84 -142
  31. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/pyproject.toml +2 -2
  32. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/utils/help_screen.py +7 -8
  33. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/utils/tui.py +131 -1
  34. canyonos-0.2.3.dev1/canyonos/auth.py +0 -565
  35. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/README.md +0 -0
  36. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/__init__.py +0 -0
  37. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/aws_provision.py +0 -0
  38. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/clean.py +0 -0
  39. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/config.py +0 -0
  40. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/contact.py +0 -0
  41. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/convert.py +0 -0
  42. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/deployment.py +0 -0
  43. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/dev_machine.py +0 -0
  44. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/docker_cmd.py +0 -0
  45. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/doctor.py +0 -0
  46. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/env.py +0 -0
  47. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/feedback.py +0 -0
  48. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/forwards.py +0 -0
  49. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/gc.py +0 -0
  50. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/kubernetes_local.py +0 -0
  51. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/logs.py +0 -0
  52. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app.py +0 -0
  53. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/.env.example +0 -0
  54. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/.gitignore +0 -0
  55. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/agents/my_agent.py.tmpl +0 -0
  56. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/agents/workflow.py.tmpl +0 -0
  57. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/config/llms.yaml +0 -0
  58. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/config/policy.yaml +0 -0
  59. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/config/prompts.yaml +0 -0
  60. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/config/scaling.yaml +0 -0
  61. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/new_app_template/config/workflow_config.yaml +0 -0
  62. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/port_utils.py +0 -0
  63. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/ports.py +0 -0
  64. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/provision.py +0 -0
  65. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/resources.py +0 -0
  66. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/selection.py +0 -0
  67. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/helloworld/deployment.yaml +0 -0
  68. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/helloworld/helloworld/agents/hello_agent.py.tmpl +0 -0
  69. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/helloworld/helloworld/config/policy.yaml +0 -0
  70. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/helloworld/helloworld/config/test_query.txt +0 -0
  71. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/helloworld/helloworld/config/workflow_config.yaml +0 -0
  72. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/deployment.yaml +0 -0
  73. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/.env +0 -0
  74. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/.env.example +0 -0
  75. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/agents/advisor_agent.py.tmpl +0 -0
  76. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/agents/intent_agent.py.tmpl +0 -0
  77. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/agents/metrics_agent.py.tmpl +0 -0
  78. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/agents/price_agent.py.tmpl +0 -0
  79. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/agents/risk_agent.py.tmpl +0 -0
  80. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/config/llms.yaml +0 -0
  81. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/config/policy.yaml +0 -0
  82. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/config/prompts.yaml +0 -0
  83. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/config/scaling.yaml +0 -0
  84. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/config/test_query.txt +0 -0
  85. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/starters/portfolio/portfolio/config/workflow_config.yaml +0 -0
  86. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/sync.py +0 -0
  87. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/target.py +0 -0
  88. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/theme.py +0 -0
  89. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/upgrade.py +0 -0
  90. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/usage/__init__.py +0 -0
  91. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/usage/consent.py +0 -0
  92. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/usage/delivery.py +0 -0
  93. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/usage/outbox.py +0 -0
  94. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/usage/settings.py +0 -0
  95. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/validate.py +0 -0
  96. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos/verify.py +0 -0
  97. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos.egg-info/dependency_links.txt +0 -0
  98. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos.egg-info/entry_points.txt +0 -0
  99. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/canyonos.egg-info/top_level.txt +0 -0
  100. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/setup.cfg +0 -0
  101. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/tests/test_port_utils_twins.py +0 -0
  102. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/tests/test_ports.py +0 -0
  103. {canyonos-0.2.3.dev1 → canyonos-0.2.3.dev2}/utils/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: canyonos
3
- Version: 0.2.3.dev1
3
+ Version: 0.2.3.dev2
4
4
  Summary: Open-source platform for multi-agent apps: per-agent scaling, tracing and cost, in plain Python
5
5
  License-Expression: AGPL-3.0-only
6
6
  Project-URL: Homepage, https://canyonos.ai
@@ -15,8 +15,8 @@ Classifier: Programming Language :: Python :: 3
15
15
  Requires-Python: >=3.10
16
16
  Description-Content-Type: text/markdown
17
17
  Requires-Dist: boto3[crt]>=1.43.109
18
+ Requires-Dist: cryptography>=50.0.2
18
19
  Requires-Dist: pyfiglet
19
- Requires-Dist: pyjwt[crypto]>=2.10.1
20
20
  Requires-Dist: python-dotenv
21
21
  Requires-Dist: pyyaml
22
22
  Requires-Dist: rich
@@ -0,0 +1,130 @@
1
+ # SPDX-FileCopyrightText: 2026 Canyon Code, Inc.
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+
4
+ """This machine's API key: one string the user picks with `--api-key`, kept in
5
+ `~/.canyonos/api_key`, that opens every endpoint deployed here and the dashboard API.
6
+ The containers get only its SHA-256 hash. Without a key nothing is checked."""
7
+
8
+ import hashlib
9
+ import os
10
+ from pathlib import Path
11
+
12
+ from canyonos import ui
13
+ from canyonos.os_support import make_private_dir, write_private_file
14
+
15
+ # packages/core/canyonos_core/auth.py repeats this on purpose: the CLI cannot import
16
+ # canyonos_core, and both sides must agree on it.
17
+ API_KEY_HASH_ENV = "CANYONOS_API_KEY_HASH"
18
+ API_KEY_ENV = "CANYONOS_API_KEY"
19
+
20
+ # The header every printed `curl` sends; the key itself is never printed.
21
+ BEARER_PLACEHOLDER = '-H "Authorization: Bearer <your api key>"'
22
+
23
+ NO_KEY_WARNING = (
24
+ "No API key is set: the endpoint and the dashboard answer anyone who reaches "
25
+ "them. Set one with --api-key <key>."
26
+ )
27
+
28
+
29
+ def api_key_path() -> Path:
30
+ """Where this machine keeps its API key: `~/.canyonos/api_key`."""
31
+ return Path.home() / ".canyonos" / "api_key"
32
+
33
+
34
+ def _stored_api_key() -> str | None:
35
+ try:
36
+ key = api_key_path().read_text(encoding="utf-8").strip()
37
+ except FileNotFoundError:
38
+ return None
39
+ except OSError as error:
40
+ raise RuntimeError(
41
+ f"Could not read {api_key_path()}: {error.strerror or error}"
42
+ ) from error
43
+ return key or None
44
+
45
+
46
+ def machine_api_key() -> str | None:
47
+ """The API key commands here send and deploys set: `CANYONOS_API_KEY` when it is
48
+ set, else the stored key; None when there is neither."""
49
+ return os.environ.get(API_KEY_ENV, "").strip() or _stored_api_key()
50
+
51
+
52
+ def hash_api_key(key: str | None) -> str:
53
+ """The SHA-256 of `key` in lowercase hex, as the verifiers hold it; "" for no key."""
54
+ if not key:
55
+ return ""
56
+ return hashlib.sha256(key.encode("utf-8")).hexdigest()
57
+
58
+
59
+ def _save(key: str) -> None:
60
+ path = api_key_path()
61
+ replaced = _stored_api_key() is not None
62
+ try:
63
+ make_private_dir(path.parent)
64
+ write_private_file(path, key + "\n")
65
+ except OSError as error:
66
+ raise RuntimeError(
67
+ f"Could not write {path}: {error.strerror or error}"
68
+ ) from error
69
+ if not replaced:
70
+ ui.ok(f"Saved this machine's API key to {path}")
71
+ return
72
+ ui.ok("Replaced this machine's API key.")
73
+ ui.hint(
74
+ "The dashboard and this deployment use the new key; other running "
75
+ "deployments keep the old one until you redeploy them."
76
+ )
77
+
78
+
79
+ def _remove() -> None:
80
+ try:
81
+ api_key_path().unlink()
82
+ except FileNotFoundError:
83
+ return
84
+ except OSError as error:
85
+ raise RuntimeError(
86
+ f"Could not remove {api_key_path()}: {error.strerror or error}"
87
+ ) from error
88
+ ui.ok("Removed this machine's API key.")
89
+
90
+
91
+ def resolve_api_key(api_key: str | None, no_api_key: bool) -> str | None:
92
+ """Apply `--api-key` (save it, replacing any stored key) or `--no-api-key` (remove
93
+ the stored key) and return the key this deploy or serve sets, warning when there is
94
+ none; raise RuntimeError for an empty `--api-key`."""
95
+ if api_key is not None and not api_key.strip():
96
+ raise RuntimeError(
97
+ "--api-key needs a key. To run without one, pass --no-api-key instead"
98
+ )
99
+ if no_api_key:
100
+ _remove()
101
+ key = None
102
+ elif api_key is not None:
103
+ key = api_key.strip()
104
+ _save(key)
105
+ else:
106
+ key = machine_api_key()
107
+ if key is None:
108
+ ui.warn(NO_KEY_WARNING)
109
+ return key
110
+
111
+
112
+ def auth_header(key: str | None = None) -> dict[str, str]:
113
+ """The header that sends `key`, by default this machine's API key; none when there
114
+ is no key."""
115
+ key = key or machine_api_key()
116
+ if not key:
117
+ return {}
118
+ return {"Authorization": f"Bearer {key}"}
119
+
120
+
121
+ def curl_auth(keyed: bool) -> str:
122
+ """The placeholder header a printed `curl` shows when the deploy is `keyed`, else
123
+ ""."""
124
+ return f" {BEARER_PLACEHOLDER}" if keyed else ""
125
+
126
+
127
+ def gc_env(key: str | None) -> list[str]:
128
+ """The `docker run` options that hand the Global Controller the hash of `key`; an
129
+ empty hash when there is no key, so nothing is checked."""
130
+ return ["-e", f"{API_KEY_HASH_ENV}={hash_api_key(key)}"]
@@ -0,0 +1,355 @@
1
+ # SPDX-FileCopyrightText: 2026 Canyon Code, Inc.
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+
4
+ """
5
+ Logic for `canyonos chat`: call running workflows from one terminal session. Each
6
+ call is a box per argument of the workflow; `/add <curl command>` remembers a new
7
+ workflow and `/switch` picks or deletes one; run from a deployment's folder, its
8
+ running workflows are added first. The questions a workflow asks are answered in
9
+ boxes as they come, and `/recent` shows the result of one of the last requests again.
10
+ """
11
+
12
+ import json
13
+ import math
14
+ import shlex
15
+ import shutil
16
+ import sys
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ from pathlib import Path
21
+ from urllib.parse import urlsplit
22
+
23
+ from pyfiglet import figlet_format
24
+ from rich.console import Group
25
+ from rich.markdown import Markdown
26
+ from rich.panel import Panel
27
+ from rich.table import Table
28
+ from rich.text import Text
29
+
30
+ from canyonos import ui
31
+ from canyonos.auth import auth_header
32
+ from canyonos.gc import GCError, _error_detail, deployed_endpoint, existing_deploy
33
+ from canyonos.os_support import is_terminal, write_private_file
34
+ from canyonos.test import _parse_answer, _query_route, _Run
35
+ from canyonos.theme import GREEN, WHITE
36
+ from utils import tui
37
+
38
+ WORKFLOWS_FILE = Path.home() / ".canyonos" / "chat.json"
39
+ REQUESTS_FILE = Path.home() / ".canyonos" / "chat-requests.json"
40
+ RECENT_REQUESTS = 5
41
+ HINT = "tab next box · enter send · / commands"
42
+ COMMANDS = {
43
+ "/add": "add a workflow from its curl command",
44
+ "/switch": "pick another workflow, or delete one",
45
+ "/recent": "show the result of one of the last requests",
46
+ "/clear": "clear the screen",
47
+ "/quit": "leave the chat",
48
+ }
49
+
50
+
51
+ def _load_workflows():
52
+ """Return the remembered workflows, last used first: each its `url` and the type
53
+ name of each argument, by name."""
54
+ try:
55
+ return json.loads(WORKFLOWS_FILE.read_text(encoding="utf-8"))
56
+ except FileNotFoundError:
57
+ return []
58
+
59
+
60
+ def _from_curl(text):
61
+ """Read the workflow a pasted `curl ... <url> ... -d '<json>'` command calls: its
62
+ URL and the type name of each argument in its body, by name. Its headers are left
63
+ out: every call sends this machine's API key."""
64
+ # A curl split over lines ends each with a backslash.
65
+ words = shlex.split(text.replace("\\\n", " "))
66
+ url = next(word for word in words if word.startswith(("http://", "https://")))
67
+ body = json.loads(words[words.index("-d") + 1])
68
+ # A workflow's route is `/<project>/<agent>/<method>` and its body a JSON object.
69
+ if len(urlsplit(url).path.strip("/").split("/")) < 3 or not isinstance(body, dict):
70
+ raise ValueError("not a workflow's curl command")
71
+ return {
72
+ "url": url,
73
+ "arguments": {name: type(value).__name__ for name, value in body.items()},
74
+ }
75
+
76
+
77
+ def _deployed_workflows():
78
+ """Return the workflows of the deploy running from this folder, each argument read
79
+ as text, or none when no deploy runs here."""
80
+ existing = existing_deploy()
81
+ if existing is None:
82
+ return []
83
+ return [
84
+ {
85
+ "url": route["url"],
86
+ "arguments": {name: "str" for name in route["arguments"]},
87
+ }
88
+ for route in deployed_endpoint(existing["port"])["routes"]
89
+ ]
90
+
91
+
92
+ def _save(workflows):
93
+ """Remember `workflows`, last used first, for the next `canyonos chat`, readable only
94
+ by you."""
95
+ WORKFLOWS_FILE.parent.mkdir(parents=True, exist_ok=True)
96
+ write_private_file(WORKFLOWS_FILE, json.dumps(workflows, indent=2))
97
+
98
+
99
+ def _remember(workflows, new):
100
+ """Put the `new` workflows first in `workflows`, in place of any with the same URL,
101
+ and save them."""
102
+ urls = {workflow["url"] for workflow in new}
103
+ workflows[:] = new + [w for w in workflows if w["url"] not in urls]
104
+ _save(workflows)
105
+
106
+
107
+ def _answer_in_boxes(question, schema):
108
+ """Show the workflow's `question` as Markdown, ask for each key of its `schema`,
109
+ which maps it to its Python type name, in a box, and return the answers by key;
110
+ Ctrl-C or Ctrl-D stops waiting for the workflow instead."""
111
+ ui.say("The workflow asks:")
112
+ ui.panel(Markdown(question))
113
+ labels = [f"{key} ({kind})" for key, kind in schema.items()]
114
+ values = tui.input_form(labels, "answer the question above · enter send")
115
+ if values is None:
116
+ raise KeyboardInterrupt
117
+ return {
118
+ key: _parse_answer(value, kind)
119
+ for (key, kind), value in zip(schema.items(), values)
120
+ }
121
+
122
+
123
+ def _grid(rows, padding=(0, 2, 0, 0)):
124
+ """Return `rows` as a grid, each cell wrapping inside its own column; `padding` is
125
+ the space (top, right, bottom, left) between cells."""
126
+ grid = Table.grid(padding=padding, collapse_padding=False)
127
+ for row in rows:
128
+ grid.add_row(*row)
129
+ return grid
130
+
131
+
132
+ def _styled(value):
133
+ """Return how to show `value`, a workflow's result or part of one: text with line
134
+ breaks as Markdown, other text white, numbers cyan, and true, false, null and empty
135
+ lists yellow, like `jq`; a dict as dim keys beside their values; a list of dicts as
136
+ cards a blank line apart; any other list one item per line."""
137
+ if isinstance(value, str):
138
+ return Markdown(value) if "\n" in value else Text(value, WHITE)
139
+ if isinstance(value, bool) or value in (None, [], {}):
140
+ return Text(json.dumps(value), "yellow")
141
+ if isinstance(value, (int, float)):
142
+ return Text(str(value), "cyan")
143
+ if isinstance(value, dict):
144
+ return _grid((Text(key, "dim"), _styled(item)) for key, item in value.items())
145
+ if all(isinstance(item, dict) for item in value):
146
+ return _grid([(_card(record),) for record in value], (0, 0, 1, 0))
147
+ return _grid((Text("•", "dim"), _styled(item)) for item in value)
148
+
149
+
150
+ def _card(record):
151
+ """Return a dict as a card: its title, name or first one-line text in bold, then
152
+ its other keys."""
153
+ title = next(
154
+ (
155
+ key
156
+ for key in ("title", "name", *record)
157
+ if isinstance(record.get(key), str) and "\n" not in record[key]
158
+ ),
159
+ None,
160
+ )
161
+ heading = [Text(record[title], f"bold {WHITE}")] if title else []
162
+ return Group(*heading, _styled({k: v for k, v in record.items() if k != title}))
163
+
164
+
165
+ def _show(result):
166
+ """Show a workflow's result after a green ●: text as Markdown, anything else laid out
167
+ by `_styled`; a dict's text with line breaks and lists of dicts come last, each under
168
+ its key in bold green, using the full width and a blank line apart."""
169
+ shown = Markdown(result) if isinstance(result, str) else _styled(result)
170
+ if isinstance(result, dict):
171
+ wide = [
172
+ key
173
+ for key, value in result.items()
174
+ if (isinstance(value, str) and "\n" in value)
175
+ or (value and isinstance(value, list) and isinstance(value[0], dict))
176
+ ]
177
+ narrow = {k: v for k, v in result.items() if k not in wide}
178
+ blocks = [_styled(narrow)] if narrow else []
179
+ blocks += [Group(Text(k, f"bold {GREEN}"), _styled(result[k])) for k in wide]
180
+ shown = _grid([(block,) for block in blocks], (0, 0, 1, 0))
181
+ ui.blank()
182
+ ui.panel(_grid([(Text("●", GREEN), shown)], (0, 1, 0, 0)))
183
+
184
+
185
+ def _load_requests():
186
+ """Return the last requests sent from chat, by workflow URL, newest first: each its
187
+ `id`, when it was sent (`at`) and what was typed (`input`)."""
188
+ try:
189
+ return json.loads(REQUESTS_FILE.read_text(encoding="utf-8"))
190
+ except FileNotFoundError:
191
+ return {}
192
+
193
+
194
+ def _note_request(url, request_id, values):
195
+ """Remember request `request_id`, sent to the workflow at `url` with the typed
196
+ `values`, as its newest, keeping its last RECENT_REQUESTS."""
197
+ requests = _load_requests()
198
+ sent = {
199
+ "id": request_id,
200
+ "at": time.strftime("%Y-%m-%d %H:%M"),
201
+ "input": " · ".join(values),
202
+ }
203
+ requests[url] = [sent, *requests.get(url, [])][:RECENT_REQUESTS]
204
+ REQUESTS_FILE.parent.mkdir(parents=True, exist_ok=True)
205
+ REQUESTS_FILE.write_text(json.dumps(requests, indent=2), encoding="utf-8")
206
+
207
+
208
+ def _show_recent(workflow, sign):
209
+ """Ask which of the last requests sent to `workflow` to show, and show its result,
210
+ or its error or state, as the endpoint has it now, asked with the header `sign`
211
+ returns."""
212
+ recent = _load_requests().get(workflow["url"], [])
213
+ if not recent:
214
+ ui.say("No requests saved yet; chat saves the ones it sends from now on.")
215
+ return
216
+ options = [(r, f"{r['at']} {r['input'][:60]}".replace("\n", " ")) for r in recent]
217
+ picked = tui.select_menu(options, "Show the result of")
218
+ if picked is None:
219
+ return
220
+ parts = urlsplit(workflow["url"])
221
+ url = f"{parts.scheme}://{parts.netloc}/status/{picked['id']}"
222
+ try:
223
+ request = urllib.request.Request(url, headers=sign())
224
+ with urllib.request.urlopen(request, timeout=10) as response:
225
+ status = json.loads(response.read())
226
+ except RuntimeError as e:
227
+ ui.fail(str(e))
228
+ return
229
+ except urllib.error.HTTPError as e:
230
+ ui.fail(f"Could not read request {picked['id']}: {_error_detail(e)}")
231
+ return
232
+ except OSError as e:
233
+ ui.fail(f"Could not reach the workflow at {url}: {e}")
234
+ return
235
+ ui.hint(f"{picked['at']} {picked['input']}")
236
+ if status["status"] == "done":
237
+ _show(status["result"])
238
+ elif status["status"] == "error":
239
+ ui.fail(status["error"])
240
+ else:
241
+ ui.say(f"Request {picked['id']} is {status['status'].replace('_', ' ')}.")
242
+
243
+
244
+ def _call(workflow, values, sign):
245
+ """Call `workflow` with `values`, typed in its argument boxes in order, each request
246
+ with the header `sign` returns, answer the questions it asks, and show its result
247
+ or error, then its request ID and how long it took."""
248
+ arguments = workflow["arguments"].items()
249
+ body = {
250
+ name: _parse_answer(value, kind)
251
+ for (name, kind), value in zip(arguments, values)
252
+ }
253
+ parts = urlsplit(workflow["url"])
254
+ base = f"{parts.scheme}://{parts.netloc}"
255
+ run = _Run(None)
256
+ started = time.monotonic()
257
+ try:
258
+ result = _query_route(
259
+ # No time limit: Ctrl-C stops waiting instead.
260
+ run,
261
+ base,
262
+ workflow["url"],
263
+ body,
264
+ math.inf,
265
+ sign,
266
+ _answer_in_boxes,
267
+ )
268
+ except RuntimeError as e:
269
+ ui.fail(str(e))
270
+ except KeyboardInterrupt:
271
+ ui.fail("Stopped waiting; the workflow may still be running.")
272
+ else:
273
+ _show(result)
274
+ if run.request_id:
275
+ ui.hint(f"request {run.request_id} · {time.monotonic() - started:.1f}s")
276
+ _note_request(workflow["url"], run.request_id, values)
277
+
278
+
279
+ def _open(workflow):
280
+ """Clear the terminal and show the banner, then the project, agent, method and URL
281
+ of the workflow the boxes call."""
282
+ ui.console.clear()
283
+ size = shutil.get_terminal_size()
284
+ boxes = (len(workflow["arguments"]) or 1) if workflow else 1
285
+ # The banner is 75 columns by 6 rows; it shows only with room left for the boxes.
286
+ if size.columns > 75 and size.lines >= 20 + 3 * boxes:
287
+ ui.gradient(figlet_format("CANYON OS", font="ansi_shadow", width=200))
288
+ about = "No workflow yet: type /add <its curl command>"
289
+ if workflow:
290
+ url = workflow["url"]
291
+ project, agent, method = urlsplit(url).path.strip("/").split("/")[-3:]
292
+ about = f"project {project}\nworkflow {agent}.{method}\nendpoint {url}"
293
+ ui.panel(Panel(Text(about, WHITE), border_style=GREEN, expand=False))
294
+
295
+
296
+ def run_chat():
297
+ """Run `canyonos chat`, starting on the newest remembered workflow, until /quit,
298
+ Ctrl-C or Ctrl-D in its boxes, each call sending this machine's API key; return
299
+ the exit code."""
300
+ if not is_terminal(sys.stdin):
301
+ ui.fail("`canyonos chat` needs a terminal to type in.")
302
+ return 1
303
+ workflows = _load_workflows()
304
+ error = None
305
+ try:
306
+ if deployed := _deployed_workflows():
307
+ _remember(workflows, deployed)
308
+ except GCError as e:
309
+ error = f"Could not read the workflows of the deploy running here: {e}"
310
+ workflow = workflows[0] if workflows else None
311
+ _open(workflow)
312
+ # What was sent to each workflow this session, by URL, for Ctrl-P and Ctrl-N.
313
+ history = {}
314
+ try:
315
+ while True:
316
+ arguments = workflow["arguments"] if workflow else {}
317
+ # A workflow without arguments still needs a box to type commands in.
318
+ labels = [f"{n} ({kind})" for n, kind in arguments.items()] or ["command"]
319
+ sent = history.setdefault(workflow["url"], []) if workflow else []
320
+ values = tui.input_form(labels, HINT, error, COMMANDS, sent)
321
+ error = None
322
+ if values is None or values[0] == "/quit":
323
+ return 0
324
+ if values[0].startswith("/add "):
325
+ try:
326
+ workflow = _from_curl(values[0][len("/add ") :])
327
+ except (StopIteration, ValueError):
328
+ error = "That is not a workflow's curl command."
329
+ continue
330
+ _remember(workflows, [workflow])
331
+ _open(workflow)
332
+ elif values[0] == "/switch":
333
+ options = [(w, w["url"]) for w in workflows]
334
+ picked = tui.select_menu(options, "Switch to", deletable=True)
335
+ if isinstance(picked, tuple):
336
+ workflows.remove(picked[1])
337
+ _save(workflows)
338
+ if picked[1] == workflow:
339
+ workflow = workflows[0] if workflows else None
340
+ elif picked:
341
+ workflow = picked
342
+ _remember(workflows, [workflow])
343
+ _open(workflow)
344
+ elif values[0] == "/clear":
345
+ _open(workflow)
346
+ elif workflow is None:
347
+ error = "Add a workflow first: /add <its curl command>"
348
+ elif values[0] == "/recent":
349
+ _show_recent(workflow, auth_header)
350
+ else:
351
+ sent.append(values)
352
+ _call(workflow, values, auth_header)
353
+ finally:
354
+ # Give the whole screen back to the shell, with its prompt under the boxes.
355
+ sys.stderr.write(f"\x1b[r\x1b[{shutil.get_terminal_size().lines};1H\n")
@@ -159,16 +159,16 @@ def endpoint_api_port(config_path):
159
159
  return port if isinstance(port, int) and not isinstance(port, bool) else None
160
160
 
161
161
 
162
- # What an endpoint answers before the Global Controller has published its trusted
163
- # keys (`auth.not_ready`): up, but refusing every request.
162
+ # What an endpoint answers before the Global Controller has published the API key
163
+ # hash (`auth.not_ready`): up, but refusing every request.
164
164
  NOT_READY_STATUS = 503
165
165
 
166
166
 
167
167
  def endpoint_answers_at(url, timeout):
168
168
  """True when the endpoint at `url` is up and taking requests: any HTTP answer to
169
- the probe, which sends no token, counts (a 401 is the endpoint verifying, and the
170
- 404 of its unknown request id comes with verification off), except the 503 it
171
- answers while it waits for its trusted keys."""
169
+ the probe, which sends no key, counts (a 401 is the endpoint checking its API key,
170
+ and the 404 of its unknown request id comes with no key set), except the 503 it
171
+ answers while it waits for the API key hash."""
172
172
  try:
173
173
  urllib.request.urlopen(
174
174
  f"{url.rstrip('/')}/status/canyonos-test-probe", timeout=timeout
@@ -0,0 +1,139 @@
1
+ # SPDX-FileCopyrightText: 2026 Canyon Code, Inc.
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+
4
+ """
5
+ Logic for `canyonos list` and `canyonos select-context`: the deployments on this
6
+ machine, and the one picked to act on from a folder that is no deployment's.
7
+
8
+ The pick is the deployment's name in `~/.canyonos/context.json`. `stop`, `clean`,
9
+ `status`, `logs`, `test` and `sync` use it when they are given no deployment and run
10
+ outside a deployment folder; a name or the current folder always wins.
11
+ """
12
+
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+
17
+ from canyonos import selection, ui
18
+ from canyonos.constants import deployment_config_path
19
+ from canyonos.gc import deploy_status
20
+
21
+ CONTEXT_FILE = Path.home() / ".canyonos" / "context.json"
22
+ PICK_AGAIN = (
23
+ "See the deployments with `canyonos list`, then pick one with "
24
+ "`canyonos select-context <deployment>`, or `canyonos select-context --clear`."
25
+ )
26
+
27
+
28
+ def _selected_name():
29
+ """The name of the selected deployment, or None when none is selected."""
30
+ try:
31
+ return json.loads(CONTEXT_FILE.read_text(encoding="utf-8"))["deployment"]
32
+ except FileNotFoundError:
33
+ return None
34
+ except (OSError, ValueError, KeyError, TypeError) as e:
35
+ raise RuntimeError(
36
+ f"Could not read the selected deployment in {CONTEXT_FILE}: {e}. "
37
+ + PICK_AGAIN
38
+ ) from None
39
+
40
+
41
+ def selected_deployment():
42
+ """The selected deployment, or None when none is selected or the command runs in a
43
+ deployment folder, which wins; raise RuntimeError saying how to pick another when
44
+ the selected one is no longer recorded on this machine."""
45
+ if os.path.isfile(deployment_config_path()):
46
+ return None
47
+ name = _selected_name()
48
+ if name is None:
49
+ return None
50
+ for recorded in selection.recorded_deployments():
51
+ if recorded.name == name:
52
+ return recorded
53
+ raise RuntimeError(
54
+ f"The selected deployment `{name}` is no longer deployed on this machine. "
55
+ + PICK_AGAIN
56
+ )
57
+
58
+
59
+ def enter_selected_folder(selected):
60
+ """Run the rest of the command from the folder of `selected`, as if it were typed
61
+ there; raise RuntimeError when the folder is gone or was never recorded."""
62
+ if not selected.folder or not os.path.isfile(
63
+ os.path.join(selected.folder, deployment_config_path())
64
+ ):
65
+ raise RuntimeError(
66
+ f"The folder of the selected deployment `{selected.name}` "
67
+ f"({selected.folder or 'not recorded'}) no longer holds its "
68
+ f"{deployment_config_path()}. " + PICK_AGAIN
69
+ )
70
+ os.chdir(selected.folder)
71
+
72
+
73
+ def _describe(recorded, selected_name):
74
+ """One line of `canyonos list`: its name, ID, whether its deploy runs, and marks
75
+ for a deploy with no API key and for the selected deployment."""
76
+ running = (deploy_status(recorded.state["port"]) or {}).get("running", False)
77
+ marks = ["running" if running else "not running"]
78
+ if recorded.state.get("auth_disabled"):
79
+ marks.append("(unauthenticated)")
80
+ if recorded.name == selected_name:
81
+ marks.append("(selected)")
82
+ return [recorded.name, recorded.id or "no ID recorded", " ".join(marks)]
83
+
84
+
85
+ def _show(recorded, selected_name):
86
+ """Show one line per deployment of `recorded`, or how to deploy one when there is
87
+ none."""
88
+ if not recorded:
89
+ ui.say(
90
+ "No deployment on this machine. Deploy one with "
91
+ "`canyonos deploy <project folder> --folder <deployment>`."
92
+ )
93
+ return
94
+ rows = [_describe(deployment, selected_name) for deployment in recorded]
95
+ widths = [max(len(row[column]) for row in rows) for column in range(2)]
96
+ for name, deployment_id, marks in rows:
97
+ ui.say(f"* {name:<{widths[0]}} {deployment_id:<{widths[1]}} {marks}")
98
+
99
+
100
+ def run_list():
101
+ """Run `canyonos list`: show every deployment recorded on this machine, one line
102
+ each, and warn when the selected one is gone."""
103
+ recorded = selection.recorded_deployments()
104
+ selected_name = _selected_name()
105
+ _show(recorded, selected_name)
106
+ if selected_name and selected_name not in {d.name for d in recorded}:
107
+ ui.warn(
108
+ f"The selected deployment `{selected_name}` is no longer deployed on this "
109
+ "machine. " + PICK_AGAIN
110
+ )
111
+ return True
112
+
113
+
114
+ def run_select_context(ref, clear=False):
115
+ """Run `canyonos select-context`: remember the recorded deployment `ref` names, by
116
+ name, folder name or ID (or its start), as `stop` takes it, or forget the pick
117
+ with `clear`. Returns False when `ref` names no deployment, or several."""
118
+ if clear:
119
+ CONTEXT_FILE.unlink(missing_ok=True)
120
+ ui.ok("No deployment is selected.")
121
+ return True
122
+ if ref is None:
123
+ ui.fail("Name the deployment to select, or pass --clear. " + PICK_AGAIN)
124
+ return False
125
+ choice = selection.choose("select-context", [ref], selection.recorded_deployments())
126
+ if not choice.ok:
127
+ ui.hint("See the deployments with `canyonos list`.")
128
+ return False
129
+ picked = choice.deployments[0]
130
+ CONTEXT_FILE.parent.mkdir(parents=True, exist_ok=True)
131
+ CONTEXT_FILE.write_text(
132
+ json.dumps({"deployment": picked.name}, indent=2), encoding="utf-8"
133
+ )
134
+ ui.ok(f"Selected {picked.name}")
135
+ ui.hint(
136
+ "stop, clean, status, logs, test and sync act on it from any folder that is "
137
+ "no deployment's; a name or a deployment folder still wins."
138
+ )
139
+ return True