Skip to content
Merged
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
16 changes: 14 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ type TemplateKey =
| "stagehand"
| "advanced-sample"
| "computer-use"
| "cua";
| "cua"
| "magnitude";
type LanguageInfo = { name: string; shorthand: string };
type TemplateInfo = {
name: string;
Expand All @@ -36,6 +37,7 @@ const TEMPLATE_STAGEHAND = "stagehand";
const TEMPLATE_ADVANCED_SAMPLE = "advanced-sample";
const TEMPLATE_COMPUTER_USE = "computer-use";
const TEMPLATE_CUA = "cua";
const TEMPLATE_MAGNITUDE = "magnitude";
const LANGUAGE_SHORTHAND_TS = "ts";
const LANGUAGE_SHORTHAND_PY = "py";

Expand Down Expand Up @@ -79,6 +81,11 @@ const TEMPLATES: Record<TemplateKey, TemplateInfo> = {
description: "Implements a Computer Use Agent (OpenAI CUA) sample",
languages: [LANGUAGE_TYPESCRIPT, LANGUAGE_PYTHON],
},
[TEMPLATE_MAGNITUDE]: {
name: "Magnitude",
description: "Implements the Magnitude.run SDK",
languages: [LANGUAGE_TYPESCRIPT],
},
};

const INVOKE_SAMPLES: Record<
Expand All @@ -95,6 +102,8 @@ const INVOKE_SAMPLES: Record<
'kernel invoke ts-cu cu-task --payload \'{"query": "Return the first url of a search result for NYC restaurant reviews Pete Wells"}\'',
[TEMPLATE_CUA]:
'kernel invoke ts-cua cua-task --payload \'{"task": "Go to https://news.ycombinator.com and get the top 5 articles"}\'',
[TEMPLATE_MAGNITUDE]:
'kernel invoke ts-magnitude mag-url-extract --payload \'{"url": "https://en.wikipedia.org/wiki/Special:Random"}\'',
},
[LANGUAGE_PYTHON]: {
[TEMPLATE_SAMPLE_APP]:
Expand All @@ -120,6 +129,7 @@ const REGISTERED_APP_NAMES: Record<
[TEMPLATE_ADVANCED_SAMPLE]: "ts-advanced",
[TEMPLATE_COMPUTER_USE]: "ts-cu",
[TEMPLATE_CUA]: "ts-cua",
[TEMPLATE_MAGNITUDE]: "ts-magnitude",
},
[LANGUAGE_PYTHON]: {
[TEMPLATE_SAMPLE_APP]: "python-basic",
Expand Down Expand Up @@ -358,6 +368,8 @@ function printNextSteps(
? "kernel deploy index.ts --env OPENAI_API_KEY=XXX"
: language === LANGUAGE_TYPESCRIPT && template === TEMPLATE_COMPUTER_USE
? "kernel deploy index.ts --env ANTHROPIC_API_KEY=XXX"
: language === LANGUAGE_TYPESCRIPT && template === TEMPLATE_MAGNITUDE
? "kernel deploy index.ts --env ANTHROPIC_API_KEY=XXX"
: language === LANGUAGE_TYPESCRIPT && template === TEMPLATE_CUA
? "kernel deploy index.ts --env OPENAI_API_KEY=XXX"
: language === LANGUAGE_PYTHON &&
Expand Down Expand Up @@ -403,7 +415,7 @@ program
)
.option(
"-t, --template <template>",
`Template type (${TEMPLATE_SAMPLE_APP}, ${TEMPLATE_BROWSER_USE}, ${TEMPLATE_STAGEHAND}, ${TEMPLATE_ADVANCED_SAMPLE}, ${TEMPLATE_COMPUTER_USE})`
`Template type (${TEMPLATE_SAMPLE_APP}, ${TEMPLATE_BROWSER_USE}, ${TEMPLATE_STAGEHAND}, ${TEMPLATE_ADVANCED_SAMPLE}, ${TEMPLATE_COMPUTER_USE}, ${TEMPLATE_CUA}, ${TEMPLATE_MAGNITUDE})`
)
.action(
async (
Expand Down
21 changes: 21 additions & 0 deletions templates/typescript/magnitude/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Kernel TypeScript Magnitude.run Template

This template demonstrates integrating Magnitude.run with a Kernel app.

It defines a single action that:
- Navigates to a given URL (via Magnitude `agent.act()`)
- Extracts up to 5 absolute URLs on the page (via Magnitude `agent.extract()`)

## Quickstart

- Deploy:
kernel login # or: export KERNEL_API_KEY=<your_api_key>
kernel deploy index.ts --env ANTHROPIC_API_KEY=XXX

- Invoke:
kernel invoke ts-magnitude mag-url-extract --payload '{"url": "https://fandom.com"}'

## Notes
- Uses Anthropic as the model provider with model: `anthropic/claude-sonnet-4`.
- Requires `ANTHROPIC_API_KEY` in the deployment environment.
- The agent connects to the Kernel-managed browser via CDP for live view & observability.
40 changes: 40 additions & 0 deletions templates/typescript/magnitude/_gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Dependencies
node_modules/
package-lock.json

# TypeScript
*.tsbuildinfo
dist/
build/

# Environment
.env
.env.local
.env.*.local

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db

# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Testing
coverage/
.nyc_output/

# Misc
.cache/
.temp/
.tmp/

99 changes: 99 additions & 0 deletions templates/typescript/magnitude/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { Kernel, type KernelContext } from "@onkernel/sdk";
import { startBrowserAgent } from "magnitude-core";
import { z } from "zod";

const kernel = new Kernel();

const app = kernel.app("ts-magnitude");

interface UrlInput {
url: string;
}

interface UrlsOutput {
urls: string[];
}

// Use env var + inline model directly in the agent call.

app.action<UrlInput, UrlsOutput>(
"mag-url-extract",
async (ctx: KernelContext, payload?: UrlInput): Promise<UrlsOutput> => {
if (!payload?.url) {
throw new Error("URL is required");
}

let target = payload.url;
if (!target.startsWith("http://") && !target.startsWith("https://")) {
target = `https://${target}`;
}
try {
// Validate URL
new URL(target);
} catch {
throw new Error(`Invalid URL: ${target}`);
}

// Create a Kernel browser so we get a live view and observability
const kernelBrowser = await kernel.browsers.create({
invocation_id: ctx.invocation_id,
stealth: true,
});

console.log(
"Kernel browser live view url:",
kernelBrowser.browser_live_view_url
);

// Start a Magnitude BrowserAgent connected to the Kernel browser via CDP
const agent = await startBrowserAgent({
narrate: true,
url: target,
llm: {
provider: "anthropic",
options: {
model: "claude-sonnet-4-20250514",
apiKey: process.env.ANTHROPIC_API_KEY as string,
},
},
browser: {
cdp: kernelBrowser.cdp_ws_url,
contextOptions: {
viewport: { width: 1024, height: 768 }
}
},
virtualScreenDimensions: { width: 1024, height: 768 }
});

try {
//////////////////////////////////////
// Navigate and extract via Magnitude
//////////////////////////////////////
await agent.act(
`Go to ${target}. Explore the page by scrolling down the page twice. Narrate key steps.`
Copy link
Contributor

Choose a reason for hiding this comment

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

I wonder if this should be in the payload since that is most likely how people will use web agents? This could be a more common patter, not entirely sure though.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I set it up this way so someone can quickly see Magnitude’s benefits without needing a specific task that highlights each feature (e.g. Extract URLs, scroll, etc.). I agree this isn’t the most common pattern or likely a workflow users would have, but it shows off the benefits well IMO and it’s easy to overwrite if needed.

);

const urls = await agent.extract(
"Extract up to 5 absolute URLs on the current page",
z.array(z.string().url()).describe("List of absolute URLs")
);

return { urls };
} finally {
try {
await agent.stop();
} catch (e) {
console.warn("Warning: failed to stop agent", e);
}
try {
await kernel.invocations.deleteBrowsers(ctx.invocation_id);
console.log(`Browsers for invocation ${ctx.invocation_id} cleaned up successfully`);
} catch (e) {
console.warn(
`Warning: failed to clean up browsers for ${ctx.invocation_id}`,
e
);
}
}
}
);
14 changes: 14 additions & 0 deletions templates/typescript/magnitude/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "ts-magnitude",
"module": "index.ts",
"type": "module",
"private": true,
"peerDependencies": {
"typescript": "^5"
},
"dependencies": {
"@onkernel/sdk": ">=0.11.0",
"magnitude-core": "latest",
"zod": "^3.25.0"
}
}
24 changes: 24 additions & 0 deletions templates/typescript/magnitude/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
},
"include": ["./**/*.ts", "./**/*.tsx"],
"exclude": ["node_modules", "dist"]
}