跳转到内容
EN

给老师做一个 AI 分身

一位老师说一句“帮我做一个我的 AI 分身,给学生用”,最后交付三样东西:

  • 一个手机打开就能聊的分身页;
  • 学生扫码输入口令和名字就能进,不用注册;
  • 老师自己的管理页:链接、二维码、口令、谁进来了、停用某个人。

对话界面就是 Praxis Kit,不另写聊天界面。其余部分是一个普通的 Praxis 应用。

网站客服、文档问答、获客、社群等其他场景,用同一套代码,只换四样东西:场景、呈现形态、进入方式和 AI 风格(见文末)。

成品

部分学生或老师看到什么
/全屏对话:老师的名字和一句介绍、开场白、4 个推荐问题、输入框
/join输入口令和名字,点“进入”,这台设备会记住 30 天
/j/<链接>名单模式下每人一个专属链接,点开直接进
/admin/entrance老师的入口与分享页:链接、二维码、口令(可以换)、可直接转发的一句话、已进入的人(可停用;名单模式下可重新生成某人的链接)

前提

  • 能用 praxis CLI 的环境,版本 0.5.0 或更高(praxis.jsonc 要支持 "platform": true),以及 Bun。
  • 一个服务智能体:praxis.agent.agents.create,kind: "service",model: "deepseek-flash",system 按下面的骨架写。
  • 老师的资料:放进知识库的资料库(praxis.knowledge.vectorStores),并以 vector_store 绑定给智能体,access 设为 read_only。见配置智能体。

指令骨架(换成老师自己的内容):

你是 Yoko 老师的 AI 分身,服务她英语写作课的学生。你帮学生改作文、讲写作方法。
说话方式:耐心、鼓励,像一位温和的老师。不直接给出整篇答案,先问学生的想法,再一步步提示。
回答写作问题前先在资料库里搜索;资料里没有的,直接说资料里没有。
你不做:代写整篇作文、回答与英语写作无关的问题。
遇到答不了或需要 Yoko 老师本人判断的问题:请学生直接问 Yoko 老师。
回答简短,适合在手机上读。

步骤

  1. praxis app create <name>,把下面完整代码里的文件加进项目,在 wrangler.jsonc 的 vars 里填 AGENT_ID,ENTRANCE_MODE 设为 passcode。
  2. bun add qrcode@1.5.4 && bun add -d @types/qrcode@1.5.5。在 app/layout.tsx 里设 <html lang="zh-CN">,顶栏站名改成分身的名字,导航改成中文,并在管理入口旁加一个“入口与分享”(/admin/entrance)的链接。
  3. bun run typecheck && bun run build,然后 praxis app publish。记下输出里的 url。
  4. 把这个 URL 的来源加进智能体的嵌入设置:先用 praxis.agent.agents.retrieveEmbedPolicy({ path: { agent_id } }) 读出当前的 allowed_origins,加上新来源,再用 praxis.agent.agents.updateEmbedPolicy({ path: { agent_id }, body: { allowed_origins } }) 整个写回。见嵌入设置。
  5. 立刻在 /register 注册老师的管理员账户(第一个注册的账户就是管理员),然后打开 /admin/entrance 读出口令。

完整代码

以下文件接在 praxis app create 生成的模板之上,模板已自带登录、数据库和 lib/auth.ts。

praxis.jsonc(保留 praxis app create 生成的 name,只加 platform):

{
"$schema": "https://deepraxis.com/schemas/praxis.json",
"kind": "application",
"name": "<app-name>",
"secrets": { "SESSION_SECRET": "generate" },
"healthcheck": "/api/health",
"platform": true
}

在 wrangler.jsonc 的 bindings 之后加:

"vars": {
"PRAXIS_API_URL": "https://api.deepraxis.com",
"AGENT_ID": "agent_REPLACE_ME",
"ENTRANCE_MODE": "passcode",
"PUBLISHABLE_KEY": ""
}

env.d.ts

