Skip to content

YujunZhou/tellonce / codex

tellonce

Verified

Use to view, explain, correct, delete or reorganize the user's saved preferences, or to record one by hand when automatic recording is off; learning and rule injection otherwise run automatically through Codex hooks.

FileKindSize
.codex-plugin/plugin.jsonconfig1.3 KB
SKILL.mdskill md12.0 KB
dashboard.shexecutablescript348 B
docs/CC_PARITY_MATRIX.mdmarkdown7.3 KB
docs/README.mdmarkdown3.4 KB
doctor.shexecutablescript345 B
hooks/hooks.jsonconfig714 B
hooks/posttooluse-deterministic-block.shexecutablescript2.0 KB
hooks/sessionstart-init.shexecutablescript1.9 KB
hooks/userpromptsubmit-dispatch.pyscript2.6 KB
hooks/userpromptsubmit-memory-upsert.shscript326 B
hooks/userpromptsubmit-pending-inject.shexecutablescript2.0 KB
hooks/userpromptsubmit-retrieve-inject.shexecutablescript3.1 KB
hooks/userpromptsubmit-shadow-alert-inject.shexecutablescript1.2 KB
install.shexecutablescript13.9 KB
shared_lib/_install_merge_settings.pyscript12.1 KB
shared_lib/_pt_hooks.txtmarkdown407 B
shared_lib/correction_interpretation.pyscript8.5 KB
shared_lib/detect_user_prefer.pyscript7.2 KB
shared_lib/deterministic_block.pyscript9.3 KB
shared_lib/event_obligations.pyscript19.8 KB
shared_lib/execution_support.pyscript75.8 KB
shared_lib/fingerprints.yamlconfig1.1 KB
shared_lib/learning_policy.pyscript4.6 KB
shared_lib/memory_judge.pyscript84.8 KB
shared_lib/memory_publication.pyscript14.9 KB
shared_lib/memory_runtime.pyscript12.2 KB
shared_lib/memory_store.pyscript99.6 KB
shared_lib/memory_upsert.pyscript57.1 KB
shared_lib/memory_upsert_hook.pyscript4.6 KB
shared_lib/model_requests.pyscript5.8 KB
shared_lib/path_config.pyscript13.3 KB
shared_lib/pending_queue_manager.pyscript23.4 KB
shared_lib/pt_platform.pyscript1.5 KB
shared_lib/redaction.pyscript3.4 KB
shared_lib/retrieve_inject.pyexecutablescript57.9 KB
shared_lib/rule_selection.pyscript18.9 KB
shared_lib/shadow_alert_inject.pyscript6.1 KB
shared_lib/training_memory.pyscript17.8 KB
shared_lib/transcript_adapter.pyscript13.7 KB
shared_lib/verify_compliance.pyexecutablescript24.5 KB
shared_lib/verify_retry_shadow.pyscript27.4 KB
tellonce_codex/__init__.pyscript52 B
tellonce_codex/__main__.pyscript49 B
tellonce_codex/cli.pyscript6.8 KB
tellonce_codex/codex_posttooluse_block.pyscript11.2 KB
tellonce_codex/dashboard.pyscript3.4 KB
tellonce_codex/doctor.pyscript10.9 KB
tellonce_codex/index.pyscript1.8 KB
tellonce_codex/install.pyscript3.1 KB
tellonce_codex/install_codex_hooks.pyscript15.1 KB
tellonce_codex/ledger.pyscript17.1 KB
tellonce_codex/memory.pyscript5.3 KB
tellonce_codex/migrate.pyscript1.3 KB
tellonce_codex/mode.pyscript2.3 KB
tellonce_codex/paths.pyscript8.6 KB
tellonce_codex/promote.pyscript4.4 KB
tellonce_codex/scan.pyscript2.6 KB
tellonce_codex/uninstall.pyscript1.7 KB
tellonce_codex/verify.pyscript5.3 KB
tellonce_codex/wrapper.pyscript12.0 KB
uninstall.shexecutablescript4.6 KB

shared_lib/detect_user_prefer.py

View on GitHub
#!/usr/bin/env python3
"""Optional, experimental heuristic: classify the user's last message as
urgent ('u') or clarity ('c') preferring. OFF by default (PT_PREFER_BACKEND=off).

When enabled, deterministic_block's hook short-circuit can skip the regex
word-check only when the user prefers an urgent response. Defaults to urgent
('u') on any failure (cheaper degradation).

CLI: python3 detect_user_prefer.py <transcript_path>
Stdout: single char 'u' or 'c'.

Default is now NO-API. The previous behaviour
silently called Anthropic SDK on every Stop where last obs entry had
detected=false (the base-rate path), charging the user's API key without
any visible signal. Reviewed env contract:

  PT_PREFER_BACKEND=off (default)   → return 'u' immediately, no API call,
                                      no token spend. Behaviour: short-circuit
                                      gate is fully open on detected=false,
                                      identical to prior behaviour ON FAILURE.
  PT_PREFER_BACKEND=sdk             → Anthropic Python SDK (legacy path).
                                      Charges per call; user opts in.
  PT_PREFER_BACKEND=cli             → Use the platform CLI in print mode (subscription
                                      mode, 0 metered cost).

This means the deterministic_block short-circuit still works (urgent = skip)
but no longer silently bills users. To re-enable adaptive classification
explicitly: `export PT_PREFER_BACKEND=cli` (subscription) or `=sdk` (API).
"""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pt_platform  # platform-specific values (this variant)


