AgentScript Base Examples
This document provides sample AgentScript code snippets along with their transpiled TypeScript to illustrate key features.
Example 1. Natural Language Context
AgentScript
function fetchUser(userId: UserID): User goal: "Fetches user data for profile display" backstory: "Interacts with the User Service API" requires: userId >= 1: "User ID must be at least 1" return: // Call to an external service callUserService(userId)
errors: UserNotFound: "No user found for the given ID" when callUserService(userId) is null APIError: "Failed to fetch user data" when callUserService(userId) throws
tests: success: // Expect a valid user object when userId is valid 1 -> { id: 1, name: "Alice" } performance: // Should respond within 10ms under normal conditions input: 10 -> expect < 10ms
Transpiled TypeScript
export function fetchUser(userId: number): User { // Contract check: userId >= 1 if (userId < 1) { throw new Error("User ID must be at least 1"); }
let user: User; try { // Implementation user = callUserService(userId); } catch (error) { throw new Error("Failed to fetch user data"); // APIError }
if (!user) { throw new Error("No user found with the given ID"); // UserNotFound }
return user;}
Explanation:
• Demonstrates meta-sections (intent, context) in AgentScript for clarity and includes error logic inline.
• Embedded tests define expected behavior across success, performance, and load categories.
• The generated TypeScript includes contract checks, a try/catch for API errors, and a condition for missing users.
Example 2. Embedded Tests
AgentScript
function calculateDiscount(price: number, discount: number): number goal: "Apply a discount to a price in e-commerce." backstory: "Used during checkout." requires: price >= 0: "Price must be non-negative" discount >= 0 && discount <= 100: "Discount must be between 0 and 100" return: price * (1 - discount / 100) errors: InvalidPrice: "Price must be non-negative" InvalidDiscount: "Discount must be between 0 and 100"
tests: success: 100, 20 -> 80 200, 50 -> 100 errors: -100, 20 -> InvalidPrice 100, -10 -> InvalidDiscount 100, 150 -> InvalidDiscount performance: input: [1000, 10] -> expect < 1ms input: [9999999, 99] -> expect < 10ms
Transpiled TypeScript
export function calculateDiscount(price: number, discount: number): number { if (price < 0) { throw new Error("Price must be non-negative"); // InvalidPrice } if (discount < 0 || discount > 100) { throw new Error("Discount must be between 0 and 100"); // InvalidDiscount } return price * (1 - discount / 100);}
Explanation:
• Multiple embedded test types specify success and smoke scenarios.
• The performance tests hint at maximum acceptable execution times.
• Transpiled TypeScript includes straightforward contract checks before performing the calculation.
Example 3. State Machines
AgentScript
function orderStateMachine(order: Order): State machine: state: pending -> confirmed on confirmOrder state: confirmed -> shipped on shipOrder state: shipped -> delivered on deliverOrder
errors: InvalidTransition: "Attempted an invalid state transition"
tests: success: { status: "pending" } -> "confirmed" after confirmOrder { status: "confirmed" } -> "shipped" after shipOrder smoke: { status: "delivered" } -> error: InvalidTransition
Transpiled TypeScript
export function orderStateMachine(order: Order): State { // A naive representation of transitioning states function confirmOrder(current: Order) { if (current.status !== "pending") { throw new Error("Attempted an invalid state transition"); // InvalidTransition } return { ...current, status: "confirmed" }; }
function shipOrder(current: Order) { if (current.status !== "confirmed") { throw new Error("Attempted an invalid state transition"); // InvalidTransition } return { ...current, status: "shipped" }; }
function deliverOrder(current: Order) { if (current.status !== "shipped") { throw new Error("Attempted an invalid state transition"); // InvalidTransition } return { ...current, status: "delivered" }; }
// In a real app, you'd call one of the above transitions // based on external events. For demo purposes, return the new order state. switch (order.status) { case "pending": return confirmOrder(order).status; case "confirmed": return shipOrder(order).status; case "shipped": return deliverOrder(order).status; default: throw new Error("Attempted an invalid state transition"); }}
Explanation:
• Machine-style definition outlines valid transitions between states (pending → confirmed → shipped → delivered).
• The TypeScript output includes functions to validate and apply transitions, highlighting the same error type on invalid transitions.
Example 4. Tagged Errors and Pipe Operator
AgentScript
function processData(data: string): number goal: "Parses, validates, then calculates a numeric result from string data." backstory: "Used in data ingestion pipeline." requires: CannotBeEmpty: "Input data cannot be empty" -> data != "" return: data |> parseJSON |> validateFormat |> computeResult
errors: ParseError: "Invalid JSON structure" ValidationError: "Data format is invalid" computationError: "Unable to compute result"
tests: success: "{ \"value\": 10 }" -> 20 smoke: "" -> CannotBeEmpty performance: input: "{ \"value\": 9999 }" -> expect < 5ms
Transpiled TypeScript
export function processData(data: string): number { if (!data) { throw new Error("Input data cannot be empty"); }
const parsed = parseJSON(data); // could throw "Invalid JSON structure" const validated = validateFormat(parsed); // could throw "Data format is invalid" const result = computeResult(validated); // could throw "Unable to compute result"
return result;}
Explanation:
• Demonstrates the pipe operator (|>) for chaining transformations and computations.
• Tagged errors let you differentiate failure points in your pipeline.
• The TypeScript output chains calls in a more verbose manner, matching each pipeline step.
Example 5. Pattern Matching
AgentScript
function handleUserRole(user: { role: string }): string goal: "Assigns privileges based on user role." return: match (user) { case { role: "admin" } -> "Admin privileges" case { role: "guest" } -> "Guest access" default -> "Basic access" }
tests: success: { role: "admin" } -> "Admin privileges" { role: "guest" } -> "Guest access" { role: "other" } -> "Basic access"
Transpiled TypeScript
export function handleUserRole(user: { role: string }): string { if (user.role === "admin") { return "Admin privileges"; } else if (user.role === "guest") { return "Guest access"; } else { return "Basic access"; }}
if (import.meta.vitest) { const { it, expect } = import.meta.vitest
it('handleUserRole', () => { expect(handleUserRole({ role: "admin" })).toBe("Admin privileges") expect(handleUserRole({ role: "guest" })).toBe("Guest access") expect(handleUserRole({ role: "other" })).toBe("Basic access") })}
Explanation:
• Uses a match block to branch logic based on pattern matching.
• Transpiled TypeScript falls back to standard conditional checks.
Summary
These examples showcase how AgentScript’s concise syntax, contract programming, built-in testing, and concurrency features map to more verbose but widely deployable TypeScript. By embedding best practices directly into the language, AgentScript ensures that AI- or human-generated code is robust, easy to maintain, and aligned with business requirements.