Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,521 changes: 1,521 additions & 0 deletions template/AIACTION_TEMPLATES_PLAN.md

Large diffs are not rendered by default.

Empty file added template/index.ts
Empty file.
102 changes: 102 additions & 0 deletions template/templates/1-social-media-feed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/**
* Template: Social Media Feed Extraction
* Category: Social Media Data Collection
* Use Case: Extract posts from Twitter/X user feed
* Target Site: x.com
*/

import "dotenv/config";
import { HyperAgent } from "../../src/agent";
import { HyperPage } from "../../src/types/agent/types";
import { z } from "zod";

// Extract schema
const TwitterFeedSchema = z.object({
posts: z.array(
z.object({
author: z.string().describe("Username or display name"),
content: z.string().describe("Tweet text content"),
timestamp: z.string().optional().describe("Relative or absolute time"),
likes: z.string().optional().describe("Like count"),
retweets: z.string().optional().describe("Retweet count"),
})
),
});

type TwitterFeedResult = z.infer<typeof TwitterFeedSchema>;

/**
* Extract posts from Twitter/X feed
* @returns Promise with extracted feed data
*/
async function extractTwitterFeed(): Promise<TwitterFeedResult> {
let agent: HyperAgent | null = null;

try {
// Initialize HyperAgent
console.log("Initializing HyperAgent...");
agent = new HyperAgent({
llm: {
provider: "anthropic",
model: "claude-sonnet-4-0",
},
debug: true,
});

// Get the page instance
const page: HyperPage = await agent.newPage();
if (!page) {
throw new Error("Failed to get page instance from HyperAgent");
}

// Navigate to Twitter
await page.goto("https://x.com");

// Wait for page to load
await page.waitForTimeout(2000);

// Click on timeline/feed (or just scroll if already on timeline)
await page.aiAction("scroll to 30%");
await page.waitForTimeout(1000); // Allow lazy load

// Scroll to load more posts
await page.aiAction("scroll to 50%");
await page.waitForTimeout(1000); // Allow lazy load

// Extract posts
const result = await page.extract(
"Extract all visible tweets/posts including author, content, timestamp, likes, and retweets",
TwitterFeedSchema
);

return result as TwitterFeedResult;
} catch (error) {
console.error("Error in extractTwitterFeed:", error);
throw error;
} finally {
if (agent) {
console.log("Closing HyperAgent connection.");
try {
await agent.closeAgent();
} catch (err) {
console.error("Error closing HyperAgent:", err);
}
}
}
}

// Example usage
if (require.main === module) {
extractTwitterFeed()
.then((result) => {
console.log("\n===== Twitter Feed Results =====");
console.log(JSON.stringify(result, null, 2));
console.log(`\nTotal posts extracted: ${result.posts.length}`);
})
.catch((error) => {
console.error("Failed:", error);
process.exit(1);
});
}

export { extractTwitterFeed, TwitterFeedSchema };
115 changes: 115 additions & 0 deletions template/templates/10-government-public-records.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* Template: Government/Public Records
* Category: Government & Public Data
* Use Case: Navigate gov site and extract public information
* Target Site: usa.gov
*/

import "dotenv/config";
import { HyperAgent } from "../../src/agent";
import { HyperPage } from "../../src/types/agent/types";
import { z } from "zod";

// Type definitions
interface GovSearchParams {
query: string;
}

// Extract schema
const GovSearchResultSchema = z.object({
results: z.array(
z.object({
title: z.string().describe("Result title/heading"),
description: z.string().optional().describe("Brief description"),
url: z.string().optional().describe("Link to resource"),
agency: z.string().optional().describe("Government agency responsible"),
})
),
});

type GovSearchResult = z.infer<typeof GovSearchResultSchema>;

/**
* Search USA.gov for government services and information
* @param params - Search parameters including query string
* @returns Promise with extracted search results
*/
async function searchGovernmentServices(
params: GovSearchParams
): Promise<GovSearchResult> {
let agent: HyperAgent | null = null;

try {
// Initialize HyperAgent
console.log("Initializing HyperAgent...");
agent = new HyperAgent({
llm: {
provider: "anthropic",
model: "claude-sonnet-4-0",
},
headless: false,
debug: true,
});

// Get the page instance
const page: HyperPage = await agent.newPage();
if (!page) {
throw new Error("Failed to get page instance from HyperAgent");
}

// Navigate to USA.gov
await page.goto("https://www.usa.gov");

// Wait for page to load
await page.waitForTimeout(2000);

// Search for government service
await page.aiAction(`fill the search box with ${params.query}`);
await page.aiAction("press Enter");

// Wait for results
await page.waitForTimeout(3000);

// Scroll to see more results
await page.aiAction("scroll to 50%");
await page.waitForTimeout(1000);

// Extract search results
const result = await page.extract(
"Extract all search results including title, description, URL, and government agency",
GovSearchResultSchema
);

return result as GovSearchResult;
} catch (error) {
console.error("Error in searchGovernmentServices:", error);
throw error;
} finally {
if (agent) {
console.log("Closing HyperAgent connection.");
try {
await agent.closeAgent();
} catch (err) {
console.error("Error closing HyperAgent:", err);
}
}
}
}

