Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

18.1 KB
Raw Blame
import type { OpenAIChatMessage } from '@lobechat/types';

import {
  VERIFY_EVIDENCE_MODALITIES,
  VERIFY_EVIDENCE_SCOPES,
  VERIFY_EVIDENCE_TYPES,
  VERIFY_ON_FAIL_ACTIONS,
  VERIFY_VERIFIER_TYPES,
} from './verify';

/** Bump when the create-goal criteria drafting prompt meaningfully changes. */
export const GOAL_CRITERIA_DRAFT_PROMPT_VERSION = 'v3';

export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {
  name: 'goal_criteria_draft',
  schema: {
    additionalProperties: false,
    properties: {
      criteria: {
        items: {
          additionalProperties: false,
          properties: {
            description: { maxLength: 280, type: 'string' },
            instruction: { type: 'string' },
            onFail: { enum: [...VERIFY_ON_FAIL_ACTIONS], type: 'string' },
            requiredEvidence: {
              items: {
                additionalProperties: false,
                properties: {
                  hint: { type: 'string' },
                  modality: { enum: [...VERIFY_EVIDENCE_MODALITIES], type: 'string' },
                  scope: { enum: [...VERIFY_EVIDENCE_SCOPES], type: 'string' },
                  type: { enum: [...VERIFY_EVIDENCE_TYPES], type: 'string' },
                },
                required: ['type', 'modality', 'scope', 'hint'],
                type: 'object',
              },
              type: 'array',
            },
            required: { type: 'boolean' },
            title: { maxLength: 80, minLength: 1, type: 'string' },
            verifierType: { enum: [...VERIFY_VERIFIER_TYPES], type: 'string' },
          },
          required: [
            'title',
            'description',
            'instruction',
            'verifierType',
            'required',
            'onFail',
            'requiredEvidence',
          ],
          type: 'object',
        },
        maxItems: 8,
        type: 'array',
      },
      instruction: { minLength: 1, type: 'string' },
      title: { maxLength: 80, minLength: 1, type: 'string' },
    },
    required: ['title', 'instruction', 'criteria'],
    type: 'object' as const,
  },
  strict: true,
};

/** Bump when the goal decomposition planning prompt meaningfully changes. */
export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v9';

export const GOAL_DECOMPOSE_JSON_SCHEMA = {
  name: 'goal_decomposition',
  schema: {
    additionalProperties: false,
    properties: {
      assumptions: { items: { maxLength: 280, type: 'string' }, maxItems: 5, type: 'array' },
      /**
       * One sentence on why this goal needs more than a single planning pass,
       * so the main Agent β€” which can inspect the workspace β€” plans it instead.
       * Null when the plan below is good enough to run.
       */
      escalate: { maxLength: 280, type: ['string', 'null'] },
      problemStatement: { maxLength: 280, minLength: 1, type: 'string' },
      /**
       * Set only for one repeated mould β€” many structurally identical units
       * sharing a single reusable transformation. Null for every ordinary goal.
       */
      rollout: {
        additionalProperties: false,
        properties: {
          recipeOutline: { maxLength: 280, type: 'string' },
          repeatable: { type: 'boolean' },
          /** Honest count of the homogeneous units in the whole goal. */
          unitCount: { minimum: 1, type: 'integer' },
          /** Roster of every homogeneous unit, probes first, in delivery order. */
          units: { items: { maxLength: 120, type: 'string' }, maxItems: 60, type: 'array' },
          /** Axes the units vary along, so a probe can cover them. */
          variants: {
            items: {
              additionalProperties: false,
              properties: {
                axis: { maxLength: 80, minLength: 1, type: 'string' },
                values: { items: { maxLength: 80, type: 'string' }, maxItems: 8, type: 'array' },
              },
              required: ['axis', 'values'],
              type: 'object',
            },
            maxItems: 4,
            type: 'array',
          },
        },
        required: ['repeatable', 'unitCount', 'recipeOutline', 'variants', 'units'],
        type: ['object', 'null'],
      },
      questions: {
        items: {
          additionalProperties: false,
          properties: {
            assumption: { maxLength: 280, minLength: 1, type: 'string' },
            blocking: { type: 'boolean' },
            impact: { maxLength: 280, type: 'string' },
            options: { items: { maxLength: 80, type: 'string' }, maxItems: 4, type: 'array' },
            question: { maxLength: 280, minLength: 1, type: 'string' },
          },
          required: ['question', 'impact', 'options', 'assumption', 'blocking'],
          type: 'object',
        },
        maxItems: 3,
        type: 'array',
      },
      tasks: {
        items: {
          additionalProperties: false,
          properties: {
            dependsOn: { items: { minimum: 0, type: 'integer' }, type: 'array' },
            hypothesis: { maxLength: 280, type: ['string', 'null'] },
            instruction: { minLength: 1, type: 'string' },
            title: { maxLength: 80, minLength: 1, type: 'string' },
          },
          required: ['title', 'instruction', 'dependsOn', 'hypothesis'],
          type: 'object',
        },
        maxItems: 5,
        minItems: 1,
        type: 'array',
      },
    },
    required: ['problemStatement', 'questions', 'assumptions', 'tasks', 'rollout', 'escalate'],
    type: 'object' as const,
  },
  strict: true,
};