_BACKEND = os.environ.get('PT_PREFER_BACKEND', 'off').strip().lower()
_PREFER_MODEL = os.environ.get('PT_PREFER_MODEL', 'claude-haiku-4-5')


def _read_last_user_msg(transcript_path: str, max_chars: int = 200) -> str:
    """Tail transcript for the latest user message text. Returns truncated."""
    try:
        with open(transcript_path, errors='ignore') as f:
            lines = list(f)
    except Exception:
        return ''
    for line in reversed(lines):
        try:
            o = json.loads(line)
        except Exception:
            continue
        if o.get('type') != 'user':
            continue
        content = o.get('message', {}).get('content', '')
        text = ''
        if isinstance(content, str):
            text = content
        elif isinstance(content, list):
            for c in content:
                if isinstance(c, dict) and c.get('type') == 'text':
                    text = c.get('text', '')
                    break
        # Skip empty + system reminders + tool result wrappers
        if not text or text.startswith('<system-reminder>') or text.startswith('<task-notification>'):
            continue
        return text[:max_chars]
    return ''


_CLASSIFY_PROMPT = (
    "User's last message:\n{user_msg}\n\n"
    "Does the user prefer URGENT (fast, terse, action-oriented) "
    "or CLARITY (detailed, explained, careful) response right now? "
    "Reply ONE letter only: u or c."
)


def _classify_via_sdk(user_msg: str) -> str:
    """Anthropic Python SDK call (charges API credit). Opt-in via
    PT_PREFER_BACKEND=sdk."""
    try:
        import anthropic
    except ImportError:
        return 'u'
    try:
        client = anthropic.Anthropic()
    except Exception:
        return 'u'
    try:
        resp = client.messages.create(
            model=_PREFER_MODEL,
            max_tokens=2,
            messages=[{"role": "user", "content": _CLASSIFY_PROMPT.format(user_msg=user_msg)}],
        )
        out = resp.content[0].text.strip().lower()
        return 'c' if out.startswith('c') else 'u'
    except Exception:
        return 'u'


def _classify_via_cli(user_msg: str) -> str:
    """Platform CLI (-p) subprocess (subscription mode, 0 metered cost). Opt-in via
    PT_PREFER_BACKEND=cli. Falls back to 'u' on any error."""
    output_path = None
    try:
        prompt = _CLASSIFY_PROMPT.format(user_msg=user_msg)
        cli = pt_platform.CLI_COMMAND
        _cli_model = os.environ.get('PT_PREFER_MODEL', pt_platform.PREFER_MODEL_DEFAULT).strip()
        prompt_input = None
        if cli == 'codex':
            output_fd, output_path = tempfile.mkstemp(
                prefix='tellonce-prefer-',
                suffix='.txt',
            )
            os.close(output_fd)
            _cmd = [
                'codex', 'exec', '--ephemeral', '--ignore-user-config',
                '--ignore-rules', '--skip-git-repo-check',
                '--sandbox', 'read-only',
                '--output-last-message', output_path,
            ]
            if _cli_model:
                _cmd += ['-m', _cli_model]
            prompt_input = prompt
        elif cli == 'claude':
            _cmd = ['claude', '-p']
            if _cli_model:
                _cmd += ['--model', _cli_model]
            _cmd += ['--output-format', 'text', '--setting-sources', 'project']
            prompt_input = prompt
        else:
            _cmd = [cli, '-p', prompt]
            if _cli_model:
                _cmd += ['--model', _cli_model]
            _cmd += ['--output-format', 'text']
        child_env = dict(os.environ)
        child_env["PT_CHILD_SESSION"] = "1"
        child_env["B5_RETRIEVE_RECURSION_GUARD"] = "1"
        child_env["B5_DETERMINISTIC_DISABLED"] = "1"
        child_env["B5_SHADOW_DISABLED"] = "1"
        child_env["B5_INJECT_DISABLED"] = "1"
        proc = subprocess.run(
            _cmd,
            input=prompt_input,
            capture_output=True, text=True, encoding='utf-8', timeout=15,
            env=child_env,
            cwd=tempfile.gettempdir(),
        )
    except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
        if output_path:
            try:
                os.unlink(output_path)
            except OSError:
                pass
        return 'u'
    except Exception:
        if output_path:
            try:
                os.unlink(output_path)
            except OSError:
                pass
        return 'u'
    try:
        if proc.returncode != 0:
            return 'u'
        if output_path and os.path.isfile(output_path):
            out = Path(output_path).read_text(encoding='utf-8', errors='replace')
        else:
            out = proc.stdout or ''
        return 'c' if out.strip().lower().startswith('c') else 'u'
    finally:
        if output_path:
            try:
                os.unlink(output_path)
            except OSError:
                pass


def classify(user_msg: str) -> str:
    """Return 'u' (urgent) or 'c' (clarity). Default 'u' on any error or when
    PT_PREFER_BACKEND is unset / off (no API call, no subscription cost)."""
    if not user_msg.strip():
        return 'u'
    backend = _BACKEND
    if backend == 'sdk':
        return _classify_via_sdk(user_msg)
    if backend == 'cli':
        return _classify_via_cli(user_msg)
    # backend == 'off' or unrecognized → no remote call, default to urgent
    return 'u'


def main() -> int:
    if len(sys.argv) < 2:
        print('u')
        return 0
    transcript = sys.argv[1]
    user_msg = _read_last_user_msg(transcript)
    print(classify(user_msg))
    return 0


if __name__ == '__main__':
    sys.exit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 323kUpdated Claude CodeCodexVerifiedInstall