@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,16 @@
1
+ import type { Branding } from "@njuptlzf/agent-chat-protocol";
2
+ type BrandingUi = NonNullable<Branding["ui"]>;
3
+ /** 「下一步建议」的三态。全局(branding.ui.followUp.mode)与人格(PersonaUi.followUpMode)共用这一份。 */
4
+ export declare const FOLLOW_UP_MODES: readonly ["off", "static", "llm"];
5
+ export type FollowUpMode = (typeof FOLLOW_UP_MODES)[number];
6
+ /** 图标语义槽白名单:键是平台定义的槽名,不是组件名。新增视觉件时在这里登记。 */
7
+ export declare const ICON_SLOTS: readonly ["attachment"];
8
+ /**
9
+ * 校验并规范化 `branding.ui`(图标值 + 下一步建议配置)。
10
+ *
11
+ * 分级与人格 ui 同一套口径:未知键 / 形状错 = 启动期 fail-fast(manifest 是签入文件,
12
+ * 错别字必须响);单个图标值非法(如非 http(s) 的 url: 前缀)= 丢弃该键回落默认,不因
13
+ * 一个坏图标让服务起不来。返回 undefined 表示产品没配(或全被丢弃)。
14
+ */
15
+ export declare function parseBrandingUi(file: string, at: string, raw: unknown): BrandingUi | undefined;
16
+ export {};
@@ -0,0 +1,119 @@
1
+ /** 「下一步建议」的三态。全局(branding.ui.followUp.mode)与人格(PersonaUi.followUpMode)共用这一份。 */
2
+ export const FOLLOW_UP_MODES = ["off", "static", "llm"];
3
+ /** 图标语义槽白名单:键是平台定义的槽名,不是组件名。新增视觉件时在这里登记。 */
4
+ export const ICON_SLOTS = ["attachment"];
5
+ const FOLLOW_UP_KEYS = ["mode", "count", "static", "systemPrompt", "maxMessages", "timeoutMs"];
6
+ const MAX_ICON_VALUE = 512;
7
+ const MAX_STATIC_ITEMS = 10;
8
+ const MAX_STATIC_CHARS = 200;
9
+ const MAX_PROMPT_CHARS = 2000;
10
+ const MAX_COUNT = 5;
11
+ const MAX_MESSAGES = 20;
12
+ const MAX_TIMEOUT_MS = 30_000;
13
+ function deny(file, msg) {
14
+ throw new Error(`Invalid manifest ${file}: ${msg}`);
15
+ }
16
+ function isRecord(v) {
17
+ return !!v && typeof v === "object" && !Array.isArray(v);
18
+ }
19
+ function isMode(v) {
20
+ return typeof v === "string" && FOLLOW_UP_MODES.includes(v);
21
+ }
22
+ /**
23
+ * 校验并规范化 `branding.ui`(图标值 + 下一步建议配置)。
24
+ *
25
+ * 分级与人格 ui 同一套口径:未知键 / 形状错 = 启动期 fail-fast(manifest 是签入文件,
26
+ * 错别字必须响);单个图标值非法(如非 http(s) 的 url: 前缀)= 丢弃该键回落默认,不因
27
+ * 一个坏图标让服务起不来。返回 undefined 表示产品没配(或全被丢弃)。
28
+ */
29
+ export function parseBrandingUi(file, at, raw) {
30
+ if (raw === undefined)
31
+ return undefined;
32
+ if (!isRecord(raw))
33
+ deny(file, `\`${at}\` must be a mapping`);
34
+ const src = raw;
35
+ for (const key of Object.keys(src)) {
36
+ if (key !== "icons" && key !== "followUp") {
37
+ deny(file, `\`${at}.${key}\` is not a branding ui field (allowed: icons, followUp)`);
38
+ }
39
+ }
40
+ let icons;
41
+ if (src.icons !== undefined) {
42
+ if (!isRecord(src.icons))
43
+ deny(file, `\`${at}.icons\` must be a mapping`);
44
+ const srcIcons = src.icons;
45
+ for (const [key, value] of Object.entries(srcIcons)) {
46
+ if (!ICON_SLOTS.includes(key)) {
47
+ deny(file, `\`${at}.icons.${key}\` is not a known icon slot (allowed: ${ICON_SLOTS.join(", ")})`);
48
+ }
49
+ if (typeof value !== "string" || value.trim() === "") {
50
+ deny(file, `\`${at}.icons.${key}\` must be a non-empty string`);
51
+ }
52
+ if (value.length > MAX_ICON_VALUE) {
53
+ deny(file, `\`${at}.icons.${key}\` must be at most ${MAX_ICON_VALUE} characters`);
54
+ }
55
+ // url: 前缀只放行 http(s);别的协议(如 javascript:)丢弃该键回落默认,不 fail。
56
+ if (value.startsWith("url:") && !/^url:https?:\/\/\S+$/i.test(value))
57
+ continue;
58
+ (icons ??= {})[key] = value;
59
+ }
60
+ if (icons && Object.keys(icons).length === 0)
61
+ icons = undefined;
62
+ }
63
+ let followUp;
64
+ if (src.followUp !== undefined) {
65
+ if (!isRecord(src.followUp))
66
+ deny(file, `\`${at}.followUp\` must be a mapping`);
67
+ const fu = src.followUp;
68
+ for (const key of Object.keys(fu)) {
69
+ if (!FOLLOW_UP_KEYS.includes(key)) {
70
+ deny(file, `\`${at}.followUp.${key}\` is not a known field (allowed: ${FOLLOW_UP_KEYS.join(", ")})`);
71
+ }
72
+ }
73
+ followUp = {};
74
+ if (fu.mode !== undefined) {
75
+ if (!isMode(fu.mode))
76
+ deny(file, `\`${at}.followUp.mode\` must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
77
+ followUp.mode = fu.mode;
78
+ }
79
+ if (fu.count !== undefined) {
80
+ const n = fu.count;
81
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_COUNT) {
82
+ deny(file, `\`${at}.followUp.count\` must be an integer between 1 and ${MAX_COUNT}`);
83
+ }
84
+ followUp.count = n;
85
+ }
86
+ if (fu.static !== undefined) {
87
+ const list = fu.static;
88
+ if (!Array.isArray(list) || list.length > MAX_STATIC_ITEMS || list.some((s) => typeof s !== "string" || !s.trim())) {
89
+ deny(file, `\`${at}.followUp.static\` must be a list of at most ${MAX_STATIC_ITEMS} non-empty strings`);
90
+ }
91
+ followUp.static = list.map((s) => (s.length > MAX_STATIC_CHARS ? s.slice(0, MAX_STATIC_CHARS) : s));
92
+ }
93
+ if (fu.systemPrompt !== undefined) {
94
+ if (typeof fu.systemPrompt !== "string" || fu.systemPrompt.trim() === "") {
95
+ deny(file, `\`${at}.followUp.systemPrompt\` must be a non-empty string`);
96
+ }
97
+ followUp.systemPrompt = fu.systemPrompt.length > MAX_PROMPT_CHARS ? fu.systemPrompt.slice(0, MAX_PROMPT_CHARS) : fu.systemPrompt;
98
+ }
99
+ if (fu.maxMessages !== undefined) {
100
+ const n = fu.maxMessages;
101
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_MESSAGES) {
102
+ deny(file, `\`${at}.followUp.maxMessages\` must be an integer between 1 and ${MAX_MESSAGES}`);
103
+ }
104
+ followUp.maxMessages = n;
105
+ }
106
+ if (fu.timeoutMs !== undefined) {
107
+ const n = fu.timeoutMs;
108
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_TIMEOUT_MS) {
109
+ deny(file, `\`${at}.followUp.timeoutMs\` must be an integer between 1 and ${MAX_TIMEOUT_MS}`);
110
+ }
111
+ followUp.timeoutMs = n;
112
+ }
113
+ if (Object.keys(followUp).length === 0)
114
+ followUp = undefined;
115
+ }
116
+ if (!icons && !followUp)
117
+ return undefined;
118
+ return { ...(icons ? { icons } : {}), ...(followUp ? { followUp } : {}) };
119
+ }
package/dist/manifest.js CHANGED
@@ -11,6 +11,7 @@ import path from "node:path";
11
11
  import { pathToFileURL } from "node:url";