export interface GoalClarificationAnswer {
  answer: string;
  question: string;
}

interface GoalDecomposeInput {
  /** Questions the user already answered for this goal; present on the re-plan after a clarification. */
  clarifications?: GoalClarificationAnswer[];
  requirement: string;
}

/**
 * Plan the opening exploration structure of a goal graph: the core question it
 * answers plus the independent task directions to pursue, before anything runs.
 */
export const chainGoalDecompose = ({
  clarifications,
  requirement,
}: GoalDecomposeInput): {
  messages: OpenAIChatMessage[];
} => ({
  messages: [
    {
      content: [
        'You plan executable tasks for a persistent autonomous goal.',
        'You plan in one pass, without seeing the workspace. That suits a goal whose shape is clear from its wording. When planning it well needs more β€” reading the repository or files to know what the units are, ordering a multi-phase change, or you are not sure the work is one repeated mould β€” set escalate to one sentence saying what, and the main Agent, which can inspect the workspace, plans the goal instead. Still return your best plan below; it runs only if no main Agent can take the goal. Leave escalate null whenever your plan is good enough to run.',
        'Decompose the goal into the outcome it must achieve and the tasks that together deliver it. Preserve the requested action: a request to build, fix, or upgrade requires implementation, not just investigation or verification.',
        'Guidelines:',
        '- problemStatement is 1–2 sentences naming the core question or outcome of the goal, in your own words. Never copy the acceptance-criteria list into it.',
        '- Return 1–5 tasks. A complex goal (analysis, research, multi-stage delivery) must be split into several directions that can be explored independently or in sequence β€” e.g. gather the raw material, analyze it from distinct angles, then synthesize. A genuinely small single-step goal may stay as one task.',
        '- Each task.title names its direction concisely; titles must be distinct from each other and from the goal name.',
        '- Each task.instruction is a complete, self-contained brief for an autonomous agent working on that direction only: what to do, the concrete deliverable, and how that deliverable will be judged. Include only the requirements relevant to this direction β€” never paste the full goal acceptance list into every task.',
        '- Align each task\'s actions, deliverable, and pass conditions. Explicitly state whether its responsibility is investigation, implementation, or verification; avoid ambiguous briefs such as "establish a baseline" without naming the expected deliverable.',
        '- An investigation task delivers evidence-backed current state, gaps, and actionable recommendations. It may pass when it proves a capability is missing; never require an investigation-only task to prove that the missing capability already works.',
        '- For build, fix, or upgrade goals, assign explicit implementation ownership for every requested capability. Implementation tasks must inspect what exists, implement or repair missing behavior within their scope, establish a runnable environment, and demonstrate the resulting behavior. A capability matrix, blocker report, or repeated checks of an unchanged product cannot substitute for working changes.',
        '- A verification task consumes an implemented deliverable and judges its behavior. Put successful product behavior criteria on the implementation and verification tasks that own them, not on preliminary investigation. If investigation is needed first, include dependent implementation tasks that consume its findings; do not produce an investigation-and-verification-only plan for a delivery goal.',
        '- Describe known prerequisite outputs and genuine external dependencies. Do not assume the user will supply an already implemented feature that the goal asks the agent to build. Preserve explicit read-only or other authorization constraints; an investigation-only goal must not become an implementation task.',
        "- Before returning, check that executing the listed actions can satisfy each task's pass conditions and that the tasks collectively deliver the requested outcome. For example, an editor upgrade may start with a gap report, then implement editing and persistence, then verify save/reopen; the gap report does not require successful editing, and discovering a read-only viewer triggers implementation rather than repeated inspection.",
        '- Preserve every concrete URL, scope, constraint, and numeric threshold from the goal in whichever task it belongs to.',
        '- Order tasks so that earlier ones produce what later ones consume.',
        '- For each task, set dependsOn to the 0-based indices of the earlier tasks whose outputs it consumes; use [] for a task that can start immediately. A pipeline-shaped goal (gather β†’ analyze β†’ synthesize) must express those edges β€” do not mark every task independent β€” but never invent a dependency the task does not actually need.',
        '- hypothesis marks a task as a candidate answer under test: one sentence stating what the direction bets on, which its result may confirm or refute, and from which later branches may be derived. Set it only for genuinely uncertain approaches that compete with or may replace an alternative. Certain delivery steps β€” gathering material, implementing a requested change, verifying a deliverable, writing a report β€” take null. Most goals have no hypothesis at all; never invent one to decorate an ordinary step.',
        '- questions lists what you cannot determine from the goal yet whose answer would change the deliverable itself β€” its scope, audience, format, target, or a choice between incompatible directions. Never ask about anything the goal (or an answered clarification) already states, about details you can discover by working, or about preferences with a sensible default. Each carries impact (what changes with the answer), up to 4 short options when the answer is a choice, and assumption: what you will do if nobody answers.',
        '- Set blocking when the goal leaves open something that defines the deliverable itself and no default is safe: who it is for, what exactly is to be analyzed or changed, what outcome a change must achieve, or which of incompatible directions to take. A guess there produces a different deliverable, not merely a weaker one. Formats, details, and preferences with a sensible default are never blocking.',
        '- The user is asked once, before any work starts, and every blocking question goes into that single round β€” there is no later chance to ask, so list them all now rather than holding one back. Keep to what truly decides the deliverable. A goal that already states these things returns no blocking question.',
        '- assumptions lists the non-obvious readings the plan relies on that the user may want to correct; skip the obvious. Write every assumption and every answered clarification into the instructions of the tasks it affects.',
        '- rollout is how you flag ONE repeated mould: many structurally identical units that share a single reusable transformation β€” for example migrating fifty sibling stores the same way, or applying one cross-cutting change to many files. If the requirement applies the same transformation to many structurally identical sibling units (a cross-cutting change to N files or modules), you MUST set rollout instead of collapsing it into a single "apply to all" task plus a verification pipeline. Leave it null for every ordinary goal that is not such a repeated mould β€” one whose directions differ, or a genuine sequence of different steps. Setting it is a claim you must be able to defend, not a way to list more tasks.',
        "- When you set rollout, repeatable must be true only if, after replacing the concrete file / module / symbol names with placeholders, every unit's transformation steps are still the same. If they differ, it is not one batch: leave rollout null and decompose the directions normally.",
        '- rollout.unitCount is your honest count of the homogeneous units in the WHOLE goal (it will usually exceed the few tasks you list). recipeOutline names that single reusable transformation in one sentence. variants lists the axes the units vary along (e.g. axis "cold-start" with values ["yes","no"]); name an axis only if some unit actually takes each value you list.',
        '- rollout.units is the full roster of every homogeneous unit as short titles, probes first and in delivery order (list all of them, up to 60). The coordinator promotes the units after the probes from this roster one wave at a time; a unit missing here will never be delivered.',
        '- When rollout is set, tasks lists only the few REPRESENTATIVE units to run first β€” 3–5 probes, not every unit. Choose probes that cover the declared variant axes and MUST include the hardest unit. Each probe is exactly ONE unit from rollout.units and its title is exactly that unit entry, character for character, and every probe instruction follows the same template β€” the shared recipe steps, then only the specifics of that unit β€” so the probes read as one mould. Do not add tasks that verify, summarize or validate the recipe: the gate of the coordinator does that after the probes. The coordinator releases the remaining units in waves once the probes prove the class runs fully automatically; do not enumerate them here.',
        '- Write all fields in the language used by the goal.',
      ].join('\n'),
      role: 'system',
    },
    {
      content: [
        `## Goal\n${requirement}`,
        clarifications?.length
          ? `## Answered clarifications (authoritative; do not ask again)\n${clarifications
              .map((item) => `- Q: ${item.question}\n  A: ${item.answer}`)
              .join('\n')}`
          : undefined,
      ]
        .filter(Boolean)
        .join('\n\n'),
      role: 'user',
    },
  ],
});

