liter-llm-cli 2.7.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,353 @@
1
+ # Build output
2
+ /e2e/c/ffi/
3
+ target/
4
+ build/
5
+ dist/
6
+ wheelhouse/
7
+ .gradle/
8
+
9
+ # Git worktrees checked out inside the repo. Untracked-but-not-ignored, poly
10
+ # walks them and reports the worktree's own copies of files as failures, so a
11
+ # single worktree turns `poly fmt --check .` red for reasons unrelated to the
12
+ # tree being checked. ~keep
13
+ .worktrees/
14
+
15
+ # Astro docs-site
16
+ docs-site/dist/
17
+ docs-site/.astro/
18
+ docs-site/node_modules/
19
+
20
+ # Language-specific build artifacts
21
+ *.so
22
+ *.dylib
23
+ *.dll
24
+ *.node
25
+ *.bundle
26
+ *.class
27
+ *.egg-info/
28
+ *$py.class
29
+ *.py[cod]
30
+ *.rs.bk
31
+ *.gem
32
+ *.whl
33
+ *.tar.gz
34
+ *.tsbuildinfo
35
+ *.jar
36
+ *.profraw
37
+ *.o
38
+ *.a
39
+ __pycache__/
40
+ _build/
41
+ .zig-cache/
42
+
43
+ # Python
44
+ .venv/
45
+ .coverage
46
+ .coverage*
47
+ coverage.xml
48
+ coverage.json
49
+ coverage.lcov
50
+ coverage.out
51
+ coverage/
52
+ htmlcov/
53
+ .pytest_cache/
54
+ .ruff_cache/
55
+ .hypothesis/
56
+ .python-version
57
+
58
+ # Node.js
59
+ node_modules/
60
+ npm-debug.log*
61
+ pnpm-debug.log*
62
+ yarn-debug.log*
63
+ yarn-error.log*
64
+
65
+ # Rust
66
+ rust-coverage.lcov
67
+ rust_out
68
+
69
+ # C#/.NET
70
+ **/bin/
71
+ **/obj/
72
+ *.pdb
73
+ *.Cache
74
+ *.cscfg
75
+ *.suo
76
+ *.user
77
+ TestResults/
78
+ packages/csharp/**/runtimes/
79
+
80
+ # Go
81
+ # packages/go/include/liter_llm.h and packages/go/.lib/<platform>/ are tracked:
82
+ # they ship in the Go module git tag so `go get + build` is self-contained.
83
+ # publish-go-module CI job populates .lib/ before creating the packages/go/{tag}.
84
+ # The legacy packages/go/lib/ path (no leading dot) remains ignored.
85
+ packages/go/lib/
86
+ # Unignore the prebuilt shared libs under packages/go/.lib/<platform>/ that the
87
+ # publish workflow bundles into the Go module tag (root *.so/*.dylib/*.dll
88
+ # rules above otherwise hide them from `git add`).
89
+ !packages/go/.lib/**/*.so
90
+ !packages/go/.lib/**/*.dylib
91
+ !packages/go/.lib/**/*.dll
92
+ # Local cargo-build copies the C header into .lib/<platform>/include/ for the Go
93
+ # binding; the canonical tracked header is packages/go/include/liter_llm.h.
94
+ packages/go/.lib/**/include/
95
+ coverage.out
96
+
97
+ # Elixir
98
+ packages/elixir/deps/
99
+ packages/elixir/_build/
100
+ erl_crash.dump
101
+
102
+ # Ruby
103
+ packages/ruby/.bundle/
104
+ packages/ruby/vendor/
105
+ packages/ruby/tmp/
106
+ .yardoc/
107
+
108
+ # PHP
109
+ vendor/
110
+ # Orphaned lockfile — the canonical composer.json/lock live at the repo root.
111
+ packages/php/composer.lock
112
+
113
+ # Java
114
+ .mvn/
115
+
116
+ # R
117
+ .Rhistory
118
+ .RData
119
+
120
+ # WASM
121
+ .wrangler/
122
+ libpdfium.a
123
+
124
+ # E2E build artifacts (generated test projects have their own builds)
125
+ e2e/rust/target/
126
+ e2e/c/test_*
127
+ !e2e/c/test_*.c
128
+ !e2e/c/test_*.h
129
+ e2e/c/*.o
130
+ e2e/c/*.dSYM/
131
+ e2e/python/.venv/
132
+ e2e/python/__pycache__/
133
+ e2e/dart/.dart_tool/
134
+ e2e/go/go.sum
135
+ e2e/ruby/.bundle/
136
+ e2e/ruby/vendor/
137
+ e2e/typescript/node_modules/
138
+ e2e/wasm/node_modules/
139
+ e2e/java/target/
140
+ e2e/csharp/bin/
141
+ e2e/csharp/obj/
142
+ e2e/elixir/deps/
143
+ e2e/elixir/_build/
144
+ e2e/php/vendor/
145
+ e2e/php/php-liter-llm.ini
146
+
147
+ # Swift Package Manager
148
+ **/.build/
149
+ **/.swiftpm/
150
+ **/*.xcodeproj/xcuserdata/
151
+
152
+ # Dart pub (test_apps)
153
+ test_apps/dart/.dart_tool/
154
+ test_apps/dart/.packages
155
+ test_apps/dart/pubspec.lock
156
+
157
+ # Install state for test_apps trees — alef regenerates the source manifests,
158
+ # but lockfiles and downloaded deps belong to the running install, not the
159
+ # checked-in tree. Each `verify-install` run pulls fresh from registries.
160
+ test_apps/*/node_modules/
161
+ test_apps/*/pnpm-lock.yaml
162
+ test_apps/*/vendor/
163
+ test_apps/*/composer.lock
164
+ test_apps/*/Gemfile.lock
165
+ test_apps/*/.bundle/
166
+ test_apps/*/.venv/
167
+ test_apps/*/deps/
168
+ test_apps/*/mix.lock
169
+ test_apps/*/.gradle/
170
+ test_apps/*/build/
171
+ test_apps/*/.dart_tool/
172
+ test_apps/*/.pub-cache/
173
+ test_apps/*/target/
174
+ test_apps/*/bin/
175
+ test_apps/*/obj/
176
+ test_apps/*/.swiftpm/
177
+ test_apps/*/.build/
178
+
179
+ # C FFI test binaries
180
+ crates/liter-llm-ffi/tests/c/test_*
181
+ !crates/liter-llm-ffi/tests/c/test_*.c
182
+ crates/liter-llm-ffi/tests/c/*.o
183
+ crates/liter-llm-ffi/tests/c/*.dSYM/
184
+
185
+ # NAPI-RS generated files (both index.js and index.d.ts are committed for npm packaging)
186
+
187
+ # Transient lockfiles produced when alef runs package managers inside crate
188
+ # source dirs during `mise run update`/`mise run upgrade`. Canonical lockfiles live
189
+ # under packages/<lang>/.
190
+ crates/liter-llm-py/src/uv.lock
191
+ crates/liter-llm-php/src/composer.lock
192
+
193
+ # Generated pkg-config files
194
+ *.pc
195
+
196
+ # IDE / OS
197
+ .DS_store
198
+ .idea/
199
+ .vscode/
200
+ .run/
201
+ *.bak
202
+ *.log
203
+ *.temp
204
+ *.tmp
205
+
206
+ # Environment
207
+ .env
208
+ requirements.txt
209
+
210
+ # AI assistant config (generated by ai-rulez)
211
+ CLAUDE.md
212
+ .claude/
213
+ .cursor/
214
+ .cursorrules
215
+ .gemini/
216
+ .windsurf/
217
+ .windsurfrules
218
+ .codex/
219
+ .mcp.json
220
+ # plugin/.mcp.json is an ai-rulez-generated plugin bundle (provenance in
221
+ # plugin/.ai-rulez-generated.json) that CI's `ai-rulez verify --plugin` reads;
222
+ # it must be committed like its sibling bundles. ~keep
223
+ !plugin/.mcp.json
224
+ AGENTS.md
225
+ GEMINI.md
226
+
227
+ # Lychee link checker cache
228
+ .lycheecache
229
+
230
+ # Misc
231
+ .cache/
232
+ .benchmarks/
233
+ site/
234
+ todo.md
235
+ [Tt][Oo][Dd][Oo]*
236
+ .tmp/
237
+ *temp/
238
+ .artifacts/
239
+ .remote-cache/
240
+ .pnpm-store/
241
+ .env*
242
+ .alef/
243
+ .polylint/
244
+ *.pyd
245
+ .gems/
246
+ vendor/bundle/
247
+ *.h.bak
248
+ *.test
249
+ bin/
250
+ # cli-proxy ships a hand-written launcher under bin/ — keep it tracked despite the broad bin/ rule.
251
+ !cli-proxy/npm/bin/
252
+ # alef generates packages/dart/bin/download_libs.dart; the broad bin/ rule above would
253
+ # discard it after every regen, so the freshness gate can never go green without this.
254
+ !packages/dart/bin/
255
+ obj/
256
+ *.nupkg
257
+ pkg/
258
+ packages/php/var/
259
+
260
+ test_apps/zig/zig-pkg/
261
+
262
+ # Swift artifact bundle downloaded by test_apps/swift_e2e/download_swift_artifact.sh
263
+ test_apps/swift_e2e/*.artifactbundle.zip
264
+
265
+ # Kotlin compiler daemon sessions
266
+ **/.kotlin/
267
+ .kotlin/
268
+
269
+ .playwright-mcp/
270
+
271
+
272
+ # basemind local index cache
273
+ .basemind/
274
+
275
+
276
+ # Alef-generated skills are source-controlled; other agent-local state stays ignored.
277
+ !.codex/
278
+ .codex/*
279
+ !.codex/skills/
280
+ .codex/skills/*
281
+ !.codex/skills/api/
282
+ !.codex/skills/api/SKILL.md
283
+ !.codex/skills/cli/
284
+ !.codex/skills/cli/SKILL.md
285
+ !.codex/skills/mcp/
286
+ !.codex/skills/mcp/SKILL.md
287
+ !.agents/
288
+ .agents/*
289
+ !.agents/skills/
290
+ .agents/skills/*
291
+ !.agents/skills/api/
292
+ !.agents/skills/api/SKILL.md
293
+ !.agents/skills/cli/
294
+ !.agents/skills/cli/SKILL.md
295
+ !.agents/skills/mcp/
296
+ !.agents/skills/mcp/SKILL.md
297
+ !.agents/plugins/
298
+ !.agents/plugins/marketplace.json
299
+ !.claude/
300
+ .claude/*
301
+ !.claude/skills/
302
+ .claude/skills/*
303
+ !.claude/skills/api/
304
+ !.claude/skills/api/SKILL.md
305
+ !.claude/skills/cli/
306
+ !.claude/skills/cli/SKILL.md
307
+ !.claude/skills/mcp/
308
+ !.claude/skills/mcp/SKILL.md
309
+
310
+ poly.local.toml
311
+
312
+ # Alef snippet validator scratch workspaces and caches ~keep
313
+ **/.alef-snippet-*/
314
+ **/.alef-cache/
315
+ **/.alef/
316
+
317
+ # BEGIN ai-rulez (DO NOT EDIT - managed by ai-rulez)
318
+ .ai-rulez/.config.local.*
319
+ .ai-rulez/.generated-manifest.json
320
+ .opencode/agents/
321
+ .opencode/commands/
322
+ /opencode.json
323
+ # END ai-rulez
324
+
325
+ # ~keep Alef verifies these generated wrapper artifacts in fresh checkouts.
326
+ !packages/kotlin-android/gradle/wrapper/gradle-wrapper.jar
327
+ !test_apps/kotlin_android/gradle/wrapper/gradle-wrapper.jar
328
+ !e2e/java/.mvn/
329
+ e2e/java/.mvn/*
330
+ !e2e/java/.mvn/wrapper/
331
+ e2e/java/.mvn/wrapper/*
332
+ !e2e/java/.mvn/wrapper/maven-wrapper.properties
333
+ !test_apps/java/.mvn/
334
+ test_apps/java/.mvn/*
335
+ !test_apps/java/.mvn/wrapper/
336
+ test_apps/java/.mvn/wrapper/*
337
+ !test_apps/java/.mvn/wrapper/maven-wrapper.properties
338
+
339
+ !test_apps/node/pnpm-lock.yaml
340
+ !test_apps/wasm/pnpm-lock.yaml
341
+
342
+ # Agent harness output outside the ai-rulez managed block: the machine-local overlay,
343
+ # plugin-root manifests, and presets this repository does not enable.
344
+ .ai-rulez/config.local.*
345
+ .ai-rulez/local/
346
+ **/.ai-rulez/.generated-manifest.local.json
347
+ plugin/.ai-rulez/.generated-manifest.json
348
+ .agents/settings.json
349
+ .claude/settings.json
350
+ .claude/plugins.json
351
+ .codex/commands/
352
+ .codex/plugins.json
353
+ .github/commands/
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.5
2
+ Name: liter-llm-cli
3
+ Version: 2.7.4
4
+ Summary: CLI proxy for liter-llm — downloads and runs the native liter-llm binary from GitHub releases.
5
+ Project-URL: Homepage, https://github.com/xberg-io/liter-llm
6
+ Project-URL: Issues, https://github.com/xberg-io/liter-llm/issues
7
+ Project-URL: Repository, https://github.com/xberg-io/liter-llm.git
8
+ Author-email: Na'aman Hirschfeld <naaman@xberg.io>, Tobias Perlstein <tobias@xberg.io>
9
+ Maintainer-email: Na'aman Hirschfeld <naaman@xberg.io>, Tobias Perlstein <tobias@xberg.io>
10
+ License: MIT
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+
23
+ # liter-llm-cli
24
+
25
+ CLI proxy for [`liter-llm`](https://github.com/xberg-io/liter-llm). Installing
26
+ this package provides a `liter-llm` command.
27
+
28
+ The package version always equals the `liter-llm` release it carries. Platform
29
+ wheels bundle the native binary; the source distribution instead downloads
30
+ exactly `liter-llm-<version>-<target>` from the matching `v<version>` GitHub
31
+ release and verifies it against `SHA256SUMS-<version>.txt` before running it.
32
+ Set `LITER_LLM_BINARY` to run a binary you already have.
@@ -0,0 +1,10 @@
1
+ # liter-llm-cli
2
+
3
+ CLI proxy for [`liter-llm`](https://github.com/xberg-io/liter-llm). Installing
4
+ this package provides a `liter-llm` command.
5
+
6
+ The package version always equals the `liter-llm` release it carries. Platform
7
+ wheels bundle the native binary; the source distribution instead downloads
8
+ exactly `liter-llm-<version>-<target>` from the matching `v<version>` GitHub
9
+ release and verifies it against `SHA256SUMS-<version>.txt` before running it.
10
+ Set `LITER_LLM_BINARY` to run a binary you already have.
@@ -0,0 +1,133 @@
1
+ """Custom hatchling build hook that bundles the native liter-llm binary into a wheel.
2
+
3
+ When building a platform-specific wheel in CI, the target triple is supplied via
4
+ the ``LITER_LLM_CLI_TARGET`` env var. The matching ``liter-llm-cli-<target>.tar.gz`` /
5
+ ``.zip`` (the release archive, staged under that name by the publish workflow) is
6
+ located in the repo root or ``dist/``, the binary is extracted into
7
+ ``liter_llm_cli/bin/<target>/``, force-included in the wheel, and the wheel is
8
+ tagged for that platform so PyPI serves the right artifact.
9
+
10
+ If no target is set (the sdist build, or a local build), the hook is a no-op and the
11
+ package falls back to the pinned, checksum-verified runtime downloader in
12
+ ``liter_llm_cli/downloader.py``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import shutil
19
+ import tarfile
20
+ import zipfile
21
+ from pathlib import Path
22
+
23
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
24
+
25
+ # ~keep The linux binaries are built on ubuntu-latest and import GLIBC_2.39 symbols, so the honest
26
+ # manylinux floor is 2_39. A 2_28 tag would let pip install a wheel that fails to start on older glibc.
27
+ _TAG_MAP = {
28
+ "x86_64-pc-windows-msvc": "win_amd64",
29
+ "x86_64-unknown-linux-gnu": "manylinux_2_39_x86_64",
30
+ "aarch64-unknown-linux-gnu": "manylinux_2_39_aarch64",
31
+ "aarch64-apple-darwin": "macosx_15_0_arm64",
32
+ }
33
+
34
+
35
+ def _safe_destination(root: Path, member_name: str) -> Path:
36
+ """Resolve an archive member path and require it to stay under root."""
37
+ root = root.resolve()
38
+ target = (root / member_name.replace("\\", "/")).resolve(strict=False)
39
+ if target != root and not target.is_relative_to(root):
40
+ raise RuntimeError(f"archive member escapes extraction directory: {member_name}")
41
+ return target
42
+
43
+
44
+ def _extract_zip_bounded(archive: Path, extract_dir: Path) -> None:
45
+ """Extract zip entries after bounding each destination path."""
46
+ with zipfile.ZipFile(archive) as zf:
47
+ for member in zf.infolist():
48
+ target = _safe_destination(extract_dir, member.filename)
49
+ if member.is_dir():
50
+ target.mkdir(parents=True, exist_ok=True)
51
+ continue
52
+
53
+ target.parent.mkdir(parents=True, exist_ok=True)
54
+ with zf.open(member) as source, target.open("wb") as destination:
55
+ shutil.copyfileobj(source, destination)
56
+
57
+
58
+ def _extract_tar_bounded(archive: Path, extract_dir: Path) -> None:
59
+ """Extract regular tar entries after bounding each destination path."""
60
+ with tarfile.open(archive, "r:gz") as tf:
61
+ for member in tf.getmembers():
62
+ target = _safe_destination(extract_dir, member.name)
63
+ if member.isdir():
64
+ target.mkdir(parents=True, exist_ok=True)
65
+ continue
66
+ if not member.isfile():
67
+ raise RuntimeError(f"unsupported archive member type: {member.name}")
68
+
69
+ target.parent.mkdir(parents=True, exist_ok=True)
70
+ source = tf.extractfile(member)
71
+ if source is None:
72
+ raise RuntimeError(f"could not read archive member: {member.name}")
73
+ with source, target.open("wb") as destination:
74
+ shutil.copyfileobj(source, destination)
75
+
76
+
77
+ class CustomBuildHook(BuildHookInterface):
78
+ """Inject the matching native binary into a platform-tagged wheel."""
79
+
80
+ PLUGIN_NAME = "custom"
81
+
82
+ def initialize(self, version: str, build_data: dict) -> None: # noqa: ARG002
83
+ """Bundle a staged native binary when building a targeted wheel."""
84
+ target = os.environ.get("LITER_LLM_CLI_TARGET", "").strip()
85
+ if not target:
86
+ return
87
+
88
+ wheel_tag = _TAG_MAP.get(target)
89
+ if wheel_tag is None:
90
+ raise RuntimeError(f"no wheel platform tag mapped for target {target}")
91
+
92
+ archive = self._find_archive(target)
93
+ if archive is None:
94
+ raise RuntimeError(
95
+ f"LITER_LLM_CLI_TARGET={target} but no liter-llm-cli-{target}.(tar.gz|zip) "
96
+ f"found in repo root or dist/; refusing to build an empty platform wheel."
97
+ )
98
+
99
+ binary = self._extract_binary(archive, target)
100
+ force_include = build_data.setdefault("force_include", {})
101
+ force_include[str(binary)] = f"liter_llm_cli/bin/{target}/{binary.name}"
102
+
103
+ build_data["pure_python"] = False
104
+ build_data["infer_tag"] = False
105
+ build_data["tag"] = f"py3-none-{wheel_tag}"
106
+
107
+ def _find_archive(self, target: str) -> Path | None:
108
+ root = Path(self.root)
109
+ repo_root = root.parent.parent
110
+ for base in (repo_root, repo_root / "dist", root, root / "dist"):
111
+ for ext in ("tar.gz", "zip"):
112
+ candidate = base / f"liter-llm-cli-{target}.{ext}"
113
+ if candidate.is_file():
114
+ return candidate
115
+ return None
116
+
117
+ def _extract_binary(self, archive: Path, target: str) -> Path:
118
+ binary_name = "liter-llm.exe" if target.endswith("windows-msvc") else "liter-llm"
119
+ extract_dir = Path(self.root) / ".build-extract" / target
120
+ if extract_dir.exists():
121
+ shutil.rmtree(extract_dir, ignore_errors=True)
122
+ extract_dir.mkdir(parents=True, exist_ok=True)
123
+
124
+ if str(archive).lower().endswith(".zip"):
125
+ _extract_zip_bounded(archive, extract_dir)
126
+ else:
127
+ _extract_tar_bounded(archive, extract_dir)
128
+
129
+ for candidate in extract_dir.rglob(binary_name):
130
+ if candidate.is_file():
131
+ candidate.chmod(0o755)
132
+ return candidate
133
+ raise RuntimeError(f"binary {binary_name} not found inside {archive.name}")
@@ -0,0 +1,3 @@
1
+ """CLI proxy package."""
2
+
3
+ __version__ = "2.7.4"
@@ -0,0 +1,16 @@
1
+ """CLI entry point for the liter-llm proxy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .downloader import run
8
+
9
+
10
+ def main() -> None:
11
+ """Resolve the native binary and exec it with forwarded argv."""
12
+ sys.exit(run(sys.argv[1:]))
13
+
14
+
15
+ if __name__ == "__main__":
16
+ main()
@@ -0,0 +1,239 @@
1
+ """Resolve, download, verify, and run the native liter-llm binary.
2
+
3
+ The package is published in lockstep with the product, so its own version names
4
+ the one release it may install: a binary bundled in the wheel is used first,
5
+ otherwise exactly ``liter-llm-<version>-<triple>`` is downloaded from the
6
+ ``v<version>`` release and verified against ``SHA256SUMS-<version>.txt``. It
7
+ never resolves "latest". All diagnostics go to stderr.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import os
14
+ import platform
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tarfile
19
+ import tempfile
20
+ import zipfile
21
+ from pathlib import Path, PurePosixPath
22
+ from urllib.error import URLError
23
+ from urllib.parse import quote, urlsplit
24
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
25
+
26
+ from . import __version__
27
+
28
+ REPO = "xberg-io/liter-llm"
29
+ BIN_NAME = "liter-llm"
30
+ PKG_NAME = "liter-llm-cli"
31
+ _USER_AGENT = "liter-llm-cli-python-proxy"
32
+
33
+
34
+ def _target_triple() -> str:
35
+ system = platform.system().lower()
36
+ machine = platform.machine().lower()
37
+
38
+ if system == "windows":
39
+ if machine in {"amd64", "x86_64"}:
40
+ return "x86_64-pc-windows-msvc"
41
+ raise RuntimeError(f"unsupported Windows arch: {machine}")
42
+ if system == "linux":
43
+ if machine in {"amd64", "x86_64"}:
44
+ return "x86_64-unknown-linux-gnu"
45
+ if machine in {"aarch64", "arm64"}:
46
+ return "aarch64-unknown-linux-gnu"
47
+ raise RuntimeError(f"unsupported Linux arch: {machine}")
48
+ if system == "darwin":
49
+ if machine in {"aarch64", "arm64"}:
50
+ return "aarch64-apple-darwin"
51
+ if machine in {"amd64", "x86_64"}:
52
+ return "x86_64-apple-darwin"
53
+ raise RuntimeError(f"unsupported macOS arch: {machine}")
54
+ raise RuntimeError(f"unsupported platform: {system} {machine}")
55
+
56
+
57
+ def _binary_name() -> str:
58
+ return f"{BIN_NAME}.exe" if platform.system().lower() == "windows" else BIN_NAME
59
+
60
+
61
+ class _HttpsOnlyRedirectHandler(HTTPRedirectHandler):
62
+ """Reject any redirect whose target is not https (downgrade/SSRF guard)."""
63
+
64
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def] # noqa: PLR0917 — overrides fixed HTTPRedirectHandler signature
65
+ if urlsplit(newurl).scheme.lower() != "https":
66
+ raise URLError(f"refusing non-https redirect to: {newurl}")
67
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
68
+
69
+
70
+ _opener = build_opener(_HttpsOnlyRedirectHandler())
71
+
72
+
73
+ def _http_get(url: str) -> bytes:
74
+ if urlsplit(url).scheme.lower() != "https":
75
+ raise RuntimeError(f"refusing non-https URL: {url}")
76
+ request = Request(url, headers={"User-Agent": _USER_AGENT})
77
+ try:
78
+ with _opener.open(request, timeout=60) as response:
79
+ if response.status != 200:
80
+ raise RuntimeError(f"HTTP {response.status} for {url}")
81
+ return response.read() # type: ignore[no-any-return]
82
+ except URLError as exc:
83
+ raise RuntimeError(f"failed to fetch {url}: {exc}") from exc
84
+
85
+
86
+ def archive_name(version: str, triple: str) -> str:
87
+ """Return the release archive name for ``version`` and ``triple``."""
88
+ extension = "zip" if triple.endswith("-windows-msvc") else "tar.gz"
89
+ return f"{BIN_NAME}-{version}-{triple}.{extension}"
90
+
91
+
92
+ def release_urls(version: str, triple: str) -> tuple[str, str, str]:
93
+ """Return (archive name, archive URL, checksums URL) pinned to ``v<version>``."""
94
+ base = f"https://github.com/{REPO}/releases/download/v{quote(version, safe='')}"
95
+ archive = archive_name(version, triple)
96
+ return archive, f"{base}/{archive}", f"{base}/SHA256SUMS-{version}.txt"
97
+
98
+
99
+ def _expected_digest(text: str, asset_name: str) -> str | None:
100
+ for line in text.splitlines():
101
+ stripped = line.strip()
102
+ if not stripped:
103
+ continue
104
+ parts = stripped.split()
105
+ if len(parts) < 2:
106
+ continue
107
+ name = parts[-1].lstrip("*")
108
+ if name == asset_name:
109
+ return parts[0].lower()
110
+ return None
111
+
112
+
113
+ def verify_checksum(data: bytes, asset_name: str, sums_text: str) -> None:
114
+ """Raise unless ``data`` matches the digest listed for ``asset_name``."""
115
+ expected = _expected_digest(sums_text, asset_name)
116
+ if not expected:
117
+ raise RuntimeError(f"no checksum entry for {asset_name} in SHA256SUMS — refusing to install unverified binary")
118
+ digest = hashlib.sha256(data).hexdigest().lower()
119
+ if digest != expected:
120
+ raise RuntimeError(f"checksum mismatch for {asset_name} (expected {expected}, got {digest})")
121
+
122
+
123
+ def _is_within(base: Path, target: Path) -> bool:
124
+ """True if `target`'s resolved path stays inside `base`."""
125
+ base_resolved = base.resolve()
126
+ try:
127
+ target.resolve().relative_to(base_resolved)
128
+ except ValueError:
129
+ return False
130
+ return True
131
+
132
+
133
+ def _reject_unsafe_member(name: str) -> None:
134
+ """Reject absolute paths and any `..` component (zip-slip / tar-slip)."""
135
+ normalized = name.replace("\\", "/")
136
+ pure = PurePosixPath(normalized)
137
+ if pure.is_absolute() or normalized.startswith("/"):
138
+ raise RuntimeError(f"refusing absolute path in archive: {name}")
139
+ if len(normalized) >= 2 and normalized[1] == ":":
140
+ raise RuntimeError(f"refusing absolute path in archive: {name}")
141
+ if any(part == ".." for part in pure.parts):
142
+ raise RuntimeError(f"refusing parent-directory escape in archive: {name}")
143
+
144
+
145
+ def _safe_extract(archive_path: Path, asset_name: str, dest: Path) -> None:
146
+ """Extract a tar/zip, validating every member stays within `dest`.
147
+
148
+ Does not rely on extractall() defaults or the 3.12-only ``filter='data'``:
149
+ each member name is rejected up front if it is absolute or contains ``..``,
150
+ and the resolved destination path is re-checked against ``dest``.
151
+ """
152
+ dest = dest.resolve()
153
+ dest.mkdir(parents=True, exist_ok=True)
154
+
155
+ if asset_name.lower().endswith(".zip"):
156
+ with zipfile.ZipFile(archive_path) as zf:
157
+ for member in zf.namelist():
158
+ _reject_unsafe_member(member)
159
+ if not _is_within(dest, dest / member):
160
+ raise RuntimeError(f"refusing archive entry escaping dest: {member}")
161
+ for member in zf.namelist():
162
+ zf.extract(member, dest)
163
+ else:
164
+ with tarfile.open(archive_path, "r:gz") as tf:
165
+ for tar_member in tf.getmembers():
166
+ _reject_unsafe_member(tar_member.name)
167
+ if not _is_within(dest, dest / tar_member.name):
168
+ raise RuntimeError(f"refusing archive entry escaping dest: {tar_member.name}")
169
+ if tar_member.islnk() or tar_member.issym():
170
+ link_target = dest / tar_member.name
171
+ if not _is_within(dest, link_target.parent / tar_member.linkname):
172
+ raise RuntimeError(f"refusing link escaping dest: {tar_member.name}")
173
+ tf.extractall(dest)
174
+
175
+
176
+ def _find_binary(root: Path, name: str) -> Path | None:
177
+ for candidate in root.rglob(name):
178
+ if candidate.is_file():
179
+ return candidate
180
+ return None
181
+
182
+
183
+ def _cache_dir(version: str) -> Path:
184
+ cache = Path.home() / ".cache" / PKG_NAME / version
185
+ cache.mkdir(parents=True, exist_ok=True, mode=0o700)
186
+ return cache
187
+
188
+
189
+ def bundled_binary() -> Path | None:
190
+ """Return the binary shipped inside a platform wheel, if there is one."""
191
+ candidate = Path(__file__).resolve().parent / "bin" / _target_triple() / _binary_name()
192
+ return candidate if candidate.is_file() else None
193
+
194
+
195
+ def ensure_binary() -> str:
196
+ """Ensure the native binary for this package's version exists, downloading if necessary."""
197
+ override = os.getenv("LITER_LLM_BINARY")
198
+ if override:
199
+ return override
200
+
201
+ bundled = bundled_binary()
202
+ if bundled is not None:
203
+ return str(bundled)
204
+
205
+ version = __version__
206
+ triple = _target_triple()
207
+ cache = _cache_dir(version)
208
+ binary_path = cache / _binary_name()
209
+ if binary_path.exists() and os.access(binary_path, os.X_OK):
210
+ return str(binary_path)
211
+
212
+ archive, archive_url, checksums_url = release_urls(version, triple)
213
+ print(f"Downloading {BIN_NAME} {version} asset {archive}...", file=sys.stderr)
214
+ data = _http_get(archive_url)
215
+ verify_checksum(data, archive, _http_get(checksums_url).decode("utf-8"))
216
+ print(f"Checksum verified for {archive}.", file=sys.stderr)
217
+ with tempfile.TemporaryDirectory() as tmpdir:
218
+ tmp = Path(tmpdir)
219
+ archive_path = tmp / archive
220
+ archive_path.write_bytes(data)
221
+ extract_dir = tmp / "extract"
222
+ extract_dir.mkdir()
223
+ _safe_extract(archive_path, archive, extract_dir)
224
+ found = _find_binary(extract_dir, _binary_name())
225
+ if not found:
226
+ raise RuntimeError(f"binary {_binary_name()} not found after extracting {archive}")
227
+ shutil.move(str(found), str(binary_path))
228
+
229
+ if platform.system().lower() != "windows":
230
+ binary_path.chmod(0o755)
231
+ print(f"{BIN_NAME} installed.", file=sys.stderr)
232
+ return str(binary_path)
233
+
234
+
235
+ def run(args: list[str]) -> int:
236
+ """Run the native binary with the given args, returning its exit code."""
237
+ binary_path = ensure_binary()
238
+ completed = subprocess.run([binary_path, *args], check=False)
239
+ return completed.returncode
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ build-backend = "hatchling.build"
3
+ requires = ["hatchling"]
4
+
5
+ [project]
6
+ maintainers = [
7
+ { name = "Na'aman Hirschfeld", email = "naaman@xberg.io" },
8
+ { name = "Tobias Perlstein", email = "tobias@xberg.io" },
9
+ ]
10
+ name = "liter-llm-cli"
11
+ version = "2.7.4"
12
+ description = "CLI proxy for liter-llm — downloads and runs the native liter-llm binary from GitHub releases."
13
+ readme = "README.md"
14
+ license = { text = "MIT" }
15
+ authors = [
16
+ { name = "Na'aman Hirschfeld", email = "naaman@xberg.io" },
17
+ { name = "Tobias Perlstein", email = "tobias@xberg.io" },
18
+ ]
19
+ requires-python = ">=3.11"
20
+ classifiers = [
21
+ "Development Status :: 4 - Beta",
22
+ "Environment :: Console",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: MIT License",
25
+ "Programming Language :: Python :: 3 :: Only",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Programming Language :: Python :: 3.14",
30
+ ]
31
+ urls.Homepage = "https://github.com/xberg-io/liter-llm"
32
+ urls.Issues = "https://github.com/xberg-io/liter-llm/issues"
33
+ urls.Repository = "https://github.com/xberg-io/liter-llm.git"
34
+ scripts.liter-llm = "liter_llm_cli.cli:main"
35
+
36
+ [tool.hatch]
37
+ build.hooks.custom.path = "hatch_build.py"
38
+ build.targets.wheel.packages = ["liter_llm_cli"]