12
12
  import { parse } from "yaml";
13
13
  import { DEFAULT_PERSONA_ID, PERSONA_UI_FIELDS } from "@njuptlzf/agent-chat-protocol";
14
+ import { FOLLOW_UP_MODES, parseBrandingUi } from "./branding-ui.js";
14
15
  const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
15
16
  const TIER_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
16
17
  const QUAL_LEVELS = ["junior", "middle", "senior"];
@@ -46,6 +47,15 @@ function loadPersonaUi(file, at, raw) {
46
47
  }
47
48
  out.suggestions = src.suggestions;
48
49
  }
50
+ // 循环外专用块(照抄 suggestions 的范式):字面量联合字段不能进上面的字符串循环,
51
+ // 否则 `out[key] = v` 会触发 TS「联合键写入取交集」编译错。
52
+ const fm = src.followUpMode;
53
+ if (fm !== undefined) {
54
+ if (typeof fm !== "string" || !FOLLOW_UP_MODES.includes(fm)) {
55
+ fail(file, `\`${at}.followUpMode\` must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
56
+ }
57
+ out.followUpMode = fm;
58
+ }
49
59
  return out;
50
60
  }
51
61
  /**
@@ -259,6 +269,9 @@ export function loadProduct(dir) {
259
269
  if (!raw.agent.model?.provider || !raw.agent.model?.id)
260
270
  fail(file, "`agent.model.provider` and `agent.model.id` are required");
261
271
  const manifest = raw;
272
+ // 视觉件与下一步建议配置():白名单校验 + 非法图标值宽容丢弃;规范化结果写回
273
+ // branding,让 `GET /api/branding` 的整体展开(server.ts `...branding`)自然带下去。
274
+ manifest.branding.ui = parseBrandingUi(file, "branding.ui", manifest.branding.ui);
262
275
  // 业务路由声明。与 tools.inline / extensions 同级信任(仓库内代码),但
263
276
  // 路径必须留在产品目录内——写 `../` 逃出去等于让 manifest 加载任意文件。
264
277
  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 } from "@njuptlzf/agent-chat-protocol";
17
+ import { FOLLOW_UP_MODES } from "./branding-ui.js";
17
18
  import { personaIdsOf } from "./manifest.js";
18
19
  export const PERSONA_CONFIG_FILENAME = "persona-config.json";
19
20
  const CACHE_TTL_MS = 1000;
@@ -177,6 +178,17 @@ function parseUi(raw, at, problems) {
177
178
  }
178
179
  continue;
179
180
  }
181
+ // 循环外专用块(与 manifest 的 loadPersonaUi 同款):字面量联合字段不能落进下面
182
+ // 的泛型字符串写,否则 `out[key] = value` 触发 TS「联合键写入取交集」编译错。
183
+ if (key === "followUpMode") {
184
+ if (typeof value !== "string" || !FOLLOW_UP_MODES.includes(value)) {
185
+ problems.push(`${at}.followUpMode must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
186
+ }
187
+ else {
188
+ out.followUpMode = value;
189
+ }
190
+ continue;
191
+ }
180
192
  if (typeof value !== "string" || value.trim() === "") {
181
193
  problems.push(`${at}.${key} must be a non-empty string`);
182
194
  continue;
package/dist/server.d.ts CHANGED
@@ -5,6 +5,7 @@ import { type AuthzLike } from "./authz.ts";
5
5
  import { type LoadedProduct, type ToolContext } from "./manifest.ts";
6
6
  import { type PersonaConfigStore } from "./persona-config.ts";
7
7
  import { type TrialInput, type TrialResult } from "./persona-trial.ts";
8
+ import { type SuggestionsRunner } from "./suggestions.ts";
8
9
  import { type CooldownRegistry } from "./model-failover.ts";
9
10
  import { type ModelConfigStore } from "./model-config.ts";
10
11
  import { type McpConfigStore } from "./mcp-config.ts";
@@ -53,6 +54,11 @@ export interface ServerDeps {
53
54
  * 测试注入替身,避免为了验证"旁路"而真的花钱。
54
55
  */
55
56
  trial?: (input: TrialInput) => Promise<TrialResult>;
57
+ /**
58
+ * 下一步建议生成器。omitted ⇒ 真调模型(`runSuggestions`);
59
+ * 测试注入替身,避免为了验证旁路而真的花钱。
60
+ */
61
+ suggestions?: SuggestionsRunner;
56
62
  /**
57
63
  * Optional 候选冷却表。omitted ⇒ 进程级默认实例(重启清空、不进 DB);
58
64
  * 测试注入自己的实例以隔离。
package/dist/server.js CHANGED
@@ -6,6 +6,7 @@ import { createEventMapper, createRunAccounting } from "./events.js";
6
6
  import { agentFor, personaIdsOf } from "./manifest.js";
7
7
  import { appendVersion, effectivePersonaVersion, PROMPT_MAX_CHARS, savePersonaConfig, validatePersona, versionEntry, versionsOf } from "./persona-config.js";
8
8
  import { runPersonaTrial, TRIAL_MAX_INPUT_CHARS } from "./persona-trial.js";
9
+ import { runSuggestions, clipMessages, SUGGESTIONS_DEFAULTS } from "./suggestions.js";
9
10
  import { MODEL_SWITCH } from "./audit.js";
10
11
  import { FAILOVER_NOTICE, candidateKey, isRetryableModelError, orderChain, processCooldown, rawModelError } from "./model-failover.js";
11
12
  import { resolveChain, resolveRunTier, saveModelConfig } from "./model-config.js";
@@ -899,6 +900,8 @@ async function handleAdminPersonas(deps, req, res, url, acting) {
899
900
  problems: cfg.problems,
900
901
  // 默认助手的 id:页面用它在列表里显示「默认助手」并区分展示字段的落点。
901
902
  defaultPersona: product.defaultPersona,
903
+ // 下一步建议的全局模式(只读):全局 off 是硬地板,页面据此禁用人格级下拉。
904
+ globalFollowUpMode: product.manifest.branding.ui?.followUp?.mode ?? "llm",
902
905
  personas: ids.map((id) => {
903
906
  const override = cfg.personas[id];
904
907
  // 生效文案(含运行时覆盖)——列表徽标与名称要用"用户看到的",不是 manifest 原文。
@@ -1874,6 +1877,55 @@ export function createChatServer(deps) {
1874
1877
  }
1875
1878
  if (req.method === "POST" && url.pathname === "/api/chat")
1876
1879
  return await handleChat(req, res);
1880
+ if (req.method === "POST" && url.pathname === "/api/suggestions") {
1881
+ const auth = await deps.authenticate(req);
1882
+ if (!auth)
1883
+ return deny401(deps, req, res);
1884
+ let body;
1885
+ try {
1886
+ body = (await readJson(req));
1887
+ }
1888
+ catch {
1889
+ return sendError(res, 400, "bad_request", "body must be valid JSON under 64KB");
1890
+ }
1891
+ // 人格 id 合法性与 /api/chat 同一条规矩(400,不静默)。默认助手也显式带 id:
1892
+ // 这里没有会话绑定,服务端要按同一个 id 复核人格级覆盖。
1893
+ if (body.persona !== undefined &&
1894
+ (typeof body.persona !== "string" || !personaIdsOf(deps.product).has(body.persona))) {
1895
+ return sendError(res, 400, "bad_request", `unknown persona "${String(body.persona)}"`);
1896
+ }
1897
+ const personaId = (typeof body.persona === "string" ? body.persona : undefined) ?? deps.product.defaultPersona;
1898
+ const followUp = deps.product.manifest.branding.ui?.followUp;
1899
+ // 生效模式(前后端同一套优先级):全局 off 是硬地板——人格不能把全局关闭
1900
+ // 重新打开;否则人格 followUpMode > 全局 mode > 缺省 llm。
1901
+ const globalMode = followUp?.mode ?? "llm";
1902
+ if (globalMode === "off")
1903
+ return sendJson(res, 200, { suggestions: [] });
1904
+ const personaMode = effectiveUiOf(deps.product, deps.personaConfig?.get(), personaId)?.followUpMode;
1905
+ const mode = personaMode ?? globalMode;
1906
+ const count = followUp?.count ?? SUGGESTIONS_DEFAULTS.count;
1907
+ const staticFallback = Array.isArray(followUp?.static) ? followUp.static : [];
1908
+ if (mode === "off")
1909
+ return sendJson(res, 200, { suggestions: [] });
1910
+ if (mode === "static")
1911
+ return sendJson(res, 200, { suggestions: staticFallback.slice(0, count) });
1912
+ // llm:这是一轮问答的附属产物,任何失败(模型不可用/超时/输入非法)都静默
1913
+ // 回落 static——绝不 4xx/5xx 冒泡,也不接配额与计费。
1914
+ let suggestions = staticFallback.slice(0, count);
1915
+ try {
1916
+ suggestions = (await (deps.suggestions ?? runSuggestions)({ product: deps.product, modelRuntime: deps.modelRuntime }, {
1917
+ messages: clipMessages(body.messages, followUp?.maxMessages ?? SUGGESTIONS_DEFAULTS.maxMessages),
1918
+ count,
1919
+ staticFallback,
1920
+ ...(followUp?.systemPrompt !== undefined ? { systemPrompt: followUp.systemPrompt } : {}),
1921
+ timeoutMs: followUp?.timeoutMs ?? SUGGESTIONS_DEFAULTS.timeoutMs,
1922
+ })).slice(0, count);
1923
+ }
1924
+ catch {
1925
+ // 静默:回落内容已在初始值里。
1926
+ }
1927
+ return sendJson(res, 200, { suggestions });
1928
+ }
1877
1929
  if (req.method === "POST" && url.pathname === "/api/decision") {
1878
1930
  const auth = await deps.authenticate(req);
1879
1931
  if (!auth)
package/dist/session.js CHANGED
@@ -445,7 +445,8 @@ export async function createProductSession(opts) {
445
445
  },
446
446
  ]
447
447
  : [];
448
- // scopedMemory (, plan B; vendored copy at 0.2.0): one factory per session,
448
+ // scopedMemory (plan B; npm 版本消费,正本在 github.com/njuptlzf/pi-scoped-memory):
449
+ // one factory per session,
449
450
  // pointed at the tenant/scope directory the host computes. The plugin itself only
450
451
  // knows a directory — no userId/scope inside it, so it stays open-sourceable
451
452
  // without business knowledge. `qual || "default"` keeps single-track products
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 「下一步建议」的生成层:一轮对话结束后,把最近的**文本**消息拍平交给产品
3
+ * 默认模型,产出 N 条用户可能发出的简短追问。
4
+ *
5
+ * 定位与 `persona-trial` 不同:这是 run 结束后的附属产物——不建会话、不走 SSE、
6
+ * 不接配额与计费、不写 runLog。调用方(server.ts 路由)负责按人格复核生效模式,
7
+ * 并在**任何失败**时回落 `branding.ui.followUp.static`,绝不 4xx/5xx 冒泡。
8
+ *
9
+ * 与 `@assistant-ui/react` 的接法:前端实现自定义 `SuggestionAdapter.generate`
10
+ * 直接发结构化 messages(库自带的 `createSuggestionAdapter` 会把消息拍成单个
11
+ * prompt 字符串,服务端无法按 role 分离、无法强制中文指令,裁剪也不可测)。
12
+ */
13
+ import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
14
+ import { type LoadedProduct } from "./manifest.ts";
15
+ /** 裁剪后的单条对话消息:只有文本,图片/附件/工具细节从不离开前端。 */
16
+ export interface ClippedMessage {
17
+ role: "user" | "assistant";
18
+ text: string;
19
+ }
20
+ /** 生成层的输入。`personaId` 由路由用于复核生效模式,生成层本身不用它。 */
21
+ export interface SuggestionsInput {
22
+ messages: ClippedMessage[];
23
+ count: number;
24
+ /** 生成失败时的回落内容(`branding.ui.followUp.static`)。 */
25
+ staticFallback: string[];
26
+ /** 覆盖内置生成指令(`branding.ui.followUp.systemPrompt`)。 */
27
+ systemPrompt?: string;
28
+ timeoutMs: number;
29
+ }
30
+ /** 生成层的依赖。真实现读 `deps.modelRuntime`;测试注入替身避免真花钱。 */
31
+ export interface SuggestionsEnv {
32
+ product: LoadedProduct;
33
+ modelRuntime: ModelRuntime;
34
+ }
35
+ export type SuggestionsRunner = (env: SuggestionsEnv, input: SuggestionsInput) => Promise<string[]>;
36
+ /**
37
+ * 缺省值与硬上限。前端 `followUpConfigOf` 各持一份同名缺省(两个包不共享模块,
38
+ * 单测钉住两边一致)——改这里要同步那边。
39
+ */
40
+ export declare const SUGGESTIONS_DEFAULTS: {
41
+ readonly count: 3;
42
+ readonly maxMessages: 10;
43
+ readonly timeoutMs: 8000;
44
+ readonly maxTokens: 200;
45
+ /** 单条消息文本上限(超出截断)。 */
46
+ readonly messageChars: 500;
47
+ /** 整段对话字符上限(从最新往回收)。 */
48
+ readonly totalChars: 4000;
49
+ /** 单条建议字符上限。 */
50
+ readonly suggestionChars: 80;
51
+ };
52
+ /** 模型回复 → 建议列表:按行拆、去编号前缀、去空行、截到 count 条。 */
53
+ export declare function parseSuggestions(text: string, count: number): string[];
54
+ /**
55
+ * 服务端强制的输入裁剪——前端已裁一道,这里是权威层:
56
+ * 只留 user/assistant 的非空文本、单条截断、取最近 maxMessages 条、整段不超 totalChars。
57
+ */
58
+ export declare function clipMessages(raw: unknown, maxMessages: number): ClippedMessage[];
59
+ /** 真调模型。任何失败都抛给路由(统一 catch 后回落 static)。 */
60
+ export declare function runSuggestions(env: SuggestionsEnv, input: SuggestionsInput): Promise<string[]>;
@@ -0,0 +1,107 @@
1
+ import { resolveTier } from "./manifest.js";
2
+ /**
3
+ * 缺省值与硬上限。前端 `followUpConfigOf` 各持一份同名缺省(两个包不共享模块,
4
+ * 单测钉住两边一致)——改这里要同步那边。
5
+ */
6
+ export const SUGGESTIONS_DEFAULTS = {
7
+ count: 3,
8
+ maxMessages: 10,
9
+ timeoutMs: 8000,
10
+ maxTokens: 200,
11
+ /** 单条消息文本上限(超出截断)。 */
12
+ messageChars: 500,
13
+ /** 整段对话字符上限(从最新往回收)。 */
14
+ totalChars: 4000,
15
+ /** 单条建议字符上限。 */
16
+ suggestionChars: 80,
17
+ };
18
+ /** 内置生成指令:中性、产品无关;`followUp.systemPrompt` 可整体覆盖。 */
19
+ function defaultSystemPrompt(count) {
20
+ return (`根据下面这段用户与助手的对话,推测用户接下来最可能发出的 ${count} 条简短追问。` +
21
+ "每行一条:不要编号、不要任何解释或前后缀,不要复述对话内容,每条不超过 30 个字。");
22
+ }
23
+ const NUMBERED = /^\s*(?:\d{1,3}[.)、]|[•*·-])\s*/;
24
+ /** 模型回复 → 建议列表:按行拆、去编号前缀、去空行、截到 count 条。 */
25
+ export function parseSuggestions(text, count) {
26
+ const cap = Math.max(1, Math.min(count, 20));
27
+ const out = [];
28
+ for (const line of text.split(/\r?\n/)) {
29
+ const s = line.replace(NUMBERED, "").trim();
30
+ if (!s)
31
+ continue;
32
+ out.push(s.length > SUGGESTIONS_DEFAULTS.suggestionChars ? s.slice(0, SUGGESTIONS_DEFAULTS.suggestionChars) : s);
33
+ if (out.length >= cap)
34
+ break;
35
+ }
36
+ return out;
37
+ }
38
+ /**
39
+ * 服务端强制的输入裁剪——前端已裁一道,这里是权威层:
40
+ * 只留 user/assistant 的非空文本、单条截断、取最近 maxMessages 条、整段不超 totalChars。
41
+ */
42
+ export function clipMessages(raw, maxMessages) {
43
+ if (!Array.isArray(raw))
44
+ return [];
45
+ const kept = [];
46
+ for (const entry of raw) {
47
+ if (!entry || typeof entry !== "object")
48
+ continue;
49
+ const role = entry.role;
50
+ const text = entry.text;
51
+ if ((role !== "user" && role !== "assistant") || typeof text !== "string")
52
+ continue;
53
+ const trimmed = text.trim();
54
+ if (!trimmed)
55
+ continue;
56
+ kept.push({ role, text: trimmed.slice(0, SUGGESTIONS_DEFAULTS.messageChars) });
57
+ }
58
+ const window = kept.slice(-Math.max(1, maxMessages));
59
+ let total = 0;
60
+ const out = [];
61
+ for (let i = window.length - 1; i >= 0; i--) {
62
+ total += window[i].text.length;
63
+ if (total > SUGGESTIONS_DEFAULTS.totalChars)
64
+ break;
65
+ out.unshift(window[i]);
66
+ }
67
+ return out;
68
+ }
69
+ /** 真调模型。任何失败都抛给路由(统一 catch 后回落 static)。 */
70
+ export async function runSuggestions(env, input) {
71
+ // 模型来源与建会话同源(manifest `agent.model`);model-config 的档位链是聊天主链
72
+ // 的东西,这条旁路不参与——失败静默,不值得为它引一整套 failover。
73
+ const tier = resolveTier(env.product);
74
+ if (!tier)
75
+ throw new Error("product has no default model");
76
+ const model = env.modelRuntime.getModel(tier.provider, tier.model);
77
+ if (!model)
78
+ throw new Error(`unknown model ${tier.provider}/${tier.model}`);
79
+ const dialogue = input.messages.map((m) => `${m.role}: ${m.text}`).join("\n");
80
+ const systemPrompt = input.systemPrompt?.trim() || defaultSystemPrompt(input.count);
81
+ const controller = new AbortController();
82
+ let timer;
83
+ try {
84
+ // 双保险:signal 传进 provider 请求;不遵守 signal 的底层由 Promise.race 兜底超时。
85
+ const timeout = new Promise((_, reject) => {
86
+ timer = setTimeout(() => {
87
+ controller.abort();
88
+ reject(new Error("suggestions timeout"));
89
+ }, Math.max(1, input.timeoutMs));
90
+ });
91
+ // 只构造一条 UserMessage 把对话拍平——AssistantMessage 必填字段太多,别手工造。
92
+ const reply = await Promise.race([
93
+ env.modelRuntime.completeSimple(model, { systemPrompt, messages: [{ role: "user", content: `最近一段对话:\n${dialogue}`, timestamp: Date.now() }] }, { signal: controller.signal, maxTokens: SUGGESTIONS_DEFAULTS.maxTokens }),
94
+ timeout,
95
+ ]);
96
+ const parts = [];
97
+ for (const c of reply.content) {
98
+ if (c.type === "text")
99
+ parts.push(c.text);
100
+ }
101
+ return parseSuggestions(parts.join("\n"), input.count);
102
+ }
103
+ finally {
104
+ if (timer !== undefined)
105
+ clearTimeout(timer);
106
+ }
107
+ }
package/package.json CHANGED
@@ -1,64 +1,64 @@
1
- {
2
- "name": "@njuptlzf/agent-chat-server",
3
- "version": "0.2.1",
4
- "description": "agentChat platform kernel: sessions, authz, billing, audit, model/MCP/persona config planes, and the product-directory loader.",
5
- "type": "module",
6
- "license": "Apache-2.0",
7
- "main": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
- "bin": {
10
- "agentchat-integrate": "./scripts/agentchat-integrate.mjs"
11
- },
12
- "exports": {
13
- ".": {
14
- "agent-chat-source": "./src/index.ts",
15
- "types": "./dist/index.d.ts",
16
- "default": "./dist/index.js"
17
- },
18
- "./main": {
19
- "agent-chat-source": "./src/main.ts",
20
- "default": "./dist/main.js"
21
- },
22
- "./testing": {
23
- "agent-chat-source": "./src/testing.ts",
24
- "types": "./dist/testing.d.ts",
25
- "default": "./dist/testing.js"
26
- },
27
- "./package.json": "./package.json"
28
- },
29
- "files": [
30
- "dist",
31
- "src",
32
- "scripts/agentchat-integrate.mjs"
33
- ],
34
- "repository": {
35
- "type": "git",
36
- "url": "git+https://github.com/njuptlzf/agent-chat.git",
37
- "directory": "packages/server"
38
- },
39
- "bugs": {
40
- "url": "https://github.com/njuptlzf/agent-chat/issues"
41
- },
42
- "homepage": "https://github.com/njuptlzf/agent-chat#readme",
43
- "keywords": [
44
- "agent-chat",
45
- "chat-server",
46
- "authz",
47
- "billing",
48
- "audit"
49
- ],
50
- "engines": {
51
- "node": ">=22.13"
52
- },
53
- "publishConfig": {
54
- "access": "public"
55
- },
56
- "dependencies": {
57
- "@njuptlzf/agent-chat-protocol": "^0.2.0",
58
- "@earendil-works/pi-coding-agent": "1.2.0",
59
- "casbin": "^5.51.1",
60
- "typebox": "^1.3.27",
61
- "yaml": "^2.8.0",
62
- "pi-scoped-memory": "^0.3.0"
63
- }
64
- }
1
+ {
2
+ "name": "@njuptlzf/agent-chat-server",
3
+ "version": "0.3.0",
4
+ "description": "agentChat platform kernel: sessions, authz, billing, audit, model/MCP/persona config planes, and the product-directory loader.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "bin": {
10
+ "agentchat-integrate": "./scripts/agentchat-integrate.mjs"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "agent-chat-source": "./src/index.ts",
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "./main": {
19
+ "agent-chat-source": "./src/main.ts",
20
+ "default": "./dist/main.js"
21
+ },
22
+ "./testing": {
23
+ "agent-chat-source": "./src/testing.ts",
24
+ "types": "./dist/testing.d.ts",
25
+ "default": "./dist/testing.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "src",
32
+ "scripts/agentchat-integrate.mjs"
33
+ ],
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/njuptlzf/agent-chat.git",
37
+ "directory": "packages/server"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/njuptlzf/agent-chat/issues"
41
+ },
42
+ "homepage": "https://github.com/njuptlzf/agent-chat#readme",
43
+ "keywords": [
44
+ "agent-chat",
45
+ "chat-server",
46
+ "authz",
47
+ "billing",
48
+ "audit"
49
+ ],
50
+ "engines": {
51
+ "node": ">=22.13"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "dependencies": {
57
+ "@njuptlzf/agent-chat-protocol": "^0.3.0",
58
+ "@earendil-works/pi-coding-agent": "1.2.0",
59
+ "casbin": "^5.51.1",
60
+ "typebox": "^1.3.27",
61
+ "yaml": "^2.8.0",
62
+ "pi-scoped-memory": "^0.3.0"
63
+ }
64
+ }
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
  /**
3
3
  * agentchat-integrate —— 「一句话对接 agentChat」的机械入口。
4
4
  *
@@ -20,7 +20,7 @@ import { createRequire } from "node:module";
20
20
  import { spawnSync } from "node:child_process";
21
21
  import process from "node:process";
22
22
 
23
- const CLI_VERSION = "0.2.0";
23
+ const CLI_VERSION = "0.3.0";
24
24
  const MIN_SERVER = "0.2.0";
25
25
  const PKG = {
26
26
  protocol: "@njuptlzf/agent-chat-protocol",
@@ -215,9 +215,9 @@ function packageTemplate(o) {
215
215
  private: true,
216
216
  type: "module",
217
217
  dependencies: {
218
- [PKG.protocol]: "^0.2.0",
219
- [PKG.server]: "^0.2.0",
220
- [PKG.web]: "^0.2.0",
218
+ [PKG.protocol]: "^0.3.0",
219
+ [PKG.server]: "^0.3.0",
220
+ [PKG.web]: "^0.3.0",
221
221
  },
222
222
  devDependencies: {
223
223
  tsx: "^4.20.0",
@@ -408,7 +408,7 @@ function checkDeps(add, dir) {
408
408
  const all = { ...(pj.dependencies ?? {}), ...(pj.devDependencies ?? {}) };
409
409
  const missing = Object.values(PKG).filter((n) => !(n in all));
410
410
  if (missing.length) add("FAIL", "deps", `未声明平台依赖:${missing.join("、")}`,
411
- `npm i ${PKG.protocol}@^0.2.0 ${PKG.server}@^0.2.0 ${PKG.web}@^0.2.0`);
411
+ `npm i ${PKG.protocol}@^0.3.0 ${PKG.server}@^0.3.0 ${PKG.web}@^0.3.0`);
412
412
  else add("OK", "deps", "三个平台包依赖已声明");
413
413
 
414
414
  try {