create-theokit 0.1.0-alpha.9 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "create-theokit",
3
- "version": "0.1.0-alpha.9",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "description": "Scaffold a new TheoKit project",
6
6
  "license": "Apache-2.0",
7
+ "scripts": {
8
+ "build": "tsup"
9
+ },
7
10
  "bin": {
8
11
  "create-theokit": "./dist/cli.js"
9
12
  },
@@ -13,8 +16,5 @@
13
16
  ],
14
17
  "dependencies": {
15
18
  "cross-spawn": "^7.0.6"
16
- },
17
- "scripts": {
18
- "build": "tsup"
19
19
  }
20
- }
20
+ }
@@ -0,0 +1,78 @@
1
+ # {{name}}
2
+
3
+ TheoKit API-only project. Backend routes with Zod validation + typed responses — no frontend bundle, no React.
4
+
5
+ > 📚 **Full docs:** https://docs.theokit.dev
6
+
7
+ ## Quick start
8
+
9
+ ```bash
10
+ # 1. Set your provider key if you wire an agent route later
11
+ echo 'OPENROUTER_API_KEY=sk-or-v1-...' > .env
12
+
13
+ # 2. Boot the dev server
14
+ npx theokit dev
15
+
16
+ # 3. Probe the health route
17
+ curl http://localhost:3000/api/health
18
+ ```
19
+
20
+ You should see `{"status":"ok"}`. The server is now serving the routes under `server/routes/`.
21
+
22
+ ## Templates
23
+
24
+ - **default** — TheoUI chat composer + agent route.
25
+ - **dashboard** — nested layouts + sidebar.
26
+ - **api-only** (this one) — server routes without React.
27
+ - **postgres** — Drizzle ORM + migrations.
28
+ - **saas** — full app with auth, billing, sessions.
29
+
30
+ ## What the framework auto-loads
31
+
32
+ - **`.env` → `process.env`**. Edit `.env`; restart the dev server.
33
+ - **`.theo/` build output cleanup** on every `theokit build`.
34
+ - **Route discovery** — every `server/routes/*.ts` becomes a wired endpoint.
35
+
36
+ ## Project structure
37
+
38
+ ```
39
+ server/
40
+ ├── routes/
41
+ │ ├── health.ts GET /api/health — returns {status:"ok"}
42
+ │ └── users.ts CRUD /api/users — Zod-validated body
43
+ theo.config.ts Framework config
44
+ .env Secrets — never committed (.gitignore)
45
+ ```
46
+
47
+ ## Sample requests
48
+
49
+ ```bash
50
+ # Health check
51
+ curl http://localhost:3000/api/health
52
+
53
+ # Create a user (POST with JSON body)
54
+ curl -X POST http://localhost:3000/api/users \
55
+ -H 'Content-Type: application/json' \
56
+ -d '{"name":"Alice","email":"alice@example.com"}'
57
+
58
+ # List users
59
+ curl http://localhost:3000/api/users
60
+ ```
61
+
62
+ ## Common commands
63
+
64
+ | Command | What it does |
65
+ |---|---|
66
+ | `npx theokit dev` | Dev server with HMR + structured logs |
67
+ | `npx theokit build` | Production build → `.theo/` |
68
+ | `npx theokit start` | Serve the production build |
69
+ | `npx theokit routes` | List all routes detected |
70
+ | `npm run typecheck` | TypeScript strict check (no emit) |
71
+
72
+ ## Add a new route
73
+
74
+ Drop a `.ts` file in `server/routes/`. Use `defineRoute` from `theokit/server` for Zod-validated handlers, or export `GET`/`POST` directly.
75
+
76
+ ## License
77
+
78
+ Apply your own. The TheoKit framework is Apache-2.0.
@@ -10,13 +10,19 @@
10
10
  "typecheck": "tsc --noEmit"
11
11
  },
12
12
  "dependencies": {
13
- "theokit": "^0.1.0-alpha.8",
13
+ "theokit": "^0.2.0",
14
14
  "react": "^19.0.0",
15
15
  "react-dom": "^19.0.0"
16
16
  },
17
17
  "devDependencies": {
18
+ "@types/node": "^22.10.0",
18
19
  "typescript": "^5.7.0",
19
20
  "@types/react": "^19.0.0",
20
21
  "@types/react-dom": "^19.0.0"
22
+ },
23
+ "pnpm": {
24
+ "onlyBuiltDependencies": [
25
+ "esbuild"
26
+ ]
21
27
  }
22
28
  }
