@njuptlzf/agent-chat-server 0.2.1 → 0.3.0

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.
@@ -0,0 +1,126 @@
1
+ import type { Branding } from "@njuptlzf/agent-chat-protocol";
2
+
3
+ type BrandingUi = NonNullable<Branding["ui"]>;
4
+ type BrandingFollowUp = NonNullable<BrandingUi["followUp"]>;
5
+
6
+ /** 「下一步建议」的三态。全局(branding.ui.followUp.mode)与人格(PersonaUi.followUpMode)共用这一份。 */
7
+ export const FOLLOW_UP_MODES = ["off", "static", "llm"] as const;
8
+ export type FollowUpMode = (typeof FOLLOW_UP_MODES)[number];
9
+
10
+ /** 图标语义槽白名单:键是平台定义的槽名,不是组件名。新增视觉件时在这里登记。 */
11
+ export const ICON_SLOTS = ["attachment"] as const;
12
+
13
+ const FOLLOW_UP_KEYS: readonly string[] = ["mode", "count", "static", "systemPrompt", "maxMessages", "timeoutMs"];
14
+
15
+ const MAX_ICON_VALUE = 512;
16
+ const MAX_STATIC_ITEMS = 10;
17
+ const MAX_STATIC_CHARS = 200;
18
+ const MAX_PROMPT_CHARS = 2000;
19
+ const MAX_COUNT = 5;
20
+ const MAX_MESSAGES = 20;
21
+ const MAX_TIMEOUT_MS = 30_000;
22
+
23
+ function deny(file: string, msg: string): never {
24
+ throw new Error(`Invalid manifest ${file}: ${msg}`);
25
+ }
26
+
27
+ function isRecord(v: unknown): v is Record<string, unknown> {
28
+ return !!v && typeof v === "object" && !Array.isArray(v);
29
+ }
30
+
31
+ function isMode(v: unknown): v is FollowUpMode {
32
+ return typeof v === "string" && (FOLLOW_UP_MODES as readonly string[]).includes(v);
33
+ }
34
+
35
+ /**
36
+ * 校验并规范化 `branding.ui`(图标值 + 下一步建议配置)。
37
+ *
38
+ * 分级与人格 ui 同一套口径:未知键 / 形状错 = 启动期 fail-fast(manifest 是签入文件,
39
+ * 错别字必须响);单个图标值非法(如非 http(s) 的 url: 前缀)= 丢弃该键回落默认,不因
40
+ * 一个坏图标让服务起不来。返回 undefined 表示产品没配(或全被丢弃)。
41
+ */
42
+ export function parseBrandingUi(file: string, at: string, raw: unknown): BrandingUi | undefined {
43
+ if (raw === undefined) return undefined;
44
+ if (!isRecord(raw)) deny(file, `\`${at}\` must be a mapping`);
45
+ const src = raw as Record<string, unknown>;
46
+ for (const key of Object.keys(src)) {
47
+ if (key !== "icons" && key !== "followUp") {
48
+ deny(file, `\`${at}.${key}\` is not a branding ui field (allowed: icons, followUp)`);
49
+ }
50
+ }
51
+
52
+ let icons: Record<string, string> | undefined;
53
+ if (src.icons !== undefined) {
54
+ if (!isRecord(src.icons)) deny(file, `\`${at}.icons\` must be a mapping`);
55
+ const srcIcons = src.icons as Record<string, unknown>;
56
+ for (const [key, value] of Object.entries(srcIcons)) {
57
+ if (!(ICON_SLOTS as readonly string[]).includes(key)) {
58
+ deny(file, `\`${at}.icons.${key}\` is not a known icon slot (allowed: ${ICON_SLOTS.join(", ")})`);
59
+ }
60
+ if (typeof value !== "string" || value.trim() === "") {
61
+ deny(file, `\`${at}.icons.${key}\` must be a non-empty string`);
62
+ }
63
+ if (value.length > MAX_ICON_VALUE) {
64
+ deny(file, `\`${at}.icons.${key}\` must be at most ${MAX_ICON_VALUE} characters`);
65
+ }
66
+ // url: 前缀只放行 http(s);别的协议(如 javascript:)丢弃该键回落默认,不 fail。
67
+ if (value.startsWith("url:") && !/^url:https?:\/\/\S+$/i.test(value)) continue;
68
+ (icons ??= {})[key] = value;
69
+ }
70
+ if (icons && Object.keys(icons).length === 0) icons = undefined;
71
+ }
72
+
73
+ let followUp: BrandingFollowUp | undefined;
74
+ if (src.followUp !== undefined) {
75
+ if (!isRecord(src.followUp)) deny(file, `\`${at}.followUp\` must be a mapping`);
76
+ const fu = src.followUp as Record<string, unknown>;
77
+ for (const key of Object.keys(fu)) {
78
+ if (!FOLLOW_UP_KEYS.includes(key)) {
79
+ deny(file, `\`${at}.followUp.${key}\` is not a known field (allowed: ${FOLLOW_UP_KEYS.join(", ")})`);
80
+ }
81
+ }
82
+ followUp = {};
83
+ if (fu.mode !== undefined) {
84
+ if (!isMode(fu.mode)) deny(file, `\`${at}.followUp.mode\` must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
85
+ followUp.mode = fu.mode;
86
+ }
87
+ if (fu.count !== undefined) {
88
+ const n = fu.count;
89
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_COUNT) {
90
+ deny(file, `\`${at}.followUp.count\` must be an integer between 1 and ${MAX_COUNT}`);
91
+ }
92
+ followUp.count = n;
93
+ }
94
+ if (fu.static !== undefined) {
95
+ const list = fu.static;
96
+ if (!Array.isArray(list) || list.length > MAX_STATIC_ITEMS || list.some((s) => typeof s !== "string" || !s.trim())) {
97
+ deny(file, `\`${at}.followUp.static\` must be a list of at most ${MAX_STATIC_ITEMS} non-empty strings`);
98
+ }
99
+ followUp.static = (list as string[]).map((s) => (s.length > MAX_STATIC_CHARS ? s.slice(0, MAX_STATIC_CHARS) : s));
100
+ }
101
+ if (fu.systemPrompt !== undefined) {
102
+ if (typeof fu.systemPrompt !== "string" || fu.systemPrompt.trim() === "") {
103
+ deny(file, `\`${at}.followUp.systemPrompt\` must be a non-empty string`);
104
+ }
105
+ followUp.systemPrompt = fu.systemPrompt.length > MAX_PROMPT_CHARS ? fu.systemPrompt.slice(0, MAX_PROMPT_CHARS) : fu.systemPrompt;
106
+ }
107
+ if (fu.maxMessages !== undefined) {
108
+ const n = fu.maxMessages;
109
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_MESSAGES) {
110
+ deny(file, `\`${at}.followUp.maxMessages\` must be an integer between 1 and ${MAX_MESSAGES}`);
111
+ }
112
+ followUp.maxMessages = n;
113
+ }
114
+ if (fu.timeoutMs !== undefined) {
115
+ const n = fu.timeoutMs;
116
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_TIMEOUT_MS) {
117
+ deny(file, `\`${at}.followUp.timeoutMs\` must be an integer between 1 and ${MAX_TIMEOUT_MS}`);
118
+ }
119
+ followUp.timeoutMs = n;
120
+ }
121
+ if (Object.keys(followUp).length === 0) followUp = undefined;
122
+ }
123
+
124
+ if (!icons && !followUp) return undefined;
125
+ return { ...(icons ? { icons } : {}), ...(followUp ? { followUp } : {}) };
126
+ }
package/src/manifest.ts CHANGED
@@ -4,6 +4,7 @@ import { pathToFileURL } from "node:url";
4
4
  import { parse } from "yaml";
