canyonos 0.2.3.dev3__tar.gz → 0.2.3.dev5__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.dev3 → canyonos-0.2.3.dev5}/PKG-INFO +1 -1
  2. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/api.py +42 -31
  3. canyonos-0.2.3.dev5/canyonos/auth.py +237 -0
  4. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/aws_provision.py +1 -4
  5. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/chat.py +30 -8
  6. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/clean.py +34 -24
  7. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/constants.py +2 -2
  8. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/context.py +22 -35
  9. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/convert.py +9 -1
  10. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/curl.py +7 -6
  11. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/dashboard.compose.yml +4 -7
  12. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/dashboard.py +13 -12
  13. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/dashboard_registration.py +17 -6
  14. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/dashboard_stack.py +53 -33
  15. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/deploy.py +41 -21
  16. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/deployment.py +44 -29
  17. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/doctor.py +2 -2
  18. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/init.py +3 -3
  19. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/internal_ca.py +1 -1
  20. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/kubernetes_local.py +6 -11
  21. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/kubernetes_target.py +30 -11
  22. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/logs.py +10 -1
  23. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app.py +1 -4
  24. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/ports.py +1 -1
  25. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/quickstart.py +12 -9
  26. canyonos-0.2.3.dev5/canyonos/records.py +413 -0
  27. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/sdk/models.py +60 -1
  28. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/selection.py +22 -23
  29. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/serve.py +28 -50
  30. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/helloworld/README.md +12 -9
  31. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/status.py +4 -2
  32. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/stop.py +22 -9
  33. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/sync.py +57 -15
  34. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/test.py +10 -11
  35. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos.egg-info/PKG-INFO +1 -1
  36. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos.egg-info/SOURCES.txt +1 -0
  37. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/cli.py +73 -52
  38. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/pyproject.toml +1 -1
  39. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/utils/help_screen.py +6 -5
  40. canyonos-0.2.3.dev3/canyonos/auth.py +0 -196
  41. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/README.md +0 -0
  42. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/__init__.py +0 -0
  43. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/config.py +0 -0
  44. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/contact.py +0 -0
  45. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/dev_machine.py +0 -0
  46. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/docker_cmd.py +0 -0
  47. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/env.py +0 -0
  48. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/feedback.py +0 -0
  49. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/forwards.py +0 -0
  50. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/.env.example +0 -0
  51. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/.gitignore +0 -0
  52. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/agents/my_agent.py.tmpl +0 -0
  53. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/agents/workflow.py.tmpl +0 -0
  54. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/config/llms.yaml +0 -0
  55. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/config/policy.yaml +0 -0
  56. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/config/prompts.yaml +0 -0
  57. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/config/scaling.yaml +0 -0
  58. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/new_app_template/config/workflow_config.yaml +0 -0
  59. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/os_support/__init__.py +0 -0
  60. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/os_support/_posix.py +0 -0
  61. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/os_support/_windows.py +0 -0
  62. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/port_utils.py +0 -0
  63. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/provision.py +0 -0
  64. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/resources.py +0 -0
  65. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/sdk/__init__.py +0 -0
  66. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/helloworld/helloworld/agents/hello_agent.py.tmpl +0 -0
  67. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/helloworld/helloworld/agents/workflow.py.tmpl +0 -0
  68. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/helloworld/helloworld/config/policy.yaml +0 -0
  69. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/helloworld/helloworld/config/test_query.txt +0 -0
  70. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/helloworld/helloworld/config/workflow_config.yaml +0 -0
  71. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/helloworld/workflow_group.yaml +0 -0
  72. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/.env +0 -0
  73. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/.env.example +0 -0
  74. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/agents/advisor_agent.py.tmpl +0 -0
  75. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/agents/intent_agent.py.tmpl +0 -0
  76. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/agents/metrics_agent.py.tmpl +0 -0
  77. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/agents/price_agent.py.tmpl +0 -0
  78. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/agents/risk_agent.py.tmpl +0 -0
  79. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/agents/workflow.py.tmpl +0 -0
  80. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/config/llms.yaml +0 -0
  81. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/config/policy.yaml +0 -0
  82. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/config/prompts.yaml +0 -0
  83. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/config/scaling.yaml +0 -0
  84. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/config/test_query.txt +0 -0
  85. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/portfolio/config/workflow_config.yaml +0 -0
  86. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/starters/portfolio/workflow_group.yaml +0 -0
  87. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/theme.py +0 -0
  88. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/ui.py +0 -0
  89. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/upgrade.py +0 -0
  90. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/usage/__init__.py +0 -0
  91. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/usage/consent.py +0 -0
  92. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/usage/delivery.py +0 -0
  93. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/usage/outbox.py +0 -0
  94. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/usage/settings.py +0 -0
  95. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/validate.py +0 -0
  96. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos/workflow_group.yaml +0 -0
  97. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos.egg-info/dependency_links.txt +0 -0
  98. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos.egg-info/entry_points.txt +0 -0
  99. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos.egg-info/requires.txt +0 -0
  100. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/canyonos.egg-info/top_level.txt +0 -0
  101. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/setup.cfg +0 -0
  102. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/utils/__init__.py +0 -0
  103. {canyonos-0.2.3.dev3 → canyonos-0.2.3.dev5}/utils/tui.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: canyonos