@@ -0,0 +1,34 @@
1
+ import { defineWebhook } from 'theokit/server'
2
+ import { createHmac, timingSafeEqual } from 'node:crypto'
3
+ import { z } from 'zod'
4
+
5
+ /**
6
+ * Echo webhook — demonstrates `defineWebhook` HMAC-SHA256 pattern
7
+ * without depending on an external provider (Stripe, GitHub, etc.).
8
+ *
9
+ * Self-test:
10
+ * SECRET=$(openssl rand -base64 32)
11
+ * echo -n '{"message":"hi"}' | openssl dgst -sha256 -hmac "$SECRET"
12
+ * curl -X POST localhost:3000/api/webhooks/echo \
13
+ * -H "x-echo-signature: <hex from above>" \
14
+ * -H "Content-Type: application/json" \
15
+ * -d '{"message":"hi"}'
16
+ */
17
+ const ECHO_SECRET = process.env.ECHO_WEBHOOK_SECRET ?? ''
18
+
19
+ export const POST = defineWebhook({
20
+ verify: ({ rawBody, headers }) => {
21
+ if (ECHO_SECRET === '') return false
22
+ const sig = headers.get('x-echo-signature') ?? ''
23
+ const expected = createHmac('sha256', ECHO_SECRET).update(rawBody).digest('hex')
24
+ try {
25
+ return timingSafeEqual(Buffer.from(sig, 'utf-8'), Buffer.from(expected, 'utf-8'))
26
+ } catch {
27
+ return false
28
+ }
29
+ },
30
+ inputSchema: z.object({ message: z.string() }),
31
+ handler: async ({ input }) => {
32
+ return Response.json({ echoed: input.message, timestamp: new Date().toISOString() })
33
+ },
34
+ })
@@ -0,0 +1,76 @@
1
+ # {{name}}
2
+
3
+ TheoKit dashboard project. Build the app your agent lives in — with nested layouts and a sidebar wired from day one.
4
+
5
+ > 📚 **Full docs:** https://docs.theokit.dev
6
+
7
+ ## Quick start
8
+
9
+ ```bash
10
+ # 1. Set your provider key (OpenRouter recommended — one key, any model)
11
+ echo 'OPENROUTER_API_KEY=sk-or-v1-...' > .env
12
+
13
+ # 2. Boot the dev server
14
+ npx theokit dev
15
+ ```
16
+
17
+ Open the printed URL. The default surface is a dashboard shell with sidebar nav + content area, ready to host your agent panels.
18
+
19
+ ## Templates
20
+
21
+ - **default** — TheoUI chat composer + agent route.
22
+ - **dashboard** (this one) — nested layouts + sidebar nav.
23
+ - **api-only** — server routes without React.
24
+ - **postgres** — Drizzle ORM + migrations.
25
+ - **saas** — full app with auth, billing, sessions.
26
+
27
+ ## What the framework auto-loads
28
+
29
+ - **`.env` → `process.env`**. Edit `.env`; restart the dev server.
30
+ - **`.theo/` build output cleanup** on every `theokit build`.
31
+ - **Tailwind + `@usetheo/ui` styling** auto-configured for the TheoUI surface.
32
+
33
+ ## Project structure
34
+
35
+ ```
36
+ app/ Frontend (file-based routing with nested layouts)
37
+ ├── layout.tsx root wrapper — TheoUI provider + theme
38
+ ├── page.tsx / — dashboard home
39
+ ├── dashboard/
40
+ │ ├── layout.tsx /dashboard/* — sidebar shell
41
+ │ └── page.tsx /dashboard — primary panel
42
+ server/ Backend (explicit routes)
43
+ ├── routes/
44
+ │ └── health.ts GET /api/health
45
+ theo.config.ts Framework config
46
+ tailwind.config.ts Tailwind theme tokens
47
+ .env Secrets — never committed
48
+ ```
49
+
50
+ ## Common commands
51
+
52
+ | Command | What it does |
53
+ |---|---|
54
+ | `npx theokit dev` | Dev server with HMR + devtools overlay |
55
+ | `npx theokit build` | Production build → `.theo/` |
56
+ | `npx theokit start` | Serve the production build |
57
+ | `npx theokit check` | Lint for upgrade-readiness |
58
+ | `npx theokit routes` | List all routes + actions detected |
59
+ | `npm run typecheck` | TypeScript strict check (no emit) |
60
+
61
+ ## Add a new panel
62
+
63
+ ```bash
64
+ mkdir -p app/dashboard/billing
65
+ cat > app/dashboard/billing/page.tsx <<'EOF'
66
+ export default function BillingPage() {
67
+ return <h2>Billing</h2>
68
+ }
69
+ EOF
70
+ ```
71
+
72
+ The route appears at `/dashboard/billing` after HMR.
73
+
74
+ ## License
75
+
76
+ Apply your own. The TheoKit framework is Apache-2.0.
@@ -10,13 +10,19 @@
10
10
  "typecheck": "tsc --noEmit"
11
11
  },
12
12
  "dependencies": {
13
- "theokit": "^0.1.0-alpha.8",
13
+ "theokit": "^0.2.0",
14
14
  "react": "^19.0.0",
15
15
  "react-dom": "^19.0.0"
16
16
  },