5
5
  import type { McpServerDecl, PersonaUi, ProductManifest, ThinkingLevel } from "@njuptlzf/agent-chat-protocol";
6
6
  import { DEFAULT_PERSONA_ID, PERSONA_UI_FIELDS } from "@njuptlzf/agent-chat-protocol";
7
+ import { FOLLOW_UP_MODES, parseBrandingUi, type FollowUpMode } from "./branding-ui.ts";
7
8
 
8
9
  /** A manifest whose relative paths have been resolved to absolute ones. */
9
10
  export interface LoadedProduct {
@@ -102,6 +103,15 @@ function loadPersonaUi(file: string, at: string, raw: unknown): PersonaUi {
102
103
  }
103
104
  out.suggestions = src.suggestions as string[];
104
105
  }
106
+ // 循环外专用块(照抄 suggestions 的范式):字面量联合字段不能进上面的字符串循环,
107
+ // 否则 `out[key] = v` 会触发 TS「联合键写入取交集」编译错。
108
+ const fm = src.followUpMode;
109
+ if (fm !== undefined) {
110
+ if (typeof fm !== "string" || !(FOLLOW_UP_MODES as readonly string[]).includes(fm)) {
111
+ fail(file, `\`${at}.followUpMode\` must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
112
+ }
113
+ out.followUpMode = fm as FollowUpMode;
114
+ }
105
115
  return out;
106
116
  }
107
117
 
@@ -303,6 +313,9 @@ export function loadProduct(dir: string): LoadedProduct {
303
313
  if (!raw.agent.model?.provider || !raw.agent.model?.id) fail(file, "`agent.model.provider` and `agent.model.id` are required");
304
314
 
305
315
  const manifest = raw as ProductManifest;
316
+ // 视觉件与下一步建议配置():白名单校验 + 非法图标值宽容丢弃;规范化结果写回
317
+ // branding,让 `GET /api/branding` 的整体展开(server.ts `...branding`)自然带下去。
318
+ manifest.branding.ui = parseBrandingUi(file, "branding.ui", manifest.branding.ui);
306
319
  // 业务路由声明。与 tools.inline / extensions 同级信任(仓库内代码),但
307
320
  // 路径必须留在产品目录内——写 `../` 逃出去等于让 manifest 加载任意文件。
308
321
  if (manifest.server?.routes !== undefined) {
@@ -14,6 +14,7 @@
14
14
  import { readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
15
15
  import path from "node:path";
16
16
  import { PERSONA_UI_FIELDS, type PersonaUi } from "@njuptlzf/agent-chat-protocol";
17
+ import { FOLLOW_UP_MODES, type FollowUpMode } from "./branding-ui.ts";
17
18
  import { personaIdsOf, type LoadedProduct } from "./manifest.ts";
18
19
 
19
20
  export const PERSONA_CONFIG_FILENAME = "persona-config.json";
@@ -230,11 +231,21 @@ function parseUi(raw: unknown, at: string, problems: string[]): PersonaUi | unde
230
231
  }
231
232
  continue;
232
233
  }
234
+ // 循环外专用块(与 manifest 的 loadPersonaUi 同款):字面量联合字段不能落进下面
235
+ // 的泛型字符串写,否则 `out[key] = value` 触发 TS「联合键写入取交集」编译错。
236
+ if (key === "followUpMode") {
237
+ if (typeof value !== "string" || !(FOLLOW_UP_MODES as readonly string[]).includes(value)) {
238
+ problems.push(`${at}.followUpMode must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
239
+ } else {
240
+ out.followUpMode = value as FollowUpMode;
241
+ }
242
+ continue;
243
+ }
233
244
  if (typeof value !== "string" || value.trim() === "") {
234
245
  problems.push(`${at}.${key} must be a non-empty string`);
235
246
  continue;
236
247
  }
237
- out[key as Exclude<keyof PersonaUi, "suggestions">] = value;
248
+ out[key as Exclude<keyof PersonaUi, "suggestions" | "followUpMode">] = value;
238
249
  }
