Skip to content

rrrrrredy/research-toolkit / plugins/research-toolkit

research-toolkit

Flagged

Use 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.

FileKindSize
.codex-plugin/plugin.jsonconfig1.0 KB
.generated-files.jsonconfig6.3 KB
.mcp.jsonconfig158 B
LICENSEother1.0 KB
README.mdmarkdown3.4 KB
README.zh-CN.mdmarkdown3.0 KB
SKILL.mdskill md7.8 KB
SKILL.zh-CN.mdmarkdown6.5 KB
VERSIONother6 B
docs/compatibility.mdmarkdown3.8 KB
docs/compatibility.zh-CN.mdmarkdown3.2 KB
docs/delivery-verification.mdmarkdown19.2 KB
docs/delivery-verification.zh-CN.mdmarkdown16.3 KB
docs/review-completion.mdmarkdown18.0 KB
docs/review-completion.zh-CN.mdmarkdown14.7 KB
docs/usage-data.mdmarkdown15.4 KB
docs/usage-data.zh-CN.mdmarkdown13.9 KB
docs/usage-modes.mdmarkdown55.6 KB
docs/usage-modes.zh-CN.mdmarkdown48.6 KB
hooks/hooks.jsonconfig3.2 KB
mcp.jsonconfig253 B
plugin.jsonconfig1.1 KB
references/gotchas.mdmarkdown6.2 KB
references/gotchas.zh-CN.mdmarkdown3.6 KB
references/horizontal-vertical-analysis.mdmarkdown4.3 KB
references/horizontal-vertical-analysis.zh-CN.mdmarkdown3.2 KB
references/optional-analysis-lenses.mdmarkdown8.1 KB
references/optional-analysis-lenses.zh-CN.mdmarkdown6.1 KB
references/postmortem-lessons.mdmarkdown4.3 KB
references/postmortem-lessons.zh-CN.mdmarkdown3.5 KB
references/quality-gates.mdmarkdown5.7 KB
references/quality-gates.zh-CN.mdmarkdown4.5 KB
references/research-standard.mdmarkdown18.2 KB
references/research-standard.zh-CN.mdmarkdown13.7 KB
references/research-workflow.mdmarkdown25.5 KB
references/research-workflow.zh-CN.mdmarkdown19.9 KB
references/subagents-and-review-loop.mdmarkdown17.0 KB
references/subagents-and-review-loop.zh-CN.mdmarkdown13.4 KB
references/task-continuity.mdmarkdown6.9 KB
references/task-continuity.zh-CN.mdmarkdown5.3 KB
references/writing-style.mdmarkdown18.1 KB
references/writing-style.zh-CN.mdmarkdown14.9 KB
requirements-mcp.txtmarkdown11 B
scripts/agent_session.pyscript6.2 KB
scripts/check_delivery.pyscript44.6 KB
scripts/check_review_completion.pyscript28.5 KB
scripts/cli_agent_session.pyscript9.6 KB
scripts/codex_session.pyscript7.5 KB
scripts/extract_source_text.pyscript10.7 KB
scripts/host_review.pyscript78.4 KB
scripts/install_usage.pyscript9.7 KB
scripts/record_changes.pyscript13.7 KB
scripts/release_updates.pyscript9.8 KB
scripts/research_guidance.pyscript5.8 KB
scripts/research_host.pyscript52.4 KB
scripts/research_mcp.pyscript18.9 KB
scripts/research_records.pyscript28.5 KB
scripts/research_workflow.pyscript40.9 KB
scripts/review_process.pyscript5.2 KB
scripts/review_runner.pyscript20.2 KB
scripts/run_observation.pyscript7.7 KB
scripts/task_context.pyscript21.1 KB
scripts/task_lock.pyscript1.7 KB
scripts/task_reading.pyscript4.0 KB
scripts/task_storage.pyscript3.1 KB
scripts/usage_events.pyscript38.9 KB
scripts/usage_host.pyscript7.8 KB
scripts/usage_opencode.mjsscript3.1 KB

scripts/agent_session.py

View on GitHub
"""Agent tool selection and the common event boundary for Agent execution."""
from __future__ import annotations

import os
from pathlib import Path
import queue
import shutil
import signal
import subprocess
import time

from review_process import ProcessCleanupError


HOSTS = ("claude", "opencode", "codex")
PROCESS_EXIT_TIMEOUT = 5


