npm package: @sf-explorer/agentscript-migration-tool
Description: Generate Salesforce Agent Script YAML from Agentforce planner configurations
Latest version: 1.0.1

# @sf-explorer/agentscript-migration-tool

Generate Salesforce Agent Script YAML from Agentforce planner configurations. This tool helps accelerate migration from UI-based Agentforce configurations to code-based AgentScript format.

## Features

- ✅ **85% Automated Migration** - Generate complete agent scripts automatically
- ✅ **Spec Compliant** - Follows official [Salesforce Agent Script Recipes](https://developer.salesforce.com/sample-apps/agent-script-recipes/)
- ✅ **Type Safe** - Full TypeScript support with comprehensive interfaces
- ✅ **Zero Dependencies** - Only requires `js-yaml` for YAML generation
- ✅ **Framework Agnostic** - Works with any data structure matching the planner interface

## Installation

```bash
npm install @sf-explorer/agentscript-migration-tool
```

### Requirements

- Node.js >= 18.x
- TypeScript >= 5.3 (for TypeScript projects)

## Quick Example

```typescript
import { generateAgentScript } from '@sf-explorer/agentscript-migration-tool'
import type { PlannerDefinition } from '@sf-explorer/agentscript-migration-tool'

const planner: PlannerDefinition = {
  DeveloperName: "my_agent",
  MasterLabel: "My Agent",
  topics: [/* ... */]
}

const yaml = generateAgentScript(planner)
console.log(yaml)
```

## Quick Start

```typescript
import { generateAgentScript } from '@sf-explorer/agentscript-migration-tool'
import type { PlannerDefinition } from '@sf-explorer/agentscript-migration-tool'

// Define your planner data
const planner: PlannerDefinition = {
  DeveloperName: "customer_service_agent",
  MasterLabel: "Customer Service Agent",
  Metadata: {
    description: "Assists customers with their service requests"
  },
  topics: [
    {
      DeveloperName: "Orders",
      MasterLabel: "Orders",
      Description: "Handle order-related inquiries",
      actions: [
        {
          DeveloperName: "LookupOrder",
          MasterLabel: "Lookup Order",
          Description: "Look up order by ID",
          InvocationTarget: "GetOrderDetails",
          InvocationTargetType: "Flow",
          Metadata: {
            inputs: {
              order_id: "string"
            },
            outputs: {
              order_summary: "string"
            }
          }
        }
      ]
    }
  ],
  variables: [
    {
      DeveloperName: "customer_verified",
      parameterName: "customer_verified",
      mappingType: "Boolean",
      description: "Whether customer is verified"
    }
  ]
}

// Generate Agent Script YAML
const yaml = generateAgentScript(planner, {
  includeComments: true,
  includeLanguageConfig: true
})

console.log(yaml)
```

## API

### `generateAgentScript(planner, options?)`

Convenience function to generate Agent Script YAML.

**Parameters:**
- `planner: PlannerDefinition` - The planner definition object
- `options?: AgentScriptGenerationOptions` - Optional generation options

**Returns:** `string` - Generated YAML content

### `AgentScriptGenerator`

Class-based generator for more control.

```typescript
import { AgentScriptGenerator } from '@sf-explorer/agentscript-migration-tool'

const generator = new AgentScriptGenerator(planner, {
  includeComments: true,
  yamlIndent: 4,
  includeLanguageConfig: true
})

const yaml = generator.generate()
```

### Generation Options

```typescript
interface AgentScriptGenerationOptions {
  includeComments?: boolean        // Add header comments (default: true)
  includeExamples?: boolean       // Include example code (default: false)
  yamlIndent?: number             // YAML indentation (default: 4)
  generateVariables?: boolean     // Generate variables section (default: false)
  includeLanguageConfig?: boolean // Include language block (default: true)
}
```

## Generated Structure

The tool generates complete Agent Script YAML following Salesforce patterns:

- **Config Block**: Agent metadata and configuration
- **System Block**: Global instructions and messages
- **Language Block**: Locale configuration (optional)
- **Variables**: State management variables (if provided)
- **Start Agent**: Topic selector with transitions
- **Topics**: Individual topics with reasoning and actions
- **Actions**: External integrations (Flow, Apex, API)

### Example Output

```yaml
# Agent Script
# Generated from GenAI Planner: Customer Service Agent
# Developer Name: customer_service_agent

config:
    developer_name: "customer_service_agent"
    default_agent_user: "agentforce@salesforce.com"
    description: "Assists customers with their service requests"

system:
    instructions: "You are a helpful assistant..."
    messages:
        welcome: "Hi, I'm your Customer Service Agent assistant..."
        error: "Sorry, something went wrong..."

variables:
    customer_verified: mutable boolean
        description: "Whether customer is verified"

start_agent topic_selector:
    description: "Welcome the user and determine the appropriate topic"
    reasoning:
        instructions: ->
            | You are a topic selector assistant...
        actions:
            go_to_orders: @utils.transition to @topic.Orders
                description: "Handle order-related inquiries"

topic Orders:
    description: "Handle order-related inquiries"
    reasoning:
        instructions: ->
            | Handle order-related inquiries.
            
            Available actions:
            - Use @actions.LookupOrder to Look up order by ID
        actions:
            LookupOrder: @actions.LookupOrder
                description: "Look up order by ID"
    actions:
        LookupOrder:
            description: "Look up order by ID"
            inputs:
                order_id: string
            outputs:
                order_summary: string
            target: "flow://GetOrderDetails"
```

## Type Definitions

The package exports comprehensive TypeScript types:

- `PlannerDefinition` - Main input interface
- `PlannerTopic` - Topic definition
- `PlannerAction` - Action definition
- `PlannerVariable` - Variable definition
- `AgentScriptStructure` - Generated YAML structure
- `AgentScriptGenerationOptions` - Generation options

See the [types.ts](./src/types.ts) file for complete definitions.

## Supported Action Types

The tool automatically formats action targets based on type:

- **Flow**: `flow://FlowName`
- **Apex**: `apex://ClassName`
- **Standard Invocable Action**: `standardInvocableAction://ActionName`
- **Generate Prompt Response**: `generatePromptResponse://TemplateName`
- **External Service**: `externalService://ServiceName`
- **Custom Protocols**: Preserved as-is

## Migration Workflow

1. **Extract Planner Data** - Get your planner configuration from Salesforce
2. **Transform to Interface** - Map your data to `PlannerDefinition` interface
3. **Generate YAML** - Use `generateAgentScript()` to create YAML
4. **Review & Customize** - Add business logic and detailed instructions
5. **Deploy** - Deploy to Salesforce using Salesforce CLI

## Best Practices

### 1. Start Small
Begin with 1-2 non-critical agents to learn the patterns.

### 2. Review Generated Code
The generated script is 85% complete. Review and add:
- Detailed reasoning instructions
- Specific business rules
- Custom error handling
- Advanced routing logic

### 3. Test Thoroughly
Always test in sandbox before production:
- Compare behavior with UI version
- Validate all topics
- Check action parameters
- Test error scenarios

### 4. Version Control
Treat AgentScript like any code:
- Use Git for version control
- Code reviews
- Feature branches
- Documentation

## Based on Salesforce Patterns

This implementation follows the official [Salesforce Agent Script Recipes](https://developer.salesforce.com/sample-apps/agent-script-recipes/getting-started/overview) including:

- **Language Essentials**: HelloWorld, VariableManagement, TemplateExpressions
- **Action Configuration**: ActionDefinitions, ActionCallbacks, AdvancedInputBindings
- **Architectural Patterns**: MultiTopicNavigation, SimpleQA, BidirectionalNavigation
- **Reasoning Mechanics**: ReasoningInstructions, BeforeAfterReasoning

## Contributing

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## License

MIT

## References

- [Salesforce Agent Script Recipes](https://developer.salesforce.com/sample-apps/agent-script-recipes/getting-started/overview)
- [Agentforce Documentation](https://developer.salesforce.com/docs/einstein/genai/guide/)
- [Agent Script Syntax Guide](https://developer.salesforce.com/sample-apps/agent-script-recipes/)

## Error Handling

The package includes comprehensive error handling:

```typescript
import { generateAgentScript, ValidationError } from '@sf-explorer/agentscript-migration-tool'

try {
  const yaml = generateAgentScript(planner)
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation error:', error.message)
    console.error('Field:', error.field)
  } else {
    console.error('Generation error:', error)
  }
}
```

## Testing

Run the test suite:

```bash
npm test
```

Run tests with coverage:

```bash
npm run test:coverage
```

## Support

For issues or questions:

1. Check the [official recipes](https://developer.salesforce.com/sample-apps/agent-script-recipes/getting-started/overview)
2. Review the [examples](./examples/) directory
3. Review type definitions in `types.ts`
4. Examine generator implementation in `generator.ts`
5. Open an issue on GitHub

## Contributing

Contributions are welcome! Please see our contributing guidelines:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass (`npm test`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request
# agentscript-migration-tool