#!/usr/bin/env bash # create_session.sh — multi-agent-mux-create 의 부속 스크립트 # Usage: # bash create_session.sh --workspace --agent --role [--session ] [--wrapper] # # 동작: # 1) preflight: herdr/claude/agy 가용성, workspace 존재 # 2) herdr 세션 이름 결정 (--session 없으면 자동) # 3) herdr 세션 시작 (claude 는 wrapper 우선, agy 는 인라인) # 4) pane 메타 캡처 (pid, cmd, cwd) # 5) agent-sessions.yaml 에 herdr_sessions[] 엔트리 append # 6) 검증 출력 # # Exit codes: # 0 = success # 1 = preflight failure # 2 = invalid args # 3 = herdr session already exists (use multi-agent-mux-resume or delete first) # 4 = agent-sessions.yaml append failure set -euo pipefail source "$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/lib.sh" usage() { cat < --agent --role [options] Options: --workspace PATH project directory (required) --agent AGENT claude | agy | hermes | cline (required) --role ROLE assigned role (required) --session NAME herdr session name (default: derived from workspace) --wrapper force use of ~/.local/bin/ wrapper even if not present --dry-run print commands without executing --herdr-server NAME specify isolated herdr server name --submit-job PROMPT submit a job to multi-agent-mux-delegate-job registry with the given prompt --onboard automatically submit a project alignment/orientation job to the new agent --no-onboard disable automatic onboarding job submission --no-isolate disable state isolation (shares global configuration/history) [default: isolated mode is always active] -h, --help this help EOF } WORKSPACE="" AGENT="" ROLE="" SESSION_NAME="" USE_WRAPPER=0 DRY_RUN=0 HERDR_SERVER_OPT="" SUBMIT_JOB_PROMPT="" ONBOARD=1 ISOLATE=1 while [ $# -gt 0 ]; do case "$1" in --workspace) WORKSPACE="$2"; shift 2 ;; --agent) AGENT="$2"; shift 2 ;; --role) ROLE="$2"; shift 2 ;; --session) SESSION_NAME="$2"; shift 2 ;; --wrapper) USE_WRAPPER=1; shift ;; --dry-run) DRY_RUN=1; shift ;; --herdr-server) HERDR_SERVER_OPT="$2"; shift 2 ;; --submit-job) SUBMIT_JOB_PROMPT="$2"; shift 2 ;; --onboard) ONBOARD=1; shift ;; --no-onboard) ONBOARD=0; shift ;; --isolate) ISOLATE=1; shift ;; # legacy compatibility --no-isolate) ISOLATE=0; shift ;; -h|--help) usage; exit 0 ;; *) echo "ERROR: unknown arg: $1" >&2; usage; exit 2 ;; esac done if [ -n "$HERDR_SERVER_OPT" ]; then export HERDR_SERVER_NAME="$HERDR_SERVER_OPT" fi # Preflight [ -n "$WORKSPACE" ] || { echo "ERROR: --workspace required" >&2; usage; exit 2; } [ -n "$AGENT" ] || { echo "ERROR: --agent required" >&2; usage; exit 2; } [ -n "$ROLE" ] || { echo "ERROR: --role required" >&2; usage; exit 2; } [ -d "$WORKSPACE" ] || { echo "ERROR: workspace $WORKSPACE not a directory" >&2; exit 1; } command -v herdr >/dev/null || { echo "ERROR: herdr not installed" >&2; exit 1; } command -v "$AGENT" >/dev/null || { echo "ERROR: $AGENT CLI not in PATH" >&2; exit 1; } # Auth Check (OAuth check for agy, loggedIn check for claude, status for hermes) if [ "$AGENT" = "claude" ]; then if ! claude auth status 2>/dev/null | grep -q '"loggedIn":\s*true'; then echo "ERROR: claude not logged in. Run 'claude auth login' first." >&2 exit 1 fi elif [ "$AGENT" = "agy" ]; then # Fast, non-blocking check: if token or credentials exist on disk, assume authenticated to prevent keyring hang if [ -f "$HOME/.gemini/oauth_creds.json" ] || [ -f "$HOME/.gemini/antigravity-cli/antigravity-oauth-token" ]; then true elif ! agy models >/dev/null 2>&1; then echo "ERROR: agy is not authenticated. Please log in first." >&2 exit 1 fi elif [ "$AGENT" = "hermes" ]; then if ! hermes status >/dev/null 2>&1; then echo "ERROR: hermes is not functional. Run 'hermes setup' first." >&2 exit 1 fi elif [ "$AGENT" = "cline" ]; then if ! cline history --json >/dev/null 2>&1; then echo "ERROR: cline is not functional or configured." >&2 exit 1 fi fi # 세션 이름 — lib.sh::derive_session_name 이 단일 소스 (P0-A) if [ -z "$SESSION_NAME" ]; then SESSION_NAME="$(derive_session_name "$WORKSPACE" "$AGENT")" fi # 이미 살아있으면 실패 if _herdr has-session -t "$SESSION_NAME" 2>/dev/null; then echo "ERROR: herdr session '$SESSION_NAME' already exists. Use multi-agent-mux-resume to attach, or multi-agent-mux-stop first." >&2 exit 3 fi # T3: 세션 격리 프로비저닝 (all-L2) — 격리 홈 생성 + auth/설정 심링크 시딩 # (implementation_plan.session_isolation.md Rev.3 / Phase 0 실측 매트릭스 기준) ISOLATION_UUID="" ISOLATION_ROOT="" ISOLATION_LEVER="" ISOLATION_SEEDED="" if [ "$ISOLATE" = "1" ]; then command -v uuidgen >/dev/null || { echo "ERROR: uuidgen not found (required for --isolate)" >&2; exit 1; } WORKSPACE_ABS="$(cd "$WORKSPACE" && pwd)" ISOLATION_UUID="$(uuidgen)" ISOLATION_ROOT="$WORKSPACE_ABS/.mam/agent_homes/$ISOLATION_UUID" ISOLATION_LEVER="$(isolation_lever "$AGENT")" if [ "$DRY_RUN" = "1" ]; then echo "[dry-run] would provision isolation: lever=$ISOLATION_LEVER root=$ISOLATION_ROOT" else ISOLATION_SEEDED="$(provision_isolation "$AGENT" "$ISOLATION_ROOT")" echo "isolation: lever=$ISOLATION_LEVER root=$ISOLATION_ROOT" fi fi # herdr 세션 띄우기 LOCAL_BIN="${LOCAL_BIN:-$HOME/.local/bin}" WRAPPER="$LOCAL_BIN/$SESSION_NAME" # cmd_full 결정 — T4: isolation 디스패치(env prefix / CLI args)를 시작 명령에 주입. # 격리 미사용 시 기존 문자열과 byte-identical (V4 회귀 0). ISO_ENV_PREFIX="" ISO_CMD_ARGS="" if [ -n "$ISOLATION_ROOT" ]; then ISO_ENV_PREFIX="$(isolation_env_prefix "$AGENT" "$ISOLATION_ROOT")" ISO_CMD_ARGS="$(isolation_cmd_args "$AGENT" "$ISOLATION_ROOT")" fi # Resolve absolute path of the agent command to prevent herdr PATH inheritance issues (especially on macOS) RESOLVED_BIN="$AGENT" if [ "$AGENT" = "cline" ]; then if command -v cline >/dev/null 2>&1; then RESOLVED_BIN="$(command -v cline)" fi else if command -v "$AGENT" >/dev/null 2>&1; then RESOLVED_BIN="$(command -v "$AGENT")" fi fi # On macOS, clear quarantine attribute for the agent binary to prevent Gatekeeper hangs if [ "$(uname)" = "Darwin" ] && [ -f "$RESOLVED_BIN" ]; then xattr -d com.apple.quarantine "$RESOLVED_BIN" 2>/dev/null || true fi case "$AGENT" in claude) CMD_FULL="${ISO_ENV_PREFIX}${RESOLVED_BIN} --dangerously-skip-permissions" ;; agy) CMD_FULL="${ISO_ENV_PREFIX}${RESOLVED_BIN} --dangerously-skip-permissions" ;; hermes) CMD_FULL="${ISO_ENV_PREFIX}${RESOLVED_BIN}" ;; cline) CMD_FULL="${RESOLVED_BIN} -i${ISO_CMD_ARGS:+ $ISO_CMD_ARGS}" ;; esac spawn() { case "$AGENT" in claude) # 격리 시 wrapper 경로는 env 주입을 운반하지 못하므로 인라인 spawn 강제 if [ "$ISOLATE" != "1" ] && { { [ -x "$WRAPPER" ] && [ "$(basename "$WRAPPER")" != "claude" ]; } || [ "$USE_WRAPPER" = "1" ]; }; then nohup "$WRAPPER" >/dev/null 2>&1 & disown else _herdr new-session -d -s "$SESSION_NAME" -x 140 -y 40 -c "$WORKSPACE" "$CMD_FULL" fi ;; agy|hermes|cline) _herdr new-session -d -s "$SESSION_NAME" -x 140 -y 40 -c "$WORKSPACE" "$CMD_FULL" ;; *) echo "ERROR: --agent must be claude, agy, hermes or cline, got: $AGENT" >&2; exit 2 ;; esac } if [ "$DRY_RUN" = "1" ]; then echo "[dry-run] would spawn: herdr session '$SESSION_NAME' in $WORKSPACE (agent=$AGENT)" exit 0 fi spawn # Trap for rolling back/cleaning up herdr session if script exits due to error cleanup_herdr_on_error() { local exit_code=$? if [ $exit_code -ne 0 ]; then echo "⚠️ Error occurred during initialization. Rolling back and killing herdr session '$SESSION_NAME'..." >&2 _herdr kill-session -t "$SESSION_NAME" 2>/dev/null || true # T3 rollback: 이 세션용으로 프로비저닝한 격리 홈 제거 (경로 가드 후 rm) if [ -n "$ISOLATION_ROOT" ] && [ -d "$ISOLATION_ROOT" ]; then case "$ISOLATION_ROOT" in */.mam/agent_homes/*) rm -rf "$ISOLATION_ROOT" ;; esac fi fi } trap cleanup_herdr_on_error EXIT # TUI 준비 대기 if ! wait_for_tui_ready "$SESSION_NAME" "$AGENT"; then echo "ERROR: agent TUI never became ready — aborting (rollback via trap)" >&2 exit 1 fi # pane 메타 캡처 PANE_PID=$(_herdr list-panes -t "$SESSION_NAME" -F '#{pane_pid}' 2>/dev/null || echo "") PANE_CWD=$(_herdr list-panes -t "$SESSION_NAME" -F '#{pane_current_path}' 2>/dev/null || echo "$WORKSPACE") PANE_CMD=$(_herdr list-panes -t "$SESSION_NAME" -F '#{pane_current_command}' 2>/dev/null || echo "$AGENT") HERDR_EPOCH=$(date +%s) NOW_ISO=$(date -u +'%Y-%m-%dT%H:%M:%SZ') # 시작 명령 (CMD_FULL 은 spawn 전에 isolation 디스패치를 반영해 확정됨 — T4) # NOTE: this must match what `spawn()` actually ran above — env-var-driven # isolation (HERDR_SERVER_NAME picked up by the lib.sh shim), not a # `--workspace