3
- Version: 0.2.3.dev3
3
+ Version: 0.2.3.dev5
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
@@ -6,7 +6,8 @@ The CanyonOS API's `/v1/workflow-groups` routes, so the commands that deploy, st
6
6
  read a workflow group don't each restate the same routes, payloads and failure modes.
7
7
 
8
8
  On Docker the API is the local stack's (`dashboard_stack`), on 127.0.0.1 at its host
9
- port, and every call sends this machine's control key; the API runs each workflow
9
+ port, and every call sends this machine's deploy key, which opens every workflow
10
+ group's routes here and is the only key that creates one; the API runs each workflow
10
11
  group's Global Controller container through Docker. On Kubernetes it is the cluster's,
11
12
  the one the operator's chart installs, reached through a port-forward with the user's
12
13
  kubectl login (`kubernetes_target.kubernetes_state`); it runs each workflow group as a
@@ -22,7 +23,7 @@ import urllib.parse
22
23
  import urllib.request
23
24
 
24
25
  from canyonos import deployment, env
25
- from canyonos.auth import control_header, control_key_path
26
+ from canyonos.auth import api_key_path, bearer_header
26
27
  from canyonos.init import load_state
27
28
 
28
29
  REQUEST_TIMEOUT_SECONDS = 60
@@ -46,19 +47,18 @@ ERROR_PREFIX = "workflow_groups."
46
47
  UNKNOWN_WORKFLOW_GROUP = "unknown_workflow_group"
47
48
  # What an older chart's API answers on Kubernetes: no route there (a release before
48
49
  # the /v1 routes), or the /v1 routes of an API that drives only Docker, without Docker
49
- # or the control key.
50
+ # or the control key those releases asked for.
50
51
  OLDER_CHART_ERRORS = {
51
52
  404: (None, "not_found"),
52
53
  503: ("docker.disabled",),
53
54
  401: ("auth.control_key_unset",),
54
55
  }
55
56
 
