#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2025 Jiri Vyskocil
# SPDX-License-Identifier: Apache-2.0
# terok:container — this file is deployed into task containers, not used on the host.

# ACP wrapper for Mistral Vibe.
#
# Sets up per-agent git identity, session capture, and workspace trust
# before running the real vibe-acp adapter.
#
# Task instructions arrive through the container's read-only
# ~/.vibe/AGENTS.md mount, independently of the selected agent profile.
#
# Unrestricted mode: VIBE_BYPASS_TOOL_PERMISSIONS env var is set at
# container level via vibe.yaml's ``auto_approve.env``.  VibeConfig
# uses pydantic-settings with env_prefix="VIBE_", case_sensitive=False,
# so the env var maps to ``bypass_tool_permissions: bool`` on the
# settings model.  ACP gates the approval callback on exactly this
# field (vibe.acp.acp_agent_loop:330), so True skips every tool prompt
# — the closest equivalent to other agents' --yolo flag.

set -euo pipefail

_AGENT_NAME="Vibe"
_AGENT_EMAIL="noreply@mistral.ai"
. /usr/local/share/terok/terok-acp-env.sh

# Hooks record the root session for a later CLI restart; storage stays native.
export TEROK_SESSION_FILE="${HOME}/.terok/vibe-session-id.txt"
if ! python3 /usr/local/share/terok/terok-vibe-session.py install; then
    echo "terok: Vibe session hooks unavailable; no shared-history auto-discovery." >&2
fi
rm -f "$TEROK_SESSION_FILE"

# Trust the container's workspace so Vibe's HarnessFilesManager walks
# the project's AGENTS.md chain into the system prompt.  ACP has no
# --trust flag; without this, ``trusted_workdir`` is None and
# ``load_project_docs`` returns early.  ~/.vibe is shared across every
# task container, so the write is ``flock``-guarded against concurrent
# updates.  ``/workspace`` is a container-only path that never resolves
# on the host — persisting it in shared state only affects future
# containers mounting the same /workspace, which is exactly what we
# want.
#
# The TOML merge itself lives in
# ``/usr/local/share/terok/terok-trust-workspace.py`` (installed by the
# L1 Dockerfile); the same script is invoked by the CLI wrapper
# (``_TRUST_WORKSPACE_FN`` in ``provider/wrappers.py``) so future Vibe
# schema changes land in one place.
_terok_trust_workspace_for_vibe() {
    local _path="$1"
    local _tf="${HOME}/.vibe/trusted_folders.toml"
    local _merge=/usr/local/share/terok/terok-trust-workspace.py
    [ -x "${_merge}" ] || return 0
    mkdir -p "$(dirname "${_tf}")"
    (
        flock -x 200
        python3 "${_merge}" "${_path}" "${_tf}"
    ) 200>"${_tf}.lock"
}
_terok_trust_workspace_for_vibe /workspace

# Stay alive to report missing session capture after the adapter exits.
_rc=0
vibe-acp "$@" || _rc=$?
if [[ ! -s "$TEROK_SESSION_FILE" ]]; then
    echo "terok: Vibe did not capture a task session (hooks unavailable or no tool/turn completed)." >&2
    echo "  Automatic CLI resume is unavailable; shared history is never guessed. Use vibe --resume to choose." >&2
fi
exit "$_rc"