// Example usage
if (require.main === module) {
searchGovernmentServices({
query: "passport application",
})
.then((result) => {
console.log("\n===== Government Service Search Results =====");
console.log(JSON.stringify(result, null, 2));
console.log(`\nTotal results extracted: ${result.results.length}`);
})
.catch((error) => {
console.error("Failed:", error);
process.exit(1);
});
}

export { searchGovernmentServices, GovSearchResultSchema };
176 changes: 176 additions & 0 deletions template/templates/11-click-iframe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/**
* Template: Iframe Interaction
* Category: Advanced DOM Interaction
* Use Case: Interact with elements inside iframes (single and nested)
* Target Site: demo.automationtesting.in/Frames.html
*/

import "dotenv/config";
import { HyperAgent } from "../../src/agent";
import { HyperPage } from "../../src/types/agent/types";
import { z } from "zod";

// Type definitions
interface IframeTestParams {
scenario: "single" | "nested";
testData?: {
name?: string;
email?: string;
};
debug?: true;
}

// Extract schema
const IframeInteractionSchema = z.object({
scenario: z.string().describe("Which iframe scenario was tested"),
elementsFound: z
.array(z.string())
.describe("List of interactive elements found in the iframe"),
interactionSuccess: z
.boolean()
.describe("Whether the iframe interaction was successful"),
message: z
.string()
.describe("Description of what happened during the interaction"),
});

type IframeInteractionResult = z.infer<typeof IframeInteractionSchema>;

/**
* Test iframe interaction on demo automation site
* @param params - Test parameters including scenario type
* @returns Promise with interaction results
*/
async function testIframeInteraction(params: IframeTestParams) {
let agent: HyperAgent<any> | null = null;

try {
// Initialize HyperAgent
console.log("Initializing HyperAgent...");
agent = new HyperAgent({
llm: {
provider: "anthropic",
model: "claude-sonnet-4-0",
},
debug: true,
cdpActions: true,
// browserProvider: "Hyperbrowser",
});

// Get the page instance
const page: HyperPage = await agent.newPage();
if (!page) {
throw new Error("Failed to get page instance from HyperAgent");
}

// Navigate to iframe demo page
console.log("Navigating to iframe demo page...");
await page.goto("https://demo.automationtesting.in/Frames.html");

// Wait for page to load
await page.waitForTimeout(2000);

if (params.scenario === "single") {
console.log("Testing single iframe scenario...");

// Click the "Single Iframe" tab
await page.aiAction('click the "Single Iframe" tab');
await page.waitForTimeout(1000);

// Interact with iframe content
// HyperAgent automatically detects elements inside iframes - no special syntax needed
const testName = params.testData?.name || "Test User";
await page.aiAction(`type "${testName}" in the input field`);
await page.waitForTimeout(500);

console.log(`Successfully typed "${testName}" in iframe input field`);
} else if (params.scenario === "nested") {
console.log("Testing nested iframe scenario...");

// Click the "Iframe with in an Iframe" tab
await page.aiAction('click the "Iframe with in an Iframe" tab');

// Wait for the nested iframe structure to load
// The nested iframe contains another iframe with SingleFrame.html
// await page.waitForTimeout(2000);

// Wait for frame with SingleFrame.html to be available
// const frames = page.frames();
// console.log(
// `Waiting for frames to load... Found ${frames.length} frames`
// );

// // Wait for frames to load their content
// await Promise.all(
// frames.map(async (frame) => {
// if (frame.url().includes("SingleFrame.html")) {
// try {
// await frame.waitForLoadState("domcontentloaded", {
// timeout: 5000,
// });
// console.log(`Frame loaded: ${frame.url()}`);
// } catch (e) {
// console.log(`Frame load timeout: ${frame.url()}`);
// }
// }
// })
// );

// Additional wait for accessibility tree to update
// await page.waitForTimeout(1000);

// Interact with nested iframe content
// HyperAgent traverses all iframe levels automatically
const testName = params.testData?.name || "Nested Test User";
await page.aiAction(`click the input field in the nested iframe`);
await page.aiAction(
`type "${testName}" in the input field in the nested iframe`
);
await page.waitForTimeout(500);

console.log(
`Successfully typed "${testName}" in nested iframe input field`
);
}

// Extract verification data
// const result = await page.extract(
// "Verify the iframe interaction was successful. List any interactive elements you found in the iframe(s) and confirm if the interactions worked properly.",
// IframeInteractionSchema
// );

// return result as IframeInteractionResult;
} catch (error) {
console.error("Error in testIframeInteraction:", error);
throw error;
} finally {
if (agent) {
console.log("Closing HyperAgent connection.");
try {
await agent.closeAgent();
} catch (err) {
console.error("Error closing HyperAgent:", err);
}
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Function returns void but defines unused schema

The function testIframeInteraction declares a return type of Promise<void> but defines an IframeInteractionSchema and has extraction code commented out (lines 136-141). Either the function should return the extracted schema result or the schema should be removed. The current state creates confusion between intent and implementation.

Fix in Cursor Fix in Web

}

// Example usage
if (require.main === module) {
// Test single iframe scenario
// testIframeInteraction({
// scenario: "single",
// testData: {
// name: "John Doe",
// email: "john@example.com",
// },
// });

// Test nested iframe scenario:
testIframeInteraction({
scenario: "nested",
testData: { name: "Jane Smith" },
});
}

export { testIframeInteraction, IframeInteractionSchema };
Loading