// hosts/claude-code/runtime/agent-teams-adapter.ts — SPEC-587
// Detects Claude Code Agent Teams support and maps Planu teammates onto it.
// Falls back to orchestrate_runtime semantics when the host lacks the feature.
import { access, mkdir, writeFile, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { homedir } from 'node:os';
const TEAMS_DIR = join(homedir(), '.claude', 'teams');
/**
 * Return true when ~/.claude/teams/ exists — heuristic for Agent Teams host support.
 * The directory is created by Claude Code on first team spawn.
 */
export async function detectAgentTeamsSupport() {
    try {
        await access(TEAMS_DIR);
        return true;
    }
    catch {
        return false;
    }
}
/** Convert a Planu TeammateInfo into an AgentTeamMember entry. */
function toTeamMember(info) {
    return {
        id: info.specId,
        role: `implementer-${info.specId}`,
        model: info.model,
        specId: info.specId,
        status: info.status === 'running'
            ? 'running'
            : info.status === 'completed'
                ? 'completed'
                : info.status === 'failed'
                    ? 'failed'
                    : 'idle',
    };
}
/**
 * Spawn (or update) a team config under ~/.claude/teams/<teamId>/config.json.
 * Idempotent: re-writing an existing config with the same teammates is a no-op
 * in terms of side-effects — the host will reconcile differences on next tick.
 *
 * When Agent Teams support is not detected, logs a single-line warning and
 * returns undefined (caller falls back to orchestrate_runtime).
 */
export async function spawnTeamMember(config) {
    const supported = await detectAgentTeamsSupport();
    if (!supported) {
        logFallback('Agent Teams', 'falling back to orchestrate_runtime — ~/.claude/teams/ not found');
        return undefined;
    }
    const teamDir = join(TEAMS_DIR, config.teamId);
    await mkdir(teamDir, { recursive: true });
    const configPath = join(teamDir, 'config.json');
    // Read existing to preserve createdAt (idempotent)
    let createdAt = new Date().toISOString();
    try {
        const existing = JSON.parse(await readFile(configPath, 'utf-8'));
        createdAt = existing.createdAt;
    }
    catch {
        // first write — use now
    }
    const teamConfig = {
        id: config.teamId,
        name: config.teamName,
        teammates: config.teammates.map(toTeamMember),
        createdAt,
    };
    await writeFile(configPath, JSON.stringify(teamConfig, null, 2), 'utf-8');
    return teamConfig;
}
/** Emit one-time fallback warning to stderr (never stdout — reserved for MCP). */
export function logFallback(surface, description) {
    console.warn(`[claude-code/agent-teams] No support for "${surface}" — ${description}`);
}
//# sourceMappingURL=agent-teams-adapter.js.map