coldmemory 0.3.6__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.
@@ -0,0 +1,135 @@
1
+ """ColdMemory as a native Hermes memory provider: NOW in the system prompt, a delta and quotes before each call.
2
+
3
+ `pip install coldmemory` into Hermes's Python registers it through the hermes_agent.memory_providers entry point;
4
+ `hermes memory setup` then asks for COLDMEMORY_STORE and COLDMEMORY_SCOPE (default private; its ledger is
5
+ _ledger/<scope>). For archive quotes and the coldmemory_ask tool, also set COLDMEMORY_TRUST_KEY (a public key file),
6
+ or COLDMEMORY_LOCAL_UNSIGNED=1 for the private scope. Hermes is imported only when it loads the provider.
7
+
8
+ Hermes rebuilds the system prompt when it compresses the conversation, so on_pre_compress opens a new
9
+ compact_epoch and the next system_prompt_block is a fresh NOW with retractions; the seen-set starts empty.
10
+ """
11
+
12
+ import json
13
+ import os
14
+
15
+ from . import ledger, push
16
+ from .mcp_server import Server
17
+
18
+ ASK = {"name": "coldmemory_ask",
19
+ "description": "Search the owner's full archive (notes, transcripts, every owner message) and decision "
20
+ "ledger. Returns quotes pinned to file:line, read from disk now.",
21
+ "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}
22
+ PRE_COMPRESS = ("The owner's decisions are kept by ColdMemory and sent again after this summary. Do not restate "
23
+ "them or any retracted decision; summarize the task state only.")
24
+
25
+
26
+ class ColdMemoryProvider:
27
+ def __init__(self):
28
+ self.store = os.environ.get("COLDMEMORY_STORE", "")
29
+ self.scope = os.environ.get("COLDMEMORY_SCOPE", "private")
30
+ self.folder = None
31
+ self.session = "default"
32
+ self.state = None
33
+ self.compacting = False
34
+ self.archive = None
35
+
36
+ @property
37
+ def name(self):
38
+ return "coldmemory"
39
+
40
+ def is_available(self):
41
+ return (bool(self.store) and os.path.isdir(os.path.expanduser(self.store)) and self.scope != "public"
42
+ and bool(ledger.KEY.fullmatch(self.scope)))
43
+
44
+ def unavailable_reason(self):
45
+ return ("set COLDMEMORY_STORE to a ColdMemory store folder and COLDMEMORY_SCOPE to a non-public scope of "
46
+ "lowercase letters, digits and -")
47
+
48
+ def initialize(self, session_id, **kwargs):
49
+ self.session = session_id or "default"
50
+ self.folder = ledger.book(self.store, self.scope)
51
+ self.state = push._load_state(push._state_path(self.folder, self.session))
52
+ trust = os.environ.get("COLDMEMORY_TRUST_KEY")
53
+ try:
54
+ self.archive = Server(self.store, [self.scope], trust_keys=[f"{self.scope}={trust}"] if trust else [],
55
+ local_unsigned=os.environ.get("COLDMEMORY_LOCAL_UNSIGNED") == "1")
56
+ except (OSError, ValueError):
57
+ self.archive = None
58
+
59
+ def _save(self):
60
+ push._save_state(push._state_path(self.folder, self.session), self.state)
61
+
62
+ def _remember_told(self, before):
63
+ told = set(before) - set(self.state["ever"])
64
+ self.state["retracted"] = sorted((set(self.state.get("retracted", [])) | told) - set(self.state["now"]))
65
+ self._save()
66
+
67
+ def _replay(self, keys, text, budget):
68
+ lines = push._fit([push._retraction(key) for key in keys], budget - push.tokens(text))
69
+ self.state["owed"] = [key for key in keys if push._retraction(key) not in lines]
70
+ return lines
71
+
72
+ def system_prompt_block(self):
73
+ if self.state is None:
74
+ self.initialize(self.session)
75
+ before = self.state["ever"]
76
+ told_earlier = [key for key in self.state.get("retracted", []) if key not in before]
77
+ text = push.start(self.folder, self.state, compacted=self.compacting)
78
+ self.compacting = False
79
+ kept = self._replay([key for key in told_earlier if key not in self.state["now"]], text, push.NOW_TOKENS)
80
+ self._remember_told(before)
81
+ return "\n".join([text, *kept])
82
+
83
+ def prefetch(self, query, *, session_id=""):
84
+ if self.state is None:
85
+ self.initialize(session_id or self.session)
86
+ before = self.state["ever"]
87
+ try:
88
+ text = push.turn(self.folder, self.state, query or "", self.archive, source=self.session)
89
+ current = {d.key for d in ledger.load(self.folder)} if self.state.get("owed") else set()
90
+ except (OSError, ValueError):
91
+ return ""
92
+ text = text or push.TURN_HEADER
93
+ kept = self._replay([key for key in self.state.get("owed", []) if key not in current], text, push.TURN_TOKENS)
94
+ self._remember_told(before)
95
+ return "\n".join([text, *kept]) if text != push.TURN_HEADER or kept else ""
96
+
97
+ def on_pre_compress(self, messages):
98
+ self.compacting = True
99
+ return PRE_COMPRESS
100
+
101
+ def on_session_switch(self, new_session_id, *, parent_session_id="", reset=False, rewound=False, **kwargs):
102
+ if parent_session_id and not reset and kwargs.get("reason") in ("compression", "branch"):
103
+ if self.state is None:
104
+ self.initialize(self.session)
105
+ self.session, self.compacting = new_session_id, True
106
+ self._save()
107
+ else:
108
+ self.session, self.state, self.compacting = new_session_id, None, False
109
+
110
+ def get_tool_schemas(self):
111
+ return [ASK] if self.archive else []
112
+
113
+ def handle_tool_call(self, tool_name, args, **kwargs):
114
+ if tool_name != ASK["name"] or self.archive is None:
115
+ return json.dumps({"error": "unknown tool"})
116
+ result = self.archive.call_tool({"name": "memory_ask", "arguments": {"query": str(args.get("query", ""))}})
117
+ return json.dumps({"result": result["content"][0]["text"], "error": result["isError"]})
118
+
119
+ def get_config_schema(self):
120
+ from .init_cmd import default_store
121
+
122
+ return [{"key": "store", "description": "Existing ColdMemory store folder (run coldmemory init first)",
123
+ "required": True, "default": self.store or str(default_store()), "env_var": "COLDMEMORY_STORE"},
124
+ {"key": "scope", "description": "Ledger scope: lowercase letters, digits and -, not public",
125
+ "default": self.scope, "env_var": "COLDMEMORY_SCOPE"}]
126
+
127
+
128
+ def provider():
129
+ from agent.memory_provider import MemoryProvider
130
+
131
+ return type("ColdMemoryProvider", (ColdMemoryProvider, MemoryProvider), {"__module__": __name__})()
132
+
133
+
134
+ def register(ctx):
135
+ ctx.register_memory_provider(provider())
@@ -0,0 +1,161 @@
1
+ """Print MCP config for each client. It never edits a client's settings."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import re
7
+ import shlex
8
+ import sys
9
+ from functools import partial
10
+ from pathlib import Path
11
+
12
+ CLIENTS = ("claude-code", "t3-code", "codex", "cursor", "antigravity", "openbot", "grok")
13
+ GROK_NOTE = ("# Grok CLI: paste into ~/.grok/config.toml (or ./.grok/config.toml), or use `grok mcp add`.\n"
14
+ "# Grok loads ColdMemory's MCP initialize instructions natively. Its session, prompt and compact\n"
15
+ "# hooks cannot inject model context, so there are no ColdMemory hooks for Grok.\n")
16
+ _SCOPE_PREFIX = re.compile(r"^[a-z0-9][a-z0-9-]*$")
17
+
18
+
19
+ def _normalize_trust_key(scope, trust_key):
20
+ if isinstance(trust_key, os.PathLike):
21
+ raw = os.fspath(trust_key)
22
+ if not raw or not str(raw).strip():
23
+ raise ValueError("--trust-key path must not be empty")
24
+ return f"{scope}={Path(raw).expanduser().absolute()}"
25
+ raw = str(trust_key)
26
+ if not raw.strip():
27
+ raise ValueError("--trust-key path must not be empty")
28
+ prefix, sep, rest = raw.partition("=")
29
+ if sep and _SCOPE_PREFIX.fullmatch(prefix):
30
+ if prefix != scope:
31
+ raise ValueError(f"--trust-key scope {prefix!r} does not match --scope {scope!r}")
32
+ if not rest.strip():
33
+ raise ValueError(f"--trust-key {raw!r} is missing a key path")
34
+ raw = rest
35
+ return f"{scope}={Path(raw).expanduser().absolute()}"
36
+
37
+
38
+ def _store_args(store, scope, trust_key, local_unsigned):
39
+ args = ["--store", str(Path(store).expanduser().absolute())]
40
+ if local_unsigned and scope == "private" and not trust_key:
41
+ return args + ["--scope", scope, "--local-unsigned"]
42
+ if trust_key and not local_unsigned:
43
+ return args + ["--scope", scope, "--trust-key", _normalize_trust_key(scope, trust_key)]
44
+ raise ValueError("choose a trust key or explicit private local unsigned mode")
45
+
46
+
47
+ def _hook_command(package_root, python, *args):
48
+ root = package_root or Path(__file__).resolve().parent.parent
49
+ return shlex.join(["env", f"PYTHONPATH={root}", python, "-m", *args])
50
+
51
+
52
+ def claude_hooks(store, package_root=None, python=sys.executable, *, scope="private", trust_key=None,
53
+ local_unsigned=False):
54
+ """Claude Code settings that print the L0 brief at session start, after compaction, and to the user."""
55
+ command = _hook_command(package_root, python, "coldmemory", "brief",
56
+ *_store_args(store, scope, trust_key, local_unsigned))
57
+ hook = {"hooks": [{"type": "command", "command": command, "timeout": 30}]}
58
+ return json.dumps({"hooks": {"SessionStart": [{"matcher": "startup|resume|clear|compact", **hook}],
59
+ "PostCompact": [hook]}}, indent=2)
60
+
61
+
62
+ def push_hooks(store, package_root=None, python=sys.executable, *, scope="private", trust_key=None,
63
+ local_unsigned=False, pre_compact=False):
64
+ """Claude Code, OpenBot (Claude agents) and Codex hooks: NOW at start and after compaction, a delta each turn.
65
+
66
+ Use these instead of claude_hooks, never with them: NOW replaces the L0 brief so nothing is sent twice.
67
+ After a compaction, SessionStart with source compact gets NOW at once; PostCompact alone makes the next prompt
68
+ get it; both for one compaction count once. pre_compact adds the PreCompact hook that writes marked owner lines
69
+ to the ledger before compaction. For a signed store, the client's COLD_ALLOWED_SCOPES must list the scope."""
70
+ command = _hook_command(package_root, python, "coldmemory.push",
71
+ *_store_args(store, scope, trust_key, local_unsigned))
72
+ hook = {"hooks": [{"type": "command", "command": command, "timeout": 5}]}
73
+ hooks = {"SessionStart": [{"matcher": "startup|resume|clear|compact", **hook}],
74
+ "PostCompact": [hook], "UserPromptSubmit": [hook]}
75
+ if pre_compact:
76
+ hooks["PreCompact"] = [hook]
77
+ return json.dumps({"hooks": hooks}, indent=2)
78
+
79
+
80
+ def server_config(store, package_root=None, python=sys.executable, *, scope="private", trust_key=None,
81
+ local_unsigned=False, tools=None):
82
+ """Build the stdio MCP server config shared by hooks_snippet and coldmemory init."""
83
+ root = package_root or Path(__file__).resolve().parent.parent
84
+ args = ["-m", "coldmemory.mcp_server", *_store_args(store, scope, trust_key, local_unsigned)]
85
+ if tools:
86
+ args += ["--tools", tools if isinstance(tools, str) else ",".join(tools)]
87
+ return {"command": python, "args": args, "env": {"PYTHONPATH": str(root)}}
88
+
89
+
90
+ def _toml_str(value):
91
+ return json.dumps(value, ensure_ascii=False).replace("\x7f", "\\u007f")
92
+
93
+
94
+ def _toml_key(key):
95
+ return key if re.fullmatch(r"[A-Za-z0-9_-]+", key) else _toml_str(key)
96
+
97
+
98
+ def codex_toml(server):
99
+ """Render the [mcp_servers.coldmemory] TOML table for Codex."""
100
+ args_toml = "[" + ", ".join(_toml_str(a) for a in server["args"]) + "]"
101
+ env_items = ", ".join(f"{_toml_key(k)} = {_toml_str(v)}" for k, v in server["env"].items())
102
+ return ("[mcp_servers.coldmemory]\n"
103
+ f"command = {_toml_str(server['command'])}\nargs = {args_toml}\n"
104
+ f"env = {{ {env_items} }}")
105
+
106
+
107
+ def snippet(client, store, package_root=None, python=sys.executable, *, scope="private", trust_key=None,
108
+ local_unsigned=False, tools=None):
109
+ server = server_config(store, package_root, python, scope=scope, trust_key=trust_key,
110
+ local_unsigned=local_unsigned, tools=tools)
111
+ if client == "claude-code":
112
+ return f"claude mcp add-json --scope user coldmemory {shlex.quote(json.dumps(server))}"
113
+ if client == "codex":
114
+ return codex_toml(server)
115
+ if client == "grok":
116
+ return GROK_NOTE + codex_toml(server)
117
+ if client == "t3-code":
118
+ return json.dumps({"name": "coldmemory", "server": server}, indent=2)
119
+ if client in ("cursor", "antigravity"):
120
+ return json.dumps({"mcpServers": {"coldmemory": server}}, indent=2)
121
+ if client == "openbot":
122
+ if any(char in value for value in [server["command"], *server["args"], *server["env"].values()] for char in "\r\n"):
123
+ raise ValueError("OpenBot's form takes one line per field; a path contains a line break")
124
+ return "\n".join(["Name: coldmemory", "Transport: STDIO", f"Command to launch: {server['command']}",
125
+ *(f"Argument {i}: {arg}" for i, arg in enumerate(server["args"], 1)),
126
+ *(line for i, (key, value) in enumerate(server["env"].items(), 1)
127
+ for line in (f"Environment variable {i} key: {key}", f"Environment variable {i} value: {value}")),
128
+ "Working directory: leave empty"])
129
+ raise ValueError("unknown client")
130
+
131
+
132
+ def main(argv=None):
133
+ parser = argparse.ArgumentParser(prog="coldmemory.hooks_snippet", description=__doc__)
134
+ parser.add_argument("client", choices=CLIENTS)
135
+ parser.add_argument("--store", required=True)
136
+ parser.add_argument("--scope", default="private")
137
+ parser.add_argument("--trust-key", metavar="SCOPE=PUBKEY")
138
+ parser.add_argument("--local-unsigned", action="store_true")
139
+ parser.add_argument("--hooks", action="store_true",
140
+ help="claude-code only: print SessionStart and PostCompact hooks to merge into settings.json")
141
+ parser.add_argument("--push", action="store_true",
142
+ help="claude-code or codex: print the NOW and per-turn push hooks (use instead of --hooks)")
143
+ parser.add_argument("--pre-compact", action="store_true",
144
+ help="with --push: also print the PreCompact hook that saves marked owner lines first")
145
+ parser.add_argument("--tools", help="comma-separated MCP tools to serve (e.g. memory_ask)")
146
+ args = parser.parse_args(argv)
147
+ if args.hooks and args.client != "claude-code":
148
+ parser.error("--hooks is for claude-code")
149
+ if args.push and args.client not in ("claude-code", "codex"):
150
+ parser.error("--push is for claude-code and codex")
151
+ if args.pre_compact and not args.push:
152
+ parser.error("--pre-compact needs --push")
153
+ if args.tools and (args.hooks or args.push):
154
+ parser.error("--tools applies to MCP server snippets, not --hooks or --push")
155
+ make = (partial(push_hooks, pre_compact=args.pre_compact) if args.push else claude_hooks if args.hooks
156
+ else partial(snippet, args.client, tools=args.tools))
157
+ print(make(args.store, scope=args.scope, trust_key=args.trust_key, local_unsigned=args.local_unsigned))
158
+
159
+
160
+ if __name__ == "__main__":
161
+ main()