import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { DEFAULT_OPENAI_MODEL, LlmAdapterService, createLogger, TraceConsoleFormatter, AgentLoopRuntimeService, RuntimeCredentialService, } from '../../../../index.js';
import { MemoryCatalogService } from '../../../../core/memory/catalog.js';
import { MemoryMaintenanceIntegrationService } from '../../../../core/memory/maintenance-integration.js';
export class ControlPlaneAskController {
    static async run(args) {
        const model = args.model ?? process.env.OPENAI_MODEL ?? process.env.ANTHROPIC_MODEL ?? DEFAULT_OPENAI_MODEL;
        const maxSteps = args.maxSteps ?? ControlPlaneAskController.parsePositiveInt(process.env.HEDDLE_MAX_STEPS) ?? 100;
        const logger = createLogger({ pretty: true, level: 'debug' });
        const memoryDir = join(args.stateRoot, 'memory');
        const apiKey = RuntimeCredentialService.resolveApiKeyForModel(model, {
            apiKey: args.apiKey,
            apiKeyProvider: args.apiKey ? 'explicit' : undefined,
            preferApiKey: args.preferApiKey,
        });
        const llm = LlmAdapterService.create({
            model,
            credentials: { apiKey },
        });
        const result = await AgentLoopRuntimeService.run({
            goal: args.goal,
            model,
            apiKey,
            maxSteps,
            logger,
            workspaceRoot: args.workspaceRoot,
            stateDir: ControlPlaneAskController.relativeStateDir(args.workspaceRoot, args.stateRoot),
            searchIgnoreDirs: args.searchIgnoreDirs,
            memoryDir,
            systemContext: new MemoryCatalogService(memoryDir).appendCatalogSystemContext({
                systemContext: args.systemContext,
            }),
            includePlanTool: false,
            llm,
        });
        const maintenance = await new MemoryMaintenanceIntegrationService(memoryDir).runForRecordedCandidates({
            llm,
            source: 'control plane ask',
            trace: result.trace,
            maxSteps: 20,
        });
        const trace = maintenance.events.length > 0 ? [...result.trace, ...maintenance.events] : result.trace;
        const traceDir = join(args.stateRoot, 'traces');
        mkdirSync(traceDir, { recursive: true });
        const traceFile = join(traceDir, `trace-${Date.now()}.json`);
        writeFileSync(traceFile, JSON.stringify(trace, null, 2));
        return {
            ...result,
            trace,
            traceFile,
            consoleOutput: TraceConsoleFormatter.format(trace),
        };
    }
    static relativeStateDir(workspaceRoot, stateRoot) {
        if (!stateRoot.startsWith(workspaceRoot)) {
            return undefined;
        }
        const suffix = stateRoot.slice(workspaceRoot.length).replace(/^\/+/, '');
        return suffix || '.heddle';
    }
    static parsePositiveInt(raw) {
        if (!raw) {
            return undefined;
        }
        const value = Number.parseInt(raw, 10);
        return Number.isFinite(value) && value > 0 ? value : undefined;
    }
}
//# sourceMappingURL=ask.js.map