hammer-ai 0.2.0 → 0.2.1

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/index.d.ts CHANGED
@@ -1699,10 +1699,23 @@ interface AgentMemoryFactoryOverrides {
1699
1699
  */
1700
1700
  declare function createAgentMemoryLayer(preset: string, overrides?: AgentMemoryFactoryOverrides): AgentMemoryLayer;
1701
1701
 
1702
+ /**
1703
+ * Shared structured control-segment prompt fragments used across agent loops.
1704
+ *
1705
+ * These helpers centralize the plain header-block response contract while
1706
+ * letting each agent layer domain-specific constraints on top.
1707
+ */
1708
+ declare const TOOL_CALL_SEPARATOR_RULE = "The slug header is a hard separator between prose/thought and command/action. Put all prose before the slug, put the standalone slug header on its own line, and put only the executable payload on the following line(s). There must be a newline before the slug header and a newline after the slug header.";
1709
+ declare const JUST_BASH_SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES: string;
1710
+ declare const JUST_BASH_SCRIPT_EXECUTION_RESTRICTION_LINES: string[];
1702
1711
  interface BashCommandsSectionOptions {
1703
1712
  shellNativeWorkflowCommandExamples?: string;
1704
1713
  additionalGuidanceLines?: string[];
1705
1714
  }
1715
+ declare const STANDARD_TOOL_CALL_FORMAT_RULES: string[];
1716
+ declare const SINGLE_TOOL_CALL_RUN_LINE_EXAMPLE: string;
1717
+ declare const SHARED_TOOL_CALL_EXAMPLE_LINES: string[];
1718
+ declare const CONTINUE_TOOL_CALL_RESPONSE_EXAMPLE: string;
1706
1719
 
1707
1720
  /**
1708
1721
  * Shared prompt building utilities for agentic loops.
@@ -1712,6 +1725,12 @@ interface BashCommandsSectionOptions {
1712
1725
  */
1713
1726
 
1714
1727
  declare const DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT = "You are an AI agent.";
1728
+ declare const ERROR_RECOVERY_RULE_LINE = "**ERROR RECOVERY**: If a tool returns `success=false`, inspect the error, fix the cause, and retry.";
1729
+ declare const ROOT_CAUSES_RULE_LINE = "**ROOT CAUSES**: Fix root causes rather than suppressing symptoms.";
1730
+ declare const VALIDATE_AFTER_CHANGES_RULE_LINE = "**VALIDATE AFTER CHANGES**: Check syntax, imports, and obvious integration errors after editing.";
1731
+ declare const INCREMENTAL_TESTING_RULE_LINE = "**INCREMENTAL TESTING**: Write \u2192 test \u2192 fix before moving on. Verify deliverables actually work before finishing successfully.";
1732
+ declare const CODE_QUALITY_RULE_LINE = "**CODE QUALITY**: For TypeScript, prefer `tsc --noEmit` or the repo's build/test command after meaningful edits.";
1733
+ declare const TODO_LIST_FIRST_RESPONSE_RULE_LINE = "You MUST call the manage_todo_list tool in your very first response to plan your work before executing any other tool. Break the task into specific, actionable steps. On subsequent responses, update the todo list to reflect progress.";
1715
1734
  interface FormatToolsSectionOptions {
1716
1735
  bashAvailable?: boolean;
1717
1736
  backgroundBashAvailable?: boolean;
@@ -1736,6 +1755,44 @@ declare function createToolsSectionOverrideCustomizer(buildToolsSection: (contex
1736
1755
  * Thin wrapper over `formatToolDefinitions` with configurable bash guidance.
1737
1756
  */
1738
1757
  declare function formatToolsSection(tools: ToolDefinition[], options?: FormatToolsSectionOptions): string;
1758
+ interface SkillSummaryLike {
1759
+ metadata: {
1760
+ name: string;
1761
+ description: string;
1762
+ };
1763
+ }
1764
+ declare function buildSkillAwareStaticContext(options: {
1765
+ allSkills: SkillSummaryLike[];
1766
+ staticRules: string;
1767
+ }): string;
1768
+ interface WorkspaceCodingStaticRulesOptions {
1769
+ rulesHeading?: string;
1770
+ skillsDirectory?: string;
1771
+ additionalRuleSections?: readonly WorkspaceCodingStaticRuleSection[];
1772
+ }
1773
+ type WorkspaceCodingStaticBuiltInSection = "workspace-safety" | "editing-strategy" | "verification" | "efficiency";
1774
+ type WorkspaceCodingStaticRuleSection = {
1775
+ section: WorkspaceCodingStaticBuiltInSection;
1776
+ ruleLines?: readonly string[];
1777
+ omitRuleLines?: readonly string[];
1778
+ heading?: never;
1779
+ } | {
1780
+ heading: string;
1781
+ ruleLines: readonly string[];
1782
+ section?: never;
1783
+ omitRuleLines?: never;
1784
+ };
1785
+ declare const PORT_CONFLICT_RULE_LINE = "**PORT CONFLICTS**: If a server fails with `EADDRINUSE` and `FreePort` is available, use it before retrying.";
1786
+ declare function buildWorkspaceCodingStaticRules(options?: WorkspaceCodingStaticRulesOptions): string;
1787
+ declare function buildAgentIdentityLine(options: {
1788
+ identity?: string;
1789
+ agentName?: string;
1790
+ roleDescription?: string;
1791
+ }): string;
1792
+ declare function buildWebRuntimeRules(options?: {
1793
+ additionalRules?: string[];
1794
+ includeVerifiedCompletionRule?: boolean;
1795
+ }): string;
1739
1796
  declare function buildAgentSystemPrompt(options: {
1740
1797
  identityLine?: string;
1741
1798
  tools: ToolDefinition[];
@@ -2051,7 +2108,22 @@ type ToolSchema = ToolDefinition["parameters"];
2051
2108
  interface ToolMetadata extends ToolDefinitionMetadata {
2052
2109
  requirements: string[];
2053
2110
  }
2054
- declare abstract class Tool {
2111
+ /**
2112
+ * Structural interface for any tool that can be registered in a ToolRegistry.
2113
+ * Using an interface lets both this class hierarchy and external class
2114
+ * hierarchies (e.g. @shared/tools) be stored in the same registry without
2115
+ * requiring a shared base-class inheritance chain.
2116
+ */
2117
+ interface ToolLike {
2118
+ execute(params: Record<string, any>): Promise<ToolResult>;
2119
+ getName(): string;
2120
+ getDescription(): string;
2121
+ getSchema(): ToolSchema;
2122
+ getUsageExample(): string | undefined;
2123
+ getMetadata(): ToolMetadata;
2124
+ toDefinition(): ToolDefinition;
2125
+ }
2126
+ declare abstract class Tool implements ToolLike {
2055
2127
  protected workspaceRoot: string;
2056
2128
  constructor(workspaceRoot?: string);
2057
2129
  /**
@@ -2094,7 +2166,7 @@ interface ToolRegistryBeforeExecuteContext {
2094
2166
  registry: ToolRegistry;
2095
2167
  }
2096
2168
  interface ToolRegistryOptions {
2097
- tools?: Iterable<Tool>;
2169
+ tools?: Iterable<ToolLike>;
2098
2170
  canExecute?: boolean | (() => boolean);
2099
2171
  executeBash?: BashExecutor;
2100
2172
  executeBackgroundBash?: BackgroundBashExecutor;
@@ -2102,23 +2174,23 @@ interface ToolRegistryOptions {
2102
2174
  onMissingTool?: (context: ToolRegistryMissingToolContext) => Error | string;
2103
2175
  beforeExecute?: (context: ToolRegistryBeforeExecuteContext) => Promise<ToolResult | void> | ToolResult | void;
2104
2176
  }
2105
- declare function createToolRegistry(tools?: Iterable<Tool>, options?: Omit<ToolRegistryOptions, "tools">): ToolRegistry;
2177
+ declare function createToolRegistry(tools?: Iterable<ToolLike>, options?: Omit<ToolRegistryOptions, "tools">): ToolRegistry;
2106
2178
  declare class ToolRegistry {
2107
- protected tools: Map<string, Tool>;
2179
+ protected tools: Map<string, ToolLike>;
2108
2180
  private canExecuteOverride?;
2109
2181
  private bashExecutor?;
2110
2182
  private backgroundBashExecutor?;
2111
2183
  private runCommandRegistry;
2112
2184
  private onMissingTool?;
2113
2185
  private beforeExecute?;
2114
- constructor(toolsOrOptions?: Iterable<Tool> | ToolRegistryOptions);
2115
- registerTool(tool: Tool): void;
2116
- registerTools(tools: Iterable<Tool>): void;
2117
- replaceTools(tools: Iterable<Tool>): void;
2186
+ constructor(toolsOrOptions?: Iterable<ToolLike> | ToolRegistryOptions);
2187
+ registerTool(tool: ToolLike): void;
2188
+ registerTools(tools: Iterable<ToolLike>): void;
2189
+ replaceTools(tools: Iterable<ToolLike>): void;
2118
2190
  hasTool(name: string): boolean;
2119
- getTool(name: string): Tool;
2191
+ getTool(name: string): ToolLike;
2120
2192
  protected buildMissingToolError(name: string): Error;
2121
- getTools(): Tool[];
2193
+ getTools(): ToolLike[];
2122
2194
  executeTool(name: string, parameters: Record<string, any>): Promise<ToolResult>;
2123
2195
  executeToolCall(toolCall: ToolCall): Promise<ToolResult>;
2124
2196
  private createConcreteRuntime;
@@ -2228,4 +2300,4 @@ declare function runStructuredLLMCompaction<TMessage extends MemoryMessage, TSta
2228
2300
  parseState: (obj: Record<string, unknown>) => TState | null;
2229
2301
  }): Promise<TState | null>;
2230
2302
 
2231
- export { AGENT_MACHINE_STATES, AgentLoop, type AgentLoopCallbacks, type AgentLoopDeps, type AgentMachineContext, type AgentMachineEvent, type AgentMachineState, type AgentMemoryCitation, type AgentMemoryConstraint, type AgentMemoryEvidence, type AgentMemoryFactoryOverrides, AgentMemoryLayer, type AgentMemoryLayerConfig, type AgentMemoryLogger, type AgentMemoryNote, type AgentMemoryTask, type AgentMessage, type AgentPhase, type AgentState, ApiError, type BackgroundBashAction, BackgroundBashRunCommand, BaseMemoryLayer, BaseValidationEnforcer, BashRunCommand, type BuildMemoryCompactionPromptOptions, CharTokenEstimator, type ChatMessage, type CommandRuntime, type CommandTargetInfo, type CompactionCursor, type CompactionLLMClient, type ConversationAdapter, type ConversationSink, type CreateWebRuntimeSetupOptions, DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT, DEFAULT_ALLOWED_RUN_TARGETS, DEFAULT_RUN_COMMAND_REGISTRY, DEFAULT_THREAD_AUTO_SCROLL_BOTTOM_THRESHOLD, DEFAULT_TOOL_MEMORY_EXTRACTOR, ERROR_TRUNCATED_RESPONSE, type EnforcerResult, type ExecuteWebLoopRunOptions, type FetchLike, type FetchResponseLike, type HammerAgentConfig, type HammerAgentProviderPreset, LLMClient, type LLMClientResponse, type LLMProviderConfig, type LLMRequest, type LLMRequestOptions, type LLMResponse, type LoopOutcome, MAX_TOOL_RESULT_CHARS, type MemoryMessage, type MemoryProvenance, type MemoryStorage, type ParseAgentResponseOptions, type ParsedAgentResponse, type ParsedBackgroundBashCommand, type ParsedStepInput, PendingAgentMessageBuffer, type PersistedMemoryData, type ProviderName, ProxyTool, type ProxyToolExecutor, type RawMessage, RunCommand, type RunCommandParseResult, type RunCommandPromptAvailability, RunCommandRegistry, type RunInvocationTarget, type RuntimeController, type RuntimeSnapshotUpdater, type RuntimeStore, type RuntimeSubscriber, SUPPORTED_RUN_TARGETS, type StepResult, type StreamCallbacks, StreamingToolParser, type StreamingToolParserCallbacks, type SystemPromptCustomizer, type TodoItem, type TodoStatus, type TokenEstimator, Tool, type ToolCall, type ToolDataPrimitive, type ToolDataSchema, type ToolDataValue, type ToolDefinition, type ToolDefinitionMetadata, type ToolExecutionResult, ToolLoopAgentRuntime, type ToolLoopAgentRuntimeDeps, type ToolLoopRuntimeExecuteStepResult, type ToolLoopRuntimeHooks, type ToolLoopRuntimeInfrastructure, type ToolLoopRuntimeLLMRequest, type ToolLoopRuntimeLLMResponse, type ToolLoopRuntimeRunStepOptions, type ToolLoopRuntimeRunStepResult, type ToolLoopRuntimeSetup, type ToolLoopRuntimeStepContext, type ToolLoopStepExecutionResult, type ToolLoopStepExecutorCallbacks, type ToolLoopStepExecutorOptions, type ToolLoopStepExecutorResponse, type ToolMemoryCitationKind, type ToolMemoryEvidenceKind, type ToolMemoryEvidencePolicy, type ToolMemoryExtractor, type ToolMemoryMetadata, type ToolMemoryNoteKind, type ToolMemoryNotePolicy, type ToolMemoryNoteScope, type ToolMetadata, type ToolParameterDefinition, ToolRegistry, type ToolRegistryBeforeExecuteContext, type ToolRegistryMissingToolContext, type ToolRegistryOptions, type ToolResult, ToolRunCommand, type ToolSchema, type TruncatedToolInfo, type WebSearchToolActionInput, WebToolLoopAgentRuntime, type WebToolLoopAgentRuntimeConstructorOptions, type WebToolLoopRuntimeStateLike, WebValidationEnforcer, agentMachine, applyIdleWebAgentState, applyInitialWebAgentRunState, buildAgentSystemPrompt, buildCompactionEntry, buildCoreStaticRules, buildNoStructuredResponseFoundError, buildParseFeedback, buildStepUserMessage, buildToolLogRevealFrames, buildToolUsageExample, buildValidationErrorMessage, canonicalizeCompactionText, coerceToolCallToDefinition, configure, containsStandaloneStructuredInvocationStart, createAgentMemoryLayer, createAppendToolsSectionCustomizer, createBackgroundBashDefinition, createConversationSink, createCustomRunCommandRegistry, createInitialWebAgentState, createRunCommandRuntimeBindings, createRuntimeStore, createToolAgentMessage, createToolRegistry, createToolsSectionOverrideCustomizer, createWebAgentMessageIdGenerator, createWebSearchToolActions, createWebToolLoopCallbacks, decodeEscapedShellText, defineRuntimeController, enrichToolResultWithUnixMetadata, executeBackgroundUnixCommandString, executeToolCallWithRunCommands, executeToolLoopStep, executeToolSafe, executeUnixCommandString, extractPrimaryCommandMetadata, extractTruncatedToolInfo, formatToolCallAsUnixCommand, formatToolDefinitions, formatToolResultMessage, formatToolsSection, formatUnixToolSurface, formatZodValidationError, getDiagnosticSummaryLine, getProviderConfig, getRunCommandPromptAvailability, getToolLogSummaryLine, isBackgroundBashToolCall, isBashToolCall, limitEntriesByRecency, machineStateToWebAgentPhase, mapConversationRoleToAgentRole, parseAgentResponse, parseResponseWithRecovery, parseStructuredAgentText, parseToolResultMessage, parseUnixToolCommand, readDiagnosticLevel, readDiagnosticSource, resolveToolDefinitionForInvocation, runStructuredLLMCompaction, selectLatestByKey, shouldAutoScrollThread, shouldSkipStepUserMessage, stripDiagnosticMessagePrefix, suppressWebValidationLog, tokenizeUnixCommand, truncateToolResult };
2303
+ export { AGENT_MACHINE_STATES, AgentLoop, type AgentLoopCallbacks, type AgentLoopDeps, type AgentMachineContext, type AgentMachineEvent, type AgentMachineState, type AgentMemoryCitation, type AgentMemoryConstraint, type AgentMemoryEvidence, type AgentMemoryFactoryOverrides, AgentMemoryLayer, type AgentMemoryLayerConfig, type AgentMemoryLogger, type AgentMemoryNote, type AgentMemoryTask, type AgentMessage, type AgentPhase, type AgentState, ApiError, type BackgroundBashAction, BackgroundBashRunCommand, BaseMemoryLayer, BaseValidationEnforcer, BashRunCommand, type BuildMemoryCompactionPromptOptions, CODE_QUALITY_RULE_LINE, CONTINUE_TOOL_CALL_RESPONSE_EXAMPLE, CharTokenEstimator, type ChatMessage, type CommandRuntime, type CommandTargetInfo, type CompactionCursor, type CompactionLLMClient, type ConversationAdapter, type ConversationSink, type CreateWebRuntimeSetupOptions, DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT, DEFAULT_ALLOWED_RUN_TARGETS, DEFAULT_RUN_COMMAND_REGISTRY, DEFAULT_THREAD_AUTO_SCROLL_BOTTOM_THRESHOLD, DEFAULT_TOOL_MEMORY_EXTRACTOR, ERROR_RECOVERY_RULE_LINE, ERROR_TRUNCATED_RESPONSE, type EnforcerResult, type ExecuteWebLoopRunOptions, type FetchLike, type FetchResponseLike, type HammerAgentConfig, type HammerAgentProviderPreset, INCREMENTAL_TESTING_RULE_LINE, JUST_BASH_SCRIPT_EXECUTION_RESTRICTION_LINES, JUST_BASH_SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES, LLMClient, type LLMClientResponse, type LLMProviderConfig, type LLMRequest, type LLMRequestOptions, type LLMResponse, type LoopOutcome, MAX_TOOL_RESULT_CHARS, type MemoryMessage, type MemoryProvenance, type MemoryStorage, PORT_CONFLICT_RULE_LINE, type ParseAgentResponseOptions, type ParsedAgentResponse, type ParsedBackgroundBashCommand, type ParsedStepInput, PendingAgentMessageBuffer, type PersistedMemoryData, type ProviderName, ProxyTool, type ProxyToolExecutor, ROOT_CAUSES_RULE_LINE, type RawMessage, RunCommand, type RunCommandParseResult, type RunCommandPromptAvailability, RunCommandRegistry, type RunInvocationTarget, type RuntimeController, type RuntimeSnapshotUpdater, type RuntimeStore, type RuntimeSubscriber, SHARED_TOOL_CALL_EXAMPLE_LINES, SINGLE_TOOL_CALL_RUN_LINE_EXAMPLE, STANDARD_TOOL_CALL_FORMAT_RULES, SUPPORTED_RUN_TARGETS, type SkillSummaryLike, type StepResult, type StreamCallbacks, StreamingToolParser, type StreamingToolParserCallbacks, type SystemPromptBuildContext, type SystemPromptCustomizer, type SystemPromptSections, TODO_LIST_FIRST_RESPONSE_RULE_LINE, TOOL_CALL_SEPARATOR_RULE, type TodoItem, type TodoStatus, type TokenEstimator, Tool, type ToolCall, type ToolDataPrimitive, type ToolDataSchema, type ToolDataValue, type ToolDefinition, type ToolDefinitionMetadata, type ToolExecutionResult, type ToolLike, ToolLoopAgentRuntime, type ToolLoopAgentRuntimeDeps, type ToolLoopRuntimeExecuteStepResult, type ToolLoopRuntimeHooks, type ToolLoopRuntimeInfrastructure, type ToolLoopRuntimeLLMRequest, type ToolLoopRuntimeLLMResponse, type ToolLoopRuntimeRunStepOptions, type ToolLoopRuntimeRunStepResult, type ToolLoopRuntimeSetup, type ToolLoopRuntimeStepContext, type ToolLoopStepExecutionResult, type ToolLoopStepExecutorCallbacks, type ToolLoopStepExecutorOptions, type ToolLoopStepExecutorResponse, type ToolMemoryCitationKind, type ToolMemoryEvidenceKind, type ToolMemoryEvidencePolicy, type ToolMemoryExtractor, type ToolMemoryMetadata, type ToolMemoryNoteKind, type ToolMemoryNotePolicy, type ToolMemoryNoteScope, type ToolMetadata, type ToolParameterDefinition, ToolRegistry, type ToolRegistryBeforeExecuteContext, type ToolRegistryMissingToolContext, type ToolRegistryOptions, type ToolResult, ToolRunCommand, type ToolSchema, type TruncatedToolInfo, VALIDATE_AFTER_CHANGES_RULE_LINE, type WebSearchToolActionInput, WebToolLoopAgentRuntime, type WebToolLoopAgentRuntimeConstructorOptions, type WebToolLoopRuntimeStateLike, WebValidationEnforcer, type WorkspaceCodingStaticRulesOptions, agentMachine, applyIdleWebAgentState, applyInitialWebAgentRunState, buildAgentIdentityLine, buildAgentSystemPrompt, buildCompactionEntry, buildCoreStaticRules, buildNoStructuredResponseFoundError, buildParseFeedback, buildSkillAwareStaticContext, buildStepUserMessage, buildToolLogRevealFrames, buildToolUsageExample, buildValidationErrorMessage, buildWebRuntimeRules, buildWorkspaceCodingStaticRules, canonicalizeCompactionText, coerceToolCallToDefinition, configure, containsStandaloneStructuredInvocationStart, createAgentMemoryLayer, createAppendToolsSectionCustomizer, createBackgroundBashDefinition, createConversationSink, createCustomRunCommandRegistry, createInitialWebAgentState, createRunCommandRuntimeBindings, createRuntimeStore, createToolAgentMessage, createToolRegistry, createToolsSectionOverrideCustomizer, createWebAgentMessageIdGenerator, createWebSearchToolActions, createWebToolLoopCallbacks, decodeEscapedShellText, defineRuntimeController, enrichToolResultWithUnixMetadata, executeBackgroundUnixCommandString, executeToolCallWithRunCommands, executeToolLoopStep, executeToolSafe, executeUnixCommandString, extractPrimaryCommandMetadata, extractTruncatedToolInfo, formatToolCallAsUnixCommand, formatToolDefinitions, formatToolResultMessage, formatToolsSection, formatUnixToolSurface, formatZodValidationError, getDiagnosticSummaryLine, getProviderConfig, getRunCommandPromptAvailability, getToolLogSummaryLine, isBackgroundBashToolCall, isBashToolCall, limitEntriesByRecency, machineStateToWebAgentPhase, mapConversationRoleToAgentRole, parseAgentResponse, parseResponseWithRecovery, parseStructuredAgentText, parseToolResultMessage, parseUnixToolCommand, readDiagnosticLevel, readDiagnosticSource, resolveToolDefinitionForInvocation, runStructuredLLMCompaction, selectLatestByKey, shouldAutoScrollThread, shouldSkipStepUserMessage, stripDiagnosticMessagePrefix, suppressWebValidationLog, tokenizeUnixCommand, truncateToolResult };
package/dist/index.js CHANGED
@@ -873,11 +873,14 @@ function buildShellNativeWorkflowCommandExamples(options) {
873
873
  return commands.join(", ");
874
874
  }
875
875
  var SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES = buildShellNativeWorkflowCommandExamples();
876
- buildShellNativeWorkflowCommandExamples({
876
+ var JUST_BASH_SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES = buildShellNativeWorkflowCommandExamples({
877
877
  includeGit: false,
878
878
  includeBun: false,
879
879
  includeCurl: false
880
880
  });
881
+ var JUST_BASH_SCRIPT_EXECUTION_RESTRICTION_LINES = [
882
+ "Never try to run scripts with `python`, `python3`, `node`, `nodejs`, `bun`, or similar runtimes unless a listed tool explicitly provides that capability."
883
+ ];
881
884
  function buildBashCommandsSectionLines(options) {
882
885
  const shellNativeWorkflowCommandExamples = options?.shellNativeWorkflowCommandExamples ?? SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES;
883
886
  const additionalGuidanceLines = (options?.additionalGuidanceLines ?? []).map((line) => line.trim()).filter((line) => line.length > 0);
@@ -927,6 +930,12 @@ function buildMultipleStructuredControlSegmentsValidationError(segmentCount) {
927
930
  `You emitted ${segmentCount} structured control blocks in one response. Emit exactly one standalone slug header per response. The slug header is the separator between prose/thought and command/action.`
928
931
  );
929
932
  }
933
+ [
934
+ "The final executable control block must use one standalone header: ---tool---, ---bash---, or ---background_bash---. Put prose first, then a newline, then the standalone header on its own line, then a newline, then the payload. The header and payload must be the LAST thing in your message - never put speech after them.",
935
+ ...STANDARD_TOOL_CALL_FORMAT_RULES,
936
+ ...SLUG_FORMAT_EXAMPLE_RULE_LINES,
937
+ "Only call tools that are explicitly listed below. If no tools are listed and bash is unavailable, do not emit a control block."
938
+ ];
930
939
  buildBashCommandsSectionLines();
931
940
  var BACKGROUND_BASH_START_EXAMPLE_LINE = `- Start:
932
941
  ${formatStructuredControlSegment("background_bash", 'start <name> --command "<long-running server command>"')}`;
@@ -965,6 +974,10 @@ var SHARED_TOOL_CALL_EXAMPLE_LINES = [
965
974
  ` \u2717 ${INCORRECT_INLINE_PROSE_AND_TOOL_SLUG_EXAMPLE}`,
966
975
  ` \u2717 ${INCORRECT_INLINE_HEADER_AND_PAYLOAD_EXAMPLE}`
967
976
  ];
977
+ var CONTINUE_TOOL_CALL_RESPONSE_EXAMPLE = [
978
+ "I need to inspect the file first.",
979
+ SINGLE_TOOL_CALL_RUN_LINE_EXAMPLE
980
+ ].join("\n");
968
981
  function buildBashCommandsSection(options) {
969
982
  return buildBashCommandsSectionLines(options).join("\n");
970
983
  }
@@ -2770,6 +2783,13 @@ function stripInvocations(content, invocations) {
2770
2783
 
2771
2784
  // src/prompt-helpers.ts
2772
2785
  var DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT = "You are an AI agent.";
2786
+ var ERROR_RECOVERY_RULE_LINE = "**ERROR RECOVERY**: If a tool returns `success=false`, inspect the error, fix the cause, and retry.";
2787
+ var ROOT_CAUSES_RULE_LINE = "**ROOT CAUSES**: Fix root causes rather than suppressing symptoms.";
2788
+ var VALIDATE_AFTER_CHANGES_RULE_LINE = "**VALIDATE AFTER CHANGES**: Check syntax, imports, and obvious integration errors after editing.";
2789
+ var INCREMENTAL_TESTING_RULE_LINE = "**INCREMENTAL TESTING**: Write \u2192 test \u2192 fix before moving on. Verify deliverables actually work before finishing successfully.";
2790
+ var CODE_QUALITY_RULE_LINE = "**CODE QUALITY**: For TypeScript, prefer `tsc --noEmit` or the repo's build/test command after meaningful edits.";
2791
+ var SKILL_INVOKE_READ_RULE_LINE = "If the user says invoke /skill-name, treat that as asking you to read the skill-name skill with ReadSkill before proceeding.";
2792
+ var TODO_LIST_FIRST_RESPONSE_RULE_LINE = "You MUST call the manage_todo_list tool in your very first response to plan your work before executing any other tool. Break the task into specific, actionable steps. On subsequent responses, update the todo list to reflect progress.";
2773
2793
  function createAppendToolsSectionCustomizer(block) {
2774
2794
  return (sections) => {
2775
2795
  const trimmedBlock = block.trim();
@@ -2795,6 +2815,20 @@ function applySystemPromptCustomizers(sections, context, customizers) {
2795
2815
  ...customizer(current, context) ?? {}
2796
2816
  }), sections);
2797
2817
  }
2818
+ function buildValidationRecoveryRuleLines(options) {
2819
+ const includeVerifiedCompletionRule = options?.includeVerifiedCompletionRule ?? false;
2820
+ const reservedControlHeadersRule = options?.reservedControlHeadersRule ?? "Treat the structured control headers as reserved control syntax and use them only in the final executable segment.";
2821
+ return [
2822
+ "If the previous response was rejected for format, do not explain the response protocol back to the system.",
2823
+ "Recover by choosing one concrete next action.",
2824
+ reservedControlHeadersRule,
2825
+ TOOL_CALL_SEPARATOR_RULE,
2826
+ ...SLUG_FORMAT_EXAMPLE_RULE_LINES,
2827
+ ...includeVerifiedCompletionRule ? [
2828
+ "Do not claim success until your latest tool results or observed state show the task is complete."
2829
+ ] : []
2830
+ ];
2831
+ }
2798
2832
  function formatToolsSection(tools, options) {
2799
2833
  const commandPromptAvailability = options?.allowedRunTargets ? getRunCommandPromptAvailability(options.allowedRunTargets) : void 0;
2800
2834
  let desc = formatToolDefinitions(tools, "unix");
@@ -2808,6 +2842,181 @@ function formatToolsSection(tools, options) {
2808
2842
  }
2809
2843
  return desc;
2810
2844
  }
2845
+ function buildSkillsSection(allSkills) {
2846
+ if (allSkills.length === 0) {
2847
+ return "";
2848
+ }
2849
+ const skillSummaries = [...allSkills].sort(
2850
+ (left, right) => left.metadata.name.localeCompare(right.metadata.name)
2851
+ ).map((skill) => ` \u2022 **${skill.metadata.name}**: ${skill.metadata.description}`).join("\n");
2852
+ return `
2853
+
2854
+ # AVAILABLE SKILLS
2855
+
2856
+ Specialized skills provide expert workflows and domain knowledge. Each skill contains detailed instructions, examples, and best practices.
2857
+
2858
+ ${skillSummaries}
2859
+
2860
+ These skill summaries are loaded into context automatically at the start of the run. If a skill is relevant, call ReadSkill to load the full instructions before implementing that workflow.
2861
+
2862
+ **Skills guidance**:
2863
+ 1. Review the skills above before starting implementation-heavy work
2864
+ 2. If a listed skill clearly matches the task, prefer reading that skill before planning or implementing a generic approach
2865
+ 3. Prefer the most specific relevant skill over a broader fallback skill when multiple skills could apply
2866
+ 4. ${SKILL_INVOKE_READ_RULE_LINE}
2867
+ 5. Use ReadSkill for the specific skill whose workflow you want to follow in detail before making substantive changes
2868
+ 6. If a skill you read instructs you to consult another foundational skill, follow that dependency before implementation
2869
+ 7. Skills are instructions, not replacements for the registered tools
2870
+
2871
+ ---
2872
+
2873
+ `;
2874
+ }
2875
+ function buildSkillAwareStaticContext(options) {
2876
+ return [
2877
+ buildSkillsSection(options.allSkills).trim(),
2878
+ options.staticRules.trim()
2879
+ ].filter((section) => section.length > 0).join("\n\n");
2880
+ }
2881
+ function formatRuleLines(ruleLines) {
2882
+ return ruleLines.map((rule) => rule.trim()).filter((rule) => rule.length > 0).map((rule) => `- ${rule}`).join("\n");
2883
+ }
2884
+ var PORT_CONFLICT_RULE_LINE = "**PORT CONFLICTS**: If a server fails with `EADDRINUSE` and `FreePort` is available, use it before retrying.";
2885
+ function buildDefaultWorkspaceCodingSections(skillsDirectory) {
2886
+ return [
2887
+ {
2888
+ id: "workspace-safety",
2889
+ heading: "Workspace Safety",
2890
+ ruleLines: [
2891
+ "**RELATIVE PATHS**: Use workspace-relative paths for file operations unless a tool explicitly requires an absolute path.",
2892
+ `**SKILLS DIRECTORY**: Skills live in \`${skillsDirectory}/\`.`,
2893
+ `If a skill references \`scripts/file.py\`, use \`${skillsDirectory}/{skill-name}/scripts/file.py\`.`,
2894
+ `If a skill references \`guide.md\`, inspect \`${skillsDirectory}/{skill-name}/guide.md\` with bash or another focused tool.`,
2895
+ "**READ BEFORE WRITE**: Inspect an existing file and nearby related files before modifying it unless you are creating a clearly new file in an empty target location.",
2896
+ "**CREATE PARENTS BEFORE CAT**: When creating a new file with shell redirection such as `cat > path/to/file <<'EOF'`, always run `mkdir -p path/to` first because `cat` and shell redirection do not create missing parent directories."
2897
+ ]
2898
+ },
2899
+ {
2900
+ id: "editing-strategy",
2901
+ heading: "Editing Strategy",
2902
+ ruleLines: [
2903
+ "**SKILL-FIRST WORKFLOWS**: When the current task clearly matches an available skill, read that skill before making substantive edits, implementation plans, or design decisions.",
2904
+ "**FILE CHANGES VIA BASH**: Use a final `---bash---` control segment for creating, editing, appending, renaming, and normalizing files. Prefer scoped edits over blind overwrites.",
2905
+ "**TARGETED EDITS**: When modifying an existing file, always use narrow search-and-replace or patch-style edits that touch only the necessary lines. Preserve surrounding code, formatting, and structure.",
2906
+ "**SEARCH/REPLACE REQUIRED**: For existing files, use in-place search-and-replace commands such as `sed` or another scoped patching approach. Do not rewrite an existing file wholesale to make a fix.",
2907
+ "**NO EXISTING-FILE CAT REWRITES**: Never regenerate or overwrite an existing file with `cat > file <<'EOF'`. Reserve `cat > file <<'EOF'` for creating a new file that does not already exist.",
2908
+ "**ERROR FIXES SHOULD BE LOCAL**: When a compiler, linter, or runtime error points to part of an existing file, patch that local region instead of rewriting the file.",
2909
+ "**EXPLORE, PLAN, THEN IMPLEMENT**: For ambiguous, multi-file, or unfamiliar work: explore first, form a plan, then implement.",
2910
+ "**KEEP SCRIPTS SHORT**: Keep one-off scripts around 100 lines or less. Split larger scripts into verified steps.",
2911
+ `**CONTEXT GATHERING**: Use bash with ${WORKSPACE_CONTEXT_GATHERING_COMMAND_EXAMPLES} to discover structure, inspect related files, and understand patterns before changing code.`,
2912
+ `**SHALLOW DISCOVERY**: ${SHALLOW_WORKSPACE_DISCOVERY_RULE_LINE}`,
2913
+ "**BASH SAFETY**: Avoid destructive broad-scope commands. Keep file operations tightly scoped."
2914
+ ]
2915
+ },
2916
+ {
2917
+ id: "verification",
2918
+ heading: "Verification",
2919
+ ruleLines: [
2920
+ ERROR_RECOVERY_RULE_LINE,
2921
+ ROOT_CAUSES_RULE_LINE,
2922
+ VALIDATE_AFTER_CHANGES_RULE_LINE,
2923
+ INCREMENTAL_TESTING_RULE_LINE,
2924
+ CODE_QUALITY_RULE_LINE
2925
+ ]
2926
+ },
2927
+ {
2928
+ id: "efficiency",
2929
+ heading: "Efficiency",
2930
+ ruleLines: [
2931
+ `**EFFICIENT FILE SEARCH**: Use bash with ${WORKSPACE_CONTEXT_GATHERING_COMMAND_EXAMPLES} to locate files and inspect focused ranges instead of repeatedly dumping whole files.`,
2932
+ "**OUTPUT SIZE & TRUNCATION**: Keep each control-segment payload reasonably small. For large file generation, prefer a complete validated file or a sequence of coherent patch-sized edits. Use incremental append steps only when tooling or truncation constraints make that necessary.",
2933
+ "**MINIMIZE FILE CHURN**: Avoid rewriting entire existing files when a scoped replacement will do. Smaller in-place edits reduce regressions, token waste, and repeated repair loops.",
2934
+ "**PREFER SED-SHAPED FIXES**: When using bash to repair existing files, use `sed`-style or other search-and-replace edits instead of `cat`-based full-file regeneration.",
2935
+ "**EFFICIENCY**: Prefer one well-composed control-segment action per response instead of fragmented follow-up steps when a single bash command or tool invocation will do. Do not re-read files already in context without a reason.",
2936
+ PORT_CONFLICT_RULE_LINE
2937
+ ]
2938
+ }
2939
+ ];
2940
+ }
2941
+ function applyWorkspaceCodingSectionOverrides(baseSections, additionalRuleSections) {
2942
+ const resolvedSections = baseSections.map((section) => ({
2943
+ ...section,
2944
+ ruleLines: [...section.ruleLines]
2945
+ }));
2946
+ for (const override of additionalRuleSections) {
2947
+ const trimmedRuleLines = (override.ruleLines ?? []).map((rule) => rule.trim()).filter((rule) => rule.length > 0);
2948
+ const omittedRuleLines = new Set(
2949
+ (override.omitRuleLines ?? []).map((rule) => rule.trim()).filter((rule) => rule.length > 0)
2950
+ );
2951
+ if (override.section) {
2952
+ const targetSection = resolvedSections.find((section) => section.id === override.section);
2953
+ if (!targetSection) {
2954
+ continue;
2955
+ }
2956
+ if (omittedRuleLines.size > 0) {
2957
+ targetSection.ruleLines = targetSection.ruleLines.filter(
2958
+ (rule) => !omittedRuleLines.has(rule)
2959
+ );
2960
+ }
2961
+ targetSection.ruleLines.push(...trimmedRuleLines);
2962
+ continue;
2963
+ }
2964
+ const heading = override.heading?.trim() ?? "";
2965
+ if (!heading || trimmedRuleLines.length === 0) {
2966
+ continue;
2967
+ }
2968
+ resolvedSections.push({
2969
+ id: `custom:${heading}`,
2970
+ heading,
2971
+ ruleLines: trimmedRuleLines
2972
+ });
2973
+ }
2974
+ return resolvedSections;
2975
+ }
2976
+ function buildWorkspaceCodingStaticRules(options) {
2977
+ const skillsDirectory = options?.skillsDirectory ?? ".claude/skills";
2978
+ const rulesHeading = options?.rulesHeading ?? "WORKSPACE CODING AGENT RULES";
2979
+ const additionalRuleSections = options?.additionalRuleSections ?? [];
2980
+ const normalizedSections = applyWorkspaceCodingSectionOverrides(
2981
+ buildDefaultWorkspaceCodingSections(skillsDirectory),
2982
+ additionalRuleSections
2983
+ ).map((section) => {
2984
+ if (section.ruleLines.length === 0) {
2985
+ return "";
2986
+ }
2987
+ return `## ${section.heading}
2988
+
2989
+ ${formatRuleLines(section.ruleLines)}`;
2990
+ }).filter((section) => section.length > 0).join("\n\n");
2991
+ const codingAgentRules = `
2992
+
2993
+ # ${rulesHeading}
2994
+
2995
+ ${normalizedSections}`;
2996
+ return buildCoreStaticRules() + codingAgentRules;
2997
+ }
2998
+ function buildAgentIdentityLine(options) {
2999
+ const {
3000
+ identity,
3001
+ agentName,
3002
+ roleDescription
3003
+ } = options;
3004
+ const identityLine = identity ?? (agentName && roleDescription ? `You are ${agentName}, a ${roleDescription} agent.` : null);
3005
+ if (!identityLine) {
3006
+ throw new Error("buildAgentIdentityLine requires either identity or both agentName and roleDescription");
3007
+ }
3008
+ return identityLine;
3009
+ }
3010
+ function buildWebRuntimeRules(options) {
3011
+ const additionalRules = options?.additionalRules ?? [];
3012
+ return [
3013
+ ...buildValidationRecoveryRuleLines({
3014
+ includeVerifiedCompletionRule: options?.includeVerifiedCompletionRule ?? false,
3015
+ reservedControlHeadersRule: "Treat the structured control headers as reserved control syntax. Use them only in the final executable segment, never inside analysis or summaries."
3016
+ }),
3017
+ ...additionalRules
3018
+ ].join("\n");
3019
+ }
2811
3020
  function buildAgentSystemPrompt(options) {
2812
3021
  const commandPromptAvailability = options.allowedRunTargets ? getRunCommandPromptAvailability(options.allowedRunTargets) : void 0;
2813
3022
  const toolsSectionOptions = {
@@ -7211,6 +7420,6 @@ async function executeToolLoopStep(options) {
7211
7420
  };
7212
7421
  }
7213
7422
 
7214
- export { AGENT_MACHINE_STATES, AgentLoop, AgentMemoryLayer, ApiError, BackgroundBashRunCommand, BaseMemoryLayer, BaseValidationEnforcer, BashRunCommand, CharTokenEstimator, DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT, DEFAULT_ALLOWED_RUN_TARGETS, DEFAULT_RUN_COMMAND_REGISTRY, DEFAULT_THREAD_AUTO_SCROLL_BOTTOM_THRESHOLD, DEFAULT_TOOL_MEMORY_EXTRACTOR, ERROR_TRUNCATED_RESPONSE, LLMClient, MAX_TOOL_RESULT_CHARS, PendingAgentMessageBuffer, ProxyTool, RunCommand, RunCommandRegistry, SUPPORTED_RUN_TARGETS, StreamingToolParser, Tool, ToolLoopAgentRuntime, ToolRegistry, ToolRunCommand, WebToolLoopAgentRuntime, WebValidationEnforcer, agentMachine, applyIdleWebAgentState, applyInitialWebAgentRunState, buildAgentSystemPrompt, buildCompactionEntry, buildCoreStaticRules, buildNoStructuredResponseFoundError, buildParseFeedback, buildStepUserMessage, buildToolLogRevealFrames, buildToolUsageExample, buildValidationErrorMessage, canonicalizeCompactionText, coerceToolCallToDefinition, configure, containsStandaloneStructuredInvocationStart, createAgentMemoryLayer, createAppendToolsSectionCustomizer, createBackgroundBashDefinition, createConversationSink, createCustomRunCommandRegistry, createInitialWebAgentState, createRunCommandRuntimeBindings, createRuntimeStore, createToolAgentMessage, createToolRegistry, createToolsSectionOverrideCustomizer, createWebAgentMessageIdGenerator, createWebSearchToolActions, createWebToolLoopCallbacks, decodeEscapedShellText, defineRuntimeController, enrichToolResultWithUnixMetadata, executeBackgroundUnixCommandString, executeToolCallWithRunCommands, executeToolLoopStep, executeToolSafe, executeUnixCommandString, extractPrimaryCommandMetadata, extractTruncatedToolInfo, formatToolCallAsUnixCommand, formatToolDefinitions, formatToolResultMessage, formatToolsSection, formatUnixToolSurface, formatZodValidationError, getDiagnosticSummaryLine, getProviderConfig, getRunCommandPromptAvailability, getToolLogSummaryLine, isBackgroundBashToolCall, isBashToolCall, limitEntriesByRecency, machineStateToWebAgentPhase, mapConversationRoleToAgentRole, parseAgentResponse, parseResponseWithRecovery, parseStructuredAgentText, parseToolResultMessage, parseUnixToolCommand, readDiagnosticLevel, readDiagnosticSource, resolveToolDefinitionForInvocation, runStructuredLLMCompaction, selectLatestByKey, shouldAutoScrollThread, shouldSkipStepUserMessage, stripDiagnosticMessagePrefix, suppressWebValidationLog, tokenizeUnixCommand, truncateToolResult };
7423
+ export { AGENT_MACHINE_STATES, AgentLoop, AgentMemoryLayer, ApiError, BackgroundBashRunCommand, BaseMemoryLayer, BaseValidationEnforcer, BashRunCommand, CODE_QUALITY_RULE_LINE, CONTINUE_TOOL_CALL_RESPONSE_EXAMPLE, CharTokenEstimator, DEFAULT_AGENT_FALLBACK_SYSTEM_PROMPT, DEFAULT_ALLOWED_RUN_TARGETS, DEFAULT_RUN_COMMAND_REGISTRY, DEFAULT_THREAD_AUTO_SCROLL_BOTTOM_THRESHOLD, DEFAULT_TOOL_MEMORY_EXTRACTOR, ERROR_RECOVERY_RULE_LINE, ERROR_TRUNCATED_RESPONSE, INCREMENTAL_TESTING_RULE_LINE, JUST_BASH_SCRIPT_EXECUTION_RESTRICTION_LINES, JUST_BASH_SHELL_NATIVE_WORKFLOW_COMMAND_EXAMPLES, LLMClient, MAX_TOOL_RESULT_CHARS, PORT_CONFLICT_RULE_LINE, PendingAgentMessageBuffer, ProxyTool, ROOT_CAUSES_RULE_LINE, RunCommand, RunCommandRegistry, SHARED_TOOL_CALL_EXAMPLE_LINES, SINGLE_TOOL_CALL_RUN_LINE_EXAMPLE, STANDARD_TOOL_CALL_FORMAT_RULES, SUPPORTED_RUN_TARGETS, StreamingToolParser, TODO_LIST_FIRST_RESPONSE_RULE_LINE, TOOL_CALL_SEPARATOR_RULE, Tool, ToolLoopAgentRuntime, ToolRegistry, ToolRunCommand, VALIDATE_AFTER_CHANGES_RULE_LINE, WebToolLoopAgentRuntime, WebValidationEnforcer, agentMachine, applyIdleWebAgentState, applyInitialWebAgentRunState, buildAgentIdentityLine, buildAgentSystemPrompt, buildCompactionEntry, buildCoreStaticRules, buildNoStructuredResponseFoundError, buildParseFeedback, buildSkillAwareStaticContext, buildStepUserMessage, buildToolLogRevealFrames, buildToolUsageExample, buildValidationErrorMessage, buildWebRuntimeRules, buildWorkspaceCodingStaticRules, canonicalizeCompactionText, coerceToolCallToDefinition, configure, containsStandaloneStructuredInvocationStart, createAgentMemoryLayer, createAppendToolsSectionCustomizer, createBackgroundBashDefinition, createConversationSink, createCustomRunCommandRegistry, createInitialWebAgentState, createRunCommandRuntimeBindings, createRuntimeStore, createToolAgentMessage, createToolRegistry, createToolsSectionOverrideCustomizer, createWebAgentMessageIdGenerator, createWebSearchToolActions, createWebToolLoopCallbacks, decodeEscapedShellText, defineRuntimeController, enrichToolResultWithUnixMetadata, executeBackgroundUnixCommandString, executeToolCallWithRunCommands, executeToolLoopStep, executeToolSafe, executeUnixCommandString, extractPrimaryCommandMetadata, extractTruncatedToolInfo, formatToolCallAsUnixCommand, formatToolDefinitions, formatToolResultMessage, formatToolsSection, formatUnixToolSurface, formatZodValidationError, getDiagnosticSummaryLine, getProviderConfig, getRunCommandPromptAvailability, getToolLogSummaryLine, isBackgroundBashToolCall, isBashToolCall, limitEntriesByRecency, machineStateToWebAgentPhase, mapConversationRoleToAgentRole, parseAgentResponse, parseResponseWithRecovery, parseStructuredAgentText, parseToolResultMessage, parseUnixToolCommand, readDiagnosticLevel, readDiagnosticSource, resolveToolDefinitionForInvocation, runStructuredLLMCompaction, selectLatestByKey, shouldAutoScrollThread, shouldSkipStepUserMessage, stripDiagnosticMessagePrefix, suppressWebValidationLog, tokenizeUnixCommand, truncateToolResult };
7215
7424
  //# sourceMappingURL=index.js.map
7216
7425
  //# sourceMappingURL=index.js.map