// Types of the bindings declared in wrangler.jsonc and the secrets declared in praxis.jsonc.
// Read them with `import { env } from "cloudflare:workers"`; add a line here for every new one.
declare namespace Cloudflare {
interface Env {
DB: D1Database;
IMAGES: R2Bucket;
ASSETS: Fetcher;
/** Signs session cookies; created by `praxis app publish` ("generate" in praxis.jsonc). */
SESSION_SECRET?: string;
/** Publish Agent: the Praxis API this app was deployed to (https://api.deepraxis.com). */
PRAXIS_API_URL: string;
/** The service agent people chat with (agent_…). */
AGENT_ID: string;
/** open | passcode | list */
ENTRANCE_MODE: string;
/** Open mode only: the publishable key (public by design). */
PUBLISHABLE_KEY?: string;
}
}

migrations/0002_entrance.sql

-- Publish Agent entrance: who may chat, without accounts of their own.
CREATE TABLE IF NOT EXISTS entrance_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
-- A member is a users row (role 'user', unusable password) plus the name people typed or the owner gave.
CREATE TABLE IF NOT EXISTS members (
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
link_hash TEXT UNIQUE,
disabled INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);

在 lib/migrations.ts 里引入 m0002 from "../migrations/0002_entrance.sql?raw",并追加 { name: "0002_entrance", sql: m0002 };在 lib/schema.ts 末尾追加:

export const entranceSettings = sqliteTable("entrance_settings", {
key: text("key").primaryKey(),
value: text("value").notNull(),
});
export const members = sqliteTable("members", {
userId: text("user_id").primaryKey(),
name: text("name").notNull(),
linkHash: text("link_hash").unique(),
disabled: integer("disabled").notNull().default(0),
createdAt: integer("created_at").notNull(),
});

lib/entrance.ts

// Publish Agent entrance: who may chat, and the Kit grant code for them. Members never register; they are a users
// row with an unusable password, signed in with the template's own session cookie.
import { env } from "cloudflare:workers";
import { and, eq } from "drizzle-orm";
import { hashPassword, newSessionToken, sha256Hex } from "./auth";
import type { Db } from "./db";
import { entranceSettings, members } from "./schema";
import { createUser, type User } from "./users";
export type EntranceMode = "open" | "passcode" | "list";
export const entranceMode = (): EntranceMode =>
env.ENTRANCE_MODE === "open" || env.ENTRANCE_MODE === "list" ? env.ENTRANCE_MODE : "passcode";
/** A six-digit passcode; easy to say aloud in a class or a group chat. */
export const newPasscode = () => String(100000 + (crypto.getRandomValues(new Uint32Array(1))[0]! % 900000));
export async function getPasscode(db: Db): Promise<string> {
const [row] = await db.select().from(entranceSettings).where(eq(entranceSettings.key, "passcode")).limit(1);
if (row) return row.value;
const passcode = newPasscode();
await db.insert(entranceSettings).values({ key: "passcode", value: passcode }).onConflictDoNothing();
return (await db.select().from(entranceSettings).where(eq(entranceSettings.key, "passcode")).limit(1))[0]!.value;
}
export async function setPasscode(db: Db, passcode: string) {
await db.insert(entranceSettings).values({ key: "passcode", value: passcode })
.onConflictDoUpdate({ target: entranceSettings.key, set: { value: passcode } });
}
/** A member account: a random username and a password nobody knows, so it can only be entered through the entrance. */
async function createMember(db: Db, name: string, linkHash: string | null): Promise<User> {
const created = await createUser(db, { username: `m_${newSessionToken().slice(0, 12).toLowerCase().replace(/[^a-z0-9]/g, "0")}`, passwordHash: await hashPassword(newSessionToken()) });
if (!created.ok) throw new Error("member username collision; try again");
await db.insert(members).values({ userId: created.user.id, name, linkHash, createdAt: Date.now() });
return created.user;
}
export const nameSchemaMax = 20;
export const cleanName = (value: unknown) => typeof value === "string" ? value.trim().slice(0, nameSchemaMax) : "";
/** Passcode mode: anyone who knows the passcode joins once with a name. */
export async function joinWithPasscode(db: Db, name: string, passcode: string): Promise<User | "wrong-passcode"> {
if (passcode.trim() !== await getPasscode(db)) return "wrong-passcode";
return createMember(db, name, null);
}
/** List mode: the owner adds a person and gets their personal link token (shown once; only its hash is stored). */
export async function addListMember(db: Db, name: string): Promise<{ user: User; token: string }> {
const token = newSessionToken();
return { user: await createMember(db, name, await sha256Hex(token)), token };
}
/** The member a personal link names, unless disabled. */
export async function memberByLink(db: Db, token: string) {
const [row] = await db.select().from(members).where(and(eq(members.linkHash, await sha256Hex(token)), eq(members.disabled, 0))).limit(1);
return row ?? null;
}
/** Who may chat: an enabled member, or the admin (the owner trying it out). */
export async function chatterOf(db: Db, user: User | null): Promise<{ id: string; name: string } | null> {
if (!user) return null;
if (user.role === "admin") return { id: user.id, name: user.username };
const [row] = await db.select().from(members).where(eq(members.userId, user.id)).limit(1);
return row && row.disabled === 0 ? { id: user.id, name: row.name } : null;
}
/** One single-use Kit grant code for this person, bound to this page's origin. Needs "platform": true in praxis.jsonc. */
export async function issueGrantCode(chatter: { id: string; name: string }, origin: string): Promise<string> {
const response = await fetch(`${env.PRAXIS_API_URL}/customer/v1/grant_codes`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
customer_id: `member_${chatter.id}`,
metadata: { name: chatter.name },
resources: [`agent:${env.AGENT_ID}:chat`],
origin,
}),
});
if (!response.ok) throw new Error(`grant code failed: HTTP ${response.status} ${(await response.text()).slice(0, 300)}`);
const body = await response.json() as { code?: string };
if (!body.code) throw new Error("grant code response has no code");
return body.code;
}
/** Ends every Kit sign-in of this person at once (used when the owner disables someone). */
export async function revokeChatSignIns(userId: string): Promise<void> {
const response = await fetch(`${env.PRAXIS_API_URL}/customer/v1/customers/${encodeURIComponent(`member_${userId}`)}/revoke_tokens`, { method: "POST" });
// 404: the person never opened the chat, so there is nothing to end.
if (!response.ok && response.status !== 404) throw new Error(`revoke failed: HTTP ${response.status}`);
}
/** List mode: a new personal link for one person; the old link stops working at once. Returns the new token. */
export async function regenerateLink(db: Db, userId: string): Promise<string> {
const token = newSessionToken();
await db.update(members).set({ linkHash: await sha256Hex(token) }).where(eq(members.userId, userId));
return token;
}

