Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
92e5fbb
chore: reorganize forge to satisfy repository standards
cyber-turtle May 1, 2026
8462c3c
docs: fix screenshot path in forge readme
cyber-turtle May 1, 2026
5ac04a5
docs: update path in setup instructions
cyber-turtle May 1, 2026
987cca8
docs: add live demo links to forge kit
cyber-turtle May 1, 2026
472dbc6
feat: add graceful error screen with sprite animation
cyber-turtle May 1, 2026
f3da84d
style: replace error sprite with premium caution icon and fix buttons
cyber-turtle May 1, 2026
0a0b2a8
fix: standardize PDF export width for A4 layout
cyber-turtle May 1, 2026
79db86b
fix: use jsPDF.html for better pagination and avoid text clipping
cyber-turtle May 1, 2026
7c47825
fix: resolve PDF text clipping using onclone style stripping
cyber-turtle May 1, 2026
552e2b9
fix: implement canvas slicing and signature page breaks for PDF export
cyber-turtle May 1, 2026
1fc6ece
fix: switch to print-based PDF export for perfect pagination
cyber-turtle May 1, 2026
66c78e8
fix: refine print styles for clean A4 PDF export
cyber-turtle May 1, 2026
2080b39
fix: rewrite print styles - eliminate dead space, restore fonts, fix …
cyber-turtle May 1, 2026
73df324
fix: preserve signature grid, match page background, strip remaining …
cyber-turtle May 1, 2026
2b3158a
fix: nuke aurora background overlays and all dark wrappers from print…
cyber-turtle May 1, 2026
3570015
fix: use print-document-wrapper to isolate document from aurora backg…
cyber-turtle May 1, 2026
a30973c
fix: hide aurora bg and noise overlay in print, strip dark bg from wr…
cyber-turtle May 1, 2026
c8b7817
fix: prevent invoice table rows from clipping across PDF pages
cyber-turtle May 1, 2026
ba5b392
docs: add comprehensive flow documentation to all four Forge flows
cyber-turtle May 1, 2026
6fcda46
final: polish export UI, fix page spacing, and add detailed flow docu…
cyber-turtle May 1, 2026
585ff33
fix: ensure manually added line items include the project currency
cyber-turtle May 1, 2026
3c4258f
docs: sync PDF export documentation and cleanup unused dependencies
cyber-turtle May 1, 2026
8076a71
Potential fix for pull request finding
cyber-turtle May 1, 2026
c1404c5
feat(forge): finalize forge kit implementation and polish UI
cyber-turtle May 5, 2026
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
216 changes: 216 additions & 0 deletions kits/forge/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
# Forge - AI Contract & Invoice Generator

> Enter your project details once. Get AI-calibrated pricing. Select a governing law. Walk away with a professional contract and matching invoice - signed and exported as PDFs, in minutes.

