api
api
¶
Public library API — the one stable import boundary for presentation layers.
The CLI and TUI import everything domain-, type-, or config-related from
this package rather than reaching into terok.lib.* internals — that
keeps the consumer surface narrow and lets internals refactor freely.
The package is split into focused sub-modules (catalogs of re-exports from the appropriate adapter):
vault— vault status, daemon lifecycle,VaultManagergate— gate-server lifecycle and statusshield— shield wrappers and the shield CLI registryagents— providers, ACP, image build, instructionsclearance—Notificationand the clearance CLI registrysetup— first-run setup, env check, sickbay primitives, uninstalltask— task lifecycle, runners, metadata, display tablesproject— project entities, lifecycle, panic, SSH
This module owns the cross-cutting bits: the
Config snapshot, the runtime peek
get_container_state, a small
number of shared sandbox types (SandboxConfig and the CLI
CommandDef /
CommandTree), and the ANSI helpers
bold/red/yellow/stage_line.
For backward compatibility every sub-module's exports are also bound on
this package (so existing from terok.lib.api import foo lines keep
working) — see __all__ at the bottom.
Pure utilities (util.emoji, util.yaml, util.ansi,
util.net, ui_utils.terminal) and core.version stay
importable directly — they are genuinely cross-cutting and have no
domain coupling worth funnelling.
AGENTS_QUESTION = Question(key='agents', kind='multichoice', prompt='Select agents to install', help="Which AI coding agents to bake into this project's image, overriding the global default. Pick 'All agents' to inherit future additions, or enumerate specific agents to freeze the set.", required=True, choices_loader=_load_agent_choices, validate=_validate_agents)
module-attribute
¶
QUESTIONS = (Question(key='security_class', kind='choice', prompt='Select security mode', choices=(tuple(SECURITY_CLASSES)), required=True), Question(key='base', kind='choice', prompt='Select base image', choices=(tuple(BASES)), required=True), Question(key='project_id', kind='text', prompt='Project ID', required=True, transform=_slugify_project_id, validate=_validate_project_id, placeholder='lowercase; letters, digits, hyphens, underscores'), Question(key='upstream_url', kind='text', prompt='Upstream git URL', help='Leave empty for a local-only project (no remote).', placeholder='git@github.com:org/repo.git or https://…', default_visible=True), Question(key='default_branch', kind='text', prompt='Default branch', help="Leave empty to use the remote's default (or ``main`` when no remote).", placeholder='main', default_visible=True), Question(key='user_snippet', kind='editor', prompt='Custom image snippet', help='Optional Dockerfile fragment appended to the project image. Use for extra packages, env vars, or setup commands.', default_visible=True))
module-attribute
¶
CONTAINER_MODES = ('cli', 'web', 'run', 'toad')
module-attribute
¶
All valid container mode suffixes used in container naming.
GPU_DISPLAY = {True: ProjectBadge(emoji='🎮', label='GPU'), False: ProjectBadge(emoji='💿', label='CPU')}
module-attribute
¶
SECURITY_CLASS_DISPLAY = {'gatekeeping': ProjectBadge(emoji='🚪', label='gate'), 'online': ProjectBadge(emoji='🌐', label='online')}
module-attribute
¶
STATUS_DISPLAY = {'running': StatusInfo(label='running', emoji='🟢', color='green'), 'init': StatusInfo(label='init', emoji='🟡', color='yellow'), 'starting': StatusInfo(label='starting', emoji='⏳', color='yellow'), 'stopped': StatusInfo(label='stopped', emoji='🔴', color='red'), 'completed': StatusInfo(label='completed', emoji='✅', color='green'), 'failed': StatusInfo(label='failed', emoji='❌', color='red'), 'created': StatusInfo(label='created', emoji='🆕', color='yellow'), 'not found': StatusInfo(label='not found', emoji='❓', color='yellow'), 'deleting': StatusInfo(label='deleting', emoji='🧹', color='yellow')}
module-attribute
¶
__all__ = ['Config', 'get_config', 'make_sandbox_config', 'set_experimental', 'get_container_state', 'SandboxConfig', 'CommandDef', 'CommandTree', 'bold', 'red', 'yellow', 'stage_line', 'ACPEndpointStatus', 'AGENT_PROVIDERS', 'AUTH_PROVIDERS', 'AgentRunner', 'BuildError', 'DEFAULT_BASE_IMAGE', 'AgentRoster', 'Authenticator', 'EXECUTOR_COMMANDS', 'ExecutorConfigView', 'ImageBuilder', 'KrunHost', 'PROVIDER_NAMES', 'SharedMountStorageInfo', 'TaskStorageInfo', 'acp_socket_is_live', 'authenticate', 'build_images', 'bundled_default_instructions', 'ensure_sandbox_ready', 'generate_dockerfiles', 'get_provider', 'installed_agents', 'installed_agents_for_project', 'parse_md_agent', 'resolve_agent_config', 'resolve_instructions', 'CLEARANCE_COMMANDS', 'CLEARANCE_HUB_UNIT_NAME', 'CLEARANCE_NOTIFIER_UNIT_NAME', 'CallbackNotifier', 'EventSubscriber', 'Notification', 'HubService', 'NotifierService', 'check_clearance_units_outdated', 'clearance_outdated_summary', 'read_installed_notifier_unit_version', 'read_installed_unit_version', 'GateAuthNotConfigured', 'GateServerManager', 'GateServerStatus', 'GateStalenessInfo', 'make_git_gate', 'AGENTS_QUESTION', 'BrokenProject', 'DeleteProjectResult', 'Project', 'ProjectConfig', 'QUESTIONS', 'Question', 'cleanup_images', 'delete_project', 'derive_project', 'discover_projects', 'execute_panic', 'find_orphaned_images', 'find_projects_sharing_gate', 'format_panic_report', 'get_project', 'list_images', 'list_projects', 'load_project', 'panic_stop_containers', 'project_image_exists', 'remove_images', 'render_project_yaml', 'require_project_exists', 'set_project_image_agents', 'summarize_ssh_init', 'validate_answer', 'write_project_yaml', 'EnvironmentCheck', 'SERVICES_TCP_OPTOUT_YAML', 'SelinuxStatus', 'SetupVerdict', 'check_environment', 'check_selinux_status', 'is_ssh_url', 'namespace_state_dir', 'needs_setup', 'public_line_of', 'resolve_container_state_dir', 'sandbox_uninstall', 'selinux_install_command', 'selinux_install_script', 'systemd_creds_has_tpm2', 'yaml_update_section', 'ArgDef', 'ExecError', 'RecoveryStatus', 'SHIELD_COMMANDS', 'ShieldCommandDef', 'ShieldHooks', 'ShieldManager', 'installed_versions', 'read_stamp', 'stamp_path', 'CONTAINER_MODES', 'GPU_DISPLAY', 'HeadlessRunRequest', 'LogViewOptions', 'ModeInfo', 'SECURITY_CLASS_DISPLAY', 'STATUS_DISPLAY', 'StatusInfo', 'Task', 'TaskDeleteResult', 'TaskMeta', 'agent_config_dir', 'container_name', 'effective_status', 'generate_task_name', 'get_all_task_states', 'get_login_command', 'get_task_meta', 'get_tasks', 'get_workspace_git_diff', 'has_gpu', 'mark_task_deleting', 'mode_info', 'sanitize_task_name', 'task_archive_list', 'task_archive_logs', 'task_delete', 'task_followup_headless', 'task_list', 'task_login', 'task_logs', 'task_new', 'task_rename', 'task_restart', 'task_run_cli', 'task_run_headless', 'task_run_toad', 'task_status', 'task_stop', 'validate_task_name', 'wait_for_container_exit', 'NoPassphraseError', 'VaultManager', 'VaultStatus', 'WrongPassphraseError', 'handle_vault_seal', 'handle_vault_to_keyring', 'vault_db']
module-attribute
¶
BrokenProject(id, config_path, error)
dataclass
¶
A project directory whose project.yml failed to load.
Carries just enough context for the TUI to render a row and show the
validation error in the details pane, without forcing callers to
re-run the failing load_project to rediscover the message.
DeleteProjectResult
¶
Project(config)
¶
Rich project object — DDD Aggregate Root.
The primary domain object that callers interact with. Wraps a
ProjectConfig value object and exposes all project-scoped
operations through a natural OOP interface::
project = get_project("myproj")
task = project.create_task(name="fix-bug")
task.run_cli()
task.stop()
project.gate.sync()
Identity is based on project.id — two Project instances with
the same ID compare equal and hash identically, so they work correctly
in sets and dicts.
Subsystem access (gate, ssh, agents) uses lazy
initialization: the service objects are created on first property access
rather than at construction time. This avoids unnecessary I/O when only
a subset of functionality is needed. Uses __slots__ for memory
efficiency; cached_property is not available because it requires
__dict__.
Obtain via get_project or
list_projects.
Initialize with a resolved project configuration.
Source code in src/terok/lib/domain/project.py
__slots__ = ('_config', '_gate', '_ssh', '_agents')
class-attribute
instance-attribute
¶
id
property
¶
Return the project ID.
config
property
¶
Return the underlying configuration value object.
security_class
property
¶
Return the project's security class ('online' or 'gatekeeping').
tasks
property
¶
All tasks in this project — convenience for unfiltered iteration.
gate
property
¶
Return the project-scoped git gate manager (lazy-initialized).
ssh
property
¶
Return the project-scoped SSH manager (lazy-initialized).
needs_ssh_key_registration
property
¶
Return True when the upstream is SSH-scheme so a deploy key must be added.
Shared predicate used by the CLI pause helper and the TUI wizard's mid-flow "continue" gate — keeps the rule (SSH URLs need registration, HTTPS and no-upstream projects don't) in one place.
agents
property
¶
Return the project-scoped agent configuration manager (lazy-initialized).
__eq__(other)
¶
__hash__()
¶
create_task(*, name=None)
¶
Create a new task and return a rich Task entity.
Source code in src/terok/lib/domain/project.py
get_task(task_id)
¶
list_tasks(*, status=None, mode=None)
¶
Return all tasks, optionally filtered by status or mode.
Source code in src/terok/lib/domain/project.py
acp_endpoints()
¶
Return one ACPEndpoint per running task.
Cheap discovery surface — walks running tasks, classifies each
endpoint as active (daemon up, socket bound), ready
(task running with at least one authed agent, daemon would
spawn on first connect), or unsupported (no agents authed
for this task's image; connect would fail).
No probing, no socket traffic — one credential-DB read for
the whole listing, one Sandbox instance shared across
tasks, and image-label lookups memoised by image-id (most
tasks share an image). terok acp list and the TUI panel
share this entry point.
Source code in src/terok/lib/domain/project.py
run_headless(request)
¶
Create and run a headless task atomically. Returns the Task.
Source code in src/terok/lib/domain/project.py
followup_headless(task_id, prompt, follow=True)
¶
Send a follow-up prompt to a completed headless task.
Source code in src/terok/lib/domain/project.py
delete()
¶
generate_dockerfiles()
¶
build_images(*, include_dev=False, refresh_agents=False, full=False)
¶
Build container images for this project.
Source code in src/terok/lib/domain/project.py
state(*, gate_commit_provider=None)
¶
Return the project's infrastructure state snapshot.
gate_commit_provider is an optional callable that, given a
project id, returns the last gate commit dict (or None).
Used by the TUI to inject the live gate manager's last_commit
lookup without reaching for it from inside the helper.
Source code in src/terok/lib/domain/project.py
storage_detail()
¶
Return a detailed view of this project's on-disk footprint.
provision_ssh_key(*, key_type='ed25519', comment=None, force=False)
¶
Mint a vault-backed keypair and bind it to this project's scope.
Opens a fresh
SSHManager via the context-manager
form so the credential DB closes after init, then assigns the
new key_id to the project scope. Rendering the result is
the caller's job — see
summarize_ssh_init.
Source code in src/terok/lib/domain/project.py
register_ssh_key(key_id)
¶
Bind an already-minted key_id to this project (idempotent).
pause_for_ssh_key_registration_if_needed()
¶
Pause so the user can register the deploy key — only for SSH upstreams.
Source code in src/terok/lib/domain/project.py
list_presets()
¶
ProjectConfig
¶
Bases: BaseModel
Resolved project configuration loaded from project.yml.
Pure value object — holds configuration fields with no behavior beyond
computed paths. The rich domain object Project
wraps this and provides behavior.
model_config = ConfigDict(frozen=True)
class-attribute
instance-attribute
¶
id
instance-attribute
¶
security_class
instance-attribute
¶
isolation = 'shared'
class-attribute
instance-attribute
¶
upstream_url
instance-attribute
¶
default_branch
instance-attribute
¶
root
instance-attribute
¶
tasks_root
instance-attribute
¶
gate_path
instance-attribute
¶
gate_enabled = True
class-attribute
instance-attribute
¶
staging_root
instance-attribute
¶
ssh_use_personal = False
class-attribute
instance-attribute
¶
Opt in to the user's ~/.ssh keys for host-side gate-sync (default off).
expose_external_remote = False
class-attribute
instance-attribute
¶
human_name = None
class-attribute
instance-attribute
¶
human_email = None
class-attribute
instance-attribute
¶
git_authorship = 'agent-human'
class-attribute
instance-attribute
¶
upstream_polling_enabled = True
class-attribute
instance-attribute
¶
upstream_polling_interval_minutes = 5
class-attribute
instance-attribute
¶
auto_sync_enabled = False
class-attribute
instance-attribute
¶
auto_sync_branches = Field(default_factory=list)
class-attribute
instance-attribute
¶
default_agent = None
class-attribute
instance-attribute
¶
default_login = None
class-attribute
instance-attribute
¶
agent_config = Field(default_factory=dict)
class-attribute
instance-attribute
¶
shutdown_timeout = 10
class-attribute
instance-attribute
¶
memory = None
class-attribute
instance-attribute
¶
Podman --memory value from run.memory in project.yml.
cpus = None
class-attribute
instance-attribute
¶
Podman --cpus value from run.cpus in project.yml.
nested_containers = False
class-attribute
instance-attribute
¶
Project runs podman/docker inside its container (see run.nested_containers).
runtime = None
class-attribute
instance-attribute
¶
OCI runtime selector from run.runtime.
None (default) means "use the global default", which itself
falls through to "crun" — the OCI runtime podman drives by
default on every supported distro. "krun" selects KVM-microVM
isolation; gated on the global experimental: true flag at
runtime selection time so a typo never silently boots the
experimental backend.
Sizing reuses the standard memory / cpus knobs — podman
writes them into the OCI spec and the runtime reads them there;
no krun-specific knob.
timezone = None
class-attribute
instance-attribute
¶
IANA timezone for task containers (from run.timezone).
None lets terok-executor fall back to the host's timezone; pass an
explicit string ("UTC", "Europe/Prague") to override — including
to pin containers to UTC for reproducible runs.
task_name_categories = None
class-attribute
instance-attribute
¶
shield_drop_on_task_run = True
class-attribute
instance-attribute
¶
shield_on_task_restart = 'retain'
class-attribute
instance-attribute
¶
hook_pre_start = None
class-attribute
instance-attribute
¶
hook_post_start = None
class-attribute
instance-attribute
¶
hook_post_ready = None
class-attribute
instance-attribute
¶
hook_post_stop = None
class-attribute
instance-attribute
¶
base_image = 'ubuntu:24.04'
class-attribute
instance-attribute
¶
family = None
class-attribute
instance-attribute
¶
Package family override for L0/L1 builds.
None lets terok-executor auto-detect from base_image; set
explicitly when the auto-detect allowlist doesn't recognise the
image (rocky, alma, suse, …).
agents = 'all'
class-attribute
instance-attribute
¶
Comma-separated roster entries to install in L1 (or "all").
snippet_inline = None
class-attribute
instance-attribute
¶
snippet_file = None
class-attribute
instance-attribute
¶
shared_dir = None
class-attribute
instance-attribute
¶
is_sealed
property
¶
Whether this project uses sealed isolation (zero bind mounts).
presets_dir
property
¶
Directory for preset config files for this project.
Question(key, kind, prompt, help='', choices=(), choices_loader=None, required=False, transform=None, validate=None, placeholder='', default_visible=False)
dataclass
¶
One wizard prompt — what to ask, how to validate, what shape the answer takes.
The presenter decides the visual treatment (numbered menu vs radio
buttons, input() vs Textual Input, $EDITOR vs TextArea);
the declaration here drives everything else.
key
instance-attribute
¶
Name of this field in the collected-values dict.
kind
instance-attribute
¶
Shape of the input — drives which widget / prompt style a presenter uses.
prompt
instance-attribute
¶
Short one-line question, used as both CLI prompt and TUI label.
help = ''
class-attribute
instance-attribute
¶
Longer explanation, rendered next to the input in the TUI; unused in CLI.
choices = ()
class-attribute
instance-attribute
¶
Static (value, label) pairs for kind in {"choice", "multichoice"}.
choices_loader = None
class-attribute
instance-attribute
¶
Runtime resolver for choices that aren't known at import time.
Set this when the option set lives in a sibling wheel (e.g. the
agent roster) and can drift between releases. When set, takes
precedence over choices.
required = False
class-attribute
instance-attribute
¶
Reject empty answers with "<prompt> is required."
transform = None
class-attribute
instance-attribute
¶
Optional normalisation applied before validation (e.g. str.lower).
validate = None
class-attribute
instance-attribute
¶
Optional validator returning an error string or None when accepted.
placeholder = ''
class-attribute
instance-attribute
¶
Hint string, rendered inside the Textual Input; unused in CLI.
default_visible = False
class-attribute
instance-attribute
¶
When True, CLI prompt shows "(optional)" to telegraph "Enter is fine".
resolve_choices()
¶
Return the effective option list — runtime loader wins over static.
Called by both presenters whenever they need to render or validate
a choice / multichoice question. The loader is expected
to be cheap; the executor's roster lookup is itself lru_cache'd
so repeated calls are free.
Source code in src/terok/lib/domain/wizards/new_project.py
HeadlessRunRequest(project_id, prompt, config_path=None, model=None, max_turns=None, timeout=None, follow=True, agents=None, preset=None, name=None, provider=None, instructions=None, unrestricted=None)
dataclass
¶
Groups all parameters for a headless (autopilot) agent run.
project_id
instance-attribute
¶
prompt
instance-attribute
¶
config_path = None
class-attribute
instance-attribute
¶
model = None
class-attribute
instance-attribute
¶
max_turns = None
class-attribute
instance-attribute
¶
timeout = None
class-attribute
instance-attribute
¶
follow = True
class-attribute
instance-attribute
¶
agents = None
class-attribute
instance-attribute
¶
preset = None
class-attribute
instance-attribute
¶
name = None
class-attribute
instance-attribute
¶
provider = None
class-attribute
instance-attribute
¶
instructions = None
class-attribute
instance-attribute
¶
unrestricted = None
class-attribute
instance-attribute
¶
LogViewOptions(follow=False, raw=False, tail=None, streaming=True)
dataclass
¶
Display options for task log viewing.
follow = False
class-attribute
instance-attribute
¶
Follow live output (-f).
raw = False
class-attribute
instance-attribute
¶
Bypass formatting, show raw podman output.
tail = None
class-attribute
instance-attribute
¶
Show only the last N lines.
streaming = True
class-attribute
instance-attribute
¶
Enable partial streaming (typewriter effect) for supported formatters.
ModeInfo(emoji, label)
dataclass
¶
StatusInfo(label, emoji, color)
dataclass
¶
Task(config, meta)
¶
Rich task entity — DDD Entity with identity and lifecycle behavior.
Each task has a unique identity within its project, defined by the tuple
(project_id, task_id). Two Task instances are equal iff they
share this identity, regardless of metadata differences.
Obtained via get_task,
create_task, or
list_tasks. Delegates lifecycle
operations to the underlying task service functions in
tasks and
task_runners.
Initialize with project config and task metadata snapshot.
Source code in src/terok/lib/domain/task.py
__slots__ = ('_config', '_meta')
class-attribute
instance-attribute
¶
id
property
¶
Return the task's ID.
name
property
¶
Return the task's human-readable name.
mode
property
¶
Return the task's mode ('cli', 'run', 'toad') or None.
status
property
¶
Return the effective status computed from container state + metadata.
container_state
property
¶
Live container state — running / exited / … or None.
Hydrated when the task is loaded; reflects what podman
inspect reported at construction time. Refresh by reloading
the parent Project view.
meta
property
¶
Return the underlying metadata value object.
__eq__(other)
¶
Two tasks are equal iff they belong to the same project and share the same ID.
__hash__()
¶
run_cli(*, agents=None, preset=None)
¶
stop(*, timeout=None)
¶
restart()
¶
delete()
¶
rename(new_name)
¶
followup(prompt, follow=True)
¶
Send a follow-up prompt to a completed headless task.
logs(options=None)
¶
login()
¶
get_login_command()
¶
get_workspace_diff(against='HEAD')
¶
show_status()
¶
Print live task status with container state diagnostics.
CLI-flavoured: writes to stdout. Domain callers that want a
structured snapshot should read :attr:meta directly.
Source code in src/terok/lib/domain/task.py
wait_for_exit(*, timeout=7200)
¶
Wait for this task's container to exit; record exit code in metadata.
Returns (exit_code, error_message). See
wait_for_container_exit
for the underlying timeout semantics.
Source code in src/terok/lib/domain/task.py
capture_logs()
¶
Capture this task's container logs to disk; return the log path.
Returns None if the task has no mode (never started) or the
executor reports a capture failure.
Source code in src/terok/lib/domain/task.py
image_is_old()
¶
Return whether the task's container image is outdated.
Compares the running container's image build-context hash against
the project's current expected hash. Returns None when the
comparison is indeterminate (image deleted, container not
running, or mode is not cli) so callers can distinguish
"definitely current" from "can't tell".
Source code in src/terok/lib/domain/task.py
doctor(*, fix=False, reporter=None, label_prefix='')
¶
Run every layered in-container health check against this task.
Convenience wrapper around
ContainerDoctor.run
— see that method for the full streaming / fix / label-prefix
semantics.
Source code in src/terok/lib/domain/task.py
TaskDeleteResult(task_id, warnings)
dataclass
¶
Outcome of a task deletion — always completes, collects warnings.
The task is considered deleted regardless (metadata and workspace
removed), but individual cleanup steps may fail. warnings
carries human-readable descriptions of any steps that did not
complete cleanly.
TaskMeta(container_state=None, exit_code=None, deleting=False, initialized=False, starting=False, *, task_id, project_id='', mode, workspace, web_port, web_token=None, backend=None, preset=None, name='', provider=None, unrestricted=None, work_status=None, work_message=None, shield_state=None, created_at=None)
dataclass
¶
Bases: TaskState
Lightweight metadata snapshot for a single task.
Inherits lifecycle fields (container_state, exit_code,
deleting, initialized) from TaskState.
task_id
instance-attribute
¶
project_id = ''
class-attribute
instance-attribute
¶
Project the task belongs to.
Carried in the meta JSON so consumers that don't already know the
project (e.g. terok-shield's host-side dossier resolver, which only
has the meta-path pointer) can render full project/task identity
without re-deriving it from the on-disk path. Empty string for
pre-this-release meta files; the lifecycle backfills it on the
next mutation.
mode
instance-attribute
¶
workspace
instance-attribute
¶
web_port
instance-attribute
¶
web_token = None
class-attribute
instance-attribute
¶
backend = None
class-attribute
instance-attribute
¶
preset = None
class-attribute
instance-attribute
¶
name = ''
class-attribute
instance-attribute
¶
provider = None
class-attribute
instance-attribute
¶
unrestricted = None
class-attribute
instance-attribute
¶
work_status = None
class-attribute
instance-attribute
¶
work_message = None
class-attribute
instance-attribute
¶
shield_state = None
class-attribute
instance-attribute
¶
created_at = None
class-attribute
instance-attribute
¶
status
property
¶
Compute effective status from live container state + metadata.
load(project_id, task_id)
classmethod
¶
Load a TaskMeta from disk, with live container state hydrated.
Raises SystemExit if the task metadata file is not found.
Equivalent to the free-fn
get_task_meta,
kept as the canonical entry point so callers reach the class
through its own factory.
Source code in src/terok/lib/orchestration/tasks/query.py
Config(config_root, core_state_dir, runtime_dir, archive_dir, vault_dir, user_projects_dir, global_config_path, public_host, shield_bypass_firewall_no_protection, tui_default_tmux, tui_external_editor, shield_security_hint)
dataclass
¶
Snapshot of the global config values consumers read at startup.
Bundles the paths, feature flags, and presentation hints that the TUI
(and CLI) previously pulled from a dozen scattered getters in
terok.lib.core.config and
terok.lib.core.paths. Capture once with
get_config; pass the result around.
Side-effecting helpers — set_experimental, make_sandbox_config —
stay as functions on the api module; they don't
belong on a frozen value object.
config_root
instance-attribute
¶
core_state_dir
instance-attribute
¶
runtime_dir
instance-attribute
¶
archive_dir
instance-attribute
¶
vault_dir
instance-attribute
¶
user_projects_dir
instance-attribute
¶
global_config_path
instance-attribute
¶
public_host
instance-attribute
¶
shield_bypass_firewall_no_protection
instance-attribute
¶
tui_default_tmux
instance-attribute
¶
tui_external_editor
instance-attribute
¶
shield_security_hint
instance-attribute
¶
authenticate(provider, project_id=None)
¶
Run the auth flow for provider, host-wide by default.
When project_id is given, the project's L2 CLI image is reused — the escape hatch for users who want project-scoped credentials or happen to have a project image handy. When omitted, terok resolves an L1 image (shared across projects that build on the same base) and offers to build one if none exists — the "fresh install, no project yet" path.
Image resolution is deferred: the executor only invokes the resolver after the user has chosen the OAuth path from the OAuth-vs-API-key prompt, so picking API key never triggers an L1 build. Vault storage is provider-scoped in both modes, so switching from a per-project auth to a host-wide one later (or vice versa) does not duplicate or overwrite credentials.
Source code in src/terok/lib/domain/auth.py
build_images(project_id, include_dev=False, refresh_agents=False, full_rebuild=False, agents=None)
¶
Shim around ProjectImage.build.
Source code in src/terok/lib/orchestration/image.py
generate_dockerfiles(project_id, *, family=None)
¶
Shim around ProjectImage.generate_dockerfiles.
Source code in src/terok/lib/orchestration/image.py
installed_agents(image_tag)
cached
¶
Return the set of agent names baked into image_tag.
Reads the ai.terok.agents OCI label written by terok-executor's L1
build (a sorted comma-separated list). Result is cached per image
tag, since the label is fixed for the life of an image.
When the image is not present locally, or the label is missing (e.g. a legacy image built before selectable agents), returns an empty set — callers treat empty as "unknown / unrestricted" so older images keep working.
Source code in src/terok/lib/core/images.py
installed_agents_for_project(project)
¶
Return the agents installed in project's L1 image.
Convenience over installed_agents for the very common
installed_agents(agent_cli_image(project.base_image)) pattern.
Source code in src/terok/lib/core/images.py
resolve_agent_config(project_id, *, agent_config=None, project_root=None, preset=None, cli_overrides=None)
¶
Build config stack and return the merged agent config dict.
Convenience wrapper around build_agent_config_stack for callers
that only need the final resolved dict (e.g. task runners).
Source code in src/terok/lib/orchestration/agent_config.py
check_clearance_units_outdated()
¶
read_installed_notifier_unit_version()
¶
Notifier unit version — shim around NotifierService.installed_version.
read_installed_unit_version()
¶
make_git_gate(config, *, use_personal_ssh=None)
¶
Construct a GitGate from a ProjectConfig (adapter factory).
Injects validate_gate_upstream_match as the gate validation callback.
The use_personal_ssh flag resolves per-invocation override (e.g.
terok gate-sync --use-personal-ssh) > per-project YAML
(ssh.use_personal) > default False.
Source code in src/terok/lib/domain/project.py
cleanup_images(dry_run=False)
¶
Find and remove orphaned terok images in one shot.
Thin convenience over find_orphaned_images
+ remove_images for callers that
don't need to inspect the list first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dry_run
|
bool
|
If True, only report what would be removed without removing. |
False
|
Returns:
| Type | Description |
|---|---|
CleanupResult
|
CleanupResult with lists of removed and failed image display names. |
Source code in src/terok/lib/domain/image_cleanup.py
delete_project(project_id)
¶
Delete a project and all its associated data.
Removes task workspaces, task metadata, build artifacts, SSH credentials, the git gate (if not shared with other projects), and the project config directory.
Source code in src/terok/lib/domain/project.py
derive_project(source_id, new_id)
¶
Copy source_id's gate mirror and vault SSH assignments under new_id.
Source code in src/terok/lib/domain/project.py
discover_projects()
¶
Load every project on disk, splitting successes from config-level failures.
The broken list lets the TUI render damaged projects alongside healthy
ones (issue #565) — silently hiding them turns "project vanished" into
a mystery. _parse_project_yaml wraps every config error (bad YAML,
schema drift, filesystem issues) in SystemExit with a human-readable
message; anything else propagates as a genuine bug.
Source code in src/terok/lib/core/projects.py
execute_panic(*, stop_containers=False)
¶
Execute the full panic sequence.
Discovers every running container, then raises shields, stops vault and gate — all in parallel. If stop_containers, also kills the containers afterwards (SIGKILL; they are not removed).
Source code in src/terok/lib/domain/panic.py
find_orphaned_images()
¶
Find terok images that are orphaned and safe to remove.
Orphaned images include:
- Dangling images (<none>:<none>) from terok layer rebuilds
- L2 project images whose project no longer exists in the config
Source code in src/terok/lib/domain/image_cleanup.py
find_projects_sharing_gate(gate_path, exclude_project=None)
¶
Find all projects configured to use the same gate path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gate_path
|
Path
|
The gate path to check for |
required |
exclude_project
|
str | None
|
Project ID to exclude from results (usually the current project) |
None
|
Returns:
| Type | Description |
|---|---|
list[tuple[str, str | None]]
|
List of (project_id, upstream_url) tuples for projects sharing this gate |
Source code in src/terok/lib/domain/project.py
format_panic_report(result)
¶
Format a human-readable summary of the panic result.
Source code in src/terok/lib/domain/panic.py
list_images(project_id=None)
¶
List terok-managed images, optionally filtered by project.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_id
|
str | None
|
If given, only show images for this project. |
None
|
Returns:
| Type | Description |
|---|---|
list[ImageInfo]
|
List of ImageInfo objects for matching images. |
Source code in src/terok/lib/domain/image_cleanup.py
list_projects()
¶
load_project(project_id)
¶
Load and return a fully resolved ProjectConfig from project_id.
Source code in src/terok/lib/core/projects.py
panic_stop_containers()
¶
Discover and SIGKILL all running containers (Phase 2 standalone).
project_image_exists(project_id)
¶
remove_images(images, *, dry_run=False)
¶
Remove a pre-computed set of images (or just report under dry_run).
Split out from cleanup_images
so the CLI can present the orphan list, prompt for confirmation, and only
then act — without paying the discovery cost twice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Iterable[ImageInfo]
|
The images to remove. Iterated once. |
required |
dry_run
|
bool
|
If True, only report names without invoking the runtime. |
False
|
Returns:
| Type | Description |
|---|---|
CleanupResult
|
CleanupResult with lists of removed and failed image display names. |
Source code in src/terok/lib/domain/image_cleanup.py
render_project_yaml(values)
¶
Render project.yml without writing it — used by the TUI review screen.
Source code in src/terok/lib/domain/wizards/new_project.py
require_project_exists(project_id)
¶
Raise SystemExit unless project_id names a known project.
Cheap stat-based check — no YAML parse, no pydantic validation. Use
this in CLI entry points that want to fail before any user-visible
side effect (interactive prompt, status print, image build offer).
The downstream load_project
call still catches malformed YAML.
Source code in src/terok/lib/core/projects.py
set_project_image_agents(project_id, selection)
¶
Write selection into the project's project.yml under image.agents.
Caller validates selection up-front; on success returns the project.yml path written.
Source code in src/terok/lib/core/projects.py
summarize_ssh_init(result)
¶
Render an ssh-init result for the terminal.
Source code in src/terok/lib/domain/ssh.py
validate_answer(question, raw)
¶
Normalise and validate a raw answer for question.
Returns (value, error_or_None) — the normalised value and an
error message if the answer was rejected. Both presenters call
this so validation semantics stay identical regardless of UI.
Normalisation, in order:
- Strip surrounding whitespace (copy-paste leftovers, accidental trailing spaces). All-whitespace input is indistinguishable from empty for the required/optional check.
- Apply
question.transformif set (e.g.str.lower). - Enforce the required flag against the final value.
- For
kind="choice", the value must be one of the declared slugs — defensive against presenter bugs that might submit a label, index, or free-form typo. - Run
question.validatefor field-specific rules.
Source code in src/terok/lib/domain/wizards/new_project.py
write_project_yaml(project_id, rendered, *, overwrite=False)
¶
Write rendered YAML to <user_projects_dir>/<project_id>/project.yml.
The TUI reviews YAML in a TextArea before writing, so this is the
write half of generate_config — kept separate so the TUI can
pass tweaked content without re-rendering the template.
Source code in src/terok/lib/domain/wizards/new_project.py
agent_config_dir(project_id, task_id)
¶
Host path of the agent-config dir bind-mounted at CONTAINER_TEROK_CONFIG.
Source code in src/terok/lib/orchestration/tasks/meta.py
container_name(project_id, mode, task_id)
¶
effective_status(task)
¶
Compute the display status from task lifecycle state.
Reads the following fields from a TaskState instance:
container_state(str | None): live podman state, or Noneexit_code(int | None): process exit code, or Nonedeleting(bool): persisted to YAML before deletion startsinitialized(bool): True onceready_atis persisted to YAML
Returns one of: "deleting", "running", "init",
"starting", "stopped", "completed", "failed",
"created", "not found".
Source code in src/terok/lib/core/task_state.py
generate_task_name(project_id=None)
¶
Generate a random human-readable task name (e.g. talented-toucan).
When project_id is given, name categories are resolved from config:
project tasks.name_categories → global tasks.name_categories
→ deterministic 3-category selection based on project ID hash.
Source code in src/terok/lib/orchestration/tasks/naming.py
get_all_task_states(project_id, tasks)
¶
Map each task to its live container state via a single batch query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_id
|
str
|
The project whose containers to query. |
required |
tasks
|
list[TaskMeta]
|
List of |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str | None]
|
|
Source code in src/terok/lib/orchestration/tasks/query.py
get_login_command(project_id, task_id)
¶
Return the podman exec command to log into a task container.
get_task_meta(project_id, task_id)
¶
Return metadata for a single task with live container state.
Hydrates container_state from the running container so that
TaskMeta.status reflects current reality rather than stale YAML.
Raises SystemExit if the task metadata file is not found.
Source code in src/terok/lib/orchestration/tasks/query.py
get_tasks(project_id, reverse=False)
¶
Return all task metadata for project_id, sorted by task ID.
get_workspace_git_diff(project_id, task_id, against='HEAD')
¶
Get git diff from a task's workspace via container exec.
Runs git diff inside the task container rather than on the host,
so that even poisoned git hooks only execute within the container sandbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_id
|
str
|
The project ID |
required |
task_id
|
str
|
The task ID |
required |
against
|
str
|
What to diff against ( |
'HEAD'
|
Returns:
| Type | Description |
|---|---|
str | None
|
The git diff output as a string, or |
Source code in src/terok/lib/orchestration/tasks/query.py
has_gpu(project)
¶
True when the project's project.yml opts into GPU passthrough.
Accepts any object with a root attribute pointing to the project
directory (typically a Project instance). Returns False on
any I/O or parse error.
Source code in src/terok/lib/core/task_state.py
mark_task_deleting(project_id, task_id)
¶
Persist deleting: true to the task's metadata file.
Source code in src/terok/lib/orchestration/tasks/meta.py
mode_info(mode)
¶
Return the display info for a task mode string.
sanitize_task_name(raw)
¶
Sanitize a raw task name into a slug-style identifier.
Strips whitespace, lowercases, replaces spaces with hyphens,
removes characters outside [a-z0-9_-], collapses consecutive
hyphens, strips trailing hyphens, and truncates to
TASK_NAME_MAX_LEN. Returns None if the result is empty.
Leading hyphens are preserved so callers can detect and reject them
(a name starting with - looks like a CLI flag).
Source code in src/terok/lib/orchestration/tasks/naming.py
task_archive_list(project_id)
¶
Print archived tasks for project_id.
Source code in src/terok/lib/orchestration/tasks/archive.py
task_archive_logs(project_id, archive_id)
¶
Return the log file path for an archived task identified by archive_id.
archive_id is matched against archive directory names (prefix match).
Returns the log file path if found, or None.
Source code in src/terok/lib/orchestration/tasks/archive.py
task_delete(project_id, task_id)
¶
Delete a task's workspace, metadata, and any associated containers.
Before removal, captures container logs and archives the task metadata
and logs to archive/<project_id>/tasks/. Containers are stopped
best-effort via podman using the <project.id>-<mode>-<task_id>
naming scheme. Returns a TaskDeleteResult so the caller can
present any warnings from cleanup steps that failed.
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
task_followup_headless(project_id, task_id, prompt, follow=True)
¶
Send a follow-up prompt to a completed/failed headless task.
Replaces prompt.txt with the new prompt (so the agent only sees the
current instruction) and archives the previous content to
prompt-history.txt. Restarts the stopped container via
podman start. Session context is
automatically restored for providers that support it:
- Claude: resumes via
--resume <session-id>(captured by aSessionStarthook that writesclaude-session.txt). - OpenCode / Blablador: resumes via
--session <id>(captured by theopencode-session-plugin.mjsplugin that writes the session file onsession.createdevents). - Vibe: resumes via
--resume <id>(session ID parsed post-run from~/.vibe/logs/session/metadata). - Codex / Copilot: no session resume support — follow-ups start a fresh session with the new prompt only.
Per-run flags (model, max_turns, timeout) carry forward from the
original task_run_headless invocation since podman start
re-executes the same container command.
Source code in src/terok/lib/orchestration/task_runners/headless.py
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | |
task_list(project_id, *, status=None, mode=None, agent=None)
¶
List tasks for a project, optionally filtered by status, mode, or agent preset.
Status is computed live from podman container state + task metadata.
Source code in src/terok/lib/orchestration/tasks/query.py
task_login(project_id, task_id)
¶
task_logs(project_id, task_id, options=None)
¶
View formatted logs for a task container.
Works on both running and exited containers (podman logs supports both).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_id
|
str
|
The project ID. |
required |
task_id
|
str
|
The task ID. |
required |
options
|
LogViewOptions | None
|
Display options (follow, raw, tail, streaming). |
None
|
Source code in src/terok/lib/domain/task_logs.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
task_new(project_id, *, name=None)
¶
Create a new task with a fresh workspace for a project.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_id
|
str
|
The project to create the task under. |
required |
name
|
str | None
|
Optional human-readable name. Allowed characters are
lowercase letters, digits, hyphens, and underscores.
If |
None
|
Workspace Initialization Protocol:¶
Each task gets its own workspace directory that persists across container runs. When a container starts, the init script (init-ssh-and-repo.sh) needs to know whether this is:
- A NEW task that should be reset to the latest remote HEAD
- A RESTARTED task where local changes should be preserved
We use a marker file (.new-task-marker) to signal intent:
- task_new() creates the marker in the workspace directory
- init-ssh-and-repo.sh checks for the marker:
- If marker exists: reset to origin/HEAD, then delete marker
- If no marker: fetch only, preserve local state
- Subsequent container runs on the same task won't see the marker, so local work is preserved
This handles edge cases like: - Stale workspace from incompletely deleted previous task with same ID - Ensuring new tasks always start with latest code
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
task_rename(project_id, task_id, new_name)
¶
Rename a task by updating its metadata file.
Sanitizes new_name and writes the result to the task's metadata file.
Raises SystemExit if the task is unknown or the sanitized name is invalid.
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
task_restart(project_id, task_id)
¶
Restart a task's container.
Semantics: stop the container if running, then start it. If the
container doesn't exist (e.g. because it was deleted out-of-band),
raise SystemExit with an actionable pointer to terok task run
— "restart" only means restart, not re-run.
Source code in src/terok/lib/orchestration/task_runners/restart.py
task_run_cli(project_id, task_id, agents=None, preset=None, unrestricted=None)
¶
Launch a CLI-mode task container and wait for its readiness marker.
Creates (or reattaches to) a detached Podman container for interactive
CLI access. After the container reports ready the task metadata is
marked running and the user is shown login instructions.
Source code in src/terok/lib/orchestration/task_runners/cli.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
task_run_headless(request)
¶
Run an agent headlessly (autopilot mode) in a new task container.
Creates a new task, prepares the agent-config directory with the provider's wrapper function and filtered subagents, then launches a detached container that runs init-ssh-and-repo.sh followed by the agent command.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
HeadlessRunRequest
|
All per-run options bundled in a |
required |
Returns the task_id.
Source code in src/terok/lib/orchestration/task_runners/headless.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
task_run_toad(project_id, task_id, agents=None, preset=None, unrestricted=None)
¶
Launch the Toad multi-agent TUI behind Caddy for token-gated browser access.
Same CLI image as interactive tasks, but the container entrypoint is
terok-toad-entry: it starts Caddy on the published port, toad on
an internal loopback port, and emits TEROK_READY once both are
listening. Caddy enforces the per-task token (see
_ensure_toad_token) on every request.
Source code in src/terok/lib/orchestration/task_runners/toad.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | |
task_status(project_id, task_id)
¶
Show live task status with container state diagnostics.
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
task_stop(project_id, task_id, *, timeout=None)
¶
Gracefully stop a running task container.
Uses podman stop --time <N> to give the container timeout seconds
before SIGKILL. When timeout is None the project's
run.shutdown_timeout setting is used (default 10 s).
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
validate_task_name(sanitized)
¶
Return an error message if sanitized is not a valid task name, else None.
A name is invalid if it starts with a hyphen (looks like a CLI flag).
Callers should first check for None from sanitize_task_name
(which indicates the name was empty after sanitization).
Source code in src/terok/lib/orchestration/tasks/naming.py
wait_for_container_exit(container_name, project_id, task_id, timeout=7200)
¶
Wait for container_name to exit and record its code in task metadata.
Returns (exit_code, error_message). On a successful wait
error_message is None and the real exit code is persisted
— including a legitimate exit code of 124, which is no longer
conflated with the watcher's own timeout. On timeout exit_code
is None and the error message describes it.
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
vault_db(*, prompt_on_tty=False)
¶
Open the shared vault CredentialDB and close it on exit.
Routes through SandboxConfig.open_credential_db so the four-tier
passphrase resolution chain (session-unlock file → keyring → config
fallback → optional prompt) runs. Daemons and background workers
leave prompt_on_tty=False so a locked vault fails fast with a
clear NoPassphraseError instead of stalling on stdin; CLI
front-ends pass True to unlock the interactive last-resort
prompt.
Source code in src/terok/lib/domain/vault.py
make_sandbox_config()
¶
Construct a SandboxConfig for sandbox operations.
Bridges terok's config layer (env vars → config.yml → XDG defaults) to
sandbox's plain dataclass. Sandbox uses its own state_dir default
(~/.local/share/terok/sandbox/) — terok no longer overrides it.
Port fields pass None (unresolved — consumers that launch services
call cfg.with_resolved_ports() to allocate via sandbox's shared
port registry) or an explicit int from config.yml. This factory
is side-effect-free, matching sandbox's R2 contract: config inspection
and sickbay paths must not silently bind sockets.
This is the single source of truth for config bridging — every
SandboxConfig field that terok
controls must be set here.
terok's config-equality promise¶
For every field with a representation in the shared config.yml
schema that sandbox/executor own, the cfg this function constructs
matches what standalone sandbox would have read from the same file
— modulo user-supplied --flag / env overrides. Runtime-only
ambient context with no config-file representation may be added
additively but must not shadow a schema field. Sandbox/executor
accept any SandboxConfig without enforcement; third-party
orchestrators choose their own contracts.
Diff terok executor show-config against standalone
terok-executor show-config over the same config.yml to verify.
Source code in src/terok/lib/core/config.py
set_experimental(value)
¶
get_config()
¶
Snapshot the global config into a single Config value.
Source code in src/terok/lib/api/__init__.py
get_container_state(cname)
¶
Return the live podman state for a container, or None if not found.
Thin wrapper for one-shot state lookups. The probe goes through
plain PodmanRuntime because container-state reads are
runtime-agnostic (podman inspect returns the same shape under
every OCI runtime), and the caller may not have project context
in scope to resolve the per-project runtime.