lib/chat-options.ts

// Kit options of this entrance (see the Kit component reference): who the agent is, its look and its start screen.
// Change the agent's look only here; never restyle the Kit's internals.
export const CHAT_OPTIONS = {
agent: { name: "Yoko 老师的 AI 分身" /* , avatar: "https://…" only when the owner gives a picture */ },
layout: "inline",
header: { title: "Yoko 老师的 AI 分身", subtitle: "基于 Yoko 老师的讲义与答疑" },
startScreen: {
greeting: "嗨,我是 Yoko 的 AI 分身。我不会直接给你答案,会陪你一步步把作文改好。",
prompts: [
{ label: "这篇作文的结构哪里有问题?", prompt: "这篇作文的结构哪里有问题?" },
{ label: "帮我检查语法错误", prompt: "帮我检查语法错误" },
{ label: "怎么写一个好的开头?", prompt: "怎么写一个好的开头?" },
{ label: "考前怎么复习写作?", prompt: "考前怎么复习写作?" },
],
},
composer: { placeholder: "问 Yoko 的分身…" },
footer: "AI 生成内容仅供参考 · 拿不准的问题请找 Yoko 老师本人",
theme: { accent: "#1F6F66", grayscale: "warm", radius: "lg" },
locale: "zh",
};

components/kit-chat.tsx

