@njuptlzf/agent-chat-web 0.1.0 → 0.2.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.
Files changed (81) hide show
  1. package/dist/AgentChat.d.ts +28 -0
  2. package/dist/AgentChat.js +355 -0
  3. package/dist/AgentChatApp.d.ts +31 -0
  4. package/dist/AgentChatApp.js +90 -0
  5. package/dist/DockPanel.d.ts +22 -0
  6. package/dist/DockPanel.js +22 -0
  7. package/dist/PersonasPage.d.ts +1 -0
  8. package/dist/PersonasPage.js +318 -0
  9. package/dist/adapter.d.ts +52 -0
  10. package/dist/adapter.js +242 -0
  11. package/dist/app-def-check.d.ts +50 -0
  12. package/dist/app-def-check.js +184 -0
  13. package/dist/app.d.ts +112 -0
  14. package/dist/app.js +174 -0
  15. package/dist/auth.d.ts +41 -0
  16. package/dist/auth.js +86 -0
  17. package/dist/dock.d.ts +52 -0
  18. package/dist/dock.js +132 -0
  19. package/dist/docs.d.ts +48 -0
  20. package/dist/docs.js +178 -0
  21. package/dist/index.d.ts +17 -0
  22. package/dist/index.js +8 -0
  23. package/dist/mount.d.ts +50 -0
  24. package/dist/mount.js +38 -0
  25. package/dist/qual.d.ts +21 -0
  26. package/dist/qual.js +53 -0
  27. package/dist/sse.d.ts +14 -0
  28. package/dist/sse.js +99 -0
  29. package/dist/styles.css +1478 -0
  30. package/dist/theme.d.ts +10 -0
  31. package/dist/theme.js +14 -0
  32. package/dist/ui/CodeCopyHeader.d.ts +7 -0
  33. package/dist/ui/CodeCopyHeader.js +22 -0
  34. package/dist/ui/ConfirmCard.d.ts +15 -0
  35. package/dist/ui/ConfirmCard.js +9 -0
  36. package/dist/ui/Lightbox.d.ts +6 -0
  37. package/dist/ui/Lightbox.js +31 -0
  38. package/dist/ui/QueueBar.d.ts +44 -0
  39. package/dist/ui/QueueBar.js +17 -0
  40. package/dist/ui/Splitter.d.ts +27 -0
  41. package/dist/ui/Splitter.js +61 -0
  42. package/dist/ui/ThemeToggle.d.ts +2 -0
  43. package/dist/ui/ThemeToggle.js +16 -0
  44. package/dist/ui/TierPicker.d.ts +14 -0
  45. package/dist/ui/TierPicker.js +54 -0
  46. package/dist/ui/UIPromptCard.d.ts +17 -0
  47. package/dist/ui/UIPromptCard.js +18 -0
  48. package/dist/ui/timefmt.d.ts +35 -0
  49. package/dist/ui/timefmt.js +110 -0
  50. package/dist/ui/useNarrow.d.ts +7 -0
  51. package/dist/ui/useNarrow.js +15 -0
  52. package/package.json +72 -68
  53. package/src/App.tsx +13 -0
  54. package/src/agent-chat/AgentChat.tsx +692 -692
  55. package/src/agent-chat/AgentChatApp.tsx +206 -206
  56. package/src/agent-chat/{Dock.tsx → DockPanel.tsx} +73 -73
  57. package/src/agent-chat/PersonasPage.tsx +678 -678
  58. package/src/agent-chat/adapter.ts +272 -272
  59. package/src/agent-chat/app-def-check.ts +215 -215
  60. package/src/agent-chat/app.tsx +327 -327
  61. package/src/agent-chat/auth.ts +83 -83
  62. package/src/agent-chat/dock.ts +161 -161
  63. package/src/agent-chat/docs.ts +179 -179
  64. package/src/agent-chat/index.ts +17 -17
  65. package/src/agent-chat/mount.tsx +123 -123
  66. package/src/agent-chat/qual.ts +55 -55
  67. package/src/agent-chat/sse.ts +104 -104
  68. package/src/agent-chat/theme.ts +23 -23
  69. package/src/agent-chat/ui/CodeCopyHeader.tsx +29 -29
  70. package/src/agent-chat/ui/ConfirmCard.tsx +32 -32
  71. package/src/agent-chat/ui/Lightbox.tsx +32 -32
  72. package/src/agent-chat/ui/QueueBar.tsx +70 -70
  73. package/src/agent-chat/ui/Splitter.tsx +81 -81
  74. package/src/agent-chat/ui/ThemeToggle.tsx +25 -25
  75. package/src/agent-chat/ui/TierPicker.tsx +112 -112
  76. package/src/agent-chat/ui/UIPromptCard.tsx +68 -68
  77. package/src/agent-chat/ui/timefmt.ts +110 -110
  78. package/src/agent-chat/ui/useNarrow.ts +20 -20
  79. package/src/fake-product/entry.tsx +54 -0
  80. package/src/main.tsx +8 -0
  81. package/src/styles.css +1478 -1478