56
- # What the API answers a /v1 call whose control key it was not started with, or when
57
- # it was started with none.
58
- CONTROL_KEY_REFUSALS = (
57
+ # What the API answers a /v1/workflow-groups call that sends neither its deploy key nor
58
+ # the workflow group's own key.
59
+ API_KEY_REFUSALS = (
59
60
  "auth.missing_key",
60
61
  "auth.invalid_key",
61
- "auth.control_key_unset",
62
62
  )
63
63
  DATABASE_UNAVAILABLE = "database.unavailable"
64
64
 
@@ -116,20 +116,28 @@ def _on_kubernetes(state):
116
116
  return bool(state and "api_url" in state)
117
117
 
118
118
 
119
+ def docker_api_headers():
120
+ """The headers every call to this machine's CanyonOS API sends: its deploy key."""
121
+ # Imported here: the stack's module reads ports this one has no need of.
122
+ from canyonos.dashboard_stack import deploy_key
123
+
124
+ return bearer_header(deploy_key())
125
+
126
+
119
127
  def _connection(state):
120
128
  """The base URL and headers a call about `state`'s workflow group goes to: the
121
- cluster's API on Kubernetes, else this machine's with the control key; this
129
+ cluster's API on Kubernetes, else this machine's with its deploy key; this
122
130
  machine's when `state` is None."""
123
131
  if _on_kubernetes(state):
124
132
  return state["api_url"], state["api_headers"]
125
- return docker_api_url(), control_header()
133
+ return docker_api_url(), docker_api_headers()
126
134
 
127
135
 
128
136
  def error_detail(body, status):
129
137
  """The error object of an answer's `body`, raw bytes, as `{error, code, findings,
130
138
  warnings}`, `error` its message and `code` its code without the prefix, from the
131
139
  CanyonOS API's `{error: code, message}`; each check that is not ok as `error` for
132
- `/readyz`'s answer, and the raw body as `error` when it is neither."""
140
+ `/v1/readyz`'s answer, and the raw body as `error` when it is neither."""
133
141
  text = body.decode(errors="replace").strip()
134
142
  try:
135
143
  parsed = json.loads(text)
@@ -171,11 +179,13 @@ def _next_step(state, code):
171
179
  its message; "" when there is nothing to add."""
172
180
  if _on_kubernetes(state):
173
181
  return ""
174
- if code in CONTROL_KEY_REFUSALS:
175
- # deploy, sync and stop restart such an API themselves (`serve.ensure_api`).
182
+ if code in API_KEY_REFUSALS:
183
+ # deploy, sync and stop restart an API on another deploy key themselves
184
+ # (`serve.ensure_api`).
176
185
  return (
177
- " Run `canyonos serve` to restart the CanyonOS API with this machine's "
178
- f"control key, in {control_key_path()}."
186
+ f" This workflow group's API key is in {api_key_path()}; "
187
+ "`canyonos deploy --api-key <key>` sets it. `canyonos serve` restarts the "
188
+ "CanyonOS API with this machine's deploy key."
179
189
  )
180
190
  if code == DATABASE_UNAVAILABLE:
181
191
  return _database_hint(state)
@@ -326,17 +336,17 @@ def list_workflow_groups(state=None):
326
336
 
327
337
 
328
338
  def _wait_until_ready(state=None):
329
- """Wait up to READY_TIMEOUT_SECONDS for the API to answer `/readyz`: it listens
330
- before its database is ready, and its `/v1` routes answer 503 until then. An older
331
- API without `/readyz` is not waited for. Raises ApiError with its last answer when
332
- it is still not ready: its database, the one thing `/readyz` waits on, is not."""
339
+ """Wait up to READY_TIMEOUT_SECONDS for the API to answer `/v1/readyz`: it listens
340
+ before its database is ready, and its `/v1/workflow-groups` routes answer 503 until then. An older
341
+ API without `/v1/readyz` is not waited for. Raises ApiError with its last answer when
342
+ it is still not ready: its database, the one thing `/v1/readyz` waits on, is not."""
333
343
  deadline = time.monotonic() + READY_TIMEOUT_SECONDS
334
344
  while True:
335
345
  try:
336
346
  _open(
337
347
  state,
338
348
  "GET",
339
- "/readyz",
349
+ "/v1/readyz",
340
350
  "Readiness check",
341
351
  timeout=STATUS_TIMEOUT_SECONDS,
342
352
  ).close()
@@ -345,7 +355,7 @@ def _wait_until_ready(state=None):
345
355
  if e.status == 404:
346
356
  return
347
357
  if time.monotonic() >= deadline:
348
- # A 503 is `/readyz` waiting on the database.
358
+ # A 503 is `/v1/readyz` waiting on the database.
349
359
  answer = str(e)
350
360
  if e.status == 503:
351
361
  answer = f"{answer.rstrip('.')}.{_database_hint(state)}"
@@ -381,9 +391,10 @@ def probe(state=None):
381
391
  def put_workflow_group(state, config, env_text, workflows=None, api_key_hash=None):
382
392
  """Upload the workflow group's name, the text `config` of its `workflow_group.yaml`
383
393
  and the text `env_text` of the `.env` beside it (None when there is none); with
384
- `workflows`, the API removes the uploaded workflows not among them; with
385
- `api_key_hash`, the SHA-256 of the deploy's API key ("" for none), it keeps that as
386
- the deploy's key. Return the new generation and the upload's warnings. Raises
394
+ `workflows`, a list of workflow_ids, the API removes the uploaded workflows not
395
+ among them; with
396
+ `api_key_hash`, the SHA-256 of this workflow group's API key ("" for none), it keeps
397
+ that as its key, which only this workflow group's routes and endpoint take. Return the new generation and the upload's warnings. Raises
387
398
  ApiError on failure."""
388
399
  body = {
389
400
  "name": deployment.folder_name(),
@@ -395,15 +406,15 @@ def put_workflow_group(state, config, env_text, workflows=None, api_key_hash=Non
395
406
  return _request(state, "PUT", _group_path(state), "Sync", body)
396
407
 
397
408
 
398
- def put_workflow(state, name, archive):
399
- """Make `archive`, an open gzip tar file of workflow `name`'s folder, that workflow's
409
+ def put_workflow(state, workflow_id, archive):
410
+ """Make `archive`, an open gzip tar file of the workflow's folder, that workflow's
400
411
  files in the Global Controller's workspace and return the new generation and the
401
412
  upload's warnings. Raises ApiError on failure, with the `findings` `canyonos
402
413
  validate` would print when the workflow breaks the contract."""
403
414
  return _request(
404
415
  state,
405
416
  "PUT",
406
- _group_path(state, f"/workflows/{_quoted(name)}"),
417
+ _group_path(state, f"/workflows/{_quoted(workflow_id)}"),
407
418
  "Sync",
408
419
  archive=archive,
409
420
  )
@@ -548,15 +559,15 @@ def controller_log(state, tail="all", follow=False):
548
559
  raise ApiError(f"Could not read the Global Controller log: {e}") from None
549
560
 
550
561
 
551
- def deployed_logs(state, name, tail):
552
- """Return the last `tail` lines of each running replica of agent `name`, or of the
553
- one replica whose ID is `name`, keyed by replica ID; raise ApiError when the API
554
- can't say, naming the agents when `name` is neither."""
562
+ def deployed_logs(state, agent_id, tail):
563
+ """Return the last `tail` lines of each running replica of the agent whose ID is
564
+ `agent_id`, or of the one replica whose ID it is, keyed by replica ID; raise ApiError
565
+ when the API can't say, naming the agents when it is neither."""
555
566
  query = urllib.parse.urlencode({"tail": tail})
556
567
  return _request(
557
568
  state,
558
569
  "GET",
559
- _group_path(state, f"/logs/agents/{_quoted(name)}?{query}"),
570
+ _group_path(state, f"/logs/agents/{_quoted(agent_id)}?{query}"),
560
571
  "Read logs",
561
572
  timeout=LOGS_REQUEST_TIMEOUT_SECONDS,
562
573
  )["logs"]
@@ -0,0 +1,237 @@
1
+ # SPDX-FileCopyrightText: 2026 Canyon Code, Inc.
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+
4
+ """Each workflow group's API key: one string the user picks with `canyonos deploy
5
+ --api-key`, kept in the workflow group's record (`~/.canyonos/workflows/<workflow
6
+ group>/api_key`), that opens that workflow group's endpoint and its routes on the
7
+ CanyonOS API, never another workflow group's. The containers get only its SHA-256 hash.
8
+ A workflow group without a key checks nothing. `CANYONOS_API_KEY` stands in for the
9
+ record's key for one command."""
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+
16
+ from canyonos import deployment, records, ui
17
+ from canyonos.os_support import make_private_dir, write_private_file
18
+
19
+ # packages/core/canyonos_core/auth.py repeats this on purpose: the CLI cannot import
20
+ # canyonos_core, and both sides must agree on it.
21
+ API_KEY_HASH_ENV = "CANYONOS_API_KEY_HASH"
22
+ API_KEY_ENV = "CANYONOS_API_KEY"
23
+ API_KEY_FILE = "api_key"
24
+
25
+ # The header every printed `curl` sends; the key itself is never printed.
26
+ BEARER_PLACEHOLDER = '-H "Authorization: Bearer <your api key>"'
27
+
28
+ NO_KEY_WARNING = (
29
+ "This workflow group has no API key: its endpoint and its dashboard routes answer "
30
+ "anyone who reaches them. Set one with --api-key <key>."
31
+ )
32
+ KEY_SET = "This workflow group now uses an API key for secure connections."
33
+ ONLY_THIS_GROUP = (
34
+ "Only this workflow group changes: other workflow groups keep their own keys."
35
+ )
36
+
37
+
38
+ def api_key_path(name: str | None = None) -> Path:
39
+ """Where the record of workflow group `name`, by default the one this command acts
40
+ on, keeps its API key."""
41
+ return Path(deployment.state_dir(name)) / API_KEY_FILE
42
+
43
+
44
+ def _machine_key_path() -> Path:
45
+ """Where a CLI before per-workflow-group keys kept one key for every workflow group
46
+ on this machine; read once, by `_adopt_machine_key`."""
47
+ return Path.home() / ".canyonos" / API_KEY_FILE
48
+
49
+
50
+ def _read_key(path: Path) -> str | None:
51
+ """The key in the file at `path`, or None when there is no file or it is empty;
52
+ raise RuntimeError when it can't be read."""
53
+ try:
54
+ key = path.read_text(encoding="utf-8").strip()
55
+ except FileNotFoundError:
56
+ return None
57
+ except OSError as error:
58
+ raise RuntimeError(
59
+ f"Could not read {path}: {error.strerror or error}"
60
+ ) from error
61
+ return key or None
62
+
63
+
64
+ def _write_key(path: Path, key: str) -> None:
65
+ try:
66
+ make_private_dir(path.parent)
67
+ write_private_file(path, key + "\n")
68
+ except OSError as error:
69
+ raise RuntimeError(
70
+ f"Could not write {path}: {error.strerror or error}"
71
+ ) from error
72
+
73
+
74
+ def _deployed_without_key(name: str) -> bool:
75
+ """Whether the Docker deploy of workflow group `name` that still runs was made with
76
+ no API key, as its `state.json` records it. False when there is no `state.json`,
77
+ which a stop removes and a Kubernetes deploy never writes, or it can't be read:
78
+ such a workflow group takes the machine key, and its next deploy sets it."""
79
+ try:
80
+ with open(deployment.state_path(name), encoding="utf-8") as f:
81
+ state = json.load(f)
82
+ except (OSError, ValueError):
83
+ return False
84
+ return isinstance(state, dict) and state.get("auth_disabled") is True
85
+
86
+
87
+ def _adopt_machine_key(deploying: str) -> None:
88
+ """Upgrade, once, as a deploy starts, from the CLI that kept one key for the whole
89
+ machine in `~/.canyonos/api_key`: every workflow group recorded here without a key
90
+ of its own, and `deploying`, the one the deploy is about to set up, take that key,
91
+ which their deploys were made with, then the file is removed, as no record needs it
92
+ anymore. A Docker workflow group still deployed with no key stays without one."""
93
+ legacy = _machine_key_path()
94
+ key = _read_key(legacy)
95
+ if key is None and not legacy.exists():
96
+ return
97
+ if key is not None:
98
+ for name in {*records.names(), deploying}:
99
+ path = api_key_path(name)
100
+ if not path.exists() and not _deployed_without_key(name):
101
+ _write_key(path, key)
102
+ try:
103
+ legacy.unlink(missing_ok=True)
104
+ except OSError as error:
105
+ raise RuntimeError(
106
+ f"Could not remove {legacy}: {error.strerror or error}"
107
+ ) from error
108
+ if key is not None:
109
+ ui.note(
110
+ f"Each workflow group now keeps its own API key: {legacy} moved into the "
111
+ "record of each workflow group here, in its api_key file."
112
+ )
113
+
114
+
115
+ def group_api_key(name: str | None = None) -> str | None:
116
+ """The API key of workflow group `name`, by default the one this command acts on:
117
+ `CANYONOS_API_KEY` when it is set, else the one its record keeps; None when there
118
+ is none. Reads only: a deploy is what moves an older CLI's machine key into the
119
+ records (`resolve_api_key`)."""
120
+ env_key = os.environ.get(API_KEY_ENV, "").strip()
121
+ if env_key:
122
+ return env_key
123
+ return _read_key(api_key_path(name))
124
+
125
+
126
+ def workflow_group_api_key(workflow_group_id: str) -> str | None:
127
+ """The API key of the workflow group whose ID is `workflow_group_id`, as
128
+ `group_api_key` finds it; None when no record has that ID, so a request about a
129
+ workflow group this machine does not know carries no other workflow group's key."""
130
+ name = records.resolve(workflow_group_id, missing_ok=True)
131
+ if name is None:
132
+ return None
133
+ return group_api_key(name)
134
+
135
+
136
+ def hash_api_key(key: str | None) -> str:
137
+ """The SHA-256 of `key` in lowercase hex, as the verifiers hold it; "" for no key."""
138
+ if not key:
139
+ return ""
140
+ return hashlib.sha256(key.encode("utf-8")).hexdigest()
141
+
142
+
143
+ def _save(key: str) -> None:
144
+ """Keep `key` in the record of the workflow group this deploy acts on, saying so in
145
+ the terminal, and that only this workflow group changes when the key replaces one
146
+ it ran with: another key, or none on a workflow group deployed before."""
147
+ path = api_key_path()
148
+ previous = _read_key(path)
149
+ if previous is None:
150
+ replaces_a_deploys_key = os.path.isfile(deployment.state_path())
151
+ else:
152
+ replaces_a_deploys_key = previous != key
153
+ _write_key(path, key)
154
+ ui.ok(KEY_SET)
155
+ if replaces_a_deploys_key:
156
+ ui.hint(ONLY_THIS_GROUP)
157
+
158
+
159
+ def _remove() -> None:
160
+ path = api_key_path()
161
+ try:
162
+ path.unlink()
163
+ except FileNotFoundError:
164
+ return
165
+ except OSError as error:
166
+ raise RuntimeError(
167
+ f"Could not remove {path}: {error.strerror or error}"
168
+ ) from error
169
+ ui.ok("Removed this workflow group's API key.")
170
+ ui.hint(ONLY_THIS_GROUP)
171
+
172
+
173
+ def check_api_key_options(api_key: str | None, no_api_key: bool) -> None:
174
+ """Raise RuntimeError for an empty `--api-key`, or when CANYONOS_API_KEY holds
175
+ another key than `--api-key` or `--no-api-key` set, which later commands would send
176
+ instead; a deploy checks this before it changes anything."""
177
+ if api_key is not None and not api_key.strip():
178
+ raise RuntimeError(
179
+ "--api-key needs a key. To run without one, pass --no-api-key instead"
180
+ )
181
+ env_key = os.environ.get(API_KEY_ENV, "").strip()
182
+ if env_key and no_api_key:
183
+ raise RuntimeError(
184
+ f"{API_KEY_ENV} holds a key, which later commands would send to this "
185
+ f"workflow group. Unset {API_KEY_ENV}, then run this again"
186
+ )
187
+ if env_key and api_key is not None and env_key != api_key.strip():
188
+ raise RuntimeError(
189
+ f"{API_KEY_ENV} holds another key, which later commands would send "
190
+ f"instead of this one. Unset {API_KEY_ENV} or set it to the new key, "
191
+ "then run this again"
192
+ )
193
+
194
+
195
+ def resolve_api_key(api_key: str | None, no_api_key: bool) -> str | None:
196
+ """Apply `--api-key` (save it in the record of the workflow group this deploy acts
197
+ on, replacing its key) or `--no-api-key` (remove its key) and return the key this
198
+ deploy sets, warning when there is none; raise RuntimeError as
199
+ `check_api_key_options` does."""
200
+ check_api_key_options(api_key, no_api_key)
201
+ _adopt_machine_key(deployment.deployment_name())
202
+ if no_api_key:
203
+ _remove()
204
+ key = None
205
+ elif api_key is not None:
206
+ key = api_key.strip()
207
+ _save(key)
208
+ else:
209
+ key = group_api_key()
210
+ if key is None:
211
+ ui.warn(NO_KEY_WARNING)
212
+ return key
213
+
214
+
215
+ def bearer_header(key: str | None) -> dict[str, str]:
216
+ """The header that sends `key`; none when there is no key."""
217
+ if not key:
218
+ return {}
219
+ return {"Authorization": f"Bearer {key}"}
220
+
221
+
222
+ def auth_header() -> dict[str, str]:
223
+ """The header that sends the API key of the workflow group this command acts on;
224
+ none when it has no key."""
225
+ return bearer_header(group_api_key())
226
+
227
+
228
+ def curl_auth(keyed: bool) -> str:
229
+ """The placeholder header a printed `curl` shows when the deploy is `keyed`, else
230
+ ""."""
231
+ return f" {BEARER_PLACEHOLDER}" if keyed else ""
232
+
233
+
234
+ def gc_env(key: str | None) -> list[str]:
235
+ """The `docker run` options that hand the Global Controller the hash of `key`; an
236
+ empty hash when there is no key, so nothing is checked."""
237
+ return ["-e", f"{API_KEY_HASH_ENV}={hash_api_key(key)}"]
@@ -1326,10 +1326,7 @@ class _AwsProvision:
1326
1326
  ui.command(f"scp -i {key} -r <workflow folder> {SSH_USER}@{address}:~/")
1327
1327
  ui.say("Then sign in, wait for the install, and deploy:")
1328
1328
  ui.command(f"ssh -i {key} {SSH_USER}@{address}")
1329
- ui.command(
1330
- "cloud-init status --wait && "
1331
- "canyonos deploy <workflow folder> --workflow-group group"
1332
- )
1329
+ ui.command("cloud-init status --wait && canyonos deploy <workflow folder>")
1333
1330
  ui.blank()
1334
1331
  ui.hint(
1335
1332
  "To run agents on EC2, set `provider: ec2-assign` and give each agent a "
@@ -27,8 +27,8 @@ from rich.panel import Panel
27
27
  from rich.table import Table
28
28
  from rich.text import Text
29
29
 
30
- from canyonos import ui
31
- from canyonos.auth import auth_header
30
+ from canyonos import deployment, records, ui
31
+ from canyonos.auth import bearer_header, group_api_key
32
32
  from canyonos.deploy import is_workflow_id
33
33
  from canyonos.api import ApiError, deployed_endpoint, existing_deploy
34
34
  from canyonos.os_support import is_terminal, write_private_file
@@ -61,7 +61,7 @@ def _load_workflows():
61
61
  def _from_curl(text):
62
62
  """Read the workflow a pasted `curl ... <url> ... -d '<json>'` command calls: its
63
63
  URL and the type name of each argument in its body, by name. Its headers are left
64
- out: every call sends this machine's API key."""
64
+ out: every call sends the API key of the workflow group it belongs to."""
65
65
  # A curl split over lines ends each with a backslash.
66
66
  words = shlex.split(text.replace("\\\n", " "))
67
67
  url = next(word for word in words if word.startswith(("http://", "https://")))
@@ -80,7 +80,7 @@ def _from_curl(text):
80
80
 
81
81
  def _deployed_workflows():
82
82
  """Return the workflows of the deploy running from this folder, each argument read
83
- as text, or none when no deploy runs here."""
83
+ as text and its workflow group named, or none when no deploy runs here."""
84
84
  existing = existing_deploy()
85
85
  if existing is None:
86
86
  return []
@@ -89,11 +89,33 @@ def _deployed_workflows():
89
89
  "url": route["url"],
90
90
  "name": f"{route['workflow']}: {route['agent']}.{route['method']}",
91
91
  "arguments": {name: "str" for name in route["arguments"]},
92
+ "workflow_group": deployment.deployment_name(),
92
93
  }
93
94
  for route in deployed_endpoint(existing)["routes"]
94
95
  ]
