memoryking 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- memoryking/__init__.py +3 -0
- memoryking/__main__.py +1328 -0
- memoryking/adapters/__init__.py +1 -0
- memoryking/adapters/adapter_state.py +242 -0
- memoryking/adapters/anchor_schema.sql +7 -0
- memoryking/adapters/atlas.py +441 -0
- memoryking/adapters/browser_commands.py +125 -0
- memoryking/adapters/dashboard.py +510 -0
- memoryking/adapters/dense_search.py +86 -0
- memoryking/adapters/egress_policy.py +244 -0
- memoryking/adapters/egress_schema.sql +13 -0
- memoryking/adapters/embedding.schema.json +302 -0
- memoryking/adapters/embedding_store.py +469 -0
- memoryking/adapters/execution.py +369 -0
- memoryking/adapters/experience.py +423 -0
- memoryking/adapters/experience.schema.json +1508 -0
- memoryking/adapters/experience_records.py +239 -0
- memoryking/adapters/experience_schema.sql +23 -0
- memoryking/adapters/handoff.py +494 -0
- memoryking/adapters/handoff.schema.json +299 -0
- memoryking/adapters/handoff_schema.sql +17 -0
- memoryking/adapters/index_schema.sql +11 -0
- memoryking/adapters/inference.py +454 -0
- memoryking/adapters/inference.schema.json +541 -0
- memoryking/adapters/inspection.py +1128 -0
- memoryking/adapters/inspection.schema.json +568 -0
- memoryking/adapters/knowledge.schema.json +633 -0
- memoryking/adapters/knowledge_schema.sql +37 -0
- memoryking/adapters/knowledge_store.py +800 -0
- memoryking/adapters/legacy_snapshot.py +358 -0
- memoryking/adapters/legacy_tables.py +49 -0
- memoryking/adapters/local_contract.py +45 -0
- memoryking/adapters/local_embeddings.py +189 -0
- memoryking/adapters/local_files.py +242 -0
- memoryking/adapters/local_ipc.py +258 -0
- memoryking/adapters/local_schema.sql +44 -0
- memoryking/adapters/local_store.py +632 -0
- memoryking/adapters/local_wire.schema.json +7672 -0
- memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/optional_schema.sql +43 -0
- memoryking/adapters/plan_dashboard.py +51 -0
- memoryking/adapters/plans.py +253 -0
- memoryking/adapters/postgres_admin.py +300 -0
- memoryking/adapters/postgres_anchor_schema.sql +9 -0
- memoryking/adapters/postgres_counter.sql +14 -0
- memoryking/adapters/postgres_egress_schema.sql +15 -0
- memoryking/adapters/postgres_experience_schema.sql +39 -0
- memoryking/adapters/postgres_index_schema.sql +7 -0
- memoryking/adapters/postgres_optional_schema.sql +71 -0
- memoryking/adapters/postgres_pool.py +77 -0
- memoryking/adapters/postgres_recovery.py +525 -0
- memoryking/adapters/postgres_schema.sql +365 -0
- memoryking/adapters/postgres_sql.py +102 -0
- memoryking/adapters/postgres_store.py +428 -0
- memoryking/adapters/postgres_summary_schema.sql +12 -0
- memoryking/adapters/postgres_trust_schema.sql +20 -0
- memoryking/adapters/processing.schema.json +471 -0
- memoryking/adapters/processing_store.py +346 -0
- memoryking/adapters/projects.py +83 -0
- memoryking/adapters/proposals.py +238 -0
- memoryking/adapters/ranking.py +315 -0
- memoryking/adapters/repository.schema.json +664 -0
- memoryking/adapters/repository_git.py +264 -0
- memoryking/adapters/repository_schema.sql +25 -0
- memoryking/adapters/repository_store.py +960 -0
- memoryking/adapters/retrieval.py +1285 -0
- memoryking/adapters/retrieval.schema.json +553 -0
- memoryking/adapters/retrieval_schema.sql +10 -0
- memoryking/adapters/shared_control.py +40 -0
- memoryking/adapters/shared_dashboard.py +636 -0
- memoryking/adapters/shared_gateway.py +63 -0
- memoryking/adapters/shared_http.py +216 -0
- memoryking/adapters/shared_mcp.py +159 -0
- memoryking/adapters/shared_service.py +124 -0
- memoryking/adapters/stdio.py +193 -0
- memoryking/adapters/stdio.tools.json +6776 -0
- memoryking/adapters/summary_schema.sql +10 -0
- memoryking/adapters/team.py +253 -0
- memoryking/adapters/timeline.py +80 -0
- memoryking/adapters/token_count.py +55 -0
- memoryking/adapters/tokenizers/LICENSE +21 -0
- memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
- memoryking/adapters/trust.py +123 -0
- memoryking/adapters/trust_schema.sql +13 -0
- memoryking/adapters/web/app.css +1251 -0
- memoryking/adapters/web/app.js +907 -0
- memoryking/adapters/web/brand.js +44 -0
- memoryking/adapters/web/crown-mono.svg +1 -0
- memoryking/adapters/web/crown.svg +8 -0
- memoryking/adapters/web/elephant.png +0 -0
- memoryking/adapters/web/favicon.svg +8 -0
- memoryking/adapters/web/graph-layout.js +52 -0
- memoryking/adapters/web/graph-worker.js +10 -0
- memoryking/adapters/web/graph.js +570 -0
- memoryking/adapters/web/index.html +208 -0
- memoryking/adapters/web/observatory.js +1208 -0
- memoryking/adapters/web/team.js +151 -0
- memoryking/adapters/web/wordmark.svg +1 -0
- memoryking/adapters/working.py +971 -0
- memoryking/adapters/working.schema.json +1717 -0
- memoryking/adapters/working_schema.sql +24 -0
- memoryking/application/__init__.py +1 -0
- memoryking/application/conformance.py +50 -0
- memoryking/application/legacy_import.py +337 -0
- memoryking/application/local_port.py +9 -0
- memoryking/application/storage.py +117 -0
- memoryking/application/store_core.py +1292 -0
- memoryking/backups.py +131 -0
- memoryking/contracts/__init__.py +6 -0
- memoryking/contracts/__main__.py +20 -0
- memoryking/contracts/canonical.py +88 -0
- memoryking/contracts/embedding.schema.json +302 -0
- memoryking/contracts/embedding_generated.py +65 -0
- memoryking/contracts/experience.schema.json +1508 -0
- memoryking/contracts/experience_generated.py +239 -0
- memoryking/contracts/generated.py +122 -0
- memoryking/contracts/handoff.schema.json +299 -0
- memoryking/contracts/handoff_generated.py +69 -0
- memoryking/contracts/inference.schema.json +541 -0
- memoryking/contracts/inference_generated.py +106 -0
- memoryking/contracts/processing.schema.json +471 -0
- memoryking/contracts/processing_generated.py +82 -0
- memoryking/contracts/py.typed +0 -0
- memoryking/contracts/repository.schema.json +664 -0
- memoryking/contracts/repository_generated.py +144 -0
- memoryking/contracts/retrieval.schema.json +553 -0
- memoryking/contracts/retrieval_generated.py +110 -0
- memoryking/contracts/schema.json +696 -0
- memoryking/contracts/validation.py +92 -0
- memoryking/contracts/working.schema.json +1717 -0
- memoryking/contracts/working_generated.py +291 -0
- memoryking/domain/__init__.py +1 -0
- memoryking/domain/anchors.py +97 -0
- memoryking/domain/briefing.py +108 -0
- memoryking/domain/briefing_text.py +222 -0
- memoryking/domain/checkpoint.py +118 -0
- memoryking/domain/compression.py +64 -0
- memoryking/domain/delta.py +129 -0
- memoryking/domain/embeddings.py +90 -0
- memoryking/domain/hints.py +465 -0
- memoryking/domain/http_status.py +45 -0
- memoryking/domain/learning.py +62 -0
- memoryking/domain/local.py +65 -0
- memoryking/domain/plans.py +140 -0
- memoryking/domain/repository.py +118 -0
- memoryking/domain/selectors.py +356 -0
- memoryking/domain/summary.py +88 -0
- memoryking/domain/usage.py +163 -0
- memoryking/embedding_loop.py +98 -0
- memoryking/embedding_worker.py +131 -0
- memoryking/harness.py +882 -0
- memoryking/harness_context.py +376 -0
- memoryking/hooks.py +171 -0
- memoryking/host_hooks.py +454 -0
- memoryking/lean.py +352 -0
- memoryking/memory_tool.py +776 -0
- memoryking/migration.py +194 -0
- memoryking/model_install.py +78 -0
- memoryking/observability.py +101 -0
- memoryking/observability_metrics.py +100 -0
- memoryking/profiles.py +150 -0
- memoryking/providers.py +330 -0
- memoryking/py.typed +0 -0
- memoryking/pytest_plugin.py +69 -0
- memoryking/reference_agent.py +152 -0
- memoryking/repository_worker.py +57 -0
- memoryking/resume_adapter.py +154 -0
- memoryking/sdk.py +302 -0
- memoryking/shared.py +301 -0
- memoryking/shared_sdk.py +101 -0
- memoryking/vault.py +176 -0
- memoryking-0.1.0.dist-info/METADATA +157 -0
- memoryking-0.1.0.dist-info/RECORD +179 -0
- memoryking-0.1.0.dist-info/WHEEL +5 -0
- memoryking-0.1.0.dist-info/entry_points.txt +7 -0
- memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
- memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
- memoryking-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""Trusted reference context and local recording provider; no network provider support.
|
|
2
|
+
|
|
3
|
+
The caller is trusted host code, never model output. Host authorization is explicit;
|
|
4
|
+
ordinary SDK/stdio clients do not acquire this protection automatically.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
import hashlib
|
|
11
|
+
import re
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from memoryking.adapters.egress_policy import LOCAL_MODEL, LOCAL_PROVIDER, LOCAL_REVISION
|
|
19
|
+
from memoryking.adapters.local_files import atomic, private_dir, private_file
|
|
20
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash, load_strict
|
|
21
|
+
from memoryking.domain.local import LocalError
|
|
22
|
+
from memoryking.providers import HttpAdapter
|
|
23
|
+
from memoryking.sdk import BINDING_FIELDS, LocalClient
|
|
24
|
+
|
|
25
|
+
EGRESS_REVISION = LOCAL_REVISION
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def digest(data: bytes) -> str:
|
|
29
|
+
return hashlib.sha256(data).hexdigest()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class LocalRecordingProvider:
|
|
33
|
+
"""A deterministic local echo with actual request files and hidden-context handles.
|
|
34
|
+
|
|
35
|
+
It does not implement a language model or transmit any data. Records are private
|
|
36
|
+
and are deliberately retained: rebuilding a conversation does not erase delivery.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, directory: Path):
|
|
40
|
+
private_dir(directory, create=True)
|
|
41
|
+
self.directory = directory
|
|
42
|
+
|
|
43
|
+
def path(self, handle: str) -> Path:
|
|
44
|
+
if re.fullmatch(r"conversation_[a-f0-9]{32}", handle) is None:
|
|
45
|
+
raise LocalError("provider_handle_invalid")
|
|
46
|
+
return self.directory / (handle + ".json")
|
|
47
|
+
|
|
48
|
+
def effective_messages(self, request: dict[str, Any]) -> list[dict[str, str]]:
|
|
49
|
+
messages: list[dict[str, str]] = []
|
|
50
|
+
visited: set[str] = set()
|
|
51
|
+
|
|
52
|
+
def expand(value: dict[str, Any]) -> None:
|
|
53
|
+
for handle in value["state_handles"]:
|
|
54
|
+
identifier = handle["id"]
|
|
55
|
+
if identifier in visited:
|
|
56
|
+
continue
|
|
57
|
+
if len(visited) >= 32:
|
|
58
|
+
raise LocalError("provider_context_limit")
|
|
59
|
+
visited.add(identifier)
|
|
60
|
+
path = self.path(identifier)
|
|
61
|
+
try:
|
|
62
|
+
private_file(path)
|
|
63
|
+
with path.open("rb") as stream:
|
|
64
|
+
raw = stream.read(98305)
|
|
65
|
+
if len(raw) > 98304:
|
|
66
|
+
raise LocalError("provider_context_limit")
|
|
67
|
+
previous = load_strict(raw)
|
|
68
|
+
except OSError as exc:
|
|
69
|
+
raise LocalError("provider_handle_unavailable") from exc
|
|
70
|
+
expand(previous)
|
|
71
|
+
messages.extend(value["messages"])
|
|
72
|
+
|
|
73
|
+
expand(request)
|
|
74
|
+
return messages
|
|
75
|
+
|
|
76
|
+
def dispatch(self, raw: bytes) -> dict[str, str]:
|
|
77
|
+
request = load_strict(raw)
|
|
78
|
+
if (
|
|
79
|
+
canonical_bytes(request) != raw
|
|
80
|
+
or request["provider"] != "local-recording"
|
|
81
|
+
or request["model"] != "echo-v1"
|
|
82
|
+
):
|
|
83
|
+
raise LocalError("provider_request_invalid")
|
|
84
|
+
self.effective_messages(request) # Resolve the actual hidden state before accepting.
|
|
85
|
+
handle = "conversation_" + uuid.uuid4().hex
|
|
86
|
+
path = self.path(handle)
|
|
87
|
+
atomic(path, raw)
|
|
88
|
+
# This deterministic response deliberately carries input content, exercising
|
|
89
|
+
# the dependency inheritance required of a real provider's derived output.
|
|
90
|
+
return {
|
|
91
|
+
"content": "Local echo: " + request["messages"][-1]["content"],
|
|
92
|
+
"handle": handle,
|
|
93
|
+
"request_path": str(path),
|
|
94
|
+
"request_hash": digest(raw),
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# Messages per dispatch; the request as a whole is also bounded at 96 KiB by the store.
|
|
99
|
+
MESSAGE_LIMIT = 128
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class AuthorizedConversation:
|
|
103
|
+
"""A full-context reference dispatcher. No automatic retry or implicit rebinding."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, client: LocalClient, provider: LocalRecordingProvider | HttpAdapter):
|
|
106
|
+
# An arbitrary callback could rewrite bytes, leak data, or hide remote state. The
|
|
107
|
+
# only providers are the local recorder and the reviewed adapters, and an adapter
|
|
108
|
+
# must have been built from the policy the daemon itself enforces.
|
|
109
|
+
if type(provider) is not LocalRecordingProvider and not isinstance(provider, HttpAdapter):
|
|
110
|
+
raise LocalError("provider_not_supported")
|
|
111
|
+
self._lock = threading.RLock()
|
|
112
|
+
self._monotonic_ns = time.monotonic_ns
|
|
113
|
+
self.client, self.provider = client, provider
|
|
114
|
+
self._binding: dict[str, Any] | None = None
|
|
115
|
+
self._messages: list[dict[str, str]] = []
|
|
116
|
+
self._proofs: list[dict[str, Any]] = []
|
|
117
|
+
self._handles: list[dict[str, str]] = []
|
|
118
|
+
self._handle_proofs: list[dict[str, Any]] = []
|
|
119
|
+
self.context_epoch = 0
|
|
120
|
+
self.model_session_id = "session_" + uuid.uuid4().hex
|
|
121
|
+
self._sync()
|
|
122
|
+
|
|
123
|
+
def _discard(self) -> None:
|
|
124
|
+
self._messages.clear()
|
|
125
|
+
self._proofs.clear()
|
|
126
|
+
self._handles.clear()
|
|
127
|
+
self._handle_proofs.clear()
|
|
128
|
+
self.context_epoch += 1
|
|
129
|
+
self.model_session_id = "session_" + uuid.uuid4().hex
|
|
130
|
+
|
|
131
|
+
def reset(self) -> None:
|
|
132
|
+
"""Call after the owning harness's pre-reset checkpoint has succeeded."""
|
|
133
|
+
with self._lock:
|
|
134
|
+
self._discard()
|
|
135
|
+
|
|
136
|
+
def rebind(self, client: LocalClient) -> None:
|
|
137
|
+
"""Identity/history changes start empty; no old host requirements migrate."""
|
|
138
|
+
with self._lock:
|
|
139
|
+
self._discard()
|
|
140
|
+
self._binding = None
|
|
141
|
+
self.client = client
|
|
142
|
+
self._sync()
|
|
143
|
+
|
|
144
|
+
def _sync(self) -> dict[str, Any]:
|
|
145
|
+
try:
|
|
146
|
+
context = self.client.context()
|
|
147
|
+
except Exception:
|
|
148
|
+
self._discard()
|
|
149
|
+
raise
|
|
150
|
+
current = {
|
|
151
|
+
key: context[key] for key in (*BINDING_FIELDS, "authorization_epoch", "purge_epoch")
|
|
152
|
+
}
|
|
153
|
+
current["delegation_chain"] = context.get("delegation_chain", [])
|
|
154
|
+
current["egress_policy_revision"] = context.get("egress_policy_revision", EGRESS_REVISION)
|
|
155
|
+
if self._binding is not None and self._binding != current:
|
|
156
|
+
self._discard()
|
|
157
|
+
self._binding = current
|
|
158
|
+
if (
|
|
159
|
+
isinstance(self.provider, HttpAdapter)
|
|
160
|
+
and self.provider.policy_revision != current["egress_policy_revision"]
|
|
161
|
+
):
|
|
162
|
+
# The adapter was built from a policy the daemon no longer enforces.
|
|
163
|
+
self._discard()
|
|
164
|
+
raise LocalError("provider_not_supported")
|
|
165
|
+
return {
|
|
166
|
+
**current,
|
|
167
|
+
"model_session_id": self.model_session_id,
|
|
168
|
+
"context_epoch": self.context_epoch,
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
def remote(self) -> bool:
|
|
173
|
+
return isinstance(self.provider, HttpAdapter)
|
|
174
|
+
|
|
175
|
+
def add_host(
|
|
176
|
+
self,
|
|
177
|
+
content: str,
|
|
178
|
+
*,
|
|
179
|
+
authorization_id: str,
|
|
180
|
+
classification: str,
|
|
181
|
+
expires_ms: int,
|
|
182
|
+
approved: bool,
|
|
183
|
+
) -> None:
|
|
184
|
+
"""Trusted caller attests current input authority; never infer this from text."""
|
|
185
|
+
with self._lock:
|
|
186
|
+
self._sync()
|
|
187
|
+
if approved is not True:
|
|
188
|
+
raise LocalError("host_authorization_required")
|
|
189
|
+
hashed = digest(content.encode())
|
|
190
|
+
self._append(
|
|
191
|
+
"user",
|
|
192
|
+
content,
|
|
193
|
+
{
|
|
194
|
+
"origin": "host",
|
|
195
|
+
"sha256": hashed,
|
|
196
|
+
"artifacts": [],
|
|
197
|
+
"host_authorizations": [
|
|
198
|
+
{
|
|
199
|
+
"id": authorization_id,
|
|
200
|
+
"classification": classification,
|
|
201
|
+
"source_hash": hashed,
|
|
202
|
+
"expires_ms": expires_ms,
|
|
203
|
+
}
|
|
204
|
+
],
|
|
205
|
+
},
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
def add_memory(self, packet: dict[str, Any]) -> None:
|
|
209
|
+
with self._lock:
|
|
210
|
+
self._sync()
|
|
211
|
+
if (
|
|
212
|
+
packet.get("status") in {"blocked", "budget_insufficient", "incomplete"}
|
|
213
|
+
or "receipt" not in packet
|
|
214
|
+
):
|
|
215
|
+
raise LocalError("essential_context_unavailable")
|
|
216
|
+
raw = canonical_bytes(packet)
|
|
217
|
+
# Retrieved memory is data the model reads, never an instruction channel: the
|
|
218
|
+
# exact retained packet travels as user content, not in the system role. The
|
|
219
|
+
# store verifies these bytes against the receipt, so no framing is added here.
|
|
220
|
+
self._append(
|
|
221
|
+
"user",
|
|
222
|
+
raw.decode(),
|
|
223
|
+
{
|
|
224
|
+
"origin": "memory",
|
|
225
|
+
"sha256": digest(raw),
|
|
226
|
+
"artifacts": [{"receipt": packet["receipt"], "sha256": digest(raw)}],
|
|
227
|
+
"host_authorizations": [],
|
|
228
|
+
},
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
def _append(self, role: str, content: str, proof: dict[str, Any]) -> None:
|
|
232
|
+
if not content or len(content) > 65536 or len(self._messages) >= MESSAGE_LIMIT:
|
|
233
|
+
raise LocalError("inference_request_limit")
|
|
234
|
+
self._messages.append({"role": role, "content": content})
|
|
235
|
+
self._proofs.append(proof)
|
|
236
|
+
|
|
237
|
+
def _args(self, binding: dict[str, Any]) -> dict[str, Any]:
|
|
238
|
+
provider, model = LOCAL_PROVIDER, LOCAL_MODEL
|
|
239
|
+
if isinstance(self.provider, HttpAdapter):
|
|
240
|
+
provider, model = self.provider.name, self.provider.model
|
|
241
|
+
return copy.deepcopy(
|
|
242
|
+
{
|
|
243
|
+
"binding": binding,
|
|
244
|
+
"request": {
|
|
245
|
+
"provider": provider,
|
|
246
|
+
"model": model,
|
|
247
|
+
"messages": self._messages,
|
|
248
|
+
"state_handles": self._handles,
|
|
249
|
+
},
|
|
250
|
+
"manifest": {"segments": self._proofs, "handles": self._handle_proofs},
|
|
251
|
+
}
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
def _report(self, binding: dict[str, Any], permit_id: str, outcome: dict[str, Any]) -> None:
|
|
255
|
+
"""Complete the daemon's audit record for a remote dispatch; never silently skipped."""
|
|
256
|
+
self.client.inference_status(
|
|
257
|
+
{
|
|
258
|
+
"version": 1,
|
|
259
|
+
"action": "report",
|
|
260
|
+
"args": {"binding": binding, "permit": permit_id, **outcome},
|
|
261
|
+
}
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
@staticmethod
|
|
265
|
+
def _inherited(proofs: list[dict[str, Any]], raw: bytes) -> dict[str, Any]:
|
|
266
|
+
closure: dict[str, list[Any]] = {}
|
|
267
|
+
for name in ("artifacts", "host_authorizations"):
|
|
268
|
+
unique = {canonical_hash(value): value for proof in proofs for value in proof[name]}
|
|
269
|
+
closure[name] = [unique[key] for key in sorted(unique)]
|
|
270
|
+
return {"origin": "derived", "sha256": digest(raw), **closure}
|
|
271
|
+
|
|
272
|
+
def dispatch(self) -> dict[str, Any]:
|
|
273
|
+
with self._lock:
|
|
274
|
+
args = self._args(self._sync())
|
|
275
|
+
if not args["request"]["messages"]:
|
|
276
|
+
raise LocalError("context_rebuild_required")
|
|
277
|
+
if len(args["request"]["messages"]) >= MESSAGE_LIMIT:
|
|
278
|
+
raise LocalError("inference_request_limit")
|
|
279
|
+
closure = self._inherited(
|
|
280
|
+
args["manifest"]["segments"] + args["manifest"]["handles"], b""
|
|
281
|
+
)
|
|
282
|
+
if len(closure["artifacts"]) > 32 or len(closure["host_authorizations"]) > 32:
|
|
283
|
+
raise LocalError("inference_request_limit")
|
|
284
|
+
# Freeze one byte string. The provider sees these exact bytes only.
|
|
285
|
+
raw = canonical_bytes(args["request"])
|
|
286
|
+
started = self._monotonic_ns()
|
|
287
|
+
try:
|
|
288
|
+
permit = self.client.inference_status(
|
|
289
|
+
{"version": 1, "action": "authorize", "args": args}
|
|
290
|
+
)
|
|
291
|
+
used = self.client.inference_status(
|
|
292
|
+
{
|
|
293
|
+
"version": 1,
|
|
294
|
+
"action": "consume",
|
|
295
|
+
"args": {**args, "permit": permit["permit"]},
|
|
296
|
+
}
|
|
297
|
+
)
|
|
298
|
+
if used["status"] != "consumed" or used["request_hash"] != digest(raw):
|
|
299
|
+
raise LocalError("inference_permit_mismatch")
|
|
300
|
+
elapsed = self._monotonic_ns() - started
|
|
301
|
+
if elapsed < 0:
|
|
302
|
+
raise LocalError("clock_untrusted")
|
|
303
|
+
if elapsed >= 5_000_000_000:
|
|
304
|
+
raise LocalError("release_expired")
|
|
305
|
+
if isinstance(self.provider, HttpAdapter):
|
|
306
|
+
try:
|
|
307
|
+
delivered = self.provider.dispatch(raw)
|
|
308
|
+
except Exception as exc:
|
|
309
|
+
failure = {
|
|
310
|
+
"status": "failed",
|
|
311
|
+
"wire_hash": self.provider.last_wire_hash,
|
|
312
|
+
"response_hash": None,
|
|
313
|
+
"usage": None,
|
|
314
|
+
}
|
|
315
|
+
try:
|
|
316
|
+
self._report(args["binding"], used["id"], failure)
|
|
317
|
+
except Exception:
|
|
318
|
+
pass # The record stays pending, which is the truth.
|
|
319
|
+
raise LocalError("provider_unavailable") from exc
|
|
320
|
+
result: dict[str, Any] = {
|
|
321
|
+
"content": delivered.content,
|
|
322
|
+
"handle": None,
|
|
323
|
+
"request_hash": delivered.request_hash,
|
|
324
|
+
"wire_hash": delivered.wire_hash,
|
|
325
|
+
"usage": delivered.usage,
|
|
326
|
+
}
|
|
327
|
+
self._report(
|
|
328
|
+
args["binding"],
|
|
329
|
+
used["id"],
|
|
330
|
+
{
|
|
331
|
+
"status": "delivered",
|
|
332
|
+
"wire_hash": delivered.wire_hash,
|
|
333
|
+
"response_hash": digest(delivered.content.encode()),
|
|
334
|
+
"usage": delivered.usage,
|
|
335
|
+
},
|
|
336
|
+
)
|
|
337
|
+
else:
|
|
338
|
+
result = dict(self.provider.dispatch(raw))
|
|
339
|
+
content = str(result["content"])
|
|
340
|
+
except Exception:
|
|
341
|
+
self._discard()
|
|
342
|
+
raise
|
|
343
|
+
# Never make an in-flight response available to the next tool/model turn
|
|
344
|
+
# until the complete derived closure passes a new, current validation.
|
|
345
|
+
try:
|
|
346
|
+
current = self._sync()
|
|
347
|
+
if current != args["binding"]:
|
|
348
|
+
raise LocalError("inference_context_changed")
|
|
349
|
+
inherited = args["manifest"]["segments"] + args["manifest"]["handles"]
|
|
350
|
+
self._append("assistant", content, self._inherited(inherited, content.encode()))
|
|
351
|
+
if result.get("handle"):
|
|
352
|
+
handle = {"kind": "conversation", "id": str(result["handle"])}
|
|
353
|
+
self._handles = [handle]
|
|
354
|
+
self._handle_proofs = [self._inherited(inherited, canonical_bytes(handle))]
|
|
355
|
+
else:
|
|
356
|
+
# A stateless adapter keeps nothing; the full context is resent each time.
|
|
357
|
+
self._handles = []
|
|
358
|
+
self._handle_proofs = []
|
|
359
|
+
checked_at = self._monotonic_ns()
|
|
360
|
+
validation = self.client.inference_status(
|
|
361
|
+
{"version": 1, "action": "validate", "args": self._args(current)}
|
|
362
|
+
)
|
|
363
|
+
if validation["status"] != "validated":
|
|
364
|
+
raise LocalError("inference_provenance_unknown")
|
|
365
|
+
elapsed = self._monotonic_ns() - checked_at
|
|
366
|
+
if elapsed < 0 or elapsed >= 5_000_000_000:
|
|
367
|
+
raise LocalError("release_expired")
|
|
368
|
+
except Exception as exc:
|
|
369
|
+
self._discard()
|
|
370
|
+
raise LocalError("inference_result_quarantined") from exc
|
|
371
|
+
return {
|
|
372
|
+
**result,
|
|
373
|
+
"status": "validated",
|
|
374
|
+
"permit": used["id"],
|
|
375
|
+
"permit_receipt": used["receipt"],
|
|
376
|
+
}
|
memoryking/hooks.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Capture from scripts, test runners and editor hooks without writing a client.
|
|
2
|
+
|
|
3
|
+
Connection details come from `--profile`-style arguments or the environment:
|
|
4
|
+
`MEMORYKING_PROFILE`, or `MEMORYKING_SOCKET` with `MEMORYKING_CREDENTIAL`, plus
|
|
5
|
+
`MEMORYKING_PROJECT`. Every capture goes through the ordinary authorized path with a
|
|
6
|
+
deterministic event id, so re-running a hook replays instead of duplicating.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from memoryking import profiles
|
|
18
|
+
from memoryking.adapters.local_files import private_file
|
|
19
|
+
from memoryking.adapters.local_ipc import request
|
|
20
|
+
from memoryking.domain.local import LocalError
|
|
21
|
+
|
|
22
|
+
TEXT_LIMIT = 65536
|
|
23
|
+
DAY_MS = 86_400_000
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def connection(
|
|
27
|
+
*,
|
|
28
|
+
profile: str | None = None,
|
|
29
|
+
socket: Path | None = None,
|
|
30
|
+
credential: Path | None = None,
|
|
31
|
+
project: str | None = None,
|
|
32
|
+
config: Path | None = None,
|
|
33
|
+
) -> tuple[Path, str, str]:
|
|
34
|
+
"""(socket, credential token, project) from arguments, then the environment."""
|
|
35
|
+
name = profile or os.environ.get("MEMORYKING_PROFILE")
|
|
36
|
+
if name and (socket is None or credential is None):
|
|
37
|
+
resolved = profiles.resolve(name, config)
|
|
38
|
+
socket = socket or Path(resolved["socket"])
|
|
39
|
+
credential = credential or Path(resolved["credential"])
|
|
40
|
+
socket = socket or (
|
|
41
|
+
Path(os.environ["MEMORYKING_SOCKET"]) if os.environ.get("MEMORYKING_SOCKET") else None
|
|
42
|
+
)
|
|
43
|
+
credential = credential or (
|
|
44
|
+
Path(os.environ["MEMORYKING_CREDENTIAL"])
|
|
45
|
+
if os.environ.get("MEMORYKING_CREDENTIAL")
|
|
46
|
+
else None
|
|
47
|
+
)
|
|
48
|
+
project = project or os.environ.get("MEMORYKING_PROJECT")
|
|
49
|
+
if socket is None:
|
|
50
|
+
raise LocalError("socket_required")
|
|
51
|
+
if credential is None:
|
|
52
|
+
raise LocalError("credential_required")
|
|
53
|
+
if not project:
|
|
54
|
+
raise LocalError("project_required")
|
|
55
|
+
private_file(credential)
|
|
56
|
+
return socket, credential.read_text().strip(), project
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def event_id(source: str, text: str, salt: str = "") -> str:
|
|
60
|
+
return "ev-" + hashlib.sha256(f"{source}\n{salt}\n{text}".encode()).hexdigest()[:40]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def capture(
|
|
64
|
+
text: str,
|
|
65
|
+
*,
|
|
66
|
+
source: str = "hook",
|
|
67
|
+
event: str | None = None,
|
|
68
|
+
readers: list[str] | None = None,
|
|
69
|
+
classification: str = "internal",
|
|
70
|
+
observed_ms: int | None = None,
|
|
71
|
+
namespace: str = "hooks",
|
|
72
|
+
**where: Any,
|
|
73
|
+
) -> dict[str, Any]:
|
|
74
|
+
"""Capture one observation; the text is truncated to the capture limit with a marker.
|
|
75
|
+
|
|
76
|
+
A replayed capture must send identical bytes, so the default observed time is the
|
|
77
|
+
current day rather than the millisecond; the store's event log records the exact
|
|
78
|
+
moment of the capture itself. Pass `observed_ms` to keep a precise time.
|
|
79
|
+
"""
|
|
80
|
+
socket, token, project = connection(**where)
|
|
81
|
+
# Unpaired surrogates (e.g. from a decoded traceback) become replacement characters.
|
|
82
|
+
text = text.encode("utf-8", "replace").decode("utf-8")
|
|
83
|
+
if len(text.encode()) > TEXT_LIMIT:
|
|
84
|
+
text = text.encode()[: TEXT_LIMIT - 32].decode("utf-8", "ignore") + "\n[truncated]"
|
|
85
|
+
if not text.strip():
|
|
86
|
+
raise LocalError("invalid_request")
|
|
87
|
+
observed = (
|
|
88
|
+
observed_ms if observed_ms is not None else int(time.time() * 1000) // DAY_MS * DAY_MS
|
|
89
|
+
)
|
|
90
|
+
# The derived key covers everything the payload varies by (project, observed time,
|
|
91
|
+
# text), so a rerun replays and another day or project is a new capture.
|
|
92
|
+
event = event or event_id(source, text, f"{project}\n{observed}")
|
|
93
|
+
space = request(socket, token, "namespace", {"project": project, "name": namespace})
|
|
94
|
+
return request(
|
|
95
|
+
socket,
|
|
96
|
+
token,
|
|
97
|
+
"capture",
|
|
98
|
+
{
|
|
99
|
+
"namespace": space["namespace"],
|
|
100
|
+
"key": event,
|
|
101
|
+
"request": {
|
|
102
|
+
"version": 1,
|
|
103
|
+
"project": project,
|
|
104
|
+
"source": source,
|
|
105
|
+
"source_event": event,
|
|
106
|
+
"text": text,
|
|
107
|
+
"readers": readers,
|
|
108
|
+
"classification": classification,
|
|
109
|
+
"observed_at_ms": observed,
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def as_of_ms(value: str) -> int:
|
|
116
|
+
"""A wall-clock instant for `--as-of`: Unix ms, a date, or an ISO date-time (UTC default)."""
|
|
117
|
+
from datetime import datetime, timezone
|
|
118
|
+
|
|
119
|
+
text = value.strip()
|
|
120
|
+
if text.isdigit():
|
|
121
|
+
return int(text)
|
|
122
|
+
try:
|
|
123
|
+
parsed = datetime.fromisoformat(text)
|
|
124
|
+
except ValueError as exc:
|
|
125
|
+
raise LocalError("invalid_request") from exc
|
|
126
|
+
if parsed.tzinfo is None:
|
|
127
|
+
parsed = parsed.replace(tzinfo=timezone.utc)
|
|
128
|
+
if len(text) == 10:
|
|
129
|
+
# A bare date means the end of that day: everything recorded on it counts.
|
|
130
|
+
parsed = parsed.replace(hour=23, minute=59, second=59, microsecond=999000)
|
|
131
|
+
return int(parsed.timestamp() * 1000)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def recall(
|
|
135
|
+
query: str,
|
|
136
|
+
*,
|
|
137
|
+
budget: int = 6000,
|
|
138
|
+
text: bool = True,
|
|
139
|
+
task: str | None = None,
|
|
140
|
+
as_of: int | None = None,
|
|
141
|
+
salience: bool = False,
|
|
142
|
+
rerank: bool = False,
|
|
143
|
+
**where: Any,
|
|
144
|
+
) -> dict[str, Any]:
|
|
145
|
+
"""A briefing through the socket, as cited Markdown by default; `as_of` in Unix ms."""
|
|
146
|
+
socket, token, project = connection(**where)
|
|
147
|
+
context = request(socket, token, "context", {"project": project})
|
|
148
|
+
args: dict[str, Any] = {
|
|
149
|
+
"project": project,
|
|
150
|
+
"query": query,
|
|
151
|
+
"bindings": [{}],
|
|
152
|
+
"max_output_tokens": budget,
|
|
153
|
+
"tokenizer": "utf8-byte-estimate-v1",
|
|
154
|
+
}
|
|
155
|
+
if text:
|
|
156
|
+
args["format"] = "text"
|
|
157
|
+
if task:
|
|
158
|
+
args["task"] = task
|
|
159
|
+
if as_of is not None:
|
|
160
|
+
args["as_of_ms"] = as_of
|
|
161
|
+
if salience:
|
|
162
|
+
args["salience"] = "on"
|
|
163
|
+
if rerank:
|
|
164
|
+
args["rerank"] = "on"
|
|
165
|
+
command = {
|
|
166
|
+
"version": 1,
|
|
167
|
+
"incarnation": context["incarnation"],
|
|
168
|
+
"action": "brief",
|
|
169
|
+
"args": args,
|
|
170
|
+
}
|
|
171
|
+
return request(socket, token, "retrieval", {"command": command})
|