# Project export: mark.ai

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2026
- Tagline: the missing layer of the agent economy, a marketplace where intelligence itself becomes tradable
- Devpost: https://devpost.com/software/mark-itkvsl
- GitHub: https://github.com/akhaire21/treehacks-2026
- Demo: https://mark-ai.vercel.app/
- Video: https://www.youtube.com/embed/cyUWh0rxfuE?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 4 GitHub contributor(s) — Alena Chan (17 commits), Keira (15 commits), Jeet Dekivadia (13 commits), Claude (3 commits)

## Devpost submission (written by the team)

### Inspiration

Yesterday, dozens of hackers ran out of Claude tokens. For $25 worth of Anthropic credits per 1000 hackers, that's ~5,000,000,000 tokens down the drain. If mark.ai existed before, they could have been saved. AI agents repeatedly spend tokens rediscovering the same reasoning patterns: planning workflows, selecting tools, handling retries, and resolving niche edge cases that have already been solved thousands of times. As agents scale globally, this duplicated reasoning becomes one of the largest sources of inefficiency in the AI economy. We built mark.ai from a simple insight: reasoning workflows are reusable digital assets, and the ecosystem needs a marketplace where agents can discover, purchase, and execute proven solutions instead of recomputing them every time.

### What it does

mark.ai is an intelligence marketplace where agents autonomously search, purchase, and execute reusable reasoning workflows. Developers can publish workflows, while agents access them through a lightweight Python SDK (pip install marktools) that exposes structured tool-callable functions such as estimate, search, buy, and execute. Agents can therefore integrate mark.ai directly into their tool-use loop, allowing them to instantly start from high-confidence execution plans while keeping all sensitive execution data local.

### How we built it

We built mark.ai as a full-stack platform consisting of a Next.js + TypeScript marketplace frontend deployed on Vercel, a Python orchestration backend running on Flask, and a hybrid retrieval system powered by Elasticsearch Serverless using combined vector (Jina embeddings) and BM25 keyword ranking for precise workflow matching. A recursive orchestration engine uses Claude to decompose complex tasks into subtasks, retrieve candidate workflow components, and recombine them into executable DAG plans that can be refined through node-level contextual search. We also built marktools, a fully packaged PyPI SDK that allows any AI agent framework, including Claude, OpenAI, LangChain, or custom agents, to communicate with mark.ai directly through structured tool interfaces.

### Challenges we ran into

One of the main challenges was achieving high-precision workflow matching while maintaining production-level latency, which required carefully designing a hybrid retrieval pipeline and separating workflow-level and node-level semantic spaces. Another challenge was building a recursive orchestration pipeline capable of handling complex multi-step tasks where a single workflow match was insufficient. Finally, designing a pricing model that fairly reflects token savings while remaining predictable for autonomous agents required implementing value-aligned pricing and wallet-based budgeting controls.

### Accomplishments we're proud of

Within the hackathon timeframe, we built a fully functional intelligence marketplace, a live production website, a packaged SDK installable via PyPI, and an orchestration system capable of decomposing complex tasks into composable workflow plans. Our system demonstrated substantial improvements in token efficiency, latency, and execution reliability across benchmark scenarios, validating that reusable reasoning workflows can operate as a scalable digital asset class for agent ecosystems.

### What we learned

We learned that scalable agent systems depend on structured execution artifacts rather than raw prompts, and that separating retrieval into multiple semantic layers dramatically improves matching precision. We also learned that privacy-first execution, where workflows are templates executed locally by agents, is critical for real-world adoption of intelligence marketplaces.

### What's next

Next, we plan to expand the creator ecosystem, introduce workflow verification and benchmarking pipelines, and deepen integrations across major agent frameworks so mark.ai becomes a default intelligence distribution layer for agents. By combining marketplace economics, verifiable execution workflows, and seamless SDK-based integrations, our goal is to enable a global economy where agents continuously build on the best available intelligence instead of repeatedly reasoning from scratch.

## README (from the GitHub repository)

