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.
Files changed (179) hide show
  1. memoryking/__init__.py +3 -0
  2. memoryking/__main__.py +1328 -0
  3. memoryking/adapters/__init__.py +1 -0
  4. memoryking/adapters/adapter_state.py +242 -0
  5. memoryking/adapters/anchor_schema.sql +7 -0
  6. memoryking/adapters/atlas.py +441 -0
  7. memoryking/adapters/browser_commands.py +125 -0
  8. memoryking/adapters/dashboard.py +510 -0
  9. memoryking/adapters/dense_search.py +86 -0
  10. memoryking/adapters/egress_policy.py +244 -0
  11. memoryking/adapters/egress_schema.sql +13 -0
  12. memoryking/adapters/embedding.schema.json +302 -0
  13. memoryking/adapters/embedding_store.py +469 -0
  14. memoryking/adapters/execution.py +369 -0
  15. memoryking/adapters/experience.py +423 -0
  16. memoryking/adapters/experience.schema.json +1508 -0
  17. memoryking/adapters/experience_records.py +239 -0
  18. memoryking/adapters/experience_schema.sql +23 -0
  19. memoryking/adapters/handoff.py +494 -0
  20. memoryking/adapters/handoff.schema.json +299 -0
  21. memoryking/adapters/handoff_schema.sql +17 -0
  22. memoryking/adapters/index_schema.sql +11 -0
  23. memoryking/adapters/inference.py +454 -0
  24. memoryking/adapters/inference.schema.json +541 -0
  25. memoryking/adapters/inspection.py +1128 -0
  26. memoryking/adapters/inspection.schema.json +568 -0
  27. memoryking/adapters/knowledge.schema.json +633 -0
  28. memoryking/adapters/knowledge_schema.sql +37 -0
  29. memoryking/adapters/knowledge_store.py +800 -0
  30. memoryking/adapters/legacy_snapshot.py +358 -0
  31. memoryking/adapters/legacy_tables.py +49 -0
  32. memoryking/adapters/local_contract.py +45 -0
  33. memoryking/adapters/local_embeddings.py +189 -0
  34. memoryking/adapters/local_files.py +242 -0
  35. memoryking/adapters/local_ipc.py +258 -0
  36. memoryking/adapters/local_schema.sql +44 -0
  37. memoryking/adapters/local_store.py +632 -0
  38. memoryking/adapters/local_wire.schema.json +7672 -0
  39. memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
  40. memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
  41. memoryking/adapters/optional_schema.sql +43 -0
  42. memoryking/adapters/plan_dashboard.py +51 -0
  43. memoryking/adapters/plans.py +253 -0
  44. memoryking/adapters/postgres_admin.py +300 -0
  45. memoryking/adapters/postgres_anchor_schema.sql +9 -0
  46. memoryking/adapters/postgres_counter.sql +14 -0
  47. memoryking/adapters/postgres_egress_schema.sql +15 -0
  48. memoryking/adapters/postgres_experience_schema.sql +39 -0
  49. memoryking/adapters/postgres_index_schema.sql +7 -0
  50. memoryking/adapters/postgres_optional_schema.sql +71 -0
  51. memoryking/adapters/postgres_pool.py +77 -0
  52. memoryking/adapters/postgres_recovery.py +525 -0
  53. memoryking/adapters/postgres_schema.sql +365 -0
  54. memoryking/adapters/postgres_sql.py +102 -0
  55. memoryking/adapters/postgres_store.py +428 -0
  56. memoryking/adapters/postgres_summary_schema.sql +12 -0
  57. memoryking/adapters/postgres_trust_schema.sql +20 -0
  58. memoryking/adapters/processing.schema.json +471 -0
  59. memoryking/adapters/processing_store.py +346 -0
  60. memoryking/adapters/projects.py +83 -0
  61. memoryking/adapters/proposals.py +238 -0
  62. memoryking/adapters/ranking.py +315 -0
  63. memoryking/adapters/repository.schema.json +664 -0
  64. memoryking/adapters/repository_git.py +264 -0
  65. memoryking/adapters/repository_schema.sql +25 -0
  66. memoryking/adapters/repository_store.py +960 -0
  67. memoryking/adapters/retrieval.py +1285 -0
  68. memoryking/adapters/retrieval.schema.json +553 -0
  69. memoryking/adapters/retrieval_schema.sql +10 -0
  70. memoryking/adapters/shared_control.py +40 -0
  71. memoryking/adapters/shared_dashboard.py +636 -0
  72. memoryking/adapters/shared_gateway.py +63 -0
  73. memoryking/adapters/shared_http.py +216 -0
  74. memoryking/adapters/shared_mcp.py +159 -0
  75. memoryking/adapters/shared_service.py +124 -0
  76. memoryking/adapters/stdio.py +193 -0
  77. memoryking/adapters/stdio.tools.json +6776 -0
  78. memoryking/adapters/summary_schema.sql +10 -0
  79. memoryking/adapters/team.py +253 -0
  80. memoryking/adapters/timeline.py +80 -0
  81. memoryking/adapters/token_count.py +55 -0
  82. memoryking/adapters/tokenizers/LICENSE +21 -0
  83. memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
  84. memoryking/adapters/trust.py +123 -0
  85. memoryking/adapters/trust_schema.sql +13 -0
  86. memoryking/adapters/web/app.css +1251 -0
  87. memoryking/adapters/web/app.js +907 -0
  88. memoryking/adapters/web/brand.js +44 -0
  89. memoryking/adapters/web/crown-mono.svg +1 -0
  90. memoryking/adapters/web/crown.svg +8 -0
  91. memoryking/adapters/web/elephant.png +0 -0
  92. memoryking/adapters/web/favicon.svg +8 -0
  93. memoryking/adapters/web/graph-layout.js +52 -0
  94. memoryking/adapters/web/graph-worker.js +10 -0
  95. memoryking/adapters/web/graph.js +570 -0
  96. memoryking/adapters/web/index.html +208 -0
  97. memoryking/adapters/web/observatory.js +1208 -0
  98. memoryking/adapters/web/team.js +151 -0
  99. memoryking/adapters/web/wordmark.svg +1 -0
  100. memoryking/adapters/working.py +971 -0
  101. memoryking/adapters/working.schema.json +1717 -0
  102. memoryking/adapters/working_schema.sql +24 -0
  103. memoryking/application/__init__.py +1 -0
  104. memoryking/application/conformance.py +50 -0
  105. memoryking/application/legacy_import.py +337 -0
  106. memoryking/application/local_port.py +9 -0
  107. memoryking/application/storage.py +117 -0
  108. memoryking/application/store_core.py +1292 -0
  109. memoryking/backups.py +131 -0
  110. memoryking/contracts/__init__.py +6 -0
  111. memoryking/contracts/__main__.py +20 -0
  112. memoryking/contracts/canonical.py +88 -0
  113. memoryking/contracts/embedding.schema.json +302 -0
  114. memoryking/contracts/embedding_generated.py +65 -0
  115. memoryking/contracts/experience.schema.json +1508 -0
  116. memoryking/contracts/experience_generated.py +239 -0
  117. memoryking/contracts/generated.py +122 -0
  118. memoryking/contracts/handoff.schema.json +299 -0
  119. memoryking/contracts/handoff_generated.py +69 -0
  120. memoryking/contracts/inference.schema.json +541 -0
  121. memoryking/contracts/inference_generated.py +106 -0
  122. memoryking/contracts/processing.schema.json +471 -0
  123. memoryking/contracts/processing_generated.py +82 -0
  124. memoryking/contracts/py.typed +0 -0
  125. memoryking/contracts/repository.schema.json +664 -0
  126. memoryking/contracts/repository_generated.py +144 -0
  127. memoryking/contracts/retrieval.schema.json +553 -0
  128. memoryking/contracts/retrieval_generated.py +110 -0
  129. memoryking/contracts/schema.json +696 -0
  130. memoryking/contracts/validation.py +92 -0
  131. memoryking/contracts/working.schema.json +1717 -0
  132. memoryking/contracts/working_generated.py +291 -0
  133. memoryking/domain/__init__.py +1 -0
  134. memoryking/domain/anchors.py +97 -0
  135. memoryking/domain/briefing.py +108 -0
  136. memoryking/domain/briefing_text.py +222 -0
  137. memoryking/domain/checkpoint.py +118 -0
  138. memoryking/domain/compression.py +64 -0
  139. memoryking/domain/delta.py +129 -0
  140. memoryking/domain/embeddings.py +90 -0
  141. memoryking/domain/hints.py +465 -0
  142. memoryking/domain/http_status.py +45 -0
  143. memoryking/domain/learning.py +62 -0
  144. memoryking/domain/local.py +65 -0
  145. memoryking/domain/plans.py +140 -0
  146. memoryking/domain/repository.py +118 -0
  147. memoryking/domain/selectors.py +356 -0
  148. memoryking/domain/summary.py +88 -0
  149. memoryking/domain/usage.py +163 -0
  150. memoryking/embedding_loop.py +98 -0
  151. memoryking/embedding_worker.py +131 -0
  152. memoryking/harness.py +882 -0
  153. memoryking/harness_context.py +376 -0
  154. memoryking/hooks.py +171 -0
  155. memoryking/host_hooks.py +454 -0
  156. memoryking/lean.py +352 -0
  157. memoryking/memory_tool.py +776 -0
  158. memoryking/migration.py +194 -0
  159. memoryking/model_install.py +78 -0
  160. memoryking/observability.py +101 -0
  161. memoryking/observability_metrics.py +100 -0
  162. memoryking/profiles.py +150 -0
  163. memoryking/providers.py +330 -0
  164. memoryking/py.typed +0 -0
  165. memoryking/pytest_plugin.py +69 -0
  166. memoryking/reference_agent.py +152 -0
  167. memoryking/repository_worker.py +57 -0
  168. memoryking/resume_adapter.py +154 -0
  169. memoryking/sdk.py +302 -0
  170. memoryking/shared.py +301 -0
  171. memoryking/shared_sdk.py +101 -0
  172. memoryking/vault.py +176 -0
  173. memoryking-0.1.0.dist-info/METADATA +157 -0
  174. memoryking-0.1.0.dist-info/RECORD +179 -0
  175. memoryking-0.1.0.dist-info/WHEEL +5 -0
  176. memoryking-0.1.0.dist-info/entry_points.txt +7 -0
  177. memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
  178. memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
  179. memoryking-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,154 @@
