kelder 0.0.1__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.
kelder/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ # Copyright (C) 2026 Adam Mercer
3
+ """kelder: run Claude Code in a smolvm guest with host directories attached."""
kelder/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ # Copyright (C) 2026 Adam Mercer
3
+ """Lets a checkout run without installing: PYTHONPATH=src python3 -m kelder."""
4
+ from .cli import main
5
+
6
+ main()
kelder/cli.py ADDED
@@ -0,0 +1,246 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ # Copyright (C) 2026 Adam Mercer
3
+ """The kelder command.
4
+
5
+ Only arguments after `self` are kelder's; everything else goes to
6
+ claude. `kelder -- self ...` gives claude a prompt starting with "self".
7
+
8
+ Each directory is attached at the same path it has on the host and detached
9
+ when the last session using it exits. Only one set of directories is attached
10
+ at a time, so Claude never sees a project it wasn't given; a second session
11
+ for a different set is refused (use VM=<name> to run it in a separate machine).
12
+ """
13
+ import importlib.metadata
14
+ import os
15
+ import re
16
+ import shlex
17
+ import signal
18
+ import subprocess
19
+ import sys
20
+ import time
21
+ from pathlib import Path
22
+
23
+ from . import smolvm
24
+ from .session import Session
25
+ from .smolvm import die, note
26
+
27
+ USAGE = """\
28
+ Usage: kelder [--] [CLAUDE_ARGS...]
29
+ kelder self [-C DIR] [-a DIR]... [--] [CLAUDE_ARGS...]
30
+ kelder self COMMAND
31
+
32
+ Run Claude Code in the smolvm guest with DIR (default: the current
33
+ directory) attached at the same path it has on the host. Only arguments
34
+ after `self` are kelder's own.
35
+
36
+ Options (after self):
37
+ -C DIR attach and start Claude in DIR
38
+ -a DIR also attach DIR and give Claude access to it (repeatable)
39
+ -- end of kelder options; the rest goes to claude
40
+
41
+ Commands (after self):
42
+ help show this help
43
+ setup create and provision the machine (safe to re-run)
44
+ smoketest test the installed smolvm in a throwaway machine
45
+ version show kelder's version
46
+
47
+ Every other argument is passed to claude unchanged; run
48
+ `kelder --help` for Claude Code's options.
49
+
50
+ Environment:
51
+ VM smolvm machine name (default: smol; smol-test for
52
+ self smoketest)
53
+ CLAUDE_STATE Claude's state directory on the host
54
+ (default: ~/.local/share/kelder/claude)
55
+ IMAGE base image for a new machine (self setup;
56
+ default: debian)
57
+ NO_UPDATE 1 skips the weekly package update when a session
58
+ boots the machine
59
+ DRY_RUN 1 prints every smolvm call instead of running it
60
+ """
61
+
62
+ COMMANDS = ("help", "setup", "smoketest", "version")
63
+
64
+ # What runs in the guest. It gets the primary directory, the state directory,
65
+ # the number of extra directories, the extra directories, then claude's
66
+ # arguments. Extra directories are passed as --add-dir=DIR: claude's --add-dir
67
+ # takes several values, and the separate form would swallow a following prompt.
68
+ GUEST_SCRIPT = """
69
+ dir=$1 state=$2 n=$3; shift 3
70
+ extra=("${@:1:n}"); shift "$n"
71
+ for d in "$dir" "${extra[@]}"; do
72
+ mountpoint -q "$d" || { echo "kelder: $d is not attached in the guest" >&2; exit 1; }
73
+ done
74
+ mountpoint -q "$state" || { echo "kelder: Claude state directory is not mounted at $state; run kelder self setup" >&2; exit 1; }
75
+ cd "$dir"
76
+ # An API key or bearer token in the environment outranks the stored login
77
+ # and would silently bill the Console instead of the subscription.
78
+ unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN
79
+ export PATH="$HOME/.local/bin:$PATH" CLAUDE_CONFIG_DIR=$state
80
+ # The session is root but attached directories belong to the host user, so
81
+ # git would refuse them as "dubious ownership". Mark them, and repositories
82
+ # below them, as safe for this session only.
83
+ i=0
84
+ for d in "$dir" "${extra[@]}"; do
85
+ for v in "$d" "$d/*"; do
86
+ export "GIT_CONFIG_KEY_$i=safe.directory" "GIT_CONFIG_VALUE_$i=$v"
87
+ i=$((i + 1))
88
+ done
89
+ done
90
+ export GIT_CONFIG_COUNT=$i
91
+ # The directory is shared with the host, whose .venv points at the host's
92
+ # Python. Give uv in the guest an environment of its own in each project.
93
+ export UV_PROJECT_ENVIRONMENT=.venv-smol
94
+ # uv's cache is on the guest's disk and the environment is in the attached
95
+ # directory, so it can never hard-link between them; copy without warning.
96
+ export UV_LINK_MODE=copy
97
+ command -v claude >/dev/null || { echo "kelder: claude is not installed in the guest; run kelder self setup" >&2; exit 127; }
98
+ exec claude "${extra[@]/#/--add-dir=}" "$@"
99
+ """
100
+
101
+
102
+ def parse_args(args):
103
+ """Split the command line into (command, primary dir, extra dirs, claude's args).
104
+
105
+ command is "run" or one of COMMANDS.
106
+ """
107
+ # Parsed by hand, not with argparse: most of the command line is claude's,
108
+ # and argparse takes every dash argument as its own. It rejects
109
+ # `self -a DIR --resume ID` as an unrecognized option unless claude's
110
+ # arguments always follow `--`, and parse_known_args would keep looking
111
+ # for -C and -a among claude's arguments.
112
+ primary, extra = ".", []
113
+ if args[:1] == ["self"]:
114
+ sub = args[1] if len(args) > 1 else ""
115
+ if sub in COMMANDS:
116
+ return sub, primary, extra, []
117
+ if sub not in ("-C", "-a"):
118
+ die(f"unknown command or option 'self {sub}'; see 'kelder self help'")
119
+ args = args[1:]
120
+ while args:
121
+ if args[0] == "-C":
122
+ if len(args) < 2:
123
+ die("-C needs a directory")
124
+ primary, args = args[1], args[2:]
125
+ elif args[0] == "-a":
126
+ if len(args) < 2:
127
+ die("-a needs a directory")
128
+ extra.append(args[1])
129
+ args = args[2:]
130
+ elif args[0] == "--":
131
+ args = args[1:]
132
+ break
133
+ else:
134
+ break
135
+ elif args[:1] == ["--"]:
136
+ args = args[1:]
137
+ return "run", primary, extra, args
138
+
139
+
140
+ def check_dir(path):
141
+ """Resolve and check a directory to attach; returns its real path."""
142
+ if not os.path.isdir(path):
143
+ die(f"not a directory: {path}")
144
+ d = os.path.realpath(path)
145
+ if d in ("/", os.path.realpath(smolvm.HOME)):
146
+ die(f"won't attach {d}; run kelder from a project directory")
147
+ if ":" in d:
148
+ die("can't attach a path containing ':'")
149
+ state = os.path.realpath(smolvm.CLAUDE_STATE)
150
+ if (d + "/").startswith(state + "/") or (state + "/").startswith(d + "/"):
151
+ die(f"won't attach {d}: it overlaps Claude's state directory {state}")
152
+ return d
153
+
154
+
155
+ def resume_command(dirs, since):
156
+ """The kelder command that resumes the session that just ended, or None.
157
+
158
+ Claude's own hint says `claude --resume ID`, which doesn't work on the
159
+ host. The ID is the name of the newest transcript written since `since`
160
+ in the state directory's folder for the primary directory.
161
+ """
162
+ projects = Path(smolvm.CLAUDE_STATE) / "projects"
163
+ # Claude names the folder after the directory with other characters
164
+ # replaced by "-"; try that and the "/"-only form, whichever exists.
165
+ folders = {re.sub(r"[^A-Za-z0-9]", "-", dirs[0]), dirs[0].replace("/", "-")}
166
+ newest = None
167
+ for folder in folders:
168
+ for transcript in (projects / folder).glob("*.jsonl"):
169
+ try:
170
+ mtime = transcript.stat().st_mtime
171
+ except OSError:
172
+ continue
173
+ if mtime >= since and (newest is None or mtime > newest[0]):
174
+ newest = (mtime, transcript.stem)
175
+ if newest is None:
176
+ return None
177
+ options = []
178
+ if dirs[0] != os.path.realpath("."):
179
+ options += ["-C", dirs[0]]
180
+ for d in dirs[1:]:
181
+ options += ["-a", d]
182
+ command = ["kelder", *(["self", *options, "--"] if options else []), "--resume", newest[1]]
183
+ prefix = f"VM={shlex.quote(smolvm.VM)} " if smolvm.VM != "smol" else ""
184
+ return prefix + shlex.join(command)
185
+
186
+
187
+ def _terminate(signum, _frame):
188
+ """Turn a fatal signal into an exit, so cleanup still runs."""
189
+ sys.exit(128 + signum)
190
+
191
+
192
+ def run_claude(primary, extra, claude_args):
193
+ """Attach the directories, run claude in the guest, clean up; returns its exit status."""
194
+ dirs = [check_dir(primary)]
195
+ for d in extra:
196
+ d = check_dir(d)
197
+ if d not in dirs:
198
+ dirs.append(d)
199
+
200
+ if not smolvm.exists():
201
+ die(f"machine '{smolvm.VM}' does not exist; run 'kelder self setup' first")
202
+
203
+ from . import provision
204
+ session = Session(dirs, on_boot=provision.update_if_stale)
205
+ session.attach()
206
+ signal.signal(signal.SIGTERM, _terminate)
207
+ signal.signal(signal.SIGHUP, _terminate)
208
+ # Let Ctrl-C reach Claude; kelder itself keeps going so cleanup still runs.
209
+ signal.signal(signal.SIGINT, lambda *_: None)
210
+ try:
211
+ # Only ask for a TTY when there is one, so `kelder -p ... | less` and scripts work.
212
+ flags = ["-i"]
213
+ if sys.stdin.isatty() and sys.stdout.isatty():
214
+ flags.append("-t")
215
+ cmd = ["machine", "exec", "--name", smolvm.VM, *flags, "--", "bash", "-c", GUEST_SCRIPT, "_",
216
+ dirs[0], smolvm.GUEST_CLAUDE_STATE, str(len(dirs) - 1), *dirs[1:], *claude_args]
217
+ if smolvm.DRY_RUN:
218
+ return smolvm.run(*cmd)[0]
219
+ started = time.time() - 2 # allow for coarse file timestamps
220
+ rc = subprocess.call([smolvm.SMOLVM_BIN, *cmd])
221
+ if "-t" in flags:
222
+ resume = resume_command(dirs, started)
223
+ if resume:
224
+ note(f"resume with: {resume}")
225
+ return 128 - rc if rc < 0 else rc # negative: killed by a signal
226
+ finally:
227
+ session.cleanup()
228
+
229
+
230
+ def main(argv=None):
231
+ command, primary, extra, claude_args = parse_args(sys.argv[1:] if argv is None else argv)
232
+ if command == "help":
233
+ print(USAGE, end="")
234
+ sys.exit(0)
235
+ if command == "version":
236
+ print("kelder", importlib.metadata.version("kelder"))
237
+ sys.exit(0)
238
+ smolvm.require()
239
+ if command == "setup":
240
+ from . import provision
241
+ provision.run()
242
+ elif command == "smoketest":
243
+ from . import smoketest
244
+ smoketest.run()
245
+ else:
246
+ sys.exit(run_claude(primary, extra, claude_args))
@@ -0,0 +1,7 @@
1
+ # smolvm/libkrun proxies guest sockets to the host (TSI). Inside a container
2
+ # network namespace a *connected* UDP socket can only send one datagram; later
3
+ # sends fail with EINVAL. glibc sends the A and AAAA queries on one socket, so
4
+ # DNS breaks (apt: "Temporary failure resolving"). single-request-reopen makes
5
+ # glibc use a fresh socket for the second query.
6
+ [containers]
7
+ dns_options = ["single-request-reopen"]
kelder/guest/smoketest ADDED
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env bash
2
+ # SPDX-License-Identifier: GPL-3.0-or-later
3
+ # Copyright (C) 2026 Adam Mercer
4
+ #
5
+ # smoketest: check, from inside the guest, the smolvm behaviours kelder
6
+ # relies on. Run it in a throwaway machine after upgrading smolvm:
7
+ #
8
+ # VM=smol-test kelder self setup
9
+ # VM=smol-test kelder then, in that session: smoketest [DIR]
10
+ #
11
+ # DIR is an attached host directory (default: the current directory).
12
+ # PASS/FAIL lines are behaviour kelder needs; KNOWN lines are smolvm bugs
13
+ # the guest config works around; CHANGED lines mean a known bug is gone and its
14
+ # workaround may be removable. Exits non-zero if anything FAILs.
15
+ set -uo pipefail
16
+
17
+ dir=${1:-$PWD}
18
+ image=docker.io/library/python:3-slim
19
+ fails=0
20
+ pass() { printf 'PASS %s\n' "$1"; }
21
+ fail() { printf 'FAIL %s\n' "$1"; fails=$((fails + 1)); }
22
+ known() { printf 'KNOWN %s\n' "$1"; }
23
+ changed() { printf 'CHANGED %s\n' "$1"; }
24
+
25
+ # --- users -------------------------------------------------------------------
26
+ uid=$(id -u)
27
+ if [[ $uid == 0 ]]; then pass "exec session runs as root"
28
+ else fail "exec session runs as uid $uid, expected 0"; fi
29
+
30
+ pid1=$(ps -o uid= -p 1 | tr -d ' ')
31
+ if [[ $pid1 == 0 ]]; then pass "PID 1 runs as root"
32
+ else fail "PID 1 runs as uid $pid1, expected 0"; fi
33
+
34
+ # --- attached directory ownership --------------------------------------------
35
+ if ! tmp=$(mktemp -p "$dir" .smoketest.XXXXXX); then
36
+ fail "cannot create a file in $dir"
37
+ else
38
+ owner=$(stat -c %u "$dir")
39
+ got=$(stat -c %u "$tmp")
40
+ if [[ $got == "$owner" ]]; then
41
+ rm -f "$tmp"
42
+ pass "files root creates in $dir belong to uid $owner, the directory's owner"
43
+ else
44
+ fail "files root creates in $dir belong to uid $got, the directory belongs to uid $owner (kept $tmp)"
45
+ fi
46
+ fi
47
+
48
+ # --- containers --------------------------------------------------------------
49
+ if ! podman pull -q "$image" >/dev/null; then
50
+ fail "cannot pull $image; container checks skipped"
51
+ else
52
+ # A connected UDP socket in a container netns fails on its 2nd send (EINVAL).
53
+ udp='import socket
54
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
55
+ s.connect(("1.1.1.1", 53))
56
+ try:
57
+ s.send(b"x"); s.send(b"x"); print("ok")
58
+ except OSError as e:
59
+ print(e.errno)'
60
+ r=$(podman run --rm "$image" python3 -c "$udp" 2>&1)
61
+ case $r in
62
+ ok) changed "connected UDP in containers works; the TSI bug may be fixed" ;;
63
+ 22) known "connected UDP in containers fails on the 2nd send (EINVAL)" ;;
64
+ *) fail "container UDP check gave: $r" ;;
65
+ esac
66
+
67
+ if podman run --rm "$image" getent ahosts deb.debian.org >/dev/null; then
68
+ pass "container DNS resolves with containers-tsi.conf"
69
+ else
70
+ fail "container DNS fails even with containers-tsi.conf"
71
+ fi
72
+
73
+ override=$(mktemp)
74
+ printf '[containers]\ndns_options = []\n' >"$override"
75
+ if CONTAINERS_CONF_OVERRIDE=$override podman run --rm "$image" \
76
+ getent ahosts deb.debian.org >/dev/null; then
77
+ changed "container DNS works without single-request-reopen; containers-tsi.conf may be removable"
78
+ else
79
+ known "container DNS fails without single-request-reopen"
80
+ fi
81
+ rm -f "$override"
82
+ fi
83
+
84
+ # --- nested VMs --------------------------------------------------------------
85
+ if testvm run -- true; then pass "testvm boots a nested VM"
86
+ else fail "testvm cannot boot a nested VM"; fi
87
+
88
+ echo
89
+ if ((fails)); then echo "$fails check(s) failed"; exit 1; fi
90
+ echo "all checks passed"