17
17
  "devDependencies": {
18
+ "@types/node": "^22.10.0",
18
19
  "typescript": "^5.7.0",
19
20
  "@types/react": "^19.0.0",
20
21
  "@types/react-dom": "^19.0.0"
22
+ },
23
+ "pnpm": {
24
+ "onlyBuiltDependencies": [
25
+ "esbuild"
26
+ ]
21
27
  }
22
28
  }
@@ -0,0 +1,50 @@
1
+ import { defineCron } from 'theokit/server/cron'
2
+ import { readdir, stat, rm } from 'node:fs/promises'
3
+ import { join, resolve } from 'node:path'
4
+
5
+ /**
6
+ * Daily GC of stale conversation transcripts.
7
+ *
8
+ * The `@usetheo/sdk` Agent persists chat history under
9
+ * `.theokit/agents/<agentId>/messages.jsonl`. With no TTL the directory
10
+ * grows unbounded — production foot-gun. This cron removes any agent
11
+ * directory whose `messages.jsonl` hasn't been touched in 30 days.
12
+ */
13
+ const MAX_AGE_DAYS = 30
14
+ const AGENTS_DIR = '.theokit/agents'
15
+
16
+ export default defineCron('cleanup-conversations', {
17
+ schedule: '0 4 * * *', // Daily 04:00 UTC
18
+ handler: async ({ log }) => {
19
+ const root = resolve(process.cwd(), AGENTS_DIR)
20
+ const cutoff = Date.now() - MAX_AGE_DAYS * 24 * 60 * 60 * 1000
21
+ let removed = 0
22
+ let kept = 0
23
+ let entries: Awaited<ReturnType<typeof readdir>>
24
+ try {
25
+ entries = await readdir(root, { withFileTypes: true })
26
+ } catch {
27
+ log.info({ msg: 'No agents dir yet — first run', dir: root })
28
+ return
29
+ }
30
+ for (const entry of entries) {
31
+ if (!entry.isDirectory()) continue
32
+ const agentDir = join(root, entry.name)
33
+ const messagesFile = join(agentDir, 'messages.jsonl')
34
+ try {
35
+ const s = await stat(messagesFile)
36
+ if (s.mtimeMs < cutoff) {
37
+ await rm(agentDir, { recursive: true, force: true })
38
+ removed++
39
+ } else {
40
+ kept++
41
+ }
42
+ } catch {
43
+ // messages.jsonl missing → orphan dir, remove
44
+ await rm(agentDir, { recursive: true, force: true }).catch(() => {})
45
+ removed++
46
+ }
47
+ }
48
+ log.info({ msg: 'cleanup-conversations complete', removed, kept, maxAgeDays: MAX_AGE_DAYS })
49
+ },
50
+ })
@@ -2,6 +2,8 @@
2
2
 
3
3
  TheoKit project. Build the app your agent lives in — routing, auth, real-time, deploy — wired.
4
4
 
5
+ > 📚 **Full docs:** https://docs.theokit.dev
6
+
5
7
  ## Quick start
6
8
 
