refactor(integrations): shared agent plugin runtimes and native adapters (#7203)

This commit is contained in:
Kartik
2026-09-08 23:32:25 +05:30
committed by GitHub
parent dae67f74f5
commit 73e7b8763a
369 changed files with 31056 additions and 20464 deletions
@@ -0,0 +1,18 @@
---
name: sidekick
description: Coding subagent for focused implementation, investigation, testing, debugging, or review work.
whenToUse: Delegate a bounded engineering task that benefits from its own isolated context.
---
You are Mem0's coding sidekick. Complete only the bounded task the main agent
delegates to you and return a concise, self-contained result.
Search Mem0 before work that may depend on prior repository decisions or user
preferences. Inspect the relevant repository rules and code, make changes when
asked, and run the smallest decisive validation. Do not claim Git worktree
isolation: Kimi provides a separate context, while filesystem isolation depends
on the caller's environment.
Your final response must state the outcome, changed files, validation, and any
remaining risk. Do not commit, push, or open a pull request unless the caller
explicitly asks.
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Detached remote checkpoint worker.
Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook
therefore persists its input first and launches this process in a new session.
"""
from __future__ import annotations
import json
import os
import sys
import time
from pathlib import Path
import telemetry
from memory_core import (
EvidenceStore,
checkpoint_session,
configure_harness,
touch_handoff_heartbeat,
)
def main() -> int:
if len(sys.argv) != 2:
return 2
handoff_path = Path(sys.argv[1])
os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path)
harness = os.environ.get("MEM0_PLUGIN_HARNESS")
if harness:
source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "")
configure_harness(
harness,
env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""),
data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""),
source_tag=source_tag,
)
telemetry.init(harness=harness, source_tag=source_tag.upper())
completed = False
try:
payload = json.loads(handoff_path.read_text(encoding="utf-8"))
delay = float(payload.get("delay_seconds") or 0)
if delay > 0:
payload.pop("delay_seconds", None)
temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp")
try:
temporary.write_text(json.dumps(payload), encoding="utf-8")
temporary.replace(handoff_path)
finally:
temporary.unlink(missing_ok=True)
time.sleep(delay)
if not handoff_path.exists():
return 0
hook_input = payload.get("hook_input") or {}
reason = str(payload.get("reason") or "checkpoint")
wait_for_inflight = bool(payload.get("wait_for_inflight"))
store = EvidenceStore()
try:
if wait_for_inflight:
session_id = str(
hook_input.get("session_id") or "unknown-session"
)
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
deadline = time.monotonic() + float(
os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")
)
while (
store.has_inflight_flush(repo.identity, session_id)
and time.monotonic() < deadline
):
touch_handoff_heartbeat()
time.sleep(0.25)
# Hooks capture the conversation before handoff; the worker only flushes it.
result = checkpoint_session(store, hook_input, reason)
print(json.dumps(result, sort_keys=True), flush=True)
completed = result.get("status") in {
"semantic-succeeded",
"explicitly-stored",
"nothing-to-flush",
}
finally:
store.close()
return 0
finally:
telemetry.flush()
if completed:
try:
handoff_path.unlink()
except OSError:
pass
elif handoff_path.suffix == ".running":
try:
handoff_path.replace(handoff_path.with_suffix(".json"))
except OSError:
pass
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,372 @@
"""Shared hook orchestration for all Mem0 agent plugins."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
import telemetry
from memory_core import (
EvidenceStore,
_session_id,
api_key,
bounded,
cache_plugin_api_key,
checkpoint_session,
clear_stale_api_key_cache,
configure_harness,
data_dir,
detached_process_kwargs,
format_context,
harness_config,
record_session_start,
record_tool,
record_user_prompt,
redact,
search_memories,
)
STALE_RUNNING_SECONDS = 300
PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60
PENDING_LAUNCH_LIMIT = 5
DEFAULT_IDLE_FLUSH_SECONDS = 300
_core_dir: Path = Path(__file__).resolve().parent
def read_hook_input() -> dict:
try:
value = json.load(sys.stdin)
return value if isinstance(value, dict) else {}
except (json.JSONDecodeError, OSError):
return {}
def default_record_stop(store: EvidenceStore, hook_input: dict):
"""Record the assistant's response without transcript parsing."""
session_id = _session_id(hook_input)
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
message = redact(hook_input.get("last_assistant_message", "")).strip()
if message:
store.record_assistant_response(repo, session_id, message)
return repo, session_id
def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict:
"""Search once before the agent handles the first prompt in a session."""
repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input)
if not is_first_prompt:
return {}
try:
minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20"))
except ValueError:
minimum_query_chars = 20
if len(prompt.strip()) < max(minimum_query_chars, 1):
return {}
result = search_memories(
store, repo, session_id, bounded(prompt, 6000),
top_k=5, operation="first-prompt-search", timeout=2,
)
if not result.memories:
return {}
context = format_context(
result.memories,
"Mem0 found these relevant memories from earlier work in this repository:",
)
telemetry.record(
"context_injected",
repo=repo, session_id=session_id, trigger="first-prompt",
memory_count=len(result.memories), context_chars=len(context),
prompt_chars=len(prompt),
)
return {
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": context,
},
}
def _launch_handoff(handoff_path: Path) -> bool:
running_path = handoff_path.with_suffix(".running")
try:
handoff_path.replace(running_path)
except OSError:
return False
worker = _core_dir / "flush_worker.py"
log_path = data_dir() / "flush-worker.log"
log_handle = open(log_path, "a", encoding="utf-8")
harness = harness_config()
child_env = os.environ.copy()
child_env.update(
{
"MEM0_CODE_DATA_DIR": str(data_dir()),
"MEM0_PLUGIN_HARNESS": harness["name"],
"MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"],
"MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"],
"MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"],
}
)
try:
subprocess.Popen(
[sys.executable, str(worker), str(running_path)],
stdin=subprocess.DEVNULL,
stdout=log_handle, stderr=log_handle,
close_fds=True,
env=child_env,
**detached_process_kwargs(),
)
finally:
log_handle.close()
return True
def recover_pending_handoffs() -> int:
pending_dir = data_dir() / "pending"
pending_dir.mkdir(parents=True, exist_ok=True)
now = time.time()
for running in pending_dir.glob("*.running"):
try:
if now - running.stat().st_mtime > STALE_RUNNING_SECONDS:
running.replace(running.with_suffix(".json"))
except OSError:
continue
recoverable = []
for handoff in pending_dir.glob("*.json"):
try:
age = now - handoff.stat().st_mtime
except OSError:
continue
if age > PENDING_EXPIRY_SECONDS:
handoff.unlink(missing_ok=True)
continue
recoverable.append((age, handoff))
recoverable.sort(key=lambda item: item[0], reverse=True)
launched = 0
for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]:
launched += int(_launch_handoff(handoff))
return launched
def refresh_pending_handoffs() -> None:
pending_dir = data_dir() / "pending"
if not pending_dir.is_dir():
return
for pattern in ("*.json", "*.running"):
for handoff in pending_dir.glob(pattern):
try:
os.utime(handoff)
except OSError:
continue
def hand_off_flush(
hook_input: dict, reason: str, *, wait_for_inflight: bool = False,
) -> None:
pending_dir = data_dir() / "pending"
pending_dir.mkdir(parents=True, exist_ok=True)
material = (
f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}"
)
digest = hashlib.sha256(material.encode()).hexdigest()[:24]
handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json"
temporary_path = handoff_path.with_suffix(".tmp")
temporary_path.write_text(
json.dumps({
"hook_input": hook_input,
"reason": reason,
"wait_for_inflight": wait_for_inflight,
}),
encoding="utf-8",
)
temporary_path.replace(handoff_path)
_launch_handoff(handoff_path)
def automatic_flush_enabled() -> bool:
return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in {
"1", "true", "yes", "on",
}
def schedule_periodic_checkpoint(
store: EvidenceStore, hook_input: dict, repo, session_id: str,
) -> bool:
if (
not automatic_flush_enabled()
or not api_key()
or not store.checkpoint_due(repo.identity, session_id)
):
return False
if store.prepare_flush(repo, session_id, "periodic") is None:
return False
hand_off_flush(hook_input, "periodic")
return True
def _idle_flush_seconds() -> int:
try:
return max(
int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))),
0,
)
except ValueError:
return DEFAULT_IDLE_FLUSH_SECONDS
def schedule_idle_flush(
store: EvidenceStore, hook_input: dict, repo, session_id: str,
) -> bool:
delay = _idle_flush_seconds()
if delay <= 0 or not automatic_flush_enabled() or not api_key():
return False
if store.has_inflight_flush(repo.identity, session_id):
return False
if not store.has_unflushed_events(repo.identity, session_id):
return False
pending_dir = data_dir() / "pending"
pending_dir.mkdir(parents=True, exist_ok=True)
material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}"
digest = hashlib.sha256(material.encode()).hexdigest()[:24]
for old in pending_dir.glob(f"idle-{digest}*"):
old.unlink(missing_ok=True)
handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json"
temporary_path = handoff_path.with_suffix(".tmp")
temporary_path.write_text(
json.dumps({
"hook_input": hook_input,
"reason": "idle",
"delay_seconds": delay,
}),
encoding="utf-8",
)
temporary_path.replace(handoff_path)
_launch_handoff(handoff_path)
return True
def log_failure(exc: Exception) -> None:
try:
log_path = data_dir() / "plugin-errors.log"
with log_path.open("a", encoding="utf-8") as handle:
handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
except OSError:
pass
def run(
*,
record_stop_fn=None,
extra_actions: dict | None = None,
data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
automatic_flush_reasons: set | None = None,
) -> int:
if record_stop_fn is None:
record_stop_fn = default_record_stop
if automatic_flush_reasons is None:
automatic_flush_reasons = {"session-end"}
base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"]
all_actions = base_actions + list((extra_actions or {}).keys())
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=all_actions)
parser.add_argument("--reason", default="manual")
parser.add_argument("--plugin-data-dir", default="")
parser.add_argument("--harness", default="")
args = parser.parse_args()
if args.harness:
configure_harness(args.harness)
telemetry.init(harness=args.harness)
if args.plugin_data_dir:
os.environ[data_dir_env] = args.plugin_data_dir
cache_plugin_api_key()
if args.action == "session-start":
clear_stale_api_key_cache()
hook_input = read_hook_input()
store = EvidenceStore()
try:
if store.is_paused():
if args.action == "session-start":
refresh_pending_handoffs()
telemetry.record("session_start", paused=True)
telemetry.spawn_flush()
return 0
if args.action == "session-start":
if telemetry.is_first_run():
telemetry.record("install")
recovered = recover_pending_handoffs()
record_session_start(store, hook_input)
if recovered:
telemetry.record("handoff_recovered", count=recovered)
telemetry.spawn_flush()
elif args.action == "user-prompt":
output = first_prompt_memory_output(store, hook_input)
if output:
print(json.dumps(output))
elif args.action == "post-tool":
record_tool(store, hook_input)
elif args.action == "stop":
repo, session_id = record_stop_fn(store, hook_input)
if not schedule_periodic_checkpoint(store, hook_input, repo, session_id):
schedule_idle_flush(store, hook_input, repo, session_id)
elif args.action == "flush":
automatic = args.reason in automatic_flush_reasons
if automatic and not automatic_flush_enabled():
return 0
if args.reason == "session-end":
record_stop_fn(store, hook_input)
if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1":
print(json.dumps(checkpoint_session(store, hook_input, args.reason)))
else:
session_id = str(hook_input.get("session_id") or "unknown-session")
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
already_running = store.has_inflight_flush(repo.identity, session_id)
if already_running and args.reason == "session-end":
hand_off_flush(hook_input, args.reason, wait_for_inflight=True)
elif not already_running and store.prepare_flush(
repo, session_id, args.reason,
) is not None:
hand_off_flush(hook_input, args.reason)
elif extra_actions and args.action in extra_actions:
result = extra_actions[args.action](store, hook_input)
if result:
print(json.dumps(result))
finally:
store.close()
return 0
def entry_point(
*,
record_stop_fn=None,
extra_actions: dict | None = None,
data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
automatic_flush_reasons: set | None = None,
) -> None:
try:
raise SystemExit(run(
record_stop_fn=record_stop_fn,
extra_actions=extra_actions,
data_dir_env=data_dir_env,
automatic_flush_reasons=automatic_flush_reasons,
))
except Exception as exc:
log_failure(exc)
raise SystemExit(0)
if __name__ == "__main__":
entry_point()
+247
View File
@@ -0,0 +1,247 @@
#!/usr/bin/env python3
"""Expose Mem0's memory search as one local coding-agent tool."""
from __future__ import annotations
import json
import os
import sys
from typing import Any
import telemetry
from memory_core import (
CODING_MEMORY_CATEGORY_NAMES,
PLUGIN_VERSION,
SEARCH_SCOPES,
format_search_result,
resolve_repo,
search_memories,
)
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
"Search memories from earlier work in this repository. ALWAYS call this "
"tool before answering anything that could depend on prior context: the "
"user's preferences, facts about this codebase, history, people, projects, "
"or earlier decisions. Do not rely on the chat window alone. The "
"repository's memory is shared by everyone who works in it and includes "
"what it took to run, test, or build here, so search before assuming an "
"invocation works. The scope argument changes what is searched: 'repo' "
"(default) is the whole repository's shared memory plus your own "
"preferences, 'dir' narrows the shared part to the directory you are "
"working in, and 'mine' is your preferences alone."
)
TOOL_SCHEMA = {
"type": "object",
"properties": {
"query": {
"type": "string",
"minLength": 1,
"maxLength": 2000,
"description": "A direct question about earlier work in this repository.",
},
"top_k": {
"type": "integer",
"minimum": 1,
"maximum": 20,
"description": "Maximum memories to return. Uses Mem0's configured default when omitted.",
},
"category": {
"type": "string",
"enum": list(CODING_MEMORY_CATEGORY_NAMES),
"description": "Optional memory category. Omit to search every category.",
},
"scope": {
"type": "string",
"enum": list(SEARCH_SCOPES),
"description": (
"Which memories to search. 'repo' (default) is the whole repository's "
"shared memory plus your own preferences, 'dir' narrows the shared "
"part to the current directory, 'mine' is your preferences alone."
),
},
"run_id": {
"type": "string",
"minLength": 1,
"description": (
"Optional coding-agent session ID. With any scope, restricts results to memories "
"saved in that session. Omit to recall memories across sessions."
),
},
},
"required": ["query"],
"additionalProperties": False,
}
class ToolInputError(ValueError):
pass
def _validate_arguments(
arguments: Any,
) -> tuple[str, int | None, str | None, str | None, str | None]:
if not isinstance(arguments, dict):
raise ToolInputError("Search arguments must be an object.")
unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"}
if unknown:
raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}")
query = arguments.get("query")
if not isinstance(query, str) or not query.strip():
raise ToolInputError("query must be a non-empty string.")
query = query.strip()
if len(query) > 2000:
raise ToolInputError("query must be at most 2,000 characters.")
top_k = arguments.get("top_k")
if top_k is not None and (
isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20
):
raise ToolInputError("top_k must be an integer from 1 to 20.")
category = arguments.get("category")
if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
raise ToolInputError("category must be one of Mem0's supported categories.")
scope = arguments.get("scope")
if scope is not None and scope not in SEARCH_SCOPES:
raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.")
run_id = arguments.get("run_id")
if run_id is not None:
if not isinstance(run_id, str) or not run_id.strip():
raise ToolInputError("run_id must be a non-empty string.")
run_id = run_id.strip()
return query, top_k, category, scope, run_id
def call_search_memories(arguments: Any, cwd: str | None = None) -> str:
query, top_k, category, scope, run_id = _validate_arguments(arguments)
repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
result = search_memories(
None,
repo,
None,
query,
top_k=top_k,
category=category,
scope=scope,
run_id=run_id,
operation="mcp-search",
)
return format_search_result(result)
def _workspace_cwd(params: dict[str, Any]) -> str | None:
meta = params.get("_meta")
if not isinstance(meta, dict):
return None
metadata = meta.get("x-codex-turn-metadata")
if not isinstance(metadata, dict):
return None
workspaces = metadata.get("workspaces") or {}
if isinstance(workspaces, dict):
return next((path for path in workspaces if isinstance(path, str) and path), None)
return None
def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]:
return {
"content": [{"type": "text", "text": text}],
"isError": is_error,
}
def handle_request(message: Any) -> dict[str, Any] | None:
if not isinstance(message, dict):
return None
request_id = message.get("id")
method = message.get("method")
if method == "notifications/initialized":
return None
if method == "initialize":
requested = (message.get("params") or {}).get("protocolVersion")
return {
"jsonrpc": "2.0",
"id": request_id,
"result": {
"protocolVersion": requested or PROTOCOL_VERSION,
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": "mem0", "version": PLUGIN_VERSION},
},
}
if method == "ping":
return {"jsonrpc": "2.0", "id": request_id, "result": {}}
if method == "tools/list":
return {
"jsonrpc": "2.0",
"id": request_id,
"result": {
"tools": [
{
"name": TOOL_NAME,
"description": TOOL_DESCRIPTION,
"inputSchema": TOOL_SCHEMA,
"annotations": {
"readOnlyHint": True,
"idempotentHint": True,
"openWorldHint": True,
},
}
]
},
}
if method == "tools/call":
params = message.get("params") or {}
if params.get("name") != TOOL_NAME:
result = _tool_response("Unknown Mem0 tool.", is_error=True)
else:
try:
result = _tool_response(
call_search_memories(params.get("arguments"), _workspace_cwd(params))
)
except ToolInputError as exc:
result = _tool_response(str(exc), is_error=True)
except Exception:
result = _tool_response("Memory search failed.", is_error=True)
return {"jsonrpc": "2.0", "id": request_id, "result": result}
if request_id is None:
return None
return {
"jsonrpc": "2.0",
"id": request_id,
"error": {"code": -32601, "message": "Method not found"},
}
def main() -> int:
for raw_line in sys.stdin:
try:
message = json.loads(raw_line)
response = handle_request(message)
except json.JSONDecodeError:
response = {
"jsonrpc": "2.0",
"id": None,
"error": {"code": -32700, "message": "Parse error"},
}
except Exception:
response = {
"jsonrpc": "2.0",
"id": None,
"error": {"code": -32603, "message": "Internal error"},
}
if response is not None:
sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n")
sys.stdout.flush()
telemetry.spawn_flush()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""Mem0 diagnostics and user controls."""
from __future__ import annotations
import argparse
import json
import os
import telemetry
from memory_core import (
EvidenceStore,
api_key,
data_dir,
doctor,
forget_remote_repo,
configure_harness,
resolve_repo,
user_id,
)
def _print_status(value: dict) -> None:
last = value.get("last_operation") or {}
print(f"Mem0: {'paused' if value['paused'] else 'active'}")
print(f"Repository: {value['repo_id']}")
print(f"Local data: {value['data_dir']}")
print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}")
print(
"Saved on this computer: "
f"{value['events']} session details, {value['flushes']} memory updates"
)
print(
f"Used in this repository: {value['retrievals']} memories returned, "
f"{value['sidekick_runs']} sidekick runs"
)
if last:
item_label = ""
if last["operation"] in {"flush", "flush-retry"}:
item_label = f", {last['item_count']} memories"
operation = (
"memory update"
if last["operation"] in {"flush", "flush-retry"}
else last["operation"].replace("-", " ")
)
print(
f"Last {operation}: "
f"{'succeeded' if last['success'] else 'failed'} "
f"({last['duration_ms']:.1f} ms{item_label})"
)
sidekick = value.get("last_sidekick") or {}
if sidekick:
state = "finished" if sidekick.get("stopped_at") else "started"
print(
"Last sidekick: "
f"{state}, received {sidekick['context_chars']} characters of memory, "
f"agent {sidekick['agent_id']}"
)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--plugin-data-dir", default="")
parser.add_argument("--harness", default="")
subparsers = parser.add_subparsers(dest="command", required=True)
status = subparsers.add_parser("status")
status.add_argument("--json", action="store_true")
doctor_parser = subparsers.add_parser("doctor")
doctor_parser.add_argument("--json", action="store_true")
subparsers.add_parser("pause")
subparsers.add_parser("resume")
forget = subparsers.add_parser("forget")
forget.add_argument("--remote", action="store_true")
forget.add_argument("--yes", action="store_true")
forget.add_argument("--include-project-memory", action="store_true")
args = parser.parse_args()
if args.harness:
source_tag = f"{args.harness.replace('-', '_')}_plugin"
configure_harness(args.harness, source_tag=source_tag)
telemetry.init(harness=args.harness, source_tag=source_tag.upper())
if args.plugin_data_dir:
os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
store = EvidenceStore()
try:
repo = resolve_repo(os.getcwd())
telemetry.record("control", repo=repo, action=args.command)
if args.command == "status":
result = {
**store.status(repo.identity),
"repo_id": repo.identity,
"app_id": repo.app_id,
"project_id": repo.project_id,
"directory": repo.directory,
"user_id": user_id(),
"data_dir": str(data_dir()),
"api_key_configured": bool(api_key()),
}
if args.json:
print(json.dumps(result, indent=2, default=str))
else:
_print_status(result)
elif args.command == "doctor":
result = doctor(os.getcwd())
if args.json:
print(json.dumps(result, indent=2, default=str))
else:
for name, check in result["checks"].items():
print(
f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}"
)
return 0 if result["ok"] else 1
elif args.command == "pause":
store.set_setting("paused", "true")
print("Mem0 stopped saving and searching memories.")
elif args.command == "resume":
store.set_setting("paused", "false")
print("Mem0 resumed saving and searching memories.")
elif args.command == "forget":
if not args.yes:
print(
"Refusing to delete data without --yes. Add --remote to also "
"delete this user/repository scope from Mem0."
)
return 2
remote_result = (
forget_remote_repo(
repo, include_project_memory=args.include_project_memory
)
if args.remote
else None
)
local_result = store.forget_local_repo(repo.identity)
print(
json.dumps(
{"local": local_result, "remote": remote_result},
indent=2,
default=str,
)
)
if remote_result and remote_result.get("status") == "error":
return 1
finally:
store.close()
telemetry.spawn_flush()
return 0
if __name__ == "__main__":
raise SystemExit(main())
File diff suppressed because it is too large Load Diff
+397
View File
@@ -0,0 +1,397 @@
#!/usr/bin/env python3
"""Anonymous usage telemetry for Mem0 agent plugins.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
A detached `python3 telemetry.py` drains the spool in one batched PostHog request,
started once per session and again from the flush worker that is already detached.
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
keys: only event names, durations, counts, coarse outcomes, and salted hashes.
"""
from __future__ import annotations
import hashlib
import json
import os
import platform
import subprocess
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
from typing import Any
import memory_core
_harness: str = "generic"
_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
"apikey",
"authorization",
"password",
"query",
"secret",
"prompt",
"token",
"text",
"memory",
"message",
"error",
"path",
"cwd",
"userid",
"agentid",
"runid",
"repoid",
"repositoryid",
"projectid",
"appid",
"filters",
}
def init(harness: str = "generic", source_tag: str = "") -> None:
global _harness, _source_tag
_harness = harness
_source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"
EVENT_PREFIX = "code"
SPOOL_LIMIT_BYTES = 256 * 1024
BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
def is_enabled() -> bool:
"""Whether telemetry is switched on for this process."""
return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in {
"false",
"0",
"no",
"off",
}
def _digest(value: str, length: int = 16) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
def _safe_value(value: Any) -> Any:
if isinstance(value, str):
return memory_core.redact(value)
if isinstance(value, dict):
return {
key: _safe_value(item)
for key, item in value.items()
if "".join(character for character in str(key).lower() if character.isalnum())
not in _PRIVATE_KEYS
}
if isinstance(value, (list, tuple)):
return [_safe_value(item) for item in value]
if value is None or isinstance(value, (bool, int, float)):
return value
return memory_core.redact(value)
def _spool_path() -> Path:
return memory_core.data_dir() / "telemetry.jsonl"
def _identity_path() -> Path:
return memory_core.data_dir() / "telemetry-identity.json"
def _read_identity() -> dict[str, str]:
try:
value = json.loads(_identity_path().read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
return value if isinstance(value, dict) else {}
def _write_identity(identity: dict[str, str]) -> None:
path = _identity_path()
temporary = path.with_suffix(f".{os.getpid()}.tmp")
try:
path.parent.mkdir(parents=True, exist_ok=True)
temporary.write_text(json.dumps(identity), encoding="utf-8")
temporary.replace(path)
except OSError:
try:
temporary.unlink()
except OSError:
pass
def anonymous_id(identity: dict[str, str] | None = None) -> str:
"""Per-machine anonymous identifier, created and persisted on first use."""
identity = _read_identity() if identity is None else identity
existing = identity.get("anonymous_id")
if existing:
return existing
created = f"code-anon-{uuid.uuid4().hex}"
identity["anonymous_id"] = created
_write_identity(identity)
return created
def is_first_run() -> bool:
"""Whether this machine has never recorded a plugin event before."""
return not _identity_path().exists()
def record(
event: str,
*,
repo: Any = None,
session_id: str | None = None,
**properties: Any,
) -> None:
"""Append one event to the local spool. Never blocks and never raises."""
if not is_enabled():
return
try:
spool = _spool_path()
try:
if spool.stat().st_size > SPOOL_LIMIT_BYTES:
return
except OSError:
pass
properties = _safe_value(properties)
properties.update(
harness=_harness,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
if repo is not None:
properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
if session_id:
properties["session_hash"] = _digest(session_id)
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
},
},
separators=(",", ":"),
default=str,
)
spool.parent.mkdir(parents=True, exist_ok=True)
with spool.open("a", encoding="utf-8") as handle:
handle.write(line + "\n")
except Exception:
pass
def error_kind(exc: BaseException | str) -> str:
"""Coarse, content-free label for a failure, safe to send."""
text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}"
lowered = text.lower()
if "timed out" in lowered or "timeout" in lowered:
return "timeout"
if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered:
return "auth"
if "429" in lowered or "rate limit" in lowered:
return "rate-limited"
if any(code in lowered for code in ("500", "502", "503", "504")):
return "server-error"
if "400" in lowered or "422" in lowered:
return "bad-request"
if isinstance(exc, str):
return "other"
if isinstance(exc, urllib.error.URLError):
return "network"
return type(exc).__name__
def spawn_flush() -> bool:
"""Start the detached sender that drains the spool."""
if not is_enabled():
return False
try:
if not _spool_path().exists() and not any(
memory_core.data_dir().glob("telemetry-*.sending")
):
return False
subprocess.Popen(
[sys.executable, str(Path(__file__).resolve())],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
close_fds=True,
**memory_core.detached_process_kwargs(),
)
return True
except Exception:
return False
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
spool = _spool_path()
try:
spool.replace(claim)
return claim
except OSError:
pass
now = time.time()
for orphan in sorted(directory.glob("telemetry-*.sending")):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
if age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
if age < CLAIM_STALE_SECONDS:
continue
try:
orphan.replace(claim)
return claim
except OSError:
continue
return None
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
request = urllib.request.Request(
url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response:
payload = json.loads(response.read().decode("utf-8"))
except Exception:
return ""
email = payload.get("user_email") if isinstance(payload, dict) else ""
return email if isinstance(email, str) else ""
def _post(payload: dict[str, Any], url: str) -> bool:
request = urllib.request.Request(
url,
data=json.dumps(payload, default=str).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=SEND_TIMEOUT):
return True
except Exception:
return False
def resolve_distinct_id() -> tuple[str, str]:
"""Return the PostHog distinct id and the anonymous id it replaced, if any."""
identity = _read_identity()
email = identity.get("email", "")
if email:
return email, ""
key = memory_core.api_key()
if not key:
return anonymous_id(identity), ""
email = _resolve_email(key)
if not email:
return anonymous_id(identity), ""
previous = identity.get("anonymous_id", "")
identity["email"] = email
_write_identity(identity)
return email, previous
def flush() -> int:
"""Drain claimed spools to PostHog and return the number of events sent."""
if not is_enabled():
return 0
claim = _claim_spool()
if claim is None:
return 0
try:
lines = claim.read_text(encoding="utf-8").splitlines()
except OSError:
return 0
events = []
for line in lines:
try:
value = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
try:
claim.unlink()
except OSError:
pass
return 0
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
_post(
{
"api_key": POSTHOG_API_KEY,
"event": "$identify",
"distinct_id": distinct_id,
"properties": {
"$anon_distinct_id": aliased_anonymous_id,
"$lib": "posthog-python",
},
},
POSTHOG_CAPTURE_URL,
)
sent = 0
for start in range(0, len(events), BATCH_SIZE):
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
"timestamp": event.get("timestamp"),
"properties": {
"source": _source_tag,
"language": "python",
"$process_person_profile": False,
"$lib": "posthog-python",
**(event.get("properties") or {}),
},
}
for event in events[start : start + BATCH_SIZE]
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
return sent
sent += len(batch)
try:
claim.unlink()
except OSError:
pass
return sent
def main() -> int:
flush()
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception:
raise SystemExit(0)
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""Translate Kimi Code hooks into the shared Mem0 runtime."""
from __future__ import annotations
import contextlib
import io
import json
import os
import sys
import uuid
from pathlib import Path
HERE = Path(__file__).resolve()
BUNDLED_CORE = HERE.parent.parent / "core"
CORE = BUNDLED_CORE if BUNDLED_CORE.is_dir() else HERE.parents[2] / "core" / "python"
sys.path.insert(0, str(CORE))
import hook_runner # noqa: E402
import telemetry # noqa: E402
from memory_core import configure_harness, record_sidekick_start, record_sidekick_stop, record_tool # noqa: E402
EVENTS = {
"SessionStart": ["session-start"],
"UserPromptSubmit": ["user-prompt"],
"PostToolUse": ["post-tool"],
"PostToolUseFailure": ["post-tool-failure"],
"Stop": ["stop"],
"PreCompact": ["flush", "--reason", "pre-compact"],
"SessionEnd": ["flush", "--reason", "session-end"],
"SubagentStart": ["sidekick-start"],
"SubagentStop": ["sidekick-stop"],
}
def _session_dir(session_id: str) -> Path | None:
home = Path(os.environ.get("KIMI_CODE_HOME", Path.home() / ".kimi-code")).expanduser()
found = None
try:
with (home / "session_index.jsonl").open(encoding="utf-8") as index:
for line in index:
try:
entry = json.loads(line)
except json.JSONDecodeError:
continue
if entry.get("sessionId") == session_id and isinstance(entry.get("sessionDir"), str):
found = Path(entry["sessionDir"])
except OSError:
pass
if found:
return found
if not session_id or Path(session_id).name != session_id:
return None
return next((path for path in (home / "sessions").glob(f"*/{session_id}") if path.is_dir()), None)
def _last_assistant_message(transcript: Path) -> str:
message = ""
step_id = None
parts = []
try:
lines = transcript.read_text(encoding="utf-8").splitlines()
except OSError:
return ""
for line in lines:
try:
record = json.loads(line)
except json.JSONDecodeError:
continue
if record.get("type") != "context.append_loop_event" or not isinstance(record.get("event"), dict):
continue
event = record["event"]
if event.get("type") == "step.begin":
step_id = event.get("uuid")
parts = []
elif event.get("type") == "content.part" and event.get("stepUuid") == step_id:
part = event.get("part")
if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str):
parts.append(part["text"])
elif event.get("type") == "step.end" and event.get("uuid") == step_id:
if event.get("finishReason") not in {"error", "interrupted"} and parts:
message = "".join(parts)
step_id = None
parts = []
return message
def normalize(payload: dict) -> dict:
value = dict(payload)
if "tool_output" in value:
value.setdefault("tool_response", value["tool_output"])
if "error" in value:
value.setdefault("tool_response", value["error"])
if "response" in value:
value.setdefault("last_assistant_message", value["response"])
if "agent_name" in value:
value.setdefault("agent_type", value["agent_name"])
if value.get("hook_event_name") == "Stop":
session = _session_dir(str(value.get("session_id") or ""))
transcript = session / "agents" / "main" / "wire.jsonl" if session else None
if transcript and transcript.is_file():
value.setdefault("transcript_path", str(transcript))
if message := _last_assistant_message(transcript):
value.setdefault("last_assistant_message", message)
return value
def _sidekick_start(store, payload):
payload = dict(payload)
payload.setdefault("agent_id", f"kimi-{uuid.uuid4().hex}")
context = record_sidekick_start(store, payload)
return {"hookSpecificOutput": {"additionalContext": context}} if context else None
def _sidekick_stop(store, payload):
record_sidekick_stop(store, payload)
def main() -> int:
if len(sys.argv) != 2 or sys.argv[1] not in EVENTS:
return 2
event = sys.argv[1]
try:
raw = json.load(sys.stdin)
except (json.JSONDecodeError, OSError):
raw = {}
sys.argv = [sys.argv[0], *EVENTS[event]]
sys.stdin = io.StringIO(json.dumps(normalize(raw if isinstance(raw, dict) else {})))
configure_harness("kimi", data_dir_name="kimi-plugin", source_tag="kimi_plugin")
telemetry.init(harness="kimi", source_tag="KIMI_PLUGIN")
output = io.StringIO()
with contextlib.redirect_stdout(output):
result = hook_runner.run(
extra_actions={
"post-tool-failure": lambda store, payload: record_tool(store, payload, failed=True),
"sidekick-start": _sidekick_start,
"sidekick-stop": _sidekick_stop,
},
automatic_flush_reasons={"session-end", "pre-compact"},
)
if event in {"UserPromptSubmit", "SubagentStart"} and (raw_output := output.getvalue().strip()):
parsed = json.loads(raw_output)
context = parsed.get("hookSpecificOutput", {}).get("additionalContext", "")
if context:
print(context)
return result
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as exc:
hook_runner.log_failure(exc)
raise SystemExit(0) from None
+32
View File
@@ -0,0 +1,32 @@
{
"name": "mem0",
"version": "0.3.1",
"description": "Cross-session memory and token savings for coding agents.",
"keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"],
"author": { "name": "Mem0", "email": "support@mem0.ai" },
"homepage": "https://docs.mem0.ai/integrations/kimi",
"license": "Apache-2.0",
"interface": {
"displayName": "Mem0",
"shortDescription": "Cross-session memory for Kimi Code"
},
"skills": "./skills/",
"agents": "./agents/",
"mcpServers": {
"mem0": {
"command": "python3",
"args": ["./core/mcp_server.py"]
}
},
"hooks": [
{ "event": "SessionStart", "command": "python3 ./hooks/adapter.py SessionStart", "timeout": 5 },
{ "event": "UserPromptSubmit", "command": "python3 ./hooks/adapter.py UserPromptSubmit", "timeout": 6 },
{ "event": "PostToolUse", "matcher": ".*", "command": "python3 ./hooks/adapter.py PostToolUse", "timeout": 3 },
{ "event": "PostToolUseFailure", "matcher": ".*", "command": "python3 ./hooks/adapter.py PostToolUseFailure", "timeout": 3 },
{ "event": "Stop", "command": "python3 ./hooks/adapter.py Stop", "timeout": 3 },
{ "event": "PreCompact", "command": "python3 ./hooks/adapter.py PreCompact", "timeout": 5 },
{ "event": "SessionEnd", "command": "python3 ./hooks/adapter.py SessionEnd", "timeout": 5 },
{ "event": "SubagentStart", "matcher": "^sidekick$", "command": "python3 ./hooks/adapter.py SubagentStart", "timeout": 5 },
{ "event": "SubagentStop", "matcher": "^sidekick$", "command": "python3 ./hooks/adapter.py SubagentStop", "timeout": 5 }
]
}
@@ -0,0 +1,13 @@
{
"id": "mem0",
"version": "0.3.1",
"homepage": "https://docs.mem0.ai/integrations/kimi",
"native": {
"pluginRoot": "${KIMI_PLUGIN_ROOT}",
"files": {
"kimi.plugin.json": "kimi.plugin.json",
"hooks/adapter.py": "hooks/adapter.py",
"agents/sidekick.md": "agents/sidekick.md"
}
}
}
@@ -0,0 +1,26 @@
---
name: forget
description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories.
disable-model-invocation: true
---
# Forget this repository's memories
This permanently deletes remote memories. Before running anything, tell the
user exactly what will be deleted: their own memories for this repository
only. The repository's project memory is shared by everyone who works in it,
so it stays unless the user explicitly asks to delete that too.
After the user confirms, run:
```bash
python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" forget --remote --yes
```
If the user also asked to delete the repository's shared project memory, add
`--include-project-memory` and say that this removes it for every teammate.
Report what the command output says was deleted. If the user only wants local
data cleared (evidence log, pending queue), run the same command without
`--remote`. Never pass `--yes` before the user has confirmed in this
conversation.
@@ -0,0 +1,20 @@
---
name: pause
description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments.
disable-model-invocation: true
---
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
anonymous telemetry ping still fires at session start unless
`MEM0_TELEMETRY=false`):
```bash
python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" pause
```
Confirm the new state back to the user, and remind them that already-created
memories still exist and remain searchable. Pending unsent packets are held
while paused, not expired, and are delivered after resuming. To turn capture
back on, use `/mem0:resume`.
@@ -0,0 +1,21 @@
---
name: remember
description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions.
disable-model-invocation: true
---
# Remember something for future sessions
Mem0 creates memories from the session automatically — there is no separate
write command. When the user asks to remember something:
1. Restate the fact clearly and completely in your reply, in one or two
sentences, including any names, values, or paths it depends on. Your visible
reply is what memory extraction reads, so a precise restatement is what gets
remembered.
2. Tell the user it will be saved with this session's memories when the session
ends or compacts, and that it will surface in future sessions in this
repository (they can check later with /mem0:search).
Do not invent a storage confirmation or a memory ID — creation happens in the
background after the session.
@@ -0,0 +1,19 @@
---
name: resume
description: Resume Mem0 memory capture after it was paused with /mem0:pause.
disable-model-invocation: true
---
# Resume memory capture
Resume memory capture for this machine.
Run:
```bash
python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" resume
```
Confirm to the user that capture is active again. New sessions record evidence and
create memories as normal; nothing that happened while paused is retroactively
captured.
@@ -0,0 +1,28 @@
---
name: search
description: Search memories from earlier Kimi sessions in this repository. Use it when earlier work may already explain the code, error, decision, or command you need, so you can avoid repeating file reads, searches, or experiments.
argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]"
disable-model-invocation: true
---
# Search memories
Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
`--scope`, and `--run-id` as tool arguments instead of including them in the
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
category; a category is a best-effort label Mem0 assigned when it saved the
memory, so if a category search misses, repeat it without the category. Omit
`scope` to use the configured default, normally `repo`: this repository's
shared memory, which everyone who works in it contributes to, plus your own
preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
monorepo), `mine` for your own preferences alone.
Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent
session. Omit `run_id` to search across sessions. It filters the memories returned;
it does not identify the session making the search request. Use a known session ID,
never invent one. Return the tool's result directly.
@@ -0,0 +1,23 @@
---
name: status
description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken.
disable-model-invocation: false
---
# Memory status
Run both commands and report the combined result in plain language:
```bash
python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" status --json
python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" doctor
```
Summarize, using only fields the JSON actually reports: whether capture is
active or paused, the user ID and repository scope (`repo_id`), whether an
API key is configured, the event/flush/retrieval counts (`flushes` is the
number of completed flushes, not a pending count), and the doctor check
results. If doctor reports an authentication failure (401 / invalid key), say
clearly that the Mem0 API key is invalid or expired and that memories are NOT
being created. Never report an auth failure as "no memories found". Suggest
reinstalling with `--config api_key=...` in that case.
+190
View File
@@ -0,0 +1,190 @@
from __future__ import annotations
import importlib.util
import json
import sys
from pathlib import Path
HOST = Path(__file__).resolve().parents[1]
CORE_ROOT = HOST.parent / "agent-plugin-core"
sys.path.insert(0, str(CORE_ROOT))
from build.build import build # noqa: E402
SPEC = importlib.util.spec_from_file_location("kimi_adapter", HOST / "hooks" / "adapter.py")
assert SPEC and SPEC.loader
adapter = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(adapter)
def _write_kimi_session(home: Path, session_id: str, records: list[dict]) -> Path:
session = home / "sessions" / "wd_mem0_deadbeef1234" / session_id
transcript = session / "agents" / "main" / "wire.jsonl"
transcript.parent.mkdir(parents=True)
transcript.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8")
(home / "session_index.jsonl").write_text(
json.dumps({"sessionId": session_id, "sessionDir": str(session), "workDir": "/work/mem0"}) + "\n",
encoding="utf-8",
)
return transcript
def test_stop_reads_main_response_from_kimi_session_transcript(tmp_path: Path, monkeypatch) -> None:
transcript = _write_kimi_session(
tmp_path,
"session_abc",
[
{"type": "metadata", "protocol_version": "1.5", "created_at": 1788431400000},
{
"type": "context.append_loop_event",
"agentId": "main",
"event": {"type": "step.begin", "uuid": "step-1", "turnId": "0", "step": 1},
"time": 1788431400100,
},
{
"type": "context.append_loop_event",
"agentId": "main",
"event": {
"type": "content.part",
"stepUuid": "step-1",
"part": {"type": "text", "text": "Earlier answer."},
},
"time": 1788431400200,
},
{
"type": "context.append_loop_event",
"agentId": "main",
"event": {"type": "step.end", "uuid": "step-1", "finishReason": "end_turn"},
"time": 1788431400300,
},
{
"type": "context.append_loop_event",
"agentId": "main",
"event": {"type": "step.begin", "uuid": "step-2", "turnId": "1", "step": 1},
"time": 1788431400400,
},
{
"type": "context.append_loop_event",
"agentId": "main",
"event": {
"type": "content.part",
"stepUuid": "step-2",
"part": {"type": "think", "think": "Do not capture this reasoning."},
},
"time": 1788431400500,
},
{
"type": "context.append_loop_event",
"agentId": "main",
"event": {
"type": "content.part",
"stepUuid": "step-2",
"part": {"type": "text", "text": "Fixed and "},
},
"time": 1788431400600,
},
{
"type": "context.append_loop_event",
"agentId": "main",
"event": {
"type": "content.part",
"stepUuid": "step-2",
"part": {"type": "text", "text": "tested."},
},
"time": 1788431400700,
},
{
"type": "context.append_loop_event",
"agentId": "main",
"event": {"type": "step.end", "uuid": "step-2", "finishReason": "end_turn"},
"time": 1788431400800,
},
],
)
monkeypatch.setenv("KIMI_CODE_HOME", str(tmp_path))
value = adapter.normalize(
{
"hook_event_name": "Stop",
"session_id": "session_abc",
"session_title": "Fix Kimi capture",
"client_type": "kimi_code_cli",
"cwd": "/work/mem0",
"stop_hook_active": False,
}
)
assert value["last_assistant_message"] == "Fixed and tested."
assert value["transcript_path"] == str(transcript)
def test_repeated_sidekick_invocations_get_distinct_run_ids(tmp_path: Path) -> None:
store = adapter.hook_runner.EvidenceStore(tmp_path / "evidence.sqlite3")
payload = {
"hook_event_name": "SubagentStart",
"session_id": "session_abc",
"session_title": "Fix Kimi capture",
"client_type": "kimi_code_cli",
"cwd": str(tmp_path),
"agent_name": "sidekick",
"prompt": "Fix the adapter",
}
try:
adapter._sidekick_start(store, adapter.normalize({**payload, "agent_id": "first"}))
adapter._sidekick_start(store, adapter.normalize({**payload, "agent_id": "second"}))
adapter._sidekick_stop(
store,
adapter.normalize(
{
**payload,
"hook_event_name": "SubagentStop",
"response": "First run complete.",
"agent_id": "first",
}
),
)
adapter._sidekick_stop(
store,
adapter.normalize(
{
**payload,
"hook_event_name": "SubagentStop",
"response": "Second run complete.",
"agent_id": "second",
}
),
)
rows = store.conn.execute(
"SELECT agent_id, stopped_at, final_message FROM sidekick_runs ORDER BY started_at, agent_id"
).fetchall()
finally:
store.close()
assert len(rows) == 2
assert rows[0]["agent_id"] != rows[1]["agent_id"]
assert all(row["stopped_at"] for row in rows)
assert {row["agent_id"]: row["final_message"] for row in rows} == {
"first": "First run complete.", "second": "Second run complete."
}
def test_native_kimi_bundle_uses_inline_native_contract(tmp_path: Path) -> None:
root = build("kimi", "native", tmp_path / "kimi")
manifest = json.loads((root / "kimi.plugin.json").read_text(encoding="utf-8"))
assert manifest["skills"] == "./skills/"
assert manifest["agents"] == "./agents/"
assert manifest["mcpServers"]["mem0"]["args"] == ["./core/mcp_server.py"]
assert {hook["event"] for hook in manifest["hooks"]} >= {
"SessionStart",
"UserPromptSubmit",
"PostToolUse",
"SubagentStart",
"SubagentStop",
"PreCompact",
"SessionEnd",
}
assert (root / "agents" / "sidekick.md").is_file()
assert not any(path.is_symlink() for path in root.rglob("*"))