239
250
  return out;
240
251
  }
package/src/server.ts CHANGED
@@ -8,6 +8,7 @@ import { createEventMapper, createRunAccounting } from "./events.ts";
8
8
  import { agentFor, type LoadedProduct, personaIdsOf, type ToolContext } from "./manifest.ts";
9
9
  import { appendVersion, effectivePersonaVersion, PROMPT_MAX_CHARS, savePersonaConfig, validatePersona, versionEntry, versionsOf, type PersonaConfigStore, type PersonaOverride } from "./persona-config.ts";
10
10
  import { runPersonaTrial, TRIAL_MAX_INPUT_CHARS, type TrialInput, type TrialResult } from "./persona-trial.ts";
11
+ import { runSuggestions, clipMessages, SUGGESTIONS_DEFAULTS, type SuggestionsRunner } from "./suggestions.ts";
11
12
  import { MODEL_SWITCH } from "./audit.ts";
12
13
  import { FAILOVER_NOTICE, candidateKey, isRetryableModelError, orderChain, processCooldown, rawModelError, type CooldownRegistry } from "./model-failover.ts";
13
14
  import { resolveChain, resolveRunTier, saveModelConfig, type ModelCandidate, type ModelConfig, type ModelConfigStore } from "./model-config.ts";
@@ -66,6 +67,11 @@ export interface ServerDeps {
66
67
  * 测试注入替身,避免为了验证"旁路"而真的花钱。
67
68
  */
68
69
  trial?: (input: TrialInput) => Promise<TrialResult>;
70
+ /**
71
+ * 下一步建议生成器。omitted ⇒ 真调模型(`runSuggestions`);
72
+ * 测试注入替身,避免为了验证旁路而真的花钱。
73
+ */
74
+ suggestions?: SuggestionsRunner;
69
75
  /**
70
76
  * Optional 候选冷却表。omitted ⇒ 进程级默认实例(重启清空、不进 DB);
71
77
  * 测试注入自己的实例以隔离。
@@ -1045,6 +1051,8 @@ async function handleAdminPersonas(
1045
1051
  problems: cfg.problems,
1046
1052
  // 默认助手的 id:页面用它在列表里显示「默认助手」并区分展示字段的落点。
1047
1053
  defaultPersona: product.defaultPersona,
1054
+ // 下一步建议的全局模式(只读):全局 off 是硬地板,页面据此禁用人格级下拉。
1055
+ globalFollowUpMode: product.manifest.branding.ui?.followUp?.mode ?? "llm",
1048
1056
  personas: ids.map((id) => {
1049
1057
  const override = cfg.personas[id];
1050
1058
  // 生效文案(含运行时覆盖)——列表徽标与名称要用"用户看到的",不是 manifest 原文。
@@ -2021,6 +2029,56 @@ export function createChatServer(deps: ServerDeps): Server {
2021
2029
  return sendJson(res, 200, { sessionId: body.sessionId, messages: toHistoryMessages(kept) });
2022
2030
  }
2023
2031
  if (req.method === "POST" && url.pathname === "/api/chat") return await handleChat(req, res);
2032
+ if (req.method === "POST" && url.pathname === "/api/suggestions") {
2033
+ const auth = await deps.authenticate(req);
2034
+ if (!auth) return deny401(deps, req, res);
2035
+ let body: { messages?: unknown; persona?: unknown };
2036
+ try {
2037
+ body = (await readJson(req)) as typeof body;
2038
+ } catch {
2039
+ return sendError(res, 400, "bad_request", "body must be valid JSON under 64KB");
2040
+ }
2041
+ // 人格 id 合法性与 /api/chat 同一条规矩(400,不静默)。默认助手也显式带 id:
2042
+ // 这里没有会话绑定,服务端要按同一个 id 复核人格级覆盖。
2043
+ if (
2044
+ body.persona !== undefined &&
2045
+ (typeof body.persona !== "string" || !personaIdsOf(deps.product).has(body.persona))
2046
+ ) {
2047
+ return sendError(res, 400, "bad_request", `unknown persona "${String(body.persona)}"`);
2048
+ }
2049
+ const personaId = (typeof body.persona === "string" ? body.persona : undefined) ?? deps.product.defaultPersona;
2050
+ const followUp = deps.product.manifest.branding.ui?.followUp;
2051
+ // 生效模式(前后端同一套优先级):全局 off 是硬地板——人格不能把全局关闭
2052
+ // 重新打开;否则人格 followUpMode > 全局 mode > 缺省 llm。
2053
+ const globalMode = followUp?.mode ?? "llm";
2054
+ if (globalMode === "off") return sendJson(res, 200, { suggestions: [] });
2055
+ const personaMode = effectiveUiOf(deps.product, deps.personaConfig?.get(), personaId)?.followUpMode;
2056
+ const mode = personaMode ?? globalMode;
2057
+ const count = followUp?.count ?? SUGGESTIONS_DEFAULTS.count;
2058
+ const staticFallback = Array.isArray(followUp?.static) ? followUp.static : [];
2059
+ if (mode === "off") return sendJson(res, 200, { suggestions: [] });
2060
+ if (mode === "static") return sendJson(res, 200, { suggestions: staticFallback.slice(0, count) });
2061
+ // llm:这是一轮问答的附属产物,任何失败(模型不可用/超时/输入非法)都静默
2062
+ // 回落 static——绝不 4xx/5xx 冒泡,也不接配额与计费。
2063
+ let suggestions = staticFallback.slice(0, count);
2064
+ try {
2065
+ suggestions = (
2066
+ await (deps.suggestions ?? runSuggestions)(
2067
+ { product: deps.product, modelRuntime: deps.modelRuntime },
2068
+ {
2069
+ messages: clipMessages(body.messages, followUp?.maxMessages ?? SUGGESTIONS_DEFAULTS.maxMessages),
2070
+ count,
2071
+ staticFallback,
2072
+ ...(followUp?.systemPrompt !== undefined ? { systemPrompt: followUp.systemPrompt } : {}),
2073
+ timeoutMs: followUp?.timeoutMs ?? SUGGESTIONS_DEFAULTS.timeoutMs,
2074
+ },
2075
+ )
2076
+ ).slice(0, count);
2077
+ } catch {
2078
+ // 静默:回落内容已在初始值里。
2079
+ }
2080
+ return sendJson(res, 200, { suggestions });
2081
+ }
2024
2082
  if (req.method === "POST" && url.pathname === "/api/decision") {
2025
2083
  const auth = await deps.authenticate(req);
2026
2084
  if (!auth) return deny401(deps, req, res);