7
9
  ```bash
@@ -160,7 +160,7 @@ export default function Page() {
160
160
  return
161
161
  }
162
162
  const action = QUICK_ACTIONS.find((a) => a.id === id)
163
- if (action) handleSubmit(action.label)
163
+ if (action) handleSubmit(typeof action.label === 'string' ? action.label : '')
164
164
  }
165
165
 
166
166
  const isStreaming = status === 'streaming'
@@ -221,9 +221,9 @@ export default function Page() {
221
221
  return (
222
222
  <AgentErrorCard
223
223
  key={item.id}
224
- kind="model"
224
+ kind="tool-failure"
225
225
  title="Agent error"
226
- description={item.message}
226
+ detail={item.message}
227
227
  />
228
228
  )
229
229
  })}
@@ -240,8 +240,8 @@ export default function Page() {
240
240
  <AgentErrorCard
241
241
  kind="network"
242
242
  title="Stream ended with an error"
243
- description="The connection to the agent endpoint was interrupted. Reset to try again."
244
- action={
243
+ detail="The connection to the agent endpoint was interrupted. Reset to try again."
244
+ actions={
245
245
  <Button variant="ghost" size="sm" onClick={() => reset()}>
246
246
  Reset
247
247
  </Button>
@@ -10,9 +10,9 @@
10
10
  "typecheck": "tsc --noEmit"
11
11
  },
12
12
  "dependencies": {
13
- "theokit": "^0.1.0-alpha.8",
14
- "@usetheo/sdk": "^1.1.0",
15
- "@usetheo/ui": "^0.12.0-next.0",
13
+ "theokit": "^0.2.0",
14
+ "@usetheo/sdk": "^1.3.0",
15
+ "@usetheo/ui": "^0.12.0",
16
16
  "lucide-react": "^0.469.0",
17
17
  "react": "^19.0.0",
18
18
  "react-dom": "^19.0.0",
@@ -20,10 +20,16 @@
20
20
  "zod": "^3.24.0"
21
21
  },
22
22
  "devDependencies": {
23
+ "@types/node": "^22.10.0",
23
24
  "typescript": "^5.7.0",
24
25
  "@types/react": "^19.0.0",
25
26
  "@types/react-dom": "^19.0.0",
26
27
  "tailwindcss": "^4.0.0",
27
28
  "@tailwindcss/vite": "^4.0.0"
29
+ },
30
+ "pnpm": {
31
+ "onlyBuiltDependencies": [
32
+ "esbuild"
33
+ ]
28
34
  }
29
35
  }
@@ -0,0 +1,59 @@
1
+ import { defineCron } from 'theokit/server/cron'
2
+ import { readdir, stat, rm } from 'node:fs/promises'
3
+ import type { Dirent } from 'node:fs'
4
+ import { join, resolve } from 'node:path'
5
+
6
+ /**
7
+ * Daily GC of stale conversation transcripts.
8
+ *
9
+ * The `@usetheo/sdk` Agent persists chat history under
10
+ * `.theokit/agents/<agentId>/messages.jsonl`. With no TTL the directory
11
+ * grows unbounded — production foot-gun. This cron removes any agent
12
+ * directory whose `messages.jsonl` hasn't been touched in 30 days.
13
+ */
14
+ const MAX_AGE_DAYS = 30
15
+ const AGENTS_DIR = '.theokit/agents'
16
+
17
+ export default defineCron('cleanup-conversations', {
18
+ schedule: '0 4 * * *', // Daily 04:00 UTC
19
+ handler: async ({ traceId }) => {
20
+ const root = resolve(process.cwd(), AGENTS_DIR)
21
+ const cutoff = Date.now() - MAX_AGE_DAYS * 24 * 60 * 60 * 1000
22
+ let removed = 0
23
+ let kept = 0
24
+ let entries: Dirent[]
25
+ try {
26
+ entries = (await readdir(root, { withFileTypes: true })) as unknown as Dirent[]
27
+ } catch {
28
+ console.info(JSON.stringify({ msg: 'No agents dir yet — first run', dir: root, traceId }))
29
+ return
30
+ }
31
+ for (const entry of entries) {
32
+ if (!entry.isDirectory()) continue
33
+ const agentDir = join(root, String(entry.name))
34
+ const messagesFile = join(agentDir, 'messages.jsonl')
35
+ try {
36
+ const s = await stat(messagesFile)
37
+ if (s.mtimeMs < cutoff) {
38
+ await rm(agentDir, { recursive: true, force: true })
39
+ removed++
40
+ } else {
41
+ kept++
42
+ }
43
+ } catch {
44
+ // messages.jsonl missing → orphan dir, remove
45
+ await rm(agentDir, { recursive: true, force: true }).catch(() => {})
46
+ removed++
47
+ }
48
+ }
49
+ console.info(
50
+ JSON.stringify({
51
+ msg: 'cleanup-conversations complete',
52
+ removed,
53
+ kept,
54
+ maxAgeDays: MAX_AGE_DAYS,
55
+ traceId,
56
+ }),
57
+ )
58
+ },
59
+ })
@@ -34,34 +34,36 @@ export const POST = defineAgentEndpoint({
34
34
  ? (body as { message?: string })
35
35
  : {}
36
36
  const { message = '' } = safeBody
37
- const orKey = process.env.OPENROUTER_API_KEY
38
- const anKey = process.env.ANTHROPIC_API_KEY
39
- const apiKey = orKey !== undefined && orKey.length > 0 ? orKey : anKey
40
- // Model defaults escolhidos pra ser cheap + funcionais empíricamente em 2026-05-28.
41
- // Stranger pode trocar pra modelo de sua preferência.
42
- const modelId =
43
- orKey !== undefined && orKey.length > 0
44
- ? 'openai/gpt-4o-mini' // OpenRouter route cheap (~$0.15/1M tokens) + always available
45
- : 'claude-sonnet-4-5-20250929' // direct Anthropic
46
- if (apiKey === undefined || apiKey.length === 0) {
47
- yield {
48
- type: 'error',
49
- message: 'Set OPENROUTER_API_KEY or ANTHROPIC_API_KEY in your .env to enable the agent.',
50
- }
51
- return
37
+ // Provider resolution centralizada (Strategy pattern) — theokit/server resolve
38
+ // apiKey + baseUrl + provider automático via OPENROUTER_API_KEY / OPENAI_API_KEY /
39
+ // ANTHROPIC_API_KEY presente no env. Wire protocol: OpenAI Chat Completions
40
+ // (universaltodos os providers implementam essa API). Consumer NÃO tem
41
+ // conditionals sobre provider é responsabilidade do framework.
42
+ // Wrap full agent lifecycle in try/catch — provider errors (invalid KEY,
43
+ // 401, rate-limit, model-not-found, 5xx) MUST surface as AgentEvent
44
+ // 'error' so the client renders an actionable message instead of a
45
+ // silent SSE closure. Dogfood chaos Phase 12 validates this contract.
46
+ try {
47
+ const { agent } = await createConversationHistory({
48
+ request,
49
+ response: { headers: cookieHeaders },
50
+ options: {
51
+ // Model id is prefixed with the provider namespace. When using
52
+ // OPENROUTER_API_KEY (default), prefixes route to the correct
53
+ // upstream — `openai/`, `anthropic/`, `google/`, `meta-llama/`,
54
+ // `mistralai/`, `groq/`, etc. See https://openrouter.ai/models.
55
+ // Without the prefix the SDK falls back to a stub response.
56
+ model: { id: 'openai/gpt-4o-mini' },
57
+ tools: [currentTime],
58
+ },
59
+ })
60
+ const run = await agent.send(message, { signal })
61
+ yield* streamAgentRun(run)
62
+ // Intentionally NO agent.dispose() — the agent stays registered so the
63
+ // next request from the same conversation resumes it (continuity).
64
+ } catch (err) {
65
+ const msg = err instanceof Error ? err.message : String(err)
66
+ yield { type: 'error', message: `Agent error: ${msg}` }
52
67
  }
53
- const { agent } = await createConversationHistory({
54
- request,
55
- response: { headers: cookieHeaders },
56
- options: {
57
- apiKey,
58
- model: { id: modelId },
59
- tools: [currentTime],
60
- },
61
- })
62
- const run = await agent.send(message, { signal })
63
- yield* streamAgentRun(run)
64
- // Intentionally NO agent.dispose() — the agent stays registered so the
65
- // next request from the same conversation resumes it (continuity).
66
68
  },
67
69
  })
@@ -0,0 +1,83 @@
1
+ # {{name}}
2
+
3
+ TheoKit project with Postgres + Drizzle ORM wired. Schema-first, migration-aware, typed end-to-end.
4
+
5
+ > 📚 **Full docs:** https://docs.theokit.dev
6
+
7
+ ## Quick start
8
+
9
+ ```bash
10
+ # 0. Provision Postgres
11
+ # Option A — local docker (one-liner):
12
+ docker run --name pg -e POSTGRES_PASSWORD=dev -p 5432:5432 -d postgres:16
13
+ # Option B — hosted: neon.tech, supabase.com, fly.io
14
+
15
+ # 1. Set env
16
+ cat > .env <<'EOF'
17
+ DATABASE_URL=postgres://postgres:dev@localhost:5432/postgres
18
+ OPENROUTER_API_KEY=sk-or-v1-...
19
+ EOF
20
+
21
+ # 2. Generate + apply migrations
22
+ pnpm db:generate
23
+ pnpm db:migrate
24
+
25
+ # 3. Boot the dev server
26
+ npx theokit dev
27
+ ```
28
+
29
+ Open the printed URL. The default surface includes a sample users API backed by Postgres.
30
+
31
+ ## Templates
32
+
33
+ - **default** — TheoUI chat composer + agent route.
34
+ - **dashboard** — nested layouts + sidebar.
35
+ - **api-only** — server routes without React.
36
+ - **postgres** (this one) — Drizzle ORM + migrations.
37
+ - **saas** — full app with auth, billing, sessions.
38
+
39
+ ## What the framework auto-loads
40
+
41
+ - **`.env` → `process.env`**. `DATABASE_URL` must be set before `pnpm db:migrate`.
42
+ - **`.theo/` build output cleanup** on every `theokit build`.
43
+ - **Drizzle schema** under `db/schema.ts` drives migrations + typed query builder.
44
+
45
+ ## Project structure
46
+
47
+ ```
48
+ app/ Frontend
49
+ ├── page.tsx / — sample UI
50
+ server/
51
+ ├── routes/
52
+ │ ├── health.ts GET /api/health
53
+ │ └── users.ts CRUD /api/users — backed by db.users
54
+ db/
55
+ ├── schema.ts Drizzle schema (tables + relations)
56
+ ├── client.ts Drizzle client (used by routes)
57
+ └── migrations/ Generated SQL files (committed)
58
+ drizzle.config.ts Drizzle CLI config
59
+ theo.config.ts Framework config
60
+ .env Secrets — never committed
61
+ ```
62
+
63
+ ## Common commands
64
+
65
+ | Command | What it does |
66
+ |---|---|
67
+ | `npx theokit dev` | Dev server with HMR |
68
+ | `npx theokit build` | Production build |
69
+ | `npx theokit start` | Serve production build |
70
+ | `pnpm db:generate` | Generate SQL migration from `db/schema.ts` |
71
+ | `pnpm db:migrate` | Apply pending migrations to `DATABASE_URL` |
72
+ | `pnpm db:studio` | Open Drizzle Studio UI |
73
+ | `npm run typecheck` | TypeScript strict check |
74
+
75
+ ## Troubleshooting
76
+
77
+ - **`pnpm db:migrate` fails with "ECONNREFUSED"** → check `DATABASE_URL` host:port + Postgres is running (`docker ps` or hosted dashboard).
78
+ - **`relation "users" does not exist`** → you forgot `pnpm db:migrate`. Run it.
79
+ - **Schema change not reflected** → `pnpm db:generate` first, then `pnpm db:migrate`.
80
+
81
+ ## License
82
+
83
+ Apply your own. The TheoKit framework is Apache-2.0.
@@ -14,7 +14,7 @@
14
14
  "db:studio": "drizzle-kit studio"
15
15
  },
16
16
  "dependencies": {
17
- "theokit": "^0.1.0-alpha.8",
17
+ "theokit": "^0.2.0",
18
18
  "react": "^19.0.0",
19
19
  "react-dom": "^19.0.0",
20
20
  "drizzle-orm": "^0.45.0",
@@ -22,9 +22,15 @@
22
22
  "zod": "^3.24.0"
23
23
  },
24
24
  "devDependencies": {
25
+ "@types/node": "^22.10.0",
25
26
  "typescript": "^5.7.0",
26
27
  "@types/react": "^19.0.0",
27
28
  "@types/react-dom": "^19.0.0",
28
29
  "drizzle-kit": "^0.31.0"
30
+ },
31
+ "pnpm": {
32
+ "onlyBuiltDependencies": [
33
+ "esbuild"
34
+ ]
29
35
  }
30
36
  }
@@ -0,0 +1,26 @@
1
+ import { defineJob } from 'theokit/server/jobs'
2
+ import { z } from 'zod'
3
+ import { appendFile, mkdir } from 'node:fs/promises'
4
+ import { resolve, dirname } from 'node:path'
5
+
6
+ /**
7
+ * Background job demonstrating `defineJob` + `ctx.queue.enqueue` pattern.
8
+ *
9
+ * Triggered from `server/routes/users.ts` POST handler via:
10
+ * await ctx.queue.enqueue('log-message', { userId, message })
11
+ *
12
+ * Per ADR-0003 (transactional outbox), enqueue is deferred until the
13
+ * route handler commits successfully — handler throws → 0 jobs dispatched.
14
+ */
15
+ export default defineJob('log-message', {
16
+ input: z.object({ userId: z.string(), message: z.string() }),
17
+ handler: async ({ input, log }) => {
18
+ // v1.1 EC-9: anchor path to process.cwd() — handler CWD may differ from
19
+ // project root when running via external job runner.
20
+ const auditPath = resolve(process.cwd(), '.theo/audit.log')
21
+ await mkdir(dirname(auditPath), { recursive: true })
22
+ const line = `${new Date().toISOString()} user=${input.userId} msg=${input.message}\n`
23
+ await appendFile(auditPath, line)
24
+ log.info({ msg: 'audit logged', userId: input.userId, path: auditPath })
25
+ },
26
+ })
@@ -0,0 +1,103 @@
1
+ # {{name}}
2
+
3
+ TheoKit SaaS template — auth, sessions, billing-ready, and an agent route. The full stack for shipping an account-aware product on day one.
4
+
5
+ > 📚 **Full docs:** https://docs.theokit.dev
6
+
7
+ ## Quick start
8
+
9
+ ```bash
10
+ # 0. Provision Postgres (sessions + users)
11
+ docker run --name pg -e POSTGRES_PASSWORD=dev -p 5432:5432 -d postgres:16
12
+ # Or use a hosted Postgres (neon.tech / supabase.com)
13
+
14
+ # 1. Set env (generate a strong session secret)
15
+ cat > .env <<EOF
16
+ DATABASE_URL=postgres://postgres:dev@localhost:5432/postgres
17
+ SESSION_SECRET=$(openssl rand -base64 32)
18
+ OPENROUTER_API_KEY=sk-or-v1-...
19
+ EOF
20
+
21
+ # 2. Migrate the schema
22
+ pnpm db:generate
23
+ pnpm db:migrate
24
+
25
+ # 3. Boot the dev server
26
+ npx theokit dev
27
+ ```
28
+
29
+ ## Sample auth flow
30
+
31
+ ```bash
32
+ # Register
33
+ curl -X POST http://localhost:3000/api/register \
34
+ -H 'Content-Type: application/json' \
35
+ -d '{"email":"alice@example.com","password":"strong-passphrase"}'
36
+
37
+ # Login (saves session cookie)
38
+ curl -X POST http://localhost:3000/api/login \
39
+ -H 'Content-Type: application/json' \
40
+ -d '{"email":"alice@example.com","password":"strong-passphrase"}' \
41
+ -c cookies.txt
42
+
43
+ # Authenticated request
44
+ curl http://localhost:3000/api/me -b cookies.txt
45
+ ```
46
+
47
+ ## Templates
48
+
49
+ - **default** — TheoUI chat composer + agent route.
50
+ - **dashboard** — nested layouts + sidebar.
51
+ - **api-only** — server routes without React.
52
+ - **postgres** — Drizzle ORM + migrations.
53
+ - **saas** (this one) — full app with auth, billing, sessions.
54
+
55
+ ## What the framework auto-loads
56
+
57
+ - **`.env` → `process.env`**. `SESSION_SECRET`, `DATABASE_URL`, `OPENROUTER_API_KEY` all required.
58
+ - **Encrypted sessions** (AES-256-GCM) via `SESSION_SECRET`.
59
+ - **`.theo/` build output cleanup** on every `theokit build`.
60
+
61
+ ## Project structure
62
+
63
+ ```
64
+ app/ Frontend
65
+ ├── page.tsx / — landing
66
+ server/
67
+ ├── routes/
68
+ │ ├── login.ts POST /api/login — sets session cookie
69
+ │ ├── logout.ts POST /api/logout — clears session
70
+ │ ├── me.ts GET /api/me — requireAuth() guarded
71
+ │ └── agent.ts POST /api/agent — agent SSE, requireAuth()
72
+ db/
73
+ ├── schema.ts users + sessions tables (Drizzle)
74
+ └── migrations/ generated SQL (committed)
75
+ drizzle.config.ts Drizzle config
76
+ theo.config.ts Framework config
77
+ .env Secrets — never committed
78
+ ```
79
+
80
+ ## Common commands
81
+
82
+ | Command | What it does |
83
+ |---|---|
84
+ | `npx theokit dev` | Dev server with HMR + auth |
85
+ | `npx theokit build` | Production build |
86
+ | `npx theokit start` | Serve production build |
87
+ | `pnpm db:generate` | Generate SQL migration |
88
+ | `pnpm db:migrate` | Apply migrations |
89
+ | `npm run typecheck` | TypeScript strict check |
90
+
91
+ ## Adding billing
92
+
93
+ Stripe is the canonical path — add `STRIPE_SECRET_KEY` to `.env`, mount `server/routes/billing/webhook.ts` via `defineWebhook`, and wire plan checks into `requireAuth()`.
94
+
95
+ ## Troubleshooting
96
+
97
+ - **`SESSION_SECRET must be at least 32 bytes`** → regenerate with `openssl rand -base64 32`.
98
+ - **`relation "users" does not exist`** → run `pnpm db:migrate` first.
99
+ - **`401 Unauthorized` on `/api/me`** → login first; cookie must be sent (`-b cookies.txt`).
100
+
101
+ ## License
102
+
103
+ Apply your own. The TheoKit framework is Apache-2.0.
@@ -14,8 +14,8 @@
14
14
  "db:studio": "drizzle-kit studio"
15
15
  },
16
16
  "dependencies": {
17
- "theokit": "^0.1.0-alpha.8",
18
- "@usetheo/ui": "^0.12.0-next.0",
17
+ "theokit": "^0.2.0",
18
+ "@usetheo/ui": "^0.12.0",
19
19
  "react": "^19.0.0",
20
20
  "react-dom": "^19.0.0",
21
21
  "react-router": "^7.0.0",
@@ -24,9 +24,15 @@
24
24
  "zod": "^3.24.0"
25
25
  },
26
26
  "devDependencies": {
27
+ "@types/node": "^22.10.0",
27
28
  "typescript": "^5.7.0",
28
29
  "@types/react": "^19.0.0",
29
30
  "@types/react-dom": "^19.0.0",
30
31
  "drizzle-kit": "^0.31.0"
32
+ },
33
+ "pnpm": {
34
+ "onlyBuiltDependencies": [
35
+ "esbuild"
36
+ ]
31
37
  }
32
38
  }
@@ -1,10 +1,20 @@
1
1
  import { defineAgentEndpoint, requireAuth, type AgentEvent } from 'theokit/server'
2
+ import { trackAgentRun } from 'theokit/server/cost'
2
3
  import type { RequestContext } from '../context.js'
3
4
 
4
5
  /**
5
6
  * Protected agent endpoint. `requireAuth` fires BEFORE the stream starts;
6
7
  * unauthorized requests get 401 immediately — no SSE bytes leak.
7
8
  *
9
+ * Observability: wraps the run with `trackAgentRun` to surface per-user
10
+ * cost + token usage to the configured `UsageStorageAdapter` (configure via
11
+ * `theo.config.ts > cost.storage`). Also feeds the devtools `Agents` tab
12
+ * (when running in dev).
13
+ *
14
+ * NOTE: `costUsd: 0` is a v1 stub. Pricing table integration is a
15
+ * `@usetheo/sdk` follow-up (R0.5.11). Devtools tab renders "$0.0000" —
16
+ * indicates "cost tracking not yet calibrated for this model".
17
+ *
8
18
  * Replace the mock generator with your LLM provider call.
9
19
  */
10
20
  export const POST = defineAgentEndpoint<{ message: string }, RequestContext>({
@@ -12,10 +22,28 @@ export const POST = defineAgentEndpoint<{ message: string }, RequestContext>({
12
22
  requireAuth(ctx.session)
13
23
  const body = (await request.json()) as { message?: string }
14
24
  const msg = body.message ?? ''
15
- yield {
16
- type: 'message',
17
- content: `Hello ${ctx.session.email}, you said: "${msg}"`,
25
+ try {
26
+ yield {
27
+ type: 'message',
28
+ content: `Hello ${ctx.session.email}, you said: "${msg}"`,
29
+ }
30
+ yield { type: 'message', content: '(Replace this mock with your LLM.)' }
31
+ } finally {
32
+ // Always emit observability — even on stream error / abort.
33
+ // `storage` resolved from theo.config.ts > cost.storage (undefined =
34
+ // no-op; configure to enable persistence + devtools tab visibility).
35
+ // To enable persistent cost tracking: wire `cost: { storage }` into
36
+ // `theo.config.ts` and forward via context. Demo passes `undefined`
37
+ // (no-op storage; still fires devtools dispatcher in dev mode).
38
+ await trackAgentRun(
39
+ {
40
+ userId: ctx.session.email,
41
+ model: 'mock/echo',
42
+ tokens: { input: msg.length, output: 0 }, // crude — real impl uses tokenizer
43
+ costUsd: 0, // v1 stub
44
+ },
45
+ { storage: undefined },
46
+ )
18
47
  }
19
- yield { type: 'message', content: '(Replace this mock with your LLM.)' }
20
48
  },
21
49
  })
@@ -0,0 +1,49 @@
1
+ import { defineWebhook } from 'theokit/server'
2
+ import { createHmac, timingSafeEqual } from 'node:crypto'
3
+ import { z } from 'zod'
4
+
5
+ /**
6
+ * Stripe webhook receiver.
7
+ *
8
+ * Verifies `Stripe-Signature` header per Stripe's documented HMAC-SHA256
9
+ * scheme (https://stripe.com/docs/webhooks/signatures). Real impl would
10
+ * handle `checkout.session.completed`, `invoice.paid`, etc.
11
+ *
12
+ * Setup:
13
+ * 1. Create webhook endpoint in Stripe Dashboard pointing to /api/billing/stripe-webhook
14
+ * 2. Copy signing secret → `.env` STRIPE_WEBHOOK_SECRET
15
+ * 3. Test locally: `stripe listen --forward-to localhost:3000/api/billing/stripe-webhook`
16
+ */
17
+ const STRIPE_SECRET = process.env.STRIPE_WEBHOOK_SECRET ?? ''
18
+
19
+ export const POST = defineWebhook({
20
+ verify: ({ rawBody, headers }) => {
21
+ if (STRIPE_SECRET === '') return false
22
+ const sigHeader = headers.get('stripe-signature') ?? ''
23
+ // Stripe format: `t=<unix-ts>,v1=<hash>` (potentially also v0)
24
+ const parts: Record<string, string> = {}
25
+ for (const pair of sigHeader.split(',')) {
26
+ const [k, v] = pair.split('=')
27
+ if (k && v) parts[k.trim()] = v.trim()
28
+ }
29
+ const t = parts['t']
30
+ const v1 = parts['v1']
31
+ if (!t || !v1) return false
32
+ const signedPayload = `${t}.${rawBody}`
33
+ const expected = createHmac('sha256', STRIPE_SECRET).update(signedPayload).digest('hex')
34
+ try {
35
+ return timingSafeEqual(Buffer.from(v1, 'utf-8'), Buffer.from(expected, 'utf-8'))
36
+ } catch {
37
+ return false
38
+ }
39
+ },
40
+ inputSchema: z.object({ type: z.string(), data: z.unknown() }),
41
+ handler: async ({ input, log }) => {
42
+ log.info({ msg: 'stripe webhook received', type: input.type })
43
+ // TODO: dispatch by input.type:
44
+ // - 'checkout.session.completed' → activate subscription
45
+ // - 'invoice.paid' → extend access
46
+ // - 'invoice.payment_failed' → notify user + retry plan
47
+ return Response.json({ received: true })
48
+ },
49
+ })
package/LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for describing the origin of the Work and
141
- reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright 2026 usetheo.dev
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.