diff --git a/README.md b/README.md index 5b18d2e..879f11a 100644 --- a/README.md +++ b/README.md @@ -97,11 +97,11 @@ MaaS 模型服务与应用开发 用户不需要分别购买和管理多个模型服务,也不需要为每个供应商单独开发接入逻辑,只需要把模亦灵枢的 Base URL、API Key 和模型名配置到自己的 AI 系统、开发工具或 SDK/HTTP 客户端中,即可开始调用多个类型的模型;对于 3D 生成等异步模型,还可以查询任务进度并获取生成结果。 -### 这一阶段的商业方向(待确认) +### 这一阶段的商业方向(内测规则已确认,正式计费后置) -第一阶段暂定以共享额度模型中转为产品形态,但以下商业规则尚未确定: +第一阶段暂定以共享额度模型中转为产品形态。内测阶段额度按人民币 `¥` 计价展示,可由管理员手动发放等值测试额度;支付、提现和退款后置。以下正式商业规则仍待确定: -- 第一版采用邀请码准入,管理员发放额度。 +- 第一版采用邀请码准入,管理员发放额度;Key 同时支持个人和工作区/项目归属。 - 控制台保留充值/套餐入口,但第一版不启用真实支付。 - 是否免费试用、试用额度如何发放。 - 预充值、套餐、按量消费或其他收费方式。 diff --git a/control-plane/README.md b/control-plane/README.md index 368df0a..529d430 100644 --- a/control-plane/README.md +++ b/control-plane/README.md @@ -38,6 +38,7 @@ pnpm dev - `GET /api/auth/me`:读取当前会话用户。 - `POST /api/auth/logout`:撤销当前会话。 - `GET /api/models`:读取当前可用的 Mock 模型和供应商目录。 +- `GET|POST /api/projects`:查看或创建当前用户拥有的工作区/项目。 - `GET|POST /api/keys`:查看或创建平台调用 Key;明文 Key 只在创建响应中返回一次。 - `POST /api/keys/:id/revoke`:撤销当前用户自己的平台 Key。 - `GET /v1/models`:使用 `Authorization: Bearer ` 查询可调用模型。 @@ -57,5 +58,6 @@ pnpm dev - 数据库仅保存密码哈希、邀请码摘要和会话摘要,不保存明文密码、明文邀请码或会话 Token。 - 生产环境必须设置随机的 `AUTH_PASSWORD_PEPPER`、强管理员密码和 HTTPS。 - 管理员接口由 Control Plane 服务端角色校验保护,隐藏前端菜单不构成权限控制。 -- D4 的 Mock Key、模型目录暂存于内存仓库;PostgreSQL 迁移已准备 `model_providers`、`model_catalog` 和 `platform_api_keys` 表,接真实持久化时复用同一接口。 +- D4 的 Mock Key、项目和模型目录暂存于内存仓库;PostgreSQL 迁移已准备 `model_providers`、`model_catalog`、`model_projects` 和 `platform_api_keys` 表,接真实持久化时复用同一接口。 +- 额度界面统一按人民币 `¥` 展示;内测额度由管理员手动发放,真实计量、扣费和账单在后续节点实现。 - 上游供应商密钥不进入模型目录或用户响应,后续由 Provider Adapter 通过环境变量/密钥管理服务读取。 diff --git a/control-plane/migrations/003_projects.sql b/control-plane/migrations/003_projects.sql new file mode 100644 index 0000000..960321a --- /dev/null +++ b/control-plane/migrations/003_projects.sql @@ -0,0 +1,13 @@ +CREATE TABLE IF NOT EXISTS model_projects ( + id varchar(64) PRIMARY KEY, + owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name varchar(80) NOT NULL, + description text NOT NULL DEFAULT '', + status varchar(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')), + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +ALTER TABLE platform_api_keys ADD COLUMN IF NOT EXISTS project_id varchar(64) REFERENCES model_projects(id) ON DELETE CASCADE; +CREATE INDEX IF NOT EXISTS model_projects_owner_user_id_idx ON model_projects(owner_user_id); +CREATE INDEX IF NOT EXISTS platform_api_keys_project_id_idx ON platform_api_keys(project_id); diff --git a/control-plane/src/catalog.ts b/control-plane/src/catalog.ts index b219387..5dd4eb8 100644 --- a/control-plane/src/catalog.ts +++ b/control-plane/src/catalog.ts @@ -37,6 +37,7 @@ export interface ModelRecord { export interface ApiKeyRecord { id: string userId: string + projectId?: string name: string keyPrefix: string keyHash: string @@ -50,6 +51,8 @@ export interface ApiKeyRecord { export interface PublicApiKey { id: string + scopeType: 'personal' | 'project' + projectId?: string name: string keyPrefix: string scopes: string[] @@ -61,6 +64,9 @@ export interface PublicApiKey { } export interface CatalogRepository { + listProjects(userId: string): Promise + findProjectById(id: string): Promise + createProject(project: ProjectRecord): Promise listProviders(includeDisabled?: boolean): Promise findProviderById(id: string): Promise createProvider(provider: ProviderRecord): Promise @@ -74,10 +80,21 @@ export interface CatalogRepository { touchApiKey(id: string, at: string): Promise } +export interface ProjectRecord { + id: string + ownerUserId: string + name: string + description: string + status: CatalogStatus + createdAt: string + updatedAt: string +} + export class MemoryCatalogRepository implements CatalogRepository { private readonly providers = new Map() private readonly models = new Map() private readonly apiKeys = new Map() + private readonly projects = new Map() constructor() { const now = new Date().toISOString() @@ -142,6 +159,21 @@ export class MemoryCatalogRepository implements CatalogRepository { .sort((left, right) => left.name.localeCompare(right.name)) } + async listProjects(userId: string) { + return [...this.projects.values()] + .filter((project) => project.ownerUserId === userId && project.status === 'active') + .sort((left, right) => right.createdAt.localeCompare(left.createdAt)) + } + + async findProjectById(id: string) { + return this.projects.get(id) + } + + async createProject(project: ProjectRecord) { + if (this.projects.has(project.id)) throw new CatalogError('PROJECT_EXISTS', '项目标识已存在', 409) + this.projects.set(project.id, project) + } + async findProviderById(id: string) { return this.providers.get(id) } @@ -262,7 +294,28 @@ export class CatalogService { return model } - async createApiKey(userId: string, input: { name?: string; scopes?: string[]; modelIds?: string[] }) { + async listProjects(userId: string) { + return this.repository.listProjects(userId) + } + + async createProject(userId: string, input: { name?: string; description?: string }) { + const name = input.name?.trim() || '' + if (!name || name.length > 80) throw new CatalogError('INVALID_PROJECT_NAME', '项目名称不能为空且不能超过 80 个字符') + const now = new Date().toISOString() + const project: ProjectRecord = { + id: `project_${randomUUID().replaceAll('-', '').slice(0, 20)}`, + ownerUserId: userId, + name, + description: input.description?.trim() || '', + status: 'active', + createdAt: now, + updatedAt: now, + } + await this.repository.createProject(project) + return project + } + + async createApiKey(userId: string, input: { name?: string; projectId?: string; scopes?: string[]; modelIds?: string[] }) { const name = input.name?.trim() || '默认开发 Key' if (name.length > 80) throw new CatalogError('INVALID_KEY_NAME', 'Key 名称不能超过 80 个字符') const scopes = [...new Set((input.scopes?.length ? input.scopes : ['invoke']).map((scope) => scope.trim()).filter(Boolean))] @@ -271,11 +324,16 @@ export class CatalogService { for (const modelId of modelIds) { if (!await this.repository.findModelById(modelId)) throw new CatalogError('MODEL_NOT_FOUND', `模型不存在:${modelId}`, 404) } + if (input.projectId) { + const project = await this.repository.findProjectById(input.projectId) + if (!project || project.ownerUserId !== userId || project.status !== 'active') throw new CatalogError('PROJECT_NOT_FOUND', '项目不存在或无权访问', 404) + } const plaintext = `sk-moyi-${randomBytes(24).toString('base64url')}` const now = new Date().toISOString() const record: ApiKeyRecord = { id: randomUUID(), userId, + ...(input.projectId ? { projectId: input.projectId } : {}), name, keyPrefix: plaintext.slice(0, 16), keyHash: hashSecret(plaintext), @@ -313,6 +371,8 @@ export class CatalogService { export function toPublicApiKey(key: ApiKeyRecord): PublicApiKey { return { id: key.id, + scopeType: key.projectId ? 'project' : 'personal', + ...(key.projectId ? { projectId: key.projectId } : {}), name: key.name, keyPrefix: key.keyPrefix, scopes: [...key.scopes], diff --git a/control-plane/src/server.ts b/control-plane/src/server.ts index a71d966..ac1def4 100644 --- a/control-plane/src/server.ts +++ b/control-plane/src/server.ts @@ -204,6 +204,23 @@ async function route(request: IncomingMessage, response: ServerResponse) { return } + if (method === 'GET' && path === '/api/projects') { + const user = await auth.requireUser(token) + send(response, 200, { projects: await catalog.listProjects(user.id) }) + return + } + + if (method === 'POST' && path === '/api/projects') { + const user = await auth.requireUser(token) + const body = await readJson(request) + const project = await catalog.createProject(user.id, { + name: stringValue(body.name), + ...(body.description ? { description: stringValue(body.description) } : {}), + }) + send(response, 201, { project }) + return + } + if (method === 'GET' && path === '/api/keys') { const user = await auth.requireUser(token) send(response, 200, { keys: await catalog.listApiKeys(user.id) }) @@ -215,6 +232,7 @@ async function route(request: IncomingMessage, response: ServerResponse) { const body = await readJson(request) const result = await catalog.createApiKey(user.id, { ...(body.name ? { name: stringValue(body.name) } : {}), + ...(body.projectId ? { projectId: stringValue(body.projectId) } : {}), ...(body.scopes !== undefined ? { scopes: stringArrayValue(body.scopes) } : {}), ...(body.modelIds !== undefined ? { modelIds: stringArrayValue(body.modelIds) } : {}), }) diff --git a/control-plane/tests/catalog.test.ts b/control-plane/tests/catalog.test.ts index a1a168a..3024a92 100644 --- a/control-plane/tests/catalog.test.ts +++ b/control-plane/tests/catalog.test.ts @@ -43,3 +43,18 @@ test('key model allowlist is enforced by the service', async () => { assert.equal(created.apiKey.modelIds[0], 'model-mock-text') assert.equal(created.apiKey.scopes.includes('invoke'), true) }) + +test('personal and project keys can coexist with project ownership checks', async () => { + const catalog = createCatalog() + const project = await catalog.createProject('user-1', { name: 'AI SoulMate 联调' }) + const personal = await catalog.createApiKey('user-1', { name: '个人调试' }) + const projectKey = await catalog.createApiKey('user-1', { name: '项目服务', projectId: project.id }) + + assert.equal(personal.apiKey.scopeType, 'personal') + assert.equal(projectKey.apiKey.scopeType, 'project') + assert.equal(projectKey.apiKey.projectId, project.id) + await assert.rejects( + catalog.createApiKey('user-2', { projectId: project.id }), + (error: unknown) => error instanceof Error && error.message === '项目不存在或无权访问', + ) +}) diff --git a/docs/01-product-definition-and-prototype.md b/docs/01-product-definition-and-prototype.md index b0cdb10..91a8773 100644 --- a/docs/01-product-definition-and-prototype.md +++ b/docs/01-product-definition-and-prototype.md @@ -78,7 +78,7 @@ | 平台准入 | 邀请码注册,未持有有效邀请码不能创建账户 | 可配置切换为公开注册、申请审核或混合模式 | | 账户注册 | 邀请码作为准入条件,注册时填写基础账号信息 | 预留手机号、邮箱、验证码、第三方登录和账号绑定能力 | | 邀请码管理 | 管理员创建、启用、停用并查看使用记录 | 预留有效期、使用次数、渠道、邀请人和活动规则 | -| 初始额度 | 管理员向用户或内部项目发放额度 | 后续接入试用额度、充值、套餐、优惠券和自动续费 | +| 初始额度 | 按人民币 `¥` 计价展示,管理员向用户或内部项目发放等值内测额度 | 后续接入试用额度、充值、套餐、优惠券和自动续费 | | 额度记录 | 每次管理员发放必须记录额度、原因、操作人、时间和可选有效期 | 后续与支付订单、退款、发票和对账关联 | | 充值入口 | 控制台保留按钮和页面位置,第一版显示“暂未开放”或申请入口 | 商业规则确定后启用真实支付和订单流程 | diff --git a/docs/05-information-readiness-checklist.md b/docs/05-information-readiness-checklist.md index a4c4ef8..8c7402c 100644 --- a/docs/05-information-readiness-checklist.md +++ b/docs/05-information-readiness-checklist.md @@ -20,7 +20,7 @@ | N-01 | 第一版目标用户 | 已确认:先服务模灵科技内部项目,再逐步邀请外部开发者 | | N-02 | 第一版模型范围 | 已确认:不是只做大语言模型,覆盖文本、图像、音频、视频、Embedding 和生成式 3D | | N-03 | 第一版准入 | 已确认:邀请码注册;手机号/邮箱公开注册只预留 | -| N-04 | 第一版额度 | 已确认:管理员发放;充值/套餐入口保留但暂不启用真实支付 | +| N-04 | 第一版额度 | 已确认:按人民币 `¥` 计价展示,管理员可发放等值内测额度;充值/套餐入口保留但暂不启用真实支付 | | N-05 | 登录与权限 | 已确认:用户端和管理端分权限;企业认证可后置 | | N-06 | 首个管理员账号 | 需要提供一个开发环境管理员账号,密码由你本地设置,不提交 Git | | N-07 | 首个接入验收方式 | 需要选择一种实际调用方式作为验收,例如标准 HTTP/SDK 接入;不绑定某个客户端品牌 | @@ -158,6 +158,7 @@ UAT 通过的标准不是“所有模型都接入”,而是首批约定模型 | 测试环境 | 使用现有服务器 | 先确认 Docker、端口、磁盘、数据库和备份条件 | | 首轮规模 | 4—5 人,3—4 个项目 | 作为测试容量假设,不作为生产承诺 | | 业务规则 | 邀请码、管理员额度、暂不支付、公开注册后置;支持用量/金额分配 | D4/D5 先做额度分配和用量记录,支付后置 | +| Key 归属 | 同时支持个人 Key 与工作区/项目 Key | 第一版项目 Key 先由项目所有者创建,成员协作和细粒度 RBAC 后置 | ### 凭证安全说明 diff --git a/docs/06-d4-integration-plan.md b/docs/06-d4-integration-plan.md index fff1e80..c5ba9b7 100644 --- a/docs/06-d4-integration-plan.md +++ b/docs/06-d4-integration-plan.md @@ -32,7 +32,8 @@ SDK 不直接暴露给 MOYI 用户。后续如果上游从 HTTP API 切换为 SD ## 三、D4 先做 Mock 的内容 -- MOYI Key 创建、只显示一次、停用和权限范围。 +- MOYI Key 创建、只显示一次、停用和权限范围;同时支持个人 Key 与工作区/项目 Key。 +- 额度按人民币 `¥` 计价展示,管理员可发放等值内测额度,支付、提现和退款后置。 - 模型目录:文本、代码、多模态、3D 类型和模型能力 Schema。 - 用户/项目/Key 到模型的访问权限。 - 供应商模型 ID 到统一模型 ID 的映射。 @@ -84,6 +85,7 @@ SDK 不直接暴露给 MOYI 用户。后续如果上游从 HTTP API 切换为 SD 当前 Control Plane 已提供一套可供前端控制台联调的内存 Mock: - `GET /api/models`:登录用户读取统一模型与供应商目录,目录中包含一个同步多模态模型和一个异步 3D 模型。 +- `GET|POST /api/projects`:用户查看或创建工作区/项目,项目 Key 与个人 Key 并列存在。 - `GET|POST /api/keys`:用户查看或创建 MOYI Key;明文只在创建响应返回一次,服务端只保存 SHA-256 摘要。 - `POST /api/keys/:id/revoke`:用户撤销自己的 Key。 - `GET /v1/models`:使用 `Authorization: Bearer ` 查询可调用模型。 diff --git a/prototype/src/services/catalog.ts b/prototype/src/services/catalog.ts new file mode 100644 index 0000000..0932cb9 --- /dev/null +++ b/prototype/src/services/catalog.ts @@ -0,0 +1,162 @@ +export type CatalogModelType = 'text' | 'code' | 'multimodal' | 'image' | 'audio' | 'video' | 'embedding' | '3d' +export type CatalogCallMode = 'sync' | 'stream' | 'async' + +export interface CatalogProvider { + id: string + code: string + name: string + protocol: 'openai-compatible' | 'http' | 'sdk' + status: 'active' | 'disabled' +} + +export interface CatalogModel { + id: string + providerId: string + publicName: string + upstreamModel: string + type: CatalogModelType + mode: CatalogCallMode + description: string + inputTypes: string[] + outputTypes: string[] + capabilities: Record + status: 'active' | 'disabled' +} + +export interface CatalogProject { + id: string + ownerUserId: string + name: string + description: string + status: 'active' | 'disabled' + createdAt: string +} + +export interface CatalogApiKey { + id: string + scopeType: 'personal' | 'project' + projectId?: string + name: string + keyPrefix: string + scopes: string[] + modelIds: string[] + status: 'active' | 'disabled' + createdAt: string + lastUsedAt?: string + revokedAt?: string +} + +export interface CreatedCatalogKey { + key: string + apiKey: CatalogApiKey +} + +export interface ChatCompletionResult { + id: string + model: string + choices: Array<{ message: { role: string; content: string }; finish_reason: string }> + usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number } +} + +export interface AsyncTaskResult { + id: string + model: string + status: 'queued' | 'running' | 'succeeded' + created_at: string + updated_at: string + result?: { format: string; url: string } +} + +export class CatalogApiError extends Error { + constructor(readonly status: number, message: string, readonly code?: string) { + super(message) + } +} + +class HttpCatalogClient { + constructor(private readonly baseUrl: string) {} + + async listModels() { + return this.request<{ providers: CatalogProvider[]; models: CatalogModel[] }>('/api/models') + } + + async listProjects() { + return this.request<{ projects: CatalogProject[] }>('/api/projects') + } + + async createProject(input: { name: string; description?: string }) { + return this.request<{ project: CatalogProject }>('/api/projects', { method: 'POST', body: JSON.stringify(input) }) + } + + async listKeys() { + return this.request<{ keys: CatalogApiKey[] }>('/api/keys') + } + + async createKey(input: { name: string; projectId?: string; scopes?: string[]; modelIds?: string[] }) { + return this.request('/api/keys', { method: 'POST', body: JSON.stringify(input) }) + } + + async revokeKey(id: string) { + await this.request(`/api/keys/${encodeURIComponent(id)}/revoke`, { method: 'POST' }) + } + + async chatCompletion(apiKey: string, input: { model: string; prompt: string }) { + return this.request('/v1/chat/completions', { + method: 'POST', + headers: { Authorization: `Bearer ${apiKey}` }, + body: JSON.stringify({ model: input.model, messages: [{ role: 'user', content: input.prompt }] }), + }) + } + + async create3dTask(apiKey: string, input: { model: string; prompt: string }) { + const payload = await this.request<{ task: AsyncTaskResult }>('/v1/3d/tasks', { + method: 'POST', + headers: { Authorization: `Bearer ${apiKey}` }, + body: JSON.stringify(input), + }) + return payload.task + } + + async getTask(apiKey: string, taskId: string) { + const payload = await this.request<{ task: AsyncTaskResult }>(`/v1/tasks/${encodeURIComponent(taskId)}`, { + headers: { Authorization: `Bearer ${apiKey}` }, + }) + return payload.task + } + + async listAdminModels() { + return this.request<{ models: CatalogModel[] }>('/api/admin/models') + } + + async listAdminProviders() { + return this.request<{ providers: CatalogProvider[] }>('/api/admin/providers') + } + + async createAdminProvider(input: { code: string; name: string; protocol: CatalogProvider['protocol']; description?: string }) { + return this.request<{ provider: CatalogProvider }>('/api/admin/providers', { method: 'POST', body: JSON.stringify(input) }) + } + + async createAdminModel(input: { providerId: string; publicName: string; upstreamModel: string; type: CatalogModelType; mode: CatalogCallMode; description?: string }) { + return this.request<{ model: CatalogModel }>('/api/admin/models', { method: 'POST', body: JSON.stringify(input) }) + } + + private async request(path: string, init?: RequestInit): Promise { + let response: Response + try { + response = await fetch(`${this.baseUrl}${path}`, { + ...init, + credentials: 'include', + headers: { 'Content-Type': 'application/json', ...init?.headers }, + }) + } catch { + throw new CatalogApiError(0, '无法连接 Control Plane,请确认服务已启动。') + } + if (response.status === 204) return undefined as T + const payload = await response.json().catch(() => ({})) as { error?: { code?: string; message?: string } } + if (!response.ok) throw new CatalogApiError(response.status, payload.error?.message || '目录请求失败', payload.error?.code) + return payload as T + } +} + +const controlPlaneUrl = (import.meta.env.VITE_CONTROL_PLANE_URL || 'http://127.0.0.1:8787').replace(/\/$/, '') +export const catalogClient = new HttpCatalogClient(controlPlaneUrl) diff --git a/prototype/src/types.ts b/prototype/src/types.ts index 5066583..a1d9b8b 100644 --- a/prototype/src/types.ts +++ b/prototype/src/types.ts @@ -32,10 +32,12 @@ export interface ModelItem { } export interface ApiKeyItem { - id: number + id: string | number name: string value: string scope: string + scopeType?: 'personal' | 'project' + projectId?: string createdAt: string lastUsed: string status: '正常' | '已停用' diff --git a/prototype/src/views/AdminConsole.vue b/prototype/src/views/AdminConsole.vue index 86744ee..ca4ee65 100644 --- a/prototype/src/views/AdminConsole.vue +++ b/prototype/src/views/AdminConsole.vue @@ -1,5 +1,5 @@