95
96
 
96
97
 
98
+ def _workflow_group_at(url):
99
+ """The workflow group recorded here whose endpoint was last on `url`'s port, for a
100
+ workflow added with /add, or None."""
101
+ port = urlsplit(url).port
102
+ for name in records.names():
103
+ try:
104
+ with open(deployment.state_path(name), encoding="utf-8") as f:
105
+ if json.load(f).get("api_port") == port:
106
+ return name
107
+ except (OSError, ValueError, AttributeError):
108
+ continue
109
+ return None
110
+
111
+
112
+ def _signer(workflow):
113
+ """What gives the header each call to `workflow` sends: the API key of the workflow
114
+ group it belongs to, none when it belongs to none recorded here."""
115
+ name = workflow.get("workflow_group") or _workflow_group_at(workflow["url"])
116
+ return lambda: bearer_header(group_api_key(name) if name else None)
117
+
118
+
97
119
  def _save(workflows):
98
120
  """Remember `workflows`, last used first, for the next `canyonos chat`, readable only
99
121
  by you."""
@@ -301,8 +323,8 @@ def _open(workflow):
301
323
 
302
324
  def run_chat():
303
325
  """Run `canyonos chat`, starting on the newest remembered workflow, until /quit,
304
- Ctrl-C or Ctrl-D in its boxes, each call sending this machine's API key; return
305
- the exit code."""
326
+ Ctrl-C or Ctrl-D in its boxes, each call sending the API key of the workflow's
327
+ workflow group; return the exit code."""
306
328
  if not is_terminal(sys.stdin):
307
329
  ui.fail("`canyonos chat` needs a terminal to type in.")
308
330
  return 1
@@ -352,10 +374,10 @@ def run_chat():
352
374
  elif workflow is None:
353
375
  error = "Add a workflow first: /add <its curl command>"
354
376
  elif values[0] == "/recent":
355
- _show_recent(workflow, auth_header)
377
+ _show_recent(workflow, _signer(workflow))
356
378
  else:
357
379
  sent.append(values)
358
- _call(workflow, values, auth_header)
380
+ _call(workflow, values, _signer(workflow))
359
381
  finally:
360
382
  # Give the whole screen back to the shell, with its prompt under the boxes.
361
383
  sys.stderr.write(f"\x1b[r\x1b[{shutil.get_terminal_size().lines};1H\n")
@@ -2,15 +2,16 @@
2
2
  # SPDX-License-Identifier: AGPL-3.0-only
3
3
 
4
4
  """Logic for canyonos clean: stop each workflow group it is given or picks (see
5
- selection.py) if it is deployed, then remove its `.canyon`, CanyonOS skills, records
6
- under `~/.canyonos/deployments/` and agent images; with --all, everything CanyonOS put
5
+ selection.py) if it is deployed, then remove its record under `~/.canyonos/workflows/`,
6
+ its settings included, and agent images, and the `.canyon` and CanyonOS skills of the
7
+ folder it runs from; with --all, everything CanyonOS put
7
8
  on this machine."""
8
9
 
9
10
  import os
10
11
  import shutil
11
12
 
12
- from canyonos import convert, deployment, selection, ui
13
- from canyonos.constants import CANYON_DIR, deployment_config_path
13
+ from canyonos import convert, deployment, records, selection, ui
14
+ from canyonos.constants import CANYON_DIR
14
15
  from canyonos.stop import (
15
16
  agent_images,
16
17
  confirm_clean_all,
@@ -23,15 +24,13 @@ from canyonos.stop import (
23
24
 
24
25
  # What `canyonos clean` removes from a workflow's folder: its port and the skill
25
26
  # `canyonos convert` installs there for each coding agent, leaving global installs.
26
- _LOCAL_FILES = (
27
- CANYON_DIR,
28
- *(spec["skill_dirs"]["local"] for spec in convert.AGENTS.values()),
29
- )
27
+ _SKILL_DIRS = tuple(spec["skill_dirs"]["local"] for spec in convert.AGENTS.values())
28
+ _LOCAL_FILES = (CANYON_DIR, *_SKILL_DIRS)
30
29
 
31
30
 
32
- def _local_files(folder):
33
- """The paths under `folder` that `canyonos clean` removes and that exist."""
34
- paths = (os.path.join(os.path.abspath(folder), path) for path in _LOCAL_FILES)
31
+ def _local_files(folder, names=_LOCAL_FILES):
32
+ """The paths of `names` under `folder` that exist."""
33
+ paths = (os.path.join(os.path.abspath(folder), path) for path in names)
35
34
  return [path for path in paths if os.path.lexists(path)]
36
35
 
37
36
 
@@ -44,10 +43,10 @@ def _remove_emptied_parents(path, root):
44
43
  parent = os.path.dirname(parent)
45
44
 
46
45
 
47
- def _remove_local_files(folder):
48
- """Remove the local files of the workflow in `folder`; False when one stayed."""
46
+ def _remove_local_files(folder, names=_LOCAL_FILES):
47
+ """Remove the `names` of the workflow in `folder`; False when one stayed."""
49
48
  removed_all = True
50
- for path in _local_files(folder):
49
+ for path in _local_files(folder, names):
51
50
  try:
52
51
  if os.path.islink(path):
53
52
  os.unlink(path)
@@ -63,9 +62,13 @@ def _remove_local_files(folder):
63
62
 
64
63
 
65
64
  def _remove_records(name):
66
- """Delete the folder under `~/.canyonos/deployments/` that holds workflow group `name`'s
67
- records, its Redis password among them; False when it stayed."""
65
+ """Delete workflow group `name`'s record under `~/.canyonos/workflows/`, its
66
+ `workflow_group.yaml` and its Redis password among them; False when it stayed."""
68
67
  records = deployment.state_dir(name)
68
+ if os.path.realpath(os.getcwd()) == os.path.realpath(records):
69
+ # Run from it (see records.enter): what runs after, `docker compose` among
70
+ # it, needs a folder that is still there.
71
+ os.chdir(deployment.deployments_dir())
69
72
  try:
70
73
  shutil.rmtree(records)
71
74
  except FileNotFoundError:
@@ -78,18 +81,26 @@ def _remove_records(name):
78
81
 
79
82
 
80
83
  def _clean_deployment(target, stop):
81
- """Stop `target` with `stop` if it is deployed, then remove its local files, its
82
- records under `~/.canyonos` and its agents' images; False when any of it stayed."""
84
+ """Stop `target` with `stop` if it is deployed, then remove the skills `convert`
85
+ installed in its workflow folders (or, for a folder no workflow group records, its
86
+ `.canyon` too), its record under `~/.canyonos` and its agents' images; False when
87
+ any of it stayed."""
83
88
  # Docker won't remove the image of a container that still runs.
