caisson-tools 0.1.0__py3-none-any.whl
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.
- caisson_tools/__init__.py +1 -0
- caisson_tools/_revision.txt +1 -0
- caisson_tools/agentctl-commands.json +1 -0
- caisson_tools/allowlist_syntax.py +44 -0
- caisson_tools/browser.py +36 -0
- caisson_tools/common.py +174 -0
- caisson_tools/context.py +36 -0
- caisson_tools/environment.py +92 -0
- caisson_tools/management.py +113 -0
- caisson_tools/manifest.py +41 -0
- caisson_tools/ops.py +839 -0
- caisson_tools/podman.py +325 -0
- caisson_tools/remote.py +158 -0
- caisson_tools/secrets.py +100 -0
- caisson_tools/serve.py +160 -0
- caisson_tools/terminal.py +194 -0
- caisson_tools/transport.py +370 -0
- caisson_tools/user.py +789 -0
- caisson_tools/version.py +37 -0
- caisson_tools-0.1.0.dist-info/METADATA +69 -0
- caisson_tools-0.1.0.dist-info/RECORD +25 -0
- caisson_tools-0.1.0.dist-info/WHEEL +4 -0
- caisson_tools-0.1.0.dist-info/entry_points.txt +3 -0
- caisson_tools-0.1.0.dist-info/licenses/LICENSE +202 -0
- caisson_tools-0.1.0.dist-info/licenses/NOTICE +6 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Caisson's laptop-side tools. No cloud SDK is imported by the user CLI."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
91db73d61592abc5771aeeb6236556862164373b
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"commands":[["version","show the Git revision of the workstation runtime"],["up","recreate VM/proxy; preserve private guest disk"],["switch-agent opencode|claude","switch agent; build Claude on demand, preserve disk"],["down","stop VM/proxy; preserve private guest disk"],["disk-grow GIB","grow stopped guest disk to total size in GiB"],["status","show VM and proxy state (JSON)"],["shell","interactive shell in /home/agent"],["agent [--directory PATH]","open the selected OpenCode or Claude terminal UI"],["exec [--root] -- COMMAND [ARG...]","run a guest command"],["pair","Show pairing link and QR code."],["logs [--follow|--no-follow]","recent VM console (optionally follow)"],["proxy-logs [--follow|--no-follow]","recent proxy traffic (optionally follow)"],["allowlist","manage outbound allowlists"],["creds","Manage proxy credentials."],["tool","manage optional agent tools"],["package","manage agent Nix packages from the workstation"],["copy-to LOCAL AGENT_PATH","copy local files into the agent"],["copy-from AGENT_PATH LOCAL","copy agent files to the local machine"]],"allowlist":[["show [LIST]","show domains and method grants"],["add URL|DOMAIN [...] [--methods METHODS]","grant GET/HEAD by default; METHODS is GET,POST or all"],["rm DOMAIN [...]","remove standalone domains"],["lists","show fleet and tool-owned lists and enabled state"],["enable LIST [...]","enable fleet or tool-owned lists"],["disable LIST [...]","disable fleet or tool-owned lists"],["reset","clear all grants, including fleet defaults"]],"groups":{"creds":{"help":"Manage proxy credentials.","epilog":"","arguments":[],"options":[],"commands":{"list":{"help":"show configured credential presets","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"configure":{"help":"securely enter a key for a credential preset","epilog":"","arguments":[{"name":"preset","help":"credential preset name","nargs":null,"required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"add":{"help":"add a custom credential rule","epilog":"","arguments":[],"options":[{"name":"url","help":"HTTPS URL; rule covers its entire hostname","nargs":null,"required":true,"default":null,"choices":null,"flags":["--url"],"flag":false,"multiple":false},{"name":"header","help":"","nargs":null,"required":false,"default":"Authorization","choices":null,"flags":["--header"],"flag":false,"multiple":false},{"name":"placeholder","help":"exact complete guest header value","nargs":null,"required":false,"default":null,"choices":null,"flags":["--placeholder"],"flag":false,"multiple":false},{"name":"inject","help":"inject if absent; Authorization uses Bearer KEY","nargs":0,"required":false,"default":false,"choices":null,"flags":["--inject"],"flag":true,"multiple":false},{"name":"remove_header","help":"header to remove when injecting (repeatable)","nargs":null,"required":false,"default":[],"choices":null,"flags":["--remove-header"],"flag":false,"multiple":true},{"name":"value","help":"header value; raw key for Bearer injection","nargs":null,"required":false,"default":null,"choices":null,"flags":["--value"],"flag":false,"multiple":false},{"name":"env","help":"reference an environment variable in host agentd","nargs":null,"required":false,"default":null,"choices":null,"flags":["--env"],"flag":false,"multiple":false},{"name":"prompt","help":"securely prompt for a literal value","nargs":0,"required":false,"default":false,"choices":null,"flags":["--prompt"],"flag":true,"multiple":false}],"commands":{},"exclusive":[{"required":true,"names":["placeholder","inject"]},{"required":true,"names":["value","env","prompt"]}]},"rm":{"help":"remove a preset or custom credential rule","epilog":"","arguments":[{"name":"preset","help":"","nargs":"?","required":false,"default":null,"choices":null}],"options":[{"name":"url","help":"HTTPS URL; rule covers its entire hostname","nargs":null,"required":false,"default":null,"choices":null,"flags":["--url"],"flag":false,"multiple":false},{"name":"header","help":"","nargs":null,"required":false,"default":"Authorization","choices":null,"flags":["--header"],"flag":false,"multiple":false},{"name":"placeholder","help":"exact complete guest header value","nargs":null,"required":false,"default":null,"choices":null,"flags":["--placeholder"],"flag":false,"multiple":false},{"name":"inject","help":"inject if absent; Authorization uses Bearer KEY","nargs":0,"required":false,"default":false,"choices":null,"flags":["--inject"],"flag":true,"multiple":false}],"commands":{},"exclusive":[{"required":false,"names":["placeholder","inject"]}]}},"exclusive":[]},"allowlist":{"help":"manage outbound allowlists","epilog":"","arguments":[],"options":[],"commands":{"show":{"help":"show domains and method grants","epilog":"","arguments":[{"name":"list","help":"fleet or tool-owned list (omit for current policy)","nargs":"?","required":false,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"add":{"help":"grant GET/HEAD by default; METHODS is GET,POST or all","epilog":"","arguments":[{"name":"targets","help":"domain or HTTPS URL (whole hostname)","nargs":"+","required":true,"default":null,"choices":null}],"options":[{"name":"methods","help":"comma-separated methods, or all","nargs":null,"required":false,"default":"GET,HEAD","choices":null,"flags":["--methods"],"flag":false,"multiple":false}],"commands":{},"exclusive":[]},"rm":{"help":"remove standalone domains","epilog":"","arguments":[{"name":"targets","help":"domain or HTTPS URL (whole hostname)","nargs":"+","required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"lists":{"help":"show fleet and tool-owned lists and enabled state","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"enable":{"help":"enable fleet or tool-owned lists","epilog":"","arguments":[{"name":"lists","help":"fleet or tool-owned list names","nargs":"+","required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"disable":{"help":"disable fleet or tool-owned lists","epilog":"","arguments":[{"name":"lists","help":"fleet or tool-owned list names","nargs":"+","required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"reset":{"help":"clear all grants, including fleet defaults","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]}},"exclusive":[]},"tool":{"help":"manage optional agent tools","epilog":"","arguments":[],"options":[],"commands":{"list":{"help":"show available tools and enabled state","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"install":{"help":"build on host and add to guest profile (no activation)","epilog":"","arguments":[{"name":"name","help":"tool name","nargs":null,"required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"enable":{"help":"install, allow runtime endpoints, and connect MCP","epilog":"","arguments":[{"name":"name","help":"tool name","nargs":null,"required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"disable":{"help":"revoke runtime allowlist and disable MCP; keep package","epilog":"","arguments":[{"name":"name","help":"tool name","nargs":null,"required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]}},"exclusive":[]},"package":{"help":"manage agent Nix packages from the workstation","epilog":"","arguments":[],"options":[],"commands":{"install":{"help":"build packages on host and add to guest profile offline","epilog":"","arguments":[{"name":"names","help":"attribute names from the host image's pinned nixpkgs","nargs":"+","required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"remove":{"help":"remove named guest profile entries (does not reclaim space)","epilog":"","arguments":[{"name":"names","help":"installed profile names (see: agentctl exec -- nix profile list)","nargs":"+","required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"gc":{"help":"wipe guest profile rollback history and collect unreachable guest store paths","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]}},"exclusive":[]}},"runtime":{"version":{"help":"show the Git revision of the workstation runtime","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"up":{"help":"recreate VM/proxy; preserve private guest disk","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"switch-agent":{"help":"switch agent; build Claude on demand, preserve disk","epilog":"","arguments":[{"name":"agent","help":"agent runtime to switch to; private disk is preserved","nargs":null,"required":true,"default":null,"choices":["opencode","claude"]}],"options":[],"commands":{},"exclusive":[]},"down":{"help":"stop VM/proxy; preserve private guest disk","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"disk-grow":{"help":"grow stopped guest disk to total size in GiB","epilog":"","arguments":[{"name":"gib","help":"total guest disk size in GiB (1\u20131000); guest must be stopped","nargs":null,"required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"status":{"help":"show VM and proxy state (JSON)","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"shell":{"help":"interactive shell in /home/agent","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"agent":{"help":"open the selected OpenCode or Claude terminal UI","epilog":"","arguments":[],"options":[{"name":"directory","help":"guest working directory (relative paths start in /home/agent)","nargs":null,"required":false,"default":"/home/agent","choices":null,"flags":["--directory"],"flag":false,"multiple":false}],"commands":{},"exclusive":[]},"exec":{"help":"run a guest command","epilog":"","arguments":[{"name":"command","help":"guest command and arguments; put -- before the command","nargs":"...","required":false,"default":null,"choices":null}],"options":[{"name":"root","help":"run as guest root, never host root","nargs":0,"required":false,"default":false,"choices":null,"flags":["--root"],"flag":true,"multiple":false}],"commands":{},"exclusive":[],"passthrough":true},"pair":{"help":"Show pairing link and QR code.","epilog":"","arguments":[],"options":[],"commands":{},"exclusive":[]},"logs":{"help":"recent VM console (optionally follow)","epilog":"Default: print recent log entries and exit. Use -f/--follow to stream.","arguments":[],"options":[{"name":"follow","help":"keep streaming new log entries","nargs":0,"required":false,"default":false,"choices":null,"flags":["-f","--follow"],"flag":true,"multiple":false},{"name":"no_follow","help":"print recent log entries and exit","nargs":0,"required":false,"default":false,"choices":null,"flags":["--no-follow"],"flag":true,"multiple":false}],"commands":{},"exclusive":[{"required":false,"names":["follow","no_follow"]}]},"proxy-logs":{"help":"recent proxy traffic (optionally follow)","epilog":"Default: print recent log entries and exit. Use -f/--follow to stream.","arguments":[],"options":[{"name":"follow","help":"keep streaming new log entries","nargs":0,"required":false,"default":false,"choices":null,"flags":["-f","--follow"],"flag":true,"multiple":false},{"name":"no_follow","help":"print recent log entries and exit","nargs":0,"required":false,"default":false,"choices":null,"flags":["--no-follow"],"flag":true,"multiple":false}],"commands":{},"exclusive":[{"required":false,"names":["follow","no_follow"]}]},"copy-to":{"help":"copy local files into the agent","epilog":"agentctl runs on the workstation: LOCAL is a workstation path. Copies directories recursively.","arguments":[{"name":"local","help":"source path on the machine running this command","nargs":null,"required":true,"default":null,"choices":null},{"name":"agent_path","help":"destination path in the agent; relative paths start in /home/agent","nargs":null,"required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]},"copy-from":{"help":"copy agent files to the local machine","epilog":"agentctl runs on the workstation: LOCAL is a workstation path. Copies directories recursively.","arguments":[{"name":"agent_path","help":"source path in the agent; relative paths start in /home/agent","nargs":null,"required":true,"default":null,"choices":null},{"name":"local","help":"destination path on the machine running this command","nargs":null,"required":true,"default":null,"choices":null}],"options":[],"commands":{},"exclusive":[]}},"catalogs":{"preset":["tavily"],"lists":["tavily"],"tools":["chunkhound","tavily"]}}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Dependency-free domain and method parsing for workspace config and proxy policy."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
DEFAULT_METHODS = frozenset(("GET", "HEAD"))
|
|
7
|
+
WILDCARD_METHODS = frozenset(("*",))
|
|
8
|
+
DOMAIN_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")
|
|
9
|
+
METHOD_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]{0,31}")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def normalize_domain(domain):
|
|
13
|
+
if not isinstance(domain, str):
|
|
14
|
+
raise ValueError("invalid allowlist domain: " + repr(domain))
|
|
15
|
+
domain = domain.lower()
|
|
16
|
+
value = domain.removeprefix(".")
|
|
17
|
+
if len(value) > 253 or "." not in value or any(
|
|
18
|
+
not DOMAIN_LABEL.fullmatch(label) for label in value.split(".")
|
|
19
|
+
):
|
|
20
|
+
raise ValueError("invalid allowlist domain: " + domain)
|
|
21
|
+
return domain
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def method_names(values, *, allow_wildcard=False):
|
|
25
|
+
"""Parse individual method tokens; only the text policy accepts the `all` alias."""
|
|
26
|
+
if allow_wildcard and values and all(value == "*" for value in values):
|
|
27
|
+
return WILDCARD_METHODS
|
|
28
|
+
if not values or any(not isinstance(value, str) or value.upper() == "ALL" or not METHOD_NAME.fullmatch(value)
|
|
29
|
+
for value in values):
|
|
30
|
+
raise ValueError("methods must be comma-separated HTTP methods, 'all', or '*'")
|
|
31
|
+
grants = frozenset(value.upper() for value in values)
|
|
32
|
+
if "CONNECT" in grants:
|
|
33
|
+
raise ValueError("CONNECT is proxy transport, not an allowed request method")
|
|
34
|
+
return grants
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def methods(value):
|
|
38
|
+
"""Parse the textual policy and CLI form, including comma separators and aliases."""
|
|
39
|
+
if not isinstance(value, str):
|
|
40
|
+
raise ValueError("methods must be a string")
|
|
41
|
+
value = value.upper()
|
|
42
|
+
if value in {"*", "ALL"}:
|
|
43
|
+
return WILDCARD_METHODS
|
|
44
|
+
return method_names([part.strip() for part in value.split(",")])
|
caisson_tools/browser.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Shared laptop browser launching with a printable fallback."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from urllib.parse import urlsplit
|
|
5
|
+
import webbrowser
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def show_url(text, *, no_open_browser=False, extra_ports=()):
|
|
11
|
+
"""Print a URL, then try the platform's default browser."""
|
|
12
|
+
url = text.strip()
|
|
13
|
+
try:
|
|
14
|
+
parsed = urlsplit(url)
|
|
15
|
+
valid = (
|
|
16
|
+
parsed.scheme == "https"
|
|
17
|
+
and parsed.hostname
|
|
18
|
+
and re.fullmatch(r"[A-Za-z0-9.-]+", parsed.hostname)
|
|
19
|
+
and not parsed.username
|
|
20
|
+
and not parsed.password
|
|
21
|
+
and not any(c.isspace() or not c.isprintable() for c in url)
|
|
22
|
+
and (parsed.port in (None, 443) or parsed.port in extra_ports)
|
|
23
|
+
)
|
|
24
|
+
except ValueError:
|
|
25
|
+
valid = False
|
|
26
|
+
if not valid:
|
|
27
|
+
raise click.ClickException("No valid HTTPS browser URL was returned")
|
|
28
|
+
click.echo(url)
|
|
29
|
+
if no_open_browser:
|
|
30
|
+
return
|
|
31
|
+
try:
|
|
32
|
+
opened = webbrowser.open(url)
|
|
33
|
+
except (OSError, webbrowser.Error):
|
|
34
|
+
opened = False
|
|
35
|
+
if not opened:
|
|
36
|
+
click.echo("Could not open a browser. Open the URL above manually.", err=True)
|
caisson_tools/common.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Shared terminal UI; Click remains the single command dispatcher."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
|
|
12
|
+
import click
|
|
13
|
+
from rich.console import Console
|
|
14
|
+
from click.shell_completion import CompletionItem
|
|
15
|
+
|
|
16
|
+
console = Console(stderr=True, markup=False)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class UXGroup(click.Group):
|
|
20
|
+
"""Readable task-oriented help without a second command framework."""
|
|
21
|
+
|
|
22
|
+
help_sections = {}
|
|
23
|
+
hidden_aliases = set()
|
|
24
|
+
group_class = type
|
|
25
|
+
help_on_empty = True
|
|
26
|
+
|
|
27
|
+
def __init__(self, *args, **kwargs):
|
|
28
|
+
kwargs.setdefault("invoke_without_command", True)
|
|
29
|
+
kwargs.setdefault("no_args_is_help", False)
|
|
30
|
+
super().__init__(*args, **kwargs)
|
|
31
|
+
|
|
32
|
+
def invoke(self, ctx):
|
|
33
|
+
result = super().invoke(ctx)
|
|
34
|
+
if self.help_on_empty and ctx.invoked_subcommand is None:
|
|
35
|
+
click.echo(ctx.get_help())
|
|
36
|
+
return result
|
|
37
|
+
|
|
38
|
+
def shell_complete(self, ctx, incomplete):
|
|
39
|
+
return [
|
|
40
|
+
item
|
|
41
|
+
for item in super().shell_complete(ctx, incomplete)
|
|
42
|
+
if item.value not in self.hidden_aliases
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
def format_commands(self, ctx, formatter):
|
|
46
|
+
remaining = {
|
|
47
|
+
name: cmd
|
|
48
|
+
for name, cmd in self.commands.items()
|
|
49
|
+
if not cmd.hidden and name not in self.hidden_aliases
|
|
50
|
+
}
|
|
51
|
+
for title, names in self.help_sections.items():
|
|
52
|
+
width = max((len(name) for name in names), default=0)
|
|
53
|
+
limit = max(30, formatter.width - width - 6)
|
|
54
|
+
rows = [
|
|
55
|
+
(name, remaining.pop(name).get_short_help_str(limit))
|
|
56
|
+
for name in names
|
|
57
|
+
if name in remaining
|
|
58
|
+
]
|
|
59
|
+
if rows:
|
|
60
|
+
with formatter.section(title):
|
|
61
|
+
formatter.write_dl(rows)
|
|
62
|
+
if remaining:
|
|
63
|
+
with formatter.section("Commands"):
|
|
64
|
+
formatter.write_dl(
|
|
65
|
+
[(name, cmd.get_short_help_str()) for name, cmd in sorted(remaining.items())]
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def workspace_completions(ctx, param, incomplete):
|
|
70
|
+
return [
|
|
71
|
+
CompletionItem(name, help="Workspace")
|
|
72
|
+
for name in (ctx.obj or {}).get("workspaces", [])
|
|
73
|
+
if name.startswith(incomplete)
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def local_paths(incomplete, directories=False):
|
|
78
|
+
"""Return full replacement tokens, leaving quoting to the REPL adapter."""
|
|
79
|
+
dirname, prefix = os.path.split(incomplete)
|
|
80
|
+
try:
|
|
81
|
+
entries = sorted(Path(os.path.expanduser(dirname or ".")).iterdir())
|
|
82
|
+
return [
|
|
83
|
+
CompletionItem(
|
|
84
|
+
os.path.join(dirname, path.name) + ("/" if path.is_dir() else ""),
|
|
85
|
+
help="Directory" if path.is_dir() else "File",
|
|
86
|
+
)
|
|
87
|
+
for path in entries
|
|
88
|
+
if path.name.startswith(prefix)
|
|
89
|
+
and (not directories or path.is_dir())
|
|
90
|
+
and (prefix.startswith(".") or not path.name.startswith("."))
|
|
91
|
+
]
|
|
92
|
+
except OSError:
|
|
93
|
+
return []
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class LocalPath(click.Path):
|
|
97
|
+
def shell_complete(self, ctx, param, incomplete):
|
|
98
|
+
return local_paths(incomplete, directories=not self.file_okay)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def prompt_text(state, name):
|
|
102
|
+
if name == "caisson":
|
|
103
|
+
if target := state.get("target"):
|
|
104
|
+
selection = "/" + state["workspace"] if state.get("workspace") else ""
|
|
105
|
+
return f"caisson[{target}{selection}]> "
|
|
106
|
+
return f"{state.get('host', 'caisson')} / {state.get('workspace') or 'no workspace'}> "
|
|
107
|
+
context = state.get("ops_context")
|
|
108
|
+
if context is None:
|
|
109
|
+
project = os.environ.get("PROJECT_ID") or "PROJECT_ID unset"
|
|
110
|
+
return f"caisson-ops [{project} · setup needed]> "
|
|
111
|
+
return f"caisson-ops [{context['PROJECT_ID']} · {context['REGION']}]> "
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class ActionError(click.ClickException):
|
|
115
|
+
def __init__(self, message, exit_code=1):
|
|
116
|
+
super().__init__(message)
|
|
117
|
+
self.exit_code = exit_code
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def run_cli(group):
|
|
121
|
+
"""Keep expected local IO/bad-tool-output failures out of Python tracebacks."""
|
|
122
|
+
try:
|
|
123
|
+
group()
|
|
124
|
+
except (OSError, ValueError) as exc:
|
|
125
|
+
click.echo(f"Error: {exc}. Check local configuration and tool output above.", err=True)
|
|
126
|
+
raise SystemExit(1) from exc
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def run(args, *, capture=False, cwd=None, input=None, env=None):
|
|
130
|
+
try:
|
|
131
|
+
return subprocess.run(
|
|
132
|
+
[str(a) for a in args],
|
|
133
|
+
cwd=cwd,
|
|
134
|
+
env=env,
|
|
135
|
+
input=input,
|
|
136
|
+
text=True,
|
|
137
|
+
stdout=subprocess.PIPE if capture else None,
|
|
138
|
+
check=True,
|
|
139
|
+
).stdout
|
|
140
|
+
except FileNotFoundError as exc:
|
|
141
|
+
raise click.ClickException(f"Required executable not found: {args[0]}") from exc
|
|
142
|
+
except subprocess.CalledProcessError as exc:
|
|
143
|
+
# Preserve the remote/tool exit code. Never echo argv (may contain secrets).
|
|
144
|
+
raise click.exceptions.Exit(exc.returncode if exc.returncode > 0 else 130) from exc
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def repl(group, state, name):
|
|
148
|
+
# One-shot commands and piped bare help don't pay for prompt_toolkit.
|
|
149
|
+
if not sys.stdin.isatty() or not sys.stdout.isatty():
|
|
150
|
+
click.echo(click.Context(group).get_help())
|
|
151
|
+
return
|
|
152
|
+
from .terminal import repl as interactive_repl
|
|
153
|
+
|
|
154
|
+
return interactive_repl(group, state, name)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def private_directory(path: Path):
|
|
158
|
+
path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
159
|
+
os.chmod(path, 0o700)
|
|
160
|
+
return path
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def write_json(path: Path, value):
|
|
164
|
+
"""Replace private JSON atomically; a failed write leaves the old file intact."""
|
|
165
|
+
temporary = None
|
|
166
|
+
try:
|
|
167
|
+
with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as stream:
|
|
168
|
+
temporary = Path(stream.name)
|
|
169
|
+
json.dump(value, stream, indent=2)
|
|
170
|
+
stream.write("\n")
|
|
171
|
+
temporary.replace(path)
|
|
172
|
+
finally:
|
|
173
|
+
if temporary is not None:
|
|
174
|
+
temporary.unlink(missing_ok=True)
|
caisson_tools/context.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Read local Tailscale display context once per management host, not per redraw."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def refresh_user_context(state):
|
|
10
|
+
host = state.get("host", "")
|
|
11
|
+
if state.get("context_host") == host:
|
|
12
|
+
return
|
|
13
|
+
state["context_host"] = host
|
|
14
|
+
state["user_context"] = {}
|
|
15
|
+
executable = shutil.which("tailscale")
|
|
16
|
+
if not executable:
|
|
17
|
+
mac_cli = Path("/Applications/Tailscale.app/Contents/MacOS/Tailscale")
|
|
18
|
+
if mac_cli.is_file():
|
|
19
|
+
executable = str(mac_cli)
|
|
20
|
+
if not executable:
|
|
21
|
+
return
|
|
22
|
+
try:
|
|
23
|
+
result = subprocess.run(
|
|
24
|
+
[executable, "status", "--json"],
|
|
25
|
+
capture_output=True, text=True, timeout=3, check=True,
|
|
26
|
+
)
|
|
27
|
+
data = json.loads(result.stdout)
|
|
28
|
+
own = data.get("Self") or {}
|
|
29
|
+
profile = (data.get("User") or {}).get(str(own.get("UserID")), {})
|
|
30
|
+
context = {}
|
|
31
|
+
if isinstance(profile.get("LoginName"), str) and profile["LoginName"]:
|
|
32
|
+
context["user"] = profile["LoginName"]
|
|
33
|
+
state["user_context"] = context
|
|
34
|
+
except (OSError, subprocess.SubprocessError, ValueError, TypeError, AttributeError):
|
|
35
|
+
# Optional local CLI/daemon: offline help and the REPL must still work.
|
|
36
|
+
return
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Dependency-free workspace config validation shared by operators and workstation boot."""
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from .allowlist_syntax import DEFAULT_METHODS, method_names, normalize_domain
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
RESERVED = r"^(CAISSON_|BASH_ENV$|ENV$|SHELLOPTS$|BASHOPTS$|LD_|HOME$|USER$|LOGNAME$|SHELL$|PATH$|IFS$|XDG_RUNTIME_DIR$)"
|
|
11
|
+
AGENT_RESERVED = r"^(XDG_|NIX_REMOTE$|.*[Pp][Rr][Oo][Xx][Yy]$|.*CA_BUNDLE$|.*CERT.*$|OPENCODE_CONFIG$|OPENCODE_PTY_BIN$)"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def environment_map(value, scope="host"):
|
|
15
|
+
if not isinstance(value, dict) or len(value) > 256:
|
|
16
|
+
raise ValueError(f"{scope}: expected a map with at most 256 entries")
|
|
17
|
+
for name, content in value.items():
|
|
18
|
+
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
|
|
19
|
+
raise ValueError(f"{scope}: invalid environment variable name")
|
|
20
|
+
if re.search(RESERVED, name) or (scope == "agent" and re.search(AGENT_RESERVED, name)):
|
|
21
|
+
raise ValueError(f"{scope}: reserved environment variable name")
|
|
22
|
+
if not isinstance(content, str) or "\0" in content:
|
|
23
|
+
raise ValueError(f"{scope}: values must be strings without NUL")
|
|
24
|
+
if len(json.dumps(value).encode()) > 65536:
|
|
25
|
+
raise ValueError(f"{scope}: environment exceeds 64 KiB")
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def environment_document(value):
|
|
30
|
+
if not isinstance(value, dict) or set(value) - {"host", "agent"}:
|
|
31
|
+
raise ValueError('Expected a JSON object with only "host" and "agent" maps')
|
|
32
|
+
return {scope: environment_map(value.get(scope, {}), scope) for scope in ("host", "agent")}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def allowlist_entries(value, name):
|
|
36
|
+
"""Normalize JSON grants without importing the workstation runtime in the CLI."""
|
|
37
|
+
if not isinstance(value, list):
|
|
38
|
+
raise ValueError(f"allowlists.{name}: expected an array")
|
|
39
|
+
merged = {}
|
|
40
|
+
for index, entry in enumerate(value, 1):
|
|
41
|
+
error = ValueError(f"allowlists.{name} entry {index}: expected a domain and optional HTTP methods")
|
|
42
|
+
if not isinstance(entry, dict) or set(entry) - {"domain", "methods"}:
|
|
43
|
+
raise error
|
|
44
|
+
domain = entry.get("domain")
|
|
45
|
+
if not isinstance(domain, str) or not domain.isascii():
|
|
46
|
+
raise error
|
|
47
|
+
try:
|
|
48
|
+
domain = normalize_domain(domain)
|
|
49
|
+
except ValueError:
|
|
50
|
+
raise error from None
|
|
51
|
+
try:
|
|
52
|
+
ipaddress.ip_address(domain.removeprefix("."))
|
|
53
|
+
except ValueError:
|
|
54
|
+
pass
|
|
55
|
+
else:
|
|
56
|
+
raise error
|
|
57
|
+
grants = DEFAULT_METHODS
|
|
58
|
+
if "methods" in entry:
|
|
59
|
+
if not isinstance(entry["methods"], list):
|
|
60
|
+
raise error
|
|
61
|
+
try:
|
|
62
|
+
grants = method_names(entry["methods"], allow_wildcard=True)
|
|
63
|
+
except ValueError:
|
|
64
|
+
raise error from None
|
|
65
|
+
merged.setdefault(domain, set()).update(grants)
|
|
66
|
+
return [{"domain": domain, "methods": ["*"] if "*" in grants else sorted(grants)}
|
|
67
|
+
for domain, grants in sorted(merged.items())]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def workspace_document(value):
|
|
71
|
+
if not isinstance(value, dict) or set(value) - {"environment", "allowlists", "default_allowlists"}:
|
|
72
|
+
raise ValueError('Expected a JSON object with only "environment", "allowlists" and "default_allowlists"')
|
|
73
|
+
allowlists = value.get("allowlists", {})
|
|
74
|
+
if not isinstance(allowlists, dict) or any(
|
|
75
|
+
not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,254}", name)
|
|
76
|
+
for name in allowlists
|
|
77
|
+
):
|
|
78
|
+
raise ValueError("allowlists: expected an object keyed by valid allowlist names")
|
|
79
|
+
defaults = value.get("default_allowlists", [])
|
|
80
|
+
if not isinstance(defaults, list) or any(
|
|
81
|
+
not isinstance(name, str) or name not in allowlists for name in defaults
|
|
82
|
+
):
|
|
83
|
+
raise ValueError("default_allowlists: expected an array of names defined in allowlists")
|
|
84
|
+
result = {
|
|
85
|
+
"environment": environment_document(value.get("environment", {})),
|
|
86
|
+
"allowlists": {name: allowlist_entries(entries, name) for name, entries in allowlists.items()},
|
|
87
|
+
"default_allowlists": list(dict.fromkeys(defaults)),
|
|
88
|
+
}
|
|
89
|
+
# Match SecretDocument.publish's encoding, including its ASCII escaping.
|
|
90
|
+
if len(json.dumps(result, separators=(",", ":")).encode()) > 65536:
|
|
91
|
+
raise ValueError("Workspace config exceeds Secret Manager's 64 KiB limit")
|
|
92
|
+
return result
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""The managed-workspace CLI's tailnet HTTPS transport."""
|
|
2
|
+
|
|
3
|
+
import http.client
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import subprocess
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
|
|
10
|
+
from .common import ActionError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def valid_management_host(value):
|
|
14
|
+
if not isinstance(value, str) or len(value) > 253 or not all(
|
|
15
|
+
re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", label)
|
|
16
|
+
for label in value.split(".")
|
|
17
|
+
):
|
|
18
|
+
raise click.BadParameter("expected a management DNS hostname")
|
|
19
|
+
return value.lower()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def management_dns_name(host):
|
|
23
|
+
host = valid_management_host(host)
|
|
24
|
+
if "." in host:
|
|
25
|
+
return host
|
|
26
|
+
# TLS certificates are issued to the full Tailscale DNS name, not the
|
|
27
|
+
# short MagicDNS alias. Don't disable verification or guess a suffix.
|
|
28
|
+
try:
|
|
29
|
+
status = json.loads(subprocess.check_output(
|
|
30
|
+
["tailscale", "status", "--json"], stderr=subprocess.DEVNULL, timeout=5,
|
|
31
|
+
))
|
|
32
|
+
tailnet = status.get("CurrentTailnet") or {}
|
|
33
|
+
suffix = tailnet.get("MagicDNSSuffix") or status.get("MagicDNSSuffix")
|
|
34
|
+
if status["BackendState"] != "Running" or not suffix:
|
|
35
|
+
raise ValueError("no connected tailnet")
|
|
36
|
+
return valid_management_host(f"{host}.{suffix.rstrip('.')}")
|
|
37
|
+
except (OSError, subprocess.SubprocessError, ValueError, KeyError, AttributeError,
|
|
38
|
+
click.BadParameter) as exc:
|
|
39
|
+
raise ActionError(
|
|
40
|
+
f"Cannot resolve management host {host}. Connect to Tailscale, or set "
|
|
41
|
+
"its full HTTPS hostname with 'caisson config set target https://HOST'.", 255,
|
|
42
|
+
) from exc
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def request_management(host, args, *, capture=False):
|
|
46
|
+
verb, *rest = args
|
|
47
|
+
operation = "list" if verb == "ls" else verb
|
|
48
|
+
payload = {}
|
|
49
|
+
if operation not in {"list", "identity"}:
|
|
50
|
+
name, *flags = rest
|
|
51
|
+
payload["name"] = name
|
|
52
|
+
if operation == "destroy" and "--yes" in flags:
|
|
53
|
+
payload["confirmed"] = True
|
|
54
|
+
|
|
55
|
+
dns_name = management_dns_name(host)
|
|
56
|
+
# Direct TLS with normal certificate/hostname verification. Do not send
|
|
57
|
+
# tailnet traffic via an environment proxy or follow HTTP redirects.
|
|
58
|
+
conn = http.client.HTTPSConnection(dns_name, timeout=10)
|
|
59
|
+
try:
|
|
60
|
+
conn.connect()
|
|
61
|
+
conn.sock.settimeout(75 * 60) # core operation timeouts are configurable
|
|
62
|
+
conn.request(
|
|
63
|
+
"POST", f"/api/v1/{operation}", body=json.dumps(payload),
|
|
64
|
+
headers={"Content-Type": "application/json", "Accept": "application/x-ndjson"},
|
|
65
|
+
)
|
|
66
|
+
with conn.getresponse() as response:
|
|
67
|
+
if response.status == 403:
|
|
68
|
+
raise click.ClickException(
|
|
69
|
+
"Management access denied. Check your Tailscale identity and Caisson access."
|
|
70
|
+
)
|
|
71
|
+
if response.status == 503:
|
|
72
|
+
raise click.ClickException("Management is busy or shutting down; try again.")
|
|
73
|
+
if response.status != 200 or response.getheader("Content-Type") != "application/x-ndjson":
|
|
74
|
+
raise click.ClickException(
|
|
75
|
+
f"Unexpected management response (HTTP {response.status}). "
|
|
76
|
+
"Check the hostname and management server version."
|
|
77
|
+
)
|
|
78
|
+
return read_events(response, capture=capture)
|
|
79
|
+
except (OSError, http.client.HTTPException) as exc:
|
|
80
|
+
raise ActionError(
|
|
81
|
+
f"HTTPS request to {dns_name} failed: {exc}. Check Tailscale and the management "
|
|
82
|
+
"hostname. If an operation was submitted, check 'caisson ls' before retrying.",
|
|
83
|
+
255,
|
|
84
|
+
) from exc
|
|
85
|
+
finally:
|
|
86
|
+
conn.close()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def read_events(response, *, capture):
|
|
90
|
+
chunks = []
|
|
91
|
+
while line := response.readline(16 * 1024 * 1024):
|
|
92
|
+
try:
|
|
93
|
+
event = json.loads(line)
|
|
94
|
+
stream = event["stream"]
|
|
95
|
+
if stream == "ready":
|
|
96
|
+
continue
|
|
97
|
+
if stream == "exit" and type(event.get("code")) is int and 0 <= event["code"] <= 255:
|
|
98
|
+
if event["code"]:
|
|
99
|
+
raise click.exceptions.Exit(event["code"])
|
|
100
|
+
return "".join(chunks) if capture else None
|
|
101
|
+
if stream in {"stdout", "stderr"} and isinstance(event.get("text"), str):
|
|
102
|
+
if capture and stream == "stdout":
|
|
103
|
+
chunks.append(event["text"])
|
|
104
|
+
else:
|
|
105
|
+
click.echo(event["text"], nl=False, err=stream == "stderr")
|
|
106
|
+
continue
|
|
107
|
+
except (ValueError, TypeError, KeyError):
|
|
108
|
+
pass
|
|
109
|
+
raise click.ClickException("Invalid management response.")
|
|
110
|
+
raise ActionError(
|
|
111
|
+
"Management connection closed before the result. Check 'caisson ls' before retrying.",
|
|
112
|
+
255,
|
|
113
|
+
)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Generated metadata, not a second implementation of agentctl validation."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@lru_cache(maxsize=1)
|
|
9
|
+
def load_manifest():
|
|
10
|
+
return json.loads(files("caisson_tools").joinpath("agentctl-commands.json").read_text())
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def runtime_help(name, note=""):
|
|
14
|
+
"""Shared command wording plus an explicitly interface-specific note."""
|
|
15
|
+
return schema_help(load_manifest()["runtime"][name], note)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def schema_help(schema, note=""):
|
|
19
|
+
"""Render shared argument/constraint help for either CLI interface."""
|
|
20
|
+
parts = [schema["help"]]
|
|
21
|
+
parts.extend(
|
|
22
|
+
f"{item['name'].upper()}: {item['help']}"
|
|
23
|
+
for item in schema.get("arguments", [])
|
|
24
|
+
if item.get("help")
|
|
25
|
+
)
|
|
26
|
+
for group in schema.get("exclusive", []):
|
|
27
|
+
labels = " / ".join("--" + name.replace("_", "-") for name in group["names"])
|
|
28
|
+
parts.append(
|
|
29
|
+
("Choose exactly one: " if group["required"] else "Use at most one: ") + labels
|
|
30
|
+
)
|
|
31
|
+
if note:
|
|
32
|
+
parts.append(note)
|
|
33
|
+
return "\n\n".join(parts)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def runtime_option_help(name, flag):
|
|
37
|
+
return next(
|
|
38
|
+
item["help"]
|
|
39
|
+
for item in load_manifest()["runtime"][name]["options"]
|
|
40
|
+
if flag in item["flags"]
|
|
41
|
+
)
|