n3memorycore-free-codex 1.9.2__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.
- n3memorycore_free_codex/__init__.py +3 -0
- n3memorycore_free_codex/codex_entry.py +203 -0
- n3memorycore_free_codex/codex_install.py +131 -0
- n3memorycore_free_codex/core/__init__.py +0 -0
- n3memorycore_free_codex/core/database.py +429 -0
- n3memorycore_free_codex/core/processor.py +613 -0
- n3memorycore_free_codex/n3memory.py +1977 -0
- n3memorycore_free_codex/paths.py +30 -0
- n3memorycore_free_codex/project.py +24 -0
- n3memorycore_free_codex-1.9.2.dist-info/METADATA +424 -0
- n3memorycore_free_codex-1.9.2.dist-info/RECORD +16 -0
- n3memorycore_free_codex-1.9.2.dist-info/WHEEL +5 -0
- n3memorycore_free_codex-1.9.2.dist-info/entry_points.txt +4 -0
- n3memorycore_free_codex-1.9.2.dist-info/licenses/LICENSE +190 -0
- n3memorycore_free_codex-1.9.2.dist-info/licenses/NOTICE +4 -0
- n3memorycore_free_codex-1.9.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Read one Codex event from stdin and save or recall its conversation text."""
|
|
2
|
+
import os as _os
|
|
3
|
+
import sys as _sys
|
|
4
|
+
|
|
5
|
+
if __name__ == "__main__":
|
|
6
|
+
# When invoked with -m outside a source checkout, exclude the current folder
|
|
7
|
+
# before importing anything the working folder could shadow.
|
|
8
|
+
_here = _os.path.normcase(_os.path.abspath(_os.getcwd()))
|
|
9
|
+
_checkout = _os.path.normcase(_os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))))
|
|
10
|
+
if _sys.path and _here != _checkout and _os.path.normcase(_os.path.abspath(_sys.path[0])) == _here:
|
|
11
|
+
del _sys.path[0]
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from . import n3memory as memory
|
|
21
|
+
from .core.processor import sanitize_surrogates
|
|
22
|
+
|
|
23
|
+
_JA_REQUEST_END = r"(?=[。!!??、,\s]*$|[。!!??\r\n\u0085\u2028\u2029])"
|
|
24
|
+
_NO_SAVE = re.compile(
|
|
25
|
+
r"(?:保存|記録|記憶)(?:を|は)?(?:しないで(?:ください)?|しなくて(?:も)?(?:いい|よい|大丈夫)|禁止|不要|やめて(?:ください)?|止めて(?:ください)?)"
|
|
26
|
+
+ _JA_REQUEST_END + "|"
|
|
27
|
+
+ r"(?:(?:記憶に|メモリに)残さないで|覚えないで)(?:ください)?" + _JA_REQUEST_END + "|"
|
|
28
|
+
+ r"(?:^|[.!?\r\n\u0085\u2028\u2029]\s*)(?:please\s+)?(?:do not|don['’]t|never)\s+"
|
|
29
|
+
r"(?:save|store|record|remember)\s+(?:(?:this|that)(?:\s+(?:reply|message|turn|conversation|chat))?|anything|our conversation|my (?:message|reply))"
|
|
30
|
+
r"(?:\s+(?:in|to)\s+memory)?(?=\s*(?:[.!?,;\r\n\u0085\u2028\u2029]|$))|"
|
|
31
|
+
r"(?:off the record|do not add (?:this|that) to memory)", re.I)
|
|
32
|
+
_SECRETS = re.compile(
|
|
33
|
+
r"-----BEGIN (?:RSA |OPENSSH |EC |DSA )?PRIVATE KEY-----|"
|
|
34
|
+
r"\b(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{20,}|"
|
|
35
|
+
r"github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|"
|
|
36
|
+
r"AIza[0-9A-Za-z_-]{30,})\b|"
|
|
37
|
+
r"\bBearer\s+[A-Za-z0-9._~+/-]{16,}\b", re.I)
|
|
38
|
+
_CREDENTIAL_ASSIGNMENT = re.compile(
|
|
39
|
+
r"\b(?:api[_ -]?key|access[_ -]?token|secret|password|passwd|"
|
|
40
|
+
r"パスワード|秘密鍵|認証トークン)[\"']?\s*[:=:]\s*[\"'`]?(\S+?)(?=[\"'`;,}\]\s]|$)", re.I)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _has_secrets(text):
|
|
44
|
+
if _SECRETS.search(text):
|
|
45
|
+
return True
|
|
46
|
+
for match in _CREDENTIAL_ASSIGNMENT.finditer(text):
|
|
47
|
+
value = match.group(1).strip("\"'")
|
|
48
|
+
if re.match(r"(?:os\.(?:environ|getenv)|getenv\(|process\.env\b|\$|%|<)", value, re.I):
|
|
49
|
+
continue
|
|
50
|
+
if re.fullmatch(r"(?:x+|\*+|your[_-]?[a-z_-]+|placeholder|dummy|example|changeme)", value, re.I):
|
|
51
|
+
continue
|
|
52
|
+
if len(value) >= 6 and re.fullmatch(r"[A-Za-z0-9_./+~!@#$%^&*()=:-]+", value):
|
|
53
|
+
return True
|
|
54
|
+
return False
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _identifiers(payload):
|
|
58
|
+
session = payload.get("session_id")
|
|
59
|
+
thread = payload.get("thread_id")
|
|
60
|
+
if session is not None and thread is not None and session != thread:
|
|
61
|
+
raise ValueError("session_id and thread_id disagree")
|
|
62
|
+
session = thread if session is None else session
|
|
63
|
+
turn = payload.get("turn_id")
|
|
64
|
+
if not all(isinstance(value, str) and value.strip() for value in (session, turn)):
|
|
65
|
+
raise ValueError("session_id (or thread_id) and turn_id are required")
|
|
66
|
+
return session, turn
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _strings(value):
|
|
70
|
+
if isinstance(value, str):
|
|
71
|
+
yield value
|
|
72
|
+
elif isinstance(value, dict):
|
|
73
|
+
for key, item in value.items():
|
|
74
|
+
if isinstance(item, str):
|
|
75
|
+
yield f"{key}: {item}"
|
|
76
|
+
yield key
|
|
77
|
+
yield from _strings(item)
|
|
78
|
+
elif isinstance(value, list):
|
|
79
|
+
for item in value:
|
|
80
|
+
yield from _strings(item)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _read_event(event, raw):
|
|
84
|
+
payload = sanitize_surrogates(json.loads(raw))
|
|
85
|
+
if not isinstance(payload, dict):
|
|
86
|
+
raise ValueError("hook input must be a JSON object")
|
|
87
|
+
if payload.get("hook_event_name", event) != event:
|
|
88
|
+
raise ValueError("hook_event_name does not match the entry point")
|
|
89
|
+
session, turn = _identifiers(payload)
|
|
90
|
+
is_prompt = event == "UserPromptSubmit"
|
|
91
|
+
body_key = "prompt" if is_prompt else "last_assistant_message"
|
|
92
|
+
message = payload.get(body_key)
|
|
93
|
+
if message is not None and not isinstance(message, str):
|
|
94
|
+
raise ValueError(f"{body_key} must be text or null")
|
|
95
|
+
return payload, session, turn, message
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def handle(event, raw):
|
|
99
|
+
payload, session, turn, message = _read_event(event, raw)
|
|
100
|
+
is_prompt = event == "UserPromptSubmit"
|
|
101
|
+
|
|
102
|
+
skip_key = hashlib.sha256(f"{session}\0{turn}".encode("utf-8")).hexdigest()
|
|
103
|
+
marker = Path(memory.MEMORY_DIR) / f"skip_{skip_key}"
|
|
104
|
+
previously_excluded = marker.exists()
|
|
105
|
+
if previously_excluded or (is_prompt and message and _NO_SAVE.search(message)) or any(
|
|
106
|
+
_has_secrets(item) for item in _strings(payload)
|
|
107
|
+
):
|
|
108
|
+
if is_prompt and not previously_excluded:
|
|
109
|
+
marker.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
marker.touch()
|
|
111
|
+
print("N3MC: turn excluded from memory.", file=_sys.stderr)
|
|
112
|
+
return {"systemMessage": "N3MC: turn excluded from memory."}
|
|
113
|
+
|
|
114
|
+
# Audit before loading configuration, searching or touching the DB. Suppress
|
|
115
|
+
# the entire line for excluded turns, including the raw payload.
|
|
116
|
+
audited = memory._audit_append({
|
|
117
|
+
"ts": datetime.now(timezone.utc).isoformat(),
|
|
118
|
+
"hook": event, "raw": sanitize_surrogates(raw)[:4096], "payload": payload,
|
|
119
|
+
})
|
|
120
|
+
if not message or not message.strip():
|
|
121
|
+
return None if audited else {"systemMessage": "N3MC could not write the local audit log."}
|
|
122
|
+
|
|
123
|
+
cfg = memory.get_config()
|
|
124
|
+
connected = memory._connection_target(cfg) is not None
|
|
125
|
+
output = {}
|
|
126
|
+
if is_prompt:
|
|
127
|
+
if not connected and memory._use_server():
|
|
128
|
+
try:
|
|
129
|
+
memory._post("/repair", {"max_records": 20}, timeout=3)
|
|
130
|
+
except Exception as exc:
|
|
131
|
+
print(f"N3MC index repair failed ({type(exc).__name__}).", file=_sys.stderr)
|
|
132
|
+
try:
|
|
133
|
+
context = memory._search_text(message, session, cfg=cfg)
|
|
134
|
+
except Exception as exc:
|
|
135
|
+
print(f"N3MC recall failed ({type(exc).__name__}).", file=_sys.stderr)
|
|
136
|
+
context = memory._placeholder("_(memory search unavailable)_", [])
|
|
137
|
+
output["hookSpecificOutput"] = {
|
|
138
|
+
"hookEventName": event,
|
|
139
|
+
"additionalContext": context,
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
try:
|
|
143
|
+
if connected:
|
|
144
|
+
from .project import detect_project
|
|
145
|
+
cwd = payload.get("cwd")
|
|
146
|
+
project = detect_project(cwd) if isinstance(cwd, str) and cwd.strip() else None
|
|
147
|
+
_, failed = memory._save_text("user" if is_prompt else "claude", message, turn, session,
|
|
148
|
+
project=project)
|
|
149
|
+
else:
|
|
150
|
+
_, failed = memory._save_text("user" if is_prompt else "claude", message, turn, session)
|
|
151
|
+
except Exception as exc:
|
|
152
|
+
if not is_prompt:
|
|
153
|
+
raise
|
|
154
|
+
print(f"N3MC prompt save failed ({type(exc).__name__}).", file=_sys.stderr)
|
|
155
|
+
failed = True
|
|
156
|
+
if failed:
|
|
157
|
+
if not is_prompt:
|
|
158
|
+
raise RuntimeError("physical save failed")
|
|
159
|
+
output["systemMessage"] = "N3MC could not save the complete prompt. Recalled context is still available."
|
|
160
|
+
elif not audited:
|
|
161
|
+
output["systemMessage"] = "N3MC could not write the local audit log."
|
|
162
|
+
|
|
163
|
+
if not is_prompt:
|
|
164
|
+
memory.cmd_stop()
|
|
165
|
+
return output or None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _run(event):
|
|
169
|
+
memory._reconfigure_streams()
|
|
170
|
+
try:
|
|
171
|
+
response = handle(event, _sys.stdin.read())
|
|
172
|
+
if response is not None:
|
|
173
|
+
print(json.dumps(response, ensure_ascii=False))
|
|
174
|
+
return 0
|
|
175
|
+
except ValueError as exc:
|
|
176
|
+
# JSONDecodeError inherits from ValueError. Its input text is omitted.
|
|
177
|
+
detail = "invalid UTF-8 JSON input" if isinstance(exc, (json.JSONDecodeError, UnicodeError)) else str(exc)
|
|
178
|
+
print(f"N3MC hook failed: {detail}.", file=_sys.stderr)
|
|
179
|
+
return 1
|
|
180
|
+
except Exception as exc:
|
|
181
|
+
print(f"N3MC hook failed ({type(exc).__name__}).", file=_sys.stderr)
|
|
182
|
+
return 1
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def prompt_main():
|
|
186
|
+
return _run("UserPromptSubmit")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def stop_main():
|
|
190
|
+
return _run("Stop")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def main():
|
|
194
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
195
|
+
mode = parser.add_mutually_exclusive_group(required=True)
|
|
196
|
+
mode.add_argument("--prompt", action="store_true")
|
|
197
|
+
mode.add_argument("--stop", action="store_true")
|
|
198
|
+
args = parser.parse_args()
|
|
199
|
+
return prompt_main() if args.prompt else stop_main()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
if __name__ == "__main__":
|
|
203
|
+
_sys.exit(main())
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Register this edition's hooks without altering other Codex handlers."""
|
|
2
|
+
import base64
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import shlex
|
|
7
|
+
import shutil
|
|
8
|
+
import sys
|
|
9
|
+
from contextlib import suppress
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from tempfile import NamedTemporaryFile
|
|
13
|
+
|
|
14
|
+
_EVENTS = {'UserPromptSubmit': '--prompt', 'Stop': '--stop'}
|
|
15
|
+
_POWERSHELL_PREFIX = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand '
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def hooks_path() -> str:
|
|
19
|
+
override = os.environ.get('N3MC_CODEX_HOOKS_PATH')
|
|
20
|
+
if override:
|
|
21
|
+
return os.path.expanduser(override)
|
|
22
|
+
home = os.environ.get('CODEX_HOME') or '~/.codex'
|
|
23
|
+
return str(Path(home).expanduser() / 'hooks.json')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _command(flag: str) -> str:
|
|
27
|
+
python = sys.executable
|
|
28
|
+
if os.name == 'nt':
|
|
29
|
+
return _windows_command(python, flag)
|
|
30
|
+
return f'{shlex.quote(python)} -I -m n3memorycore_free_codex.codex_entry {flag}'
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _windows_command(python: str, flag: str) -> str:
|
|
34
|
+
if re.fullmatch(r'[A-Za-z0-9_:/\\.-]+', python):
|
|
35
|
+
# A quoted executable expression needs a call operator in PowerShell.
|
|
36
|
+
# A plain absolute path works in both PowerShell and cmd.exe.
|
|
37
|
+
return f'{python} -I -m n3memorycore_free_codex.codex_entry {flag}'
|
|
38
|
+
literal = python.replace("'", "''")
|
|
39
|
+
script = f"& '{literal}' -I -m n3memorycore_free_codex.codex_entry {flag}; exit $LASTEXITCODE"
|
|
40
|
+
encoded = base64.b64encode(script.encode('utf-16le')).decode('ascii')
|
|
41
|
+
return _POWERSHELL_PREFIX + encoded
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _owned(handler: object, flag: str) -> bool:
|
|
45
|
+
if not isinstance(handler, dict) or handler.get('type') != 'command':
|
|
46
|
+
return False
|
|
47
|
+
command = handler.get('command')
|
|
48
|
+
if not isinstance(command, str):
|
|
49
|
+
return False
|
|
50
|
+
arguments = rf'-m\s+(?:n3memorycore_free_codex|n3memorycore)\.codex_entry\s+{re.escape(flag)}'
|
|
51
|
+
if command.startswith(_POWERSHELL_PREFIX):
|
|
52
|
+
try:
|
|
53
|
+
script = base64.b64decode(command[len(_POWERSHELL_PREFIX):], validate=True).decode('utf-16le')
|
|
54
|
+
except ValueError:
|
|
55
|
+
return False
|
|
56
|
+
return bool(re.fullmatch(rf"& '(?:[^']|'')+' -I {arguments}; exit \$LASTEXITCODE", script))
|
|
57
|
+
return bool(re.fullmatch(
|
|
58
|
+
rf'\s*(?:"[^"]+"|\'[^\']+\'|[^\s]+)\s+(?:-I\s+)?{arguments}\s*', command))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def merge_hooks(document: dict) -> dict:
|
|
62
|
+
if not isinstance(document, dict):
|
|
63
|
+
raise ValueError('hooks.json must contain a JSON object')
|
|
64
|
+
hooks = document.setdefault('hooks', {})
|
|
65
|
+
if not isinstance(hooks, dict):
|
|
66
|
+
raise ValueError('hooks must be a JSON object')
|
|
67
|
+
for event, flag in _EVENTS.items():
|
|
68
|
+
groups = hooks.get(event, [])
|
|
69
|
+
if not isinstance(groups, list):
|
|
70
|
+
raise ValueError(f'hooks.{event} must be an array')
|
|
71
|
+
kept = []
|
|
72
|
+
for group in groups:
|
|
73
|
+
handlers = group.get('hooks') if isinstance(group, dict) else None
|
|
74
|
+
if not isinstance(handlers, list):
|
|
75
|
+
kept.append(group)
|
|
76
|
+
continue
|
|
77
|
+
others = [handler for handler in handlers if not _owned(handler, flag)]
|
|
78
|
+
if others or not handlers:
|
|
79
|
+
kept.append({**group, 'hooks': others})
|
|
80
|
+
kept.append({'hooks': [{
|
|
81
|
+
'type': 'command',
|
|
82
|
+
'command': _command(flag),
|
|
83
|
+
'timeout': 120,
|
|
84
|
+
'statusMessage': 'N3MC-Free-Codex memory',
|
|
85
|
+
}]})
|
|
86
|
+
hooks[event] = kept
|
|
87
|
+
return document
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def install() -> int:
|
|
91
|
+
path = Path(hooks_path())
|
|
92
|
+
temporary = None
|
|
93
|
+
try:
|
|
94
|
+
try:
|
|
95
|
+
original = path.read_bytes()
|
|
96
|
+
except FileNotFoundError:
|
|
97
|
+
original = None
|
|
98
|
+
after = merge_hooks(json.loads(original) if original is not None else {})
|
|
99
|
+
if original is not None and after == json.loads(original):
|
|
100
|
+
print(f'Already registered: {path}')
|
|
101
|
+
return 0
|
|
102
|
+
|
|
103
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
with NamedTemporaryFile(mode='w', encoding='utf-8', newline='\n',
|
|
105
|
+
dir=path.parent, prefix='.n3mc-', delete=False) as file:
|
|
106
|
+
temporary = Path(file.name)
|
|
107
|
+
json.dump(after, file, ensure_ascii=False, indent=2)
|
|
108
|
+
file.write('\n')
|
|
109
|
+
file.flush()
|
|
110
|
+
os.fsync(file.fileno())
|
|
111
|
+
|
|
112
|
+
current = path.read_bytes() if path.exists() else None
|
|
113
|
+
if current != original:
|
|
114
|
+
raise ValueError('hooks.json changed during registration; retry')
|
|
115
|
+
if original is not None:
|
|
116
|
+
stamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
|
|
117
|
+
backup = path.with_name(f'{path.name}.bak-n3mc-{stamp}')
|
|
118
|
+
shutil.copy2(path, backup)
|
|
119
|
+
print(f'Backup: {backup}')
|
|
120
|
+
os.replace(temporary, path)
|
|
121
|
+
temporary = None
|
|
122
|
+
except (OSError, ValueError) as exc:
|
|
123
|
+
print(f'Cannot update {path}: {exc}', file=sys.stderr)
|
|
124
|
+
return 1
|
|
125
|
+
finally:
|
|
126
|
+
if temporary is not None:
|
|
127
|
+
with suppress(OSError):
|
|
128
|
+
temporary.unlink(missing_ok=True)
|
|
129
|
+
print(f'Codex hooks registered: {path}')
|
|
130
|
+
print('Review and trust the two N3MC-Free-Codex handlers in Codex Settings → Hooks or CLI /hooks.')
|
|
131
|
+
return 0
|
|
File without changes
|