84
89
  if target.state is not None and stop(target.state, target.name):
85
90
  ui.fail(f"{target.name} could not be stopped, so nothing of it was cleaned.")
86
91
  return False
87
- removed = True
88
- if target.folder is not None and os.path.isdir(target.folder):
89
- removed = _remove_local_files(target.folder)
92
+ if target.name in records.names():
93
+ # A recorded workflow group's workflows keep their `.canyon`.
94
+ folders = [
95
+ path for path in records.workflow_paths(target.name) if os.path.isdir(path)
96
+ ]
97
+ removed = all([_remove_local_files(folder, _SKILL_DIRS) for folder in folders])
90
98
  else:
99
+ folders = [target.folder] if os.path.isdir(target.folder or "") else []
100
+ removed = all([_remove_local_files(folder) for folder in folders])
101
+ if not folders:
91
102
  ui.hint(
92
- f"{target.name}'s folder is not on this machine any more, so only its "
103
+ f"{target.name}'s folders are not on this machine any more, so only its "
93
104
  "deploy, records and images were removed."
94
105
  )
95
106
  records_removed = _remove_records(target.name)
@@ -104,8 +115,7 @@ def _candidates():
104
115
  clean and isn't deployed."""
105
116
  deployed = selection.recorded_deployments()
106
117
  here = selection.current_deployment()
107
- holds_files = _local_files(here.folder) or os.path.isfile(deployment_config_path())
108
- if holds_files and here.name not in {p.name for p in deployed}:
118
+ if _local_files(here.folder) and here.name not in {p.name for p in deployed}:
109
119
  return [*deployed, here]
110
120
  return deployed
111
121
 
@@ -76,8 +76,8 @@ def existing_config_path():
76
76
  config_path = deployment_config_path()
77
77
  if not os.path.isfile(config_path):
78
78
  raise RuntimeError(
79
- f"No {config_path} here. Run `canyonos deploy <workflow folder>...` from "
80
- "the folder that holds the workflow group."
79
+ "No workflow group here. Deploy one with `canyonos deploy <workflow "
80
+ "folder>...`, or pick one with `canyonos select-context <workflow group>`."
81
81
  )
82
82
  return config_path
83
83