feat(engine): merge cloudflare-migration — paradigm D engine, BYOK proxy, story persistence (#95)

Squash-merge the cloudflare-migration branch (7 commits by Kai ki) into
staging with conflict resolution, feature integration, and bug fixes.

Engine:
- Paradigm D: single-stream Writer replacing dual-phase Plan/Beats
- Delete Architect agent; story bible generated via Writer <plan> tag
- Modular prompt architecture (segments/registry/builder)
- StreamRouter for tagged stream splitting (<plan>/<story>/<choices>)

Infrastructure:
- Cloudflare Workers deployment (wrangler.jsonc, OpenNext adapter)
- D1 database schema + Drizzle ORM (scaffolded, not yet active)
- R2 storage helpers (scaffolded, not yet active)
- Story persistence API routes + client-side persistence

BYOK (Bring Your Own Key):
- /api/llm/user-proxy with SSRF-protected LLM proxy (+ requireUser auth)
- CORS-aware fetch in ai-client: auto-detect CORS failure, fallback to
  server proxy transparently via OpenAI SDK custom fetch
- BYO config support added to classify-freeform and vision routes
- SettingsModal CORS privacy notice (keys never logged/stored)

SSE streaming:
- engineClient.ts: fetchSSE helper for progressive scene events
- startSession/requestScene accept optional emit callback
- Fix SSE error event field name (error → message) in scene/start routes

i18n integration:
- Wire buildLanguageDirective into paradigm D's prompt builder
- Update corsNotice i18n keys (zh-CN/en/ja) with CORS proxy privacy text
- Preserve Session.language + LanguageSwitcher from i18n commit

Co-authored-by: Kai ki <155355644+zbf1009@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Zonghao Yuan
2026-06-18 18:05:38 +08:00
committed by GitHub
parent 05bd7e229c
commit 0e4c2ebef4
78 changed files with 7396 additions and 919 deletions
+5 -3
View File
@@ -1,7 +1,7 @@
import { classifyFreeform } from "@infiplot/engine";
import type { FreeformClassifyRequest } from "@infiplot/types";
import { NextResponse } from "next/server";
import { loadEngineConfig } from "@/lib/config";
import { loadEngineConfig, buildByoEngineConfig } from "@/lib/config";
import { requireUser } from "@/lib/supabase/guard";
export const runtime = "nodejs";
@@ -25,11 +25,13 @@ export async function POST(req: Request) {
}
try {
const config = loadEngineConfig();
const official = loadEngineConfig();
const config = body.byo ? buildByoEngineConfig(body.byo, official) : official;
const result = await classifyFreeform(config, body);
return NextResponse.json(result);
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
return NextResponse.json({ error: message }, { status: 500 });
const status = message.includes("Invalid BYO") || message.includes("Missing BYO") ? 400 : 500;
return NextResponse.json({ error: message }, { status });
}
}
-1
View File
@@ -26,7 +26,6 @@ export async function POST(req: Request) {
try {
const base = loadEngineConfig();
// See StartRequest.clientTts — BYO clients synth in-browser, so drop server TTS.
const config = body.clientTts === true ? { ...base, tts: undefined } : base;
const result = await requestInsertBeat(config, body);
return NextResponse.json({
+43
View File
@@ -0,0 +1,43 @@
import { proxyLLM, type ProxyLLMParams } from "@/lib/byoProxy";
import { NextResponse } from "next/server";
import { requireUser } from "@/lib/supabase/guard";
export const runtime = "nodejs";
export async function POST(req: Request): Promise<Response> {
const auth = await requireUser();
if (auth instanceof NextResponse) return auth;
let parsed: Partial<ProxyLLMParams>;
try {
parsed = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
// Validate required fields
const { provider, apiKey, baseUrl, body } = parsed;
if (!provider || !apiKey || !baseUrl || !body) {
return NextResponse.json(
{ error: "Missing required fields: provider, apiKey, baseUrl, body" },
{ status: 400 },
);
}
// Validate provider
if (!["openai", "claude", "gemini"].includes(provider)) {
return NextResponse.json(
{ error: `Unsupported provider: ${provider}` },
{ status: 400 },
);
}
// Forward to proxy core
return proxyLLM({
provider: provider as "openai" | "claude" | "gemini",
apiKey,
baseUrl,
body,
model: parsed.model,
stream: parsed.stream,
});
}
+55 -6
View File
@@ -1,5 +1,5 @@
import { requestScene } from "@infiplot/engine";
import type { Character, SceneRequest } from "@infiplot/types";
import type { Character, SceneRequest, SceneStreamEvent } from "@infiplot/types";
import { NextResponse } from "next/server";
import { loadEngineConfig } from "@/lib/config";
import { requireUser } from "@/lib/supabase/guard";
@@ -13,6 +13,10 @@ function stripKnownVoices(
);
}
function formatSSE(event: SceneStreamEvent | { type: string; [k: string]: unknown }): string {
return `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`;
}
export const runtime = "nodejs";
export async function POST(req: Request) {
@@ -30,17 +34,62 @@ export async function POST(req: Request) {
return NextResponse.json({ error: "session is required" }, { status: 400 });
}
const acceptsSSE = req.headers.get("accept")?.includes("text/event-stream");
try {
const base = loadEngineConfig();
// See StartRequest.clientTts — BYO clients synth in-browser, so drop server TTS.
const config = body.clientTts === true ? { ...base, tts: undefined } : base;
const result = await requestScene(config, body);
if (!acceptsSSE) {
const result = await requestScene(config, body);
const knownNames = new Set(
(body.session.characters ?? []).map((c) => c.name),
);
return NextResponse.json({
...result,
characters: stripKnownVoices(result.characters, knownNames),
});
}
const encoder = new TextEncoder();
const knownNames = new Set(
(body.session.characters ?? []).map((c) => c.name),
);
return NextResponse.json({
...result,
characters: stripKnownVoices(result.characters, knownNames),
const stream = new ReadableStream({
async start(controller) {
try {
const result = await requestScene(config, body, (event) => {
controller.enqueue(encoder.encode(formatSSE(event)));
});
controller.enqueue(
encoder.encode(
formatSSE({
type: "done",
response: {
...result,
characters: stripKnownVoices(result.characters, knownNames),
},
}),
),
);
controller.close();
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
controller.enqueue(
encoder.encode(formatSSE({ type: "error", message })),
);
controller.close();
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
},
});
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
+43 -6
View File
@@ -1,9 +1,13 @@
import { startSession } from "@infiplot/engine";
import type { StartRequest } from "@infiplot/types";
import type { SceneStreamEvent, StartRequest } from "@infiplot/types";
import { NextResponse } from "next/server";
import { loadEngineConfig } from "@/lib/config";
import { requireUser } from "@/lib/supabase/guard";
function formatSSE(event: SceneStreamEvent | { type: string; [k: string]: unknown }): string {
return `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`;
}
export const runtime = "nodejs";
// Matches /api/vision and /api/parse-style-image — the user's resized 512px
@@ -43,14 +47,47 @@ export async function POST(req: Request) {
}
}
const acceptsSSE = req.headers.get("accept")?.includes("text/event-stream");
try {
const base = loadEngineConfig();
// BYO key: the browser provisions + synths voices directly against Xiaomi
// (key never reaches us), so strip server-side TTS so the engine skips all
// provisioning + synth. See StartRequest.clientTts.
const config = body.clientTts === true ? { ...base, tts: undefined } : base;
const result = await startSession(config, body);
return NextResponse.json(result);
if (!acceptsSSE) {
const result = await startSession(config, body);
return NextResponse.json(result);
}
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
try {
const result = await startSession(config, body, (event) => {
controller.enqueue(encoder.encode(formatSSE(event)));
});
controller.enqueue(
encoder.encode(
formatSSE({ type: "done", response: result }),
),
);
controller.close();
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
controller.enqueue(
encoder.encode(formatSSE({ type: "error", message })),
);
controller.close();
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
},
});
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
return NextResponse.json({ error: message }, { status: 500 });
+31
View File
@@ -0,0 +1,31 @@
import { NextResponse } from "next/server";
export const runtime = "nodejs";
/**
* GET/DELETE /api/stories/[id] — TEMPORARILY DISABLED (2026-06-09)
*
* D1 persistence disabled until authentication integration.
* Returns 404 so client handles gracefully (localStorage is the source of truth).
*
* To re-enable: Restore original implementation after auth integration.
*/
export async function GET(
_req: Request,
_context: { params: Promise<{ id: string }> },
) {
return NextResponse.json(
{ error: "Server persistence temporarily disabled" },
{ status: 404 },
);
}
export async function DELETE(
_req: Request,
_context: { params: Promise<{ id: string }> },
) {
return NextResponse.json(
{ error: "Server persistence temporarily disabled" },
{ status: 404 },
);
}
+48
View File
@@ -0,0 +1,48 @@
import { NextResponse } from "next/server";
import { getDb } from "@/lib/db/client";
import { FeaturedRepository } from "@/lib/db/repositories/featuredRepo";
export const runtime = "nodejs";
/**
* GET /api/stories/featured?gender=male
*
* List active featured stories for homepage display.
* Fallback: D1 query fails → return empty array (homepage shows no cards, gracefully degrades).
*
* Query Params:
* gender: "male" | "female" (required)
*
* Response: { stories: FeaturedStory[] }
* Errors: 400 (invalid gender), 500 (should not reach user - caught and degraded)
*/
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const genderParam = searchParams.get("gender");
// Validate gender
if (!genderParam || !["male", "female"].includes(genderParam)) {
return NextResponse.json(
{ error: "gender query parameter must be 'male' or 'female'" },
{ status: 400 },
);
}
const gender = genderParam as "male" | "female";
try {
const db = getDb();
const repo = new FeaturedRepository(db);
const stories = await repo.listByGender(gender);
return NextResponse.json({ stories });
} catch (err) {
// D1 unavailable or query failed - degrade to empty array
// (homepage will show no cards but remain functional)
const message = err instanceof Error ? err.message : "Unknown error";
console.error("[stories/featured] D1 query failed, returning empty array:", message);
return NextResponse.json({ stories: [] });
}
}
+15
View File
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server";
export const runtime = "nodejs";
/**
* GET /api/stories/list — TEMPORARILY DISABLED (2026-06-09)
*
* D1 persistence disabled until authentication integration.
* Returns empty list so client falls back to localStorage-only mode.
*
* To re-enable: Restore original implementation after auth integration.
*/
export async function GET(_req: Request) {
return NextResponse.json({ stories: [] });
}
+27
View File
@@ -0,0 +1,27 @@
import { NextResponse } from "next/server";
export const runtime = "nodejs";
/**
* POST /api/stories/save — TEMPORARILY DISABLED (2026-06-09)
*
* D1 persistence is disabled until an authentication system (better-auth) is
* integrated. Without auth, anonymous writes to D1 have no rate limiting,
* per-user quota, or ownership verification — an abuse/DoS risk on a public,
* registration-less site. The client (lib/clientStoryPersistence.ts) now
* persists stories to localStorage only; this 503 keeps the contract intact
* for any caller that still hits the endpoint.
*
* The full D1 implementation lives in StoryRepository (lib/db/repositories/
* storyRepo.ts), which is untouched. To re-enable after auth integration:
* restore the handler to validate input + call `repo.save(...)` (see the
* task-10 implementation log) and gate it behind an authenticated session.
*
* See: ARCHITECTURE_DESIGN.md Phase 2, memory tech_d1_anonymous_write_risk
*/
export async function POST(_req: Request) {
return NextResponse.json(
{ error: "Server persistence temporarily disabled - using local storage" },
{ status: 503 },
);
}
+5 -3
View File
@@ -1,7 +1,7 @@
import { visionDecide } from "@infiplot/engine";
import type { VisionRequest } from "@infiplot/types";
import { NextResponse } from "next/server";
import { loadEngineConfig } from "@/lib/config";
import { loadEngineConfig, buildByoEngineConfig } from "@/lib/config";
import { requireUser } from "@/lib/supabase/guard";
export const runtime = "nodejs";
@@ -45,11 +45,13 @@ export async function POST(req: Request) {
}
try {
const config = loadEngineConfig();
const official = loadEngineConfig();
const config = body.byo ? buildByoEngineConfig(body.byo, official) : official;
const result = await visionDecide(config, body);
return NextResponse.json(result);
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
return NextResponse.json({ error: message }, { status: 500 });
const status = message.includes("Invalid BYO") || message.includes("Missing BYO") ? 400 : 500;
return NextResponse.json({ error: message }, { status });
}
}