1
+ """Host adapter reconstructing full essential context from optional transport deltas."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from memoryking.adapters.inference import EGRESS_REVISION
9
+ from memoryking.contracts.canonical import ContractError, canonical_bytes, canonical_hash
10
+ from memoryking.domain.delta import SCHEMA, materialize
11
+ from memoryking.domain.local import LocalError
12
+ from memoryking.sdk import LocalClient
13
+
14
+ if TYPE_CHECKING:
15
+ from memoryking.harness_context import AuthorizedConversation
16
+
17
+
18
+ class ResumeAdapter:
19
+ """In-memory authorized state only; never evidence of model context retention."""
20
+
21
+ def __init__(self, client: LocalClient, model_session: str, context_epoch: int = 0):
22
+ self.client = client
23
+ self.model_session, self.context_epoch = model_session, context_epoch
24
+ self._target: dict[str, Any] | None = None
25
+ self._base: dict[str, Any] | None = None
26
+ self._binding: dict[str, Any] | None = None
27
+ self.last_envelope: dict[str, Any] | None = None
28
+ self.transfers: list[dict[str, Any]] = []
29
+
30
+ def discard(self) -> None:
31
+ self._target = self._base = self._binding = None
32
+
33
+ def reset_model_context(self, model_session: str) -> None:
34
+ self.model_session = model_session
35
+ self.context_epoch += 1
36
+ self.discard()
37
+
38
+ def resume_for(self, conversation: AuthorizedConversation, **options: Any) -> dict[str, Any]:
39
+ """Reference-host integration: sync resets/revocations before any base reuse."""
40
+ if conversation.client is not self.client:
41
+ self.discard()
42
+ raise LocalError("context_changed")
43
+ with conversation._lock:
44
+ context = conversation._sync()
45
+ self.model_session = context["model_session_id"]
46
+ self.context_epoch = context["context_epoch"]
47
+ return self.resume(**options)
48
+
49
+ def resume(
50
+ self,
51
+ *,
52
+ task: str,
53
+ bindings: list[dict[str, Any]],
54
+ max_output_tokens: int,
55
+ tokenizer: str,
56
+ run: str | None = None,
57
+ checkpoint: str | None = None,
58
+ ) -> dict[str, Any]:
59
+ args = {
60
+ "project": self.client.project,
61
+ "task": task,
62
+ "run": run,
63
+ "checkpoint": checkpoint,
64
+ "bindings": bindings,
65
+ "max_output_tokens": max_output_tokens,
66
+ "tokenizer": tokenizer,
67
+ "adapter_context": {
68
+ "model_session": self.model_session,
69
+ "context_epoch": self.context_epoch,
70
+ },
71
+ }
72
+ self.transfers = []
73
+ for attempt in range(2):
74
+ try:
75
+ context = self.client.context()
76
+ binding = {
77
+ key: context[key]
78
+ for key in (
79
+ "store",
80
+ "tenant",
81
+ "principal",
82
+ "incarnation",
83
+ "project",
84
+ "authorization_epoch",
85
+ "purge_epoch",
86
+ "delegation_chain",
87
+ )
88
+ }
89
+ binding.update(
90
+ egress_policy_revision=EGRESS_REVISION,
91
+ model_session=self.model_session,
92
+ context_epoch=self.context_epoch,
93
+ view_hash=canonical_hash(
94
+ {
95
+ key: args[key]
96
+ for key in (
97
+ "project",
98
+ "task",
99
+ "run",
100
+ "checkpoint",
101
+ "bindings",
102
+ "tokenizer",
103
+ )
104
+ }
105
+ ),
106
+ )
107
+ if self._binding != binding:
108
+ self.discard()
109
+ envelope = self.client.working(
110
+ {
111
+ "version": 1,
112
+ "incarnation": self.client.binding[-1],
113
+ "action": "adapter_resume",
114
+ "args": {**args, "base": self._base},
115
+ }
116
+ )
117
+ except Exception:
118
+ self.discard()
119
+ raise
120
+ self.last_envelope = copy.deepcopy(envelope)
121
+ self.transfers.append(
122
+ {
123
+ "mode": envelope.get("mode"),
124
+ "bytes": len(canonical_bytes(envelope)),
125
+ "tokens": envelope.get("usage", {}).get("output_tokens"),
126
+ "attempt": attempt + 1,
127
+ }
128
+ )
129
+ if envelope.get("status") == "budget_insufficient":
130
+ self.discard()
131
+ raise LocalError("budget_insufficient")
132
+ try:
133
+ target = materialize(envelope, self._target, binding)
134
+ except (LocalError, ContractError, KeyError, TypeError, ValueError):
135
+ self.discard()
136
+ if attempt == 0:
137
+ continue # One fresh authorized full compilation, never old full bytes.
138
+ raise LocalError("delta_reconstruction_failed") from None
139
+ self._target = target
140
+ self._binding = binding
141
+ self._base = (
142
+ {
143
+ "id": envelope["base_id"],
144
+ "hash": envelope["target_hash"],
145
+ "sequence": envelope["sequence"],
146
+ "schema": SCHEMA,
147
+ }
148
+ if envelope["base_id"]
149
+ else None
150
+ )
151
+ # The model sees the same complete packet as the ordinary resume path,
152
+ # with its own retained full artifact for exact inference authorization.
153
+ return copy.deepcopy(target["packet"])
154
+ raise LocalError("delta_reconstruction_failed")
memoryking/sdk.py ADDED
@@ -0,0 +1,302 @@
1
+ """Small local SDK with explicit binding, current checks and no automatic mutation retry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import secrets
7
+ import time
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from jsonschema import Draft202012Validator
12
+
13
+ from memoryking.adapters.local_files import private_file
14
+ from memoryking.adapters.local_ipc import request
15
+ from memoryking.contracts.validation import (
16
+ validate_embedding,
17
+ validate_experience,
18
+ validate_handoff,
19
+ validate_inference,
20
+ validate_processing,
21
+ validate_repository,
22
+ validate_retrieval,
23
+ validate_working,
24
+ )
25
+ from memoryking.domain.checkpoint import complete
26
+ from memoryking.domain.local import LocalError
27
+
28
+ CATALOG = json.loads(Path(__file__).with_name("adapters").joinpath("stdio.tools.json").read_text())
29
+ TOOL_VALIDATORS = {
30
+ item["name"]: Draft202012Validator(item["inputSchema"]) for item in CATALOG["tools"]
31
+ }
32
+ DEFAULT_BUDGET = 6000
33
+ MUTATION_TOOLS = {"memory_checkpoint", "memory_handoff", "memory_feedback"}
34
+ PLAN_MUTATIONS = {"plan_save", "plan_step"}
35
+
36
+
37
+ def _resolve(node: dict[str, Any], defs: dict[str, Any]) -> dict[str, Any]:
38
+ ref = node.get("$ref")
39
+ while isinstance(ref, str) and ref.startswith("#/$defs/"):
40
+ node = defs[ref.removeprefix("#/$defs/")]
41
+ ref = node.get("$ref")
42
+ return node
43
+
44
+
45
+ def _tool_args() -> dict[tuple[str, Any], set[str]]:
46
+ """Which args each tool action accepts, so defaults are filled only where they fit."""
47
+ result: dict[tuple[str, Any], set[str]] = {}
48
+ for item in CATALOG["tools"]:
49
+ defs = item["inputSchema"].get("$defs", {})
50
+ for branch in item["inputSchema"].get("oneOf", []):
51
+ action = branch["properties"].get("action", {}).get("const")
52
+ args = _resolve(branch["properties"].get("args", {}), defs)
53
+ properties = args.get("properties", {})
54
+ result[(item["name"], action)] = set(properties)
55
+ nested = properties.get("brief")
56
+ if isinstance(nested, dict):
57
+ result[(item["name"], "brief")] = set(_resolve(nested, defs).get("properties", {}))
58
+ return result
59
+
60
+
61
+ TOOL_ARGS = _tool_args()
62
+ _TOKENIZER: list[str] = []
63
+
64
+
65
+ def default_tokenizer() -> str:
66
+ """The exact tokenizer when the optional lock is installed, else the disclosed estimate."""
67
+ if not _TOKENIZER:
68
+ from memoryking.adapters.token_count import encoding
69
+
70
+ try:
71
+ encoding()
72
+ _TOKENIZER.append("cl100k_base")
73
+ except LocalError:
74
+ _TOKENIZER.append("utf8-byte-estimate-v1")
75
+ return _TOKENIZER[0]
76
+
77
+
78
+ BINDING_FIELDS = ("store", "tenant", "principal", "project", "incarnation")
79
+
80
+
81
+ class LocalClient:
82
+ """One project and identity/history per instance. Recreate explicitly after a context change.
83
+
84
+ Ordinary memory calls cannot remove data retained by a consuming host. The separate
85
+ inference_status method is a trusted host surface; use AuthorizedConversation to
86
+ enforce exact-byte dispatch, dependency inheritance and conversation rebuilding.
87
+ """
88
+
89
+ def __init__(self, socket: Path, credential_file: Path, project: str, namespace: str = "sdk"):
90
+ self.socket, self.credential_file, self.project = socket, credential_file, project
91
+ # A named namespace makes `key` a real idempotency key across processes.
92
+ self.namespace = namespace
93
+ self.last_context = self._request(self._credential(), "context", {"project": project})
94
+ self.binding = tuple(self.last_context[key] for key in BINDING_FIELDS)
95
+
96
+ def _credential(self) -> str:
97
+ private_file(self.credential_file)
98
+ try:
99
+ with self.credential_file.open("rb") as source:
100
+ raw = source.read(8193)
101
+ if len(raw) > 8192 or not raw.strip():
102
+ raise LocalError("invalid_token")
103
+ return raw.decode("utf-8").strip()
104
+ except UnicodeError as exc:
105
+ raise LocalError("invalid_token") from exc
106
+
107
+ def _request(self, credential: str, operation: str, args: dict[str, Any]) -> dict[str, Any]:
108
+ try:
109
+ return request(self.socket, credential, operation, args)
110
+ except OSError as exc:
111
+ raise LocalError("transport_unavailable") from exc
112
+
113
+ def _current(self) -> tuple[str, dict[str, Any]]:
114
+ credential = self._credential()
115
+ context = self._request(credential, "context", {"project": self.project})
116
+ if tuple(context[key] for key in BINDING_FIELDS) != self.binding:
117
+ raise LocalError("context_changed")
118
+ self.last_context = context
119
+ return credential, context
120
+
121
+ def context(self) -> dict[str, Any]:
122
+ return self._current()[1]
123
+
124
+ def _bound(self, command: dict[str, Any]) -> None:
125
+ if command["incarnation"] != self.binding[-1]:
126
+ raise LocalError("history_changed")
127
+ if command["args"]["project"] != self.project:
128
+ raise LocalError("scope_mismatch")
129
+
130
+ def retrieval(self, command: dict[str, Any]) -> dict[str, Any]:
131
+ validate_retrieval(command)
132
+ self._bound(command)
133
+ credential, _ = self._current()
134
+ return self._request(credential, "retrieval", {"command": command})
135
+
136
+ def atlas(self, *, bindings: list[dict[str, Any]], **options: Any) -> dict[str, Any]:
137
+ """Read the bounded graph/list for a host UI; not a model-facing MCP tool.
138
+
139
+ Labels are excerpts for inspection. Counts refer only to returned nodes,
140
+ and truncation never establishes absence outside the authorized window.
141
+ """
142
+ return self.retrieval(
143
+ {
144
+ "version": 1,
145
+ "incarnation": self.binding[-1],
146
+ "action": "atlas",
147
+ "args": {**options, "project": self.project, "bindings": bindings},
148
+ }
149
+ )
150
+
151
+ def repository(self, command: dict[str, Any]) -> dict[str, Any]:
152
+ """Trusted host repository surface; no registration in the model tool catalog."""
153
+ validate_repository(command)
154
+ self._bound(command)
155
+ credential, _ = self._current()
156
+ return self._request(credential, "repository", {"command": command})
157
+
158
+ def embedding(self, command: dict[str, Any]) -> dict[str, Any]:
159
+ """Trusted operator/worker surface, excluded from model-facing MCP tools."""
160
+ validate_embedding(command)
161
+ self._bound(command)
162
+ credential, _ = self._current()
163
+ return self._request(credential, "embedding", {"command": command})
164
+
165
+ def processing(self, command: dict[str, Any]) -> dict[str, Any]:
166
+ """Trusted operator/worker surface, excluded from model-facing MCP tools."""
167
+ validate_processing(command)
168
+ self._bound(command)
169
+ credential, _ = self._current()
170
+ return self._request(credential, "processing", {"command": command})
171
+
172
+ def experience(self, command: dict[str, Any]) -> dict[str, Any]:
173
+ """Experience surface; MCP exposes only outcome and feedback, never activation."""
174
+ validate_experience(command)
175
+ self._bound(command)
176
+ credential, _ = self._current()
177
+ return self._request(credential, "experience", {"command": command})
178
+
179
+ def working(self, command: dict[str, Any]) -> dict[str, Any]:
180
+ validate_working(command)
181
+ self._bound(command)
182
+ if command["action"] == "assign_writer":
183
+ raise LocalError("administrative_operation_required")
184
+ credential, _ = self._current()
185
+ return self._request(credential, "working", {"command": command})
186
+
187
+ def inspection(self, command: dict[str, Any]) -> dict[str, Any]:
188
+ """A bounded inspection (`catalog`, `history`, `cost`, ...) over the socket."""
189
+ self._bound(command)
190
+ credential, _ = self._current()
191
+ return self._request(credential, "inspection", {"command": command})
192
+
193
+ def knowledge(self, command: dict[str, Any]) -> dict[str, Any]:
194
+ """A knowledge command (`propose`, `query`, `review`, ...); the store validates it."""
195
+ self._bound(command)
196
+ credential, _ = self._current()
197
+ return self._request(credential, "knowledge", {"command": command})
198
+
199
+ def purge(self, observation: str) -> None:
200
+ """Erase one observation and what was built from it; denied without an admin grant."""
201
+ credential, _ = self._current()
202
+ self._request(credential, "purge", {"observation": observation})
203
+
204
+ def capture(self, key: str, observation: dict[str, Any]) -> dict[str, Any]:
205
+ if observation.get("project") != self.project:
206
+ raise LocalError("scope_mismatch")
207
+ credential, _ = self._current()
208
+ namespace = self._request(
209
+ credential, "namespace", {"project": self.project, "name": self.namespace}
210
+ )["namespace"]
211
+ return self._request(
212
+ credential, "capture", {"namespace": namespace, "key": key, "request": observation}
213
+ )
214
+
215
+ def handoff(self, command: dict[str, Any]) -> dict[str, Any]:
216
+ validate_handoff(command)
217
+ self._bound(command)
218
+ credential, _ = self._current()
219
+ return self._request(credential, "handoff", {"command": command})
220
+
221
+ def inference_status(self, command: dict[str, Any]) -> dict[str, Any]:
222
+ """Trusted host surface; deliberately absent from the model-facing tool catalog."""
223
+ validate_inference(command)
224
+ args = command["args"]
225
+ project = args["binding"]["project"] if "binding" in args else args.get("project")
226
+ if project != self.project:
227
+ raise LocalError("scope_mismatch")
228
+ credential, _ = self._current()
229
+ return self._request(credential, "inference", {"command": command})
230
+
231
+ def defaults(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
232
+ """Fill what the catalog leaves optional from the session binding.
233
+
234
+ The store still validates the completed command, so a caller who sends every
235
+ field explicitly gets exactly the old behavior.
236
+ """
237
+ arguments = {**arguments}
238
+ if name == "memory_status":
239
+ arguments.setdefault("project", self.project)
240
+ return arguments
241
+ if name == "memory_capture":
242
+ request = arguments.get("request")
243
+ if isinstance(request, dict):
244
+ arguments["request"] = {"version": 1, "project": self.project, **request}
245
+ return arguments
246
+ arguments = {"version": 1, "incarnation": self.binding[-1], **arguments}
247
+ plan_write = name == "memory_plan" and arguments.get("action") in PLAN_MUTATIONS
248
+ if (name in MUTATION_TOOLS or plan_write) and "key" not in arguments:
249
+ # Without a caller-supplied key there is nothing to replay, so a fresh key
250
+ # keeps the call valid; supply a stable key to make retries idempotent.
251
+ arguments["key"] = "auto-" + secrets.token_hex(12)
252
+ args = arguments.get("args")
253
+ if isinstance(args, dict):
254
+ arguments["args"] = self._default_args(name, arguments.get("action"), args)
255
+ return arguments
256
+
257
+ def _default_args(self, name: str, action: Any, args: dict[str, Any]) -> dict[str, Any]:
258
+ args = {**args}
259
+ fields = TOOL_ARGS.get((name, action), set())
260
+ if name == "memory_checkpoint" and action == "save":
261
+ # Progressive checkpoints: a minimal body saves in one call, the gaps are
262
+ # recorded, and a missing expected_revision accepts the current one.
263
+ args.setdefault("run", None)
264
+ args.setdefault("readers", None) # keep the stream's readers (writer on first save)
265
+ args.setdefault("expected_revision", None)
266
+ if isinstance(args.get("checkpoint"), dict):
267
+ args["checkpoint"] = complete(args["checkpoint"], int(time.time() * 1000))
268
+ if name == "memory_resume" and action == "resume":
269
+ args.setdefault("run", None)
270
+ if "project" in fields:
271
+ args.setdefault("project", self.project)
272
+ if "bindings" in fields:
273
+ args.setdefault("bindings", [{}])
274
+ if "max_output_tokens" in fields:
275
+ args.setdefault("max_output_tokens", DEFAULT_BUDGET)
276
+ if "tokenizer" in fields:
277
+ args.setdefault("tokenizer", default_tokenizer())
278
+ nested = args.get("brief")
279
+ if "brief" in fields and isinstance(nested, dict):
280
+ args["brief"] = self._default_args(name, "brief", nested)
281
+ return args
282
+
283
+ def tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
284
+ validator = TOOL_VALIDATORS.get(name)
285
+ if validator is None:
286
+ raise LocalError("unknown_tool")
287
+ if not validator.is_valid(arguments):
288
+ raise LocalError("invalid_tool_arguments")
289
+ arguments = self.defaults(name, arguments)
290
+ if name == "memory_status":
291
+ if arguments["project"] != self.project:
292
+ raise LocalError("scope_mismatch")
293
+ return self.context()
294
+ if name == "memory_capture":
295
+ return self.capture(arguments["key"], arguments["request"])
296
+ if name in {"memory_brief", "memory_fetch"}:
297
+ return self.retrieval(arguments)
298
+ if name == "memory_handoff":
299
+ return self.handoff(arguments)
300
+ if name == "memory_feedback":
301
+ return self.experience(arguments)
302
+ return self.working(arguments)