// The chat is the Praxis Kit (<praxis-agent>), loaded from the Praxis CDN. Nothing here restyles the Kit: change its
// look through `options` (theme, header, startScreen, composer, footer). Server component: it renders the element and
// one module script; the page signs in once with configure(), the element takes its identity from that sign-in.
import { env } from "cloudflare:workers";
/** Kit options (see the Kit component reference). `agent` is filled in from AGENT_ID. */
export type KitOptions = Record<string, unknown>;
const cdnOf = (_apiUrl: string) => "https://cdn.deepraxis.com";
/** JSON inside an inline script: escape "<" so a value can never close the script tag. */
const inline = (value: unknown) => JSON.stringify(value).replace(/</g, "\\u003c");
export function KitChat({ options, credential, className = "", height = "100%" }: {
options: KitOptions;
/** "grant": the page asks /api/praxis-grant-code (members, list, the owner's login); "open": the publishable key. */
credential: "grant" | "open";
className?: string;
height?: string;
}) {
const api = env.PRAXIS_API_URL;
const cdn = cdnOf(api);
const script = `
import { configure } from "${cdn}/v1/praxis-session.js";
const api = ${inline(api)};
const credential = ${inline(credential)};
const options = ${inline({ ...options, agent: { ...(options.agent as object ?? {}), id: env.AGENT_ID } })};
async function signIn() {
if (credential === "open") { configure({ api: { url: api, publishableKey: ${inline(env.PUBLISHABLE_KEY ?? "")} } }); return; }
const response = await fetch("/api/praxis-grant-code", { method: "POST", credentials: "same-origin", cache: "no-store" });
if (response.status === 401) { location.href = "/join"; return; }
if (!response.ok) throw new Error("grant code " + response.status);
configure({ api: { url: api, grantCode: (await response.json()).code } });
}
await signIn();
await import("${cdn}/v1/praxis-kit.js");
await customElements.whenDefined("praxis-agent");
const element = document.querySelector("praxis-agent");
element.setOptions(options);
// A sign-in that ended (expired, revoked) is renewed with a fresh grant code; the conversation history stays.
element.addEventListener("praxis.session.end", () => { signIn().catch(() => {}); });
element.addEventListener("praxis.error", () => { document.querySelector("#chat-status").textContent = "对话暂时不可用,请稍后刷新重试。"; });
`;
return (
<div className={className} style={{ height }}>
<div style={{ height: "100%" }} dangerouslySetInnerHTML={{ __html: `<praxis-agent style="display:block;height:100%;width:100%"></praxis-agent>` }} />
<p id="chat-status" role="status" className="sr-only" />
<script type="module" dangerouslySetInnerHTML={{ __html: script }} />
</div>
);
}

app/page.tsx

// The entrance: a full-page chat. Members (or the owner) only, unless ENTRANCE_MODE is open.
import { redirect } from "next/navigation";
import { KitChat } from "@/components/kit-chat";
import { getDb } from "@/lib/db";
import { chatterOf, entranceMode } from "@/lib/entrance";
import { getCurrentUser } from "@/lib/guard";
import { CHAT_OPTIONS } from "@/lib/chat-options";
export const dynamic = "force-dynamic";
export default async function Home() {
const open = entranceMode() === "open";
if (!open && !(await chatterOf(await getDb(), await getCurrentUser()))) redirect("/join");
// fixed + inset-0 covers the template's header and container: the chat owns the whole screen. On a wide screen the
// conversation stays a readable column (max-w-3xl) instead of stretching edge to edge; the Kit itself is untouched.
return (
<div className="fixed inset-0 z-50 flex justify-center bg-background">
<KitChat className="h-full w-full max-w-3xl" options={CHAT_OPTIONS} credential={open ? "open" : "grant"} />
</div>
);
}

app/join/page.tsx

// How people get in without an account: the passcode and a name (passcode mode). List mode uses personal links (/j/…).
import { redirect } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { getDb } from "@/lib/db";
import { chatterOf, entranceMode } from "@/lib/entrance";
import { getCurrentUser } from "@/lib/guard";
import { CHAT_OPTIONS } from "@/lib/chat-options";
export const dynamic = "force-dynamic";
const ERRORS: Record<string, string> = { passcode: "口令不对,请向发给你链接的人确认。", name: "请填写你的名字(最多 20 个字)。" };
export default async function Join({ searchParams }: { searchParams: Promise<{ error?: string; name?: string }> }) {
const mode = entranceMode();
if (mode === "open" || await chatterOf(await getDb(), await getCurrentUser())) redirect("/");
const { error, name } = await searchParams;
const title = CHAT_OPTIONS.header.title;
return (
<div className="fixed inset-0 z-50 overflow-y-auto bg-background">
<div className="mx-auto flex min-h-full max-w-sm flex-col justify-center gap-8 px-6 py-12">
<div className="flex flex-col items-center gap-3 text-center">
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-accent text-3xl font-semibold text-primary">{title.slice(0, 1)}</div>
<h1 className="text-xl font-semibold">{title}</h1>
<p className="text-sm text-muted-foreground">{CHAT_OPTIONS.header.subtitle}</p>
</div>
{mode === "list" ? (
<p className="text-center text-sm text-muted-foreground">请使用发给你的专属链接或二维码进入。</p>
) : (
<form action="/api/entrance/join" method="post" className="flex flex-col gap-5">
<div className="flex flex-col gap-2">
<Label htmlFor="passcode">口令</Label>
<Input id="passcode" name="passcode" inputMode="numeric" autoComplete="off" placeholder="请输入 6 位口令" required />
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="name">你的名字</Label>
<Input id="name" name="name" maxLength={20} defaultValue={name ?? ""} placeholder="怎么称呼你" required />
</div>
{error && ERRORS[error] && <p role="alert" className="text-sm text-destructive">{ERRORS[error]}</p>}
<Button type="submit" className="w-full">进入</Button>
<p className="text-center text-xs text-muted-foreground">不用注册。下次打开会记住你。</p>
</form>
)}
</div>
</div>
);
}