interface GoalCriteriaDraftInput {
  context?: string;
  goal: string;
  maxCriteria: number;
}

/** Draft the standing acceptance contract shown during goal creation. */
export const chainGoalCriteriaDraft = ({
  context,
  goal,
  maxCriteria,
}: GoalCriteriaDraftInput): { messages: OpenAIChatMessage[] } => ({
  messages: [
    {
      content: [
        'You define the standing acceptance contract for a persistent autonomous goal.',
        'Turn the goal into a concise set of durable, user-reviewable pass/fail criteria that can be applied after every iteration.',
        'Guidelines:',
        '- title is a concise goal name, not a copy of the full request.',
        '- The top-level instruction is a complete, actionable task brief for the autonomous agent. Preserve every concrete URL, scope, constraint, and requested outcome from the user.',
        `- Return at most ${maxCriteria} criteria. Prefer fewer independent criteria that together define success.`,
        '- Describe outcomes and delivered artifacts, not implementation steps or one particular execution plan.',
        '- Criteria must remain valid across multiple attempts. Do not mention the current round, temporary progress, or how the agent should work.',
        '- Preserve every explicit numeric threshold, comparison operator, unit, time window, and stopping condition from the user exactly; never weaken or omit them.',
        '- When the user did not provide a numeric threshold, do not invent an arbitrary one. Define a measurable, domain-appropriate success condition from the stated outcome and make any assumption explicit for user review.',
        '- Never use unit tests, test suites, coverage, type-checks, lint, or a clean build as user-facing acceptance criteria.',
        '- List the evidence needed to judge each criterion. Use [] only when the final text answer alone is sufficient.',
        '- Use verifierType="agent" when judging requires active investigation, opening files, or multiple evidence types; use "llm" only for inline text or a directly inspectable image; use "program" only for deterministic command checks.',
        '- Set required=true when failure means the goal has not been achieved.',
        '- Set onFail="auto_repair" when another autonomous iteration can address the failure; otherwise use "manual".',
        '- Each criteria[].description is a one-sentence summary. Each criteria[].instruction is the exact, detailed judging rubric, including pass conditions, failure conditions, evidence, and important edge cases.',
        '- Write all human-facing fields in the language used by the goal.',
      ].join('\n'),
      role: 'system',
    },
    {
      content: [`## Goal\n${goal}`, context ? `\n## Context\n${context}` : '']
        .filter(Boolean)
        .join('\n'),
      role: 'user',
    },
  ],
});