# Mark AI — The Intelligence Marketplace

> **Marketplace for AI agents.** A marketplace where AI agents autonomously search, purchase, and execute pre-solved reasoning workflows — saving 70%+ tokens and eliminating repeated planning waste.

Built at [TreeHacks 2026](https://www.treehacks.com/)

---

## The Problem

Every time an AI agent encounters a task — filing Ohio taxes, parsing a Stripe invoice, comparing laptops — it starts from scratch. It burns tokens re-deriving domain knowledge that thousands of other agents have already figured out.

- **10–25% of all tokens** wasted on planning (decomposing tasks, deciding tool calls, handling errors)
- Same hyper-specific tasks get re-solved **millions of times** across agents worldwide
- Too specific to train separate models, but common enough to be enormously valuable

## The Solution

A marketplace of **reusable reasoning workflows** — hyper-specific, battle-tested solution templates that agents buy and execute locally with their own private data.

```bash
pip install marktools
```

```python
from marktools import MarkClient

mark = MarkClient(api_key="mk_...")

# Agent autonomously: estimate → buy → execute → rate
receipt = mark.solve("File Ohio 2024 taxes with W2 and itemized deductions")
print(f"Tokens saved: {receipt.tokens_saved}")  # ~10,000 tokens
```

Three lines of code. Any AI agent (Claude, GPT-4, LangChain) gets access to an ever-growing library of expert-level domain knowledge.

---

## Table of Contents

- [Architecture](#architecture)
- [Project Structure](#project-structure)
- [Tech Stack](#tech-stack)
- [Getting Started](#getting-started)
- [SDK — `marktools`](#sdk--marktools)
- [API Reference](#api-reference)
- [Search Algorithm](#search-algorithm)
- [Dynamic Pricing](#dynamic-pricing)
- [Privacy Architecture](#privacy-architecture)
- [Deployment](#deployment)
- [Demo](#demo)
- [License](#license)

---

## Architecture

```
┌──────────────────────────────────────────────────────────────┐
│                        Mark AI Platform                       │
├──────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌─────────────┐    ┌──────────────┐    ┌────────────────┐  │
│  │  Next.js App │───▶│  Flask API   │───▶│ Elasticsearch  │  │
│  │  (frontend)  │    │  (backend)   │    │  (serverless)  │  │
│  └─────────────┘    └──────┬───────┘    └────────────────┘  │
│                            │                                  │
│                     ┌──────┴───────┐                         │
│                     │   Services   │                         │
│                     ├──────────────┤                         │
│                     │ Claude (LLM) │                         │
│                     │ JINA (embed) │                         │
│                     │ Supabase     │                         │
│                     │ Visa Direct  │                         │
│                     └──────────────┘                         │
│                                                               │
│  ┌─────────────────────────────────────────────────────────┐ │
│  │                    marktools SDK                         │ │
│  │  pip install marktools                                   │ │
│  │  Agents call: estimate → buy → execute → rate            │ │
│  └─────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
```

### Elasticsearch Two-Index Design

Two separate indices instead of one monolithic store:

| Index | Purpose | Content |
|-------|---------|---------|
| `workflows` | Broad search | Full workflow metadata + 1024-dim JINA embeddings |
| `workflows_nodes` | Tree-aware search | Individual steps within workflows + embeddings |

This gives **25% faster** workflow search and **75% faster** node-level search at scale (1,000+ workflows) by eliminating cross-type filter overhead and keeping each index in its own semantic space.

---

## Project Structure

```
mark-ai/
├── app/                          # Next.js pages (App Router)
│   ├── page.tsx                  #   Landing page
│   ├── layout.tsx                #   Root layout
│   ├── globals.css               #   Global styles
│   ├── auth/                     #   Auth flows (login, signup, callback)
│   ├── dashboard/                #   User dashboard
│   ├── marketplace/              #   Browse & purchase workflows
│   ├── sdk/                      #   SDK documentation page
│   └── workflow/                 #   Workflow visualization
│
├── components/                   # React components
│   ├── AgentChat.tsx             #   Live agent chat interface
│   ├── Dashboard.tsx             #   Token balance & history
│   ├── Hero.tsx                  #   Landing hero section
│   ├── HowItWorks.tsx            #   Feature walkthrough
│   ├── Marketplace.tsx           #   Workflow grid
│   ├── Nav.tsx                   #   Navigation bar
│   ├── PricingBreakdown.tsx      #   Pricing calculation display
│   ├── PurchaseModal.tsx         #   Purchase confirmation modal
│   ├── WorkflowCard.tsx          #   Workflow listing card
│   ├── WorkflowVisualizer.tsx    #   DAG/tree visualization
│   └── VisaPayment.tsx           #   Visa payment integration
│
├── backend/                      # Flask API server
│   ├── api.py                    #   Main app — all REST endpoints
│   ├── config.py                 #   Environment & configuration
│   ├── models.py                 #   Dataclasses (Workflow, DAG, etc.)
│   ├── matcher.py                #   Embedding-based workflow matching
│   ├── sanitizer.py              #   PII removal from queries
│   ├── pricing.py                #   Dynamic pricing engine
│   ├── orchestrator.py           #   Multi-step task orchestration
│   ├── query_decomposer.py       #   Recursive query decomposition
│   ├── recomposer.py             #   DAG recomposition
│   ├── agent.py                  #   Claude agent integration
│   ├── commerce.py               #   Token economy & purchases
│   ├── elastic_client.py         #   Elasticsearch client wrapper
│   ├── visa_payments.py          #   Visa CyberSource + Direct
│   ├── workflow_loader.py        #   Workflow JSON loader
│   ├── workflows.json            #   Workflow definitions
│   ├── services/                 #   Service modules
│   │   ├── cache_service.py      #     Response caching
│   │   ├── claude_service.py     #     Anthropic Claude client
│   │   ├── elasticsearch_service.py  # ES operations
│   │   └── embedding_service.py  #     JINA embedding client
│   └── requirements.txt          #   Python dependencies
│
├── marktools/                    # Python SDK package
│   ├── src/marktools/            #   Package source
│   ├── tests/                    #   Test suite
│   ├── pyproject.toml            #   Package config
│   └── LICENSE                   #   MIT license
│
├── agent-sdk/                    # Agent demo scripts
│   ├── tax_agent.py              #   Ohio tax filing agent
│   ├── shopping_agent.py         #   Product comparison agent
│   ├── orchestrator_agent.py     #   Multi-task chaining agent
│   ├── run_all.py                #   Run all demos
│   └── scenarios.py              #   Demo scenarios
│
├── demo/                         # Pitch demo
│   ├── run_demo.py               #   Self-contained demo runner
│   ├── with_marktools.py         #   Agent with marktools
│   ├── without_marktools.py      #   Baseline agent (no marktools)
│   └── benchmark_suite.py        #   Performance benchmarks
│
├── lib/supabase/                 # Supabase client helpers
├── middleware.ts                 # Next.js auth middleware
├── next.config.mjs               # Next.js config
├── vercel.json                   # Vercel deployment config
├── render.yaml                   # Render deployment config
└── package.json                  # Node.js dependencies
```

---

## Tech Stack

### Backend
| Technolog

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 97 recognized source files, 768 KB.
- Anthropic (technology) — detected in the code
- CSS (language) — detected in the code
- Flask (technology) — detected in the code
- Next.js (technology) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Supabase (technology) — detected in the code
- TypeScript (language) — detected in the code
- Vercel (technology) — claimed on Devpost, not found in the code
- AI coding agent: Claude Code — evidence: commit authorship or trailers

## Codebase structure (from repository index)

### Files (114 of 114)

```
.env.example
.gitignore
agent-sdk/agent_runner.py
agent-sdk/orchestrator_agent.py
agent-sdk/requirements.txt
agent-sdk/run_all.py
agent-sdk/scenarios.py
agent-sdk/shopping_agent.py
agent-sdk/tax_agent.py
app/auth/callback/route.ts
app/auth/login/page.tsx
app/auth/signup/page.tsx
app/dashboard/page.tsx
app/docs/page.module.css
app/docs/page.tsx
app/globals.css
app/layout.tsx
app/marketplace/marketplace.module.css
app/marketplace/page.tsx
app/page.tsx
app/sdk/page.tsx
app/sdk/sdk.module.css
app/test-visa/page.tsx
app/workflow/page.module.css
app/workflow/page.tsx
backend/.env.example
backend/agent.py
backend/api.py
backend/commerce.py
backend/config.py
backend/debug_elastic.py
backend/elastic_client.py
backend/matcher.py
backend/models.py
backend/orchestrator.py
backend/pricing.py
backend/query_decomposer.py
backend/recomposer.py
backend/render.yaml
backend/requirements.txt
backend/runtime.txt
backend/sanitizer.py
backend/services/__init__.py
backend/services/cache_service.py
backend/services/claude_service.py
backend/services/elasticsearch_service.py
backend/services/embedding_service.py
backend/setup_elastic.py
backend/test_api.py
backend/test_e2e.py
backend/test_elastic_connection.py
backend/test_end_to_end.py
backend/update_pricing.py
backend/verify_keys.py
backend/visa_payments.py
backend/workflow_loader.py
backend/workflows.json
components/AgentChat.module.css
components/AgentChat.tsx
components/auth/LogoutButton.tsx
components/auth/UserInfo.tsx
components/Background.tsx
components/Dashboard.module.css
components/Dashboard.tsx
components/Footer.module.css
components/Footer.tsx
components/Hero.module.css
components/Hero.tsx
components/HowItWorks.module.css
components/HowItWorks.tsx
components/Marketplace.module.css
components/Marketplace.tsx
components/Nav.module.css
components/Nav.tsx
components/PricingBreakdown.module.css
components/PricingBreakdown.tsx
components/PurchaseModal.module.css
components/PurchaseModal.tsx
components/Tools.module.css
components/Tools.tsx
components/VisaPayment.tsx
components/WorkflowCard.module.css
components/WorkflowCard.tsx
components/WorkflowVisualizer.module.css
components/WorkflowVisualizer.tsx
demo/benchmark_results.csv
demo/benchmark_results.json
demo/benchmark_suite.py
demo/demo_results.json
demo/run_demo.py
demo/with_marktools.py
demo/without_marktools.py
lib/supabase/client.ts
lib/supabase/middleware.ts
lib/supabase/server.ts
marktools/LICENSE
marktools/pyproject.toml
marktools/src/marktools/__init__.py
marktools/src/marktools/client.py
marktools/src/marktools/exceptions.py
marktools/src/marktools/models.py
marktools/src/marktools/py.typed
marktools/src/marktools/tools.py
marktools/tests/__init__.py
marktools/tests/test_marktools.py
middleware.ts
next.config.mjs
package.json
README.md
render.yaml
start-backend.sh
stop-backend.sh
tsconfig.json
vercel.json
```

### Dependencies

- agent-sdk/requirements.txt: anthropic@>=0.40.0, marktools@>=1.0.0, rich@>=12.0.0
- backend/requirements.txt: anthropic@==0.49.0, elasticsearch@==8.12.0, flask@==3.0.0, flask-cors@==4.0.0, gunicorn@==21.2.0, numpy@==1.26.3, python-dotenv@==1.0.0, python-jose@==3.3.0, requests@==2.31.0, scikit-learn@>=1.4.0
- marktools/pyproject.toml: anthropic@>=0.40.0, anthropic@>=0.40.0, langchain-core@>=0.1.0, langchain-core@>=0.1.0, mypy@>=1.0, openai@>=1.0.0, openai@>=1.0.0, pydantic@>=2.0.0, pytest@>=7.0, pytest-asyncio@>=0.21, requests@>=2.28.0, responses@>=0.23, ruff@>=0.1.0
- package.json: @paper-design/shaders-react@^0.0.71, @supabase/ssr@^0.8.0, @supabase/supabase-js@^2.95.3, @types/node@^20, @types/react@18.3.28, @types/react-dom@^18, framer-motion@^12.34.0, next@^14.2.0, react@^18.3.0, react-dom@^18.3.0, react-markdown@^10.1.0, remark-gfm@^4.0.1, typescript@^5

### Recent commits (newest first)

- final push guys
- updated the headliner text
- updated the documentation tab content and the logo
- updated sdk simulation responses
- updated the SDK and Docs tab
- final push of hackathon by me
- fixed the sign up/login buttons
- feat: add PurchaseModal component and integrate purchasing workflow functionality
- updated ui
- refactor: update Workflow interfaces to enforce required avg_tokens fields and improve pricing logic in WorkflowCard
- fixing 0s again
- enhance pricing logic in workflows: calculate avg_tokens_without and avg_tokens_with, improve pricing display in WorkflowCard
- fixing 0s
- fix
- updated navbar
- resolve merge
- changed UI design on homepage, added a copy paste install section
- vercel error fix
- added the dashboard to be a new page and updated wallet
- remove prize refs

## Key source files (fetched from GitHub, selected and truncated for size)

### package.json

```
{
  "name": "mark-marketplace",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@paper-design/shaders-react": "^0.0.71",
    "@supabase/ssr": "^0.8.0",
    "@supabase/supabase-js": "^2.95.3",
    "framer-motion": "^12.34.0",
    "next": "^14.2.0",
    "react": "^18.3.0",
    "react-dom": "^18.3.0",
    "react-markdown": "^10.1.0",
    "remark-gfm": "^4.0.1"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "18.3.28",
    "@types/react-dom": "^18",
    "typescript": "^5"
  }
}

```

### agent-sdk/requirements.txt

```
marktools>=1.0.0
anthropic>=0.40.0
rich>=12.0.0

```

### backend/requirements.txt

```
# Web Framework
flask==3.0.0
flask-cors==4.0.0

# AI & ML Services
anthropic==0.49.0
requests==2.31.0

# Elasticsearch
elasticsearch==8.12.0

# Environment & Config
python-dotenv==1.0.0

# Data / ML
numpy==1.26.3
scikit-learn>=1.4.0

# Production Server
gunicorn==21.2.0

# Payment Processing (Visa Developer API)
python-jose==3.3.0

```

### marktools/pyproject.toml

```
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "marktools"
version = "1.0.0"
description = "SDK for the Mark AI Agent Workflow Marketplace — search, buy, and rate pre-solved reasoning workflows for your AI agents."
readme = "README.md"
license = {file = "LICENSE"}
requires-python = ">=3.9"
authors = [
    {name = "Archit Akhaire"},
]
keywords = [
    "ai",
    "agents",
    "marketplace",
    "workflows",
    "tools",
    "llm",
    "claude",
    "openai",
    "langchain",
    "mcp",
]
classifiers = [
    "Development Status :: 5 - Production/Stable",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.9",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.11",
    "Programming Language :: Python :: 3.12",
    "Programming Language :: Python :: 3.13",
    "Topic :: Scientific/Engineering :: Artificial Intelligence",
    "Topic :: Software Development :: Libraries :: Python Modules",
    "Typing :: Typed",
]
dependencies = [
    "requests>=2.28.0",
    "pydantic>=2.0.0",
]

[project.optional-dependencies]
anthropic = ["anthropic>=0.40.0"]
openai = ["openai>=1.0.0"]
langchain = ["langchain-core>=0.1.0"]
all = [
    "anthropic>=0.40.0",
    "openai>=1.0.0",
    "langchain-core>=0.1.0",
]
dev = [
    "pytest>=7.0",
    "pytest-asyncio>=0.21",
    "responses>=0.23",
    "ruff>=0.1.0",
    "mypy>=1.0",
]

[project.urls]
Homepage = "https://mark.ai"
Documentation = "https://docs.mark.ai"
Repository = "https://github.com/akhaire21/treehacks-2026"
Issues = "https://github.com/akhaire21/treehacks-2026/issues"

[tool.hatch.build.targets.wheel]
packages = ["src/marktools"]

[tool.ruff]
target-version = "py39"
line-length = 100

[tool.mypy]
python_version = "3.9"
strict = true

```

### app/page.tsx

```typescript
import Nav from '@/components/Nav'
import Hero from '@/components/Hero'
import HowItWorks from '@/components/HowItWorks'
import Tools from '@/components/Tools'
import Marketplace from '@/components/Marketplace'
import AgentChat from '@/components/AgentChat'
import Footer from '@/components/Footer'

export default function Home() {
  return (
    <>
      <Nav />
      <Hero />
      <HowItWorks />
      <Tools />
      <Marketplace />
      <AgentChat />
      <Footer />
    </>
  )
}

```

### app/layout.tsx

```typescript
import type { Metadata } from 'next'
import { JetBrains_Mono, Sora } from 'next/font/google'
import './globals.css'
import Background from '@/components/Background'

const jetbrainsMono = JetBrains_Mono({
  subsets: ['latin'],
  variable: '--font-mono',
  weight: ['300', '400', '500', '600', '700'],
})

const sora = Sora({
  subsets: ['latin'],
  variable: '--font-sans',
  weight: ['300', '400', '500', '600', '700'],
})

export const metadata: Metadata = {
  title: 'Mark — The Agent Marketplace',
  description: 'The marketplace your agents already know how to use.',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={`${jetbrainsMono.variable} ${sora.variable}`}>
        <Background />
        {children}
      </body>
    </html>
  )
}

```

### app/dashboard/page.tsx

```typescript
import Nav from '@/components/Nav'
import Dashboard from '@/components/Dashboard'
import Footer from '@/components/Footer'

export default function DashboardPage() {
  return (
    <>
      <Nav />
      <Dashboard />
      <Footer />
    </>
  )
}

```

### app/workflow/page.tsx

```typescript
'use client'

import WorkflowVisualizer from '@/components/WorkflowVisualizer'
import styles from './page.module.css'

export default function WorkflowPage() {
  return (
    <div className={styles.page}>
      <header className={styles.header}>
        <a href="/" className={styles.logo}>
          mark<span className={styles.dot}>.</span>
        </a>
        <div className={styles.badge}>workflow explorer</div>
      </header>
      <main className={styles.main}>
        <h1 className={styles.title}>Agent → Marketplace Flow</h1>
        <p className={styles.subtitle}>
          Interactive visualization of how agents query, purchase, and rate solutions through the Mark protocol.
        </p>
        <WorkflowVisualizer />
      </main>
    </div>
  )
}

```

### lib/supabase/server.ts

```typescript
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { cookies } from 'next/headers'

export async function createClient() {
  const cookieStore = await cookies()

  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL ?? ''
  const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? ''

  return createServerClient(
    supabaseUrl,
    supabaseAnonKey,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value
        },
        set(name: string, value: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value, ...options })
          } catch (error) {
            // The `set` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing
            // user sessions.
          }
        },
        remove(name: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value: '', ...options })
          } catch (error) {
            // The `delete` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing
            // user sessions.
          }
        },
      },
    }
  )
}

```

### app/test-visa/page.tsx

```typescript
'use client'

import { useState } from 'react'

export default function TestVisaPage() {
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<any>(null)
  const [error, setError] = useState<string | null>(null)

  // Test payment creation
  const testPayment = async (packageType: string) => {
    setLoading(true)
    setError(null)
    setResult(null)

    try {
      const response = await fetch('http://localhost:5001/api/visa/create-payment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_id: 'test_user_' + Date.now(),
          token_package: packageType,
        }),
      })

      const data = await response.json()

      if (data.success) {
        setResult(data)

        // Auto-submit to CyberSource for testing
        const form = document.createElement('form')
        form.method = 'POST'
        form.action = data.payment_url

        Object.entries(data.form_data).forEach(([key, value]) => {
          const input = document.createElement('input')
          input.type = 'hidden'
          input.name = key
          input.value = value as string
          form.appendChild(input)
        })

        document.body.appendChild(form)
        form.submit()
      } else {
        setError('Payment creation failed: ' + JSON.stringify(data))
      }
    } catch (err) {
      setError('Error: ' + (err as Error).message)
    } finally {
      setLoading(false)
    }
  }

  // Test payout
  const testPayout = async () => {
    setLoading(true)
    setError(null)

    try {
      const response = await fetch('http://localhost:5001/api/visa/payout-creator', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          creator_id: 'test_creator_123',
          card_number: '4111111111111111',
          amount_tokens: 1700,
          workflow_id: 'test_workflow',
        }),
      })

      const data = await response.json()
      setResult(data)

      if (!data.success) {
        setError('Payout failed: ' + JSON.stringify(data))
      }
    } catch (err) {
      setError('Error: ' + (err as Error).message)
    } finally {
      setLoading(false)
    }
  }

  // Check Visa health
  const checkHealth = async () => {
    setLoading(true)
    setError(null)

    try {
      const response = await fetch('http://localhost:5001/api/visa/health')
      const data = await response.json()
      setResult(data)
    } catch (err) {
      setError('Error: ' + (err as Error).message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 p-8">
      <div className="max-w-4xl mx-auto">
        <h1 className="text-3xl font-bold mb-2">🧪 Visa Payment Testing</h1>
        <p className="text-gray-600 mb-8">
          Test Visa CyberSource payments and Visa Direct payouts
        </p>

        {/* Health Check */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <h2 className="text-xl font-bold mb-4">1. Check Visa Integration Status</h2>
          <button
            onClick={checkHealth}
            disabled={loading}
            className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 disabled:bg-gray-400"
          >
            Check Health
          </button>
        </div>

        {/* Payment Testing */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <h2 className="text-xl font-bold mb-4">2. Test Token Purchase (CyberSource)</h2>
          <p className="text-sm text-gray-600 mb-4">
            Click to create payment and redirect to CyberSource test page.
            <br />
            <strong>Test Card:</strong> 4111111111111111 | CVV: 123 | Expiry: 12/2025
          </p>
          <div className="flex gap-4">
            <button
              onClick={() => testPayment('starter')}
              disabled={loading}
              className="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 disabled:bg-gray-400"
            >
              Starter ($10)
            </button>
            <button
              onClick={() => testPayment('pro')}
              disabled={loading}
              className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 disabled:bg-gray-400"
            >
              Pro ($45)
            </button>
            <button
              onClick={() => testPayment('enterprise')}
              disabled={loading}
              className="bg-purple-600 text-white px-6 py-3 rounded-lg hover:bg-purple-700 disabled:bg-gray-400"
            >
              Enterprise ($120)
            </button>
          </div>
        </div>

        {/* Payout Testing */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <h2 className="text-xl font-bold mb-4">3. Test Creator Payout (Visa Direct)</h2>
          <p className="text-sm text-gray-600 mb-4">
            Test instant payout to creator's card (1700 tokens = $17)
          </p>
          <button
            onClick={testPayout}
            disabled={loading}
            className="bg-yellow-600 text-white px-6 py-3 rounded-lg hover:bg-yellow-700 disabled:bg-gray-400"
          >
            Test Payout ($17)
          </button>
        </div>

        {/* Results Display */}
        {loading && (
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
            <p className="text-blue-800">⏳ Loading...</p>
          </div>
        )}

        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <h3 className="font-bold text-red-800 mb-2">❌ Error</h3>
            <pre className="text-sm text-red-700 whitespace-pre-wrap">{error}</pre>
          </div>
        )}

        {result && (
          <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
            <h3 className="font-bold text-green-800 mb-2"
[truncated — 1621 more characters]
```

[88 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]