app/api/entrance/join/route.ts

import { env } from "cloudflare:workers";
import { MissingSecretError, requireSecret } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { cleanName, entranceMode, joinWithPasscode } from "@/lib/entrance";
import { redirectResponse } from "@/lib/guard";
import { createSession, sessionCookie } from "@/lib/session";
// Passcode mode only. A wrong passcode costs nothing but a retry; rate limiting per IP would go here.
export async function POST(req: Request) {
try {
requireSecret(env.SESSION_SECRET);
if (entranceMode() !== "passcode") return redirectResponse("/join");
const form = await req.formData();
const name = cleanName(form.get("name"));
if (!name) return redirectResponse("/join?error=name");
const db = await getDb();
const member = await joinWithPasscode(db, name, String(form.get("passcode") ?? ""));
if (member === "wrong-passcode") return redirectResponse(`/join?error=passcode&name=${encodeURIComponent(name)}`);
const session = await createSession(db, member.id, env.SESSION_SECRET);
return redirectResponse("/", sessionCookie(session.value, session.expiresAt));
} catch (e) {
if (e instanceof MissingSecretError) return new Response(e.message, { status: 500 });
throw e;
}
}

app/j/[token]/route.ts

// List mode: a personal link signs its person in and opens the chat.
import { env } from "cloudflare:workers";
import { getDb } from "@/lib/db";
import { memberByLink } from "@/lib/entrance";
import { redirectResponse } from "@/lib/guard";
import { createSession, sessionCookie } from "@/lib/session";
export async function GET(_req: Request, { params }: { params: Promise<{ token: string }> }) {
const db = await getDb();
const member = await memberByLink(db, (await params).token);
if (!member) return new Response("这个链接已失效,请联系发给你链接的人。", { status: 404, headers: { "Content-Type": "text/plain; charset=utf-8" } });
const session = await createSession(db, member.userId, env.SESSION_SECRET);
return redirectResponse("/", sessionCookie(session.value, session.expiresAt));
}

app/api/praxis-grant-code/route.ts

// The Kit asks here for a single-use grant code for the signed-in member (or the owner). Never cache a code.
import { getDb } from "@/lib/db";
import { chatterOf, issueGrantCode } from "@/lib/entrance";
import { getCurrentUser } from "@/lib/guard";
export async function POST(req: Request) {
const chatter = await chatterOf(await getDb(), await getCurrentUser(req.headers.get("cookie")));
if (!chatter) return Response.json({ error: "not signed in" }, { status: 401 });
const code = await issueGrantCode(chatter, new URL(req.url).origin);
return Response.json({ code }, { headers: { "Cache-Control": "no-store" } });
}

app/admin/entrance/page.tsx

