rrrrrredy/research-toolkit / plugins/research-toolkit
research-toolkit
FlaggedUse for source-backed long-form research and writing in English or Chinese across fields, including revisions and continuation. Understand requirements, develop analysis through substantive research collaboration, and deliver a complete report after independent review, audit and acceptance.
scripts/install_usage.py
View on GitHub"""Configure Toolkit usage recording in Codex, Claude Code or OpenCode."""
from __future__ import annotations
import argparse
import base64
import json
import os
import re
from pathlib import Path
import sys
import time
import usage_events as usage
EVENTS = ["UserPromptSubmit", "PreToolUse", "PostToolUse", "SubagentStart", "SubagentStop", "Stop", "SessionEnd", "PreCompact"]
def launcher(paths, host, windows=False):
if not windows:
return f'"{paths[0]}" "{paths[1]}" --host {host}'
quoted = ["'"+value.replace("'", "''")+"'" for value in paths]
script_text = ("$OutputEncoding = [System.Text.UTF8Encoding]::new(); "
"[Console]::InputEncoding = $OutputEncoding; "
f"[Console]::In.ReadToEnd() | & {quoted[0]} {quoted[1]} --host {host}; exit $LASTEXITCODE")
return "powershell.exe -NoProfile -NonInteractive -EncodedCommand "+base64.b64encode(script_text.encode("utf-16le")).decode()
def owned_launcher(command, host):
"""Recognize only the exact launchers generated here, including an older install path."""
if not isinstance(command, str):
return False
direct = re.fullmatch(r'"([^"]+)" "([^"]+/scripts/usage_host\.py)" --host ' + re.escape(host), command)
if direct:
return command == launcher(direct.groups(), host)
encoded = re.fullmatch(r'powershell\.exe -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/=]+)', command)
if not encoded:
return False
try:
script = base64.b64decode(encoded[1], validate=True).decode('utf-16le')
except (ValueError, UnicodeError):
return False
match = re.search(r" \| & '((?:[^']|'')*)' '((?:[^']|'')*)' --host " + re.escape(host) + r'; exit \$LASTEXITCODE$', script)
if not match:
return False
paths = [value.replace("''", "'") for value in match.groups()]
return paths[1].endswith('/scripts/usage_host.py') and command == launcher(paths, host, windows=True)
def write_changed(path, text):
if path.exists():
before = path.read_text(encoding="utf-8")
if before == text:
return
backup = path.with_name(path.name+".toolkit-backup-"+str(time.time_ns()))
backup.write_text(before, encoding="utf-8")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def install(host, project, remove=False):
script = Path(__file__).resolve().with_name("usage_host.py")
# Quote POSIX paths; Windows uses the explicit PowerShell launcher below.
# Refuse expansion metacharacters rather than interpolate them.
paths = [Path(sys.executable).as_posix(), script.as_posix()]
if any(any(char in item for char in ['"', '$', '`', '%', '\n', '\r']) for item in paths):
raise ValueError("Install path contains shell metacharacters; use a plain directory path")
command = launcher(paths, host, windows=os.name == "nt")
if host == "opencode":
path = project/".opencode/plugins/research-toolkit-usage.js"
if path.exists() and "research-toolkit usage observer" not in path.read_text(encoding="utf-8"):
raise ValueError("Existing OpenCode plugin file is not managed by Toolkit; preserved")
if remove:
if path.exists():
path.unlink()
else:
module = script.with_name("usage_opencode.mjs").as_uri()
write_changed(path, "// research-toolkit usage observer\nimport { createUsagePlugin } from "+json.dumps(module)+";\nexport default createUsagePlugin("+json.dumps(sys.executable)+");\n")
return path
path = project/(".codex/hooks.json" if host == "codex" else ".claude/settings.local.json")
if remove and not path.exists():
return path
config = json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {}
if not isinstance(config, dict) or not isinstance(config.get("hooks", {}), dict):
raise ValueError("Existing agent tool hooks configuration is not an object; preserved")
groups = config.setdefault("hooks", {})
for event in EVENTS + (["PostToolUseFailure"] if host == "claude" else []):
existing = groups.get(event, [])
if not isinstance(existing, list):
raise ValueError(f"hooks.{event} must be an array; existing file preserved")
kept = []
for group in existing:
if not isinstance(group, dict) or not isinstance(group.get("hooks", []), list):
raise ValueError(f"hooks.{event} contains an invalid group; existing file preserved")
handlers = group.get("hooks", [])
if any(not isinstance(handler, dict) for handler in handlers):
raise ValueError(f"hooks.{event} contains an invalid handler; existing file preserved")
remaining = [handler for handler in handlers if not owned_launcher(handler.get("command"), host)]
if remaining or not handlers:
kept.append({**group, "hooks": remaining})
if not remove:
kept.append({"hooks": [{"type": "command", "command": command, "timeout": 3}]})
if kept:
groups[event] = kept
else:
groups.pop(event, None)
write_changed(path, json.dumps(config, ensure_ascii=False, indent=2)+"\n")
return path
def main(argv=None, *, setup=False):
parser = argparse.ArgumentParser(prog=(Path(sys.argv[0]).name + " setup") if setup else None, description=__doc__)
parser.add_argument("--host", required=True, choices=["codex", "claude", "opencode"])
parser.add_argument("--project", type=Path, default=Path.cwd())
parser.add_argument("--channel", choices=sorted(usage.CHANNELS), default="manual")
parser.add_argument("--form", choices=["skill", "plugin", "cli", "mcp"], default="skill")
parser.add_argument("--remove", action="store_true")
parser.add_argument("--no-telemetry", action="store_true", help="Skip usage configuration for this setup.")
parser.add_argument("--apply", action="store_true", help="Apply optional hooks using the existing recording choice.")
parser.add_argument("--preview", "--dry-run", action="store_true",
help="Show the effective setting, target and planned hooks without writing anything.")
args = parser.parse_args(argv)
project = args.project.resolve()
path = project / (".opencode/plugins/research-toolkit-usage.js" if args.host == "opencode" else
".codex/hooks.json" if args.host == "codex" else ".claude/settings.local.json")
if args.apply and (args.preview or args.no_telemetry):
parser.error("--apply cannot be combined with --preview or --no-telemetry")
if args.preview or args.no_telemetry or (setup and not args.apply):
enabled = usage.recording_enabled()
events = EVENTS + (["PostToolUseFailure"] if args.host == "claude" else [])
if args.host == "opencode":
events = ["OpenCode usage observer"]
print(json.dumps({"host": args.host, "preview": True, "recording_enabled": enabled,
"target": str(path), "configuration_exists": path.is_file(),
"planned_action": "none" if args.no_telemetry else "remove_owned_hooks" if args.remove else
"configure_hooks" if enabled else "none",
"hooks": events if (enabled or args.remove) and not args.no_telemetry else [],
"configuration_changed": False}))
return
if not args.remove and not usage.recording_enabled():
print(json.dumps({"host": args.host, "path": str(path), "removed": False,
"configuration_changed": False,
"next": "Basic usage recording is off. No project hooks were installed."}))
return
before = path.read_bytes() if path.exists() else None
path = install(args.host, project, args.remove)
configuration_changed = before != (path.read_bytes() if path.exists() else None)
next_step = "Only Toolkit usage recording configuration was removed."
if not args.remove:
first_installation = False
with usage.database() as db:
usage.set_setting(db, usage.installation_key()+"channel", args.channel)
usage.set_setting(db, usage.installation_key()+"form", args.form)
config = usage.settings(db)
enabled = config["enabled"] == "on" and not usage.disabled_by_environment()
if enabled:
usage.notice(db, config)
if config.get("seen") != "1":
usage.enqueue(db, config, "installation_seen", host=args.host, entry=args.form)
usage.set_setting(db, "seen", "1")
first_installation = True
if enabled:
usage.schedule_upload()
reload_instruction = ("Reload or reopen the Codex session to load this configuration."
if args.host == "codex" else
"Follow the application's trust or reload instructions to load this configuration.")
next_step = (
(("Usage recording configuration was written. " if configuration_changed else
"Existing usage recording configuration is unchanged and reused. ") +
("The installation event is queued. " if first_installation else "") +
(reload_instruction if configuration_changed else "")).rstrip()
if enabled else "Usage recording remains off; the existing off setting was preserved."
)
visible = usage.visible_notice() if not args.remove else None
print(json.dumps({"host": args.host, "path": str(path), "removed": args.remove,
"configuration_changed": configuration_changed, "next": next_step,
**({"usage_notice": visible} if visible else {})}))
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |