import {
  researcherProfile
} from "./chunk-5QOB7H74.js";
import {
  supervise
} from "./chunk-FRXDOBFP.js";

// src/knowledge/improvement-job.ts
import {
  evaluateKnowledgeBaseReadiness,
  improveKnowledgeBase
} from "@tangle-network/agent-knowledge";

// src/knowledge/supervised-update.ts
var RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [
  "You are a research supervisor. You do not answer the research question yourself.",
  "You create and manage researcher workers that improve one shared knowledge base until it is ready.",
  "",
  "Each round:",
  "1. Read the goal and the gaps the readiness check still reports.",
  "2. Decompose the open work into independent sub-topics.",
  "3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.",
  "4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.",
  "",
  "Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground."
].join("\n");
function knowledgeReadinessDeliverable(options) {
  return {
    describe: `knowledge base at ${options.root} is ready for: ${options.goal}`,
    async check() {
      const result = await options.readiness({
        root: options.root,
        goal: options.goal,
        readinessSpecs: options.readinessSpecs,
        readinessTaskId: options.readinessTaskId,
        readiness: options.readinessOptions
      });
      return typeof result === "boolean" ? result : result.ready;
    }
  };
}
function createSupervisedKnowledgeUpdater(options) {
  return (input) => runSupervisedKnowledgeUpdate({
    ...options,
    root: input.candidateRoot ?? input.root ?? options.root,
    goal: input.goal ?? options.goal,
    findings: input.findings ?? options.findings,
    metadata: { ...options.metadata, ...input.metadata }
  });
}
async function runSupervisedKnowledgeUpdate(options) {
  const { profile: workerProfile } = researcherProfile({ harness: options.harness });
  const baseInstructions = options.supervisorSystemPrompt ?? RESEARCH_SUPERVISOR_SYSTEM_PROMPT;
  const workerContract = workerProfile.prompt?.systemPrompt;
  const systemPrompt = workerContract ? `${baseInstructions}

Each researcher worker you spawn follows this contract:
${workerContract}` : baseInstructions;
  const profile = {
    name: "knowledge-research-supervisor",
    model: options.supervisorModel,
    systemPrompt
  };
  const run = options.runSupervised ?? supervise;
  const task = formatSupervisedKnowledgeTask(options);
  const supervised = await run(profile, task, {
    ...options.superviseOptions,
    budget: options.budget,
    backend: options.backend,
    deliverable: knowledgeReadinessDeliverable(options),
    makeWorkerAgent: options.makeWorkerAgent,
    allowedModels: options.allowedModels
  });
  return {
    applied: supervised.kind === "winner",
    summary: supervised.kind === "winner" ? "research supervisor completed and the knowledge base passed readiness" : `research supervisor stopped without a ready knowledge base: ${supervised.reason}`,
    supervised,
    metadata: {
      supervised: true,
      root: options.root,
      goal: options.goal,
      result: supervised.kind
    }
  };
}
function formatSupervisedKnowledgeTask(options) {
  const sections = [
    `Goal: ${options.goal}`,
    `Knowledge base root: ${options.root}`,
    options.readinessTaskId ? `Readiness task id: ${options.readinessTaskId}` : void 0,
    options.readinessSpecs?.length ? `Readiness specs:
${JSON.stringify(options.readinessSpecs, null, 2)}` : void 0,
    options.findings?.length ? `Current findings:
${JSON.stringify(options.findings, null, 2)}` : void 0,
    options.metadata && Object.keys(options.metadata).length > 0 ? `Metadata:
${JSON.stringify(options.metadata, null, 2)}` : void 0
  ].filter((section) => Boolean(section));
  return `${sections.join("\n\n")}

Update files under the knowledge base root only. Stop when the readiness check passes.`;
}

// src/knowledge/improvement-job.ts
function createAgentKnowledgeReadinessCheck(options) {
  return async (input) => {
    const readiness = await evaluateKnowledgeBaseReadiness({
      root: input.root,
      goal: input.goal ?? options.goal,
      readinessSpecs: input.readinessSpecs ?? options.readinessSpecs,
      readinessTaskId: input.readinessTaskId ?? options.readinessTaskId,
      readiness: input.readiness ?? options.readiness,
      strict: options.strict,
      kbQuality: options.kbQuality
    });
    return {
      ready: readiness.ready,
      summary: readiness.summary,
      metadata: {
        dimensions: readiness.dimensions,
        validationOk: readiness.validation.ok,
        kbQualityOk: readiness.kbQuality.ok,
        blockingMissing: readiness.readiness?.report.blockingMissingRequirements.length ?? 0
      }
    };
  };
}
async function runKnowledgeImprovementJob(options) {
  const {
    allowedModels,
    backend,
    budget,
    harness,
    makeWorkerAgent,
    onMeasurement,
    readinessCheck,
    runSupervised,
    supervisorModel,
    supervisorSystemPrompt,
    superviseOptions,
    ...knowledgeOptions
  } = options;
  const startedAtMs = Date.now();
  const startedAt = new Date(startedAtMs).toISOString();
  const supervisedSpent = emptySpent();
  let updateCalls = 0;
  let updateDurationMs = 0;
  const readiness = readinessCheck ?? createAgentKnowledgeReadinessCheck(options);
  const updateKnowledge = createSupervisedKnowledgeUpdater({
    root: options.root,
    goal: options.goal,
    readiness,
    readinessSpecs: options.readinessSpecs,
    readinessTaskId: options.readinessTaskId,
    readinessOptions: options.readiness,
    budget,
    backend,
    makeWorkerAgent,
    harness,
    supervisorModel,
    supervisorSystemPrompt,
    superviseOptions,
    allowedModels,
    runSupervised
  });
  const resolvedImprovement = await improveKnowledgeBase({
    ...knowledgeOptions,
    updateKnowledge: async (input) => {
      const updateStartedAt = Date.now();
      updateCalls += 1;
      const result = await updateKnowledge(input);
      updateDurationMs += Date.now() - updateStartedAt;
      addSpent(supervisedSpent, result.supervised);
      return result;
    }
  });
  const finishedAtMs = Date.now();
  const measurement = {
    startedAt,
    finishedAt: new Date(finishedAtMs).toISOString(),
    durationMs: finishedAtMs - startedAtMs,
    updateCalls,
    updateDurationMs,
    supervisedSpent
  };
  await onMeasurement?.(measurement);
  return {
    improvement: resolvedImprovement,
    measurement,
    promoted: resolvedImprovement.promoted,
    blocked: resolvedImprovement.blocked
  };
}
function emptySpent() {
  return { iterations: 0, inputTokens: 0, outputTokens: 0, usd: 0, ms: 0 };
}
function addSpent(target, result) {
  const spent = result.spentTotal;
  target.iterations += spent.iterations ?? 0;
  target.inputTokens += spent.tokens?.input ?? 0;
  target.outputTokens += spent.tokens?.output ?? 0;
  target.usd += spent.usd ?? 0;
  target.ms += spent.ms ?? 0;
}

export {
  RESEARCH_SUPERVISOR_SYSTEM_PROMPT,
  knowledgeReadinessDeliverable,
  createSupervisedKnowledgeUpdater,
  runSupervisedKnowledgeUpdate,
  formatSupervisedKnowledgeTask,
  createAgentKnowledgeReadinessCheck,
  runKnowledgeImprovementJob
};
//# sourceMappingURL=chunk-TNUBPPZA.js.map