// The owner's entrance page: the link and QR code to share, the passcode, and who has joined.
import { desc, eq } from "drizzle-orm";
import { headers } from "next/headers";
import QRCode from "qrcode";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { getDb } from "@/lib/db";
import { entranceMode, getPasscode } from "@/lib/entrance";
import { formatDateTime } from "@/lib/format";
import { requireAdmin } from "@/lib/guard";
import { members } from "@/lib/schema";
export const dynamic = "force-dynamic";
export default async function EntranceAdmin({ searchParams }: { searchParams: Promise<{ link?: string; name?: string }> }) {
await requireAdmin("/admin/entrance");
const db = await getDb();
const mode = entranceMode();
const h = await headers();
const origin = `https://${h.get("host")}`;
const [passcode, people] = await Promise.all([
mode === "passcode" ? getPasscode(db) : Promise.resolve(null),
db.select().from(members).orderBy(desc(members.createdAt)),
]);
const qr = await QRCode.toString(origin, { type: "svg", margin: 1, width: 160 });
const { link, name } = await searchParams;
const share = mode === "passcode" ? `扫码或打开 ${origin} ,输入口令 ${passcode} 就能开始问。` : mode === "open" ? `打开 ${origin} 就能开始问。` : "";
return (
<div className="space-y-6">
<Card>
<CardHeader><CardTitle>分享给使用的人</CardTitle></CardHeader>
<CardContent className="flex flex-col gap-6 sm:flex-row sm:items-start">
<div className="flex h-44 w-44 shrink-0 items-center justify-center rounded-lg border border-border bg-white [&>svg]:h-40 [&>svg]:w-40" role="img" aria-label="入口二维码" dangerouslySetInnerHTML={{ __html: qr }} />
<div className="flex min-w-0 flex-col gap-3 text-sm">
<p className="break-all"><span className="text-muted-foreground">链接:</span>{origin}</p>
{passcode && (
<div className="flex flex-wrap items-center gap-3">
<span className="text-muted-foreground">口令:</span>
<span className="font-mono text-2xl tracking-widest">{passcode}</span>
<form action="/api/entrance/admin" method="post"><input type="hidden" name="action" value="rotate" /><Button variant="outline" size="sm">换口令</Button></form>
</div>
)}
{share && <p className="rounded-md bg-accent px-3 py-2 text-accent-foreground">可以直接转发:{share}</p>}
{passcode && <p className="text-muted-foreground">换口令后,新来的人要用新口令;已经进来的人不受影响。</p>}
</div>
</CardContent>
</Card>
{mode === "list" && (
<Card>
<CardHeader><CardTitle>添加成员</CardTitle></CardHeader>
<CardContent className="space-y-3">
<form action="/api/entrance/admin" method="post" className="flex gap-3">
<input type="hidden" name="action" value="add" />
<Input name="name" maxLength={20} placeholder="成员名字" required />
<Button type="submit">生成专属链接</Button>
</form>
{link && <p className="break-all rounded-md bg-accent px-3 py-2 text-sm text-accent-foreground">{name} 的专属链接(只显示这一次,请现在发给 TA;旧链接已失效):{origin}/j/{link}</p>}
</CardContent>
</Card>
)}
<Card>
<CardHeader><CardTitle>已进入的人({people.length})</CardTitle></CardHeader>
<CardContent>
{people.length === 0 ? <p className="text-sm text-muted-foreground">还没有人进入。把上面的链接或二维码发出去吧。</p> : (
// A list, not a table: it reads on a 390 px phone and on a laptop alike.
<ul className="divide-y divide-border">
{people.map(p => (
<li key={p.userId} className="flex flex-wrap items-center gap-x-4 gap-y-2 py-3">
<div className="min-w-0 flex-1">
<p className="font-medium">{p.name}</p>
<p className="text-xs text-muted-foreground">{formatDateTime(p.createdAt)} 进入</p>
</div>
<Badge variant={p.disabled ? "secondary" : "default"}>{p.disabled ? "已停用" : "可使用"}</Badge>
<div className="flex gap-1">
{mode === "list" && !p.disabled && (
<form action="/api/entrance/admin" method="post"><input type="hidden" name="action" value="relink" /><input type="hidden" name="user" value={p.userId} /><Button variant="ghost" size="sm">重新生成链接</Button></form>
)}
<form action="/api/entrance/admin" method="post"><input type="hidden" name="action" value={p.disabled ? "enable" : "disable"} /><input type="hidden" name="user" value={p.userId} /><Button variant="ghost" size="sm">{p.disabled ? "恢复" : "停用"}</Button></form>
</div>
</li>
))}
</ul>
)}
<p className="mt-4 text-xs text-muted-foreground">每个人问了什么:在 Praxis 控制台 → 服务智能体 → 这个智能体 → 会话里查看。</p>
</CardContent>
</Card>
</div>
);
}

