def main(prog: str = "terok") -> None:
"""Parse CLI arguments and dispatch to the appropriate command handler.
``prog`` selects which surface this invocation presents:
* ``"terok"`` — human-friendly entry point. Bare ``terok`` in an
interactive terminal execs ``terok-tui`` instead of printing the
usage error.
* ``"terokctl"`` — scriptable surface. Always parses arguments, so
no-args produces the argparse ``required subcommand`` error (stable,
predictable exit code). The command tree is identical today; the
split exists so ``terok`` can evolve richer UX while ``terokctl``
preserves backwards compatibility.
"""
# The config helpers are imported here, at dispatch time, rather than at
# module scope: they pull ``core.config`` (and thus the sandbox wheel), so
# importing them eagerly would make a bare ``import terok.cli`` pay for the
# stack. Command modules are loaded lazily too — only the invoked verb's
# module (see ``_load_own_commands``) — so ``terok <verb>`` imports one
# command module instead of all fourteen.
from terok_util import SetupDowngradeError, SetupRequiredError, configure
from terok.lib.core.config import declare_setup_invocation, set_experimental
# One-time unified logging: routes every getLogger(__name__) under terok.*
# to journald (when present) or stderr, with no per-module wiring.
configure(identifier="terok")
declare_setup_invocation()
# Fast-path: bare ``terok`` in a terminal launches the TUI. Scripts
# piping ``terok`` get the argparse usage error instead — the TTY
# check keeps the convenience shortcut from surprising automation.
# If ``terok-tui`` isn't on PATH (partial install, exotic layout), fall
# through to argparse so the user sees a usage error rather than a
# traceback from ``execlp``.
if prog == "terok" and len(sys.argv) == 1 and sys.stdin.isatty() and sys.stdout.isatty():
import os
try:
os.execlp(require_host_tool("terok-tui"), "terok-tui") # nosec B606 - resolved host tool, fixed argv
return # type: ignore[unreachable] # in tests os.execlp is mocked
except FileNotFoundError:
pass
# Fast-path: ``terok --tmux [args...]`` is a shortcut for ``terok tui
# --tmux [args...]`` — exec before any parser or subcommand registration
# work. A missing ``terok-tui`` falls through to argparse like the bare
# invocation above.
if prog == "terok" and sys.argv[1:2] == ["--tmux"]:
import os
try:
os.execlp(require_host_tool("terok-tui"), "terok-tui", *sys.argv[1:]) # nosec B606 B607 - executable resolved from host PATH; argv is fixed + user's own flags
return # type: ignore[unreachable] # in tests os.execlp is mocked
except FileNotFoundError:
pass
# Get version info for --version flag
version, branch = get_version_info()
version_string = format_version_string(version, branch)
parser = argparse.ArgumentParser(
prog=prog,
description="terok – generate/build images and run per-project task containers",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"Quick start:\n"
f" 1. Bootstrap: {prog} setup (install host services)\n"
f" 2. Auth: {prog} auth claude (host-wide auth — no project needed)\n"
f" 3. Project: {prog} project wizard (create a project)\n"
f" 4. Work: {prog} task run <project_name> (attach into a new CLI task)\n"
"\n"
f"Bare {prog} auth opens an interactive menu for multiple providers.\n"
"\n"
"Standalone agent (no project):\n"
f" {prog} executor run claude . (headless against cwd)\n"
f" {prog} executor run claude . -p 'fix' (with prompt)\n"
"\n"
f"Tip: enable tab completion with: {prog} completions install\n"
),
)
parser.add_argument(
"--version",
action="version",
version=f"{prog} {version_string}",
)
parser.add_argument(
"--experimental",
action="store_true",
default=False,
help="Enable experimental features (e.g. web tasks)",
)
parser.add_argument(
"--no-emoji",
action="store_true",
default=False,
help="Replace emojis with text labels (e.g. [gate] instead of \U0001f6aa)",
)
sub = parser.add_subparsers(dest="cmd", required=True)
# Register subcommands. Order matters — it's the order they appear in
# ``--help``. Lazy: only the invoked verb's module is imported (the whole
# point — each command module transitively pulls the executor / sandbox
# stack). The full-surface cases (bare, ``--help``, unknown verb, shell
# completion) register every own command so the listing stays complete.
argv = sys.argv[1:]
cmd_modules = _load_own_commands(argv)
for module in cmd_modules:
if module.__name__.rsplit(".", 1)[-1] == "task":
# task group + flat ``login`` shortcut; ``prog`` gates terokctl-only verbs.
module.register(sub, prog=prog)
else:
module.register(sub)
# Build the terok-side CommandTree from upstream packages, apply
# terok's cfg-injection overlay (concept translation: terok's
# SandboxConfig wins over sandbox's default), and surface every
# sibling subtree both deeply (terok executor sandbox vault X) and
# as top-level shortcuts (terok vault X) that share CommandDef
# identity with the deep path.
#
# Gated: building the tree imports the executor / sandbox / clearance
# wheels, so a terok-own verb (``config``, ``task``, …) skips it. The
# full-surface cases still build it so the command listing (and an unknown
# verb's error) include the sibling groups.
if _invocation_needs_wired_tree(argv) or _needs_full_own_surface(argv):
_build_wired_tree().wire(sub)
# TUI launcher — only on the human-facing ``terok`` binary. ``terokctl``
# is the scripting surface; launching an interactive TUI from there is
# never useful and just clutters the help listing.
if prog == "terok":
sub.add_parser("tui", help="Launch the Textual TUI")
# Enable bash completion if argcomplete is present and activated
if argcomplete is not None: # pragma: no cover - shell integration
try:
argcomplete.autocomplete(parser)
except (TypeError, AttributeError):
pass
# Fast-path: ``terok tui [args...]`` bypasses argparse and execs terok-tui.
# This avoids argparse rejecting TUI-specific flags like --tmux.
# Gated on prog="terok" so ``terokctl tui`` falls through to argparse
# (which will error — tui is not registered on the scripting surface).
if prog == "terok" and len(sys.argv) >= 2 and sys.argv[1] == "tui":
import os
os.execlp(require_host_tool("terok-tui"), "terok-tui", *sys.argv[2:]) # nosec B606 - resolved host tool, user's own flags
return # type: ignore[unreachable] # in tests os.execlp is mocked
args = parser.parse_args()
set_experimental(args.experimental)
if args.no_emoji:
from ..lib.util.emoji import set_emoji_enabled
set_emoji_enabled(False)
# Post-parse tui handler: covers ``terok --no-emoji tui ...`` where the
# fast-path (argv[1] == "tui") doesn't fire because root flags come first.
if getattr(args, "cmd", None) == "tui":
import os
os.execlp( # nosec B606 - resolved host tool, user's own flags
require_host_tool("terok-tui"), "terok-tui", *sys.argv[sys.argv.index("tui") + 1 :]
)
return # type: ignore[unreachable] # in tests os.execlp is mocked
from terok.lib.api.shield import ShieldSetupError
from terok.lib.api.vault import CredentialsConfigError, NoPassphraseError
# Dispatch chain — tried in order; first True wins. Only the modules we
# actually loaded contribute a ``dispatch`` (own verbs are disjoint, so at
# most one matches); ``_commandtree_dispatch`` handles the sibling-wired
# verbs, which set ``args._cmd`` rather than ``args.cmd``.
dispatchers = [module.dispatch for module in cmd_modules]
dispatchers.append(_commandtree_dispatch)
try:
for dispatch in dispatchers:
if dispatch(args):
return
except SetupDowngradeError as exc:
from .commands.setup import DOWNGRADE_HINT
print(f"error: {exc}\nhint: {DOWNGRADE_HINT}.", file=sys.stderr)
sys.exit(4)
except SetupRequiredError as exc:
print(f"error: {exc}\nhint: run `terok setup`.", file=sys.stderr)
sys.exit(3)
except NoPassphraseError as exc:
# sandbox#278 stripped CLI-hint text from the library raise sites so
# they stay diagnostic-only. We're the operator-facing surface, so
# the actionable hint lives here.
print(
f"error: {exc}\n"
"hint: run `terok vault unlock` to provision the vault passphrase for this session.",
file=sys.stderr,
)
sys.exit(2)
except CredentialsConfigError as exc:
# The message is complete as sandbox raises it: it names the config
# files and, for a key that was renamed, the new name. It shows no
# config value, so it is safe to print as it is.
print(f"error: {exc}", file=sys.stderr)
sys.exit(2)
except ShieldSetupError as exc:
# Same split: sandbox reports what failed and what it refused; the
# remedy — diagnose, or opt out of the firewall — is named here.
print(
f"error: {exc}\n"
"hint: run `terok sickbay` to diagnose the shield, or set "
"`shield.disable_firewall_no_protection: true` in config.yml to launch "
"without the firewall.",
file=sys.stderr,
)
sys.exit(2)
parser.error("Unknown command")