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/codex_session.py

View on GitHub
"""Small stdio client for the installed Codex agent tool; no model or account overrides."""
from __future__ import annotations

from datetime import datetime, timezone
import json
import os
from pathlib import Path
import queue
import shutil
import subprocess
import sys
import threading

from agent_session import PROCESS_EXIT_TIMEOUT, stop_native_process
from review_process import ProcessCleanupError, WindowsJob, WINDOWS_GATE


class CodexRequestError(RuntimeError):
    def __init__(self, method, error):
        super().__init__(f"{method}: {error}")
        self.method, self.error = method, error


class CodexSession:
    """Keep native threads and their original events, using the agent tool's login/config."""

    def __init__(self, cwd: Path, directory: Path, command=None):
        self.cwd = cwd.resolve()
        directory.mkdir(parents=True, exist_ok=True)
        self.events = queue.Queue()
        self.pending = {}
        self.mutex = threading.Lock()
        self.writer = threading.Lock()
        self.next_id = 0
        self.closed = False
        self.disconnected = False
        self.trace = (directory / "protocol.jsonl").open("a", encoding="utf-8")
        self.stderr = (directory / "stderr.txt").open("a", encoding="utf-8")
        self.job = None
        self.process = None
        executable = command or [shutil.which("codex.exe") or shutil.which("codex")]
        if not executable[0]:
            self.close()
            raise OSError("Codex executable not found. Use the installed agent tool's native agents, or add Codex to PATH.")
        command = executable + ["app-server", "--listen", "stdio://"]
        try:
            self.job = WindowsJob() if os.name == "nt" else None
            argv = ([sys.executable, "-c", WINDOWS_GATE, json.dumps(command)] if self.job else command)
            self.process = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                stderr=self.stderr, cwd=self.cwd, text=True, encoding="utf-8", bufsize=1,
                creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
                start_new_session=os.name != "nt")
            if self.job:
                self.job.attach(self.process.pid)
                self.process.stdin.write("1")
                self.process.stdin.flush()
            self.reader = threading.Thread(target=self._read, daemon=True)
            self.reader.start()
            self.request("initialize", {"clientInfo": {"name": "research_toolkit",
                "title": "Research Toolkit", "version": "1"}})
            self.send({"method": "initialized", "params": {}})
        except BaseException:
            self.close()
            raise

    def _record(self, direction, message):
        self.trace.write(json.dumps({"at": datetime.now(timezone.utc).isoformat(),
            "direction": direction, "message": message}, ensure_ascii=False) + "\n")
        self.trace.flush()

    def send(self, message):
        with self.writer:
            with self.mutex:
                if self.disconnected or self.closed:
                    raise RuntimeError("Codex app-server disconnected; original events retained.")
                self._record("send", message)
            try:
                self.process.stdin.write(json.dumps(message, ensure_ascii=False) + "\n")
                self.process.stdin.flush()
            except OSError as exc:
                raise RuntimeError(f"Codex app-server stopped accepting requests; see {self.trace.name}.") from exc

    def _read(self):
        try:
            for line in self.process.stdout:
                message = json.loads(line)
                with self.mutex:
                    self._record("receive", message)
                    if not isinstance(message, dict):
                        raise ValueError("Codex protocol event must be a JSON object.")
                    waiter = self.pending.get(message.get("id")) if "method" not in message else None
                if waiter is not None:
                    waiter.put(message)
                else:
                    self.events.put(message)
        except (OSError, ValueError) as exc:
            self.events.put({"method": "transport/error", "params": {"error": str(exc)}})
        finally:
            with self.mutex:
                self.disconnected = True
                for waiter in self.pending.values():
                    waiter.put({"error": {"message": "Codex app-server disconnected; original events retained."}})
            self.events.put({"method": "transport/closed", "params": {}})

    def request(self, method, params):
        with self.mutex:
            self.next_id += 1
            identity = self.next_id
            waiter = self.pending[identity] = queue.Queue()
        try:
            self.send({"id": identity, "method": method, "params": params})
            # This is a transport-response deadline, not a limit on a research turn.
            reply = waiter.get(timeout=60)
            if "error" in reply:
                raise CodexRequestError(method, reply["error"])
            return reply["result"]
        except queue.Empty as exc:
            raise RuntimeError(f"{method}: Codex did not acknowledge the request within 60 seconds; see {self.trace.name}.") from exc
        finally:
            with self.mutex:
                self.pending.pop(identity, None)

    def thread(self, previous=None, cwd=None):
        # Use the installed tool's permissions and model. The caller supplies a
        # separate working directory for each contribution/review invocation.
        params = {"cwd": str(cwd or self.cwd)}
        if previous:
            params.update(threadId=previous, excludeTurns=True)
            return self.request("thread/resume", params)["thread"]["id"]
        params.update(ephemeral=False, serviceName="research-toolkit")
        return self.request("thread/start", params)["thread"]["id"]

    def turn(self, thread, prompt, cwd=None):
        params = {"threadId": thread, "input": [{"type": "text", "text": prompt}]}
        if cwd is not None:
            # Research needs downloads and executable calculations. Keep writes
            # inside this invocation; approval/admin policy is still inherited.
            params.update(cwd=str(cwd), sandboxPolicy={"type": "workspaceWrite",
                          "writableRoots": [str(cwd)], "networkAccess": True})
        return self.request("turn/start", params)["turn"]["id"]

    def steer(self, thread, turn, prompt):
        return self.request("turn/steer", {"threadId": thread, "expectedTurnId": turn,
            "input": [{"type": "text", "text": prompt}]})

    def close(self):
        if self.closed:
            return
        self.closed = True
        try:
            if self.process:
                try:
                    self.process.stdin.close()
                    self.process.wait(timeout=PROCESS_EXIT_TIMEOUT)
                except (OSError, subprocess.TimeoutExpired):
                    # Stop the process tree below even when orderly EOF fails.
                    pass
            stop_native_process(self.process, self.job)
            if hasattr(self, "reader"):
                self.reader.join(timeout=PROCESS_EXIT_TIMEOUT)
                if self.reader.is_alive():
                    raise ProcessCleanupError(f"Codex protocol reader did not close; see {self.trace.name}.")
            if self.process:
                self.process.stdout.close()
        finally:
            self.stderr.close()
        self.trace.close()

    def __enter__(self):
        return self

    def __exit__(self, *_):
        self.close()
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