pi-tuck 1.1.3 → 1.3.1

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 (86) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +28 -59
  3. package/dist/index.d.ts +2 -6
  4. package/dist/index.js +16 -111
  5. package/dist/src/bash-command.d.ts +8 -0
  6. package/dist/src/bash-command.js +116 -0
  7. package/dist/src/build-id.d.ts +1 -1
  8. package/dist/src/build-id.js +1 -1
  9. package/dist/src/compaction.d.ts +2 -103
  10. package/dist/src/compaction.js +20 -140
  11. package/dist/src/diagnostic-replay.js +3 -3
  12. package/dist/src/diagnostics.d.ts +3 -2
  13. package/dist/src/diagnostics.js +30 -9
  14. package/dist/src/history-tools.js +3 -3
  15. package/dist/src/kept-reads.d.ts +2 -2
  16. package/dist/src/kept-reads.js +35 -8
  17. package/dist/src/kept-searches.d.ts +11 -0
  18. package/dist/src/kept-searches.js +202 -0
  19. package/dist/src/ledger.d.ts +1 -1
  20. package/dist/src/ledger.js +5 -3
  21. package/dist/src/legacy-cleanup.d.ts +3 -0
  22. package/dist/src/legacy-cleanup.js +190 -0
  23. package/dist/src/notify.d.ts +3 -0
  24. package/dist/src/notify.js +13 -0
  25. package/dist/src/omissions.d.ts +1 -1
  26. package/dist/src/omissions.js +3 -3
  27. package/dist/src/path-key.d.ts +3 -0
  28. package/dist/src/path-key.js +8 -0
  29. package/dist/src/request-capacity.js +1 -1
  30. package/dist/src/run.d.ts +1 -3
  31. package/dist/src/run.js +3 -5
  32. package/dist/src/source-export.d.ts +1 -1
  33. package/dist/src/source-export.js +1 -1
  34. package/dist/src/status.d.ts +0 -6
  35. package/dist/src/status.js +1 -6
  36. package/dist/src/tuck/core/content.d.ts +0 -11
  37. package/dist/src/tuck/core/content.js +5 -55
  38. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  39. package/dist/src/tuck/core/keyword-query.js +1 -1
  40. package/dist/src/tuck/core/search-entries.d.ts +5 -28
  41. package/dist/src/tuck/core/search-entries.js +14 -156
  42. package/dist/src/tuck/core/transcript.js +2 -1
  43. package/dist/src/tuck.d.ts +7 -15
  44. package/dist/src/tuck.js +409 -409
  45. package/dist/src/windows-private-storage.d.ts +9 -0
  46. package/dist/src/windows-private-storage.js +90 -0
  47. package/index.ts +18 -82
  48. package/package.json +5 -8
  49. package/src/bash-command.ts +59 -0
  50. package/src/build-id.ts +1 -1
  51. package/src/compaction.ts +19 -107
  52. package/src/diagnostic-replay.ts +3 -3
  53. package/src/diagnostics.ts +24 -9
  54. package/src/history-tools.ts +3 -3
  55. package/src/kept-reads.ts +27 -10
  56. package/src/kept-searches.ts +163 -0
  57. package/src/ledger.ts +5 -3
  58. package/src/legacy-cleanup.ts +134 -0
  59. package/src/notify.ts +10 -0
  60. package/src/omissions.ts +3 -3
  61. package/src/path-key.ts +9 -0
  62. package/src/request-capacity.ts +1 -1
  63. package/src/run.ts +4 -6
  64. package/src/source-export.ts +1 -1
  65. package/src/status.ts +1 -10
  66. package/src/tuck/core/content.ts +4 -52
  67. package/src/tuck/core/keyword-query.ts +2 -2
  68. package/src/tuck/core/search-entries.ts +15 -202
  69. package/src/tuck/core/transcript.ts +2 -1
  70. package/src/tuck.ts +350 -357
  71. package/src/windows-private-storage.ts +94 -0
  72. package/dist/src/assets.d.ts +0 -58
  73. package/dist/src/assets.js +0 -80
  74. package/dist/src/eligibility-cache.d.ts +0 -19
  75. package/dist/src/eligibility-cache.js +0 -33
  76. package/dist/src/semantic-recall.d.ts +0 -422
  77. package/dist/src/semantic-recall.js +0 -1386
  78. package/dist/src/setup.d.ts +0 -3
  79. package/dist/src/setup.js +0 -191
  80. package/scripts/eg2-runtime.py +0 -307
  81. package/scripts/provision-eg2.py +0 -139
  82. package/scripts/semantic-worker.py +0 -234
  83. package/src/assets.ts +0 -92
  84. package/src/eligibility-cache.ts +0 -43
  85. package/src/semantic-recall.ts +0 -592
  86. package/src/setup.ts +0 -163
@@ -1,234 +0,0 @@
1
- #!/usr/bin/env python3
2
- """One session-owned native encoder; tokenizer offsets and SQLite remain local utilities."""
3
- import os,sys,json,pathlib,sqlite3,math,struct,subprocess,signal,time,socket,http.client,runpy,secrets
4
- RUNTIME=runpy.run_path(str(pathlib.Path(__file__).with_name('eg2-runtime.py')))
5
- ROOT=pathlib.Path(os.environ['PI_SEMANTIC_RUNTIME_ROOT']).resolve()
6
- PINS=RUNTIME['read_json'](ROOT/'pins.json')
7
- IDENTITY=RUNTIME['configuration_identity'](ROOT,__file__)
8
- class Refusal(Exception):pass
9
- verified=False;tokenizer=None;server=None
10
- # Only Windows uses TCP. Never publish the token in config, files, argv or replies.
11
- WINDOWS=os.name=='nt';encoder_port=None;encoder_token=None
12
- class LocalHTTP(http.client.HTTPConnection):
13
- def connect(self):
14
- self.sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);self.sock.settimeout(self.timeout);self.sock.connect('encoder.sock')
15
- # A native request's timeout: 55 s, plus 30 s per text it embeds (the host's EMBED_TEXT_MS), so a starved CPU slows a batch down and does not fail it.
16
- def request(path,data=None,texts=0):
17
- if path not in ('/health','/props','/v1/embeddings'):raise Refusal('native_path_failure')
18
- if WINDOWS:
19
- if encoder_port is None or not encoder_token:raise Refusal('native_transport_unavailable')
20
- connection=http.client.HTTPConnection('127.0.0.1',encoder_port,timeout=55+30*texts)
21
- else:connection=LocalHTTP('localhost',timeout=55+30*texts)
22
- try:
23
- headers={'Content-Type':'application/json'}
24
- if WINDOWS:headers['Authorization']='Bearer '+encoder_token
25
- body=None if data is None else json.dumps(data).encode();connection.request('GET' if data is None else 'POST',path,body,headers)
26
- response=connection.getresponse();payload=response.read(16*1024*1024+1)
27
- if len(payload)>16*1024*1024:raise Refusal('native_response_bound')
28
- if response.status!=200:raise Refusal('native_request_failure')
29
- return json.loads(payload)
30
- except TimeoutError:raise Refusal('native_request_failure')
31
- finally:connection.close()
32
- def native_executable():
33
- executable=ROOT/('native/llama-server.exe' if WINDOWS else 'native/llama-server')
34
- # A target mismatch cannot select an unmanifested executable.
35
- if executable.relative_to(ROOT).as_posix() not in RUNTIME['read_json'](ROOT/'assets.sha256.json'):raise Refusal('native_target_failure')
36
- return executable
37
- def verify():
38
- global verified,PINS,IDENTITY
39
- if verified:return
40
- try:
41
- RUNTIME['python_supported']();pins=RUNTIME['verify_runtime'](ROOT);native_executable();RUNTIME['verify_tokenizers'](ROOT)
42
- if RUNTIME['configuration_identity'](ROOT,__file__)!=IDENTITY:raise ValueError('runtime_changed_before_readiness')
43
- except ValueError as error:raise Refusal(str(error))
44
- PINS=pins;verified=True
45
- def tok():
46
- global tokenizer
47
- if tokenizer is None:
48
- verify();from tokenizers import Tokenizer
49
- tokenizer=Tokenizer.from_file(str(ROOT/'models/embedding/tokenizer.json'));tokenizer.no_truncation();tokenizer.no_padding()
50
- return tokenizer
51
- def texts(req):
52
- a=req.get('texts',[])
53
- if not isinstance(a,list) or len(a)>24 or any(not isinstance(x,str) for x in a):raise Refusal('invalid_batch')
54
- return a
55
- def framed(t,kind):
56
- if kind not in ('query','passage'):raise Refusal('invalid_kind')
57
- return PINS['embedding']['queryInstruction' if kind=='query' else 'documentInstruction']+t
58
- def enc(t):
59
- ids=tok().encode(t,add_special_tokens=True).ids
60
- if len(ids)>8192:raise Refusal('token_limit')
61
- return ids
62
- SERVER_EXIT_GRACE_S=1.5 # longer than the package's 1 s SIGKILL of the group: under its custody a slow shutdown meets that SIGKILL (no crash report), never a second SIGTERM; the terminate() below serves a signal from outside it
63
- def close_native(signaled=False):
64
- global server,encoder_port,encoder_token
65
- if server is not None:
66
- # The group signal already reached llama-server; a second interrupt during its shutdown makes it abort (SIGABRT).
67
- if signaled:
68
- try:server.wait(timeout=SERVER_EXIT_GRACE_S)
69
- except subprocess.TimeoutExpired:pass
70
- if server.poll() is None:
71
- server.terminate()
72
- try:server.wait(timeout=.7)
73
- except subprocess.TimeoutExpired:server.kill();server.wait()
74
- server=None
75
- encoder_port=None;encoder_token=None
76
- def terminate(signum,frame):
77
- close_native(True);raise SystemExit(128+signum)
78
- for sig in (signal.SIGTERM,signal.SIGINT):signal.signal(sig,terminate)
79
- def load():
80
- global server,encoder_port,encoder_token
81
- if server is None:
82
- verify();env={k:v for k,v in os.environ.items() if not k.startswith(('LLAMA_','GGML_'))}
83
- executable=native_executable()
84
- transport=['--host','encoder.sock']
85
- if WINDOWS:
86
- encoder_token=secrets.token_hex(32)
87
- # Reserve an OS-selected loopback port until immediately before launch. A bind
88
- # collision is a start failure, never a retry to an unauthenticated endpoint.
89
- with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as reservation:
90
- reservation.bind(('127.0.0.1',0));encoder_port=reservation.getsockname()[1]
91
- transport=['--host','127.0.0.1','--port',str(encoder_port)]
92
- # Pinned common/arg.cpp supports LLAMA_API_KEY; server-http.cpp requires Bearer
93
- # on /props and embeddings, but /health is public. No token in process argv.
94
- env['LLAMA_API_KEY']=encoder_token
95
- def launch(limit):
96
- """The server, or None when it exits or is not healthy within `limit` seconds (it is then stopped)."""
97
- child=subprocess.Popen([str(executable),'-m',str(ROOT/'model.gguf'),'--embedding','--pooling','mean','--embd-normalize','2','--ctx-size','8192','--batch-size','8192','--ubatch-size','8192','--parallel','1','--n-gpu-layers','99','--cache-type-k','f32','--cache-type-v','f32','--flash-attn','off','--threads','4',*transport,'--no-webui','--log-disable'],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,env=env)
98
- started=time.monotonic()
99
- while child.poll() is None and time.monotonic()-started<=limit:
100
- try:
101
- if request('/health').get('status')=='ok':
102
- if WINDOWS:request('/props') # Public health alone is not authenticated readiness.
103
- if child.poll() is None:return child
104
- except (OSError,Refusal):pass
105
- time.sleep(.02)
106
- if child.poll() is None:
107
- child.kill();child.wait()
108
- return None
109
- # Semantic recall runs on Metal only (the project's platform choice): on Apple silicon it embeds a batch about 56 times faster than the
110
- # CPU did (0.7 s against 39 s for 8 passages at load 44-76). Where Metal cannot start (a VM, no GPU) the server exits or never becomes
111
- # healthy, and semantic recall goes off with that reason; word recall keeps working. A busy machine can take minutes to start it; the
112
- # limit stays under the host's start deadline (START_DEADLINE_MS, 600 s).
113
- # pi-tuck's own pinned server serves on the CPU, with only a log line, when it finds no Metal device: it must list one. A server a host
114
- # configures is its owner's choice and is not checked.
115
- own=os.environ.get('PI_SEMANTIC_OWN_SERVER_SHA256')
116
- if own and RUNTIME['read_json'](ROOT/'assets.sha256.json').get(executable.relative_to(ROOT).as_posix())==own:
117
- try:listed=subprocess.run([str(executable),'--list-devices'],stdin=subprocess.DEVNULL,capture_output=True,text=True,env=env,timeout=120)
118
- except (OSError,subprocess.TimeoutExpired):raise Refusal('metal_unavailable')
119
- if not any(line.strip().startswith('MTL') for line in (listed.stdout+'\n'+listed.stderr).splitlines()):raise Refusal('metal_unavailable')
120
- server=launch(540)
121
- if server is None:raise Refusal('metal_unavailable')
122
- return server
123
- def run(req):
124
- op=req['op']
125
- if op=='close':close_native();return {'closed':True}
126
- if op=='ready':
127
- verify()
128
- return {'identity':IDENTITY,'dimensions':768,'maxTokens':8192,'offline':True,'dtype':PINS['embedding']['dtype'],'computePrecision':'float32','pythonVersion':list(sys.version_info[:3]),'model':PINS['embedding']}
129
- if op=='tokenize':
130
- a=texts(req);kind=req.get('kind','passage')
131
- if req.get('split'):
132
- if kind!='passage':raise Refusal('query_split_forbidden')
133
- result=[]
134
- for t in a:
135
- offsets=tok().encode(t,add_special_tokens=False).offsets;ranges=[]
136
- if not offsets and t:ranges.append({'start':0,'end':len(t.encode('utf-16-le'))//2,'tokens':2})
137
- limit=req.get('maxTokens',256);overhead=len(enc(framed('',kind)));step=limit-overhead-4
138
- if not 1<=step<=8192-overhead:raise Refusal('invalid_chunk_limit')
139
- bounds=sorted(set([0,len(t)]+[offsets[i][0] for i in range(step,len(offsets),step)]))
140
- for start,end in zip(bounds,bounds[1:]):
141
- count=len(enc(framed(t[start:end],kind)))
142
- if count>limit:raise Refusal('chunk_token_limit')
143
- ranges.append({'start':len(t[:start].encode('utf-16-le'))//2,'end':len(t[:end].encode('utf-16-le'))//2,'tokens':count})
144
- result.append(ranges)
145
- return {'ranges':result,'offsetUnit':'utf16'}
146
- return {'counts':[len(tok().encode(framed(t,kind),add_special_tokens=True).ids) for t in a],'maxTokens':8192}
147
- if op=='embed':
148
- a=texts(req);kind=req.get('kind','passage')
149
- if len(a)>8:raise Refusal('batch_limit')
150
- ids=[enc(framed(t,kind)) for t in a]
151
- if not a:return {'vectors':[],'identity':IDENTITY}
152
- load();out=request('/v1/embeddings',{'input':ids,'encoding_format':'float','truncate':False},len(ids))['data'];out.sort(key=lambda row:row['index']);vectors=[row['embedding'] for row in out]
153
- if len(vectors)!=len(a) or any(len(v)!=768 or any(not math.isfinite(x) for x in v) or abs(sum(x*x for x in v)**.5-1)>1e-5 for v in vectors):raise Refusal('invalid_vector')
154
- return {'vectors':vectors,'identity':IDENTITY,'nativePID':server.pid}
155
- if op=='index':return index(req)
156
- raise Refusal('unknown_op')
157
- def index(r):
158
- path=pathlib.Path(r['path']).resolve()
159
- project=pathlib.Path(r.get('projectDirectory',os.getcwd())).resolve()
160
- if path==project or project in path.parents:raise Refusal('index_requires_external_path')
161
- supplied=pathlib.Path(r['path'])
162
- if not supplied.is_absolute() or ROOT==path or ROOT in path.parents:raise Refusal('index_requires_external_path')
163
- if any(part.is_symlink() for part in (supplied,*supplied.parents)):raise Refusal('index_symlink_forbidden')
164
- readonly=r['action'] in ('status','score')
165
- if readonly and not path.exists():return {'coveredKeys':[]} if r['action']=='status' else {'ranked':[],'observed':0}
166
- if not readonly:path.parent.mkdir(parents=True,exist_ok=True)
167
- db=sqlite3.connect(path.as_uri()+'?mode=ro',uri=True) if readonly else sqlite3.connect(str(path))
168
- if not readonly:
169
- db.execute('PRAGMA max_page_count=8192')
170
- db.execute('PRAGMA secure_delete=ON')
171
- if not readonly:db.execute('CREATE TABLE IF NOT EXISTS records (key TEXT PRIMARY KEY,entryId TEXT NOT NULL,start INTEGER NOT NULL,end INTEGER NOT NULL,inputSha TEXT NOT NULL,identity TEXT NOT NULL,vector BLOB NOT NULL)')
172
- try:
173
- action=r['action'];identity=r['identity']
174
- if action=='reconcile':
175
- keys=r['keys']
176
- if len(keys)>10000:raise Refusal('record_limit')
177
- allowed=set(keys)
178
- remove=[x[0] for x in db.execute('SELECT key,identity FROM records') if x[0] not in allowed or x[1]!=identity]
179
- db.executemany('DELETE FROM records WHERE key=?',[(x,) for x in remove]);out={'removed':len(remove)}
180
- elif action=='delete':
181
- keys=r['keys']
182
- if len(keys)>10000:raise Refusal('record_limit')
183
- db.executemany('DELETE FROM records WHERE key=?',[(x,) for x in keys]);out={'deleted':len(keys)}
184
- elif action=='upsert':
185
- rows=r['rows']
186
- if len(rows)>8:raise Refusal('batch_limit')
187
- for x in rows:
188
- v=x['vector']
189
- if len(v)!=768 or any(not math.isfinite(y) for y in v):raise Refusal('invalid_vector')
190
- if x['start']<0 or x['end']<x['start']:raise Refusal('invalid_range')
191
- if any(not isinstance(x[k],str) or len(x[k])>1024 for k in ('key','entryId','inputSha')) or len(identity)>1024:raise Refusal('metadata_limit')
192
- db.execute('INSERT OR REPLACE INTO records VALUES(?,?,?,?,?,?,?)',(x['key'],x['entryId'],x['start'],x['end'],x['inputSha'],identity,struct.pack('<768f',*v)))
193
- if db.execute('SELECT count(*) FROM records').fetchone()[0]>10000:raise Refusal('record_limit')
194
- out={'upserted':len(rows)}
195
- elif action=='status':
196
- keys=r['keys']
197
- if len(keys)>10000:raise Refusal('record_limit')
198
- out={'coveredKeys':[x[0] for x in db.execute(f"SELECT key FROM records WHERE identity=? AND key IN ({','.join('?' for _ in keys)}) ORDER BY rowid",(identity,*keys))] if keys else []}
199
- elif action=='score':
200
- # Dot product of every requested stored vector with the query, in key order: 128-key sub-batches, each in rowid order, a plain sequential float64 sum
201
- # (bit-identical to the node reduce this replaced; sum(), math.sumprod and numpy are not). Returns the stable top 24 by descending score, and how many rows were found.
202
- keys=r['keys'];query=r['query']
203
- if len(keys)>10000:raise Refusal('record_limit')
204
- if len(query)!=768 or any(not math.isfinite(y) for y in query):raise Refusal('invalid_vector')
205
- scored=[]
206
- for i in range(0,len(keys),128):
207
- part=keys[i:i+128]
208
- for x in db.execute(f"SELECT key,vector FROM records WHERE identity=? AND key IN ({','.join('?' for _ in part)}) ORDER BY rowid",(identity,*part)):
209
- s=0.0
210
- for a,b in zip(struct.unpack('<768f',x[1]),query):s+=a*b
211
- scored.append((x[0],s))
212
- scored.sort(key=lambda t:t[1],reverse=True) # reverse=True keeps equal scores in their original order
213
- out={'ranked':[{'key':k,'score':s} for k,s in scored[:24]],'observed':len(scored)}
214
- else:raise Refusal('unknown_index_action')
215
- db.commit();return out
216
- except:db.rollback();raise
217
- finally:db.close()
218
- try:
219
- while True:
220
- line=sys.stdin.buffer.readline(1048577)
221
- if not line:break
222
- if len(line)>1048576 and not line.endswith(b'\n'):
223
- while True:
224
- tail=sys.stdin.buffer.readline(1048577)
225
- if not tail or tail.endswith(b'\n'):break
226
- req={}
227
- try:
228
- if len(line)>1048576:raise Refusal('input_limit')
229
- req=json.loads(line);result=run(req);response={'id':req.get('id'),'ok':True,'result':result}
230
- except Refusal as e:response={'id':req.get('id'),'ok':False,'error':{'code':str(e)}}
231
- except Exception:response={'id':req.get('id'),'ok':False,'error':{'code':'local_runtime_failure'}}
232
- print(json.dumps(response,separators=(',',':')),flush=True)
233
- if req.get('op')=='close':break
234
- finally:close_native()
package/src/assets.ts DELETED
@@ -1,92 +0,0 @@
1
- // Everything semantic recall's local runtime is built from: a public source and its SHA-256 for each file. setup.ts downloads and
2
- // verifies these, and a change to any of them gives the runtime a new id, so an update provisions beside the old runtime, never over it.
3
-
4
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
- import { createHash } from "node:crypto";
6
- import { join } from "node:path";
7
-
8
- export interface Download { url: string; sha256: string; size: number }
9
-
10
- /** Where pi-tuck keeps the runtime, its downloads and the indexes: one folder, so deleting it removes all of them. */
11
- export const defaultRoot = () => join(getAgentDir(), "pi-tuck");
12
-
13
- const MODEL_REVISION = "031f0d4b35536f69ab3509d4893c923264fcf253", TOKENIZER_REVISION = "914f7f89142e33e77833254d9c9b90c3cef7303b";
14
- const LLAMA_COMMIT = "988190680d5a89fce97de3c20df2c2813731fd61";
15
-
16
- /** A relocatable CPython for macOS arm64; the runtime's virtual environment is made from it and keeps pointing at it. */
17
- export const PYTHON: Download & { version: string; name: string } = {
18
- name: "cpython-3.13.18+20261026", version: "3.13", size: 25394044,
19
- url: "https://github.com/astral-sh/python-build-standalone/releases/download/20261026/cpython-3.13.18%2B20261026-aarch64-apple-darwin-install_only.tar.gz",
20
- sha256: "e5af2fde6a937a0e0c795a0c595c4efb70578d57463a2657c819992b9b9acbac",
21
- };
22
-
23
- /** EmbeddingGemma-2, 8-bit GGUF. */
24
- export const MODEL: Download = {
25
- url: `https://huggingface.co/unsloth/embeddinggemma-2-GGUF/resolve/${MODEL_REVISION}/embeddinggemma-2-Q8_0.gguf`,
26
- sha256: "6f1bd4ac6c5df7444f9cca7ca36cafe6cfa34cd6f49fefb1e0b4be8143aed8bc", size: 309855520,
27
- };
28
-
29
- /** The model's own tokenizer: passages are split on its token offsets. */
30
- export const TOKENIZER: Download = {
31
- url: `https://huggingface.co/google/embeddinggemma-2/resolve/${TOKENIZER_REVISION}/tokenizer.json`,
32
- sha256: "4d777ef5bdc1aa36227abdfb77c3e49e7b9c892d16e1b6bda41c393504828be4", size: 32170510,
33
- };
34
-
35
- /** llama.cpp release b11476 (commit 988190680d5a). `files` are the server and the libraries it loads from its own folder; the archive
36
- * names most libraries through symlinks, which the runtime refuses, so each is copied as a plain file under the name the server loads. */
37
- export const LLAMA: Download & { folder: string; files: Record<string, string>; license: string } = {
38
- url: "https://github.com/ggml-org/llama.cpp/releases/download/b11476/llama-b11476-bin-macos-arm64.tar.gz",
39
- sha256: "577634a1b8a59e8dabe02ba10de1e610be0574dfaf1cf3020e6dd42853ed877e", size: 12012019,
40
- folder: "llama-b11476",
41
- files: {
42
- "llama-server": "1bf5602a2be50097c44282a6ecc63234d94ee8f96d39fd45fed6eff4e74b6b41",
43
- "libllama-server-impl.dylib": "d699e1d7f0b3d5c63c9e7cd88c50e37c96cbf64802dbcefdc784983565a29608",
44
- "libllama-common.0.dylib": "e90e6f5bba4ff114f7fb9ed1328171b1c4eceac71ee8923178f5d417310b0d4e",
45
- "libmtmd.0.dylib": "c87488222bc71275f75da743e8cc628b014b59d051bc0e303c444e96f54762a7",
46
- "libllama.0.dylib": "423bd595e045f0bb8225ad721571d5ab9842815f1b975f2462d2c7c8e0594bd7",
47
- "libggml.0.dylib": "85ac40d540a5cc86f28a70270ddcdde677e92eb585c3bacd1b7e82270fe8934b",
48
- "libggml-cpu.0.dylib": "937073375f79a187d8fda2e3900a9095e979593b691d6bbb146956743ceddd82",
49
- "libggml-blas.0.dylib": "6526259e8f70a5b3a394df3ba082050c290d7653846efbdc84b3710b22fb4eac",
50
- "libggml-metal.0.dylib": "a40058fab152c973339e40e80df900c1b311e06bcfb4c1c473cb169c7ee88a5c",
51
- "libggml-rpc.0.dylib": "48c13b7c2c56e2b569b636e6a28d1c0853ad2d1db1980c0afd374651c6e897d0",
52
- "libggml-base.0.dylib": "6fba8bb7fb529801d1b73782ac1707b653b1ea4caf53f667b85bc801e2883326",
53
- },
54
- license: "94f29bbed6a22c35b992c5c6ebf0e7c92f13b836b90f36f461c9cf2f0f1d010d",
55
- };
56
-
57
- const pypi = (path: string, sha256: string, size: number): Download => ({ url: "https://files.pythonhosted.org/packages/" + path, sha256, size });
58
- /** The tokenizer library and its declared dependencies, installed offline with hash checking. */
59
- export const WHEELS: Record<string, Download> = {
60
- "anyio-4.15.1-py3-none-any.whl": pypi("12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", "6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", 132079),
61
- "certifi-2026.7.22-py3-none-any.whl": pypi("0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", "62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", 136983),
62
- "click-8.5.0-py3-none-any.whl": pypi("58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", "255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", 125251),
63
- "filelock-4.0.12-py3-none-any.whl": pypi("da/a1/b047e1c486a2c66283633b7dbb73872ca16ca1ce6a426f70d4d037fc8e1c/filelock-4.0.12-py3-none-any.whl", "5f17ee83ecee8a6f3e389c75822fb70a1c2f0506b99438a6dffa1d56793588c8", 111732),
64
- "fsspec-2026.9.0-py3-none-any.whl": pypi("6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl", "8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f", 221738),
65
- "h11-0.16.0-py3-none-any.whl": pypi("04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", "63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", 37515),
66
- "hf_xet-1.7.0-cp38-abi3-macosx_11_0_arm64.whl": pypi("c3/47/a26ebdce7056a61e931f228439bc0ab08cbec239d1690f965e5e637cba79/hf_xet-1.7.0-cp38-abi3-macosx_11_0_arm64.whl", "59fba37039233c7fcbe196817d6cdcf1b40dfb17b410f229d85b0cf0a1848da4", 3560352),
67
- "httpcore-1.0.9-py3-none-any.whl": pypi("7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", "2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", 78784),
68
- "httpx-0.28.1-py3-none-any.whl": pypi("2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", "d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", 73517),
69
- "huggingface_hub-1.33.0-py3-none-any.whl": pypi("fc/16/963096d224b80909432dc16561a615fd33d2d13beef3ce4c63fa25e40867/huggingface_hub-1.33.0-py3-none-any.whl", "04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899", 846435),
70
- "idna-3.20-py3-none-any.whl": pypi("58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", "ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", 69583),
71
- "packaging-26.3-py3-none-any.whl": pypi("63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", "d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", 129956),
72
- "pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl": pypi("b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", "2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", 173252),
73
- "tokenizers-0.23.2-cp310-abi3-macosx_11_0_arm64.whl": pypi("67/49/22da045a91732384d3a3771816bf188dc5a1f702c32e635afa7c679c0bef/tokenizers-0.23.2-cp310-abi3-macosx_11_0_arm64.whl", "986670e43691469dcee610ea0f846f91a8f84e91fc6f7a48d4c064414c0ec2bf", 3101593),
74
- "tqdm-4.70.1-py3-none-any.whl": pypi("a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", "c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", 80199),
75
- "typing_extensions-4.16.0-py3-none-any.whl": pypi("49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", "481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", 45571),
76
- };
77
-
78
- /** What scripts/eg2-runtime.py checks the runtime against: the model, its encoding contract and the native build. */
79
- export const PINS = {
80
- embedding: { model: "google/embeddinggemma-2", revision: TOKENIZER_REVISION, dimensions: 768, maxTokens: 8192,
81
- queryInstruction: "task: search result | query: ", documentInstruction: "title: none | text: ",
82
- pooling: "mask-aware mean including prompt, projected token states, then float32 L2", dtype: "Q8_0", textOnly: true },
83
- runtime: { tokenizers: "0.23.2", python: PYTHON.version },
84
- backend: { name: "llama.cpp", commit: LLAMA_COMMIT, artifact: "Q8_0", computePrecision: "float32", gpuLayers: 0,
85
- compute: "CPU float32 with f32 KV; quantized weights where selected", modelRepository: "unsloth/embeddinggemma-2-GGUF",
86
- modelRevision: MODEL_REVISION, modelSHA256: MODEL.sha256 },
87
- };
88
-
89
- /** A digest of every pinned input: a changed pin provisions a new runtime beside the old one instead of mutating it. */
90
- export const RUNTIME_ID = createHash("sha256").update(JSON.stringify({ PYTHON, MODEL, TOKENIZER, LLAMA, WHEELS, PINS })).digest("hex").slice(0, 16);
91
- /** The provisioned runtime's configuration, written last by provisioning: its presence means the runtime is complete. */
92
- export const runtimeConfigPath = (root: string) => join(root, "runtime", RUNTIME_ID, "semantic-recall.json");
@@ -1,43 +0,0 @@
1
- import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
- import type { RecallPolicy } from './recall';
3
- import { semanticEligibleSources } from './semantic-recall';
4
-
5
- type Context = Pick<ExtensionContext, 'sessionManager' | 'cwd'>;
6
- type Snapshot = ReturnType<typeof semanticEligibleSources>;
7
- // The controller fills `units`, `complete`, `indexed` and `window` on the snapshot it is given, so a hit never hands out the stored object. Only
8
- // what the build derives from the session and nothing later changes is stored; a hit gets fresh `units`, `complete` and `indexed`, and no
9
- // `window` (`prepare` assigns it). A required field added to the snapshot is a type error in the hit literal below, but an optional one (as
10
- // `window` is) is not: it would be dropped on a hit and present on a miss. The structural test in eligibility-cache.test.ts classifies every
11
- // field of a snapshot exactly and fails on an unclassified one.
12
- type Immutable = Pick<Snapshot, 'id' | 'session' | 'project' | 'sources' | 'throughEntryId' | 'viewStart'>;
13
- interface Entry { policy: RecallPolicy | undefined; key: readonly unknown[]; stored: Immutable }
14
-
15
- const cache = new WeakMap<object, Entry>();
16
-
17
- /** The one place that decides when the snapshot stored for a session manager and policy is still the snapshot a rebuild would give, and when `tuck_search` must rerun its lexical offer after its await: Pi entries
18
- * are append-only, so a new entry changes the entry count, and a branch switch changes the leaf. Change what invalidates it here and nowhere else.
19
- * The lexical recheck in `tuck_search` relies on the same contract: `tuckRecall` is pure in (entries, branch, input, policy) whenever it returns (its only clock use is a 3 s abort that throws), so an unchanged key across the await means an unchanged
20
- * lexical offer and the second pass is skipped (`eligibilityKeyMoved`). An entry edited in place
21
- * after it was appended, a `readAttemptMarker` with hidden state, or a policy mutated after install is outside this contract for both uses. */
22
- export function eligibilityKey(ctx: Context): readonly unknown[] {
23
- const manager = ctx.sessionManager;
24
- return [manager.getSessionId(), ctx.cwd, manager.getLeafId(), manager.getBranch().length, manager.getEntries().length];
25
- }
26
-
27
- const same = (a: readonly unknown[], b: readonly unknown[]) => a.length === b.length && a.every((value, i) => Object.is(value, b[i]));
28
- /** Whether the session moved since `since` was taken from `eligibilityKey(ctx)`. */
29
- export const eligibilityKeyMoved = (ctx: Context, since: readonly unknown[]) => !same(since, eligibilityKey(ctx));
30
-
31
- /** `semanticEligibleSources` for an unchanged session without the rebuild. `access()` runs on every call, hits included, and a throw is
32
- * the same `SemanticAccessError` that `semanticEligibleSources` raises (the mapping below is that function's first statement, verbatim).
33
- * The policy is trusted by identity, so it must not change after install: a policy object mutated in place (a type added to
34
- * `privateCustomTypes`) or a `readAttemptMarker` with hidden state is not noticed until the history changes. */
35
- export function memoizedEligibleSources(ctx: Context, policy: RecallPolicy | undefined, access: () => void, pendingKeptId?: string): Snapshot {
36
- try { access(); } catch (error) { throw Object.assign(new Error(error instanceof Error ? error.message : 'Source access denied'), { name: 'SemanticAccessError' }); }
37
- const key = [...eligibilityKey(ctx), pendingKeptId ?? null], held = cache.get(ctx.sessionManager);
38
- if (held && held.policy === policy && same(held.key, key)) return { ...held.stored, units: [], complete: false, indexed: new Set() };
39
- // Access was checked on the line above with nothing awaited in between, so the rebuild does not check it a second time.
40
- const built = semanticEligibleSources(ctx, policy ?? {}, () => {}, pendingKeptId);
41
- cache.set(ctx.sessionManager, { policy, key, stored: { id: built.id, session: built.session, project: built.project, sources: built.sources, throughEntryId: built.throughEntryId, viewStart: built.viewStart } });
42
- return built;
43
- }