@deepagents/orchestrator 7.0.2 → 7.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/arxiv/arxiv.d.ts +9 -3
- package/dist/lib/arxiv/arxiv.d.ts.map +1 -1
- package/dist/lib/arxiv/arxiv.js +3 -11
- package/dist/lib/arxiv/arxiv.js.map +2 -2
- package/dist/lib/citation.js +3 -6
- package/dist/lib/citation.js.map +2 -2
- package/dist/lib/deepplan/demo.js.map +1 -1
- package/dist/lib/deepplan/executors/research-executor.js.map +2 -2
- package/dist/lib/deepplan/plan-and-solve.js +2 -6
- package/dist/lib/deepplan/plan-and-solve.js.map +2 -2
- package/dist/lib/deepplan/planner-agent.d.ts.map +1 -1
- package/dist/lib/deepplan/planner-agent.js +1 -4
- package/dist/lib/deepplan/planner-agent.js.map +2 -2
- package/dist/lib/deepplan/replanner-agent.d.ts.map +1 -1
- package/dist/lib/deepplan/replanner-agent.js +1 -2
- package/dist/lib/deepplan/replanner-agent.js.map +2 -2
- package/dist/lib/deepresearch.v0.d.ts.map +1 -1
- package/dist/lib/deepresearch.v0.js +21 -18
- package/dist/lib/deepresearch.v0.js.map +2 -2
- package/dist/lib/deepresearch.v1.d.ts.map +1 -1
- package/dist/lib/deepresearch.v1.js +3 -5
- package/dist/lib/deepresearch.v1.js.map +2 -2
- package/dist/lib/deepwiki/complete-wiki.js +4 -2
- package/dist/lib/deepwiki/complete-wiki.js.map +2 -2
- package/dist/lib/deepwiki/deepwiki.js +4 -2
- package/dist/lib/deepwiki/deepwiki.js.map +2 -2
- package/dist/lib/deepwiki/gitignore-agent.d.ts +4 -2
- package/dist/lib/deepwiki/gitignore-agent.d.ts.map +1 -1
- package/dist/lib/deepwiki/gitignore-agent.js +2 -3
- package/dist/lib/deepwiki/gitignore-agent.js.map +2 -2
- package/dist/lib/deepwiki/outline-agent.d.ts.map +1 -1
- package/dist/lib/deepwiki/outline-agent.js +4 -2
- package/dist/lib/deepwiki/outline-agent.js.map +2 -2
- package/dist/lib/deepwiki/wiki-writer.js +4 -2
- package/dist/lib/deepwiki/wiki-writer.js.map +2 -2
- package/dist/lib/deepwiki/writer.d.ts.map +1 -1
- package/dist/lib/deepwiki/writer.js +5 -5
- package/dist/lib/deepwiki/writer.js.map +2 -2
- package/dist/lib/evolving.js +1 -1
- package/dist/lib/evolving.js.map +2 -2
- package/dist/lib/openai-deepresearch/clarrify-agent.d.ts +5 -1
- package/dist/lib/openai-deepresearch/clarrify-agent.d.ts.map +1 -1
- package/dist/lib/openai-deepresearch/lead-research.d.ts.map +1 -1
- package/dist/lib/openai-deepresearch/lead-research.js +2 -3
- package/dist/lib/openai-deepresearch/lead-research.js.map +2 -2
- package/dist/lib/openai-deepresearch/openai-deepresearch.js +6 -8
- package/dist/lib/openai-deepresearch/openai-deepresearch.js.map +3 -3
- package/dist/lib/openai-deepresearch/reasearcher.js.map +2 -2
- package/dist/lib/openai-deepresearch/research-brief.d.ts +3 -1
- package/dist/lib/openai-deepresearch/research-brief.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/deepplan/plan-and-solve.ts", "../../../src/lib/deepplan/executors/generic-executor.ts", "../../../src/lib/deepplan/planner-agent.ts", "../../../src/lib/deepplan/replanner-agent.ts", "../../../src/lib/deepplan/synthesizer.ts"],
|
|
4
|
-
"sourcesContent": ["import { pl } from 'zod/v4/locales';\n\nimport {\n type Agent,\n type ContextVariables,\n execute,\n generate,\n user,\n} from '@deepagents/agent';\n\nimport {\n type ExecutionContext,\n formatStepForExecutor,\n} from './executors/generic-executor.ts';\nimport { type PlanStep, plan } from './planner-agent.ts';\nimport { replan } from './replanner-agent.ts';\nimport { synthesize } from './synthesizer.ts';\n\n/**\n * Lifecycle hooks for Plan-and-Solve execution.\n *\n * These hooks allow you to intercept and react to key points in the execution lifecycle,\n * enabling progress tracking, persistence, notifications, and custom logic injection.\n *\n * **Important:** You can manually terminate the execution loop by setting `context.is_complete = true`\n * in either hook. This allows you to stop execution early based on custom conditions (e.g., user cancellation,\n * resource limits, or completion detection).\n */\nexport interface PlanHooks {\n /**\n * Hook executed immediately after the initial plan is created.\n *\n * **When to use:**\n * - Review and validate the initial plan\n * - Persist the initial plan to storage\n * - Log the planned steps for auditing\n * - Modify the plan before execution starts\n * - Display the plan to users for confirmation\n * - Estimate total execution time or cost\n * - **Terminate execution before it starts** by setting `context.is_complete = true`\n *\n * **Timing:** After the planner agent creates the initial plan, before any step execution\n *\n * @param context - Initial execution context with the complete plan\n * @returns Modified context (or undefined to keep current context)\n *\n * @example\n * ```typescript\n * onInitialPlan: async (context) => {\n * // Log the initial plan\n * console.log(`Plan created with ${context.current_plan.length} steps`);\n *\n * // Save for later review\n * await writeFile('initial_plan.json', JSON.stringify(context, null, 2));\n *\n * // Validate plan isn't too complex\n * if (context.current_plan.length > 20) {\n * console.error('Plan too complex, aborting');\n * context.is_complete = true;\n * }\n *\n * return context;\n * }\n * ```\n */\n onInitialPlan?: (\n context: ExecutionContext,\n ) => Promise<ExecutionContext | void> | ExecutionContext | void;\n\n /**\n * Hook executed before replanning occurs (after a step completes).\n *\n * **When to use:**\n * - Save execution progress/checkpoints\n * - Log intermediate results for auditing\n * - Modify context before the replanner evaluates it\n * - Track execution metrics\n * - Stream progress updates to a client/UI\n * - **Terminate execution early** by setting `context.is_complete = true`\n *\n * **Timing:** After a step executes, before the replanner agent runs\n *\n * @param context - Current execution state including completed step results\n * @returns Modified context (or undefined to keep current context)\n */\n beforeReplan?: (\n context: ExecutionContext,\n ) => Promise<ExecutionContext | void> | ExecutionContext | void;\n\n /**\n * Hook executed after replanning occurs and the plan is updated.\n *\n * **When to use:**\n * - Persist the updated plan to storage\n * - Log plan changes and reasoning\n * - Notify users of plan adjustments\n * - Update progress indicators\n * - Implement custom plan filtering/validation\n * - Stream plan updates to a dashboard\n * - Send alerts if major changes occur\n * - **Terminate execution early** by setting `context.is_complete = true`\n *\n * **Timing:** After the replanner agent has updated the plan, before next step execution\n *\n * @param context - Current execution state with updated plan\n * @returns Modified context (or undefined to keep current context)\n */\n afterReplan?: (\n context: ExecutionContext,\n ) => Promise<ExecutionContext | void> | ExecutionContext | void;\n}\n\nasync function runExecutor(\n agent: Agent<any, any>,\n context: ExecutionContext,\n step: PlanStep,\n state: ContextVariables,\n) {\n const { text } = await generate(\n agent,\n [user(formatStepForExecutor(step, context))],\n state,\n );\n return {\n ...context,\n variables: { ...context.variables },\n step_results: [...context.step_results, text],\n };\n}\n\n/**\n * Executes a Plan-and-Solve Plus (PS+) workflow with adaptive replanning.\n *\n * This function creates a complete autonomous task execution pipeline:\n * 1. Plans the task into specific steps\n * 2. Executes each step sequentially\n * 3. Replans after each execution to adapt based on results\n * 4. Synthesizes results into a final output\n *\n * @param options - Configuration for the plan-and-solve execution\n * @param options.input - The user's request or task description\n * @param options.executor - The agent that will execute individual plan steps\n * @param options.state - Execution context variables (e.g., repo_path, API keys)\n * @param options.hooks - Optional lifecycle hooks for extensibility (see {@link PlanHooks})\n *\n * @example\n * ```typescript\n * const result = await planAndSolve({\n * input: \"Find all AI startups that raised Series A\",\n * executor: researchExecutor,\n * state: {\n * repo_path: process.cwd()\n * },\n * environment: {\n * executor_type: 'research',\n * available_tools: ['browser_search', 'scratchpad'],\n * domain: 'market research',\n * capabilities: ['web search', 'source verification', 'numerical data extraction']\n * },\n * },\n * hooks: {\n * beforeReplan: async (context) => {\n * // Save progress before replanning\n * await saveCheckpoint(context);\n * return context;\n * },\n * afterReplan: async (context) => {\n * // Log plan updates\n * console.log(`Updated plan: ${context.current_plan.length} steps remaining`);\n * return context;\n * }\n * }\n * });\n * ```\n */\nexport async function planAndSolve(options: {\n input: string;\n executor: Agent<any, any>;\n state: ContextVariables;\n hooks?: PlanHooks;\n}) {\n let context = await plan(options.input);\n const plans = [context.current_plan];\n\n if (options.hooks?.onInitialPlan) {\n const initialPlanResult = await options.hooks.onInitialPlan(context);\n if (initialPlanResult) {\n context = initialPlanResult;\n }\n }\n\n if (context.is_complete) {\n return synthesize(context.step_results, context.original_request);\n }\n\n while (context.current_plan.length > 0) {\n const currentStep = context.current_plan[0];\n context = await runExecutor(\n options.executor,\n context,\n currentStep,\n options.state,\n );\n if (options.hooks?.beforeReplan) {\n const beforeReplanResult = await options.hooks.beforeReplan(context);\n if (beforeReplanResult) {\n context = beforeReplanResult;\n }\n }\n if (context.is_complete) {\n // User requested early termination\n break;\n }\n\n // -- Start Replanning --\n context = await replan(context);\n plans.push(context.current_plan);\n // -- End Replanning --\n\n if (options.hooks?.afterReplan) {\n const afterReplanResult = await options.hooks.afterReplan(context);\n if (afterReplanResult) {\n context = afterReplanResult;\n }\n }\n\n if (context.is_complete) {\n break;\n }\n }\n\n options.state.plans = plans;\n return synthesize(context.step_results, context.original_request);\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\n\nimport { agent } from '@deepagents/agent';\nimport { scratchpad_tool, search_content_tool } from '@deepagents/toolbox';\n\nimport type { PlanStep, PlannerOutput } from '../planner-agent.ts';\n\n/**\n * Executor Agent\n *\n * Executes individual plan steps while:\n * 1. Tracking what information is gathered\n * 2. Extracting numerical variables from results\n * 3. Calculating intermediate results with attention to accuracy\n * 4. Paying attention to correct numerical calculation and commonsense\n * 5. Making observations about findings\n * 6. Noting any issues or unexpected results\n */\nexport const executorAgent = agent({\n name: 'executor_agent',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0 },\n }),\n }),\n prompt: `\n <SystemContext>\n You are a precise execution agent that follows plans and gathers information systematically.\n You pay close attention to details and track what you find.\n </SystemContext>\n\n <Identity>\n Your task is to execute a single step from a plan and report back with structured results.\n You are part of an adaptive planning system where your findings will influence future steps.\n </Identity>\n\n <ExecutionPrinciples>\n 1. **Focus on the Objective**\n - Understand exactly what this step is asking for\n - Review the expected outcome\n - Stay focused on gathering that specific information\n\n 2. **Extract Variables and Numerals**\n - As you find information, extract key data points\n - **CRITICAL: Extract numerical values separately from units**\n - Store them as structured variables (e.g., {product_name: \"iPhone 15\", release_date: \"Sep 2024\", release_month: 9, release_year: 2024})\n - Track counts, amounts, dates, and measurements explicitly\n - These variables help track progress across steps\n\n 3. **Calculate Intermediate Results**\n - Pay attention to correct numerical calculation and commonsense\n - Perform any required calculations step-by-step\n - Verify numerical accuracy (e.g., date ranges, counts, sums)\n - Check results against common sense (e.g., dates in valid range, reasonable quantities)\n - Show your calculation work when computing values\n\n 4. **Verify Results**\n - Carefully review what you find for accuracy\n - Ensure numerical values are consistent\n - Check for logical coherence\n - Note anything unexpected or inconsistent\n\n 5. **Make Observations**\n - What patterns did you notice?\n - What numerical trends are apparent?\n - What might affect subsequent steps?\n\n 6. **Note Issues**\n - Were there any calculation difficulties?\n - Was the information hard to find?\n - Were there any errors or ambiguities?\n </ExecutionPrinciples>\n\n\n <ContextAwareness>\n You will be given:\n - The current step to execute\n - The original user request (for context)\n - Variables gathered from previous steps\n - Data collected so far\n\n Use this context to:\n - Avoid re-gathering information you already have\n - Build on previous findings\n - Connect new information to what's already known\n </ContextAwareness>\n\n <ReportingGuidelines>\n Your report should include:\n\n 1. **Status**\n - success: Step completed as expected\n - partial: Got some but not all information\n - failed: Could not complete the step\n\n 2. **Data Gathered**\n - Summarize what you found\n - Be specific and factual\n - Include enough detail to be useful\n\n 3. **Extracted Variables and Numerals**\n - Key data points you discovered\n - Format as key-value pairs with numerical values separated\n - Examples: {count: 5, average_price: 299, latest_date: \"2024-01-15\", date_month: 1, date_year: 2024}\n - Include any intermediate calculations performed\n\n 4. **Observations**\n - Notable patterns or insights\n - Anything that might affect the plan\n - Connections to the overall goal\n\n 5. **Issues**\n - Any problems encountered\n - Missing or unclear information\n - Limitations of what you found\n </ReportingGuidelines>\n\n <Examples>\n Step: \"Find Apple's official announcements from the past 3 months\"\n Context: {company: \"Apple\", timeframe: \"3 months\"}\n\n Good Execution:\n - Use browser_search to find Apple newsroom/press releases\n - Filter results to last 3 months\n - List the announcements found\n - Extract count, dates, types\n - Note any gaps or issues\n\n Report (with numerical extraction):\n - Status: success\n - Data: \"Found 15 press releases from Apple newsroom (Oct-Dec 2024)\"\n - Variables: {\n press_release_count: 15,\n date_range: \"Oct-Dec 2024\",\n start_month: 10,\n end_month: 12,\n year: 2024,\n months_covered: 3\n }\n - Observations: [\"Mix of product, service, and corporate announcements\", \"Exactly covers the requested 3-month timeframe\"]\n - Issues: []\n </Examples>\n\n <CriticalInstructions>\n - Execute the step precisely as described\n - **Extract numerical variables and their values separately**\n - **Pay attention to correct numerical calculation and commonsense**\n - Calculate and verify intermediate results step-by-step\n - Report accurately with verified numbers - your results influence future steps\n - Use the context from previous steps to work smarter\n - If you can't find something, say so clearly\n - Double-check all numerical values for accuracy\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured step result with:\n - status (success/partial/failed)\n - data_gathered (summary of findings)\n - extracted_variables (key-value pairs)\n - observations (notable insights)\n - issues (any problems)\n </OutputFormat>\n `,\n tools: {\n scratchpad: scratchpad_tool,\n search: search_content_tool,\n // browser_search: groq.tools.browserSearch({}),\n },\n});\n\n/**\n * Format step for executor with full context\n */\nexport function formatStepForExecutor(\n step: PlanStep,\n context: ExecutionContext,\n): string {\n return `\n<UserRequest>${context.original_request}</UserRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<PreviousSteps>\n${context.step_results.length ? context.step_results.map((result, i) => `Step ${i + 1}: ${result}`).join('\\n') : 'No previous steps'}\n</PreviousSteps>\n\n<CurrentStep>\nStep Description: ${step.description}\nExpected Outcome: ${step.expected_outcome}\n</CurrentStep>\n\nExecute this step and provide a detailed report of what you find.\n `.trim();\n}\n\nexport function createExecutionContext(\n request: string,\n plannerOutput: PlannerOutput,\n): ExecutionContext {\n return {\n original_request: request,\n understanding: plannerOutput.understanding,\n initial_plan: plannerOutput.steps,\n current_plan: [...plannerOutput.steps],\n variables: { ...plannerOutput.variables },\n step_results: [],\n is_complete: false,\n };\n}\n\nexport interface ExecutionContext {\n // Request information\n original_request: string;\n understanding: string;\n\n // Planning state\n initial_plan: PlanStep[];\n current_plan: PlanStep[];\n\n // Data collected\n variables: Record<string, string | number | boolean>;\n\n // Execution history\n step_results: string[];\n\n // Status\n is_complete: boolean;\n success_criteria_met?: boolean;\n}\n", "import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { lmstudio } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n createBashTool,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport { createExecutionContext } from './executors/generic-executor.ts';\n\nconst PlanStepSchema = z.object({\n description: z\n .string()\n .describe('What information to find or action to take'),\n expected_outcome: z\n .string()\n .describe('What should be accomplished by this step'),\n});\n\nexport const PlannerOutputSchema = z.object({\n understanding: z\n .string()\n .describe('Clear understanding of what the user is asking for and why'),\n variables: z\n .record(z.string(), z.any())\n .describe(\n 'Key variables with numerical values extracted from the request. Examples: {company: \"Apple\", timeframe_value: 3, timeframe_unit: \"months\", min_salary: 150000}',\n ),\n constraints: z\n .array(z.string())\n .default([])\n .describe('Any constraints or limitations mentioned'),\n success_criteria: z\n .string()\n .describe('How to know if the task was completed successfully'),\n steps: z\n .array(PlanStepSchema)\n .min(1)\n .max(4)\n .describe('Ordered list of steps to execute'),\n});\n\nexport type PlanStep = z.infer<typeof PlanStepSchema>;\nexport type PlannerOutput = z.infer<typeof PlannerOutputSchema>;\n\n/**\n * Environment context that describes the execution capabilities.\n * This helps the planner create steps that are actually executable.\n */\nexport interface PlanEnvironment {\n /**\n * Type of executor that will execute the steps\n * @example 'research', 'hackernews', 'generic', 'product_manager'\n */\n executor_type: string;\n\n /**\n * Available tools the executor has access to\n * @example ['browser_search', 'scratchpad'], ['hackernews_search', 'scratchpad']\n */\n available_tools: string[];\n\n /**\n * Domain or task category\n * @example 'market research', 'hackernews sentiment analysis', 'code repository search'\n */\n domain: string;\n\n /**\n * High-level capabilities description\n * @example ['web search', 'source verification', 'numerical data extraction']\n */\n capabilities?: string[];\n}\n\n/**\n * Planner agent that creates structured execution plans:\n * 1. Understanding Phase: Deeply understand the user's request\n * 2. Variable Extraction: Extract relevant variables and their corresponding numerical values\n * 3. Plan Devising: Break down into specific, actionable steps\n * 4. Success Criteria: Define how to know when the task is complete\n *\n * Enhanced with adaptive replanning for dynamic task execution.\n */\nconst plannerModel = wrapLanguageModel({\n model: lmstudio('google/gemma-3-12b'),\n // model: groq('moonshotai/kimi-k2-instruct-0905'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.3 }, // Slightly creative for better planning\n }),\n});\n\nfunction createPlannerPrompt(context?: {\n environment?: PlanEnvironment;\n}): string {\n return `\n <SystemContext>\n You are an expert planning agent that creates adaptive, well-structured plans.\n Plans are executed step-by-step and adjusted as needed based on findings.\n </SystemContext>\n\n <ExecutionEnvironment>\n ${formatEnvironmentContext(context?.environment)}\n\n CRITICAL: Create steps that match the available tools and domain.\n - Only plan steps that can be executed with the available tools\n - Tailor your approach to the executor's domain and capabilities\n - Don't ask for actions the executor cannot perform\n - Frame steps in terms the executor understands\n </ExecutionEnvironment>\n\n <Identity>\n Your task is to deeply understand user requests and create detailed execution plans.\n You excel at:\n - Understanding what users truly need\n - Extracting key variables and constraints\n - Breaking complex tasks into clear, actionable steps\n - Defining success criteria\n - Creating executable plans that match available capabilities\n </Identity>\n\n <PlanningMethodology>\n Follow this two-phase approach:\n First understand the problem, extract relevant variables and their numerical values,\n and devise a plan. Then the plan will be carried out step by step.\n\n ## PHASE 1: Understanding & Analysis\n\n 1. **Understand the Request**\n - What is the user asking for?\n - Why do they need this information?\n - What is the core intent behind the request?\n\n 2. **Extract Variables and Numerals**\n - Identify all key variables (e.g., company names, time periods, categories)\n - **CRITICALLY: Extract numerical values and their units** (e.g., \"3 months\", \"$150k\", \"5 products\")\n - Map variables to their corresponding numerical values (e.g., {timeframe: 3, unit: \"months\"})\n - Note any implicit variables and numerical relationships\n - Identify calculations that may be required\n\n 3. **Identify Constraints**\n - Time constraints (e.g., \"last 3 months\", \"2024\")\n - Category constraints (e.g., \"AI startups\", \"developer tools\")\n - Scope constraints (e.g., \"in Europe\", \"Y Combinator companies\")\n - Quality constraints (e.g., \"above $150k\", \"4-day work week\")\n\n 4. **Define Success**\n - How will we know the task is complete?\n - What must be included in the final result?\n - What level of detail is needed?\n\n ## PHASE 2: Plan Creation\n\n 5. **Devise Subtasks**\n - Break the request into smaller, specific steps\n - Each step should gather ONE specific type of information\n - Make each step independently executable\n\n 6. **Specify Expected Outcomes**\n - For each step, define what should be accomplished\n - This helps the executor know what to deliver\n - This helps the replanner know if the step succeeded\n\n </PlanningMethodology>\n\n <StepDesignPrinciples>\n Each step should:\n \u2713 Be SPECIFIC and ACTIONABLE\n \u2713 Focus on gathering ONE type of information\n \u2713 Start with action verbs: \"Find...\", \"Identify...\", \"Determine...\", \"Extract...\"\n \u2713 Have a clear expected outcome\n \u2713 Be verifiable (can check if it succeeded)\n\n Avoid:\n \u2717 Vague steps like \"Research the topic\"\n \u2717 Implementation details like \"Query the database\"\n \u2717 Multiple objectives in one step\n \u2717 Summary/aggregation steps (that happens automatically)\n \u2717 Delivery steps (system handles that)\n </StepDesignPrinciples>\n\n <Examples>\n Example 1: Web Research Task\n\n User Request: \"Did Apple release any new products in the past 3 months?\"\n Environment: Executor Type: research, Tools: [browser_search, scratchpad], Domain: market research\n\n Understanding: User wants to know about recent Apple product launches\n\n Variables (with numerical values extracted):\n - company: \"Apple\"\n - timeframe_value: 3\n - timeframe_unit: \"months\"\n - info_type: \"product releases\"\n\n Constraints:\n - Only products (not services, updates, etc.)\n - Only last 3 months\n - Apple only (not subsidiaries)\n\n Success Criteria: List of Apple products released in last 3 months with names and dates\n\n Steps (tailored to browser_search capability):\n 1. Search Apple's newsroom for product announcements from the past 3 months\n Expected: List of official press releases and announcements\n\n 2. Identify product-specific announcements (filter out software updates, services)\n Expected: Subset of announcements that are actual product launches\n\n 3. Extract product names and release dates from announcements\n Expected: Product name, date, and brief description for each\n\n ---\n\n Example 2: HackerNews Research Task\n\n User Request: \"What does the tech community think about Rust vs Go?\"\n Environment: Executor Type: hackernews, Tools: [hackernews_search, scratchpad], Domain: hackernews sentiment analysis\n\n Understanding: User wants to understand tech community opinions comparing Rust and Go\n\n Variables:\n - languages: [\"Rust\", \"Go\"]\n - info_type: \"sentiment comparison\"\n\n Constraints:\n - HackerNews community only\n - Recent discussions preferred\n\n Success Criteria: Summary of HN community sentiment on Rust vs Go with key points from both sides\n\n Steps (tailored to hackernews_search capability):\n 1. Search HackerNews for recent discussions about Rust programming language\n Expected: Stories and comments about Rust with engagement metrics\n\n 2. Search HackerNews for recent discussions about Go programming language\n Expected: Stories and comments about Go with engagement metrics\n\n 3. Search HackerNews for direct comparisons between Rust and Go\n Expected: Discussions explicitly comparing the two languages\n </Examples>\n\n <CriticalInstructions>\n - Take time to truly UNDERSTAND the request before planning\n - **Extract ALL relevant variables with their numerical values**\n - Separate numerical values from their units (e.g., 3 and \"months\", not \"3 months\")\n - Identify any calculations or comparisons that will be needed\n - Create focused steps that each have ONE clear purpose\n - Define what success looks like\n - Steps should be about WHAT to find, not HOW to find it\n - Remember: the plan will be adjusted as execution proceeds\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured plan with:\n 1. Understanding of the request\n 2. Extracted variables (as key-value pairs)\n 3. Identified constraints\n 4. Success criteria\n 5. Ordered list of steps with expected outcomes.\n </OutputFormat>\n `;\n}\n\n/**\n * Format environment context for the planner prompt\n */\nfunction formatEnvironmentContext(environment?: PlanEnvironment): string {\n if (!environment) {\n return `No specific environment provided. Infer environment from user request.`;\n }\n\n const capabilitiesText = environment.capabilities\n ? `\\n Capabilities: ${environment.capabilities.join(', ')}`\n : '';\n\n return `\n Executor Type: ${environment.executor_type}\n Domain: ${environment.domain}\n Available Tools: ${environment.available_tools.join(', ')}${capabilitiesText}\n `.trim();\n}\n\n/**\n * Create an execution plan for the given user request\n *\n * @param userRequest - The user's task or question\n * @param environment - Optional execution environment describing available tools and domain\n */\nexport async function plan(\n userRequest: string,\n state: { environment?: PlanEnvironment } = {},\n) {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `planner-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'planner_agent',\n role: 'You are an expert planning agent that creates adaptive, well-structured plans.',\n objective:\n 'Deeply understand user requests and return executable plans with structured variables, constraints, success criteria, and steps.',\n }),\n fragment('planner_instructions', createPlannerPrompt(state)),\n user(userRequest),\n );\n\n const plannerOutput = structuredOutput({\n model: plannerModel,\n context,\n schema: PlannerOutputSchema,\n });\n\n const output = await plannerOutput.generate();\n return createExecutionContext(\n userRequest,\n output as {\n understanding: string;\n variables: Record<string, unknown>;\n constraints: string[];\n success_criteria: string;\n steps: { description: string; expected_outcome: string }[];\n },\n );\n}\n", "import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { lmstudio } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n createBashTool,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport { type ExecutionContext } from './executors/generic-executor.ts';\nimport type { PlanStep } from './planner-agent.ts';\n\nconst PlanStepSchema = z.object({\n description: z\n .string()\n .describe('What information to find or action to take'),\n expected_outcome: z\n .string()\n .describe('What should be accomplished by this step'),\n});\nexport const ReplanDecisionSchema = z.object({\n reasoning: z.string().describe('Why this replanning decision was made'),\n should_continue: z.boolean().describe('Should we continue executing?'),\n remaining_steps: z\n .array(PlanStepSchema)\n .max(4)\n .describe('Updated list of remaining steps'),\n new_insights: z\n .string()\n .describe('New insights learned that affected the plan'),\n});\n\nexport type ReplanDecision = z.infer<typeof ReplanDecisionSchema>;\n\n/**\n * Replanner Agent\n *\n * After each step execution, the replanner:\n * 1. Reviews what was accomplished vs what was expected\n * 2. Analyzes how this affects the remaining plan\n * 3. Decides if the plan needs adjustment\n * 4. Updates remaining steps based on new information\n *\n * This creates an adaptive planning system that learns as it executes.\n */\nconst replannerModel = wrapLanguageModel({\n // model: groq('moonshotai/kimi-k2-instruct-0905'),\n model: lmstudio('google/gemma-3-12b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.1 },\n }),\n});\n\nfunction createReplannerPrompt(): string {\n return `\n <SystemContext>\n You are an adaptive replanning agent.\n After each step execution, you review progress and adjust the plan as needed.\n </SystemContext>\n\n <Identity>\n Your role is to ensure the execution stays on track and adapts to new information.\n You analyze results, learn from findings, and modify the plan to achieve the goal efficiently.\n </Identity>\n\n <ReplanningPrinciples>\n 1. **Review Results**\n - What was the step supposed to accomplish?\n - What was actually accomplished?\n - Was it successful, partial, or failed?\n\n 2. **Analyze Impact**\n - How do these results affect the overall goal?\n - What did we learn that we didn't know before?\n - Does this change what we need to do next?\n\n 3. **Assess Remaining Plan**\n - Are the remaining steps still appropriate?\n - Do we need additional steps?\n - Can we skip any steps?\n - Should we change the order?\n\n 4. **Make Decisions**\n - Should we continue with the plan?\n - What adjustments are needed?\n - How significant are the changes?\n\n 5. **Update Steps**\n - Modify remaining steps based on learnings\n - Add new steps if needed\n - Remove unnecessary steps\n - Reorder for efficiency\n </ReplanningPrinciples>\n\n <WhenToMakeChanges>\n ## Add Steps When:\n - Found more information than expected (need to filter/process)\n - Discovered new relevant categories (need to explore)\n - Hit limitations (need alternative approaches)\n - Found partial data (need additional sources)\n\n ## Remove Steps When:\n - Already got the information another way\n - The step is no longer relevant based on findings\n - The goal can be achieved without it\n - It's redundant with completed steps\n\n ## Modify Steps When:\n - Need to be more specific based on findings\n - Scope needs adjustment (broader or narrower)\n - Better approach became apparent\n - Need to work around issues discovered\n\n ## Keep Steps When:\n - They're still relevant and needed\n - Results so far support the original plan\n - No better alternative is apparent\n </WhenToMakeChanges>\n\n <ChangeMagnitude>\n Classify plan changes as:\n - **none**: No changes needed, continue as planned\n - **minor**: Small tweaks (wording, ordering, slight additions)\n - **major**: Significant restructuring (many new steps, removed steps, different approach)\n </ChangeMagnitude>\n\n <DecisionMaking>\n Decide if execution should continue:\n\n \u2713 **Continue** when:\n - More steps are needed to complete the goal\n - Making progress toward the objective\n - Can adapt the plan to handle issues\n\n \u2717 **Stop** when:\n - Goal has been fully achieved\n - Discovered the answer isn't available\n - Fundamental blocker that can't be worked around\n - Success criteria have been met\n </DecisionMaking>\n\n <Examples>\n Scenario 1: Found more data than expected\n\n Step Result: Found 50 press releases instead of expected 10-15\n\n Replanning Decision:\n - Reasoning: Large volume needs filtering before analysis\n - Changes: major\n - Add step: \"Filter press releases to product-related only\"\n - Modify next step: Focus on filtered subset\n - Continue: true\n\n ---\n\n Scenario 2: Got exactly what was needed\n\n Step Result: Successfully identified 3 products with all details\n\n Replanning Decision:\n - Reasoning: Already have complete information\n - Changes: none or minor (maybe skip redundant verification step)\n - Continue: Check if success criteria met, might stop\n\n ---\n\n Scenario 3: Information not available\n\n Step Result: Official source doesn't have the data\n\n Replanning Decision:\n - Reasoning: Need alternative data source\n - Changes: major\n - Add step: \"Search tech news sites for announcements\"\n - Continue: true (with new approach)\n </Examples>\n\n <ContextAwareness>\n You have access to:\n - Original user request\n - Initial understanding and success criteria\n - All previous step results\n - Current variables and gathered data\n - The remaining steps in the plan\n\n Use this to make informed replanning decisions.\n </ContextAwareness>\n\n <CriticalInstructions>\n - Be thoughtful but decisive\n - Adapt the plan based on ACTUAL results, not assumptions\n - Keep the end goal in mind (user's original request)\n - Don't keep executing steps if the goal is already achieved\n - Don't abandon the plan too easily - adapt when possible\n - Make changes that improve efficiency and effectiveness\n - Explain your reasoning clearly\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a replanning decision with:\n - reasoning: Why you're making this decision\n - should_continue: true/false\n - remaining_steps: Updated list of steps to execute\n - new_insights: What you learned that affected the plan\n </OutputFormat>\n `;\n}\n\nfunction formatReplannerPrompt(\n context: ExecutionContext,\n remainingSteps: PlanStep[],\n): string {\n const executionHistory = context.step_results\n .map((r, i) => `Step ${i}: ${r}`)\n .join('\\n');\n\n return `\n<OriginalRequest>${context.original_request}</OriginalRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<SuccessCriteria>\nCheck if we have achieved the goal of the original request.\n</SuccessCriteria>\n\n<ExecutionHistory>\n${executionHistory}\n</ExecutionHistory>\n\n<MostRecentStep>\n${context.step_results.at(-1) ?? 'No steps executed yet'}\n</MostRecentStep>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<RemainingSteps>\n${remainingSteps.length > 0 ? remainingSteps.map((s, i) => `${i}. ${s.description} (Expected: ${s.expected_outcome})`).join('\\n') : 'No remaining steps'}\n</RemainingSteps>\n\n<YourTask>\nReview the most recent step result and determine:\n1. Should we continue execution?\n2. Does the plan need adjustment based on what we found?\n3. What should the remaining steps be?\n\nConsider:\n- Did we find what we were looking for?\n- Is the goal achievable with the current approach?\n- Do results suggest a better path forward?\n- Have we already met the success criteria?\n</YourTask>\n `.trim();\n}\n\nexport async function replan(context: ExecutionContext) {\n const remainingSteps = context.current_plan.slice(1);\n const plannerContext = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `replanner-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n plannerContext.set(\n persona({\n name: 'replanner_agent',\n role: 'You are an adaptive replanning agent.',\n objective:\n 'Review execution progress and adjust remaining steps so the plan reaches the original goal efficiently.',\n }),\n fragment('replanner_instructions', createReplannerPrompt()),\n user(formatReplannerPrompt(context, remainingSteps)),\n );\n\n const replannerOutput = structuredOutput({\n model: replannerModel,\n context: plannerContext,\n schema: ReplanDecisionSchema,\n });\n\n const output = await replannerOutput.generate();\n const decision = output as {\n remaining_steps: typeof context.current_plan;\n should_continue: boolean;\n };\n return {\n ...context,\n current_plan: decision.remaining_steps,\n is_complete: !decision.should_continue,\n };\n}\n", "import { agent, execute, lmstudio, user } from '@deepagents/agent';\n\n/**\n * Synthesizer agent that compiles step results into a final answer\n * Applies numerical accuracy and commonsense validation\n */\nconst synthesizer = agent({\n name: 'synthesizer_agent',\n model: lmstudio('google/gemma-3-12b'),\n prompt: `\n\t\t<SystemContext>\n\t\t\tYou are a synthesizer agent that compiles the results of executed plan steps into a final answer.\n\t\t\tYou ensure accuracy and coherence in the final output.\n\t\t</SystemContext>\n\n\t\t<Identity>\n\t\t\tYour task is to take the individual step results and synthesize them into a coherent final response that addresses the original user request.\n\t\t</Identity>\n\n\t\t<ConstraintDetection>\n\t\t\t**CRITICAL: Check the original request for output constraints FIRST**\n\t\t</ConstraintDetection>\n\n\t\t<SynthesisPrinciples>\n\t\t\t1. **Verify Numerical Accuracy**\n\t\t\t\t - Check all numerical values for consistency\n\t\t\t\t - Ensure calculations are correct across steps\n\t\t\t\t - Verify dates, counts, and measurements make sense\n\n\t\t\t2. **Apply Commonsense Validation**\n\t\t\t\t - Do the results make logical sense?\n\t\t\t\t - Are there any contradictions or inconsistencies?\n\t\t\t\t - Do temporal relationships align (e.g., dates in proper order)?\n\n\t\t\t3. **Aggregate Intermediate Results**\n\t\t\t\t - Combine findings from multiple steps coherently\n\t\t\t\t - Preserve important numerical details\n\t\t\t\t - Show clear connections between steps\n\n\t\t\t4. **Show the Answer Clearly**\n\t\t\t\t - Present the final answer in a structured format\n\t\t\t\t - Highlight key numerical findings\n\t\t\t\t - Make the conclusion explicit and unambiguous\n\t\t</SynthesisPrinciples>\n\n\t\t<Instructions>\n\t\t\t1. **Read the original user request carefully** and identify any output constraints\n\t\t\t2. Review all step results carefully\n\t\t\t3. **Verify numerical consistency and commonsense**\n\t\t\t4. If constraints exist: compile results according to constraints (minimal output)\n\t\t\t5. If no constraints: synthesize insights into a comprehensive answer\n\t\t\t6. **Show the answer clearly** with verified numbers and logical coherence\n\n\t\t\tCRITICAL:\n\t\t\t- Always prioritize explicit constraints over comprehensive analysis\n\t\t\t- When in doubt about constraints, prefer minimal output\n\t\t\t- Verify numerical accuracy before finalizing\n\t\t\t- Check for commonsense and logical coherence\n\t\t\t- The final answer should be well-structured and easy to understand\n\t\t</Instructions>\n\t`,\n});\n\nexport async function synthesize(\n stepResults: string[],\n originalRequest: string,\n) {\n const stepResultsText = stepResults\n .map((step, index) => `Step ${index + 1} Result:\\n${step}`)\n .join('\\n\\n');\n\n const prompt = `\nOriginal User Request:\n${originalRequest}\n\n---\n\n${stepResultsText}\n `.trim();\n\n return (await execute(synthesizer, [user(prompt)], {})).text;\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,OAAmB;AAEnB;AAAA,EAIE;AAAA,EACA,QAAAA;AAAA,OACK;;;ACRP,SAAS,YAAY;AACrB,SAAS,2BAA2B,yBAAyB;AAE7D,SAAS,aAAa;AACtB,SAAS,iBAAiB,2BAA2B;AAe9C,IAAM,gBAAgB,MAAM;AAAA,EACjC,MAAM;AAAA,EACN,OAAO,kBAAkB;AAAA,IACvB,OAAO,KAAK,oBAAoB;AAAA,IAChC,YAAY,0BAA0B;AAAA,MACpC,UAAU,EAAE,aAAa,EAAE;AAAA,IAC7B,CAAC;AAAA,EACH,CAAC;AAAA,EACD,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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S,wBAAwB,oBAAoB,KAAK,CAAC;AAAA,IAC3D,KAAK,WAAW;AAAA,EAClB;AAEA,QAAM,gBAAgB,iBAAiB;AAAA,IACrC,OAAO;AAAA,IACP;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AAED,QAAM,SAAS,MAAM,cAAc,SAAS;AAC5C,SAAO
|
|
4
|
+
"sourcesContent": ["import { pl } from 'zod/v4/locales';\n\nimport {\n type Agent,\n type ContextVariables,\n execute,\n generate,\n user,\n} from '@deepagents/agent';\n\nimport {\n type ExecutionContext,\n formatStepForExecutor,\n} from './executors/generic-executor.ts';\nimport { type PlanStep, plan } from './planner-agent.ts';\nimport { replan } from './replanner-agent.ts';\nimport { synthesize } from './synthesizer.ts';\n\n/**\n * Lifecycle hooks for Plan-and-Solve execution.\n *\n * These hooks allow you to intercept and react to key points in the execution lifecycle,\n * enabling progress tracking, persistence, notifications, and custom logic injection.\n *\n * **Important:** You can manually terminate the execution loop by setting `context.is_complete = true`\n * in either hook. This allows you to stop execution early based on custom conditions (e.g., user cancellation,\n * resource limits, or completion detection).\n */\nexport interface PlanHooks {\n /**\n * Hook executed immediately after the initial plan is created.\n *\n * **When to use:**\n * - Review and validate the initial plan\n * - Persist the initial plan to storage\n * - Log the planned steps for auditing\n * - Modify the plan before execution starts\n * - Display the plan to users for confirmation\n * - Estimate total execution time or cost\n * - **Terminate execution before it starts** by setting `context.is_complete = true`\n *\n * **Timing:** After the planner agent creates the initial plan, before any step execution\n *\n * @param context - Initial execution context with the complete plan\n * @returns Modified context (or undefined to keep current context)\n *\n * @example\n * ```typescript\n * onInitialPlan: async (context) => {\n * // Log the initial plan\n * console.log(`Plan created with ${context.current_plan.length} steps`);\n *\n * // Save for later review\n * await writeFile('initial_plan.json', JSON.stringify(context, null, 2));\n *\n * // Validate plan isn't too complex\n * if (context.current_plan.length > 20) {\n * console.error('Plan too complex, aborting');\n * context.is_complete = true;\n * }\n *\n * return context;\n * }\n * ```\n */\n onInitialPlan?: (\n context: ExecutionContext,\n ) => Promise<ExecutionContext | void> | ExecutionContext | void;\n\n /**\n * Hook executed before replanning occurs (after a step completes).\n *\n * **When to use:**\n * - Save execution progress/checkpoints\n * - Log intermediate results for auditing\n * - Modify context before the replanner evaluates it\n * - Track execution metrics\n * - Stream progress updates to a client/UI\n * - **Terminate execution early** by setting `context.is_complete = true`\n *\n * **Timing:** After a step executes, before the replanner agent runs\n *\n * @param context - Current execution state including completed step results\n * @returns Modified context (or undefined to keep current context)\n */\n beforeReplan?: (\n context: ExecutionContext,\n ) => Promise<ExecutionContext | void> | ExecutionContext | void;\n\n /**\n * Hook executed after replanning occurs and the plan is updated.\n *\n * **When to use:**\n * - Persist the updated plan to storage\n * - Log plan changes and reasoning\n * - Notify users of plan adjustments\n * - Update progress indicators\n * - Implement custom plan filtering/validation\n * - Stream plan updates to a dashboard\n * - Send alerts if major changes occur\n * - **Terminate execution early** by setting `context.is_complete = true`\n *\n * **Timing:** After the replanner agent has updated the plan, before next step execution\n *\n * @param context - Current execution state with updated plan\n * @returns Modified context (or undefined to keep current context)\n */\n afterReplan?: (\n context: ExecutionContext,\n ) => Promise<ExecutionContext | void> | ExecutionContext | void;\n}\n\nasync function runExecutor(\n agent: Agent<any, any>,\n context: ExecutionContext,\n step: PlanStep,\n state: ContextVariables,\n) {\n const { text } = await generate(\n agent,\n [user(formatStepForExecutor(step, context))],\n state,\n );\n return {\n ...context,\n variables: { ...context.variables },\n step_results: [...context.step_results, text],\n };\n}\n\n/**\n * Executes a Plan-and-Solve Plus (PS+) workflow with adaptive replanning.\n *\n * This function creates a complete autonomous task execution pipeline:\n * 1. Plans the task into specific steps\n * 2. Executes each step sequentially\n * 3. Replans after each execution to adapt based on results\n * 4. Synthesizes results into a final output\n *\n * @param options - Configuration for the plan-and-solve execution\n * @param options.input - The user's request or task description\n * @param options.executor - The agent that will execute individual plan steps\n * @param options.state - Execution context variables (e.g., repo_path, API keys)\n * @param options.hooks - Optional lifecycle hooks for extensibility (see {@link PlanHooks})\n *\n * @example\n * ```typescript\n * const result = await planAndSolve({\n * input: \"Find all AI startups that raised Series A\",\n * executor: researchExecutor,\n * state: {\n * repo_path: process.cwd()\n * },\n * environment: {\n * executor_type: 'research',\n * available_tools: ['browser_search', 'scratchpad'],\n * domain: 'market research',\n * capabilities: ['web search', 'source verification', 'numerical data extraction']\n * },\n * },\n * hooks: {\n * beforeReplan: async (context) => {\n * // Save progress before replanning\n * await saveCheckpoint(context);\n * return context;\n * },\n * afterReplan: async (context) => {\n * // Log plan updates\n * console.log(`Updated plan: ${context.current_plan.length} steps remaining`);\n * return context;\n * }\n * }\n * });\n * ```\n */\nexport async function planAndSolve(options: {\n input: string;\n executor: Agent<any, any>;\n state: ContextVariables;\n hooks?: PlanHooks;\n}) {\n let context = await plan(options.input);\n const plans = [context.current_plan];\n\n if (options.hooks?.onInitialPlan) {\n const initialPlanResult = await options.hooks.onInitialPlan(context);\n if (initialPlanResult) {\n context = initialPlanResult;\n }\n }\n\n if (context.is_complete) {\n return synthesize(context.step_results, context.original_request);\n }\n\n while (context.current_plan.length > 0) {\n const currentStep = context.current_plan[0];\n context = await runExecutor(\n options.executor,\n context,\n currentStep,\n options.state,\n );\n if (options.hooks?.beforeReplan) {\n const beforeReplanResult = await options.hooks.beforeReplan(context);\n if (beforeReplanResult) {\n context = beforeReplanResult;\n }\n }\n if (context.is_complete) {\n // User requested early termination\n break;\n }\n\n // -- Start Replanning --\n context = await replan(context);\n plans.push(context.current_plan);\n // -- End Replanning --\n\n if (options.hooks?.afterReplan) {\n const afterReplanResult = await options.hooks.afterReplan(context);\n if (afterReplanResult) {\n context = afterReplanResult;\n }\n }\n\n if (context.is_complete) {\n break;\n }\n }\n\n options.state.plans = plans;\n return synthesize(context.step_results, context.original_request);\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\n\nimport { agent } from '@deepagents/agent';\nimport { scratchpad_tool, search_content_tool } from '@deepagents/toolbox';\n\nimport type { PlanStep, PlannerOutput } from '../planner-agent.ts';\n\n/**\n * Executor Agent\n *\n * Executes individual plan steps while:\n * 1. Tracking what information is gathered\n * 2. Extracting numerical variables from results\n * 3. Calculating intermediate results with attention to accuracy\n * 4. Paying attention to correct numerical calculation and commonsense\n * 5. Making observations about findings\n * 6. Noting any issues or unexpected results\n */\nexport const executorAgent = agent({\n name: 'executor_agent',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0 },\n }),\n }),\n prompt: `\n <SystemContext>\n You are a precise execution agent that follows plans and gathers information systematically.\n You pay close attention to details and track what you find.\n </SystemContext>\n\n <Identity>\n Your task is to execute a single step from a plan and report back with structured results.\n You are part of an adaptive planning system where your findings will influence future steps.\n </Identity>\n\n <ExecutionPrinciples>\n 1. **Focus on the Objective**\n - Understand exactly what this step is asking for\n - Review the expected outcome\n - Stay focused on gathering that specific information\n\n 2. **Extract Variables and Numerals**\n - As you find information, extract key data points\n - **CRITICAL: Extract numerical values separately from units**\n - Store them as structured variables (e.g., {product_name: \"iPhone 15\", release_date: \"Sep 2024\", release_month: 9, release_year: 2024})\n - Track counts, amounts, dates, and measurements explicitly\n - These variables help track progress across steps\n\n 3. **Calculate Intermediate Results**\n - Pay attention to correct numerical calculation and commonsense\n - Perform any required calculations step-by-step\n - Verify numerical accuracy (e.g., date ranges, counts, sums)\n - Check results against common sense (e.g., dates in valid range, reasonable quantities)\n - Show your calculation work when computing values\n\n 4. **Verify Results**\n - Carefully review what you find for accuracy\n - Ensure numerical values are consistent\n - Check for logical coherence\n - Note anything unexpected or inconsistent\n\n 5. **Make Observations**\n - What patterns did you notice?\n - What numerical trends are apparent?\n - What might affect subsequent steps?\n\n 6. **Note Issues**\n - Were there any calculation difficulties?\n - Was the information hard to find?\n - Were there any errors or ambiguities?\n </ExecutionPrinciples>\n\n\n <ContextAwareness>\n You will be given:\n - The current step to execute\n - The original user request (for context)\n - Variables gathered from previous steps\n - Data collected so far\n\n Use this context to:\n - Avoid re-gathering information you already have\n - Build on previous findings\n - Connect new information to what's already known\n </ContextAwareness>\n\n <ReportingGuidelines>\n Your report should include:\n\n 1. **Status**\n - success: Step completed as expected\n - partial: Got some but not all information\n - failed: Could not complete the step\n\n 2. **Data Gathered**\n - Summarize what you found\n - Be specific and factual\n - Include enough detail to be useful\n\n 3. **Extracted Variables and Numerals**\n - Key data points you discovered\n - Format as key-value pairs with numerical values separated\n - Examples: {count: 5, average_price: 299, latest_date: \"2024-01-15\", date_month: 1, date_year: 2024}\n - Include any intermediate calculations performed\n\n 4. **Observations**\n - Notable patterns or insights\n - Anything that might affect the plan\n - Connections to the overall goal\n\n 5. **Issues**\n - Any problems encountered\n - Missing or unclear information\n - Limitations of what you found\n </ReportingGuidelines>\n\n <Examples>\n Step: \"Find Apple's official announcements from the past 3 months\"\n Context: {company: \"Apple\", timeframe: \"3 months\"}\n\n Good Execution:\n - Use browser_search to find Apple newsroom/press releases\n - Filter results to last 3 months\n - List the announcements found\n - Extract count, dates, types\n - Note any gaps or issues\n\n Report (with numerical extraction):\n - Status: success\n - Data: \"Found 15 press releases from Apple newsroom (Oct-Dec 2024)\"\n - Variables: {\n press_release_count: 15,\n date_range: \"Oct-Dec 2024\",\n start_month: 10,\n end_month: 12,\n year: 2024,\n months_covered: 3\n }\n - Observations: [\"Mix of product, service, and corporate announcements\", \"Exactly covers the requested 3-month timeframe\"]\n - Issues: []\n </Examples>\n\n <CriticalInstructions>\n - Execute the step precisely as described\n - **Extract numerical variables and their values separately**\n - **Pay attention to correct numerical calculation and commonsense**\n - Calculate and verify intermediate results step-by-step\n - Report accurately with verified numbers - your results influence future steps\n - Use the context from previous steps to work smarter\n - If you can't find something, say so clearly\n - Double-check all numerical values for accuracy\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured step result with:\n - status (success/partial/failed)\n - data_gathered (summary of findings)\n - extracted_variables (key-value pairs)\n - observations (notable insights)\n - issues (any problems)\n </OutputFormat>\n `,\n tools: {\n scratchpad: scratchpad_tool,\n search: search_content_tool,\n // browser_search: groq.tools.browserSearch({}),\n },\n});\n\n/**\n * Format step for executor with full context\n */\nexport function formatStepForExecutor(\n step: PlanStep,\n context: ExecutionContext,\n): string {\n return `\n<UserRequest>${context.original_request}</UserRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<PreviousSteps>\n${context.step_results.length ? context.step_results.map((result, i) => `Step ${i + 1}: ${result}`).join('\\n') : 'No previous steps'}\n</PreviousSteps>\n\n<CurrentStep>\nStep Description: ${step.description}\nExpected Outcome: ${step.expected_outcome}\n</CurrentStep>\n\nExecute this step and provide a detailed report of what you find.\n `.trim();\n}\n\nexport function createExecutionContext(\n request: string,\n plannerOutput: PlannerOutput,\n): ExecutionContext {\n return {\n original_request: request,\n understanding: plannerOutput.understanding,\n initial_plan: plannerOutput.steps,\n current_plan: [...plannerOutput.steps],\n variables: { ...plannerOutput.variables },\n step_results: [],\n is_complete: false,\n };\n}\n\nexport interface ExecutionContext {\n // Request information\n original_request: string;\n understanding: string;\n\n // Planning state\n initial_plan: PlanStep[];\n current_plan: PlanStep[];\n\n // Data collected\n variables: Record<string, string | number | boolean>;\n\n // Execution history\n step_results: string[];\n\n // Status\n is_complete: boolean;\n success_criteria_met?: boolean;\n}\n", "import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { lmstudio } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n createBashTool,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport { createExecutionContext } from './executors/generic-executor.ts';\n\nconst PlanStepSchema = z.object({\n description: z\n .string()\n .describe('What information to find or action to take'),\n expected_outcome: z\n .string()\n .describe('What should be accomplished by this step'),\n});\n\nexport const PlannerOutputSchema = z.object({\n understanding: z\n .string()\n .describe('Clear understanding of what the user is asking for and why'),\n variables: z\n .record(z.string(), z.any())\n .describe(\n 'Key variables with numerical values extracted from the request. Examples: {company: \"Apple\", timeframe_value: 3, timeframe_unit: \"months\", min_salary: 150000}',\n ),\n constraints: z\n .array(z.string())\n .default([])\n .describe('Any constraints or limitations mentioned'),\n success_criteria: z\n .string()\n .describe('How to know if the task was completed successfully'),\n steps: z\n .array(PlanStepSchema)\n .min(1)\n .max(4)\n .describe('Ordered list of steps to execute'),\n});\n\nexport type PlanStep = z.infer<typeof PlanStepSchema>;\nexport type PlannerOutput = z.infer<typeof PlannerOutputSchema>;\n\n/**\n * Environment context that describes the execution capabilities.\n * This helps the planner create steps that are actually executable.\n */\nexport interface PlanEnvironment {\n /**\n * Type of executor that will execute the steps\n * @example 'research', 'hackernews', 'generic', 'product_manager'\n */\n executor_type: string;\n\n /**\n * Available tools the executor has access to\n * @example ['browser_search', 'scratchpad'], ['hackernews_search', 'scratchpad']\n */\n available_tools: string[];\n\n /**\n * Domain or task category\n * @example 'market research', 'hackernews sentiment analysis', 'code repository search'\n */\n domain: string;\n\n /**\n * High-level capabilities description\n * @example ['web search', 'source verification', 'numerical data extraction']\n */\n capabilities?: string[];\n}\n\n/**\n * Planner agent that creates structured execution plans:\n * 1. Understanding Phase: Deeply understand the user's request\n * 2. Variable Extraction: Extract relevant variables and their corresponding numerical values\n * 3. Plan Devising: Break down into specific, actionable steps\n * 4. Success Criteria: Define how to know when the task is complete\n *\n * Enhanced with adaptive replanning for dynamic task execution.\n */\nconst plannerModel = wrapLanguageModel({\n model: lmstudio('google/gemma-3-12b'),\n // model: groq('moonshotai/kimi-k2-instruct-0905'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.3 }, // Slightly creative for better planning\n }),\n});\n\nfunction createPlannerPrompt(context?: {\n environment?: PlanEnvironment;\n}): string {\n return `\n <SystemContext>\n You are an expert planning agent that creates adaptive, well-structured plans.\n Plans are executed step-by-step and adjusted as needed based on findings.\n </SystemContext>\n\n <ExecutionEnvironment>\n ${formatEnvironmentContext(context?.environment)}\n\n CRITICAL: Create steps that match the available tools and domain.\n - Only plan steps that can be executed with the available tools\n - Tailor your approach to the executor's domain and capabilities\n - Don't ask for actions the executor cannot perform\n - Frame steps in terms the executor understands\n </ExecutionEnvironment>\n\n <Identity>\n Your task is to deeply understand user requests and create detailed execution plans.\n You excel at:\n - Understanding what users truly need\n - Extracting key variables and constraints\n - Breaking complex tasks into clear, actionable steps\n - Defining success criteria\n - Creating executable plans that match available capabilities\n </Identity>\n\n <PlanningMethodology>\n Follow this two-phase approach:\n First understand the problem, extract relevant variables and their numerical values,\n and devise a plan. Then the plan will be carried out step by step.\n\n ## PHASE 1: Understanding & Analysis\n\n 1. **Understand the Request**\n - What is the user asking for?\n - Why do they need this information?\n - What is the core intent behind the request?\n\n 2. **Extract Variables and Numerals**\n - Identify all key variables (e.g., company names, time periods, categories)\n - **CRITICALLY: Extract numerical values and their units** (e.g., \"3 months\", \"$150k\", \"5 products\")\n - Map variables to their corresponding numerical values (e.g., {timeframe: 3, unit: \"months\"})\n - Note any implicit variables and numerical relationships\n - Identify calculations that may be required\n\n 3. **Identify Constraints**\n - Time constraints (e.g., \"last 3 months\", \"2024\")\n - Category constraints (e.g., \"AI startups\", \"developer tools\")\n - Scope constraints (e.g., \"in Europe\", \"Y Combinator companies\")\n - Quality constraints (e.g., \"above $150k\", \"4-day work week\")\n\n 4. **Define Success**\n - How will we know the task is complete?\n - What must be included in the final result?\n - What level of detail is needed?\n\n ## PHASE 2: Plan Creation\n\n 5. **Devise Subtasks**\n - Break the request into smaller, specific steps\n - Each step should gather ONE specific type of information\n - Make each step independently executable\n\n 6. **Specify Expected Outcomes**\n - For each step, define what should be accomplished\n - This helps the executor know what to deliver\n - This helps the replanner know if the step succeeded\n\n </PlanningMethodology>\n\n <StepDesignPrinciples>\n Each step should:\n \u2713 Be SPECIFIC and ACTIONABLE\n \u2713 Focus on gathering ONE type of information\n \u2713 Start with action verbs: \"Find...\", \"Identify...\", \"Determine...\", \"Extract...\"\n \u2713 Have a clear expected outcome\n \u2713 Be verifiable (can check if it succeeded)\n\n Avoid:\n \u2717 Vague steps like \"Research the topic\"\n \u2717 Implementation details like \"Query the database\"\n \u2717 Multiple objectives in one step\n \u2717 Summary/aggregation steps (that happens automatically)\n \u2717 Delivery steps (system handles that)\n </StepDesignPrinciples>\n\n <Examples>\n Example 1: Web Research Task\n\n User Request: \"Did Apple release any new products in the past 3 months?\"\n Environment: Executor Type: research, Tools: [browser_search, scratchpad], Domain: market research\n\n Understanding: User wants to know about recent Apple product launches\n\n Variables (with numerical values extracted):\n - company: \"Apple\"\n - timeframe_value: 3\n - timeframe_unit: \"months\"\n - info_type: \"product releases\"\n\n Constraints:\n - Only products (not services, updates, etc.)\n - Only last 3 months\n - Apple only (not subsidiaries)\n\n Success Criteria: List of Apple products released in last 3 months with names and dates\n\n Steps (tailored to browser_search capability):\n 1. Search Apple's newsroom for product announcements from the past 3 months\n Expected: List of official press releases and announcements\n\n 2. Identify product-specific announcements (filter out software updates, services)\n Expected: Subset of announcements that are actual product launches\n\n 3. Extract product names and release dates from announcements\n Expected: Product name, date, and brief description for each\n\n ---\n\n Example 2: HackerNews Research Task\n\n User Request: \"What does the tech community think about Rust vs Go?\"\n Environment: Executor Type: hackernews, Tools: [hackernews_search, scratchpad], Domain: hackernews sentiment analysis\n\n Understanding: User wants to understand tech community opinions comparing Rust and Go\n\n Variables:\n - languages: [\"Rust\", \"Go\"]\n - info_type: \"sentiment comparison\"\n\n Constraints:\n - HackerNews community only\n - Recent discussions preferred\n\n Success Criteria: Summary of HN community sentiment on Rust vs Go with key points from both sides\n\n Steps (tailored to hackernews_search capability):\n 1. Search HackerNews for recent discussions about Rust programming language\n Expected: Stories and comments about Rust with engagement metrics\n\n 2. Search HackerNews for recent discussions about Go programming language\n Expected: Stories and comments about Go with engagement metrics\n\n 3. Search HackerNews for direct comparisons between Rust and Go\n Expected: Discussions explicitly comparing the two languages\n </Examples>\n\n <CriticalInstructions>\n - Take time to truly UNDERSTAND the request before planning\n - **Extract ALL relevant variables with their numerical values**\n - Separate numerical values from their units (e.g., 3 and \"months\", not \"3 months\")\n - Identify any calculations or comparisons that will be needed\n - Create focused steps that each have ONE clear purpose\n - Define what success looks like\n - Steps should be about WHAT to find, not HOW to find it\n - Remember: the plan will be adjusted as execution proceeds\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured plan with:\n 1. Understanding of the request\n 2. Extracted variables (as key-value pairs)\n 3. Identified constraints\n 4. Success criteria\n 5. Ordered list of steps with expected outcomes.\n </OutputFormat>\n `;\n}\n\n/**\n * Format environment context for the planner prompt\n */\nfunction formatEnvironmentContext(environment?: PlanEnvironment): string {\n if (!environment) {\n return `No specific environment provided. Infer environment from user request.`;\n }\n\n const capabilitiesText = environment.capabilities\n ? `\\n Capabilities: ${environment.capabilities.join(', ')}`\n : '';\n\n return `\n Executor Type: ${environment.executor_type}\n Domain: ${environment.domain}\n Available Tools: ${environment.available_tools.join(', ')}${capabilitiesText}\n `.trim();\n}\n\n/**\n * Create an execution plan for the given user request\n *\n * @param userRequest - The user's task or question\n * @param environment - Optional execution environment describing available tools and domain\n */\nexport async function plan(\n userRequest: string,\n state: { environment?: PlanEnvironment } = {},\n) {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `planner-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'planner_agent',\n role: 'You are an expert planning agent that creates adaptive, well-structured plans.',\n objective:\n 'Deeply understand user requests and return executable plans with structured variables, constraints, success criteria, and steps.',\n }),\n fragment('planner_instructions', createPlannerPrompt(state)),\n user(userRequest),\n );\n\n const plannerOutput = structuredOutput({\n model: plannerModel,\n context,\n schema: PlannerOutputSchema,\n });\n\n const output = await plannerOutput.generate();\n return createExecutionContext(userRequest, output);\n}\n", "import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { lmstudio } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n createBashTool,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport { type ExecutionContext } from './executors/generic-executor.ts';\nimport type { PlanStep } from './planner-agent.ts';\n\nconst PlanStepSchema = z.object({\n description: z\n .string()\n .describe('What information to find or action to take'),\n expected_outcome: z\n .string()\n .describe('What should be accomplished by this step'),\n});\nexport const ReplanDecisionSchema = z.object({\n reasoning: z.string().describe('Why this replanning decision was made'),\n should_continue: z.boolean().describe('Should we continue executing?'),\n remaining_steps: z\n .array(PlanStepSchema)\n .max(4)\n .describe('Updated list of remaining steps'),\n new_insights: z\n .string()\n .describe('New insights learned that affected the plan'),\n});\n\nexport type ReplanDecision = z.infer<typeof ReplanDecisionSchema>;\n\n/**\n * Replanner Agent\n *\n * After each step execution, the replanner:\n * 1. Reviews what was accomplished vs what was expected\n * 2. Analyzes how this affects the remaining plan\n * 3. Decides if the plan needs adjustment\n * 4. Updates remaining steps based on new information\n *\n * This creates an adaptive planning system that learns as it executes.\n */\nconst replannerModel = wrapLanguageModel({\n // model: groq('moonshotai/kimi-k2-instruct-0905'),\n model: lmstudio('google/gemma-3-12b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.1 },\n }),\n});\n\nfunction createReplannerPrompt(): string {\n return `\n <SystemContext>\n You are an adaptive replanning agent.\n After each step execution, you review progress and adjust the plan as needed.\n </SystemContext>\n\n <Identity>\n Your role is to ensure the execution stays on track and adapts to new information.\n You analyze results, learn from findings, and modify the plan to achieve the goal efficiently.\n </Identity>\n\n <ReplanningPrinciples>\n 1. **Review Results**\n - What was the step supposed to accomplish?\n - What was actually accomplished?\n - Was it successful, partial, or failed?\n\n 2. **Analyze Impact**\n - How do these results affect the overall goal?\n - What did we learn that we didn't know before?\n - Does this change what we need to do next?\n\n 3. **Assess Remaining Plan**\n - Are the remaining steps still appropriate?\n - Do we need additional steps?\n - Can we skip any steps?\n - Should we change the order?\n\n 4. **Make Decisions**\n - Should we continue with the plan?\n - What adjustments are needed?\n - How significant are the changes?\n\n 5. **Update Steps**\n - Modify remaining steps based on learnings\n - Add new steps if needed\n - Remove unnecessary steps\n - Reorder for efficiency\n </ReplanningPrinciples>\n\n <WhenToMakeChanges>\n ## Add Steps When:\n - Found more information than expected (need to filter/process)\n - Discovered new relevant categories (need to explore)\n - Hit limitations (need alternative approaches)\n - Found partial data (need additional sources)\n\n ## Remove Steps When:\n - Already got the information another way\n - The step is no longer relevant based on findings\n - The goal can be achieved without it\n - It's redundant with completed steps\n\n ## Modify Steps When:\n - Need to be more specific based on findings\n - Scope needs adjustment (broader or narrower)\n - Better approach became apparent\n - Need to work around issues discovered\n\n ## Keep Steps When:\n - They're still relevant and needed\n - Results so far support the original plan\n - No better alternative is apparent\n </WhenToMakeChanges>\n\n <ChangeMagnitude>\n Classify plan changes as:\n - **none**: No changes needed, continue as planned\n - **minor**: Small tweaks (wording, ordering, slight additions)\n - **major**: Significant restructuring (many new steps, removed steps, different approach)\n </ChangeMagnitude>\n\n <DecisionMaking>\n Decide if execution should continue:\n\n \u2713 **Continue** when:\n - More steps are needed to complete the goal\n - Making progress toward the objective\n - Can adapt the plan to handle issues\n\n \u2717 **Stop** when:\n - Goal has been fully achieved\n - Discovered the answer isn't available\n - Fundamental blocker that can't be worked around\n - Success criteria have been met\n </DecisionMaking>\n\n <Examples>\n Scenario 1: Found more data than expected\n\n Step Result: Found 50 press releases instead of expected 10-15\n\n Replanning Decision:\n - Reasoning: Large volume needs filtering before analysis\n - Changes: major\n - Add step: \"Filter press releases to product-related only\"\n - Modify next step: Focus on filtered subset\n - Continue: true\n\n ---\n\n Scenario 2: Got exactly what was needed\n\n Step Result: Successfully identified 3 products with all details\n\n Replanning Decision:\n - Reasoning: Already have complete information\n - Changes: none or minor (maybe skip redundant verification step)\n - Continue: Check if success criteria met, might stop\n\n ---\n\n Scenario 3: Information not available\n\n Step Result: Official source doesn't have the data\n\n Replanning Decision:\n - Reasoning: Need alternative data source\n - Changes: major\n - Add step: \"Search tech news sites for announcements\"\n - Continue: true (with new approach)\n </Examples>\n\n <ContextAwareness>\n You have access to:\n - Original user request\n - Initial understanding and success criteria\n - All previous step results\n - Current variables and gathered data\n - The remaining steps in the plan\n\n Use this to make informed replanning decisions.\n </ContextAwareness>\n\n <CriticalInstructions>\n - Be thoughtful but decisive\n - Adapt the plan based on ACTUAL results, not assumptions\n - Keep the end goal in mind (user's original request)\n - Don't keep executing steps if the goal is already achieved\n - Don't abandon the plan too easily - adapt when possible\n - Make changes that improve efficiency and effectiveness\n - Explain your reasoning clearly\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a replanning decision with:\n - reasoning: Why you're making this decision\n - should_continue: true/false\n - remaining_steps: Updated list of steps to execute\n - new_insights: What you learned that affected the plan\n </OutputFormat>\n `;\n}\n\nfunction formatReplannerPrompt(\n context: ExecutionContext,\n remainingSteps: PlanStep[],\n): string {\n const executionHistory = context.step_results\n .map((r, i) => `Step ${i}: ${r}`)\n .join('\\n');\n\n return `\n<OriginalRequest>${context.original_request}</OriginalRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<SuccessCriteria>\nCheck if we have achieved the goal of the original request.\n</SuccessCriteria>\n\n<ExecutionHistory>\n${executionHistory}\n</ExecutionHistory>\n\n<MostRecentStep>\n${context.step_results.at(-1) ?? 'No steps executed yet'}\n</MostRecentStep>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<RemainingSteps>\n${remainingSteps.length > 0 ? remainingSteps.map((s, i) => `${i}. ${s.description} (Expected: ${s.expected_outcome})`).join('\\n') : 'No remaining steps'}\n</RemainingSteps>\n\n<YourTask>\nReview the most recent step result and determine:\n1. Should we continue execution?\n2. Does the plan need adjustment based on what we found?\n3. What should the remaining steps be?\n\nConsider:\n- Did we find what we were looking for?\n- Is the goal achievable with the current approach?\n- Do results suggest a better path forward?\n- Have we already met the success criteria?\n</YourTask>\n `.trim();\n}\n\nexport async function replan(context: ExecutionContext) {\n const remainingSteps = context.current_plan.slice(1);\n const plannerContext = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `replanner-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n plannerContext.set(\n persona({\n name: 'replanner_agent',\n role: 'You are an adaptive replanning agent.',\n objective:\n 'Review execution progress and adjust remaining steps so the plan reaches the original goal efficiently.',\n }),\n fragment('replanner_instructions', createReplannerPrompt()),\n user(formatReplannerPrompt(context, remainingSteps)),\n );\n\n const replannerOutput = structuredOutput({\n model: replannerModel,\n context: plannerContext,\n schema: ReplanDecisionSchema,\n });\n\n const decision = await replannerOutput.generate();\n return {\n ...context,\n current_plan: decision.remaining_steps,\n is_complete: !decision.should_continue,\n };\n}\n", "import { agent, execute, lmstudio, user } from '@deepagents/agent';\n\n/**\n * Synthesizer agent that compiles step results into a final answer\n * Applies numerical accuracy and commonsense validation\n */\nconst synthesizer = agent({\n name: 'synthesizer_agent',\n model: lmstudio('google/gemma-3-12b'),\n prompt: `\n\t\t<SystemContext>\n\t\t\tYou are a synthesizer agent that compiles the results of executed plan steps into a final answer.\n\t\t\tYou ensure accuracy and coherence in the final output.\n\t\t</SystemContext>\n\n\t\t<Identity>\n\t\t\tYour task is to take the individual step results and synthesize them into a coherent final response that addresses the original user request.\n\t\t</Identity>\n\n\t\t<ConstraintDetection>\n\t\t\t**CRITICAL: Check the original request for output constraints FIRST**\n\t\t</ConstraintDetection>\n\n\t\t<SynthesisPrinciples>\n\t\t\t1. **Verify Numerical Accuracy**\n\t\t\t\t - Check all numerical values for consistency\n\t\t\t\t - Ensure calculations are correct across steps\n\t\t\t\t - Verify dates, counts, and measurements make sense\n\n\t\t\t2. **Apply Commonsense Validation**\n\t\t\t\t - Do the results make logical sense?\n\t\t\t\t - Are there any contradictions or inconsistencies?\n\t\t\t\t - Do temporal relationships align (e.g., dates in proper order)?\n\n\t\t\t3. **Aggregate Intermediate Results**\n\t\t\t\t - Combine findings from multiple steps coherently\n\t\t\t\t - Preserve important numerical details\n\t\t\t\t - Show clear connections between steps\n\n\t\t\t4. **Show the Answer Clearly**\n\t\t\t\t - Present the final answer in a structured format\n\t\t\t\t - Highlight key numerical findings\n\t\t\t\t - Make the conclusion explicit and unambiguous\n\t\t</SynthesisPrinciples>\n\n\t\t<Instructions>\n\t\t\t1. **Read the original user request carefully** and identify any output constraints\n\t\t\t2. Review all step results carefully\n\t\t\t3. **Verify numerical consistency and commonsense**\n\t\t\t4. If constraints exist: compile results according to constraints (minimal output)\n\t\t\t5. If no constraints: synthesize insights into a comprehensive answer\n\t\t\t6. **Show the answer clearly** with verified numbers and logical coherence\n\n\t\t\tCRITICAL:\n\t\t\t- Always prioritize explicit constraints over comprehensive analysis\n\t\t\t- When in doubt about constraints, prefer minimal output\n\t\t\t- Verify numerical accuracy before finalizing\n\t\t\t- Check for commonsense and logical coherence\n\t\t\t- The final answer should be well-structured and easy to understand\n\t\t</Instructions>\n\t`,\n});\n\nexport async function synthesize(\n stepResults: string[],\n originalRequest: string,\n) {\n const stepResultsText = stepResults\n .map((step, index) => `Step ${index + 1} Result:\\n${step}`)\n .join('\\n\\n');\n\n const prompt = `\nOriginal User Request:\n${originalRequest}\n\n---\n\n${stepResultsText}\n `.trim();\n\n return (await execute(synthesizer, [user(prompt)], {})).text;\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,OAAmB;AAEnB;AAAA,EAIE;AAAA,EACA,QAAAA;AAAA,OACK;;;ACRP,SAAS,YAAY;AACrB,SAAS,2BAA2B,yBAAyB;AAE7D,SAAS,aAAa;AACtB,SAAS,iBAAiB,2BAA2B;AAe9C,IAAM,gBAAgB,MAAM;AAAA,EACjC,MAAM;AAAA,EACN,OAAO,kBAAkB;AAAA,IACvB,OAAO,KAAK,oBAAoB;AAAA,IAChC,YAAY,0BAA0B;AAAA,MACpC,UAAU,EAAE,aAAa,EAAE;AAAA,IAC7B,CAAC;AAAA,EACH,CAAC;AAAA,EACD,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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K;AACtC,QAAM,QAAQ,CAAC,QAAQ,YAAY;AAEnC,MAAI,QAAQ,OAAO,eAAe;AAChC,UAAM,oBAAoB,MAAM,QAAQ,MAAM,cAAc,OAAO;AACnE,QAAI,mBAAmB;AACrB,gBAAU;AAAA,IACZ;AAAA,EACF;AAEA,MAAI,QAAQ,aAAa;AACvB,WAAO,WAAW,QAAQ,cAAc,QAAQ,gBAAgB;AAAA,EAClE;AAEA,SAAO,QAAQ,aAAa,SAAS,GAAG;AACtC,UAAM,cAAc,QAAQ,aAAa,CAAC;AAC1C,cAAU,MAAM;AAAA,MACd,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,IACV;AACA,QAAI,QAAQ,OAAO,cAAc;AAC/B,YAAM,qBAAqB,MAAM,QAAQ,MAAM,aAAa,OAAO;AACnE,UAAI,oBAAoB;AACtB,kBAAU;AAAA,MACZ;AAAA,IACF;AACA,QAAI,QAAQ,aAAa;AAEvB;AAAA,IACF;AAGA,cAAU,MAAM,OAAO,OAAO;AAC9B,UAAM,KAAK,QAAQ,YAAY;AAG/B,QAAI,QAAQ,OAAO,aAAa;AAC9B,YAAM,oBAAoB,MAAM,QAAQ,MAAM,YAAY,OAAO;AACjE,UAAI,mBAAmB;AACrB,kBAAU;AAAA,MACZ;AAAA,IACF;AAEA,QAAI,QAAQ,aAAa;AACvB;AAAA,IACF;AAAA,EACF;AAEA,UAAQ,MAAM,QAAQ;AACtB,SAAO,WAAW,QAAQ,cAAc,QAAQ,gBAAgB;AAClE;",
|
|
6
6
|
"names": ["user", "defaultSettingsMiddleware", "wrapLanguageModel", "wrapLanguageModel", "defaultSettingsMiddleware", "defaultSettingsMiddleware", "wrapLanguageModel", "z", "lmstudio", "ContextEngine", "InMemoryContextStore", "fragment", "persona", "structuredOutput", "user", "PlanStepSchema", "z", "wrapLanguageModel", "lmstudio", "defaultSettingsMiddleware", "ContextEngine", "InMemoryContextStore", "persona", "fragment", "user", "structuredOutput", "agent", "lmstudio", "user", "agent", "user"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner-agent.d.ts","sourceRoot":"","sources":["../../../src/lib/deepplan/planner-agent.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,KAAK,CAAC;AAepB,QAAA,MAAM,cAAc;;;iBAOlB,CAAC;AAEH,eAAO,MAAM,mBAAmB;;;;;;;;;iBAqB9B,CAAC;AAEH,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AACtD,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,eAAe,EAAE,MAAM,EAAE,CAAC;IAE1B;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AAkND;;;;;GAKG;AACH,wBAAsB,IAAI,CACxB,WAAW,EAAE,MAAM,EACnB,KAAK,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,
|
|
1
|
+
{"version":3,"file":"planner-agent.d.ts","sourceRoot":"","sources":["../../../src/lib/deepplan/planner-agent.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,KAAK,CAAC;AAepB,QAAA,MAAM,cAAc;;;iBAOlB,CAAC;AAEH,eAAO,MAAM,mBAAmB;;;;;;;;;iBAqB9B,CAAC;AAEH,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AACtD,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,eAAe,EAAE,MAAM,EAAE,CAAC;IAE1B;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AAkND;;;;;GAKG;AACH,wBAAsB,IAAI,CACxB,WAAW,EAAE,MAAM,EACnB,KAAK,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,uEA2B9C"}
|
|
@@ -404,10 +404,7 @@ async function plan(userRequest, state = {}) {
|
|
|
404
404
|
schema: PlannerOutputSchema
|
|
405
405
|
});
|
|
406
406
|
const output = await plannerOutput.generate();
|
|
407
|
-
return createExecutionContext(
|
|
408
|
-
userRequest,
|
|
409
|
-
output
|
|
410
|
-
);
|
|
407
|
+
return createExecutionContext(userRequest, output);
|
|
411
408
|
}
|
|
412
409
|
export {
|
|
413
410
|
PlannerOutputSchema,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/deepplan/planner-agent.ts", "../../../src/lib/deepplan/executors/generic-executor.ts"],
|
|
4
|
-
"sourcesContent": ["import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { lmstudio } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n createBashTool,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport { createExecutionContext } from './executors/generic-executor.ts';\n\nconst PlanStepSchema = z.object({\n description: z\n .string()\n .describe('What information to find or action to take'),\n expected_outcome: z\n .string()\n .describe('What should be accomplished by this step'),\n});\n\nexport const PlannerOutputSchema = z.object({\n understanding: z\n .string()\n .describe('Clear understanding of what the user is asking for and why'),\n variables: z\n .record(z.string(), z.any())\n .describe(\n 'Key variables with numerical values extracted from the request. Examples: {company: \"Apple\", timeframe_value: 3, timeframe_unit: \"months\", min_salary: 150000}',\n ),\n constraints: z\n .array(z.string())\n .default([])\n .describe('Any constraints or limitations mentioned'),\n success_criteria: z\n .string()\n .describe('How to know if the task was completed successfully'),\n steps: z\n .array(PlanStepSchema)\n .min(1)\n .max(4)\n .describe('Ordered list of steps to execute'),\n});\n\nexport type PlanStep = z.infer<typeof PlanStepSchema>;\nexport type PlannerOutput = z.infer<typeof PlannerOutputSchema>;\n\n/**\n * Environment context that describes the execution capabilities.\n * This helps the planner create steps that are actually executable.\n */\nexport interface PlanEnvironment {\n /**\n * Type of executor that will execute the steps\n * @example 'research', 'hackernews', 'generic', 'product_manager'\n */\n executor_type: string;\n\n /**\n * Available tools the executor has access to\n * @example ['browser_search', 'scratchpad'], ['hackernews_search', 'scratchpad']\n */\n available_tools: string[];\n\n /**\n * Domain or task category\n * @example 'market research', 'hackernews sentiment analysis', 'code repository search'\n */\n domain: string;\n\n /**\n * High-level capabilities description\n * @example ['web search', 'source verification', 'numerical data extraction']\n */\n capabilities?: string[];\n}\n\n/**\n * Planner agent that creates structured execution plans:\n * 1. Understanding Phase: Deeply understand the user's request\n * 2. Variable Extraction: Extract relevant variables and their corresponding numerical values\n * 3. Plan Devising: Break down into specific, actionable steps\n * 4. Success Criteria: Define how to know when the task is complete\n *\n * Enhanced with adaptive replanning for dynamic task execution.\n */\nconst plannerModel = wrapLanguageModel({\n model: lmstudio('google/gemma-3-12b'),\n // model: groq('moonshotai/kimi-k2-instruct-0905'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.3 }, // Slightly creative for better planning\n }),\n});\n\nfunction createPlannerPrompt(context?: {\n environment?: PlanEnvironment;\n}): string {\n return `\n <SystemContext>\n You are an expert planning agent that creates adaptive, well-structured plans.\n Plans are executed step-by-step and adjusted as needed based on findings.\n </SystemContext>\n\n <ExecutionEnvironment>\n ${formatEnvironmentContext(context?.environment)}\n\n CRITICAL: Create steps that match the available tools and domain.\n - Only plan steps that can be executed with the available tools\n - Tailor your approach to the executor's domain and capabilities\n - Don't ask for actions the executor cannot perform\n - Frame steps in terms the executor understands\n </ExecutionEnvironment>\n\n <Identity>\n Your task is to deeply understand user requests and create detailed execution plans.\n You excel at:\n - Understanding what users truly need\n - Extracting key variables and constraints\n - Breaking complex tasks into clear, actionable steps\n - Defining success criteria\n - Creating executable plans that match available capabilities\n </Identity>\n\n <PlanningMethodology>\n Follow this two-phase approach:\n First understand the problem, extract relevant variables and their numerical values,\n and devise a plan. Then the plan will be carried out step by step.\n\n ## PHASE 1: Understanding & Analysis\n\n 1. **Understand the Request**\n - What is the user asking for?\n - Why do they need this information?\n - What is the core intent behind the request?\n\n 2. **Extract Variables and Numerals**\n - Identify all key variables (e.g., company names, time periods, categories)\n - **CRITICALLY: Extract numerical values and their units** (e.g., \"3 months\", \"$150k\", \"5 products\")\n - Map variables to their corresponding numerical values (e.g., {timeframe: 3, unit: \"months\"})\n - Note any implicit variables and numerical relationships\n - Identify calculations that may be required\n\n 3. **Identify Constraints**\n - Time constraints (e.g., \"last 3 months\", \"2024\")\n - Category constraints (e.g., \"AI startups\", \"developer tools\")\n - Scope constraints (e.g., \"in Europe\", \"Y Combinator companies\")\n - Quality constraints (e.g., \"above $150k\", \"4-day work week\")\n\n 4. **Define Success**\n - How will we know the task is complete?\n - What must be included in the final result?\n - What level of detail is needed?\n\n ## PHASE 2: Plan Creation\n\n 5. **Devise Subtasks**\n - Break the request into smaller, specific steps\n - Each step should gather ONE specific type of information\n - Make each step independently executable\n\n 6. **Specify Expected Outcomes**\n - For each step, define what should be accomplished\n - This helps the executor know what to deliver\n - This helps the replanner know if the step succeeded\n\n </PlanningMethodology>\n\n <StepDesignPrinciples>\n Each step should:\n \u2713 Be SPECIFIC and ACTIONABLE\n \u2713 Focus on gathering ONE type of information\n \u2713 Start with action verbs: \"Find...\", \"Identify...\", \"Determine...\", \"Extract...\"\n \u2713 Have a clear expected outcome\n \u2713 Be verifiable (can check if it succeeded)\n\n Avoid:\n \u2717 Vague steps like \"Research the topic\"\n \u2717 Implementation details like \"Query the database\"\n \u2717 Multiple objectives in one step\n \u2717 Summary/aggregation steps (that happens automatically)\n \u2717 Delivery steps (system handles that)\n </StepDesignPrinciples>\n\n <Examples>\n Example 1: Web Research Task\n\n User Request: \"Did Apple release any new products in the past 3 months?\"\n Environment: Executor Type: research, Tools: [browser_search, scratchpad], Domain: market research\n\n Understanding: User wants to know about recent Apple product launches\n\n Variables (with numerical values extracted):\n - company: \"Apple\"\n - timeframe_value: 3\n - timeframe_unit: \"months\"\n - info_type: \"product releases\"\n\n Constraints:\n - Only products (not services, updates, etc.)\n - Only last 3 months\n - Apple only (not subsidiaries)\n\n Success Criteria: List of Apple products released in last 3 months with names and dates\n\n Steps (tailored to browser_search capability):\n 1. Search Apple's newsroom for product announcements from the past 3 months\n Expected: List of official press releases and announcements\n\n 2. Identify product-specific announcements (filter out software updates, services)\n Expected: Subset of announcements that are actual product launches\n\n 3. Extract product names and release dates from announcements\n Expected: Product name, date, and brief description for each\n\n ---\n\n Example 2: HackerNews Research Task\n\n User Request: \"What does the tech community think about Rust vs Go?\"\n Environment: Executor Type: hackernews, Tools: [hackernews_search, scratchpad], Domain: hackernews sentiment analysis\n\n Understanding: User wants to understand tech community opinions comparing Rust and Go\n\n Variables:\n - languages: [\"Rust\", \"Go\"]\n - info_type: \"sentiment comparison\"\n\n Constraints:\n - HackerNews community only\n - Recent discussions preferred\n\n Success Criteria: Summary of HN community sentiment on Rust vs Go with key points from both sides\n\n Steps (tailored to hackernews_search capability):\n 1. Search HackerNews for recent discussions about Rust programming language\n Expected: Stories and comments about Rust with engagement metrics\n\n 2. Search HackerNews for recent discussions about Go programming language\n Expected: Stories and comments about Go with engagement metrics\n\n 3. Search HackerNews for direct comparisons between Rust and Go\n Expected: Discussions explicitly comparing the two languages\n </Examples>\n\n <CriticalInstructions>\n - Take time to truly UNDERSTAND the request before planning\n - **Extract ALL relevant variables with their numerical values**\n - Separate numerical values from their units (e.g., 3 and \"months\", not \"3 months\")\n - Identify any calculations or comparisons that will be needed\n - Create focused steps that each have ONE clear purpose\n - Define what success looks like\n - Steps should be about WHAT to find, not HOW to find it\n - Remember: the plan will be adjusted as execution proceeds\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured plan with:\n 1. Understanding of the request\n 2. Extracted variables (as key-value pairs)\n 3. Identified constraints\n 4. Success criteria\n 5. Ordered list of steps with expected outcomes.\n </OutputFormat>\n `;\n}\n\n/**\n * Format environment context for the planner prompt\n */\nfunction formatEnvironmentContext(environment?: PlanEnvironment): string {\n if (!environment) {\n return `No specific environment provided. Infer environment from user request.`;\n }\n\n const capabilitiesText = environment.capabilities\n ? `\\n Capabilities: ${environment.capabilities.join(', ')}`\n : '';\n\n return `\n Executor Type: ${environment.executor_type}\n Domain: ${environment.domain}\n Available Tools: ${environment.available_tools.join(', ')}${capabilitiesText}\n `.trim();\n}\n\n/**\n * Create an execution plan for the given user request\n *\n * @param userRequest - The user's task or question\n * @param environment - Optional execution environment describing available tools and domain\n */\nexport async function plan(\n userRequest: string,\n state: { environment?: PlanEnvironment } = {},\n) {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `planner-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'planner_agent',\n role: 'You are an expert planning agent that creates adaptive, well-structured plans.',\n objective:\n 'Deeply understand user requests and return executable plans with structured variables, constraints, success criteria, and steps.',\n }),\n fragment('planner_instructions', createPlannerPrompt(state)),\n user(userRequest),\n );\n\n const plannerOutput = structuredOutput({\n model: plannerModel,\n context,\n schema: PlannerOutputSchema,\n });\n\n const output = await plannerOutput.generate();\n return createExecutionContext(\n userRequest,\n output as {\n understanding: string;\n variables: Record<string, unknown>;\n constraints: string[];\n success_criteria: string;\n steps: { description: string; expected_outcome: string }[];\n },\n );\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\n\nimport { agent } from '@deepagents/agent';\nimport { scratchpad_tool, search_content_tool } from '@deepagents/toolbox';\n\nimport type { PlanStep, PlannerOutput } from '../planner-agent.ts';\n\n/**\n * Executor Agent\n *\n * Executes individual plan steps while:\n * 1. Tracking what information is gathered\n * 2. Extracting numerical variables from results\n * 3. Calculating intermediate results with attention to accuracy\n * 4. Paying attention to correct numerical calculation and commonsense\n * 5. Making observations about findings\n * 6. Noting any issues or unexpected results\n */\nexport const executorAgent = agent({\n name: 'executor_agent',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0 },\n }),\n }),\n prompt: `\n <SystemContext>\n You are a precise execution agent that follows plans and gathers information systematically.\n You pay close attention to details and track what you find.\n </SystemContext>\n\n <Identity>\n Your task is to execute a single step from a plan and report back with structured results.\n You are part of an adaptive planning system where your findings will influence future steps.\n </Identity>\n\n <ExecutionPrinciples>\n 1. **Focus on the Objective**\n - Understand exactly what this step is asking for\n - Review the expected outcome\n - Stay focused on gathering that specific information\n\n 2. **Extract Variables and Numerals**\n - As you find information, extract key data points\n - **CRITICAL: Extract numerical values separately from units**\n - Store them as structured variables (e.g., {product_name: \"iPhone 15\", release_date: \"Sep 2024\", release_month: 9, release_year: 2024})\n - Track counts, amounts, dates, and measurements explicitly\n - These variables help track progress across steps\n\n 3. **Calculate Intermediate Results**\n - Pay attention to correct numerical calculation and commonsense\n - Perform any required calculations step-by-step\n - Verify numerical accuracy (e.g., date ranges, counts, sums)\n - Check results against common sense (e.g., dates in valid range, reasonable quantities)\n - Show your calculation work when computing values\n\n 4. **Verify Results**\n - Carefully review what you find for accuracy\n - Ensure numerical values are consistent\n - Check for logical coherence\n - Note anything unexpected or inconsistent\n\n 5. **Make Observations**\n - What patterns did you notice?\n - What numerical trends are apparent?\n - What might affect subsequent steps?\n\n 6. **Note Issues**\n - Were there any calculation difficulties?\n - Was the information hard to find?\n - Were there any errors or ambiguities?\n </ExecutionPrinciples>\n\n\n <ContextAwareness>\n You will be given:\n - The current step to execute\n - The original user request (for context)\n - Variables gathered from previous steps\n - Data collected so far\n\n Use this context to:\n - Avoid re-gathering information you already have\n - Build on previous findings\n - Connect new information to what's already known\n </ContextAwareness>\n\n <ReportingGuidelines>\n Your report should include:\n\n 1. **Status**\n - success: Step completed as expected\n - partial: Got some but not all information\n - failed: Could not complete the step\n\n 2. **Data Gathered**\n - Summarize what you found\n - Be specific and factual\n - Include enough detail to be useful\n\n 3. **Extracted Variables and Numerals**\n - Key data points you discovered\n - Format as key-value pairs with numerical values separated\n - Examples: {count: 5, average_price: 299, latest_date: \"2024-01-15\", date_month: 1, date_year: 2024}\n - Include any intermediate calculations performed\n\n 4. **Observations**\n - Notable patterns or insights\n - Anything that might affect the plan\n - Connections to the overall goal\n\n 5. **Issues**\n - Any problems encountered\n - Missing or unclear information\n - Limitations of what you found\n </ReportingGuidelines>\n\n <Examples>\n Step: \"Find Apple's official announcements from the past 3 months\"\n Context: {company: \"Apple\", timeframe: \"3 months\"}\n\n Good Execution:\n - Use browser_search to find Apple newsroom/press releases\n - Filter results to last 3 months\n - List the announcements found\n - Extract count, dates, types\n - Note any gaps or issues\n\n Report (with numerical extraction):\n - Status: success\n - Data: \"Found 15 press releases from Apple newsroom (Oct-Dec 2024)\"\n - Variables: {\n press_release_count: 15,\n date_range: \"Oct-Dec 2024\",\n start_month: 10,\n end_month: 12,\n year: 2024,\n months_covered: 3\n }\n - Observations: [\"Mix of product, service, and corporate announcements\", \"Exactly covers the requested 3-month timeframe\"]\n - Issues: []\n </Examples>\n\n <CriticalInstructions>\n - Execute the step precisely as described\n - **Extract numerical variables and their values separately**\n - **Pay attention to correct numerical calculation and commonsense**\n - Calculate and verify intermediate results step-by-step\n - Report accurately with verified numbers - your results influence future steps\n - Use the context from previous steps to work smarter\n - If you can't find something, say so clearly\n - Double-check all numerical values for accuracy\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured step result with:\n - status (success/partial/failed)\n - data_gathered (summary of findings)\n - extracted_variables (key-value pairs)\n - observations (notable insights)\n - issues (any problems)\n </OutputFormat>\n `,\n tools: {\n scratchpad: scratchpad_tool,\n search: search_content_tool,\n // browser_search: groq.tools.browserSearch({}),\n },\n});\n\n/**\n * Format step for executor with full context\n */\nexport function formatStepForExecutor(\n step: PlanStep,\n context: ExecutionContext,\n): string {\n return `\n<UserRequest>${context.original_request}</UserRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<PreviousSteps>\n${context.step_results.length ? context.step_results.map((result, i) => `Step ${i + 1}: ${result}`).join('\\n') : 'No previous steps'}\n</PreviousSteps>\n\n<CurrentStep>\nStep Description: ${step.description}\nExpected Outcome: ${step.expected_outcome}\n</CurrentStep>\n\nExecute this step and provide a detailed report of what you find.\n `.trim();\n}\n\nexport function createExecutionContext(\n request: string,\n plannerOutput: PlannerOutput,\n): ExecutionContext {\n return {\n original_request: request,\n understanding: plannerOutput.understanding,\n initial_plan: plannerOutput.steps,\n current_plan: [...plannerOutput.steps],\n variables: { ...plannerOutput.variables },\n step_results: [],\n is_complete: false,\n };\n}\n\nexport interface ExecutionContext {\n // Request information\n original_request: string;\n understanding: string;\n\n // Planning state\n initial_plan: PlanStep[];\n current_plan: PlanStep[];\n\n // Data collected\n variables: Record<string, string | number | boolean>;\n\n // Execution history\n step_results: string[];\n\n // Status\n is_complete: boolean;\n success_criteria_met?: boolean;\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,6BAAAA,4BAA2B,qBAAAC,0BAAyB;AAC7D,OAAO,OAAO;AAEd,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACZP,SAAS,YAAY;AACrB,SAAS,2BAA2B,yBAAyB;AAE7D,SAAS,aAAa;AACtB,SAAS,iBAAiB,2BAA2B;AAe9C,IAAM,gBAAgB,MAAM;AAAA,EACjC,MAAM;AAAA,EACN,OAAO,kBAAkB;AAAA,IACvB,O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AAAA,IACD,SAAS,wBAAwB,oBAAoB,KAAK,CAAC;AAAA,IAC3D,KAAK,WAAW;AAAA,EAClB;AAEA,QAAM,gBAAgB,iBAAiB;AAAA,IACrC,OAAO;AAAA,IACP;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AAED,QAAM,SAAS,MAAM,cAAc,SAAS;AAC5C,SAAO
|
|
4
|
+
"sourcesContent": ["import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { lmstudio } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n createBashTool,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport { createExecutionContext } from './executors/generic-executor.ts';\n\nconst PlanStepSchema = z.object({\n description: z\n .string()\n .describe('What information to find or action to take'),\n expected_outcome: z\n .string()\n .describe('What should be accomplished by this step'),\n});\n\nexport const PlannerOutputSchema = z.object({\n understanding: z\n .string()\n .describe('Clear understanding of what the user is asking for and why'),\n variables: z\n .record(z.string(), z.any())\n .describe(\n 'Key variables with numerical values extracted from the request. Examples: {company: \"Apple\", timeframe_value: 3, timeframe_unit: \"months\", min_salary: 150000}',\n ),\n constraints: z\n .array(z.string())\n .default([])\n .describe('Any constraints or limitations mentioned'),\n success_criteria: z\n .string()\n .describe('How to know if the task was completed successfully'),\n steps: z\n .array(PlanStepSchema)\n .min(1)\n .max(4)\n .describe('Ordered list of steps to execute'),\n});\n\nexport type PlanStep = z.infer<typeof PlanStepSchema>;\nexport type PlannerOutput = z.infer<typeof PlannerOutputSchema>;\n\n/**\n * Environment context that describes the execution capabilities.\n * This helps the planner create steps that are actually executable.\n */\nexport interface PlanEnvironment {\n /**\n * Type of executor that will execute the steps\n * @example 'research', 'hackernews', 'generic', 'product_manager'\n */\n executor_type: string;\n\n /**\n * Available tools the executor has access to\n * @example ['browser_search', 'scratchpad'], ['hackernews_search', 'scratchpad']\n */\n available_tools: string[];\n\n /**\n * Domain or task category\n * @example 'market research', 'hackernews sentiment analysis', 'code repository search'\n */\n domain: string;\n\n /**\n * High-level capabilities description\n * @example ['web search', 'source verification', 'numerical data extraction']\n */\n capabilities?: string[];\n}\n\n/**\n * Planner agent that creates structured execution plans:\n * 1. Understanding Phase: Deeply understand the user's request\n * 2. Variable Extraction: Extract relevant variables and their corresponding numerical values\n * 3. Plan Devising: Break down into specific, actionable steps\n * 4. Success Criteria: Define how to know when the task is complete\n *\n * Enhanced with adaptive replanning for dynamic task execution.\n */\nconst plannerModel = wrapLanguageModel({\n model: lmstudio('google/gemma-3-12b'),\n // model: groq('moonshotai/kimi-k2-instruct-0905'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.3 }, // Slightly creative for better planning\n }),\n});\n\nfunction createPlannerPrompt(context?: {\n environment?: PlanEnvironment;\n}): string {\n return `\n <SystemContext>\n You are an expert planning agent that creates adaptive, well-structured plans.\n Plans are executed step-by-step and adjusted as needed based on findings.\n </SystemContext>\n\n <ExecutionEnvironment>\n ${formatEnvironmentContext(context?.environment)}\n\n CRITICAL: Create steps that match the available tools and domain.\n - Only plan steps that can be executed with the available tools\n - Tailor your approach to the executor's domain and capabilities\n - Don't ask for actions the executor cannot perform\n - Frame steps in terms the executor understands\n </ExecutionEnvironment>\n\n <Identity>\n Your task is to deeply understand user requests and create detailed execution plans.\n You excel at:\n - Understanding what users truly need\n - Extracting key variables and constraints\n - Breaking complex tasks into clear, actionable steps\n - Defining success criteria\n - Creating executable plans that match available capabilities\n </Identity>\n\n <PlanningMethodology>\n Follow this two-phase approach:\n First understand the problem, extract relevant variables and their numerical values,\n and devise a plan. Then the plan will be carried out step by step.\n\n ## PHASE 1: Understanding & Analysis\n\n 1. **Understand the Request**\n - What is the user asking for?\n - Why do they need this information?\n - What is the core intent behind the request?\n\n 2. **Extract Variables and Numerals**\n - Identify all key variables (e.g., company names, time periods, categories)\n - **CRITICALLY: Extract numerical values and their units** (e.g., \"3 months\", \"$150k\", \"5 products\")\n - Map variables to their corresponding numerical values (e.g., {timeframe: 3, unit: \"months\"})\n - Note any implicit variables and numerical relationships\n - Identify calculations that may be required\n\n 3. **Identify Constraints**\n - Time constraints (e.g., \"last 3 months\", \"2024\")\n - Category constraints (e.g., \"AI startups\", \"developer tools\")\n - Scope constraints (e.g., \"in Europe\", \"Y Combinator companies\")\n - Quality constraints (e.g., \"above $150k\", \"4-day work week\")\n\n 4. **Define Success**\n - How will we know the task is complete?\n - What must be included in the final result?\n - What level of detail is needed?\n\n ## PHASE 2: Plan Creation\n\n 5. **Devise Subtasks**\n - Break the request into smaller, specific steps\n - Each step should gather ONE specific type of information\n - Make each step independently executable\n\n 6. **Specify Expected Outcomes**\n - For each step, define what should be accomplished\n - This helps the executor know what to deliver\n - This helps the replanner know if the step succeeded\n\n </PlanningMethodology>\n\n <StepDesignPrinciples>\n Each step should:\n \u2713 Be SPECIFIC and ACTIONABLE\n \u2713 Focus on gathering ONE type of information\n \u2713 Start with action verbs: \"Find...\", \"Identify...\", \"Determine...\", \"Extract...\"\n \u2713 Have a clear expected outcome\n \u2713 Be verifiable (can check if it succeeded)\n\n Avoid:\n \u2717 Vague steps like \"Research the topic\"\n \u2717 Implementation details like \"Query the database\"\n \u2717 Multiple objectives in one step\n \u2717 Summary/aggregation steps (that happens automatically)\n \u2717 Delivery steps (system handles that)\n </StepDesignPrinciples>\n\n <Examples>\n Example 1: Web Research Task\n\n User Request: \"Did Apple release any new products in the past 3 months?\"\n Environment: Executor Type: research, Tools: [browser_search, scratchpad], Domain: market research\n\n Understanding: User wants to know about recent Apple product launches\n\n Variables (with numerical values extracted):\n - company: \"Apple\"\n - timeframe_value: 3\n - timeframe_unit: \"months\"\n - info_type: \"product releases\"\n\n Constraints:\n - Only products (not services, updates, etc.)\n - Only last 3 months\n - Apple only (not subsidiaries)\n\n Success Criteria: List of Apple products released in last 3 months with names and dates\n\n Steps (tailored to browser_search capability):\n 1. Search Apple's newsroom for product announcements from the past 3 months\n Expected: List of official press releases and announcements\n\n 2. Identify product-specific announcements (filter out software updates, services)\n Expected: Subset of announcements that are actual product launches\n\n 3. Extract product names and release dates from announcements\n Expected: Product name, date, and brief description for each\n\n ---\n\n Example 2: HackerNews Research Task\n\n User Request: \"What does the tech community think about Rust vs Go?\"\n Environment: Executor Type: hackernews, Tools: [hackernews_search, scratchpad], Domain: hackernews sentiment analysis\n\n Understanding: User wants to understand tech community opinions comparing Rust and Go\n\n Variables:\n - languages: [\"Rust\", \"Go\"]\n - info_type: \"sentiment comparison\"\n\n Constraints:\n - HackerNews community only\n - Recent discussions preferred\n\n Success Criteria: Summary of HN community sentiment on Rust vs Go with key points from both sides\n\n Steps (tailored to hackernews_search capability):\n 1. Search HackerNews for recent discussions about Rust programming language\n Expected: Stories and comments about Rust with engagement metrics\n\n 2. Search HackerNews for recent discussions about Go programming language\n Expected: Stories and comments about Go with engagement metrics\n\n 3. Search HackerNews for direct comparisons between Rust and Go\n Expected: Discussions explicitly comparing the two languages\n </Examples>\n\n <CriticalInstructions>\n - Take time to truly UNDERSTAND the request before planning\n - **Extract ALL relevant variables with their numerical values**\n - Separate numerical values from their units (e.g., 3 and \"months\", not \"3 months\")\n - Identify any calculations or comparisons that will be needed\n - Create focused steps that each have ONE clear purpose\n - Define what success looks like\n - Steps should be about WHAT to find, not HOW to find it\n - Remember: the plan will be adjusted as execution proceeds\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured plan with:\n 1. Understanding of the request\n 2. Extracted variables (as key-value pairs)\n 3. Identified constraints\n 4. Success criteria\n 5. Ordered list of steps with expected outcomes.\n </OutputFormat>\n `;\n}\n\n/**\n * Format environment context for the planner prompt\n */\nfunction formatEnvironmentContext(environment?: PlanEnvironment): string {\n if (!environment) {\n return `No specific environment provided. Infer environment from user request.`;\n }\n\n const capabilitiesText = environment.capabilities\n ? `\\n Capabilities: ${environment.capabilities.join(', ')}`\n : '';\n\n return `\n Executor Type: ${environment.executor_type}\n Domain: ${environment.domain}\n Available Tools: ${environment.available_tools.join(', ')}${capabilitiesText}\n `.trim();\n}\n\n/**\n * Create an execution plan for the given user request\n *\n * @param userRequest - The user's task or question\n * @param environment - Optional execution environment describing available tools and domain\n */\nexport async function plan(\n userRequest: string,\n state: { environment?: PlanEnvironment } = {},\n) {\n const context = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `planner-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n context.set(\n persona({\n name: 'planner_agent',\n role: 'You are an expert planning agent that creates adaptive, well-structured plans.',\n objective:\n 'Deeply understand user requests and return executable plans with structured variables, constraints, success criteria, and steps.',\n }),\n fragment('planner_instructions', createPlannerPrompt(state)),\n user(userRequest),\n );\n\n const plannerOutput = structuredOutput({\n model: plannerModel,\n context,\n schema: PlannerOutputSchema,\n });\n\n const output = await plannerOutput.generate();\n return createExecutionContext(userRequest, output);\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\n\nimport { agent } from '@deepagents/agent';\nimport { scratchpad_tool, search_content_tool } from '@deepagents/toolbox';\n\nimport type { PlanStep, PlannerOutput } from '../planner-agent.ts';\n\n/**\n * Executor Agent\n *\n * Executes individual plan steps while:\n * 1. Tracking what information is gathered\n * 2. Extracting numerical variables from results\n * 3. Calculating intermediate results with attention to accuracy\n * 4. Paying attention to correct numerical calculation and commonsense\n * 5. Making observations about findings\n * 6. Noting any issues or unexpected results\n */\nexport const executorAgent = agent({\n name: 'executor_agent',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0 },\n }),\n }),\n prompt: `\n <SystemContext>\n You are a precise execution agent that follows plans and gathers information systematically.\n You pay close attention to details and track what you find.\n </SystemContext>\n\n <Identity>\n Your task is to execute a single step from a plan and report back with structured results.\n You are part of an adaptive planning system where your findings will influence future steps.\n </Identity>\n\n <ExecutionPrinciples>\n 1. **Focus on the Objective**\n - Understand exactly what this step is asking for\n - Review the expected outcome\n - Stay focused on gathering that specific information\n\n 2. **Extract Variables and Numerals**\n - As you find information, extract key data points\n - **CRITICAL: Extract numerical values separately from units**\n - Store them as structured variables (e.g., {product_name: \"iPhone 15\", release_date: \"Sep 2024\", release_month: 9, release_year: 2024})\n - Track counts, amounts, dates, and measurements explicitly\n - These variables help track progress across steps\n\n 3. **Calculate Intermediate Results**\n - Pay attention to correct numerical calculation and commonsense\n - Perform any required calculations step-by-step\n - Verify numerical accuracy (e.g., date ranges, counts, sums)\n - Check results against common sense (e.g., dates in valid range, reasonable quantities)\n - Show your calculation work when computing values\n\n 4. **Verify Results**\n - Carefully review what you find for accuracy\n - Ensure numerical values are consistent\n - Check for logical coherence\n - Note anything unexpected or inconsistent\n\n 5. **Make Observations**\n - What patterns did you notice?\n - What numerical trends are apparent?\n - What might affect subsequent steps?\n\n 6. **Note Issues**\n - Were there any calculation difficulties?\n - Was the information hard to find?\n - Were there any errors or ambiguities?\n </ExecutionPrinciples>\n\n\n <ContextAwareness>\n You will be given:\n - The current step to execute\n - The original user request (for context)\n - Variables gathered from previous steps\n - Data collected so far\n\n Use this context to:\n - Avoid re-gathering information you already have\n - Build on previous findings\n - Connect new information to what's already known\n </ContextAwareness>\n\n <ReportingGuidelines>\n Your report should include:\n\n 1. **Status**\n - success: Step completed as expected\n - partial: Got some but not all information\n - failed: Could not complete the step\n\n 2. **Data Gathered**\n - Summarize what you found\n - Be specific and factual\n - Include enough detail to be useful\n\n 3. **Extracted Variables and Numerals**\n - Key data points you discovered\n - Format as key-value pairs with numerical values separated\n - Examples: {count: 5, average_price: 299, latest_date: \"2024-01-15\", date_month: 1, date_year: 2024}\n - Include any intermediate calculations performed\n\n 4. **Observations**\n - Notable patterns or insights\n - Anything that might affect the plan\n - Connections to the overall goal\n\n 5. **Issues**\n - Any problems encountered\n - Missing or unclear information\n - Limitations of what you found\n </ReportingGuidelines>\n\n <Examples>\n Step: \"Find Apple's official announcements from the past 3 months\"\n Context: {company: \"Apple\", timeframe: \"3 months\"}\n\n Good Execution:\n - Use browser_search to find Apple newsroom/press releases\n - Filter results to last 3 months\n - List the announcements found\n - Extract count, dates, types\n - Note any gaps or issues\n\n Report (with numerical extraction):\n - Status: success\n - Data: \"Found 15 press releases from Apple newsroom (Oct-Dec 2024)\"\n - Variables: {\n press_release_count: 15,\n date_range: \"Oct-Dec 2024\",\n start_month: 10,\n end_month: 12,\n year: 2024,\n months_covered: 3\n }\n - Observations: [\"Mix of product, service, and corporate announcements\", \"Exactly covers the requested 3-month timeframe\"]\n - Issues: []\n </Examples>\n\n <CriticalInstructions>\n - Execute the step precisely as described\n - **Extract numerical variables and their values separately**\n - **Pay attention to correct numerical calculation and commonsense**\n - Calculate and verify intermediate results step-by-step\n - Report accurately with verified numbers - your results influence future steps\n - Use the context from previous steps to work smarter\n - If you can't find something, say so clearly\n - Double-check all numerical values for accuracy\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured step result with:\n - status (success/partial/failed)\n - data_gathered (summary of findings)\n - extracted_variables (key-value pairs)\n - observations (notable insights)\n - issues (any problems)\n </OutputFormat>\n `,\n tools: {\n scratchpad: scratchpad_tool,\n search: search_content_tool,\n // browser_search: groq.tools.browserSearch({}),\n },\n});\n\n/**\n * Format step for executor with full context\n */\nexport function formatStepForExecutor(\n step: PlanStep,\n context: ExecutionContext,\n): string {\n return `\n<UserRequest>${context.original_request}</UserRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<PreviousSteps>\n${context.step_results.length ? context.step_results.map((result, i) => `Step ${i + 1}: ${result}`).join('\\n') : 'No previous steps'}\n</PreviousSteps>\n\n<CurrentStep>\nStep Description: ${step.description}\nExpected Outcome: ${step.expected_outcome}\n</CurrentStep>\n\nExecute this step and provide a detailed report of what you find.\n `.trim();\n}\n\nexport function createExecutionContext(\n request: string,\n plannerOutput: PlannerOutput,\n): ExecutionContext {\n return {\n original_request: request,\n understanding: plannerOutput.understanding,\n initial_plan: plannerOutput.steps,\n current_plan: [...plannerOutput.steps],\n variables: { ...plannerOutput.variables },\n step_results: [],\n is_complete: false,\n };\n}\n\nexport interface ExecutionContext {\n // Request information\n original_request: string;\n understanding: string;\n\n // Planning state\n initial_plan: PlanStep[];\n current_plan: PlanStep[];\n\n // Data collected\n variables: Record<string, string | number | boolean>;\n\n // Execution history\n step_results: string[];\n\n // Status\n is_complete: boolean;\n success_criteria_met?: boolean;\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,6BAAAA,4BAA2B,qBAAAC,0BAAyB;AAC7D,OAAO,OAAO;AAEd,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACZP,SAAS,YAAY;AACrB,SAAS,2BAA2B,yBAAyB;AAE7D,SAAS,aAAa;AACtB,SAAS,iBAAiB,2BAA2B;AAe9C,IAAM,gBAAgB,MAAM;AAAA,EACjC,MAAM;AAAA,EACN,OAAO,kBAAkB;AAAA,IACvB,OAAO,KAAK,oBAAoB;AAAA,IAChC,YAAY,0BAA0B;AAAA,MACpC,UAAU,EAAE,aAAa,EAAE;AAAA,IAC7B,CAAC;AAAA,EACH,CAAC;AAAA,EACD,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgKtD;AAKA,SAAS,yBAAyB,aAAuC;AACvE,MAAI,CAAC,aAAa;AAChB,WAAO;AAAA,EACT;AAEA,QAAM,mBAAmB,YAAY,eACjC;AAAA,sBAAyB,YAAY,aAAa,KAAK,IAAI,CAAC,KAC5D;AAEJ,SAAO;AAAA,uBACc,YAAY,aAAa;AAAA,gBAChC,YAAY,MAAM;AAAA,yBACT,YAAY,gBAAgB,KAAK,IAAI,CAAC,GAAG,gBAAgB;AAAA,IAC9E,KAAK;AACT;AAQA,eAAsB,KACpB,aACA,QAA2C,CAAC,GAC5C;AACA,QAAM,UAAU,IAAI,cAAc;AAAA,IAChC,OAAO,IAAI,qBAAqB;AAAA,IAChC,QAAQ,WAAW,OAAO,WAAW,CAAC;AAAA,IACtC,QAAQ;AAAA,EACV,CAAC;AAED,UAAQ;AAAA,IACN,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,WACE;AAAA,IACJ,CAAC;AAAA,IACD,SAAS,wBAAwB,oBAAoB,KAAK,CAAC;AAAA,IAC3D,KAAK,WAAW;AAAA,EAClB;AAEA,QAAM,gBAAgB,iBAAiB;AAAA,IACrC,OAAO;AAAA,IACP;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AAED,QAAM,SAAS,MAAM,cAAc,SAAS;AAC5C,SAAO,uBAAuB,aAAa,MAAM;AACnD;",
|
|
6
6
|
"names": ["defaultSettingsMiddleware", "wrapLanguageModel", "wrapLanguageModel", "defaultSettingsMiddleware"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replanner-agent.d.ts","sourceRoot":"","sources":["../../../src/lib/deepplan/replanner-agent.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,KAAK,CAAC;AAapB,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAUnD,eAAO,MAAM,oBAAoB;;;;;;;;iBAU/B,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAgOlE,wBAAsB,MAAM,CAAC,OAAO,EAAE,gBAAgB;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"replanner-agent.d.ts","sourceRoot":"","sources":["../../../src/lib/deepplan/replanner-agent.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,KAAK,CAAC;AAapB,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAUnD,eAAO,MAAM,oBAAoB;;;;;;;;iBAU/B,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAgOlE,wBAAsB,MAAM,CAAC,OAAO,EAAE,gBAAgB;;;;;;;;;;;;GA+BrD"}
|
|
@@ -403,8 +403,7 @@ async function replan(context) {
|
|
|
403
403
|
context: plannerContext,
|
|
404
404
|
schema: ReplanDecisionSchema
|
|
405
405
|
});
|
|
406
|
-
const
|
|
407
|
-
const decision = output;
|
|
406
|
+
const decision = await replannerOutput.generate();
|
|
408
407
|
return {
|
|
409
408
|
...context,
|
|
410
409
|
current_plan: decision.remaining_steps,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/deepplan/replanner-agent.ts", "../../../src/lib/deepplan/executors/generic-executor.ts"],
|
|
4
|
-
"sourcesContent": ["import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { lmstudio } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n createBashTool,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport { type ExecutionContext } from './executors/generic-executor.ts';\nimport type { PlanStep } from './planner-agent.ts';\n\nconst PlanStepSchema = z.object({\n description: z\n .string()\n .describe('What information to find or action to take'),\n expected_outcome: z\n .string()\n .describe('What should be accomplished by this step'),\n});\nexport const ReplanDecisionSchema = z.object({\n reasoning: z.string().describe('Why this replanning decision was made'),\n should_continue: z.boolean().describe('Should we continue executing?'),\n remaining_steps: z\n .array(PlanStepSchema)\n .max(4)\n .describe('Updated list of remaining steps'),\n new_insights: z\n .string()\n .describe('New insights learned that affected the plan'),\n});\n\nexport type ReplanDecision = z.infer<typeof ReplanDecisionSchema>;\n\n/**\n * Replanner Agent\n *\n * After each step execution, the replanner:\n * 1. Reviews what was accomplished vs what was expected\n * 2. Analyzes how this affects the remaining plan\n * 3. Decides if the plan needs adjustment\n * 4. Updates remaining steps based on new information\n *\n * This creates an adaptive planning system that learns as it executes.\n */\nconst replannerModel = wrapLanguageModel({\n // model: groq('moonshotai/kimi-k2-instruct-0905'),\n model: lmstudio('google/gemma-3-12b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.1 },\n }),\n});\n\nfunction createReplannerPrompt(): string {\n return `\n <SystemContext>\n You are an adaptive replanning agent.\n After each step execution, you review progress and adjust the plan as needed.\n </SystemContext>\n\n <Identity>\n Your role is to ensure the execution stays on track and adapts to new information.\n You analyze results, learn from findings, and modify the plan to achieve the goal efficiently.\n </Identity>\n\n <ReplanningPrinciples>\n 1. **Review Results**\n - What was the step supposed to accomplish?\n - What was actually accomplished?\n - Was it successful, partial, or failed?\n\n 2. **Analyze Impact**\n - How do these results affect the overall goal?\n - What did we learn that we didn't know before?\n - Does this change what we need to do next?\n\n 3. **Assess Remaining Plan**\n - Are the remaining steps still appropriate?\n - Do we need additional steps?\n - Can we skip any steps?\n - Should we change the order?\n\n 4. **Make Decisions**\n - Should we continue with the plan?\n - What adjustments are needed?\n - How significant are the changes?\n\n 5. **Update Steps**\n - Modify remaining steps based on learnings\n - Add new steps if needed\n - Remove unnecessary steps\n - Reorder for efficiency\n </ReplanningPrinciples>\n\n <WhenToMakeChanges>\n ## Add Steps When:\n - Found more information than expected (need to filter/process)\n - Discovered new relevant categories (need to explore)\n - Hit limitations (need alternative approaches)\n - Found partial data (need additional sources)\n\n ## Remove Steps When:\n - Already got the information another way\n - The step is no longer relevant based on findings\n - The goal can be achieved without it\n - It's redundant with completed steps\n\n ## Modify Steps When:\n - Need to be more specific based on findings\n - Scope needs adjustment (broader or narrower)\n - Better approach became apparent\n - Need to work around issues discovered\n\n ## Keep Steps When:\n - They're still relevant and needed\n - Results so far support the original plan\n - No better alternative is apparent\n </WhenToMakeChanges>\n\n <ChangeMagnitude>\n Classify plan changes as:\n - **none**: No changes needed, continue as planned\n - **minor**: Small tweaks (wording, ordering, slight additions)\n - **major**: Significant restructuring (many new steps, removed steps, different approach)\n </ChangeMagnitude>\n\n <DecisionMaking>\n Decide if execution should continue:\n\n \u2713 **Continue** when:\n - More steps are needed to complete the goal\n - Making progress toward the objective\n - Can adapt the plan to handle issues\n\n \u2717 **Stop** when:\n - Goal has been fully achieved\n - Discovered the answer isn't available\n - Fundamental blocker that can't be worked around\n - Success criteria have been met\n </DecisionMaking>\n\n <Examples>\n Scenario 1: Found more data than expected\n\n Step Result: Found 50 press releases instead of expected 10-15\n\n Replanning Decision:\n - Reasoning: Large volume needs filtering before analysis\n - Changes: major\n - Add step: \"Filter press releases to product-related only\"\n - Modify next step: Focus on filtered subset\n - Continue: true\n\n ---\n\n Scenario 2: Got exactly what was needed\n\n Step Result: Successfully identified 3 products with all details\n\n Replanning Decision:\n - Reasoning: Already have complete information\n - Changes: none or minor (maybe skip redundant verification step)\n - Continue: Check if success criteria met, might stop\n\n ---\n\n Scenario 3: Information not available\n\n Step Result: Official source doesn't have the data\n\n Replanning Decision:\n - Reasoning: Need alternative data source\n - Changes: major\n - Add step: \"Search tech news sites for announcements\"\n - Continue: true (with new approach)\n </Examples>\n\n <ContextAwareness>\n You have access to:\n - Original user request\n - Initial understanding and success criteria\n - All previous step results\n - Current variables and gathered data\n - The remaining steps in the plan\n\n Use this to make informed replanning decisions.\n </ContextAwareness>\n\n <CriticalInstructions>\n - Be thoughtful but decisive\n - Adapt the plan based on ACTUAL results, not assumptions\n - Keep the end goal in mind (user's original request)\n - Don't keep executing steps if the goal is already achieved\n - Don't abandon the plan too easily - adapt when possible\n - Make changes that improve efficiency and effectiveness\n - Explain your reasoning clearly\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a replanning decision with:\n - reasoning: Why you're making this decision\n - should_continue: true/false\n - remaining_steps: Updated list of steps to execute\n - new_insights: What you learned that affected the plan\n </OutputFormat>\n `;\n}\n\nfunction formatReplannerPrompt(\n context: ExecutionContext,\n remainingSteps: PlanStep[],\n): string {\n const executionHistory = context.step_results\n .map((r, i) => `Step ${i}: ${r}`)\n .join('\\n');\n\n return `\n<OriginalRequest>${context.original_request}</OriginalRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<SuccessCriteria>\nCheck if we have achieved the goal of the original request.\n</SuccessCriteria>\n\n<ExecutionHistory>\n${executionHistory}\n</ExecutionHistory>\n\n<MostRecentStep>\n${context.step_results.at(-1) ?? 'No steps executed yet'}\n</MostRecentStep>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<RemainingSteps>\n${remainingSteps.length > 0 ? remainingSteps.map((s, i) => `${i}. ${s.description} (Expected: ${s.expected_outcome})`).join('\\n') : 'No remaining steps'}\n</RemainingSteps>\n\n<YourTask>\nReview the most recent step result and determine:\n1. Should we continue execution?\n2. Does the plan need adjustment based on what we found?\n3. What should the remaining steps be?\n\nConsider:\n- Did we find what we were looking for?\n- Is the goal achievable with the current approach?\n- Do results suggest a better path forward?\n- Have we already met the success criteria?\n</YourTask>\n `.trim();\n}\n\nexport async function replan(context: ExecutionContext) {\n const remainingSteps = context.current_plan.slice(1);\n const plannerContext = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `replanner-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n plannerContext.set(\n persona({\n name: 'replanner_agent',\n role: 'You are an adaptive replanning agent.',\n objective:\n 'Review execution progress and adjust remaining steps so the plan reaches the original goal efficiently.',\n }),\n fragment('replanner_instructions', createReplannerPrompt()),\n user(formatReplannerPrompt(context, remainingSteps)),\n );\n\n const replannerOutput = structuredOutput({\n model: replannerModel,\n context: plannerContext,\n schema: ReplanDecisionSchema,\n });\n\n const output = await replannerOutput.generate();\n const decision = output as {\n remaining_steps: typeof context.current_plan;\n should_continue: boolean;\n };\n return {\n ...context,\n current_plan: decision.remaining_steps,\n is_complete: !decision.should_continue,\n };\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\n\nimport { agent } from '@deepagents/agent';\nimport { scratchpad_tool, search_content_tool } from '@deepagents/toolbox';\n\nimport type { PlanStep, PlannerOutput } from '../planner-agent.ts';\n\n/**\n * Executor Agent\n *\n * Executes individual plan steps while:\n * 1. Tracking what information is gathered\n * 2. Extracting numerical variables from results\n * 3. Calculating intermediate results with attention to accuracy\n * 4. Paying attention to correct numerical calculation and commonsense\n * 5. Making observations about findings\n * 6. Noting any issues or unexpected results\n */\nexport const executorAgent = agent({\n name: 'executor_agent',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0 },\n }),\n }),\n prompt: `\n <SystemContext>\n You are a precise execution agent that follows plans and gathers information systematically.\n You pay close attention to details and track what you find.\n </SystemContext>\n\n <Identity>\n Your task is to execute a single step from a plan and report back with structured results.\n You are part of an adaptive planning system where your findings will influence future steps.\n </Identity>\n\n <ExecutionPrinciples>\n 1. **Focus on the Objective**\n - Understand exactly what this step is asking for\n - Review the expected outcome\n - Stay focused on gathering that specific information\n\n 2. **Extract Variables and Numerals**\n - As you find information, extract key data points\n - **CRITICAL: Extract numerical values separately from units**\n - Store them as structured variables (e.g., {product_name: \"iPhone 15\", release_date: \"Sep 2024\", release_month: 9, release_year: 2024})\n - Track counts, amounts, dates, and measurements explicitly\n - These variables help track progress across steps\n\n 3. **Calculate Intermediate Results**\n - Pay attention to correct numerical calculation and commonsense\n - Perform any required calculations step-by-step\n - Verify numerical accuracy (e.g., date ranges, counts, sums)\n - Check results against common sense (e.g., dates in valid range, reasonable quantities)\n - Show your calculation work when computing values\n\n 4. **Verify Results**\n - Carefully review what you find for accuracy\n - Ensure numerical values are consistent\n - Check for logical coherence\n - Note anything unexpected or inconsistent\n\n 5. **Make Observations**\n - What patterns did you notice?\n - What numerical trends are apparent?\n - What might affect subsequent steps?\n\n 6. **Note Issues**\n - Were there any calculation difficulties?\n - Was the information hard to find?\n - Were there any errors or ambiguities?\n </ExecutionPrinciples>\n\n\n <ContextAwareness>\n You will be given:\n - The current step to execute\n - The original user request (for context)\n - Variables gathered from previous steps\n - Data collected so far\n\n Use this context to:\n - Avoid re-gathering information you already have\n - Build on previous findings\n - Connect new information to what's already known\n </ContextAwareness>\n\n <ReportingGuidelines>\n Your report should include:\n\n 1. **Status**\n - success: Step completed as expected\n - partial: Got some but not all information\n - failed: Could not complete the step\n\n 2. **Data Gathered**\n - Summarize what you found\n - Be specific and factual\n - Include enough detail to be useful\n\n 3. **Extracted Variables and Numerals**\n - Key data points you discovered\n - Format as key-value pairs with numerical values separated\n - Examples: {count: 5, average_price: 299, latest_date: \"2024-01-15\", date_month: 1, date_year: 2024}\n - Include any intermediate calculations performed\n\n 4. **Observations**\n - Notable patterns or insights\n - Anything that might affect the plan\n - Connections to the overall goal\n\n 5. **Issues**\n - Any problems encountered\n - Missing or unclear information\n - Limitations of what you found\n </ReportingGuidelines>\n\n <Examples>\n Step: \"Find Apple's official announcements from the past 3 months\"\n Context: {company: \"Apple\", timeframe: \"3 months\"}\n\n Good Execution:\n - Use browser_search to find Apple newsroom/press releases\n - Filter results to last 3 months\n - List the announcements found\n - Extract count, dates, types\n - Note any gaps or issues\n\n Report (with numerical extraction):\n - Status: success\n - Data: \"Found 15 press releases from Apple newsroom (Oct-Dec 2024)\"\n - Variables: {\n press_release_count: 15,\n date_range: \"Oct-Dec 2024\",\n start_month: 10,\n end_month: 12,\n year: 2024,\n months_covered: 3\n }\n - Observations: [\"Mix of product, service, and corporate announcements\", \"Exactly covers the requested 3-month timeframe\"]\n - Issues: []\n </Examples>\n\n <CriticalInstructions>\n - Execute the step precisely as described\n - **Extract numerical variables and their values separately**\n - **Pay attention to correct numerical calculation and commonsense**\n - Calculate and verify intermediate results step-by-step\n - Report accurately with verified numbers - your results influence future steps\n - Use the context from previous steps to work smarter\n - If you can't find something, say so clearly\n - Double-check all numerical values for accuracy\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured step result with:\n - status (success/partial/failed)\n - data_gathered (summary of findings)\n - extracted_variables (key-value pairs)\n - observations (notable insights)\n - issues (any problems)\n </OutputFormat>\n `,\n tools: {\n scratchpad: scratchpad_tool,\n search: search_content_tool,\n // browser_search: groq.tools.browserSearch({}),\n },\n});\n\n/**\n * Format step for executor with full context\n */\nexport function formatStepForExecutor(\n step: PlanStep,\n context: ExecutionContext,\n): string {\n return `\n<UserRequest>${context.original_request}</UserRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<PreviousSteps>\n${context.step_results.length ? context.step_results.map((result, i) => `Step ${i + 1}: ${result}`).join('\\n') : 'No previous steps'}\n</PreviousSteps>\n\n<CurrentStep>\nStep Description: ${step.description}\nExpected Outcome: ${step.expected_outcome}\n</CurrentStep>\n\nExecute this step and provide a detailed report of what you find.\n `.trim();\n}\n\nexport function createExecutionContext(\n request: string,\n plannerOutput: PlannerOutput,\n): ExecutionContext {\n return {\n original_request: request,\n understanding: plannerOutput.understanding,\n initial_plan: plannerOutput.steps,\n current_plan: [...plannerOutput.steps],\n variables: { ...plannerOutput.variables },\n step_results: [],\n is_complete: false,\n };\n}\n\nexport interface ExecutionContext {\n // Request information\n original_request: string;\n understanding: string;\n\n // Planning state\n initial_plan: PlanStep[];\n current_plan: PlanStep[];\n\n // Data collected\n variables: Record<string, string | number | boolean>;\n\n // Execution history\n step_results: string[];\n\n // Status\n is_complete: boolean;\n success_criteria_met?: boolean;\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,6BAAAA,4BAA2B,qBAAAC,0BAAyB;AAC7D,OAAO,OAAO;AAEd,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACZP,SAAS,YAAY;AACrB,SAAS,2BAA2B,yBAAyB;AAE7D,SAAS,aAAa;AACtB,SAAS,iBAAiB,2BAA2B;AAe9C,IAAM,gBAAgB,MAAM;AAAA,EACjC,MAAM;AAAA,EACN,OAAO,kBAAkB;AAAA,IACvB,OAAO,KAAK,oBAAoB;AAAA,IAChC,YAAY,0BAA0B;AAAA,MACpC,UAAU,EAAE,aAAa,EAAE;AAAA,IAC7B,CAAC;AAAA,EACH,CAAC;AAAA,EACD,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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oB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAepJ,KAAK;AACT;AAEA,eAAsB,OAAO,SAA2B;AACtD,QAAM,iBAAiB,QAAQ,aAAa,MAAM,CAAC;AACnD,QAAM,iBAAiB,IAAI,cAAc;AAAA,IACvC,OAAO,IAAI,qBAAqB;AAAA,IAChC,QAAQ,aAAa,OAAO,WAAW,CAAC;AAAA,IACxC,QAAQ;AAAA,EACV,CAAC;AAED,iBAAe;AAAA,IACb,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,WACE;AAAA,IACJ,CAAC;AAAA,IACD,SAAS,0BAA0B,sBAAsB,CAAC;AAAA,IAC1D,KAAK,sBAAsB,SAAS,cAAc,CAAC;AAAA,EACrD;AAEA,QAAM,kBAAkB,iBAAiB;AAAA,IACvC,OAAO;AAAA,IACP,SAAS;AAAA,IACT,QAAQ;AAAA,EACV,CAAC;AAED,QAAM,
|
|
4
|
+
"sourcesContent": ["import { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { lmstudio } from '@deepagents/agent';\nimport {\n ContextEngine,\n InMemoryContextStore,\n createBashTool,\n fragment,\n persona,\n structuredOutput,\n user,\n} from '@deepagents/context';\n\nimport { type ExecutionContext } from './executors/generic-executor.ts';\nimport type { PlanStep } from './planner-agent.ts';\n\nconst PlanStepSchema = z.object({\n description: z\n .string()\n .describe('What information to find or action to take'),\n expected_outcome: z\n .string()\n .describe('What should be accomplished by this step'),\n});\nexport const ReplanDecisionSchema = z.object({\n reasoning: z.string().describe('Why this replanning decision was made'),\n should_continue: z.boolean().describe('Should we continue executing?'),\n remaining_steps: z\n .array(PlanStepSchema)\n .max(4)\n .describe('Updated list of remaining steps'),\n new_insights: z\n .string()\n .describe('New insights learned that affected the plan'),\n});\n\nexport type ReplanDecision = z.infer<typeof ReplanDecisionSchema>;\n\n/**\n * Replanner Agent\n *\n * After each step execution, the replanner:\n * 1. Reviews what was accomplished vs what was expected\n * 2. Analyzes how this affects the remaining plan\n * 3. Decides if the plan needs adjustment\n * 4. Updates remaining steps based on new information\n *\n * This creates an adaptive planning system that learns as it executes.\n */\nconst replannerModel = wrapLanguageModel({\n // model: groq('moonshotai/kimi-k2-instruct-0905'),\n model: lmstudio('google/gemma-3-12b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.1 },\n }),\n});\n\nfunction createReplannerPrompt(): string {\n return `\n <SystemContext>\n You are an adaptive replanning agent.\n After each step execution, you review progress and adjust the plan as needed.\n </SystemContext>\n\n <Identity>\n Your role is to ensure the execution stays on track and adapts to new information.\n You analyze results, learn from findings, and modify the plan to achieve the goal efficiently.\n </Identity>\n\n <ReplanningPrinciples>\n 1. **Review Results**\n - What was the step supposed to accomplish?\n - What was actually accomplished?\n - Was it successful, partial, or failed?\n\n 2. **Analyze Impact**\n - How do these results affect the overall goal?\n - What did we learn that we didn't know before?\n - Does this change what we need to do next?\n\n 3. **Assess Remaining Plan**\n - Are the remaining steps still appropriate?\n - Do we need additional steps?\n - Can we skip any steps?\n - Should we change the order?\n\n 4. **Make Decisions**\n - Should we continue with the plan?\n - What adjustments are needed?\n - How significant are the changes?\n\n 5. **Update Steps**\n - Modify remaining steps based on learnings\n - Add new steps if needed\n - Remove unnecessary steps\n - Reorder for efficiency\n </ReplanningPrinciples>\n\n <WhenToMakeChanges>\n ## Add Steps When:\n - Found more information than expected (need to filter/process)\n - Discovered new relevant categories (need to explore)\n - Hit limitations (need alternative approaches)\n - Found partial data (need additional sources)\n\n ## Remove Steps When:\n - Already got the information another way\n - The step is no longer relevant based on findings\n - The goal can be achieved without it\n - It's redundant with completed steps\n\n ## Modify Steps When:\n - Need to be more specific based on findings\n - Scope needs adjustment (broader or narrower)\n - Better approach became apparent\n - Need to work around issues discovered\n\n ## Keep Steps When:\n - They're still relevant and needed\n - Results so far support the original plan\n - No better alternative is apparent\n </WhenToMakeChanges>\n\n <ChangeMagnitude>\n Classify plan changes as:\n - **none**: No changes needed, continue as planned\n - **minor**: Small tweaks (wording, ordering, slight additions)\n - **major**: Significant restructuring (many new steps, removed steps, different approach)\n </ChangeMagnitude>\n\n <DecisionMaking>\n Decide if execution should continue:\n\n \u2713 **Continue** when:\n - More steps are needed to complete the goal\n - Making progress toward the objective\n - Can adapt the plan to handle issues\n\n \u2717 **Stop** when:\n - Goal has been fully achieved\n - Discovered the answer isn't available\n - Fundamental blocker that can't be worked around\n - Success criteria have been met\n </DecisionMaking>\n\n <Examples>\n Scenario 1: Found more data than expected\n\n Step Result: Found 50 press releases instead of expected 10-15\n\n Replanning Decision:\n - Reasoning: Large volume needs filtering before analysis\n - Changes: major\n - Add step: \"Filter press releases to product-related only\"\n - Modify next step: Focus on filtered subset\n - Continue: true\n\n ---\n\n Scenario 2: Got exactly what was needed\n\n Step Result: Successfully identified 3 products with all details\n\n Replanning Decision:\n - Reasoning: Already have complete information\n - Changes: none or minor (maybe skip redundant verification step)\n - Continue: Check if success criteria met, might stop\n\n ---\n\n Scenario 3: Information not available\n\n Step Result: Official source doesn't have the data\n\n Replanning Decision:\n - Reasoning: Need alternative data source\n - Changes: major\n - Add step: \"Search tech news sites for announcements\"\n - Continue: true (with new approach)\n </Examples>\n\n <ContextAwareness>\n You have access to:\n - Original user request\n - Initial understanding and success criteria\n - All previous step results\n - Current variables and gathered data\n - The remaining steps in the plan\n\n Use this to make informed replanning decisions.\n </ContextAwareness>\n\n <CriticalInstructions>\n - Be thoughtful but decisive\n - Adapt the plan based on ACTUAL results, not assumptions\n - Keep the end goal in mind (user's original request)\n - Don't keep executing steps if the goal is already achieved\n - Don't abandon the plan too easily - adapt when possible\n - Make changes that improve efficiency and effectiveness\n - Explain your reasoning clearly\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a replanning decision with:\n - reasoning: Why you're making this decision\n - should_continue: true/false\n - remaining_steps: Updated list of steps to execute\n - new_insights: What you learned that affected the plan\n </OutputFormat>\n `;\n}\n\nfunction formatReplannerPrompt(\n context: ExecutionContext,\n remainingSteps: PlanStep[],\n): string {\n const executionHistory = context.step_results\n .map((r, i) => `Step ${i}: ${r}`)\n .join('\\n');\n\n return `\n<OriginalRequest>${context.original_request}</OriginalRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<SuccessCriteria>\nCheck if we have achieved the goal of the original request.\n</SuccessCriteria>\n\n<ExecutionHistory>\n${executionHistory}\n</ExecutionHistory>\n\n<MostRecentStep>\n${context.step_results.at(-1) ?? 'No steps executed yet'}\n</MostRecentStep>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<RemainingSteps>\n${remainingSteps.length > 0 ? remainingSteps.map((s, i) => `${i}. ${s.description} (Expected: ${s.expected_outcome})`).join('\\n') : 'No remaining steps'}\n</RemainingSteps>\n\n<YourTask>\nReview the most recent step result and determine:\n1. Should we continue execution?\n2. Does the plan need adjustment based on what we found?\n3. What should the remaining steps be?\n\nConsider:\n- Did we find what we were looking for?\n- Is the goal achievable with the current approach?\n- Do results suggest a better path forward?\n- Have we already met the success criteria?\n</YourTask>\n `.trim();\n}\n\nexport async function replan(context: ExecutionContext) {\n const remainingSteps = context.current_plan.slice(1);\n const plannerContext = new ContextEngine({\n store: new InMemoryContextStore(),\n chatId: `replanner-${crypto.randomUUID()}`,\n userId: 'system',\n });\n\n plannerContext.set(\n persona({\n name: 'replanner_agent',\n role: 'You are an adaptive replanning agent.',\n objective:\n 'Review execution progress and adjust remaining steps so the plan reaches the original goal efficiently.',\n }),\n fragment('replanner_instructions', createReplannerPrompt()),\n user(formatReplannerPrompt(context, remainingSteps)),\n );\n\n const replannerOutput = structuredOutput({\n model: replannerModel,\n context: plannerContext,\n schema: ReplanDecisionSchema,\n });\n\n const decision = await replannerOutput.generate();\n return {\n ...context,\n current_plan: decision.remaining_steps,\n is_complete: !decision.should_continue,\n };\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\n\nimport { agent } from '@deepagents/agent';\nimport { scratchpad_tool, search_content_tool } from '@deepagents/toolbox';\n\nimport type { PlanStep, PlannerOutput } from '../planner-agent.ts';\n\n/**\n * Executor Agent\n *\n * Executes individual plan steps while:\n * 1. Tracking what information is gathered\n * 2. Extracting numerical variables from results\n * 3. Calculating intermediate results with attention to accuracy\n * 4. Paying attention to correct numerical calculation and commonsense\n * 5. Making observations about findings\n * 6. Noting any issues or unexpected results\n */\nexport const executorAgent = agent({\n name: 'executor_agent',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0 },\n }),\n }),\n prompt: `\n <SystemContext>\n You are a precise execution agent that follows plans and gathers information systematically.\n You pay close attention to details and track what you find.\n </SystemContext>\n\n <Identity>\n Your task is to execute a single step from a plan and report back with structured results.\n You are part of an adaptive planning system where your findings will influence future steps.\n </Identity>\n\n <ExecutionPrinciples>\n 1. **Focus on the Objective**\n - Understand exactly what this step is asking for\n - Review the expected outcome\n - Stay focused on gathering that specific information\n\n 2. **Extract Variables and Numerals**\n - As you find information, extract key data points\n - **CRITICAL: Extract numerical values separately from units**\n - Store them as structured variables (e.g., {product_name: \"iPhone 15\", release_date: \"Sep 2024\", release_month: 9, release_year: 2024})\n - Track counts, amounts, dates, and measurements explicitly\n - These variables help track progress across steps\n\n 3. **Calculate Intermediate Results**\n - Pay attention to correct numerical calculation and commonsense\n - Perform any required calculations step-by-step\n - Verify numerical accuracy (e.g., date ranges, counts, sums)\n - Check results against common sense (e.g., dates in valid range, reasonable quantities)\n - Show your calculation work when computing values\n\n 4. **Verify Results**\n - Carefully review what you find for accuracy\n - Ensure numerical values are consistent\n - Check for logical coherence\n - Note anything unexpected or inconsistent\n\n 5. **Make Observations**\n - What patterns did you notice?\n - What numerical trends are apparent?\n - What might affect subsequent steps?\n\n 6. **Note Issues**\n - Were there any calculation difficulties?\n - Was the information hard to find?\n - Were there any errors or ambiguities?\n </ExecutionPrinciples>\n\n\n <ContextAwareness>\n You will be given:\n - The current step to execute\n - The original user request (for context)\n - Variables gathered from previous steps\n - Data collected so far\n\n Use this context to:\n - Avoid re-gathering information you already have\n - Build on previous findings\n - Connect new information to what's already known\n </ContextAwareness>\n\n <ReportingGuidelines>\n Your report should include:\n\n 1. **Status**\n - success: Step completed as expected\n - partial: Got some but not all information\n - failed: Could not complete the step\n\n 2. **Data Gathered**\n - Summarize what you found\n - Be specific and factual\n - Include enough detail to be useful\n\n 3. **Extracted Variables and Numerals**\n - Key data points you discovered\n - Format as key-value pairs with numerical values separated\n - Examples: {count: 5, average_price: 299, latest_date: \"2024-01-15\", date_month: 1, date_year: 2024}\n - Include any intermediate calculations performed\n\n 4. **Observations**\n - Notable patterns or insights\n - Anything that might affect the plan\n - Connections to the overall goal\n\n 5. **Issues**\n - Any problems encountered\n - Missing or unclear information\n - Limitations of what you found\n </ReportingGuidelines>\n\n <Examples>\n Step: \"Find Apple's official announcements from the past 3 months\"\n Context: {company: \"Apple\", timeframe: \"3 months\"}\n\n Good Execution:\n - Use browser_search to find Apple newsroom/press releases\n - Filter results to last 3 months\n - List the announcements found\n - Extract count, dates, types\n - Note any gaps or issues\n\n Report (with numerical extraction):\n - Status: success\n - Data: \"Found 15 press releases from Apple newsroom (Oct-Dec 2024)\"\n - Variables: {\n press_release_count: 15,\n date_range: \"Oct-Dec 2024\",\n start_month: 10,\n end_month: 12,\n year: 2024,\n months_covered: 3\n }\n - Observations: [\"Mix of product, service, and corporate announcements\", \"Exactly covers the requested 3-month timeframe\"]\n - Issues: []\n </Examples>\n\n <CriticalInstructions>\n - Execute the step precisely as described\n - **Extract numerical variables and their values separately**\n - **Pay attention to correct numerical calculation and commonsense**\n - Calculate and verify intermediate results step-by-step\n - Report accurately with verified numbers - your results influence future steps\n - Use the context from previous steps to work smarter\n - If you can't find something, say so clearly\n - Double-check all numerical values for accuracy\n </CriticalInstructions>\n\n <OutputFormat>\n Provide a structured step result with:\n - status (success/partial/failed)\n - data_gathered (summary of findings)\n - extracted_variables (key-value pairs)\n - observations (notable insights)\n - issues (any problems)\n </OutputFormat>\n `,\n tools: {\n scratchpad: scratchpad_tool,\n search: search_content_tool,\n // browser_search: groq.tools.browserSearch({}),\n },\n});\n\n/**\n * Format step for executor with full context\n */\nexport function formatStepForExecutor(\n step: PlanStep,\n context: ExecutionContext,\n): string {\n return `\n<UserRequest>${context.original_request}</UserRequest>\n\n<Understanding>${context.understanding}</Understanding>\n\n<CurrentVariables>\n${JSON.stringify(context.variables, null, 2)}\n</CurrentVariables>\n\n<PreviousSteps>\n${context.step_results.length ? context.step_results.map((result, i) => `Step ${i + 1}: ${result}`).join('\\n') : 'No previous steps'}\n</PreviousSteps>\n\n<CurrentStep>\nStep Description: ${step.description}\nExpected Outcome: ${step.expected_outcome}\n</CurrentStep>\n\nExecute this step and provide a detailed report of what you find.\n `.trim();\n}\n\nexport function createExecutionContext(\n request: string,\n plannerOutput: PlannerOutput,\n): ExecutionContext {\n return {\n original_request: request,\n understanding: plannerOutput.understanding,\n initial_plan: plannerOutput.steps,\n current_plan: [...plannerOutput.steps],\n variables: { ...plannerOutput.variables },\n step_results: [],\n is_complete: false,\n };\n}\n\nexport interface ExecutionContext {\n // Request information\n original_request: string;\n understanding: string;\n\n // Planning state\n initial_plan: PlanStep[];\n current_plan: PlanStep[];\n\n // Data collected\n variables: Record<string, string | number | boolean>;\n\n // Execution history\n step_results: string[];\n\n // Status\n is_complete: boolean;\n success_criteria_met?: boolean;\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,6BAAAA,4BAA2B,qBAAAC,0BAAyB;AAC7D,OAAO,OAAO;AAEd,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACZP,SAAS,YAAY;AACrB,SAAS,2BAA2B,yBAAyB;AAE7D,SAAS,aAAa;AACtB,SAAS,iBAAiB,2BAA2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BAAsB,CAAC;AAAA,IAC1D,KAAK,sBAAsB,SAAS,cAAc,CAAC;AAAA,EACrD;AAEA,QAAM,kBAAkB,iBAAiB;AAAA,IACvC,OAAO;AAAA,IACP,SAAS;AAAA,IACT,QAAQ;AAAA,EACV,CAAC;AAED,QAAM,WAAW,MAAM,gBAAgB,SAAS;AAChD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,cAAc,SAAS;AAAA,IACvB,aAAa,CAAC,SAAS;AAAA,EACzB;AACF;",
|
|
6
6
|
"names": ["defaultSettingsMiddleware", "wrapLanguageModel", "wrapLanguageModel", "defaultSettingsMiddleware"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deepresearch.v0.d.ts","sourceRoot":"","sources":["../../src/lib/deepresearch.v0.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"deepresearch.v0.d.ts","sourceRoot":"","sources":["../../src/lib/deepresearch.v0.ts"],"names":[],"mappings":"AAiHA,wBAAsB,mBAAmB,CACvC,SAAS,EAAE,MAAM,EACjB,qBAAqB,EAAE,MAAM,EAAE,EAC/B,WAAW,EAAE,MAAM,EAAE,EACrB,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,EAAE,CAAC,CAyCnB;AAED,wBAAsB,mBAAmB,CACvC,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,MAAM,EAAE,GACpB,OAAO,CAAC,MAAM,CAAC,CAUjB"}
|