![Built with Lamatic](https://img.shields.io/badge/Built%20with-Lamatic-5B21B6?style=flat-square)
![Next.js 14](https://img.shields.io/badge/Next.js-14-000000?style=flat-square)
![TypeScript](https://img.shields.io/badge/TypeScript-5-3178C6?style=flat-square)
![mission-possible](https://img.shields.io/badge/challenge-mission-possible-F59E0B?style=flat-square)

[**Live Demo →**](https://forge-wheat-one.vercel.app/)

![Forge Screenshot](apps/public/screenshot.png)

---

## 1. The Problem

Cross-border freelancers, especially in Africa, South Asia, and Latin America, routinely work without professional contracts. They send vague invoices, have no governing law clause, and price their services based on gut feeling rather than market data. When disputes arise, they have zero legal protection.

Hiring a lawyer to draft a cross-border services agreement costs $500–$2,000. Most freelancers skip it entirely.

---

## 2. The Approach

Forge completely automates the creation of professional freelance contracts and invoices using 4 Lamatic AI flows in a guided wizard:

**Flow 1 - Pricing Analysis (`forge-pricing`):**
Takes the freelancer's field, experience level, country, and deliverables - returns AI-calibrated per-item pricing with market context and justification for each rate. The freelancer can edit rates before confirming.

**Flow 2 - Governing Law Tradeoff (`forge-tradeoff`):**
Analyses both parties' countries, the payment structure, and the freelancer's primary concern (IP, getting paid, scope creep, disputes). Returns 3 governing law options with pros, cons, and a recommendation.

**Flow 3 - Contract Generation (`forge-contract`):**
Takes all accumulated data - project details, confirmed pricing, chosen governing law - and generates a full 13-section services agreement: parties, recitals, scope, timeline, payment terms, IP, confidentiality, revision policy, late payment, termination, governing law, dispute resolution, and signatures.

**Flow 4 - Invoice Generation (`forge-invoice`):**
Generates a professional invoice with the confirmed line items, freelancer/client details, payment instructions, and notes referencing the contract date.

Both documents can be **signed** with an e-signature canvas and **exported as multi-page PDFs**.

---

## 3. The Result

A freelancer fills out one form, waits ~60 seconds, and receives a contract and invoice that would have taken a lawyer hours to draft. The documents are tailored to their specific jurisdiction, payment method, and experience level. No auth, no database, no subscription - just Lamatic as the backend.

---

## 4. Tradeoffs & Assumptions

**Tradeoffs:**
- **No backend persistence:** All state lives in `localStorage`, so it persists in the same browser until the user clears site data or uses a different browser/device. This keeps the architecture simple (no database, no auth) but means there is no cross-device sync or account-based recovery.
- **API key security vs. simplicity:** Flow IDs use `NEXT_PUBLIC_` prefix (visible to the browser) since they aren't secrets. The actual `LAMATIC_API_KEY` stays server-side and is proxied through `/api/flow`.
- **PDF fidelity:** We use the browser's native print engine (`window.print()`) for exports. This ensures perfect A4 pagination, vector-sharp text, and zero section clipping, surpassing typical canvas-based libraries. The tradeoff is that it opens a system print dialog rather than a direct background download.

**Assumptions:**
- The user is a freelancer doing remote/digital work (code, design, writing, consulting). Physical trades or heavily regulated industries may need more specialised contract language.
- The AI-generated contract is a strong starting point, not a substitute for legal advice on high-stakes engagements.

---

## Tech Stack

| Layer | Technology |
|-------|-----------|
| Flow orchestration | **Lamatic.ai** (4 flows) |
| Frontend | **Next.js 14** (App Router, TypeScript) |
| Styling | **Tailwind CSS** |
| PDF export | **Browser Native** (`window.print()`) |
| E-signature | **react-signature-canvas** |
| Icons | **lucide-react** |

---

## Prerequisites

- Node.js 18+ and npm 9+
- A [Lamatic.ai](https://lamatic.ai) account with all 4 Forge flows deployed
- Vercel account (optional, for deployment)

---

## Setup Instructions

1. **Clone and navigate to the kit folder**
```bash
git clone https://github.com/Lamatic/AgentKit.git
cd AgentKit/kits/forge/apps
```

2. **Install dependencies**
```bash
npm install
```

3. **Set up environment variables**
```bash
cp .env.example .env.local
```
Then fill in `.env.local` with your real values (see table below).

4. **Start the development server**
```bash
npm run dev
```

5. **Open your browser**
```text
http://localhost:3000
```

---

## Environment Variables

| Variable | Description | Where to Find |
|----------|-------------|--------------|
| `NEXT_PUBLIC_LAMATIC_ENDPOINT` | Your Lamatic GraphQL API endpoint | Lamatic Studio → Settings → API Docs |
| `NEXT_PUBLIC_LAMATIC_PROJECT_ID` | Your Lamatic project ID | Lamatic Studio → Settings → Project |
| `LAMATIC_API_KEY` | Your API key (server-only, never exposed) | Lamatic Studio → Settings → API Keys |
| `NEXT_PUBLIC_FLOW_PRICING` | Forge Pricing flow ID | Lamatic Studio → forge-pricing → ⋮ → Flow ID |
| `NEXT_PUBLIC_FLOW_TRADEOFF` | Forge Tradeoff flow ID | Lamatic Studio → forge-tradeoff → ⋮ → Flow ID |
| `NEXT_PUBLIC_FLOW_CONTRACT` | Forge Contract flow ID | Lamatic Studio → forge-contract → ⋮ → Flow ID |
| `NEXT_PUBLIC_FLOW_INVOICE` | Forge Invoice flow ID | Lamatic Studio → forge-invoice → ⋮ → Flow ID |

> ⚠️ `LAMATIC_API_KEY` must NEVER be exposed client-side. All Lamatic calls go through the server-side API route at `/api/flow`.

---

## Flows

### Pricing Flow (`forge-pricing`)
**Input:** `{ work_type, field, experience_level, years_of_experience, deliverables, payment_structure, currency, freelancer_country, client_country }`
**Output:** `{ pricing: string (JSON) }` → parsed to `{ experience_assessment, market_context, line_items[], total_amount, currency }`

Analyses the freelancer's experience and geography against market data, returns per-item suggested pricing with justification.

### Tradeoff Flow (`forge-tradeoff`)
**Input:** `{ freelancer_name, freelancer_country, freelancer_payment_method, freelancer_primary_concern, client_name, client_country, client_type, project_title, project_description, deliverables, timeline_start, timeline_end, payment_amount, payment_currency, payment_structure, work_type }`
**Output:** `{ options: string (JSON) }` → parsed to `Array<{ option_name, explanation, pros[], cons[], recommended }>`

Returns 3 governing law options with pros, cons, and a recommendation based on both parties' jurisdictions.

### Contract Flow (`forge-contract`)
**Input:** All project details + `payment_amount`, `payment_currency`, `chosen_governing_law`
**Output:** `{ contract: string (JSON) }` → parsed to `Record<string, { heading, body }>`

Generates a full 13-section services agreement: parties, recitals, scope, timeline, payment, IP, confidentiality, revisions, late payment, termination, governing law, dispute resolution, signatures.

### Invoice Flow (`forge-invoice`)
**Input:** Freelancer/client details + `line_items` (stringified JSON), `currency`, `total_amount`, `payment_instructions`, `notes`
**Output:** `{ invoice: string (JSON) }` → parsed to `{ header, freelancer, client, line_items[], totals, payment_instructions, notes }`

Generates a formatted invoice matching the confirmed pricing from the contract.

> **Important:** All flow responses come back as `result.result.fieldName` where `fieldName` is a JSON string that must be parsed with `JSON.parse()`.
Comment thread
cyber-turtle marked this conversation as resolved.

---

## Project Structure

```
kits/forge/
├── lamatic.config.ts # REQUIRED: project metadata
├── agent.md # REQUIRED: agent identity doc
├── README.md # Root setup guide
├── constitutions/ # Guardrails
├── flows/ # Flow definitions
└── apps/ # Next.js App
├── app/
├── components/
├── actions/
├── lib/
└── package.json
```

---

## Deploy to Vercel

1. Push your branch to GitHub:
```bash
git checkout -b feat/forge
git add kits/forge/
git commit -m "feat: Add Forge - AI Contract & Invoice Generator"
git push origin feat/forge
```

2. Go to [vercel.com](https://vercel.com) and import your repo

3. Set the **root directory** to `kits/forge/apps`

4. Add all environment variables from the table above

5. Click **Deploy**

---

## Live Preview

[**Open the live demo →**](https://forge-wheat-one.vercel.app/)

![Forge Screenshot](apps/public/screenshot.png)

---

## Contributing

This kit was built for the [mission-possible](https://github.com/Lamatic/AgentKit). To open a PR:

```text
github.com/Lamatic/AgentKit/compare/main...YOUR-USERNAME:feat/forge?expand=1
```

Add the `mission-possible` label to your PR.
120 changes: 120 additions & 0 deletions kits/forge/agent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# Forge

## Overview
Forge is an AI-powered document generation agent specifically engineered for cross-border freelancers. It addresses the massive legal and financial gap faced by independent contractors who often operate without formal services agreements due to high legal fees and jurisdictional complexity.

Forge uses a multi-flow guided wizard architecture (4 distinct Lamatic flows) to automate the entire onboarding-to-billing lifecycle. It doesn't just "fill templates"; it performs AI-calibrated market analysis for pricing, evaluates international jurisdictional tradeoffs for governing law selection, and synthesizes complete, legally-structured 13-section contracts and matching invoices. The system is designed to be session-based and stateless, utilizing local storage for temporary persistence and Lamatic AgentKit flows for the core intelligence.

---

## Purpose
Forge exists to democratize access to professional legal and financial documentation for the global freelance economy. Many freelancers, particularly in emerging markets, price their services based on intuition and work without the protection of a governing law clause. Forge solves this by providing:

1. **Market Calibration**: An AI flow that suggests rates based on global market data, freelancer location, and deliverables.
2. **Jurisdictional Risk Mitigation**: A tradeoff analysis flow that helps freelancers choose between their local law, the client's law, or a neutral third jurisdiction (like Delaware or England & Wales).
3. **Execution Ready Documents**: High-fidelity, signed, and exportable PDFs that would otherwise cost thousands of dollars in legal fees.

By the end of a Forge session, a freelancer has a professional contract and a matching invoice, significantly reducing the risk of payment disputes and scope creep.

---

## Flows

### `Forge - Pricing Analysis`

- **Trigger**
- Invoked via a GraphQL request when the user completes Step 1 (Project Details).
- **What it does**
1. Receives data about the work type, field, deliverables, and both parties' countries.
2. Analyzes the freelancer's experience level and geography against global market benchmarks.
3. Returns a structured pricing breakdown with market context and justifications for each rate.
- **When to use this flow**
- To provide the user with data-driven confidence in their pricing before generating a contract.
- **Output**
- A JSON object containing `experience_assessment`, `market_context`, `line_items[]` (with suggested rates), and `total_amount`.

### `Forge - Tradeoff Analysis`

- **Trigger**
- Invoked when the user selects their primary concern (IP, Getting Paid, etc.) in Step 3.
- **What it does**
1. Compares the legal jurisdictions of the freelancer and the client.
2. Evaluates the specific payment structure and project deliverables.
3. Proposes three distinct governing law options tailored to the user's primary concern.
- **When to use this flow**
- To help users decide which country's laws should govern their services agreement.
- **Output**
- An array of `options` containing `option_name`, `explanation`, `pros[]`, `cons[]`, and a `recommended` flag.

### `Forge - Contract Generation`

- **Trigger**
- Invoked in Step 4 after the user confirms all pricing and legal choices.
- **What it does**
1. Synthesizes every data point collected throughout the wizard.
2. Generates a full 13-section Services Agreement including: Parties, Recitals, Scope, Timeline, Payment, IP, Confidentiality, Revisions, Late Payment, Termination, Governing Law, Dispute Resolution, and Signatures.
- **When to use this flow**
- To create the final legal document for the engagement.
- **Output**
- A detailed JSON record where each key is a section heading and the value contains the legal body text.

### `Forge - Invoice Generation`

- **Trigger**
- Invoked simultaneously with or immediately after the contract generation.
- **What it does**
1. Translates the confirmed line items and pricing from the contract into a standard invoice format.
2. Adds professional headers, freelancer/client contact info, and payment instructions.
- **When to use this flow**
- To generate the corresponding billable document for the project.
- **Output**
- A formatted invoice JSON containing `freelancer`, `client`, `line_items[]`, `totals`, and `notes`.

---

## Guardrails
- **Legal Advice**: Forge must include a disclaimer that it is a decision-support tool, not a law firm.
- **PII Handling**: Personal details (names, emails) are processed but not persisted long-term in the vector store; they exist only in session memory.
- **Integrity**: Generated rates must be justified with market context to prevent arbitrary pricing.
- **Structure**: Contracts must never omit critical "kill clauses" like termination or IP ownership.

---

## Integration Reference

| Integration | Purpose | Config Key |
|---|---|---|
| Lamatic AgentKit | Orchestrates the 4 document/pricing flows | `NEXT_PUBLIC_FLOW_...` |
| LLM Provider | Synthesis of pricing, tradeoffs, and legal text | Configured in Lamatic Studio |
| PDF Engine | Browser's native print engine (`window.print()`) | Native |
| Storage | Session management | `localStorage` |

---

## Environment Setup
- `NEXT_PUBLIC_FLOW_PRICING` — Flow ID for Pricing Analysis.
- `NEXT_PUBLIC_FLOW_TRADEOFF` — Flow ID for Tradeoff Analysis.
- `NEXT_PUBLIC_FLOW_CONTRACT` — Flow ID for Contract Synthesis.
- `NEXT_PUBLIC_FLOW_INVOICE` — Flow ID for Invoice Generation.
- `LAMATIC_API_KEY` — Server-only secret for authenticating flow calls.
- `NEXT_PUBLIC_LAMATIC_ENDPOINT` — Your project's GraphQL endpoint.
- `NEXT_PUBLIC_LAMATIC_PROJECT_ID` — Your Lamatic project ID.

---

## Common Failure Modes

| Symptom | Likely Cause | Fix |
|---|---|---|
| "Failed to generate pricing" | Invalid field or missing country data | Ensure all Step 1 fields are filled. |
| "Governing law options empty" | Unsupported jurisdiction pair | Select a more standard country or manually input law. |
| PDF exports looking cut off | Layout shift or incorrect @media print settings | Our custom `@media print` CSS in `globals.css` handles this by isolating the document surface. |
| 401 Unauthorized | Server-side proxy missing API Key | Check `LAMATIC_API_KEY` in `.env.local` or Vercel settings. |

---

## Notes
- This is a **Kit** contribution (`type: kit`) with a complete Next.js UI in the `apps/` directory.
- Live demo is linked in `lamatic.config.ts`: `https://forge-wheat-one.vercel.app/`
- All AI logic is externalized into Lamatic flows to keep the frontend light and maintainable.
- Future improvements include persistent document storage and automated email delivery of signed PDFs.
17 changes: 17 additions & 0 deletions kits/forge/apps/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Lamatic Project Configuration
# Found in: Lamatic Studio → Settings → API Docs → API → Endpoint and use as follows, ([your endpoint]/graphql)
NEXT_PUBLIC_LAMATIC_ENDPOINT="YOUR_LAMATIC_ENDPOINT"

# Found in: Lamatic Studio → Settings → Project → Project ID
NEXT_PUBLIC_LAMATIC_PROJECT_ID="YOUR_PROJECT_ID"

# Found in: Lamatic Studio → Settings → API Keys
# IMPORTANT: Keep this server-side only. Do not prefix with NEXT_PUBLIC_
LAMATIC_API_KEY="YOUR_API_KEY"

# Forge Flow IDs
# Found in: Lamatic Studio → [Flow Name] → Three-dot menu (⋮) → Flow ID
NEXT_PUBLIC_FLOW_PRICING="YOUR_FORGE_PRICING_FLOW_ID"
NEXT_PUBLIC_FLOW_TRADEOFF="YOUR_FORGE_TRADEOFF_FLOW_ID"
NEXT_PUBLIC_FLOW_CONTRACT="YOUR_FORGE_CONTRACT_FLOW_ID"
NEXT_PUBLIC_FLOW_INVOICE="YOUR_FORGE_INVOICE_FLOW_ID"
28 changes: 28 additions & 0 deletions kits/forge/apps/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules

# next.js
/.next/
/out/

# production
/build

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files
.env
.env.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
Loading