package/dist/dock.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * 全局聊天坞(agentChat Dock)的状态。
3
+ *
4
+ * 三种形态:
5
+ * - `docked` 宽屏默认:贴右缘、挤压业务内容区;
6
+ * - `floating` 悬浮面板,不改变业务布局(窄屏首选);
7
+ * - `closed` 收起成右缘一条竖排唤回按钮。
8
+ * 「聊天」路由(#/<默认路由>)不是第四种形态,它是把坞撑满内容区的用法,由路由决定,
9
+ * 因此不在这里存——少一份要同步的状态。
10
+ *
11
+ * 业务页只通过 `sendToChat()` / `useDockMode()` 与它交互,不再 iframe/postMessage。
12
+ */
13
+ export type DockMode = "closed" | "docked" | "floating";
14
+ /** 打开态(不含 closed),收起后要记住它以便原样唤回。 */
15
+ export type DockOpen = Exclude<DockMode, "closed">;
16
+ /** 宽屏默认挤压式常驻;窄屏没有余量,先收起,需要时由业务页唤出悬浮。 */
17
+ export declare function defaultMode(wide: boolean): DockMode;
18
+ /** 记忆值合法才用(损坏的 localStorage 不能把布局带坏),否则回落默认。 */
19
+ export declare function resolveMode(stored: string | null, wide: boolean): DockMode;
20
+ /** 收起态被唤醒时该用哪种打开态:记住上次的,没记忆就按屏宽给默认。 */
21
+ export declare function reopenMode(mode: DockMode, last: DockOpen, wide: boolean): DockOpen;
22
+ export declare const dockStore: {
23
+ subscribe(fn: () => void): () => void;
24
+ mode(): DockMode;
25
+ lastOpen(): DockOpen;
26
+ running(): boolean;
27
+ setMode(next: DockMode): void;
28
+ setRunning(next: boolean): void;
29
+ };
30
+ /** 当前坞形态(响应式)。
31
+ * `wide` 由调用方传入,避免这里再挂一个 matchMedia 监听——路由层已经知道屏宽了。
32
+ * 实际取值在首次渲染时由 `ensureInit` 按真实屏宽定形。 */
33
+ export declare function useDockMode(): DockMode;
34
+ /** 坞里是否有对话正在跑(业务页跳转前要用它决定是否提示,见 C7)。 */
35
+ export interface ChatTask {
36
+ text: string;
37
+ context?: Record<string, unknown>;
38
+ }
39
+ type Sink = (task: ChatTask) => void;
40
+ /**
41
+ * 把一段话(连同页面上下文)投给对话。坞收起时会顺带唤出,对话组件随后
42
+ * 挂载并从队列里取走——所以业务页不需要关心坞当前开没开。
43
+ */
44
+ export declare function sendToChat(text: string, context?: Record<string, unknown>): void;
45
+ /** 对话组件登记消费端(返回注销函数,严格模式双挂载也安全)。 */
46
+ export declare function subscribeChat(fn: Sink): () => void;
47
+ /**
48
+ * 换会话 / 换选项会丢掉正在跑的那一轮回答,动手前先问一句。
49
+ * 切业务路由**不是**打断(坞常驻、对话流不断),所以不在这里拦。
50
+ */
51
+ export declare function confirmInterrupt(what?: string, who?: string): boolean;
52
+ export {};
package/dist/dock.js ADDED
@@ -0,0 +1,132 @@
1
+ import { useSyncExternalStore } from "react";
2
+ const MODE_KEY = "dock.mode";
3
+ const LAST_KEY = "dock.last";
4
+ /** 宽屏默认挤压式常驻;窄屏没有余量,先收起,需要时由业务页唤出悬浮。 */
5
+ export function defaultMode(wide) {
6
+ return wide ? "docked" : "closed";
7
+ }
8
+ /** 记忆值合法才用(损坏的 localStorage 不能把布局带坏),否则回落默认。 */
9
+ export function resolveMode(stored, wide) {
10
+ return stored === "docked" || stored === "floating" || stored === "closed" ? stored : defaultMode(wide);
11
+ }
12
+ /** 收起态被唤醒时该用哪种打开态:记住上次的,没记忆就按屏宽给默认。 */
13
+ export function reopenMode(mode, last, wide) {
14
+ if (mode !== "closed")
15
+ return mode;
16
+ return last === "floating" || last === "docked" ? last : defaultMode(wide);
17
+ }
18
+ function read(key) {
19
+ try {
20
+ return localStorage.getItem(key);
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ function write(key, value) {
27
+ try {
28
+ localStorage.setItem(key, value);
29
+ }
30
+ catch {
31
+ /* 隐私模式写不进去只影响"记忆",不影响本次布局 */
32
+ }
33
+ }
34
+ const subs = new Set();
35
+ const wideNow = () => typeof window !== "undefined" && window.innerWidth > 1100;
36
+ let mode = "closed";
37
+ let last = "docked";
38
+ let running = false;
39
+ let initialised = false;
40
+ function emit() {
41
+ for (const fn of subs)
42
+ fn();
43
+ }
44
+ /** 首次访问时按屏宽+记忆定形(放在读取处而不是模块顶层,避免测试环境无 window)。 */
45
+ function ensureInit() {
46
+ if (initialised)
47
+ return;
48
+ initialised = true;
49
+ const storedLast = read(LAST_KEY);
50
+ if (storedLast === "docked" || storedLast === "floating")
51
+ last = storedLast;
52
+ mode = resolveMode(read(MODE_KEY), wideNow());
53
+ }
54
+ export const dockStore = {
55
+ subscribe(fn) {
56
+ subs.add(fn);
57
+ return () => subs.delete(fn);
58
+ },
59
+ mode() {
60
+ ensureInit();
61
+ return mode;
62
+ },
63
+ lastOpen() {
64
+ ensureInit();
65
+ return last;
66
+ },
67
+ running() {
68
+ return running;
69
+ },
70
+ setMode(next) {
71
+ ensureInit();
72
+ if (next !== "closed") {
73
+ last = next;
74
+ write(LAST_KEY, next);
75
+ }
76
+ if (next === mode)
77
+ return;
78
+ mode = next;
79
+ write(MODE_KEY, next);
80
+ emit();
81
+ },
82
+ setRunning(next) {
83
+ if (next === running)
84
+ return;
85
+ running = next;
86
+ emit();
87
+ },
88
+ };
89
+ /** 当前坞形态(响应式)。
90
+ * `wide` 由调用方传入,避免这里再挂一个 matchMedia 监听——路由层已经知道屏宽了。
91
+ * 实际取值在首次渲染时由 `ensureInit` 按真实屏宽定形。 */
92
+ export function useDockMode() {
93
+ return useSyncExternalStore(dockStore.subscribe, dockStore.mode, () => "closed");
94
+ }
95
+ let sink;
96
+ let queue = [];
97
+ /**
98
+ * 把一段话(连同页面上下文)投给对话。坞收起时会顺带唤出,对话组件随后
99
+ * 挂载并从队列里取走——所以业务页不需要关心坞当前开没开。
100
+ */
101
+ export function sendToChat(text, context) {
102
+ dockStore.setMode(reopenMode(dockStore.mode(), dockStore.lastOpen(), wideNow()));
103
+ const task = context ? { text, context } : { text };
104
+ if (sink)
105
+ sink(task);
106
+ else
107
+ queue.push(task);
108
+ }
109
+ /** 对话组件登记消费端(返回注销函数,严格模式双挂载也安全)。 */
110
+ export function subscribeChat(fn) {
111
+ sink = fn;
112
+ const pending = queue;
113
+ queue = [];
114
+ for (const t of pending)
115
+ fn(t);
116
+ return () => {
117
+ if (sink === fn)
118
+ sink = undefined;
119
+ };
120
+ }
121
+ /**
122
+ * 换会话 / 换选项会丢掉正在跑的那一轮回答,动手前先问一句。
123
+ * 切业务路由**不是**打断(坞常驻、对话流不断),所以不在这里拦。
124
+ */
125
+ export function confirmInterrupt(what = "切换", who = "助手") {
126
+ if (!running)
127
+ return true;
128
+ if (typeof window === "undefined")
129
+ return true;
130
+ // 助手的名字是产品事实:core 的默认说法是「助手」,产品传自己的叫法。
131
+ return window.confirm(`${who}正在回答,${what}会中断这一轮。继续?`);
132
+ }
package/dist/docs.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Browser-side document -> Markdown conversion (批 B4-A).
3
+ *
4
+ * Everything we send the model must be text, so the browser converts the
5
+ * user's file and the result travels as `ChatRequest.attachments`. The server
6
+ * parses nothing — that is the design decision this module exists for
7
+ * (the B5 design doc in docs/ records the server-side alternative).
8
+ *
9
+ * Accepted fidelity loss (user's call): text layers of pdf/docx/xlsx are
10
+ * extracted roughly linearly; layout, complex tables and scanned pages come
11
+ * out degraded, and an empty extraction is surfaced as an error instead of
12
+ * being sent. The heavy parsers are dynamically imported so the base bundle
13
+ * stays lean.
14
+ */
15
+ import type { ChatAttachment } from "@njuptlzf/agent-chat-protocol";
16
+ export declare const MAX_DOCS = 4;
17
+ /** Keep in sync with the server's MAX_ATTACHMENT_CHARS; the server is the gate. */
18
+ export declare const MAX_DOC_CHARS = 24000;
19
+ export type DocKind = "text" | "csv" | "pdf" | "docx" | "xlsx";
20
+ export declare function docKind(fileName: string): DocKind | undefined;
21
+ /** An attachment plus what the user needs to know about its conversion. */
22
+ export interface DocEntry extends ChatAttachment {
23
+ truncated: boolean;
24
+ }
25
+ /**
26
+ * Hard cap with a human-readable marker. The result stays under `cap` chars
27
+ * (marker included) so a client-capped document never trips the server check.
28
+ */
29
+ export declare function truncateDoc(text: string, cap?: number): {
30
+ text: string;
31
+ truncated: boolean;
32
+ };
33
+ /**
34
+ * The file-part carrier for the local runtime. The adapter re-reads these
35
+ * back into ChatRequest.attachments by mimeType, so "text/markdown" here
36
+ * means "converted document text" (data is the Markdown itself, not base64).
37
+ */
38
+ export declare function docPart(doc: ChatAttachment): {
39
+ type: "file";
40
+ filename: string;
41
+ mimeType: string;
42
+ data: string;
43
+ };
44
+ /** Rows -> Markdown table; every cell escaped so no pipe can forge a column. */
45
+ export declare function tableFromRows(rows: string[][]): string;
46
+ export declare function csvToMarkdown(text: string): string;
47
+ /** Convert one browser File to a sendable attachment. Throws with a user-readable message. */
48
+ export declare function fileToDoc(file: File): Promise<DocEntry>;
package/dist/docs.js ADDED
@@ -0,0 +1,178 @@
1
+ export const MAX_DOCS = 4;
2
+ /** Keep in sync with the server's MAX_ATTACHMENT_CHARS; the server is the gate. */
3
+ export const MAX_DOC_CHARS = 24_000;
4
+ const EXT_KIND = {
5
+ md: "text", markdown: "text", txt: "text", log: "text", json: "text",
6
+ yaml: "text", yml: "text", toml: "text", ini: "text",
7
+ csv: "csv", tsv: "csv",
8
+ pdf: "pdf",
9
+ docx: "docx",
10
+ xlsx: "xlsx", xlsm: "xlsx",
11
+ };
12
+ export function docKind(fileName) {
13
+ const dot = fileName.lastIndexOf(".");
14
+ if (dot < 0)
15
+ return undefined;
16
+ return EXT_KIND[fileName.slice(dot + 1).toLowerCase()];
17
+ }
18
+ /**
19
+ * Hard cap with a human-readable marker. The result stays under `cap` chars
20
+ * (marker included) so a client-capped document never trips the server check.
21
+ */
22
+ export function truncateDoc(text, cap = MAX_DOC_CHARS) {
23
+ const clean = text.trim();
24
+ if (clean.length <= cap)
25
+ return { text: clean, truncated: false };
26
+ const keep = cap - 100;
27
+ return {
28
+ text: `${clean.slice(0, keep)}\n\n…[已截断:原文 ${clean.length} 字符,只上传了前 ${keep} 字符]`,
29
+ truncated: true,
30
+ };
31
+ }
32
+ /**
33
+ * The file-part carrier for the local runtime. The adapter re-reads these
34
+ * back into ChatRequest.attachments by mimeType, so "text/markdown" here
35
+ * means "converted document text" (data is the Markdown itself, not base64).
36
+ */
37
+ export function docPart(doc) {
38
+ return { type: "file", filename: doc.name, mimeType: "text/markdown", data: doc.text };
39
+ }
40
+ /** Rows -> Markdown table; every cell escaped so no pipe can forge a column. */
41
+ export function tableFromRows(rows) {
42
+ if (rows.length === 0)
43
+ return "";
44
+ const esc = (v) => v.trim().replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
45
+ const width = rows.reduce((m, r) => Math.max(m, r.length), 0);
46
+ const grid = rows.map((r) => Array.from({ length: width }, (_, i) => esc(r[i] ?? "")));
47
+ const line = (cells) => `| ${cells.join(" | ")} |`;
48
+ return [line(grid[0]), line(grid[0].map(() => "---")), ...grid.slice(1).map(line)].join("\n");
49
+ }
50
+ /** Minimal quote-aware delimited-text parser with first-line delimiter sniffing. */
51
+ function parseDelimited(text) {
52
+ const src = text.replace(/\r\n?/g, "\n").replace(/\n$/, "");
53
+ const nl = src.indexOf("\n");
54
+ const firstLine = nl < 0 ? src : src.slice(0, nl);
55
+ const count = (d) => firstLine.split(d).length;
56
+ const delim = [",", "\t", ";"].reduce((a, b) => (count(b) > count(a) ? b : a), ",");
57
+ const rows = [];
58
+ let row = [];
59
+ let field = "";
60
+ let quoted = false;
61
+ for (let i = 0; i < src.length; i++) {
62
+ const c = src[i];
63
+ if (quoted) {
64
+ if (c === '"') {
65
+ if (src[i + 1] === '"') {
66
+ field += '"';
67
+ i++;
68
+ }
69
+ else
70
+ quoted = false;
71
+ }
72
+ else
73
+ field += c;
74
+ }
75
+ else if (c === '"')
76
+ quoted = true;
77
+ else if (c === delim) {
78
+ row.push(field);
79
+ field = "";
80
+ }
81
+ else if (c === "\n") {
82
+ row.push(field);
83
+ rows.push(row);
84
+ row = [];
85
+ field = "";
86
+ }
87
+ else
88
+ field += c;
89
+ }
90
+ row.push(field);
91
+ rows.push(row);
92
+ return rows.filter((r) => r.some((f) => f.trim() !== ""));
93
+ }
94
+ export function csvToMarkdown(text) {
95
+ return tableFromRows(parseDelimited(text));
96
+ }
97
+ let pdfWorkerConfigured = false;
98
+ async function pdfToMarkdown(data) {
99
+ const pdfjs = await import("pdfjs-dist");
100
+ if (!pdfWorkerConfigured) {
101
+ pdfWorkerConfigured = true;
102
+ const { default: workerUrl } = await import("pdfjs-dist/build/pdf.worker.min.mjs?url");
103
+ pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;
104
+ }
105
+ const doc = await pdfjs.getDocument({ data: new Uint8Array(data) }).promise;
106
+ const pages = [];
107
+ for (let i = 1; i <= doc.numPages; i++) {
108
+ const content = await (await doc.getPage(i)).getTextContent();
109
+ let text = "";
110
+ let lastY;
111
+ for (const item of content.items) {
112
+ if (!("str" in item))
113
+ continue;
114
+ const y = item.transform[5];
115
+ if (lastY !== undefined && Math.abs(y - lastY) > 4)
116
+ text += "\n";
117
+ text += item.str;
118
+ lastY = y;
119
+ }
120
+ pages.push(doc.numPages > 1 ? `【第 ${i} 页】\n${text.trim()}` : text.trim());
121
+ }
122
+ return pages.join("\n\n");
123
+ }
124
+ async function docxToMarkdown(data) {
125
+ const mammoth = (await import("mammoth")).default;
126
+ // The shipped lib/index.d.ts has not caught up with the runtime:
127
+ // convertToMarkdown exists (lib/index.js:14) but is not declared on the
128
+ // interface. Local cast instead of patching global types.
129
+ const convert = mammoth.convertToMarkdown;
130
+ const result = await convert({ arrayBuffer: data });
131
+ return result.value;
132
+ }
133
+ async function xlsxToMarkdown(data) {
134
+ const { Workbook } = await import("exceljs");
135
+ const wb = new Workbook();
136
+ await wb.xlsx.load(data);
137
+ const parts = [];
138
+ for (const ws of wb.worksheets) {
139
+ const rows = [];
140
+ ws.eachRow({ includeEmpty: false }, (row) => {
141
+ const cells = [];
142
+ row.eachCell({ includeEmpty: true }, (cell) => cells.push(cell.text));
143
+ rows.push(cells);
144
+ });
145
+ if (rows.length > 0)
146
+ parts.push(`【工作表 ${ws.name}】\n${tableFromRows(rows)}`);
147
+ }
148
+ return parts.join("\n\n");
149
+ }
150
+ /** Convert one browser File to a sendable attachment. Throws with a user-readable message. */
151
+ export async function fileToDoc(file) {
152
+ const kind = docKind(file.name);
153
+ if (!kind)
154
+ throw new Error(`暂不支持的文件类型:${file.name}`);
155
+ let raw;
156
+ switch (kind) {
157
+ case "text":
158
+ raw = await file.text();
159
+ break;
160
+ case "csv":
161
+ raw = csvToMarkdown(await file.text());
162
+ break;
163
+ case "pdf":
164
+ raw = await pdfToMarkdown(await file.arrayBuffer());
165
+ break;
166
+ case "docx":
167
+ raw = await docxToMarkdown(await file.arrayBuffer());
168
+ break;
169
+ case "xlsx":
170
+ raw = await xlsxToMarkdown(await file.arrayBuffer());
171
+ break;
172
+ }
173
+ // Empty extraction (scanned pdf, empty file) must not silently reach the model.
174
+ if (raw.trim() === "")
175
+ throw new Error(`未检出可提取文本(扫描件或空文件?):${file.name}`);
176
+ const t = truncateDoc(raw);
177
+ return { name: file.name, text: t.text, truncated: t.truncated };
178
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@njuptlzf/agent-chat-web` 的公共入口。
3
+ *
4
+ * 平台前端壳对外只有《[PUBLIC_API](../../../../docs/design/PUBLIC_API.md)》
5
+ * 登记的 13 项:产品 web 通过 `@njuptlzf/agent-chat-web` 取 `AppDef` / `HostCtx` /
6
+ * `AgentApp` 与几个 HTTP 小工具,不再走 `apps/web/src/agent-chat/*` 深路径。
7
+ * 壳内部(卡片槽、AppShell、面板)都是实现,随时可改。
8
+ */
9
+ export type { AppDef, HostCtx } from "./app.tsx";
10
+ export { apiHeaders, auth } from "./auth.ts";
11
+ export { sendToChat } from "./dock.ts";
12
+ export { AgentApp } from "./mount.tsx";
13
+ export { default as PersonasPage } from "./PersonasPage.tsx";
14
+ export { isEnabled } from "./qual.ts";
15
+ export { deleteJson, fetchJson, postJson } from "./sse.ts";
16
+ export { fmtDate, fmtTime, relativeTime } from "./ui/timefmt.ts";
17
+ export { applyThemeMode, loadThemeMode, saveThemeMode, type ThemeMode } from "./theme.ts";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { apiHeaders, auth } from "./auth.js";
2
+ export { sendToChat } from "./dock.js";
3
+ export { AgentApp } from "./mount.js";
4
+ export { default as PersonasPage } from "./PersonasPage.js";
5
+ export { isEnabled } from "./qual.js";
6
+ export { deleteJson, fetchJson, postJson } from "./sse.js";
7
+ export { fmtDate, fmtTime, relativeTime } from "./ui/timefmt.js";
8
+ export { applyThemeMode, loadThemeMode, saveThemeMode } from "./theme.js";
@@ -0,0 +1,50 @@
1
+ /**
2
+ * 组合根的通用实现(接缝的最后一层,2026-11-03)。
3
+ *
4
+ * 以前这份接线长在 `apps/web/src/App.tsx` 里(113 行),产品事实与机械传参
5
+ * 混在一处——第二个产品只能**把整份文件复制走再改 import**。这里把机械部分
6
+ * 收进 core,产品只保留自己的事实(导航注册表、文案兜底、侧栏入口、宿主级组件)。
7
+ *
8
+ * 插槽契约(照抄时最容易踩的一条):
9
+ * `footer` / `extras` 是**普通闭包**,不是组件——它们在 AgentApp 的 render
10
+ * 期间被调用,所以里面**不要调用 hook**(要 state 就在产品自己的组件里
11
+ * 用 useState,闭包里只捕获 setter)。
12
+ *
13
+ * 依赖方向恒为 产品 → agent-chat:本文件不 import 任何产品代码。
14
+ */
15
+ import type { ReactNode } from "react";
16
+ import type { BrandingResponse } from "@njuptlzf/agent-chat-protocol";
17
+ import { useAppHost, type AppDef } from "./app.tsx";
18
+ /** 宿主状态(`useAppHost` 的返回值):插槽从这里取品牌、身份、路由、人格。 */
19
+ export type AppHost = ReturnType<typeof useAppHost>;
20
+ /** 产品给的界面文案:全由 branding(manifest 声明)与当前人格决定。 */
21
+ export interface AppTexts {
22
+ /** 坞标题(换人格时要换,否则点了「声明人格」还写着「默认助手」)。 */
23
+ title: string;
24
+ /** 助手在界面上的叫法(「正在回答」这类提示语用)。 */
25
+ assistantLabel: string;
26
+ /** 提示条:这个助手是谁、不做什么。 */
27
+ policyNote?: string;
28
+ welcome?: string;
29
+ suggestions?: string[];
30
+ }
31
+ export interface AgentAppProps {
32
+ /** 导航注册表(产品事实)。 */
33
+ def: AppDef;
34
+ /** 文案兜底:core 不认得任何人格名,也不写死任何一句话。 */
35
+ texts(branding: BrandingResponse, persona: string): AppTexts;
36
+ /** 侧栏底部的产品入口(声明人格、反馈问题…)。闭包,不能调 hook。 */
37
+ footer?(host: AppHost): ReactNode;
38
+ /** 宿主级组件(每日总结、反馈抽屉…)。闭包,不能调 hook。 */
39
+ extras?(host: AppHost): ReactNode;
40
+ /** 加载失败时给产品的启动提示(core 不知道启动命令长什么样)。 */
41
+ loadErrorHint?: ReactNode;
42
+ }
43
+ /**
44
+ * 产品组合根:branding/whoami → 宿主状态 → 侧栏 + 坞 + 页面。
45
+ *
46
+ * 与改造前 `App.tsx` 的行为逐项对齐(full/compact 的判据、key 重挂、插槽位置),
47
+ * 差别只有一处:人格不再由 core 判断"谁是声明人格"——`host.persona` 原样传给
48
+ * `AgentChatApp`("" 收敛成 undefined = 产品默认助手),文案由 `texts` 决定。
49
+ */
50
+ export declare function AgentApp({ def, texts, footer, extras, loadErrorHint }: AgentAppProps): import("react").JSX.Element;
package/dist/mount.js ADDED
@@ -0,0 +1,38 @@
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
+ import AgentChatApp from "./AgentChatApp.js";
3
+ import DockPanel from "./DockPanel.js";
4
+ import { AppShell, themeVarsOf, useAppHost } from "./app.js";
5
+ /**
6
+ * 产品组合根:branding/whoami → 宿主状态 → 侧栏 + 坞 + 页面。
7
+ *
8
+ * 与改造前 `App.tsx` 的行为逐项对齐(full/compact 的判据、key 重挂、插槽位置),
9
+ * 差别只有一处:人格不再由 core 判断"谁是声明人格"——`host.persona` 原样传给
10
+ * `AgentChatApp`("" 收敛成 undefined = 产品默认助手),文案由 `texts` 决定。
11
+ */
12
+ export function AgentApp({ def, texts, footer, extras, loadErrorHint }) {
13
+ const host = useAppHost(def);
14
+ if (host.loadError) {
15
+ return (_jsxs("div", { className: "center", children: [_jsxs("p", { children: ["\u65E0\u6CD5\u8FDE\u63A5\u670D\u52A1\uFF1A", host.loadError] }), loadErrorHint] }));
16
+ }
17
+ if (!host.ready)
18
+ return _jsx("div", { className: "center", children: "\u52A0\u8F7D\u4E2D\u2026" });
19
+ const { branding, who, qual, route, shown, onQuals, persona, go, ctx } = host;
20
+ // 坞是否撑满内容区。同一个判据喂给 Dock.full 与 AgentChatApp.compact
21
+ // (2026-11-03:以前 compact 单独判「路由不是聊天页」,漏了选项页这种
22
+ // 「路由还是 chatRoute 但坞不是全屏」的状态,会话侧栏把输入框挤成 56px)。
23
+ const dockFull = !onQuals && route === def.chatRoute;
24
+ const t = texts(branding, persona);
25
+ return (_jsx("div", { className: "shell", style: themeVarsOf(branding), children: _jsxs(AppShell, { branding: branding, qual: qual, route: shown, nav: def.navItems(ctx), who: who,
26
+ // 侧栏导航回聊天路由 = 回**默认人格**(2026-11-04):从声明人格切「默认助手」时只改
27
+ // 路由的话,人格还挂在声明人格上,标题/预备问题都不换。人格化入口(人格化按钮)
28
+ // 走 host.go 自己先 setPersona,不经过这里,所以不会被这条冲掉。
29
+ onRoute: (r) => {
30
+ if (r === def.chatRoute && host.persona)
31
+ host.setPersona("");
32
+ go(r);
33
+ }, onQuals: () => go("quals"), switchTitle: def.labels?.switchTitle, footer: footer?.(host), children: [_jsx(DockPanel, { title: t.title, full: dockFull, onClose: host.closeChat, chat: _jsx(AgentChatApp
34
+ // key 让切人格时重挂:会话绑死人格,同一个实例换 persona 只会撞 persona_mismatch。
35
+ , { branding: branding, scope: qual?.id, renderCard: def.cardRenderer,
36
+ // core 只做形状收敛("" → undefined = 产品默认助手),不认识具体名字。
37
+ persona: persona || undefined, title: t.title, assistantLabel: t.assistantLabel, policyNote: t.policyNote, welcome: t.welcome, suggestions: t.suggestions, compact: !dockFull }, persona), children: def.page(ctx) }), extras?.(host)] }) }));
38
+ }
package/dist/qual.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ export declare function saveQual(id: string): void;
2
+ /** 可用 = 内容已就绪(`enabled` 不为 false)。 */
3
+ export declare function isEnabled(q: {
4
+ enabled?: boolean;
5
+ }): boolean;
6
+ /** 当前选项:本地记忆优先,否则回落第一个可用的选项。 */
7
+ export declare function currentQual<T extends {
8
+ id: string;
9
+ enabled?: boolean;
10
+ }>(quals: T[] | undefined): T | null;
11
+ /**
12
+ * 深链里的选项(`#/<业务页>?qual=<轨道>&id=…`)。
13
+ *
14
+ * 为什么需要:页面记住的选项(ac.qual)与会话的 `AC_SCOPE` 是两件事——助手在
15
+ * system-integration 的会话里给了一张题卡,点进去时页面可能还停在 architect,
16
+ * 结果 404。深链把选项带上,壳静默切过去。
17
+ *
18
+ * 只认 `?` 之后的 query 段:路径里也可能出现 qual 字样(`#/quals`),用 includes
19
+ * 判断会误伤。空值当没写。
20
+ */
21
+ export declare function qualFromHash(hash: string): string | null;
package/dist/qual.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * 当前选项的本地偏好(从 <product>/qual.ts 拆入 core):
3
+ * 产品可选项目录是通用协议形状,"记住上次选了哪一项"是壳机制不是产品事实。
4
+ * 存储键保持 `ac.qual` 不变——老用户的偏好直接沿用。
5
+ *
6
+ * 产品侧只留具体选项的语义与路由映射。
7
+ */
8
+ const KEY = "ac.qual";
9
+ function loadQual() {
10
+ try {
11
+ return localStorage.getItem(KEY);
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ }
17
+ export function saveQual(id) {
18
+ try {
19
+ localStorage.setItem(KEY, id);
20
+ }
21
+ catch {
22
+ // 隐私模式下 localStorage 可能抛错;选项只是偏好,丢了回选择页即可。
23
+ }
24
+ }
25
+ /** 可用 = 内容已就绪(`enabled` 不为 false)。 */
26
+ export function isEnabled(q) {
27
+ return q.enabled !== false;
28
+ }
29
+ /** 当前选项:本地记忆优先,否则回落第一个可用的选项。 */
30
+ export function currentQual(quals) {
31
+ if (!quals || quals.length === 0)
32
+ return null;
33
+ const saved = loadQual();
34
+ const hit = saved ? quals.find((q) => q.id === saved && isEnabled(q)) : undefined;
35
+ return hit ?? quals.find(isEnabled) ?? null;
36
+ }
37
+ /**
38
+ * 深链里的选项(`#/<业务页>?qual=<轨道>&id=…`)。
39
+ *
40
+ * 为什么需要:页面记住的选项(ac.qual)与会话的 `AC_SCOPE` 是两件事——助手在
41
+ * system-integration 的会话里给了一张题卡,点进去时页面可能还停在 architect,
42
+ * 结果 404。深链把选项带上,壳静默切过去。
43
+ *
44
+ * 只认 `?` 之后的 query 段:路径里也可能出现 qual 字样(`#/quals`),用 includes
45
+ * 判断会误伤。空值当没写。
46
+ */
47
+ export function qualFromHash(hash) {
48
+ const q = hash.indexOf("?");
49
+ if (q < 0)
50
+ return null;
51
+ const id = new URLSearchParams(hash.slice(q + 1)).get("qual");
52
+ return id ? id : null;
53
+ }
package/dist/sse.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { ChatEvent, ChatRequest, ConfirmDecision } from "@njuptlzf/agent-chat-protocol";
2
+ /** GET a JSON API with the optional host auth token; throws on non-2xx. */
3
+ export declare function fetchJson<T>(path: string, authHeader?: string): Promise<T>;
4
+ /** POST a JSON body with the optional host auth token; throws on non-2xx. */
5
+ export declare function postJson<T>(path: string, body: unknown, authHeader?: string): Promise<T>;
6
+ /** DELETE with the optional host auth token; throws on non-2xx. */
7
+ export declare function deleteJson<T>(path: string, authHeader?: string): Promise<T>;
8
+ /** Answer a `tool_confirm` event; must be called while its run's stream is open. */
9
+ export declare function postDecision(dec: ConfirmDecision, authHeader?: string): Promise<boolean>;
10
+ /**
11
+ * POST /api/chat and stream back protocol events. SSE frames are
12
+ * `data: <json>\n\n`; we parse them by hand because EventSource cannot POST.
13
+ */
14
+ export declare function streamChat(req: ChatRequest, signal: AbortSignal, authHeader?: string): AsyncGenerator<ChatEvent>;