def stop_native_process(process, job):
    """Stop a local host and its descendants, even if the parent already exited."""
    try:
        if job:
            job.close()  # Kill-on-close covers children holding the protocol pipes open.
            if process and process.poll() is None:
                process.kill()  # Also close a launch gate whose job attachment failed.
        elif process:
            try:
                os.killpg(process.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
        if process:
            process.wait(timeout=PROCESS_EXIT_TIMEOUT)
    except (OSError, subprocess.TimeoutExpired) as exc:
        target = f"PID {process.pid}" if process is not None else "the launch job"
        raise ProcessCleanupError(f"Native process cleanup could not be confirmed for {target}.") from exc


def select_host(host=None):
    host = host or os.environ.get("RESEARCH_TOOLKIT_HOST")
    if not host:
        detected = [name for name, present in (
            ("claude", os.environ.get("CLAUDECODE")),
            ("codex", os.environ.get("CODEX_THREAD_ID"))) if present]
        if not detected:
            detected = [name for name in HOSTS if shutil.which(name)]
        if len(detected) == 1:
            host = detected[0]
    if host not in HOSTS:
        raise ValueError("host: specify the current agent tool with --host claude, opencode or codex "
                         "(or RESEARCH_TOOLKIT_HOST). No agent tool is selected as a fallback.")
    return host


def executable_for(host, executable=None):
    value = executable or shutil.which(host + ".exe") or shutil.which(host)
    if not value:
        raise OSError(f"{host}: executable not found; use the installed agent tool or --executable PATH.")
    path = Path(value).expanduser().resolve()
    if not path.is_file():
        raise OSError(f"executable: file not found: {path}")
    if os.name == "nt" and path.suffix.lower() in {".cmd", ".bat"}:
        # Resolve common npm installations without running a shell or putting
        # prompts in command-line quoting. Other wrappers can supply the binary.
        candidates = {
            "claude": [(path.parent / "node_modules/@anthropic-ai/claude-code/cli.js")],
            "opencode": [(path.parent / "node_modules/opencode-ai/bin/opencode.exe")],
        }.get(host, [])
        for candidate in candidates:
            if candidate.is_file():
                if candidate.suffix == ".js" and shutil.which("node"):
                    return [shutil.which("node"), str(candidate)]
                if candidate.suffix == ".exe":
                    return [str(candidate)]
        raise OSError(f"{host}: {path} is a shell wrapper; pass --executable with the native executable path.")
    return [str(path)]


def native_id(host, previous):
    if not previous:
        return None
    prefix, separator, identity = previous.partition(":")
    if separator:
        if prefix != host or not identity:
            raise ValueError(f"host_task {previous!r} belongs to another agent tool; resume its owner with --host {prefix}.")
        return identity
    # v2.2.0 saved unqualified Codex IDs. Keep those tasks resumable.
    if host == "codex":
        return previous
    raise ValueError(f"host_task {previous!r} has no {host} identity; keep its original agent tool or use native handoff.")


class CodexAgentSession:
    name = "codex"
    supports_steer = True

    def __init__(self, cwd, directory, executable=None):
        from codex_session import CodexSession
        self.client = CodexSession(cwd, directory, command=executable_for(self.name, executable))

    @property
    def available(self):
        return not self.client.disconnected and not self.client.closed

    def start(self, prompt, previous=None, read_paths=None, *, workdir=None):
        session = self.client.thread(native_id(self.name, previous), cwd=workdir)
        return session, self.client.turn(session, prompt, cwd=workdir)

    def steer(self, session, turn, prompt):
        return self.client.steer(session, turn, prompt)

    def next_event(self, timeout=1):
        deadline = time.monotonic() + timeout
        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise queue.Empty
            raw = self.client.events.get(timeout=remaining)
            method, params = raw.get("method"), raw.get("params", {})
            if "id" in raw:
                try:
                    self.client.send({"id": raw["id"], "error": {"code": -32601,
                        "message": "Return the unresolved action to the coordinator; this adapter cannot approve it."}})
                except RuntimeError as exc:
                    # Process the queued terminal notifications, including any completed turns.
                    return {"kind": "request", "method": method, "raw": raw, "error": str(exc)}
                return {"kind": "request", "method": method, "raw": raw}
            if method in {"transport/error", "transport/closed"}:
                return {"kind": "error", "raw": raw}
            event = {"session": params.get("threadId"), "turn": params.get("turnId"), "raw": raw}
            if method == "item/completed" and params["item"]["type"] == "agentMessage":
                return {**event, "kind": "message", **{k: params["item"].get(k) for k in ("id", "text", "phase")}}
            if method == "turn/completed":
                return {**event, "kind": "completed", "turn": params["turn"]["id"],
                        "status": params["turn"]["status"]}

    def close(self):
        self.client.close()


def open_session(cwd, directory, host=None, executable=None):
    host = select_host(host)
    if host == "codex":
        return CodexAgentSession(cwd, directory, executable)
    from cli_agent_session import CLIAgentSession
    return CLIAgentSession(cwd, directory, host, executable_for(host, executable))
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: 472kUpdated Claude CodeCodexVerifiedInstall
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: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall