pi-tuck 1.1.2 → 1.2.0

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +7 -3
  3. package/dist/index.d.ts +2 -6
  4. package/dist/index.js +16 -111
  5. package/dist/src/build-id.d.ts +1 -1
  6. package/dist/src/build-id.js +1 -1
  7. package/dist/src/compaction.d.ts +2 -103
  8. package/dist/src/compaction.js +29 -146
  9. package/dist/src/diagnostic-replay.js +2 -2
  10. package/dist/src/diagnostics.d.ts +3 -2
  11. package/dist/src/diagnostics.js +30 -9
  12. package/dist/src/history-tools.js +3 -3
  13. package/dist/src/kept-reads.d.ts +2 -2
  14. package/dist/src/kept-reads.js +144 -8
  15. package/dist/src/ledger.d.ts +1 -1
  16. package/dist/src/ledger.js +5 -3
  17. package/dist/src/legacy-cleanup.d.ts +3 -0
  18. package/dist/src/legacy-cleanup.js +190 -0
  19. package/dist/src/notify.d.ts +3 -0
  20. package/dist/src/notify.js +13 -0
  21. package/dist/src/omissions.d.ts +1 -1
  22. package/dist/src/omissions.js +3 -3
  23. package/dist/src/path-key.d.ts +3 -0
  24. package/dist/src/path-key.js +8 -0
  25. package/dist/src/request-capacity.js +1 -1
  26. package/dist/src/run.d.ts +1 -3
  27. package/dist/src/run.js +3 -5
  28. package/dist/src/source-export.d.ts +1 -1
  29. package/dist/src/source-export.js +1 -1
  30. package/dist/src/status.d.ts +0 -6
  31. package/dist/src/status.js +1 -6
  32. package/dist/src/tuck/core/content.js +6 -9
  33. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  34. package/dist/src/tuck/core/keyword-query.js +1 -1
  35. package/dist/src/tuck/core/search-entries.js +5 -5
  36. package/dist/src/tuck/core/transcript.js +2 -1
  37. package/dist/src/tuck.js +390 -394
  38. package/dist/src/windows-private-storage.d.ts +9 -0
  39. package/dist/src/windows-private-storage.js +90 -0
  40. package/index.ts +18 -82
  41. package/package.json +5 -8
  42. package/src/build-id.ts +1 -1
  43. package/src/compaction.ts +28 -113
  44. package/src/diagnostic-replay.ts +2 -2
  45. package/src/diagnostics.ts +24 -9
  46. package/src/history-tools.ts +3 -3
  47. package/src/kept-reads.ts +78 -10
  48. package/src/ledger.ts +5 -3
  49. package/src/legacy-cleanup.ts +134 -0
  50. package/src/notify.ts +10 -0
  51. package/src/omissions.ts +3 -3
  52. package/src/path-key.ts +9 -0
  53. package/src/request-capacity.ts +1 -1
  54. package/src/run.ts +4 -6
  55. package/src/source-export.ts +1 -1
  56. package/src/status.ts +1 -10
  57. package/src/tuck/core/content.ts +5 -10
  58. package/src/tuck/core/keyword-query.ts +2 -2
  59. package/src/tuck/core/search-entries.ts +5 -5
  60. package/src/tuck/core/transcript.ts +2 -1
  61. package/src/tuck.ts +329 -335
  62. package/src/windows-private-storage.ts +94 -0
  63. package/dist/src/assets.d.ts +0 -58
  64. package/dist/src/assets.js +0 -80
  65. package/dist/src/eligibility-cache.d.ts +0 -19
  66. package/dist/src/eligibility-cache.js +0 -33
  67. package/dist/src/semantic-recall.d.ts +0 -422
  68. package/dist/src/semantic-recall.js +0 -1386
  69. package/dist/src/setup.d.ts +0 -3
  70. package/dist/src/setup.js +0 -191
  71. package/scripts/eg2-runtime.py +0 -307
  72. package/scripts/provision-eg2.py +0 -139
  73. package/scripts/semantic-worker.py +0 -234
  74. package/src/assets.ts +0 -92
  75. package/src/eligibility-cache.ts +0 -43
  76. package/src/semantic-recall.ts +0 -592
  77. package/src/setup.ts +0 -163
