lima-ai 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.
lima_ai/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """lima-ai: disposable Lima VMs for parallel Claude Code agents."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("lima-ai")
lima_ai/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from lima_ai.cli import main
2
+
3
+ main()
lima_ai/auth.py ADDED
@@ -0,0 +1,33 @@
1
+ import os
2
+
3
+ from lima_ai.config import config_dir
4
+ from lima_ai.errors import LimaAiError
5
+ from lima_ai.runner import Runner
6
+
7
+
8
+ def token_path():
9
+ return config_dir() / "oauth-token"
10
+
11
+
12
+ def read_token() -> str:
13
+ path = token_path()
14
+ if not path.is_file():
15
+ raise LimaAiError("auth", f"no Claude token at {path}; run `lima-ai auth` first")
16
+ return path.read_text().strip()
17
+
18
+
19
+ def write_token(token: str) -> None:
20
+ token = token.strip()
21
+ if not token or any(char.isspace() for char in token):
22
+ raise LimaAiError("auth", "the token must be a single non-empty word")
23
+ path = token_path()
24
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
25
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
26
+ with os.fdopen(fd, "w") as f:
27
+ f.write(token + "\n")
28
+ path.chmod(0o600)
29
+
30
+
31
+ def run_setup_token(runner: Runner) -> None:
32
+ """`claude setup-token` prints a long-lived OAuth token for the Max subscription."""
33
+ runner.run(["claude", "setup-token"], interactive=True, step="auth")
lima_ai/backup.py ADDED
@@ -0,0 +1,284 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import shlex
5
+ from collections.abc import Callable, Sequence
6
+ from datetime import UTC, datetime
7
+ from pathlib import Path
8
+
9
+ import click
10
+
11
+ from lima_ai.config import Config
12
+ from lima_ai.errors import LimaAiError
13
+ from lima_ai.instance import Feature, note
14
+
15
+ GUEST_BACKUPS = "/backups/docker"
16
+
17
+ # The files plain `docker compose` loads from a project root, in precedence
18
+ # order (observed with Docker Compose 5.5.1).
19
+ COMPOSE_NAMES = ("compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml")
20
+ OVERRIDE_NAMES = (
21
+ "compose.override.yml",
22
+ "compose.override.yaml",
23
+ "docker-compose.override.yml",
24
+ "docker-compose.override.yaml",
25
+ )
26
+
27
+
28
+ def parse_dotenv(text: str) -> dict[str, str]:
29
+ """KEY=VALUE lines the way compose reads .env: export prefix, quotes, ` #` comments."""
30
+ env = {}
31
+ for raw in text.splitlines():
32
+ line = raw.strip()
33
+ if not line or line.startswith("#"):
34
+ continue
35
+ if line.startswith("export "):
36
+ line = line.removeprefix("export ").lstrip()
37
+ key, sep, value = line.partition("=")
38
+ if not sep:
39
+ continue
40
+ value = value.strip()
41
+ if value[:1] in ("'", '"') and value.find(value[0], 1) != -1:
42
+ value = value[1 : value.find(value[0], 1)]
43
+ else:
44
+ value = re.split(r"\s+#", value, maxsplit=1)[0].rstrip()
45
+ env[key.strip()] = value
46
+ return env
47
+
48
+
49
+ def detect_compose_files(names: set[str], dotenv: str | None) -> list[str]:
50
+ """Compose files, relative to the project root, that `docker compose` would load there."""
51
+ env = parse_dotenv(dotenv) if dotenv else {}
52
+ if env.get("COMPOSE_FILE"):
53
+ separator = env.get("COMPOSE_PATH_SEPARATOR") or ":"
54
+ return [name for name in env["COMPOSE_FILE"].split(separator) if name]
55
+ main = next((name for name in COMPOSE_NAMES if name in names), None)
56
+ if main is None:
57
+ return []
58
+ override = next((name for name in OVERRIDE_NAMES if name in names), None)
59
+ return [main, override] if override else [main]
60
+
61
+
62
+ def compose_files(
63
+ explicit: Sequence[str], names: set[str], dotenv: str | None, required: bool, where: str
64
+ ) -> list[str]:
65
+ """--compose-file values if given, else detection; an error when required and none is found."""
66
+ files = list(explicit) or detect_compose_files(names, dotenv)
67
+ if required and not files:
68
+ raise LimaAiError(
69
+ "compose files",
70
+ f"no compose file found in {where}; pass --compose-file FILE, or use --full "
71
+ "to back up the whole Docker daemon",
72
+ )
73
+ return files
74
+
75
+
76
+ def backup_name(slug: str, feat: str, full: bool, now: datetime | None = None) -> str:
77
+ stamp = (now or datetime.now(UTC)).strftime("%Y%m%dT%H%M%SZ")
78
+ return f"{slug}-{feat}-full-{stamp}" if full else f"{slug}-{feat}-{stamp}"
79
+
80
+
81
+ def backup_argv(files: list[str], dest: str, full: bool, no_images: bool, no_external: bool) -> list[str]:
82
+ argv = ["docker-backup", "backup"]
83
+ if not full:
84
+ argv += ["--from-docker-compose", ",".join(files)]
85
+ if no_images:
86
+ argv.append("--no-images")
87
+ if no_external and not full:
88
+ argv.append("--no-external")
89
+ return [*argv, dest]
90
+
91
+
92
+ def restore_argv(files: list[str], source: str, overwrite: bool) -> list[str]:
93
+ """Never --yes: docker-backup's preview and prompt are the confirmation."""
94
+ argv = ["docker-backup", "restore"]
95
+ if files:
96
+ argv += ["--from-docker-compose", ",".join(files)]
97
+ argv.append(source)
98
+ return [*argv, "--overwrite"] if overwrite else argv
99
+
100
+
101
+ def compose_argv(files: list[str], *command: str) -> list[str]:
102
+ return ["docker", "compose", *[arg for name in files for arg in ("-f", name)], *command]
103
+
104
+
105
+ def _display(path: Path) -> str:
106
+ """A host path for copy-pasting: ~-relative when under the home folder, shell-quoted."""
107
+ try:
108
+ return "~/" + shlex.quote(path.relative_to(Path.home()).as_posix())
109
+ except ValueError:
110
+ return shlex.quote(str(path))
111
+
112
+
113
+ def host_commands(
114
+ cfg: Config, project: str, files: list[str], explicit: bool, name: str, full: bool, no_external: bool
115
+ ) -> list[str]:
116
+ """Commands (printed, never run) that restore a backup into the host's Colima."""
117
+ source = _display(cfg.backups_dir / name)
118
+ compose = shlex.join(compose_argv(files)) if explicit else "docker compose"
119
+ if full:
120
+ restore = f"docker-backup restore {source}"
121
+ overwrite_comment = "replaces every volume in the backup that exists on the host"
122
+ else:
123
+ restore = f"docker-backup restore --from-docker-compose {shlex.quote(','.join(files))} {source}"
124
+ overwrite_comment = "replaces this project's existing volumes"
125
+ lines = [
126
+ f"cd {_display(cfg.developer_dir / project)}",
127
+ f"{compose} stop",
128
+ f"docker-backup info {source}",
129
+ f"{restore} # new volumes only",
130
+ f"{restore} --overwrite # {overwrite_comment}",
131
+ f"{compose} up -d",
132
+ ]
133
+ if full:
134
+ lines.append(
135
+ "# Note: with a full backup, --overwrite replaces every volume in its manifest that "
136
+ "already exists on the host, whatever project it belongs to."
137
+ )
138
+ elif not no_external:
139
+ lines.append(
140
+ "# Note: --overwrite also replaces the project's external volumes, which on the host "
141
+ "may be shared with other projects; back up with --no-external to leave them out."
142
+ )
143
+ return lines
144
+
145
+
146
+ def resolve_backup(cfg: Config, arg: str) -> tuple[Path, str]:
147
+ """A backup given as a host path or relative to backups_dir → (host path, guest path)."""
148
+ path = Path(arg).expanduser()
149
+ if not path.is_absolute():
150
+ path = cfg.backups_dir / path
151
+ path = Path(os.path.normpath(path))
152
+ try:
153
+ relative = path.relative_to(os.path.normpath(cfg.backups_dir))
154
+ except ValueError:
155
+ raise LimaAiError("restore", f"the backup must be inside {cfg.backups_dir} (got {arg})") from None
156
+ if relative == Path("."):
157
+ raise LimaAiError("restore", f"{arg} is the backups folder itself; name a backup inside it")
158
+ if not path.exists():
159
+ raise LimaAiError("restore", f"backup not found: {path}")
160
+ return path, f"{GUEST_BACKUPS}/{relative.as_posix()}"
161
+
162
+
163
+ def _guest_listing(feature: Feature) -> tuple[set[str], str | None]:
164
+ """Top-level names in the VM's working copy, and its .env if there is one."""
165
+ out = feature.shell(["ls", "-1A"], workdir=feature.workdir, step="compose files").stdout
166
+ names = set(out.splitlines())
167
+ dotenv = None
168
+ if ".env" in names:
169
+ dotenv = feature.shell(["cat", ".env"], workdir=feature.workdir, step="compose files").stdout
170
+ return names, dotenv
171
+
172
+
173
+ def _host_listing(root: Path) -> tuple[set[str], str | None]:
174
+ if not root.is_dir():
175
+ return set(), None
176
+ names = {path.name for path in root.iterdir() if path.is_file()}
177
+ dotenv = (root / ".env").read_text() if ".env" in names else None
178
+ return names, dotenv
179
+
180
+
181
+ def run_backup(feature: Feature, full: bool, no_images: bool, no_external: bool, explicit: Sequence[str]) -> None:
182
+ if full and (no_external or explicit):
183
+ raise LimaAiError("backup", "--no-external and --compose-file cannot be combined with --full")
184
+ feature.running_instance()
185
+ names, dotenv = _guest_listing(feature)
186
+ where = f"the VM's ~/{feature.names.workdir}"
187
+ files = compose_files(explicit, names, dotenv, required=not full, where=where)
188
+ name = backup_name(feature.names.slug, feature.names.feat, full)
189
+ dest = f"{GUEST_BACKUPS}/{name}"
190
+
191
+ def in_vm(argv: list[str], **kwargs):
192
+ return feature.shell(argv, workdir=feature.workdir, **kwargs)
193
+
194
+ if files:
195
+ note("==> Stopping the compose stack (volumes are read live)")
196
+ in_vm(compose_argv(files, "stop"), step="compose stop")
197
+ else:
198
+ note("Note: no compose file, so no stack to stop; running containers' volumes are read live.")
199
+ try:
200
+ in_vm(backup_argv(files, dest, full, no_images, no_external), interactive=True, step="backup")
201
+ finally:
202
+ if files:
203
+ note("==> Starting the compose stack again")
204
+ in_vm(compose_argv(files, "start"), step="compose start")
205
+ in_vm(["docker-backup", "info", dest], interactive=True, step="backup info")
206
+
207
+ host_files = list(explicit)
208
+ if not host_files:
209
+ host_names, host_dotenv = _host_listing(feature.cfg.developer_dir / feature.names.project)
210
+ host_files = detect_compose_files(host_names, host_dotenv) or files
211
+ click.echo(f"\nBackup written to {feature.cfg.backups_dir / name}")
212
+ click.echo("To bring it into the host's Colima:")
213
+ for line in host_commands(feature.cfg, feature.names.project, host_files, bool(explicit), name, full, no_external):
214
+ click.echo(f" {line}")
215
+
216
+
217
+ def run_restore(feature: Feature, backup: str, overwrite: bool, full: bool, explicit: Sequence[str]) -> None:
218
+ if full and explicit:
219
+ raise LimaAiError("restore", "--compose-file cannot be combined with --full")
220
+ _, source = resolve_backup(feature.cfg, backup)
221
+ feature.running_instance()
222
+
223
+ def in_vm(argv: list[str], **kwargs):
224
+ return feature.shell(argv, workdir=feature.workdir, **kwargs)
225
+
226
+ info = in_vm(["docker-backup", "info", "--json", source], step="backup info")
227
+ try:
228
+ manifest = json.loads(info.stdout)
229
+ except json.JSONDecodeError:
230
+ manifest = {}
231
+ if isinstance(manifest, dict) and manifest.get("type") == "volume":
232
+ raise LimaAiError(
233
+ "restore",
234
+ f"{backup} is a single-volume archive, which lima-ai does not restore. Restore it by hand: "
235
+ f"`{feature.hint('shell')}`, then `docker-backup restore-volume {source} [--as NAME]`",
236
+ )
237
+ in_vm(["docker-backup", "info", source], interactive=True, step="backup info")
238
+
239
+ if overwrite:
240
+ click.confirm(
241
+ "--overwrite: every volume the project uses that already exists in the VM, external ones "
242
+ "included, will be emptied and refilled from the backup. Continue?",
243
+ abort=True,
244
+ err=True,
245
+ )
246
+ names, dotenv = _guest_listing(feature)
247
+ stack = compose_files(explicit, names, dotenv, required=False, where="")
248
+ if stack:
249
+ note("==> Stopping the compose stack")
250
+ in_vm(compose_argv(stack, "stop"), step="compose stop")
251
+ result = in_vm(
252
+ restore_argv([] if full else stack, source, overwrite), interactive=True, check=False, step="restore"
253
+ )
254
+ note(
255
+ 'Note: compose will warn "volume ... was not created by Docker Compose". That is harmless: '
256
+ "restored volumes lack compose labels, and compose mounts the restored data anyway."
257
+ )
258
+ code = result.returncode
259
+ if code == 0:
260
+ if stack:
261
+ note("==> Starting the compose stack")
262
+ in_vm(compose_argv(stack, "up", "-d"), step="compose up")
263
+ click.echo("Restore complete.")
264
+ elif code in (2, 3):
265
+ if stack:
266
+ in_vm(compose_argv(stack, "start"), step="compose start")
267
+ raise LimaAiError(
268
+ "restore",
269
+ f"docker-backup exited {code}, so nothing was changed (declined at the prompt, nothing for "
270
+ "this project in the backup, or docker/compose unavailable); the stack was started again",
271
+ )
272
+ else:
273
+ raise LimaAiError(
274
+ "restore",
275
+ f"docker-backup exited {code}: an item failed part-way. A volume created or emptied before "
276
+ "the failure may be partly filled; rerun with --overwrite to refill it. "
277
+ "The compose stack is left stopped.",
278
+ )
279
+
280
+
281
+ def restore_step(feature: Feature, backup: str) -> Callable[[], None]:
282
+ """`new --restore`: check the backup path now, restore (never --overwrite) once the VM is ready."""
283
+ resolve_backup(feature.cfg, backup)
284
+ return lambda: run_restore(feature, backup, overwrite=False, full=False, explicit=())
lima_ai/base.py ADDED
@@ -0,0 +1,38 @@
1
+ import click
2
+
3
+ from lima_ai.config import Config, state_dir
4
+ from lima_ai.errors import LimaAiError
5
+ from lima_ai.limactl import Limactl
6
+ from lima_ai.naming import BASE_INSTANCE
7
+ from lima_ai.render import guest_script, render_base
8
+ from lima_ai.runner import Runner
9
+
10
+
11
+ def build(cfg: Config, runner: Runner, rebuild: bool) -> None:
12
+ """Build, verify and seal the golden dev-base VM that features are cloned from."""
13
+ lima = Limactl(runner)
14
+ template = render_base(cfg, state_dir() / "base")
15
+ if lima.get(BASE_INSTANCE):
16
+ if not rebuild:
17
+ raise LimaAiError("base", f"{BASE_INSTANCE} is already built; use --rebuild to replace it")
18
+ click.echo(f"==> Deleting the old {BASE_INSTANCE}", err=True)
19
+ lima.delete(BASE_INSTANCE)
20
+ cfg.backups_dir.mkdir(parents=True, exist_ok=True)
21
+
22
+ click.echo(f"==> Creating {BASE_INSTANCE} (provisioning takes several minutes)", err=True)
23
+ lima.create_and_start(BASE_INSTANCE, template)
24
+
25
+ click.echo("==> Verifying the toolchain", err=True)
26
+ try:
27
+ lima.shell(BASE_INSTANCE, ["bash", "-c", guest_script("verify-base.sh")], step="verify-base")
28
+ except LimaAiError as err:
29
+ raise LimaAiError(
30
+ "verify-base",
31
+ f"{err.message}. {BASE_INSTANCE} is left running for inspection: limactl shell {BASE_INSTANCE}",
32
+ err.stderr_tail,
33
+ ) from None
34
+
35
+ click.echo("==> Sealing and stopping", err=True)
36
+ lima.shell(BASE_INSTANCE, ["sudo", "bash", "-c", guest_script("seal-base.sh")], step="seal-base")
37
+ lima.stop(BASE_INSTANCE)
38
+ click.echo(f"{BASE_INSTANCE} is ready. Create a feature VM with: lima-ai new <project> <feat>")
@@ -0,0 +1,125 @@
1
+ import copy
2
+ import json
3
+ import re
4
+ import tempfile
5
+ from pathlib import Path
6
+
7
+ import click
8
+
9
+ from lima_ai.errors import LimaAiError
10
+ from lima_ai.limactl import Instance
11
+ from lima_ai.runner import Runner
12
+ from lima_ai.sync import rsync_argv, ssh_host
13
+
14
+ # What is copied from the host ~/.claude; everything else (history, projects,
15
+ # sessions, caches, credentials, ...) stays on the host.
16
+ INCLUDE_FILES = ("CLAUDE.md", "RTK.md", "settings.json", "statusline-command.sh")
17
+ INCLUDE_DIRS = ("skills", "plugins", "commands", "agents")
18
+ INCLUDE = INCLUDE_FILES + INCLUDE_DIRS
19
+
20
+ # Characters that end a path inside a shell command.
21
+ _PATH_CHARS = r"[^\s'\";|&()<>]*"
22
+
23
+
24
+ def filter_options() -> list[str]:
25
+ """rsync filters copying the include list, minus the files stage_transformed writes."""
26
+ options = ["--exclude=*.bak", "--exclude=/settings.json", "--exclude=/plugins/*.json"]
27
+ options += [f"--include=/{name}" for name in INCLUDE_FILES]
28
+ for name in INCLUDE_DIRS:
29
+ options += [f"--include=/{name}/", f"--include=/{name}/**"]
30
+ options.append("--exclude=*")
31
+ return options
32
+
33
+
34
+ def _home_relative(path: str, host_home: str) -> str | None:
35
+ prefix = host_home.rstrip("/") + "/"
36
+ if path == host_home.rstrip("/"):
37
+ return ""
38
+ return path[len(prefix) :] if path.startswith(prefix) else None
39
+
40
+
41
+ def _referenced_home_paths(command: str, host_home: str) -> list[str]:
42
+ """Paths under the host home in a command, relative to it (/Users/x/…, ~/…, $HOME/…)."""
43
+ prefixes = rf"{re.escape(host_home.rstrip('/'))}|(?<![\w~])~|\$HOME|\$\{{HOME\}}"
44
+ return [match[1][1:] for match in re.finditer(rf"(?:{prefixes})(/{_PATH_CHARS})", command)]
45
+
46
+
47
+ def _available_in_guest(relative: str, developer_rel: str | None) -> bool:
48
+ parts = relative.split("/")
49
+ if parts[0] == ".claude" and len(parts) > 1 and parts[1] in INCLUDE:
50
+ return True
51
+ if developer_rel and (relative == developer_rel or relative.startswith(developer_rel + "/")):
52
+ return True # mounted read-only at the same path
53
+ return False
54
+
55
+
56
+ def filter_hooks(settings: dict, host_home: str, developer_dir: str) -> dict:
57
+ """Drop hooks that run host-home files the guest will not have; drop what is left empty."""
58
+ result = copy.deepcopy(settings)
59
+ hooks = result.get("hooks")
60
+ if not isinstance(hooks, dict):
61
+ return result
62
+ developer_rel = _home_relative(developer_dir, host_home)
63
+
64
+ def keep(hook: dict) -> bool:
65
+ command = hook.get("command", "")
66
+ return all(_available_in_guest(path, developer_rel) for path in _referenced_home_paths(command, host_home))
67
+
68
+ for event in list(hooks):
69
+ groups = []
70
+ for group in hooks[event]:
71
+ kept = [hook for hook in group.get("hooks", []) if keep(hook)]
72
+ if kept:
73
+ groups.append({**group, "hooks": kept})
74
+ if groups:
75
+ hooks[event] = groups
76
+ else:
77
+ del hooks[event]
78
+ return result
79
+
80
+
81
+ def rewrite_home(text: str, host_home: str, guest_home: str, developer_dir: str) -> str:
82
+ """Host home prefix → guest home, except under developer_dir, which the guest mounts as is."""
83
+ developer_rel = _home_relative(developer_dir, host_home)
84
+ keep = rf"(?!{re.escape(developer_rel)}(?![\w.-]))" if developer_rel else ""
85
+ pattern = re.escape(host_home.rstrip("/") + "/") + keep
86
+ return re.sub(pattern, guest_home.rstrip("/") + "/", text)
87
+
88
+
89
+ def stage_transformed(claude_dir: Path, staging: Path, host_home: str, guest_home: str, developer_dir: str) -> None:
90
+ """Write the transformed settings.json and plugins/*.json into staging."""
91
+ staging.mkdir(parents=True, exist_ok=True)
92
+ settings = claude_dir / "settings.json"
93
+ if settings.is_file():
94
+ try:
95
+ data = json.loads(settings.read_text())
96
+ except json.JSONDecodeError as exc:
97
+ raise LimaAiError("sync-claude", f"{settings} is not valid JSON: {exc}") from None
98
+ text = json.dumps(filter_hooks(data, host_home, developer_dir), indent=2) + "\n"
99
+ target = staging / "settings.json"
100
+ target.write_text(rewrite_home(text, host_home, guest_home, developer_dir))
101
+ target.chmod(0o600)
102
+ plugins = claude_dir / "plugins"
103
+ for source in sorted(plugins.glob("*.json")) if plugins.is_dir() else []:
104
+ target = staging / "plugins" / source.name
105
+ target.parent.mkdir(exist_ok=True)
106
+ target.write_text(rewrite_home(source.read_text(), host_home, guest_home, developer_dir))
107
+
108
+
109
+ def push_claude_config(
110
+ runner: Runner, instance: Instance, guest_home: str, developer_dir: Path, host_home: Path
111
+ ) -> None:
112
+ claude_dir = host_home / ".claude"
113
+ if not claude_dir.is_dir():
114
+ click.echo(f" {claude_dir} not found; skipping Claude config", err=True)
115
+ return
116
+ dest = f"{ssh_host(instance.name)}:.claude/"
117
+ with tempfile.TemporaryDirectory(prefix="lima-ai-claude-") as tmp:
118
+ staging = Path(tmp)
119
+ stage_transformed(claude_dir, staging, str(host_home), guest_home, str(developer_dir))
120
+ # No --delete: sessions and history created in the guest survive re-syncs.
121
+ runner.run(
122
+ rsync_argv([f"{claude_dir}/"], dest, instance.ssh_config, ["--copy-unsafe-links", *filter_options()]),
123
+ step="sync-claude",
124
+ )
125
+ runner.run(rsync_argv([f"{staging}/"], dest, instance.ssh_config, []), step="sync-claude")