app/api/entrance/admin/route.ts

import { eq } from "drizzle-orm";
import { getDb } from "@/lib/db";
import { addListMember, cleanName, newPasscode, regenerateLink, revokeChatSignIns, setPasscode } from "@/lib/entrance";
import { getCurrentUser, redirectResponse } from "@/lib/guard";
import { members, sessions } from "@/lib/schema";
export async function POST(req: Request) {
const user = await getCurrentUser(req.headers.get("cookie"));
if (user?.role !== "admin") return redirectResponse("/login?next=/admin/entrance");
const form = await req.formData();
const db = await getDb();
const action = form.get("action");
if (action === "rotate") await setPasscode(db, newPasscode());
if (action === "add") {
const name = cleanName(form.get("name"));
if (!name) return redirectResponse("/admin/entrance");
const { token } = await addListMember(db, name);
return redirectResponse(`/admin/entrance?link=${encodeURIComponent(token)}&name=${encodeURIComponent(name)}`);
}
if (action === "relink") {
const id = String(form.get("user") ?? "");
const [person] = await db.select().from(members).where(eq(members.userId, id)).limit(1);
if (!person) return redirectResponse("/admin/entrance");
const token = await regenerateLink(db, id);
return redirectResponse(`/admin/entrance?link=${encodeURIComponent(token)}&name=${encodeURIComponent(person.name)}`);
}
if (action === "disable" || action === "enable") {
const id = String(form.get("user") ?? "");
await db.update(members).set({ disabled: action === "disable" ? 1 : 0 }).where(eq(members.userId, id));
// Disabling signs the person out of this app and ends their chat sign-ins right away.
if (action === "disable") {
await db.delete(sessions).where(eq(sessions.userId, id));
await revokeChatSignIns(id);
}
}
return redirectResponse("/admin/entrance");
}

自动验证

终端窗口
U=<url>; A=$(mktemp); M=$(mktemp)
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -c $A -d 'username=yoko&password=<强密码>' $U/api/auth/register # 303 /account
P=$(curl -s -b $A $U/admin/entrance | grep -oE 'tracking-widest">[0-9]{6}' | grep -oE '[0-9]{6}')
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -d "passcode=000000&name=test" $U/api/entrance/join # 303 /join?error=passcode
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -c $M -d "passcode=$P&name=test" $U/api/entrance/join # 303 /
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' $U/ # 307 /join
curl -s -b $M -X POST -H "Origin: $U" $U/api/praxis-grant-code # {"code":"cgc_…"}

然后在浏览器里,用 390 px 宽的手机视图用口令进入,问 3 个典型问题,对照资料核对答案;再在 1280 px 宽下看管理页。最后在管理页把测试成员停用。

失败分支

现象原因处理
对话显示不可用,报 ORIGIN_NOT_ALLOWED应用的来源不在嵌入设置里步骤 4
/api/praxis-grant-code 返回 500,日志里平台返回 401部署时没有带 "platform": true写进 praxis.jsonc 后重新部署
GRANT_CODE_INVALID授权码被重复使用或已过期每次打开页面都重新取码,不要缓存
回答不引用资料资料库没绑定、文件还在处理,或指令里没写先搜索检查“前提”一节
第一个进来的学生成了管理员部署后没有先注册老师的账户部署后立刻做步骤 5

换一个场景

只改四样,其余代码不变:

  • 场景与 AI 风格:改 system 和 lib/chat-options.ts 里的开场白与推荐问题。
  • 呈现形态:独立页就用这套代码。放进已有网站时,给一段 Kit 代码:layout 设为 popup 是悬浮球,sidebar 是侧边栏,inline 是页内嵌入,见组件参考。
  • 进入方式:谁拿到链接都能用、也不需要自己的页面时,不必建应用:打开智能体的分享开关,建一条分享链接(praxis.share.permissions.create,资源类型 agent),打开就是智能体自己的全页对话,同一浏览器回来是同一个访客,可随时撤销。要自己的页面时,ENTRANCE_MODE 设为 open(配一个可公开 key)、passcode 或 list。已有自己账户体系的网站,用自己的登录签发授权码,见网页嵌入指南。