@@ -1,3 +0,0 @@
1
- /** Returns the runtime configuration's path, setting the runtime up first if it is missing. Safe to call from several Pi processes at
2
- * once: one sets up, the others wait for it. `notice` is called once, when a download actually starts. */
3
- export declare function ensureSemanticRuntime(root: string, notice?: (message: string) => void): Promise<string>;
package/dist/src/setup.js DELETED
@@ -1,191 +0,0 @@
1
- // One-time setup of semantic recall's local runtime: download the pinned files (assets.ts), check each against its SHA-256, assemble
2
- // them into the companion layout scripts/provision-eg2.py expects, and provision it. Everything lives under one folder, by default
3
- // ~/.pi/agent/pi-tuck; deleting that folder removes all of it.
4
- import { createHash, randomUUID } from "node:crypto";
5
- import { constants, createWriteStream, existsSync } from "node:fs";
6
- import { copyFile, mkdir, readdir, readFile, realpath, rename, rm, stat, statfs, writeFile } from "node:fs/promises";
7
- import { execFile } from "node:child_process";
8
- import { dirname, join } from "node:path";
9
- import { Readable } from "node:stream";
10
- import { pipeline } from "node:stream/promises";
11
- import { fileURLToPath } from "node:url";
12
- import { promisify } from "node:util";
13
- import { LLAMA, MODEL, PINS, PYTHON, TOKENIZER, WHEELS, runtimeConfigPath } from "./assets.js";
14
- const run = promisify(execFile);
15
- const sha256 = (data) => createHash("sha256").update(data).digest("hex");
16
- const scripts = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../scripts/" : "../../scripts/", import.meta.url));
17
- const DOWNLOAD_BYTES = [PYTHON, MODEL, TOKENIZER, LLAMA, ...Object.values(WHEELS)].reduce((n, d) => n + d.size, 0);
18
- /** Provisioning keeps 5 GiB free after it copies the companion; the downloads and the staged copy come on top. */
19
- const NEEDED_BYTES = 5 * 1024 ** 3 + 3 * DOWNLOAD_BYTES;
20
- /** Returns the runtime configuration's path, setting the runtime up first if it is missing. Safe to call from several Pi processes at
21
- * once: one sets up, the others wait for it. `notice` is called once, when a download actually starts. */
22
- export async function ensureSemanticRuntime(root, notice = () => { }) {
23
- if (existsSync(runtimeConfigPath(root)))
24
- return runtimeConfigPath(root);
25
- await mkdir(join(root, "runtime"), { recursive: true });
26
- root = await realpath(root); // provisioning refuses paths through symlinks
27
- const config = runtimeConfigPath(root), runtime = dirname(config);
28
- const release = await lock(runtime + ".lock");
29
- const staging = join(root, `staging-${process.pid}`), lockFile = staging + ".lock.json";
30
- try {
31
- if (existsSync(config))
32
- return config; // set up by another process while this one waited
33
- // Remains of a setup killed before it could clean up; the lock means no other setup is using them.
34
- await rm(runtime, { recursive: true, force: true });
35
- for (const [folder, name] of [[root, /^staging-/], [join(root, "downloads"), /\.part$/], [join(root, "python"), /\.part$/]])
36
- for (const entry of await readdir(folder).catch(() => []))
37
- if (name.test(entry))
38
- await rm(join(folder, entry), { recursive: true, force: true });
39
- const { bavail, bsize } = await statfs(root);
40
- if (bavail * bsize < NEEDED_BYTES)
41
- throw new Error(`semantic recall needs ${Math.ceil(NEEDED_BYTES / 1e9)} GB of free disk space`);
42
- notice(`pi-tuck: setting up semantic recall, a one-time download of about ${Math.round(DOWNLOAD_BYTES / 1e6)} MB. Word recall works meanwhile.`);
43
- const downloads = join(root, "downloads");
44
- const get = (download) => fetchVerified(download, downloads);
45
- const [python, llama, model, tokenizer, wheels] = await Promise.all([get(PYTHON), get(LLAMA), get(MODEL), get(TOKENIZER),
46
- Promise.all(Object.entries(WHEELS).map(async ([name, download]) => [name, await get(download)]))]);
47
- const interpreter = await installPython(root, python);
48
- const files = await assemble(staging, { llama, model, tokenizer, wheels });
49
- const wheel = Object.keys(WHEELS).find(name => name.startsWith("tokenizers-"));
50
- await writeFile(lockFile, JSON.stringify({ format: 1, platform: "darwin-arm64", python: PYTHON.version, wheel: "wheels/" + wheel, files }));
51
- await provision(interpreter, ["-I", "-B", join(scripts, "provision-eg2.py"), runtime, "--assets", staging, "--lock", lockFile,
52
- "--python", interpreter, "--index-directory", join(root, "index")]);
53
- await rm(downloads, { recursive: true, force: true });
54
- return config;
55
- }
56
- finally {
57
- await rm(staging, { recursive: true, force: true });
58
- await rm(lockFile, { force: true });
59
- await release();
60
- }
61
- }
62
- /** Downloads once into a content-addressed cache; a file reaches its final name only after its size and SHA-256 match the pin. */
63
- async function fetchVerified(download, directory) {
64
- const path = join(directory, download.sha256);
65
- if (existsSync(path))
66
- return path;
67
- await mkdir(directory, { recursive: true });
68
- const partial = `${path}.${randomUUID()}.part`; // a download abandoned by a failed sibling may still be writing its own
69
- const response = await fetch(download.url);
70
- if (!response.ok || !response.body)
71
- throw new Error(`download failed (HTTP ${response.status}): ${download.url}`);
72
- const hash = createHash("sha256");
73
- let size = 0;
74
- await pipeline(Readable.fromWeb(response.body), async function* (chunks) {
75
- for await (const chunk of chunks) {
76
- hash.update(chunk);
77
- size += chunk.length;
78
- yield chunk;
79
- }
80
- }, createWriteStream(partial));
81
- if (size !== download.size || hash.digest("hex") !== download.sha256) {
82
- await rm(partial, { force: true });
83
- throw new Error(`download does not match its pinned SHA-256: ${download.url}`);
84
- }
85
- await rename(partial, path);
86
- return path;
87
- }
88
- /** The interpreter stays where it is unpacked: the runtime's virtual environment points at it. */
89
- async function installPython(root, archive) {
90
- const directory = join(root, "python", PYTHON.name), interpreter = join(directory, "python", "bin", "python3");
91
- if (existsSync(interpreter))
92
- return interpreter;
93
- const partial = `${directory}.${process.pid}.part`;
94
- await rm(partial, { recursive: true, force: true });
95
- await mkdir(partial, { recursive: true });
96
- await run("tar", ["-xzf", archive, "-C", partial]);
97
- await rm(directory, { recursive: true, force: true });
98
- await rename(partial, directory);
99
- return interpreter;
100
- }
101
- /** Lays out the companion and returns its manifest: every file's path and SHA-256. */
102
- async function assemble(staging, inputs) {
103
- const files = {};
104
- const put = async (path, from, sha) => {
105
- await mkdir(join(staging, path, ".."), { recursive: true });
106
- await copyFile(from, join(staging, path), constants.COPYFILE_FICLONE);
107
- files[path] = sha;
108
- };
109
- const write = async (path, data, sha = sha256(data)) => {
110
- await mkdir(join(staging, path, ".."), { recursive: true });
111
- await writeFile(join(staging, path), data);
112
- files[path] = sha;
113
- };
114
- await put("model.gguf", inputs.model, MODEL.sha256);
115
- await put("models/embedding/tokenizer.json", inputs.tokenizer, TOKENIZER.sha256);
116
- for (const [name, path] of inputs.wheels)
117
- await put("wheels/" + name, path, WHEELS[name].sha256);
118
- const unpacked = staging + ".llama";
119
- await mkdir(unpacked, { recursive: true });
120
- try {
121
- await run("tar", ["-xzf", inputs.llama, "-C", unpacked]);
122
- // Reading follows the archive's symlinks, so each copy is a plain file.
123
- const member = async (name, sha, path) => {
124
- const bytes = await readFile(join(unpacked, LLAMA.folder, name));
125
- if (sha256(bytes) !== sha)
126
- throw new Error(`llama.cpp archive member does not match its pinned SHA-256: ${name}`);
127
- await write(path, bytes, sha);
128
- };
129
- for (const [name, sha] of Object.entries(LLAMA.files))
130
- await member(name, sha, "native/" + name);
131
- await member("LICENSE", LLAMA.license, "notices/llama.cpp/LICENSE");
132
- }
133
- finally {
134
- await rm(unpacked, { recursive: true, force: true });
135
- }
136
- // A wheel's filename starts with its distribution name and version.
137
- await write("requirements.lock", Object.entries(WHEELS).map(([wheel, { sha256 }]) => {
138
- const [name, version] = wheel.split("-");
139
- return `${name}==${version} --hash=sha256:${sha256}\n`;
140
- }).join(""));
141
- await write("pins.json", JSON.stringify(PINS));
142
- return files;
143
- }
144
- /** Runs provisioning so that it ends with Pi: an orphan would roll back its own folder under a later setup. Its error is the last
145
- * line it wrote, not the whole command and log. */
146
- async function provision(interpreter, args) {
147
- const pending = run(interpreter, args, { maxBuffer: 16 * 1024 * 1024 }), stop = () => pending.child.kill("SIGTERM");
148
- process.once("exit", stop);
149
- try {
150
- await pending;
151
- }
152
- catch (error) {
153
- const lines = String(error.stderr ?? "").trim().split("\n");
154
- throw new Error(`provisioning failed: ${lines.at(-1) || error.message}`);
155
- }
156
- finally {
157
- process.off("exit", stop);
158
- }
159
- }
160
- /** A directory lock: whoever creates it sets up. It is taken over when its holder has exited, or after six hours (a reused pid);
161
- * the takeover renames the lock away first, so of several waiters only one takes it. */
162
- async function lock(path) {
163
- for (;;) {
164
- try {
165
- await mkdir(path);
166
- await writeFile(join(path, "pid"), String(process.pid));
167
- return () => rm(path, { recursive: true, force: true });
168
- }
169
- catch (error) {
170
- if (error.code !== "EEXIST")
171
- throw error;
172
- }
173
- const holder = Number(await readFile(join(path, "pid"), "utf8").catch(() => ""));
174
- const age = Date.now() - (await stat(path).catch(() => ({ mtimeMs: Date.now() }))).mtimeMs;
175
- // A lock with no pid yet is a holder between its two steps, unless it has been like that for a while.
176
- if (age > 6 * 3600_000 || (holder ? !alive(holder) : age > 30_000)) {
177
- const taken = `${path}.stale-${randomUUID()}`;
178
- if (await rename(path, taken).then(() => true, () => false))
179
- await rm(taken, { recursive: true, force: true });
180
- }
181
- else
182
- await new Promise(done => setTimeout(done, 2000));
183
- }
184
- }
185
- const alive = (pid) => { try {
186
- process.kill(pid, 0);
187
- return true;
188
- }
189
- catch (error) {
190
- return error.code === "EPERM";
191
- } };
@@ -1,307 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Shared offline EG2 schema/byte verification; publisher authenticity belongs to the host."""
3
- import hashlib
4
- import json
5
- import pathlib
6
- import re
7
- import sys
8
-
9
- OFFICIAL_REVISION = '914f7f89142e33e77833254d9c9b90c3cef7303b'
10
- NATIVE_COMMIT = '988190680d5a89fce97de3c20df2c2813731fd61' # llama.cpp release b11476, what pi-tuck's setup installs
11
- # Runtimes provisioned earlier with a source build of llama.cpp at 448147d stay valid.
12
- NATIVE_COMMITS = (NATIVE_COMMIT, '448147d42a71d0147c6dc844f99f9ffe7419183a')
13
- ARTIFACTS = ('Q4_0', 'Q4_K_S', 'Q4_K_M', 'Q8_0', 'BF16')
14
- COMPUTE = 'CPU float32 with f32 KV; quantized weights where selected'
15
- POOLING = 'mask-aware mean including prompt, projected token states, then float32 L2'
16
- REQUIRED = {'model.gguf', 'models/embedding/tokenizer.json', 'pins.json', 'requirements.lock'}
17
- NATIVE_SERVERS = {'native/llama-server', 'native/llama-server.exe'}
18
- # Small mandatory tokenizers closure, derived from the pinned wheel METADATA.
19
- # No extras, layout stack, network resolver, or alternate versions.
20
- UTILITIES = {
21
- 'tokenizers': ('0.23.2', ('tokenizers', 'tokenizers.libs')),
22
- 'huggingface-hub': ('1.33.0', ('huggingface_hub',)),
23
- 'anyio': ('4.15.1', ('anyio',)), 'certifi': ('2026.7.22', ('certifi',)),
24
- 'click': ('8.5.0', ('click',)), 'filelock': ('4.0.12', ('filelock',)),
25
- 'fsspec': ('2026.9.0', ('fsspec',)), 'h11': ('0.16.0', ('h11',)),
26
- 'hf-xet': ('1.7.0', ('hf_xet',)), 'httpcore': ('1.0.9', ('httpcore',)),
27
- 'httpx': ('0.28.1', ('httpx',)), 'idna': ('3.20', ('idna',)),
28
- 'packaging': ('26.3', ('packaging',)), 'pyyaml': ('6.0.3', ('yaml', '_yaml')),
29
- 'tqdm': ('4.70.1', ('tqdm',)),
30
- 'typing-extensions': ('4.16.0', ('typing_extensions.py',)),
31
- }
32
-
33
-
34
- def utility_versions(manifest):
35
- result = dict(UTILITIES)
36
- if 'native/llama-server.exe' in manifest:
37
- result['colorama'] = ('0.4.6', ('colorama',))
38
- return result
39
-
40
-
41
- def normalized(name):
42
- return re.sub('[-_.]+', '-', name).lower()
43
-
44
-
45
- def digest(path):
46
- h = hashlib.sha256()
47
- with path.open('rb') as stream:
48
- while data := stream.read(1024 * 1024):
49
- h.update(data)
50
- return h.hexdigest()
51
-
52
-
53
- def read_json(path):
54
- def unique(pairs):
55
- result = {}
56
- for key, value in pairs:
57
- if key in result:
58
- raise ValueError('duplicate_json_key')
59
- result[key] = value
60
- return result
61
- return json.loads(path.read_text(), object_pairs_hook=unique)
62
-
63
-
64
- def python_supported(version=None):
65
- if tuple(sys.version_info[:2] if version is None else version) not in ((3, 12), (3, 13)):
66
- raise ValueError('python_3_12_or_3_13_required')
67
-
68
-
69
- def validate_manifest(manifest):
70
- if not isinstance(manifest, dict) or not REQUIRED <= manifest.keys():
71
- raise ValueError('incomplete_asset_manifest')
72
- if len(NATIVE_SERVERS & manifest.keys()) != 1:
73
- raise ValueError('invalid_native_server_inventory')
74
- for name, sha in manifest.items():
75
- if not isinstance(name, str):
76
- raise ValueError('asset_path_failure')
77
- path = pathlib.PurePosixPath(name)
78
- if not name or path.is_absolute() or '..' in path.parts or path.as_posix() != name or '\\' in name or ':' in name:
79
- raise ValueError('asset_path_failure')
80
- if not isinstance(sha, str) or not re.fullmatch('[0-9a-f]{64}', sha):
81
- raise ValueError('invalid_asset_digest')
82
-
83
-
84
- def validate_pins(pins, manifest):
85
- validate_manifest(manifest)
86
- e, b, r = (pins.get(name, {}) for name in ('embedding', 'backend', 'runtime'))
87
- if (e.get('model') != 'google/embeddinggemma-2' or e.get('revision') != OFFICIAL_REVISION
88
- or e.get('dimensions') != 768 or e.get('maxTokens') != 8192
89
- or e.get('queryInstruction') != 'task: search result | query: '
90
- or e.get('documentInstruction') != 'title: none | text: '
91
- or e.get('pooling') != POOLING):
92
- raise ValueError('invalid_embedding_pin')
93
- if (b.get('name') != 'llama.cpp' or b.get('commit') not in NATIVE_COMMITS
94
- or b.get('artifact') not in ARTIFACTS or e.get('dtype') != b.get('artifact')
95
- or b.get('modelSHA256') != manifest['model.gguf'] or b.get('gpuLayers') != 0
96
- or b.get('compute') != COMPUTE or b.get('computePrecision', 'float32') != 'float32'
97
- or b.get('modelRepository') != 'unsloth/embeddinggemma-2-GGUF'
98
- or not isinstance(b.get('modelRevision'), str)
99
- or not re.fullmatch('[0-9a-f]{40}', b['modelRevision'])):
100
- raise ValueError('invalid_backend_pin')
101
- if r.get('tokenizers') != '0.23.2':
102
- raise ValueError('runtime_version_mismatch')
103
-
104
-
105
- def verify_files(root, manifest):
106
- validate_manifest(manifest)
107
- for name, expected in manifest.items():
108
- path = root / name
109
- if any(p.is_symlink() for p in (path, *path.parents)) or not path.is_file():
110
- raise ValueError('asset_path_failure')
111
- if digest(path) != expected:
112
- raise ValueError('asset_integrity_failure')
113
-
114
-
115
- def verify_gguf(path, artifact):
116
- import struct
117
- types = {'Q4_0': 2, 'Q4_K_S': 14, 'Q4_K_M': 15, 'Q8_0': 7, 'BF16': 32}
118
- widths = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
119
- size = path.stat().st_size
120
- with path.open('rb') as stream:
121
- def read(n):
122
- data = stream.read(n)
123
- if len(data) != n:
124
- raise ValueError('invalid_gguf_header')
125
- return data
126
- def number(fmt):
127
- return struct.unpack('<' + fmt, read(struct.calcsize(fmt)))[0]
128
- def string(keep=True):
129
- length = number('Q')
130
- if length > 16 * 1024 * 1024 or stream.tell() + length > size:
131
- raise ValueError('invalid_gguf_header')
132
- if keep:
133
- return read(length).decode('utf-8')
134
- stream.seek(length, 1)
135
- def value(kind, keep=False, depth=0):
136
- if kind == 8:
137
- return string(keep)
138
- if kind == 9 and depth == 0:
139
- element, count = number('I'), number('Q')
140
- if count > 2000000:
141
- raise ValueError('invalid_gguf_header')
142
- if element in widths:
143
- stream.seek(widths[element] * count, 1)
144
- else:
145
- for _ in range(count): value(element, False, depth + 1)
146
- elif kind in widths:
147
- data = read(widths[kind])
148
- if keep and kind == 4:
149
- return struct.unpack('<I', data)[0]
150
- else:
151
- raise ValueError('invalid_gguf_header')
152
- if stream.tell() > size:
153
- raise ValueError('invalid_gguf_header')
154
- if read(4) != b'GGUF' or number('I') != 3:
155
- raise ValueError('unsupported_gguf_format')
156
- tensors, count = number('Q'), number('Q')
157
- if not 1 <= tensors <= 100000 or not 1 <= count <= 10000:
158
- raise ValueError('invalid_gguf_header')
159
- found = {}
160
- for _ in range(count):
161
- name, kind = string(), number('I')
162
- wanted = name in ('general.architecture', 'general.file_type')
163
- data = value(kind, wanted)
164
- if wanted:
165
- if name in found:
166
- raise ValueError('invalid_gguf_header')
167
- found[name] = data
168
- if found != {'general.architecture': 'gemma-embedding2', 'general.file_type': types[artifact]}:
169
- raise ValueError('gguf_pin_mismatch')
170
-
171
-
172
- def verify_runtime(root):
173
- manifest = read_json(root / 'assets.sha256.json')
174
- verify_files(root, manifest)
175
- pins = read_json(root / 'pins.json')
176
- validate_pins(pins, manifest)
177
- validate_requirements(root, manifest)
178
- verify_gguf(root / 'model.gguf', pins['backend']['artifact'])
179
- return pins
180
-
181
-
182
- def validate_requirements(root, manifest):
183
- expected = utility_versions(manifest)
184
- locked = {}
185
- for line in (root / 'requirements.lock').read_text().splitlines():
186
- match = re.fullmatch(r'([A-Za-z0-9_.-]+)==([A-Za-z0-9.+_-]+) --hash=sha256:([0-9a-f]{64})', line)
187
- if not match or normalized(match[1]) in locked:
188
- raise ValueError('invalid_requirements_lock')
189
- name = normalized(match[1])
190
- if name not in expected or match[2] != expected[name][0]:
191
- raise ValueError('invalid_requirements_lock')
192
- locked[name] = match[3]
193
- if locked.keys() != expected.keys():
194
- raise ValueError('invalid_requirements_lock')
195
- wheels = [name for name in manifest if name.startswith('wheels/') and name.endswith('.whl')]
196
- if wheels:
197
- found = set()
198
- for wheel in wheels:
199
- parts = pathlib.PurePosixPath(wheel).name[:-4].split('-')
200
- name = normalized(parts[0])
201
- if (len(parts) not in (5, 6) or name in found or name not in expected
202
- or parts[1] != expected[name][0] or manifest[wheel] != locked[name]):
203
- raise ValueError('invalid_requirements_lock')
204
- found.add(name)
205
- if found != expected.keys():
206
- raise ValueError('invalid_requirements_lock')
207
- elif not any('/site-packages/tokenizers/' in name and name.endswith(('.so', '.pyd')) for name in manifest):
208
- raise ValueError('missing_exact_tokenizers_assets')
209
- return expected
210
-
211
-
212
- def verify_tokenizers(root):
213
- import importlib.metadata
214
- import importlib.util
215
- import zipfile
216
- manifest = read_json(root / 'assets.sha256.json')
217
- validate_manifest(manifest)
218
- utilities = validate_requirements(root, manifest)
219
- for name, (version, _) in utilities.items():
220
- if importlib.metadata.version(name) != version:
221
- raise ValueError('runtime_version_mismatch')
222
- spec = importlib.util.find_spec('tokenizers')
223
- if spec is None or spec.origin is None:
224
- raise ValueError('tokenizers_origin_failure')
225
- package = pathlib.Path(spec.origin).parent
226
- wheels = [name for name in manifest if name.startswith('wheels/') and name.endswith('.whl')]
227
- for wheel in wheels:
228
- if digest(root / wheel) != manifest[wheel]:
229
- raise ValueError('tokenizers_integrity_failure')
230
- # Bind the whole utility payload, including Windows extensions and bundled DLLs.
231
- # Bytecode is not accepted: -B prevents writes but does not prevent loading old pyc.
232
- for _, members in utilities.values():
233
- if not any((package.parent / member).exists() for member in members):
234
- raise ValueError('tokenizers_membership_failure')
235
- payload = {member for _, members in utilities.values() for member in members} | {name.replace('-', '_') + '.libs' for name in utilities}
236
- metadata = {name.replace('-', '_') + '-' + version + '.dist-info' for name, (version, _) in utilities.items()}
237
- def utility_member(name):
238
- return name.split('/')[0] in payload | metadata
239
- actual = set()
240
- for tree in (package.parent / name for name in payload | metadata):
241
- if any(p.is_symlink() for p in (tree, *tree.parents)):
242
- raise ValueError('tokenizers_origin_failure')
243
- for path in ([tree] if tree.is_file() else tree.rglob('*')):
244
- if path.is_symlink():
245
- raise ValueError('tokenizers_origin_failure')
246
- if path.is_file():
247
- name = path.relative_to(package.parent).as_posix()
248
- if path.suffix in ('.pyc', '.pyo'):
249
- raise ValueError('tokenizers_membership_failure')
250
- actual.add(name)
251
- if not wheels:
252
- # A managed runtime binds every installed library byte, including dependency
253
- # metadata/native companions and the signed interpreter's pip seed.
254
- actual = set()
255
- for path in package.parent.rglob('*'):
256
- if path.is_symlink():
257
- raise ValueError('tokenizers_origin_failure')
258
- if path.is_file():
259
- if path.suffix in ('.pyc', '.pyo'):
260
- raise ValueError('tokenizers_membership_failure')
261
- actual.add(path.relative_to(package.parent).as_posix())
262
- try:
263
- prefix = package.parent.relative_to(root).as_posix() + '/'
264
- except ValueError:
265
- raise ValueError('tokenizers_origin_failure')
266
- names = {name[len(prefix):] for name in manifest if name.startswith(prefix)}
267
- if names != actual:
268
- raise ValueError('tokenizers_membership_failure')
269
- for name in names:
270
- if digest(package.parent / name) != manifest[prefix + name]:
271
- raise ValueError('tokenizers_integrity_failure')
272
- else:
273
- # pip rewrites RECORD and adds installation bookkeeping. Root admission
274
- # verifies their exact signed-pip parity; never treat editable RECORD as authority.
275
- generated = {directory + '/' + leaf for directory in metadata for leaf in ('RECORD', 'INSTALLER', 'REQUESTED')}
276
- names = set()
277
- for wheel in wheels:
278
- with zipfile.ZipFile(root / wheel) as archive:
279
- inventory = archive.namelist()
280
- if len(set(inventory)) != len(inventory):
281
- raise ValueError('tokenizers_membership_failure')
282
- for name in inventory:
283
- path = pathlib.PurePosixPath(name)
284
- if (path.is_absolute() or '..' in path.parts or '\\' in name or ':' in name
285
- or path.as_posix() != name.rstrip('/')):
286
- raise ValueError('asset_path_failure')
287
- members = {name for name in inventory if utility_member(name) and not name.endswith('/') and name not in generated}
288
- if names & members:
289
- raise ValueError('tokenizers_membership_failure')
290
- names.update(members)
291
- for name in members:
292
- if not (package.parent / name).is_file() or (package.parent / name).read_bytes() != archive.read(name):
293
- raise ValueError('tokenizers_integrity_failure')
294
- if names != actual - generated:
295
- raise ValueError('tokenizers_membership_failure')
296
-
297
-
298
- def configuration_identity(root, worker_path):
299
- h = hashlib.sha256()
300
- # Raw bytes bind all publisher metadata, including optional vision/encoder configuration.
301
- for path in (root / 'pins.json', root / 'requirements.lock', root / 'assets.sha256.json',
302
- pathlib.Path(worker_path), pathlib.Path(__file__)):
303
- data = path.read_bytes()
304
- h.update(len(data).to_bytes(8, 'big'))
305
- h.update(data)
306
- h.update(str(sys.version_info[:3]).encode())
307
- return h.hexdigest()
@@ -1,139 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Offline EG2 provisioning from an exact companion lock; pi-tuck's setup downloads and assembles the companion first."""
3
- import argparse
4
- import json
5
- import os
6
- import pathlib
7
- import platform
8
- import runpy
9
- import shutil
10
- import signal
11
- import subprocess
12
-
13
- RUNTIME = runpy.run_path(str(pathlib.Path(__file__).with_name('eg2-runtime.py')))
14
- RESERVE = 5 * 1024**3
15
-
16
-
17
- def verify_assets(root, lock):
18
- if lock.get('format') != 1 or lock.get('platform') != 'darwin-arm64' or lock.get('python') not in ('3.12', '3.13'):
19
- raise RuntimeError('Unsupported companion lock')
20
- manifest = lock['files']
21
- RUNTIME['validate_manifest'](manifest)
22
- if lock.get('wheel') not in manifest:
23
- raise RuntimeError('Missing pinned wheel')
24
- actual = set()
25
- for path in root.rglob('*'):
26
- if path.is_symlink() or not (path.is_file() or path.is_dir()):
27
- raise RuntimeError('Companion contains a link or unsupported member')
28
- if path.is_file():
29
- actual.add(str(path.relative_to(root)))
30
- if actual != set(manifest):
31
- raise RuntimeError('Exact companion membership differs')
32
- RUNTIME['verify_files'](root, manifest)
33
- pins = RUNTIME['read_json'](root / 'pins.json')
34
- RUNTIME['validate_pins'](pins, manifest)
35
- RUNTIME['validate_requirements'](root, manifest)
36
- RUNTIME['verify_gguf'](root / 'model.gguf', pins['backend']['artifact'])
37
-
38
-
39
- def outside(base, path):
40
- return base != path and base not in path.parents
41
-
42
-
43
- def main():
44
- parser = argparse.ArgumentParser(description=__doc__)
45
- parser.add_argument('destination', type=pathlib.Path, help='NEW absolute external immutable asset root')
46
- parser.add_argument('--assets', required=True, type=pathlib.Path, help='extracted exact companion directory')
47
- parser.add_argument('--lock', required=True, type=pathlib.Path, help='format-1 lock binding every companion file to its SHA-256')
48
- parser.add_argument('--python', required=True, type=pathlib.Path, help='absolute native arm64 Python 3.12 or 3.13 with venv/ensurepip')
49
- parser.add_argument('--environment-directory', type=pathlib.Path, help='NEW permanent venv path; default destination/env; never relocate')
50
- parser.add_argument('--index-directory', required=True, type=pathlib.Path, help='absolute external disposable cache, outside runtime/project')
51
- parser.add_argument('--scratch-directory', type=pathlib.Path, help='external mutable parent; default index sibling')
52
- args = parser.parse_args()
53
- if platform.system() != 'Darwin' or platform.machine() != 'arm64':
54
- raise RuntimeError('Only Darwin arm64 is qualified')
55
- paths = [args.destination, args.assets, args.lock, args.python, args.index_directory]
56
- paths += [p for p in (args.environment_directory, args.scratch_directory) if p is not None]
57
- if not all(p.is_absolute() for p in paths):
58
- raise RuntimeError('Use absolute paths')
59
- if os.path.lexists(args.destination):
60
- raise RuntimeError('Destination already exists; no overwrite/repair')
61
- target, assets, index = args.destination.resolve(), args.assets.resolve(), args.index_directory.resolve()
62
- environment = args.environment_directory or target / 'env'
63
- if args.environment_directory is not None and os.path.lexists(environment):
64
- raise RuntimeError('Environment already exists; no overwrite/repair')
65
- environment = environment.resolve()
66
- scratch = (args.scratch_directory or index.parent).resolve()
67
- if (not outside(target, index) or not outside(target, scratch) or not outside(target, assets)
68
- or not outside(environment, index) or not outside(environment, scratch)
69
- or (args.environment_directory is not None and (not outside(target, environment) or not outside(environment, target)))):
70
- raise RuntimeError('Assets/environment/cache/scratch must not overlap software destinations')
71
- for path in (args.destination, args.index_directory, args.environment_directory, args.scratch_directory):
72
- if path is not None and any(p.is_symlink() for p in (path, *path.parents)):
73
- raise RuntimeError('Destination/cache/scratch symlink forbidden')
74
- probe = json.loads(subprocess.check_output([str(args.python), '-I', '-B', '-c', 'import sys,platform,json; print(json.dumps([list(sys.version_info[:2]),platform.machine()]))'], text=True))
75
- RUNTIME['python_supported'](probe[0])
76
- if probe[1] != 'arm64':
77
- raise RuntimeError('Native arm64 Python required')
78
- lock = RUNTIME['read_json'](args.lock)
79
- verify_assets(assets, lock)
80
- if '.'.join(map(str, probe[0])) != lock['python']:
81
- raise RuntimeError('Python differs from the exact companion lock')
82
- ancestor = target.parent
83
- while not ancestor.exists():
84
- ancestor = ancestor.parent
85
- size = sum((assets / name).stat().st_size for name in lock['files'])
86
- if shutil.disk_usage(ancestor).free < RESERVE + size + 256 * 1024**2:
87
- raise RuntimeError('5 GiB reserve plus setup headroom required')
88
- # Only newly created destinations are rollback-owned. Never copy an existing venv.
89
- target.parent.mkdir(parents=True, exist_ok=True)
90
- target.mkdir(mode=0o700)
91
- complete = False
92
- environment_owned = False
93
- def interrupted(signum, frame):
94
- raise KeyboardInterrupt('Setup interrupted')
95
- previous = signal.signal(signal.SIGTERM, interrupted)
96
- try:
97
- for name in lock['files']:
98
- output = target / name
99
- output.parent.mkdir(parents=True, exist_ok=True)
100
- shutil.copy2(assets / name, output)
101
- RUNTIME['verify_files'](target, lock['files'])
102
- (target / 'native/llama-server').chmod(0o755)
103
- if args.environment_directory is not None:
104
- environment.parent.mkdir(parents=True, exist_ok=True)
105
- environment.mkdir(mode=0o700)
106
- environment_owned = True
107
- subprocess.run([str(args.python), '-I', '-B', '-m', 'venv', str(environment)], check=True)
108
- python = str(environment / 'bin/python')
109
- subprocess.run([python, '-I', '-B', '-m', 'pip', '--isolated', 'install', '--no-index', '--no-cache-dir', '--no-compile', '--no-deps', '--only-binary=:all:', '--require-hashes', '--find-links', str(target / 'wheels'), '-r', str(target / 'requirements.lock')], check=True)
110
- subprocess.run([python, '-I', '-B', '-m', 'pip', '--isolated', 'check'], check=True)
111
- # ensurepip explicitly compiles its seed even under -B. No installed
112
- # bytecode may remain; -B alone does not prohibit loading existing pyc.
113
- for path in environment.rglob('*'):
114
- if path.is_file() and path.suffix in ('.pyc', '.pyo'):
115
- path.unlink()
116
- for path in sorted(environment.rglob('__pycache__'), reverse=True):
117
- if path.is_dir(): shutil.rmtree(path)
118
- # The retained exact wheels verify the entire utility closure membership/bytes.
119
- (target / 'assets.sha256.json').write_text(json.dumps(lock['files'], indent=2) + '\n')
120
- check = 'import runpy,sys,pathlib; m=runpy.run_path(sys.argv[1]); root=pathlib.Path(sys.argv[2]); m["python_supported"](); m["verify_runtime"](root); m["verify_tokenizers"](root); from tokenizers import Tokenizer; Tokenizer.from_file(str(root/"models/embedding/tokenizer.json"))'
121
- subprocess.run([python, '-I', '-B', '-c', check, str(pathlib.Path(__file__).with_name('eg2-runtime.py')), str(target)], check=True)
122
- config = target / 'semantic-recall.json'
123
- value = {'pythonPath': python, 'runtimeRoot': str(target), 'indexDirectory': str(index), 'queryWaitMs': 30000}
124
- if args.scratch_directory is not None:
125
- value['scratchDirectory'] = str(scratch)
126
- config.write_text(json.dumps(value, indent=2) + '\n')
127
- config.chmod(0o600)
128
- complete = True
129
- print(str(config))
130
- finally:
131
- signal.signal(signal.SIGTERM, previous)
132
- if not complete:
133
- if environment_owned:
134
- shutil.rmtree(environment)
135
- shutil.rmtree(target)
136
-
137
-
138
- if __name__ == '__main__':
139
- main()