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
caisson_tools/user.py
ADDED
|
@@ -0,0 +1,789 @@
|
|
|
1
|
+
"""Laptop CLI: management discovery and direct workstation SSH."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
|
|
13
|
+
from .browser import show_url
|
|
14
|
+
from .common import (
|
|
15
|
+
LocalPath,
|
|
16
|
+
UXGroup,
|
|
17
|
+
console,
|
|
18
|
+
local_paths,
|
|
19
|
+
private_directory,
|
|
20
|
+
repl,
|
|
21
|
+
run,
|
|
22
|
+
run_cli,
|
|
23
|
+
workspace_completions,
|
|
24
|
+
write_json,
|
|
25
|
+
)
|
|
26
|
+
from .context import refresh_user_context
|
|
27
|
+
from .management import request_management, valid_management_host
|
|
28
|
+
from .manifest import load_manifest, runtime_help, runtime_option_help
|
|
29
|
+
from .remote import remote_tree
|
|
30
|
+
from .serve import PORTS as SERVE_PORTS
|
|
31
|
+
from .transport import SSH, is_ssh_destination
|
|
32
|
+
from .version import add_version_commands
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
DEFAULT_TARGET = "https://caisson"
|
|
36
|
+
TARGET_FORMAT = "local, ssh://[user@]host, or https://server (http:// also uses HTTPS)"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def config_path():
|
|
40
|
+
return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "caisson/config.json"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def valid_target(value, *, param_hint=None):
|
|
44
|
+
if value == "local":
|
|
45
|
+
return value
|
|
46
|
+
if isinstance(value, str):
|
|
47
|
+
scheme, sep, host = value.partition("://")
|
|
48
|
+
if scheme in {"http", "https"} and sep:
|
|
49
|
+
try:
|
|
50
|
+
return "https://" + valid_management_host(host)
|
|
51
|
+
except click.BadParameter as exc:
|
|
52
|
+
raise click.BadParameter(exc.message, param_hint=param_hint) from exc
|
|
53
|
+
if scheme == "ssh" and sep and is_ssh_destination(host):
|
|
54
|
+
return "ssh://" + host
|
|
55
|
+
raise click.BadParameter(f"expected {TARGET_FORMAT}", param_hint=param_hint)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def configured_target():
|
|
59
|
+
try:
|
|
60
|
+
return valid_target(json.loads(config_path().read_text())["target"])
|
|
61
|
+
except FileNotFoundError:
|
|
62
|
+
return DEFAULT_TARGET
|
|
63
|
+
except (ValueError, KeyError, TypeError, click.BadParameter) as exc:
|
|
64
|
+
raise click.ClickException(f"Invalid config: {config_path()}") from exc
|
|
65
|
+
except OSError as exc:
|
|
66
|
+
raise click.ClickException(f"Cannot read config {config_path()}: {exc.strerror}") from exc
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def management(state, args, *, capture=False):
|
|
70
|
+
if state.get("target"):
|
|
71
|
+
return podman_target(state, args, capture=capture)
|
|
72
|
+
if state.get("config_error"):
|
|
73
|
+
raise click.ClickException(
|
|
74
|
+
f"{state['config_error']}. Repair with 'caisson config set target TARGET', "
|
|
75
|
+
"or override with --target TARGET."
|
|
76
|
+
)
|
|
77
|
+
return request_management(state["host"], args, capture=capture)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def command_hint(state, command):
|
|
81
|
+
if target := state.get("target_override"):
|
|
82
|
+
return f"caisson --target {target} {command}"
|
|
83
|
+
if state.get("in_repl"):
|
|
84
|
+
return command
|
|
85
|
+
return "caisson " + command
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def podman_target(state, args, *, capture=False, tty=None):
|
|
89
|
+
interactive = sys.stdin.isatty() if tty is None else tty
|
|
90
|
+
argv = ["caisson-podman", *args]
|
|
91
|
+
if state["target"] == "local":
|
|
92
|
+
return run(argv, capture=capture)
|
|
93
|
+
destination = state["target"].removeprefix("ssh://")
|
|
94
|
+
if interactive and capture:
|
|
95
|
+
return state["ssh"].capture_terminal(destination, argv)
|
|
96
|
+
return state["ssh"].execute(destination, argv, capture=capture, tty=interactive)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def active_target(state):
|
|
100
|
+
return state.get("target") or state["host"]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def require_management(state, feature):
|
|
104
|
+
if state.get("target"):
|
|
105
|
+
raise click.ClickException(f"{feature} is not available on Podman targets")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def management_json(state, args):
|
|
109
|
+
try:
|
|
110
|
+
result = json.loads(management(state, args, capture=True))
|
|
111
|
+
if not isinstance(result, dict):
|
|
112
|
+
raise ValueError("expected an object")
|
|
113
|
+
return result
|
|
114
|
+
except (ValueError, TypeError) as exc:
|
|
115
|
+
raise click.ClickException("Invalid JSON response from management") from exc
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def inventory(state):
|
|
119
|
+
data = management_json(state, ["ls", "--json", "--details"])
|
|
120
|
+
try:
|
|
121
|
+
state["workspaces"] = [w["name"] for w in data["workspaces"]]
|
|
122
|
+
return data["workspaces"]
|
|
123
|
+
except (KeyError, TypeError) as exc:
|
|
124
|
+
raise click.ClickException("Management response is missing workspace inventory") from exc
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def workspace(state, name=None):
|
|
128
|
+
chosen = name or state.get("workspace")
|
|
129
|
+
if chosen:
|
|
130
|
+
return chosen
|
|
131
|
+
# Cached names are only selection hints, never authorization/state. Actual
|
|
132
|
+
# connection resolution and lifecycle commands still verify on the server.
|
|
133
|
+
names = state.get("workspaces") if state.get("in_repl") else None
|
|
134
|
+
if names is None:
|
|
135
|
+
names = [w["name"] for w in inventory(state)]
|
|
136
|
+
if len(names) == 1:
|
|
137
|
+
return names[0]
|
|
138
|
+
if not names:
|
|
139
|
+
raise click.ClickException(
|
|
140
|
+
"No workspaces; create one with: " + command_hint(state, "new NAME")
|
|
141
|
+
)
|
|
142
|
+
if not sys.stdin.isatty():
|
|
143
|
+
raise click.UsageError("Select a workspace with --workspace NAME")
|
|
144
|
+
from .terminal import pick_workspace
|
|
145
|
+
|
|
146
|
+
chosen = pick_workspace(active_target(state), names)
|
|
147
|
+
if state.get("in_repl"):
|
|
148
|
+
state["workspace"] = chosen
|
|
149
|
+
return chosen
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def destination(state, name=None):
|
|
153
|
+
name = workspace(state, name)
|
|
154
|
+
def lookup():
|
|
155
|
+
data = management_json(state, ["status", name])
|
|
156
|
+
if data.get("needs_repair") or not data.get("access_verified"):
|
|
157
|
+
raise click.ClickException(
|
|
158
|
+
"Workspace needs repair: " + command_hint(state, f"new {name} --no-start")
|
|
159
|
+
)
|
|
160
|
+
if not data.get("ssh_host") or not data.get("ssh_user"):
|
|
161
|
+
raise click.ClickException("Management returned no supported SSH destination")
|
|
162
|
+
target = f"{data['ssh_user']}@{data['ssh_host']}"
|
|
163
|
+
state["ssh"].options(target) # validate before use
|
|
164
|
+
return data, target
|
|
165
|
+
|
|
166
|
+
data, target = lookup()
|
|
167
|
+
if data.get("state") not in {"RUNNING", "STATE_RUNNING"}:
|
|
168
|
+
if data.get("state") not in {"STOPPED", "STATE_STOPPED"}:
|
|
169
|
+
raise click.ClickException(
|
|
170
|
+
f"Workspace is {data.get('state', 'unknown')}; wait and retry"
|
|
171
|
+
)
|
|
172
|
+
if not sys.stdin.isatty() or not click.confirm(
|
|
173
|
+
f"Start {state['host']} / {name} (billable compute)?"
|
|
174
|
+
):
|
|
175
|
+
raise click.ClickException(
|
|
176
|
+
"Workspace is stopped. Run: " + command_hint(state, f"start {name}")
|
|
177
|
+
)
|
|
178
|
+
management(state, ["start", name], capture=True)
|
|
179
|
+
data, target = lookup()
|
|
180
|
+
if data.get("state") not in {"RUNNING", "STATE_RUNNING"}:
|
|
181
|
+
raise click.ClickException("Workspace is not ready after start; check status and retry")
|
|
182
|
+
return target
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def workstation_exec(state, name, args=(), **options):
|
|
186
|
+
if not state.get("target"):
|
|
187
|
+
return state["ssh"].execute(destination(state, name), args, **options)
|
|
188
|
+
tty = bool(options.pop("tty", False) and sys.stdin.isatty())
|
|
189
|
+
flags = ["--tty"] if tty else []
|
|
190
|
+
return podman_target(
|
|
191
|
+
state, ["exec", workspace(state, name), *flags, "--", *args],
|
|
192
|
+
# Captured replies frame stdout separately so sudo can still prompt.
|
|
193
|
+
tty=None if options.get("capture") else tty, **options,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def clear_workspace(state):
|
|
198
|
+
for key in ("workspace", "workspaces"):
|
|
199
|
+
state.pop(key, None)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def activate_target(state, target, *, refresh_context=True):
|
|
203
|
+
host = target.removeprefix("https://") if target.startswith("https://") else None
|
|
204
|
+
podman = None if host else target
|
|
205
|
+
changed = state.get("target") != podman or (host is not None and state.get("host") != host)
|
|
206
|
+
selection_cleared = changed and bool(state.get("workspace"))
|
|
207
|
+
if changed:
|
|
208
|
+
clear_workspace(state)
|
|
209
|
+
if host:
|
|
210
|
+
state.pop("target", None)
|
|
211
|
+
state["host"] = host
|
|
212
|
+
if refresh_context and state.get("in_repl"):
|
|
213
|
+
refresh_user_context(state)
|
|
214
|
+
else:
|
|
215
|
+
state["target"] = podman
|
|
216
|
+
state.pop("config_error", None)
|
|
217
|
+
return selection_cleared
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def show_workspaces(state, items):
|
|
221
|
+
if not items:
|
|
222
|
+
click.echo(
|
|
223
|
+
f"No workspaces on {active_target(state)}. Create one with: {command_hint(state, 'new NAME')}"
|
|
224
|
+
)
|
|
225
|
+
return
|
|
226
|
+
from rich.table import Table
|
|
227
|
+
from rich.console import Console
|
|
228
|
+
|
|
229
|
+
title = f"Workspaces on {active_target(state)}"
|
|
230
|
+
table = Table("Name", "State", "Hostname", title=title, min_width=len(title))
|
|
231
|
+
for item in sorted(items, key=lambda item: item["name"] != state.get("workspace")):
|
|
232
|
+
active = item["name"] == state.get("workspace")
|
|
233
|
+
name = item["name"] + (" (active)" if active else "")
|
|
234
|
+
status = item["state"] + (", needs repair" if item["needs_repair"] else "")
|
|
235
|
+
table.add_row(
|
|
236
|
+
name, status, item.get("ssh_host") or "—",
|
|
237
|
+
style="bold" if active else None,
|
|
238
|
+
)
|
|
239
|
+
Console().print(table)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@click.group(
|
|
243
|
+
cls=UXGroup,
|
|
244
|
+
invoke_without_command=True,
|
|
245
|
+
epilog="""Examples:
|
|
246
|
+
|
|
247
|
+
caisson agent Open the coding agent
|
|
248
|
+
|
|
249
|
+
caisson agent dev Choose a workspace
|
|
250
|
+
|
|
251
|
+
caisson copy-to ./file Upload a file to the agent's home
|
|
252
|
+
|
|
253
|
+
caisson copy-from results.json Download a file to this directory
|
|
254
|
+
|
|
255
|
+
Run 'caisson COMMAND --help' for details, or bare 'caisson' for the REPL.""",
|
|
256
|
+
)
|
|
257
|
+
@click.option("-t", "--target", help=f"Override the saved target: {TARGET_FORMAT}.")
|
|
258
|
+
@click.option(
|
|
259
|
+
"-w",
|
|
260
|
+
"--workspace",
|
|
261
|
+
"selected",
|
|
262
|
+
shell_complete=workspace_completions,
|
|
263
|
+
help="Workspace name.",
|
|
264
|
+
)
|
|
265
|
+
@click.pass_context
|
|
266
|
+
def cli(ctx, target, selected):
|
|
267
|
+
"""Manage workspaces and their agents from your laptop."""
|
|
268
|
+
state = ctx.ensure_object(dict)
|
|
269
|
+
if target is not None:
|
|
270
|
+
target = valid_target(target, param_hint="--target")
|
|
271
|
+
if target and ctx.invoked_subcommand != "config":
|
|
272
|
+
# An override inside the REPL applies to this command, not its prompt
|
|
273
|
+
# or the next command. Bare `caisson --target …` scopes a whole REPL.
|
|
274
|
+
scoped = state.get("in_repl") and ctx.invoked_subcommand is not None
|
|
275
|
+
if scoped:
|
|
276
|
+
ctx.obj = state = state.copy()
|
|
277
|
+
if "workspaces" in state:
|
|
278
|
+
state["workspaces"] = state["workspaces"].copy()
|
|
279
|
+
activate_target(state, target, refresh_context=not scoped)
|
|
280
|
+
state["target_override"] = target
|
|
281
|
+
elif "host" not in state and "target" not in state:
|
|
282
|
+
try:
|
|
283
|
+
activate_target(state, configured_target())
|
|
284
|
+
except click.ClickException as exc:
|
|
285
|
+
state["host"], state["config_error"] = "caisson", exc
|
|
286
|
+
if "ssh" not in state:
|
|
287
|
+
state["ssh"] = SSH()
|
|
288
|
+
ctx.call_on_close(state["ssh"].close)
|
|
289
|
+
if selected:
|
|
290
|
+
state["workspace"] = selected
|
|
291
|
+
if ctx.invoked_subcommand is None:
|
|
292
|
+
if state.get("in_repl"):
|
|
293
|
+
return
|
|
294
|
+
if sys.stdin.isatty() and sys.stdout.isatty():
|
|
295
|
+
state["in_repl"] = True
|
|
296
|
+
if not state.get("target"):
|
|
297
|
+
refresh_user_context(state)
|
|
298
|
+
# Discover once on entry, both to warm the management connection and
|
|
299
|
+
# to make workspace-name completion useful before the first command.
|
|
300
|
+
try:
|
|
301
|
+
console.print(f"Connecting to {active_target(state)}…")
|
|
302
|
+
items = inventory(state)
|
|
303
|
+
if len(items) == 1 and not state.get("workspace"):
|
|
304
|
+
state["workspace"] = items[0]["name"]
|
|
305
|
+
show_workspaces(state, items)
|
|
306
|
+
except (click.ClickException, click.exceptions.Exit, KeyboardInterrupt) as exc:
|
|
307
|
+
console.print(
|
|
308
|
+
f"Could not load workspaces: {exc or 'cancelled'}. "
|
|
309
|
+
"Check the target connection; run ls to retry."
|
|
310
|
+
)
|
|
311
|
+
repl(cli, state, "caisson")
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
@cli.group()
|
|
315
|
+
def config():
|
|
316
|
+
"""Manage the saved target (default: https://caisson)."""
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@config.command("set")
|
|
320
|
+
@click.argument("key", type=click.Choice(["target"]), expose_value=False)
|
|
321
|
+
@click.argument("value")
|
|
322
|
+
@click.pass_obj
|
|
323
|
+
def config_set(state, value):
|
|
324
|
+
target = valid_target(value, param_hint="VALUE")
|
|
325
|
+
path = config_path()
|
|
326
|
+
private_directory(path.parent)
|
|
327
|
+
# Never put authentication material in this file.
|
|
328
|
+
write_json(path, {"target": target})
|
|
329
|
+
selection_cleared = activate_target(state, target)
|
|
330
|
+
state.pop("target_override", None)
|
|
331
|
+
click.echo(f"Target: {target}.")
|
|
332
|
+
if selection_cleared:
|
|
333
|
+
click.echo("Workspace selection cleared.")
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
@config.command("show")
|
|
337
|
+
def config_show():
|
|
338
|
+
"""Show the saved target, ignoring command-line overrides."""
|
|
339
|
+
try:
|
|
340
|
+
target = configured_target()
|
|
341
|
+
except click.ClickException as exc:
|
|
342
|
+
raise click.ClickException(f"{exc}. Repair with: caisson config set target TARGET") from exc
|
|
343
|
+
click.echo(json.dumps({"target": target}, indent=2))
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
@cli.command("use")
|
|
347
|
+
@click.argument("name", shell_complete=workspace_completions)
|
|
348
|
+
@click.pass_obj
|
|
349
|
+
def select_workspace(state, name):
|
|
350
|
+
"""Select a workspace."""
|
|
351
|
+
names = state.get("workspaces", [])
|
|
352
|
+
if name not in names:
|
|
353
|
+
names = [w["name"] for w in inventory(state)]
|
|
354
|
+
if name not in names:
|
|
355
|
+
raise click.BadParameter("not one of your workspaces")
|
|
356
|
+
state["workspace"] = name
|
|
357
|
+
click.echo(f"Selected {name}")
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
@cli.command("ls")
|
|
361
|
+
@click.option("--json", "as_json", is_flag=True)
|
|
362
|
+
@click.pass_obj
|
|
363
|
+
def list_workspaces(state, as_json):
|
|
364
|
+
"""List your workspaces."""
|
|
365
|
+
items = inventory(state)
|
|
366
|
+
if as_json:
|
|
367
|
+
click.echo(json.dumps({"workspaces": items}, indent=2))
|
|
368
|
+
else:
|
|
369
|
+
show_workspaces(state, items)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
@cli.command("whoami")
|
|
373
|
+
@click.pass_obj
|
|
374
|
+
def whoami(state):
|
|
375
|
+
"""Print your authenticated management identity."""
|
|
376
|
+
require_management(state, "whoami")
|
|
377
|
+
click.echo(management_json(state, ["identity"])["email"])
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def show_status(state, name, data, *, as_json):
|
|
381
|
+
if as_json:
|
|
382
|
+
click.echo(json.dumps(data, indent=2))
|
|
383
|
+
return
|
|
384
|
+
|
|
385
|
+
def text(value):
|
|
386
|
+
return "".join(c if c.isprintable() else "?" for c in str(value))
|
|
387
|
+
|
|
388
|
+
click.echo(f"Name: {text(name)}")
|
|
389
|
+
for key in ("state", "config", "provider", "created"):
|
|
390
|
+
if value := data.get(key):
|
|
391
|
+
click.echo(f"{key.title() + ':':<11}{text(value)}")
|
|
392
|
+
if not data.get("access_verified") or data.get("needs_repair"):
|
|
393
|
+
click.echo("Access: NEEDS-REPAIR")
|
|
394
|
+
click.echo("Repair with: " + command_hint(state, f"new {name} --no-start"))
|
|
395
|
+
return
|
|
396
|
+
click.echo("Access: verified (owner only)")
|
|
397
|
+
if data.get("ssh_user") and data.get("ssh_host"):
|
|
398
|
+
click.echo(f"SSH: ssh {text(data['ssh_user'])}@{text(data['ssh_host'])}")
|
|
399
|
+
if data.get("state") in {"STOPPED", "STATE_STOPPED"}:
|
|
400
|
+
click.echo("Start with: " + command_hint(state, f"start {name}"))
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def lifecycle(command):
|
|
404
|
+
@click.command(command)
|
|
405
|
+
@click.argument("name", required=command == "new", shell_complete=workspace_completions)
|
|
406
|
+
@click.pass_obj
|
|
407
|
+
def invoke(state, name, yes=False, as_json=False, no_start=False):
|
|
408
|
+
selected = workspace(state, name)
|
|
409
|
+
if command == "status" and not state.get("target"):
|
|
410
|
+
show_status(state, selected, management_json(state, ["status", selected]), as_json=as_json)
|
|
411
|
+
return
|
|
412
|
+
args = [command, selected]
|
|
413
|
+
if as_json:
|
|
414
|
+
args.append("--json")
|
|
415
|
+
start_in_helper = command == "new" and not no_start and state.get("target")
|
|
416
|
+
if start_in_helper:
|
|
417
|
+
args.append("--start")
|
|
418
|
+
if command == "destroy":
|
|
419
|
+
if not yes and not click.confirm(
|
|
420
|
+
f"Permanently delete {active_target(state)} / {selected} and ALL its files?"
|
|
421
|
+
):
|
|
422
|
+
raise click.exceptions.Exit(9)
|
|
423
|
+
args.append("--yes")
|
|
424
|
+
# Own these summaries locally; capture only stdout so progress/errors stream.
|
|
425
|
+
local_summary = command in {"new", "start", "rebuild"}
|
|
426
|
+
if state.get("target"):
|
|
427
|
+
# When stdout is redirected, keep remote PTY prompts on stderr.
|
|
428
|
+
capture = as_json or not sys.stdout.isatty()
|
|
429
|
+
output = management(state, args, capture=capture)
|
|
430
|
+
if command == "status" and capture:
|
|
431
|
+
click.echo(output.strip())
|
|
432
|
+
else:
|
|
433
|
+
management(state, args, capture=local_summary)
|
|
434
|
+
if command == "new":
|
|
435
|
+
click.echo(f"Workspace {selected} created or repaired.")
|
|
436
|
+
if command == "new" and "workspaces" in state and selected not in state["workspaces"]:
|
|
437
|
+
state["workspaces"].append(selected)
|
|
438
|
+
if command == "new" and not no_start and not start_in_helper:
|
|
439
|
+
management(state, ["start", selected], capture=True)
|
|
440
|
+
if command == "start" or (command == "new" and not no_start):
|
|
441
|
+
click.echo(f"Workspace {selected} is running.")
|
|
442
|
+
elif command == "rebuild":
|
|
443
|
+
click.echo(
|
|
444
|
+
f"Workspace {selected} was rebuilt and is running. "
|
|
445
|
+
"Files under the home directory were kept."
|
|
446
|
+
)
|
|
447
|
+
if local_summary:
|
|
448
|
+
if command == "new" and no_start:
|
|
449
|
+
steps = [(command_hint(state, f"start {selected}"), "start it")]
|
|
450
|
+
else:
|
|
451
|
+
steps = [(command_hint(state, f"shell {selected}"), "open an agent shell")]
|
|
452
|
+
if not state.get("target"):
|
|
453
|
+
steps.insert(0, (
|
|
454
|
+
command_hint(state, f"enroll {selected}"), "set up Tailscale (first time)"
|
|
455
|
+
))
|
|
456
|
+
width = max(len(command) for command, _ in steps)
|
|
457
|
+
click.echo("\nNext:")
|
|
458
|
+
for command_text, description in steps:
|
|
459
|
+
click.echo(f" {command_text:<{width}} {description}")
|
|
460
|
+
if command == "destroy":
|
|
461
|
+
state["workspaces"] = [w for w in state.get("workspaces", []) if w != selected]
|
|
462
|
+
if state.get("workspace") == selected:
|
|
463
|
+
state.pop("workspace")
|
|
464
|
+
|
|
465
|
+
descriptions = {
|
|
466
|
+
"new": "Create or repair a workspace, then start billable compute.",
|
|
467
|
+
"start": "Start a workspace. Starts billable compute.",
|
|
468
|
+
"stop": "Stop compute; keep the workspace and its files.",
|
|
469
|
+
"rebuild": "Restart on the current image; keep files, terminate running processes.",
|
|
470
|
+
"status": "Show workspace state, access and connection details.",
|
|
471
|
+
"destroy": "Permanently delete a workspace and ALL its files.",
|
|
472
|
+
}
|
|
473
|
+
invoke.help = (
|
|
474
|
+
descriptions[command] + "\n\nOmit NAME to use the selected or only workspace."
|
|
475
|
+
if command != "new"
|
|
476
|
+
else descriptions[command]
|
|
477
|
+
)
|
|
478
|
+
if command == "destroy":
|
|
479
|
+
invoke.params.append(
|
|
480
|
+
click.Option(["--yes"], is_flag=True, help="Skip permanent-deletion confirmation.")
|
|
481
|
+
)
|
|
482
|
+
if command == "new":
|
|
483
|
+
invoke.params.append(
|
|
484
|
+
click.Option(
|
|
485
|
+
["--no-start"], is_flag=True,
|
|
486
|
+
help="Create or repair only; do not start the workspace.",
|
|
487
|
+
)
|
|
488
|
+
)
|
|
489
|
+
if command == "status":
|
|
490
|
+
invoke.params.append(
|
|
491
|
+
click.Option(["--json", "as_json"], is_flag=True, help="Print machine-readable JSON.")
|
|
492
|
+
)
|
|
493
|
+
return invoke
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
for _name in ("new", "start", "stop", "rebuild", "status", "destroy"):
|
|
497
|
+
cli.add_command(lifecycle(_name))
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@cli.command("enroll")
|
|
501
|
+
@click.argument("name", required=False, shell_complete=workspace_completions)
|
|
502
|
+
@click.option("--no-open-browser", is_flag=True, help="Print the URL without opening a browser.")
|
|
503
|
+
@click.pass_obj
|
|
504
|
+
def enroll(state, name, no_open_browser):
|
|
505
|
+
"""Open the first-time Tailscale enrollment page.
|
|
506
|
+
|
|
507
|
+
Omit NAME to use the selected or only workspace.
|
|
508
|
+
"""
|
|
509
|
+
require_management(state, "enroll")
|
|
510
|
+
url = management(state, ["enroll", workspace(state, name)], capture=True)
|
|
511
|
+
show_url(url, no_open_browser=no_open_browser)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
@cli.command("web")
|
|
515
|
+
@click.argument("name", required=False, shell_complete=workspace_completions)
|
|
516
|
+
@click.option("--no-open-browser", is_flag=True, help="Print the URL without opening a browser.")
|
|
517
|
+
@click.pass_obj
|
|
518
|
+
def web(state, name, no_open_browser):
|
|
519
|
+
"""Open the workspace's tailnet-only OpenCode web UI.
|
|
520
|
+
|
|
521
|
+
Omit NAME to use the selected or only workspace.
|
|
522
|
+
"""
|
|
523
|
+
selected = workspace(state, name)
|
|
524
|
+
if state.get("target"):
|
|
525
|
+
url = management(state, ["web", selected], capture=True)
|
|
526
|
+
show_url(url, no_open_browser=no_open_browser, extra_ports=SERVE_PORTS)
|
|
527
|
+
return
|
|
528
|
+
# Use normal authorized connection resolution, including the stopped-workspace prompt.
|
|
529
|
+
target = destination(state, selected)
|
|
530
|
+
url = state["ssh"].execute(
|
|
531
|
+
target, ["sh", "-c", "cat /run/caisson/status/opencode-url 2>/dev/null || true"],
|
|
532
|
+
capture=True,
|
|
533
|
+
)
|
|
534
|
+
if not url.strip():
|
|
535
|
+
raise click.ClickException(
|
|
536
|
+
"Workspace web UI is not available. Check Tailscale enrollment "
|
|
537
|
+
f"with '{command_hint(state, f'enroll {selected}')}' and HTTPS Serve on the workstation."
|
|
538
|
+
)
|
|
539
|
+
show_url(url, no_open_browser=no_open_browser)
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
@cli.command("host-shell")
|
|
543
|
+
@click.argument("name", required=False, shell_complete=workspace_completions)
|
|
544
|
+
@click.pass_obj
|
|
545
|
+
def host_shell(state, name):
|
|
546
|
+
"""Open a workstation shell.
|
|
547
|
+
|
|
548
|
+
Omit NAME to use the selected or only workspace.
|
|
549
|
+
"""
|
|
550
|
+
workstation_exec(state, name, tty=True)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
@cli.command(
|
|
554
|
+
"agent-shell",
|
|
555
|
+
help=runtime_help("shell", note="Omit NAME to use the selected or only workspace."),
|
|
556
|
+
)
|
|
557
|
+
@click.argument("name", required=False, shell_complete=workspace_completions)
|
|
558
|
+
@click.pass_obj
|
|
559
|
+
def agent_shell(state, name):
|
|
560
|
+
workstation_exec(state, name, ["agentctl", "shell"], tty=True)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
cli.add_command(agent_shell, "shell")
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
@cli.command(
|
|
567
|
+
"pair",
|
|
568
|
+
help=runtime_help(
|
|
569
|
+
"pair",
|
|
570
|
+
note="Omit NAME to use the selected or only workspace. "
|
|
571
|
+
"Open the one-time link manually when ready.",
|
|
572
|
+
),
|
|
573
|
+
)
|
|
574
|
+
@click.argument("name", required=False, shell_complete=workspace_completions)
|
|
575
|
+
@click.option(
|
|
576
|
+
"--no-open-browser", is_flag=True, expose_value=False,
|
|
577
|
+
help="Accepted for compatibility; pairing never opens a browser.",
|
|
578
|
+
)
|
|
579
|
+
@click.option(
|
|
580
|
+
"--tty/--no-tty",
|
|
581
|
+
default=None,
|
|
582
|
+
help="Force a terminal, or keep stdout/stderr separate (default: auto).",
|
|
583
|
+
)
|
|
584
|
+
@click.pass_obj
|
|
585
|
+
def pair(state, name, tty):
|
|
586
|
+
if tty is None:
|
|
587
|
+
tty = sys.stdin.isatty() and sys.stdout.isatty()
|
|
588
|
+
output = workstation_exec(state, name, ["agentctl", "pair"], tty=tty, capture=True)
|
|
589
|
+
click.echo(output, nl=False)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
@cli.command("forward")
|
|
593
|
+
@click.argument("port", type=click.IntRange(1, 65535))
|
|
594
|
+
@click.option("--local-port", type=click.IntRange(1, 65535))
|
|
595
|
+
@click.pass_obj
|
|
596
|
+
def forward(state, port, local_port):
|
|
597
|
+
"""Forward an agent TCP port to laptop loopback; Ctrl-C closes it."""
|
|
598
|
+
require_management(state, "forward")
|
|
599
|
+
target = destination(state)
|
|
600
|
+
click.echo(
|
|
601
|
+
f"Opening tunnel to agent port {port} at 127.0.0.1:{local_port or port}; "
|
|
602
|
+
"keep running, Ctrl-C to stop.",
|
|
603
|
+
err=True,
|
|
604
|
+
)
|
|
605
|
+
state["ssh"].forward(target, local_port or port, port)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
@cli.command("scp")
|
|
609
|
+
@click.option("-r", "--recursive", is_flag=True, help="Copy directories recursively.")
|
|
610
|
+
@click.option("-p", "--preserve", is_flag=True, help="Preserve file times and permissions.")
|
|
611
|
+
@click.argument("source", shell_complete=lambda ctx, param, incomplete: scp_completions(incomplete))
|
|
612
|
+
@click.argument(
|
|
613
|
+
"destination_path",
|
|
614
|
+
metavar="DESTINATION",
|
|
615
|
+
shell_complete=lambda ctx, param, incomplete: scp_completions(incomplete),
|
|
616
|
+
)
|
|
617
|
+
@click.pass_obj
|
|
618
|
+
def scp(state, recursive, preserve, source, destination_path):
|
|
619
|
+
"""Copy LOCAL agent:PATH, or agent:PATH LOCAL, directly over SFTP.
|
|
620
|
+
|
|
621
|
+
Relative agent paths are relative to /home/agent. Requires modern OpenSSH
|
|
622
|
+
scp (SFTP with -D support); no files are staged on the workstation host.
|
|
623
|
+
"""
|
|
624
|
+
source_remote = source.startswith("agent:")
|
|
625
|
+
destination_remote = destination_path.startswith("agent:")
|
|
626
|
+
if source_remote == destination_remote:
|
|
627
|
+
raise click.UsageError(
|
|
628
|
+
"Exactly one endpoint must be agent:PATH; the other is a laptop path"
|
|
629
|
+
)
|
|
630
|
+
local = destination_path if source_remote else source
|
|
631
|
+
guest = (source if source_remote else destination_path).removeprefix("agent:")
|
|
632
|
+
copy_files(
|
|
633
|
+
state, local, guest or ".", upload=not source_remote, recursive=recursive, preserve=preserve
|
|
634
|
+
)
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def copy_files(state, local, guest, *, upload, recursive, preserve):
|
|
638
|
+
if "\0" in str(local) or "\0" in guest:
|
|
639
|
+
raise click.BadParameter("Paths cannot contain NUL bytes")
|
|
640
|
+
# Absolute laptop paths cannot be mistaken for scp options or host:path.
|
|
641
|
+
local = str(Path(local).expanduser().absolute())
|
|
642
|
+
if upload:
|
|
643
|
+
if not Path(local).exists():
|
|
644
|
+
raise click.BadParameter(f"Laptop source does not exist: {local}", param_hint="LOCAL")
|
|
645
|
+
if Path(local).is_dir() and not recursive:
|
|
646
|
+
raise click.UsageError(
|
|
647
|
+
"The laptop source is a directory. Use -r/--recursive to copy directories."
|
|
648
|
+
)
|
|
649
|
+
remote = "agent:" + (guest or ".")
|
|
650
|
+
source, target = (local, remote) if upload else (remote, local)
|
|
651
|
+
if podman := state.get("target"):
|
|
652
|
+
state["ssh"].podman_scp(
|
|
653
|
+
podman, workspace(state), source, target, recursive=recursive, preserve=preserve,
|
|
654
|
+
)
|
|
655
|
+
return
|
|
656
|
+
state["ssh"].scp(
|
|
657
|
+
destination(state),
|
|
658
|
+
source,
|
|
659
|
+
target,
|
|
660
|
+
recursive=recursive,
|
|
661
|
+
preserve=preserve,
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
@cli.command(
|
|
666
|
+
"copy-to",
|
|
667
|
+
help=runtime_help(
|
|
668
|
+
"copy-to",
|
|
669
|
+
note=(
|
|
670
|
+
"LOCAL is a laptop path. AGENT_PATH defaults to /home/agent; no agent: prefix is needed. "
|
|
671
|
+
"Use -r for directories. Existing files may be overwritten, as with scp."
|
|
672
|
+
),
|
|
673
|
+
),
|
|
674
|
+
epilog="Examples:\n\n caisson copy-to ./notes.txt\n\n caisson copy-to -r ./project projects/",
|
|
675
|
+
)
|
|
676
|
+
@click.option("-r", "--recursive", is_flag=True, help="Copy directories recursively.")
|
|
677
|
+
@click.option("-p", "--preserve", is_flag=True, help="Preserve file times and permissions.")
|
|
678
|
+
@click.argument("local", type=LocalPath())
|
|
679
|
+
@click.argument("agent_path", required=False, default=".")
|
|
680
|
+
@click.pass_obj
|
|
681
|
+
def copy_to(state, recursive, preserve, local, agent_path):
|
|
682
|
+
copy_files(state, local, agent_path, upload=True, recursive=recursive, preserve=preserve)
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
@cli.command(
|
|
686
|
+
"copy-from",
|
|
687
|
+
help=runtime_help(
|
|
688
|
+
"copy-from",
|
|
689
|
+
note=(
|
|
690
|
+
"LOCAL is a laptop path and defaults to the current directory; no agent: prefix is needed. "
|
|
691
|
+
"Use -r for directories. Existing files may be overwritten, as with scp."
|
|
692
|
+
),
|
|
693
|
+
),
|
|
694
|
+
epilog="Examples:\n\n caisson copy-from results.json\n\n caisson copy-from -r project ./download",
|
|
695
|
+
)
|
|
696
|
+
@click.option("-r", "--recursive", is_flag=True, help="Copy directories recursively.")
|
|
697
|
+
@click.option("-p", "--preserve", is_flag=True, help="Preserve file times and permissions.")
|
|
698
|
+
@click.argument("agent_path")
|
|
699
|
+
@click.argument("local", required=False, default=".", type=LocalPath())
|
|
700
|
+
@click.pass_obj
|
|
701
|
+
def copy_from(state, recursive, preserve, agent_path, local):
|
|
702
|
+
copy_files(state, local, agent_path, upload=False, recursive=recursive, preserve=preserve)
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def scp_completions(incomplete):
|
|
706
|
+
from click.shell_completion import CompletionItem
|
|
707
|
+
|
|
708
|
+
if incomplete.startswith("agent:"):
|
|
709
|
+
return (
|
|
710
|
+
[CompletionItem("agent:", help="Guest path (relative to /home/agent)")]
|
|
711
|
+
if incomplete == "agent:"
|
|
712
|
+
else []
|
|
713
|
+
)
|
|
714
|
+
return (
|
|
715
|
+
[CompletionItem("agent:", help="Copy to/from guest")]
|
|
716
|
+
if "agent:".startswith(incomplete)
|
|
717
|
+
else []
|
|
718
|
+
) + local_paths(incomplete)
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
@cli.command(
|
|
722
|
+
help=runtime_help(
|
|
723
|
+
"agent",
|
|
724
|
+
note=(
|
|
725
|
+
"Omit NAME to use the selected or only workspace. "
|
|
726
|
+
"Use 'caisson runtime' for VM maintenance."
|
|
727
|
+
),
|
|
728
|
+
),
|
|
729
|
+
)
|
|
730
|
+
@click.argument("name", required=False, shell_complete=workspace_completions)
|
|
731
|
+
@click.option("--directory", help=runtime_option_help("agent", "--directory"))
|
|
732
|
+
@click.pass_obj
|
|
733
|
+
def agent(state, name, directory):
|
|
734
|
+
if not sys.stdin.isatty() or not sys.stdout.isatty():
|
|
735
|
+
raise click.UsageError("agent requires an interactive terminal; use exec for scripts")
|
|
736
|
+
hints = []
|
|
737
|
+
for env_name in ("COLORTERM", "TERM_PROGRAM", "TERM_PROGRAM_VERSION"):
|
|
738
|
+
value = os.environ.get(env_name, "")
|
|
739
|
+
if re.fullmatch(r"[A-Za-z0-9._-]{1,64}", value):
|
|
740
|
+
hints.append(f"{env_name}={value}")
|
|
741
|
+
args = ["env", *hints, "agentctl", "agent"]
|
|
742
|
+
if directory:
|
|
743
|
+
args += ["--directory", directory]
|
|
744
|
+
workstation_exec(state, name, args, tty=True)
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
@cli.group(cls=UXGroup)
|
|
748
|
+
def runtime():
|
|
749
|
+
"""Inspect and maintain the workspace's VM and proxy."""
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
@cli.group(cls=UXGroup)
|
|
753
|
+
def logs():
|
|
754
|
+
"""Read VM console or proxy traffic logs."""
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
RUNTIME_COMMANDS = {"status", "up", "down", "disk-grow", "version"}
|
|
758
|
+
LOG_COMMANDS = {"logs": "vm", "proxy-logs": "proxy"}
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
for _usage, _help in load_manifest()["commands"]:
|
|
762
|
+
_name = _usage.split()[0]
|
|
763
|
+
# Copy paths are host-local in agentctl, not laptop-local. Don't expose a trap.
|
|
764
|
+
if _name in {"copy-to", "copy-from", "shell", "agent", "pair"}:
|
|
765
|
+
continue
|
|
766
|
+
_schema = load_manifest()["groups"].get(_name) or load_manifest()["runtime"][_name]
|
|
767
|
+
_command = remote_tree([_name], _help, workstation_exec, _schema)
|
|
768
|
+
if _name in LOG_COMMANDS:
|
|
769
|
+
logs.add_command(_command, LOG_COMMANDS[_name])
|
|
770
|
+
elif _name in RUNTIME_COMMANDS:
|
|
771
|
+
runtime.add_command(_command)
|
|
772
|
+
else:
|
|
773
|
+
cli.add_command(_command)
|
|
774
|
+
|
|
775
|
+
add_version_commands(cli, "caisson")
|
|
776
|
+
|
|
777
|
+
cli.help_sections = {
|
|
778
|
+
"Start here": ["new", "ls", "use", "shell", "web"],
|
|
779
|
+
"Workspaces": ["start", "stop", "rebuild", "status", "enroll", "destroy"],
|
|
780
|
+
"Files & ports": ["copy-to", "copy-from", "forward"],
|
|
781
|
+
"Agent tools": ["agent", "switch-agent", "tool", "package", "allowlist", "creds", "pair"],
|
|
782
|
+
"Advanced": ["exec", "logs", "runtime", "host-shell", "config", "version"],
|
|
783
|
+
}
|
|
784
|
+
cli.hidden_aliases = {"agent-shell", "scp"}
|
|
785
|
+
cli.help_on_empty = False
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def main():
|
|
789
|
+
run_cli(cli)
|