Spaces:
Running
Running
Download ui-src/src/api.ts from Ethscriptions/xiaoshuo: direct link, hf CLI and curl.
- Browser
- Download file 23.9 kB
-
https://huggingface.co/spaces/Ethscriptions/xiaoshuo/resolve/main/ui-src/src/api.ts
- Command line
-
hf download hf://spaces/Ethscriptions/xiaoshuo/ui-src/src/api.ts
-
curl -L -o api.ts https://huggingface.co/spaces/Ethscriptions/xiaoshuo/resolve/main/ui-src/src/api.ts
23.9 kB
| // 与服务器通信:所有接口沿用原有地址和格式,只是换了界面。 | |
| const PASSWORD_KEY = 'xiaoshuo_app_password' | |
| const LEGACY_KEYS = ['xiaoshuo_fanqie_password'] | |
| export function getPassword(): string { | |
| try { | |
| const v = localStorage.getItem(PASSWORD_KEY) | |
| if (v) return v | |
| for (const k of LEGACY_KEYS) { | |
| const old = localStorage.getItem(k) | |
| if (old) return old | |
| } | |
| } catch {} | |
| return '' | |
| } | |
| export function setPassword(v: string) { | |
| try { | |
| if (v) localStorage.setItem(PASSWORD_KEY, v) | |
| else localStorage.removeItem(PASSWORD_KEY) | |
| } catch {} | |
| } | |
| export class ApiError extends Error { | |
| status: number | |
| data: any | |
| constructor(status: number, message: string, data?: any) { | |
| super(message) | |
| this.status = status | |
| this.data = data | |
| } | |
| } | |
| let onUnauthorized: (() => void) | null = null | |
| export function setUnauthorizedHandler(fn: () => void) { onUnauthorized = fn } | |
| function headers(extra?: Record<string, string>) { | |
| // 工作台自己的请求带上标记:写新章锁只拦写作 AI,不拦作者 | |
| const h: Record<string, string> = { 'x-client': 'workbench', ...(extra || {}) } | |
| const pw = getPassword() | |
| if (pw) h['x-app-password'] = encodeURIComponent(pw) | |
| const vk = getVaultKey() | |
| if (vk) h['x-vault-key'] = encodeURIComponent(vk) | |
| return h | |
| } | |
| /* ---------- 采集室钥匙:只有作者本人知道,只存在本机浏览器 ---------- */ | |
| const VAULT_KEY = 'xs_vault_key' | |
| export function getVaultKey(): string { try { return sessionStorage.getItem(VAULT_KEY) || localStorage.getItem(VAULT_KEY) || '' } catch { return '' } } | |
| export function setVaultKey(v: string, remember = false) { | |
| try { | |
| sessionStorage.removeItem(VAULT_KEY); localStorage.removeItem(VAULT_KEY) | |
| if (v) (remember ? localStorage : sessionStorage).setItem(VAULT_KEY, v) | |
| document.cookie = v ? `xs_vk=${encodeURIComponent(v)}; path=/; SameSite=Strict${remember ? '; max-age=2592000' : ''}` : 'xs_vk=; path=/; max-age=0; SameSite=Strict' | |
| } catch {} | |
| } | |
| export async function request<T = any>(method: string, url: string, body?: unknown): Promise<T> { | |
| const init: RequestInit = { method, headers: headers(body !== undefined ? { 'Content-Type': 'application/json' } : undefined) } | |
| if (body !== undefined) init.body = JSON.stringify(body) | |
| let res: Response | |
| try { | |
| res = await fetch(url, init) | |
| } catch { | |
| throw new ApiError(0, '网络连接失败,请稍后再试') | |
| } | |
| const text = await res.text() | |
| let data: any = null | |
| try { data = text ? JSON.parse(text) : null } catch { data = text } | |
| if (res.status === 423) throw new ApiError(423, (data && data.error) || '采集室已上锁', data) | |
| if (res.status === 401) { | |
| onUnauthorized?.() | |
| throw new ApiError(401, '需要访问密码', data) | |
| } | |
| if (!res.ok) throw new ApiError(res.status, (data && data.error) || `请求失败(${res.status})`, data) | |
| return data as T | |
| } | |
| export const get = <T = any>(url: string) => request<T>('GET', url) | |
| export const post = <T = any>(url: string, body: unknown = {}) => request<T>('POST', url, body) | |
| export const put = <T = any>(url: string, body: unknown = {}) => request<T>('PUT', url, body) | |
| export const patch = <T = any>(url: string, body: unknown = {}) => request<T>('PATCH', url, body) | |
| export const del = <T = any>(url: string) => request<T>('DELETE', url) | |
| export function qs(params: Record<string, any>) { | |
| const u = new URLSearchParams() | |
| for (const [k, v] of Object.entries(params)) { | |
| if (v === undefined || v === null || v === '' || v === false) continue | |
| u.set(k, String(v === true ? 1 : v)) | |
| } | |
| const s = u.toString() | |
| return s ? `?${s}` : '' | |
| } | |
| export async function checkPassword(pw: string): Promise<boolean> { | |
| const res = await fetch('/api/auth/check', { headers: { 'x-app-password': encodeURIComponent(pw) } }) | |
| return res.ok | |
| } | |
| export async function authRequired(): Promise<boolean> { | |
| try { | |
| const r = await fetch('/api/auth') | |
| const d = await r.json() | |
| return Boolean(d?.required) | |
| } catch { return true } | |
| } | |
| // 下载需要密码的文件 | |
| export async function download(url: string, filename: string) { | |
| const res = await fetch(url, { headers: headers() }) | |
| if (res.status === 401) { onUnauthorized?.(); throw new ApiError(401, '需要访问密码') } | |
| if (!res.ok) throw new ApiError(res.status, `下载失败(${res.status})`) | |
| const blob = await res.blob() | |
| const a = document.createElement('a') | |
| a.href = URL.createObjectURL(blob) | |
| a.download = filename | |
| document.body.appendChild(a) | |
| a.click() | |
| setTimeout(() => { URL.revokeObjectURL(a.href); a.remove() }, 1000) | |
| } | |
| /* ---------- 整本书文件:导出 / 导入 ---------- */ | |
| export interface BookFile { format: string; version: number; exported_at: string; project: { project_id: string; title: string }; file_count: number; files_sha256: string; files: Record<string, any> } | |
| async function gunzipBytes(buf: ArrayBuffer): Promise<string> { | |
| const u = new Uint8Array(buf) | |
| if (!(u[0] === 0x1f && u[1] === 0x8b)) return new TextDecoder().decode(u) | |
| const DS = (globalThis as any).DecompressionStream | |
| if (!DS) throw new Error('这个浏览器打不开压缩文件') | |
| const stream = new Blob([u]).stream().pipeThrough(new DS('gzip')) | |
| return await new Response(stream).text() | |
| } | |
| async function sha256Hex(text: string) { | |
| const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)) | |
| return [...new Uint8Array(d)].map(b => b.toString(16).padStart(2, '0')).join('') | |
| } | |
| /** 读一个书本文件并核对:内容完整、和导出时一模一样 */ | |
| export async function readBookFile(buf: ArrayBuffer): Promise<{ doc: BookFile; ok: boolean; chapters: number; versions: number }> { | |
| const doc = JSON.parse(await gunzipBytes(buf)) as BookFile | |
| if (!doc || doc.format !== 'xiaoshuo-book' || !doc.files) throw new Error('这不是工作台导出的书') | |
| let ok = Object.keys(doc.files).length === doc.file_count | |
| try { ok = ok && (await sha256Hex(JSON.stringify(doc.files))) === doc.files_sha256 } catch {} | |
| const keys = Object.keys(doc.files) | |
| return { doc, ok, chapters: (doc.files['chapters/index.json']?.chapters || []).length, versions: keys.filter(k => /\/versions\/(?!index)[^/]+\.json$/.test(k)).length } | |
| } | |
| export async function exportBook(pid: string, title: string) { | |
| const res = await fetch(`/fanqie/api/projects/${pid}/export`, { headers: headers() }) | |
| if (res.status === 401) { onUnauthorized?.(); throw new ApiError(401, '需要访问密码') } | |
| if (!res.ok) { let m = `导出失败(${res.status})`; try { m = (await res.json()).error || m } catch {} throw new ApiError(res.status, m) } | |
| const buf = await res.arrayBuffer() | |
| const check = await readBookFile(buf) | |
| const filename = `${title.replace(/[\\/:*?"<>|]/g, '_')}-${new Date().toISOString().slice(0, 10)}.xsbook` | |
| const a = document.createElement('a') | |
| a.href = URL.createObjectURL(new Blob([buf], { type: 'application/octet-stream' })) | |
| a.download = filename | |
| document.body.appendChild(a); a.click() | |
| setTimeout(() => { URL.revokeObjectURL(a.href); a.remove() }, 4000) | |
| return { filename, bytes: buf.byteLength, ...check } | |
| } | |
| export async function importBook(file: Blob) { | |
| let res: Response | |
| try { res = await fetch('/fanqie/api/projects/import', { method: 'POST', headers: headers({ 'Content-Type': 'application/octet-stream' }), body: file }) } | |
| catch { throw new ApiError(0, '网络连接失败,请稍后再试') } | |
| const text = await res.text(); let data: any = null | |
| try { data = JSON.parse(text) } catch { data = text } | |
| if (res.status === 401) { onUnauthorized?.(); throw new ApiError(401, '需要访问密码') } | |
| if (!res.ok) throw new ApiError(res.status, (data && data.error) || `导入失败(${res.status})`, data) | |
| return data as { project: Project; file_count: number } | |
| } | |
| /* ---------- 数据类型 ---------- */ | |
| export interface Project { | |
| project_id: string | |
| title: string | |
| genre: string | |
| target_platform: string | |
| target_words: number | |
| pov: string | |
| style: string | |
| premise: string | |
| status: string | |
| created_at: string | |
| updated_at: string | |
| revision: number | |
| current_chapter_id: string | null | |
| chapter_words_min?: number | null | |
| chapter_words_max?: number | null | |
| } | |
| export interface Chapter { | |
| chapter_id: string | |
| project_id: string | |
| number: number | |
| volume: string | |
| title: string | |
| goal: string | |
| outline: string | |
| scenes: any[] | |
| previous_summary: string | |
| status: string | |
| current_version_id: string | null | |
| word_count?: number | |
| created_at: string | |
| updated_at: string | |
| revision: number | |
| versions?: VersionMeta[] | |
| } | |
| export interface VersionMeta { version_id: string; chapter_id: string; created_at: string; kind: string; summary: string; word_count: number } | |
| export interface Version extends VersionMeta { project_id: string; text: string; notes: string; source_version_id: string | null; created_by: string } | |
| export interface Bible { | |
| story_core: string; main_plot: string; ending_direction: string; reader_expectation: string | |
| characters: any[]; relationships: any[]; timeline: any[]; settings: any[]; foreshadowing: any[] | |
| open_questions: any[]; style_rules: any[]; safety_rules: any[]; source_material_uids: any[] | |
| ai_rules?: any[]; glossary?: any[]; self_check?: any[] | |
| updated_at?: string; [k: string]: any | |
| } | |
| export interface Outline { three_act: any[]; volumes: any[]; chapters: any[]; updated_at?: string; [k: string]: any } | |
| export interface Material { | |
| uid: string; ch: string; at: string; d: string; q: number; g: string; k: string; sum: string; text: string | |
| why?: string; edits?: [string, string][]; src?: string | null; react?: number; score?: number | |
| card?: MaterialCard | |
| } | |
| export interface MaterialCard { | |
| uid: string; use?: boolean; motifs?: string[]; logline?: string; beats?: string[] | |
| people?: { role?: string; trait?: string; want?: string }[]; arc?: string; details?: string[] | |
| scene?: string; hook?: string; twist?: string; roles?: string[] | |
| } | |
| export interface WordRange { min: number | null; max: number | null; source: 'project' | 'bible'; label: string } | |
| export interface ProjectBundle { project: Project; bible: Bible; outline: Outline; materials: { items: any[] }; chapters: Chapter[]; word_range?: WordRange | null } | |
| // 本章字数在不在本书规定的范围内(字数 = 去掉空白后的字数) | |
| export function wordFlag(words: number | undefined, r?: WordRange | null): 'low' | 'high' | null { | |
| if (!r || !words || words <= 0) return null | |
| if (r.min && words < r.min) return 'low' | |
| if (r.max && words > r.max) return 'high' | |
| return null | |
| } | |
| const P = '/fanqie/api/projects' | |
| export const projectsApi = { | |
| list: () => get<{ projects: Project[] }>(P), | |
| create: (body: Partial<Project>) => post<ProjectBundle>(P, body), | |
| get: (id: string) => get<ProjectBundle>(`${P}/${id}`), | |
| update: (id: string, body: Partial<Project>) => patch<Project>(`${P}/${id}`, body), | |
| remove: (id: string) => del(`${P}/${id}`), | |
| saveBible: (id: string, body: Bible) => put<Bible>(`${P}/${id}/bible`, body), | |
| saveOutline: (id: string, body: Outline) => put<Outline>(`${P}/${id}/outline`, body), | |
| saveMaterials: (id: string, items: any[]) => put<{ items: any[] }>(`${P}/${id}/materials`, { items }), | |
| chapters: (id: string) => get<Chapter[]>(`${P}/${id}/chapters`), | |
| createChapter: (id: string, body: Partial<Chapter>) => post<Chapter>(`${P}/${id}/chapters`, body), | |
| chapter: (id: string, cid: string) => get<{ project: Project; chapter: Chapter; versions: VersionMeta[] }>(`${P}/${id}/chapters/${cid}`), | |
| updateChapter: (id: string, cid: string, body: Partial<Chapter>) => patch<Chapter>(`${P}/${id}/chapters/${cid}`, body), | |
| versions: (id: string, cid: string) => get<VersionMeta[]>(`${P}/${id}/chapters/${cid}/versions`), | |
| version: (id: string, cid: string, vid: string) => get<Version>(`${P}/${id}/chapters/${cid}/versions/${vid}`), | |
| saveVersion: (id: string, cid: string, body: { text: string; kind?: string; summary?: string; notes?: string; source_version_id?: string | null; created_by?: string }) => | |
| post<Version>(`${P}/${id}/chapters/${cid}/versions`, body), | |
| rollback: (id: string, cid: string, vid: string) => post<{ chapter: Chapter; version: Version }>(`${P}/${id}/chapters/${cid}/versions/${vid}/rollback`, {}), | |
| check: (id: string, cid: string) => post<any>(`${P}/${id}/chapters/${cid}/check`, {}), | |
| getCheck: (id: string, vid: string) => get<any>(`${P}/${id}/checks/${vid}`), | |
| context: (id: string, cid?: string) => get<any>(`${P}/${id}/context${qs({ chapter_id: cid })}`), | |
| requests: (id: string) => get<{ requests: any[] }>(`${P}/${id}/requests`), | |
| createRequest: (id: string, body: { type: string; instruction: string; chapter_id?: string | null }) => post<any>(`${P}/${id}/requests`, body), | |
| notes: (id: string, cid: string) => get<{ notes: Note[]; reviews: Review[] }>(`${P}/${id}/chapters/${cid}/notes`), | |
| peer: (id: string, cid?: string) => get<{ items: PeerItem[]; counts: Record<string, number> }>(`${P}/${id}/peer${qs({ chapter_id: cid })}`), | |
| decidePeer: (id: string, itemId: string, body: { decision: '' | 'adopt' | 'keep' | 'own'; note?: string }) => put<PeerItem>(`${P}/${id}/peer/${itemId}/author`, body), | |
| progress: (id: string) => get<ReadProgress>(`${P}/${id}/progress`), | |
| saveProgress: (id: string, body: { reader?: { chapter_id: string; para: number; ratio?: number }; chapter?: { chapter_id: string; read_para?: number; read_ratio?: number; edit_ratio?: number } }) => put<ReadProgress>(`${P}/${id}/progress`, body), | |
| allNotes: (id: string, status?: string) => get<{ chapters: { chapter_id: string; number: number; title: string; current_version_id: string | null; notes: Note[] }[] }>(`${P}/${id}/notes${qs({ status })}`), | |
| changes: (id: string, p: { by?: string; chapter_id?: string; limit?: number } = {}) => get<ChangeList>(`${P}/${id}/changes${qs(p)}`), | |
| writeMode: (id: string) => get<WriteMode>(`${P}/${id}/write-mode`), | |
| endWriteMode: (id: string) => del<{ active: false }>(`${P}/${id}/write-mode`), | |
| publish: (id: string) => get<{ chapters: PublishRow[]; word_range?: WordRange | null; updated_at: string | null }>(`${P}/${id}/publish`), | |
| setPublish: (id: string, cid: string, published: boolean) => put<{ chapter_id: string; published: PublishRow['published'] }>(`${P}/${id}/publish/${cid}`, { published }), | |
| saveDraft: (id: string, cid: string, body: { text: string; base: string | null }) => put<{ ok: boolean }>(`${P}/${id}/chapters/${cid}/draft`, body), | |
| createNote: (id: string, cid: string, body: Partial<Note>) => post<Note>(`${P}/${id}/chapters/${cid}/notes`, body), | |
| updateNote: (id: string, cid: string, nid: string, body: Partial<Note>) => patch<Note>(`${P}/${id}/chapters/${cid}/notes/${nid}`, body), | |
| deleteNote: (id: string, cid: string, nid: string) => del(`${P}/${id}/chapters/${cid}/notes/${nid}`), | |
| saveReview: (id: string, cid: string, body: Partial<Review>) => post<Review>(`${P}/${id}/chapters/${cid}/reviews`, body), | |
| deleteReview: (id: string, cid: string, rid: string) => del(`${P}/${id}/chapters/${cid}/reviews/${rid}`), | |
| } | |
| export interface Note { | |
| note_id: string; chapter_id: string; version_id?: string | null; quote: string; start: number; end: number | |
| type: string; severity: 'must' | 'should' | 'maybe'; comment: string; suggestion?: string; reply?: string | |
| status: 'open' | 'fixed' | 'closed' | 'wontfix'; created_by: string; created_at: string; updated_at?: string | |
| } | |
| export interface ChangeHunk { para: number; before: string[]; after: string[] } | |
| export interface ChangeItem { | |
| change_id: string; chapter_id: string; number: number; title: string; at: string; kind: 'save' | 'rollback'; by: string; by_author: boolean | |
| from_version_id: string | null; to_version_id: string; summary?: string; hunks: ChangeHunk[]; hunk_count: number; word_delta: number | |
| acks?: { by: string; note: string; at: string }[] | |
| } | |
| export interface AgentFocus { project_id: string | null; title?: string; started_at?: string; expires_at?: string; history?: { project_id: string; title: string; at: string; from: string; reason: string }[] } | |
| export interface WriteMode { active: boolean; chapter?: number | null; by?: string; started_at?: string; expires_at?: string } | |
| export interface PublishRow { | |
| chapter_id: string; number: number; title: string; volume: string; status: string; words: number; words_flag?: 'low' | 'high' | null; words_range?: string | null; current_version_id: string | null; updated_at: string | |
| check: { status: 'none' | 'pass' | 'warn' | 'fail'; stale: boolean; kinds: { kind: string; status: string; at: string; version_id: string | null }[] } | |
| open_notes: number; peer_todo: number; unsaved_draft: boolean | |
| published: { at: string; version_id: string; words: number; changed: boolean } | null | |
| } | |
| export interface ChangeList { | |
| items: ChangeItem[]; total: number; updated_at: string | null | |
| unsaved_author_drafts: { chapter_id: string; number: number; title: string; at: string; hunks: ChangeHunk[]; hunk_count: number; word_delta: number }[] | |
| } | |
| export interface Review { review_id: string; version_id?: string | null; scores: Record<string, number>; summary: string; verdict: 'pass' | 'revise' | 'rewrite'; created_by: string; created_at: string } | |
| const M = '/fanqie/api/materials' | |
| export const materialsApi = { | |
| stats: () => get<any>(`${M}/stats`), | |
| list: (p: Record<string, any>) => get<{ total: number; page: number; size: number; items: Material[] }>(`${M}${qs(p)}`), | |
| random: (p: Record<string, any>) => get<{ total: number; items: Material[] }>(`${M}/random${qs(p)}`), | |
| item: (uid: string) => get<Material>(`${M}/item${qs({ uid })}`), | |
| motifs: () => get<any>(`${M}/motifs`), | |
| motif: (id: string, page = 1, size = 20) => get<any>(`${M}/motif${qs({ id, page, size })}`), | |
| search: (p: Record<string, any>) => get<{ total: number; motifs: string[]; items: Material[] }>(`${M}/search${qs(p)}`), | |
| compose: (p: Record<string, any>) => get<any>(`${M}/compose${qs(p)}`), | |
| } | |
| export const vaultApi = { | |
| status: () => get<{ set: boolean; unlocked: boolean; set_at?: string }>('/api/vault/status'), | |
| setup: (key: string, old?: string) => post<{ ok: boolean }>('/api/vault/setup', { key, old }), | |
| audit: (n = 100) => get<{ items: { t: string; ev: string; path?: string; kind?: string; ua?: string }[] }>(`/api/vault/audit${qs({ n })}`), | |
| } | |
| /* ---------- AI 协作 ---------- */ | |
| export interface AgentProfile { | |
| account: 'new' | 'active' | 'veteran'; level: string; first_book: 'none' | 'writing' | 'done'; contract: 'none' | 'applying' | 'signed' | |
| published_chapters: number; goal: string; note: string; updated_at?: string; labels?: Record<string, string>; implications: string[] | |
| } | |
| export interface AuditItem { id: string; title: string; result: 'pass' | 'warn' | 'fail' | 'na'; note: string; quote: string; fix: string } | |
| export interface Audit { | |
| audit_id: string; project_id: string; kind: 'checklist' | 'platform' | 'logic'; scope: 'book' | 'chapter'; chapter_id: string | null | |
| chapter_number: number | null; version_id: string | null; by: string; status: 'pass' | 'warn' | 'fail'; summary: string; items: AuditItem[]; created_at: string | |
| } | |
| export interface ReviewerCfg { | |
| name: string; mode: 'surf' | 'openai' | 'anthropic' | 'custom'; endpoint: string; model: string; headers_tpl: string; body_tpl: string; reply_path: string | |
| sse: boolean; max_chars: number; system: string; note?: string; token_set: boolean; token_tail: string; token_saved_at?: string; updated_at?: string | |
| refresh_set?: boolean; token_expires_at?: string | null; token_refreshed_at?: string; auto_refresh?: boolean | |
| renew_count?: number; renew_fail?: number; renew_error?: string; renew_dead?: boolean; renew_failed_at?: string; renew_test?: 'ok' | 'fail' | |
| keep?: { on: boolean; every_min: number; ahead_min: number; started_at?: string | null; last_check_at?: string | null; next_check_at?: string | null } | null | |
| surf_model?: string; surf_effort?: string; instant?: boolean | |
| surf_models?: Record<string, string>; surf_efforts?: { id: string; label: string }[]; surf_catalog_at?: string | null; tasks?: Record<string, string> | |
| } | |
| export interface PeerItem { | |
| item_id: string; chapter_id: string | null; chapter_number: number | null; ask_id: string; topic: string | |
| reviewer_said: string; my_view: string; decision: string; verdict: 'agree' | 'partial' | 'disagree'; created_by: string; created_at: string; updated_at: string | |
| quote?: string; evidence?: string; author_decision?: '' | 'adopt' | 'keep' | 'own'; author_note?: string; author_at?: string | null | |
| resolved?: boolean; resolution?: string; resolved_at?: string | null | |
| } | |
| export interface ReadProgress { | |
| reader: { chapter_id: string; para: number; ratio?: number; at: string } | null | |
| chapters: Record<string, { read_para?: number; read_ratio?: number; edit_ratio?: number; at?: string }> | |
| updated_at?: string | |
| } | |
| export interface ReviewerAsk { | |
| ask_id: string; project_id: string | null; topic: string; question: string; attach: string[]; asked_by: string; reviewer: string | |
| created_at: string; ok: boolean; reply?: string; error?: string; http?: number | null; ms?: number; status: 'new' | 'adopted' | 'partial' | 'rejected'; response?: string | |
| task?: string; state?: 'running' | 'queued' | 'done' | 'error'; live?: boolean; partial_reply?: string; engine?: string; url?: string | null; session_id?: string | null | |
| continued_from?: string | null; cost_usd?: number | null; turn?: number; partial?: boolean; warn?: string; recovered?: boolean; code?: string | null | |
| } | |
| export interface ReviewerCheck { | |
| ok: boolean | null; mode: string; note?: string; user?: { name: string; email: string; plan: string | null } | |
| token_expires_in_min?: number | null; auto_refresh?: boolean; credits?: any | |
| } | |
| const A = '/fanqie/api/agent' | |
| export const agentApi = { | |
| focus: () => get<AgentFocus>(`${A}/focus`), | |
| setFocus: (project_id: string, reason = '') => post<AgentFocus>(`${A}/focus`, { project_id, switch: true, reason }), | |
| clearFocus: () => del<{ project_id: null }>(`${A}/focus`), | |
| profile: () => get<AgentProfile>(`${A}/profile`), | |
| saveProfile: (b: Partial<AgentProfile>) => put<AgentProfile>(`${A}/profile`, b), | |
| rules: () => get<{ version?: string; checked?: string; checklist: any[]; platform: any[]; ai_spec: any[] }>(`${A}/rules`), | |
| audits: (p: { project_id: string; kind?: string; chapter_id?: string; scope?: string; n?: number }) => get<{ items: Audit[]; kinds: Record<string, string> }>(`${A}/audits${qs(p)}`), | |
| deleteAudit: (pid: string, aid: string) => del(`${A}/audits/${aid}${qs({ project_id: pid })}`), | |
| reviewer: () => get<ReviewerCfg>(`${A}/reviewer`), | |
| saveReviewer: (b: Partial<ReviewerCfg> & { token?: string; clear_token?: boolean }) => put<ReviewerCfg>(`${A}/reviewer`, b), | |
| ask: (b: { project_id?: string; topic?: string; question: string; attach?: string[]; asked_by?: string; task?: string; wait?: number; continue?: string }) => post<ReviewerAsk>(`${A}/reviewer/ask`, b), | |
| check: () => post<ReviewerCheck>(`${A}/reviewer/check`, {}), | |
| renew: () => post<ReviewerCfg>(`${A}/reviewer/renew`, {}), | |
| catalog: (fresh = false) => get<{ models: Record<string, string>; efforts: { id: string; label: string }[]; at: string | null; error: string | null }>(`${A}/reviewer/catalog${fresh ? '?fresh=1' : ''}`), | |
| cancelAsk: (aid: string, project_id?: string | null) => post<ReviewerAsk>(`${A}/reviewer/log/${aid}/cancel`, { project_id: project_id || undefined }), | |
| log: (project_id?: string, n = 50) => get<{ items: ReviewerAsk[] }>(`${A}/reviewer/log${qs({ project_id, n })}`), | |
| patchLog: (aid: string, b: { project_id?: string; status?: string; response?: string }) => patch<ReviewerAsk>(`${A}/reviewer/log/${aid}`, b), | |
| guideMd: async () => { | |
| const r = await fetch(`${A}/guide.md`, { headers: headers() }) | |
| if (r.status === 401) { onUnauthorized?.(); throw new ApiError(401, '需要访问密码') } | |
| if (!r.ok) throw new ApiError(r.status, `读取失败(${r.status})`) | |
| return r.text() | |
| }, | |
| } | |