@nexface/chat 0.1.1-alpha.7 → 0.1.1-alpha.9

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 (42) hide show
  1. package/dist/assistant-attachments.d.ts +31 -0
  2. package/dist/assistant-attachments.js +158 -0
  3. package/dist/assistant-attachments.js.map +1 -0
  4. package/dist/assistant-components.d.ts +18 -0
  5. package/dist/assistant-components.js +36 -0
  6. package/dist/assistant-components.js.map +1 -0
  7. package/dist/assistant-runtime.d.ts +24 -0
  8. package/dist/assistant-runtime.js +104 -0
  9. package/dist/assistant-runtime.js.map +1 -0
  10. package/dist/attachments.d.ts +3 -1
  11. package/dist/attachments.js +13 -0
  12. package/dist/attachments.js.map +1 -1
  13. package/dist/client.d.ts +2 -1
  14. package/dist/client.js +35 -4
  15. package/dist/client.js.map +1 -1
  16. package/dist/config.js.map +1 -1
  17. package/dist/default-chat.d.ts +2 -1
  18. package/dist/default-chat.js +58 -106
  19. package/dist/default-chat.js.map +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/messages.js.map +1 -1
  22. package/dist/page-confirmation.js.map +1 -1
  23. package/dist/protocol-messages.js +1 -1
  24. package/dist/protocol-messages.js.map +1 -1
  25. package/dist/protocol-response.d.ts +32 -0
  26. package/dist/protocol-response.js +62 -0
  27. package/dist/protocol-response.js.map +1 -0
  28. package/dist/react.d.ts +9 -6
  29. package/dist/react.js +58 -7
  30. package/dist/react.js.map +1 -1
  31. package/dist/storage.js +4 -2
  32. package/dist/storage.js.map +1 -1
  33. package/dist/styles.css +42 -52
  34. package/dist/tool-result.d.ts +1 -0
  35. package/dist/tool-result.js +12 -0
  36. package/dist/tool-result.js.map +1 -0
  37. package/dist/types.d.ts +35 -0
  38. package/dist/types.js.map +1 -1
  39. package/package.json +6 -9
  40. package/dist/client-entry.d.ts +0 -2
  41. package/dist/client-entry.js +0 -2
  42. package/dist/client-entry.js.map +0 -1
@@ -0,0 +1,31 @@
1
+ import type { AttachmentAdapter, PendingAttachment, CompleteAttachment } from "@assistant-ui/react";
2
+ import { type Attachment } from "./attachments.js";
3
+ import type { ChatAttachmentOptions } from "./types.js";
4
+ export declare function toAssistantAttachment(attachment: Attachment): CompleteAttachment;
5
+ export declare class AssistantAttachments implements AttachmentAdapter {
6
+ private changed;
7
+ private notice;
8
+ readonly accept = "*";
9
+ private entries;
10
+ private disposed;
11
+ options: false | ChatAttachmentOptions;
12
+ constructor(changed: () => void, notice: (message: string) => void);
13
+ get blocked(): boolean;
14
+ get processing(): boolean;
15
+ get sending(): boolean;
16
+ preview(id: string): string | undefined;
17
+ add({ file }: {
18
+ file: File;
19
+ }): AsyncGenerator<PendingAttachment, void>;
20
+ send(attachment: {
21
+ id: string;
22
+ }): Promise<CompleteAttachment>;
23
+ remove(attachment: {
24
+ id: string;
25
+ }): Promise<void>;
26
+ take(attachments: readonly CompleteAttachment[]): Attachment[];
27
+ commit(attachments: readonly CompleteAttachment[]): void;
28
+ dispose(): void;
29
+ private live;
30
+ private assertLive;
31
+ }
@@ -0,0 +1,158 @@
1
+ import { ImageInputContentSchema, TextInputContentSchema } from "@ag-ui/core";
2
+ import { attachmentContent, readAttachment, validateAttachment } from "./attachments.js";
3
+ const errorText = (error) => error instanceof Error ? error.message : String(error);
4
+ const durablePreview = (preview) => preview?.startsWith("data:image/") ? preview : undefined;
5
+ // Stop local waiting even when a service ignores cancellation; consume late rejections.
6
+ function abortable(signal, task) {
7
+ return new Promise((resolve, reject) => {
8
+ const abort = () => reject(new DOMException("附件处理已取消。", "AbortError"));
9
+ signal.addEventListener("abort", abort, { once: true });
10
+ void task.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
11
+ if (signal.aborted)
12
+ abort();
13
+ });
14
+ }
15
+ export function toAssistantAttachment(attachment) {
16
+ const content = attachmentContent(attachment).map((part) => {
17
+ if (part.type === "text")
18
+ return part;
19
+ return { type: "image", image: part.source.type === "data" ? `data:${part.source.mimeType};base64,${part.source.value}` : part.source.value };
20
+ });
21
+ return { id: attachment.id, name: attachment.name, type: attachment.preview ? "image" : "document", content, status: { type: "complete" } };
22
+ }
23
+ // Only this bridge knows assistant-ui's attachment state and lifecycle types.
24
+ export class AssistantAttachments {
25
+ changed;
26
+ notice;
27
+ accept = "*";
28
+ entries = new Map();
29
+ disposed = false;
30
+ options = {};
31
+ constructor(changed, notice) {
32
+ this.changed = changed;
33
+ this.notice = notice;
34
+ }
35
+ get blocked() { return [...this.entries.values()].some((entry) => entry.adding || Boolean(entry.error)); }
36
+ get processing() { return [...this.entries.values()].some((entry) => entry.adding || entry.sending); }
37
+ get sending() { return [...this.entries.values()].some((entry) => entry.sending); }
38
+ preview(id) { return this.entries.get(id)?.preview; }
39
+ async *add({ file }) {
40
+ if (this.disposed || this.options === false)
41
+ throw new Error("附件已禁用。");
42
+ const options = this.options;
43
+ const maxCount = options.maxCount ?? 3;
44
+ if (!Number.isInteger(maxCount) || maxCount <= 0)
45
+ throw new Error("附件数量限制必须是正整数。");
46
+ if (this.entries.size >= maxCount)
47
+ throw new Error("附件数量超出限制。");
48
+ const entry = { id: crypto.randomUUID(), file, controller: new AbortController(), adapter: options.adapter, adding: true, sending: false };
49
+ this.entries.set(entry.id, entry);
50
+ this.changed();
51
+ const base = { id: entry.id, file, name: file.name, contentType: file.type, type: file.type.startsWith("image/") ? "image" : "document" };
52
+ yield { ...base, status: { type: "running", reason: "uploading", progress: 0 } };
53
+ try {
54
+ if (entry.adapter) {
55
+ validateAttachment(file, options);
56
+ const result = await abortable(entry.controller.signal, entry.adapter.add({ id: entry.id, file, signal: entry.controller.signal }));
57
+ this.assertLive(entry);
58
+ entry.data = result.data;
59
+ entry.preview = result.preview;
60
+ }
61
+ else {
62
+ entry.local = await abortable(entry.controller.signal, readAttachment(file, options));
63
+ this.assertLive(entry);
64
+ entry.preview = entry.local.preview;
65
+ }
66
+ yield { ...base, status: { type: "requires-action", reason: "composer-send" } };
67
+ }
68
+ catch (error) {
69
+ if (!this.live(entry))
70
+ return;
71
+ entry.error = errorText(error);
72
+ yield { ...base, status: { type: "incomplete", reason: "error", message: entry.error } };
73
+ }
74
+ finally {
75
+ entry.adding = false;
76
+ if (!this.disposed)
77
+ this.changed();
78
+ }
79
+ }
80
+ async send(attachment) {
81
+ const entry = this.entries.get(attachment.id);
82
+ if (!entry)
83
+ throw new Error("附件已移除。");
84
+ this.assertLive(entry);
85
+ if (entry.adding || entry.error)
86
+ throw new Error(entry.error ?? "附件尚未准备完成。");
87
+ entry.sending = true;
88
+ this.changed();
89
+ try {
90
+ let content;
91
+ if (entry.adapter) {
92
+ const result = await abortable(entry.controller.signal, entry.adapter.send({ id: entry.id, file: entry.file, data: entry.data, signal: entry.controller.signal }));
93
+ this.assertLive(entry);
94
+ if (!Array.isArray(result.content) || !result.content.length)
95
+ throw new Error("附件处理必须返回文本或内联图片。");
96
+ content = result.content.map((part) => {
97
+ if (part.type === "text")
98
+ return TextInputContentSchema.parse(part);
99
+ const image = ImageInputContentSchema.parse(part);
100
+ if (image.source.type !== "data")
101
+ throw new Error("附件仅支持内联图片,不支持图片 URL。");
102
+ return image;
103
+ });
104
+ }
105
+ else
106
+ content = attachmentContent(entry.local);
107
+ this.assertLive(entry);
108
+ const preview = durablePreview(entry.preview);
109
+ entry.result = { id: entry.id, name: entry.file.name, content, ...(preview ? { preview } : {}) };
110
+ return toAssistantAttachment(entry.result);
111
+ }
112
+ catch (error) {
113
+ if (this.live(entry))
114
+ this.notice(errorText(error));
115
+ throw error;
116
+ }
117
+ finally {
118
+ entry.sending = false;
119
+ if (!this.disposed)
120
+ this.changed();
121
+ }
122
+ }
123
+ // Removal is local-first. Cleanup failures must not resurrect the chip.
124
+ async remove(attachment) {
125
+ const entry = this.entries.get(attachment.id);
126
+ if (!entry)
127
+ return;
128
+ this.entries.delete(entry.id);
129
+ entry.controller.abort();
130
+ if (!this.disposed)
131
+ this.changed();
132
+ void Promise.resolve().then(() => entry.adapter?.remove?.({ id: entry.id, file: entry.file, data: entry.data }))
133
+ .catch((error) => { if (!this.disposed)
134
+ this.notice(`附件清理失败:${errorText(error)}`); });
135
+ }
136
+ take(attachments) {
137
+ return attachments.map((attachment) => {
138
+ const entry = this.entries.get(attachment.id);
139
+ if (!entry?.result)
140
+ throw new Error("附件尚未准备完成。");
141
+ return entry.result;
142
+ });
143
+ }
144
+ commit(attachments) {
145
+ for (const attachment of attachments)
146
+ this.entries.delete(attachment.id);
147
+ this.changed();
148
+ }
149
+ dispose() {
150
+ this.disposed = true;
151
+ for (const id of this.entries.keys())
152
+ void this.remove({ id });
153
+ }
154
+ live(entry) { return !this.disposed && !entry.controller.signal.aborted && this.entries.get(entry.id) === entry; }
155
+ assertLive(entry) { if (!this.live(entry))
156
+ throw new DOMException("附件处理已取消。", "AbortError"); }
157
+ }
158
+ //# sourceMappingURL=assistant-attachments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assistant-attachments.js","sourceRoot":"","sources":["../src/assistant-attachments.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,kBAAkB,EAAmB,MAAM,kBAAkB,CAAC;AAgB1G,MAAM,SAAS,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC7F,MAAM,cAAc,GAAG,CAAC,OAAgB,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAEtG,wFAAwF;AACxF,SAAS,SAAS,CAAI,MAAmB,EAAE,IAAgB;IACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,M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IAAI,OAAO,CAAC,IAAI,CAAC,QAAQ,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC;IACzH,UAAU,CAAC,KAAY,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,YAAY,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;CAC9G","sourcesContent":["import type { AgentInputContent } from \"@nexface/agent\";\nimport type { AttachmentAdapter, PendingAttachment, CompleteAttachment } from \"@assistant-ui/react\";\nimport { ImageInputContentSchema, TextInputContentSchema } from \"@ag-ui/core\";\nimport { attachmentContent, readAttachment, validateAttachment, type Attachment } from \"./attachments.js\";\nimport type { ChatAttachmentOptions } from \"./types.js\";\n\ntype Entry = {\n id: string;\n file: File;\n controller: AbortController;\n adapter: ChatAttachmentOptions[\"adapter\"];\n data?: unknown;\n preview?: string | undefined;\n local?: Attachment;\n result?: Attachment;\n adding: boolean;\n sending: boolean;\n error?: string;\n};\nconst errorText = (error: unknown) => error instanceof Error ? error.message : String(error);\nconst durablePreview = (preview?: string) => preview?.startsWith(\"data:image/\") ? preview : undefined;\n\n// Stop local waiting even when a service ignores cancellation; consume late rejections.\nfunction abortable<T>(signal: AbortSignal, task: Promise<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n const abort = () => reject(new DOMException(\"附件处理已取消。\", \"AbortError\"));\n signal.addEventListener(\"abort\", abort, { once: true });\n void task.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", abort));\n if (signal.aborted) abort();\n });\n}\n\nexport function toAssistantAttachment(attachment: Attachment): CompleteAttachment {\n const content: CompleteAttachment[\"content\"] = attachmentContent(attachment).map((part) => {\n if (part.type === \"text\") return part;\n return { type: \"image\", image: part.source.type === \"data\" ? `data:${part.source.mimeType};base64,${part.source.value}` : part.source.value };\n });\n return { id: attachment.id, name: attachment.name, type: attachment.preview ? \"image\" : \"document\", content, status: { type: \"complete\" } };\n}\n\n// Only this bridge knows assistant-ui's attachment state and lifecycle types.\nexport class AssistantAttachments implements AttachmentAdapter {\n readonly accept = \"*\";\n private entries = new Map<string, Entry>();\n private disposed = false;\n options: false | ChatAttachmentOptions = {};\n constructor(private changed: () => void, private notice: (message: string) => void) {}\n get blocked() { return [...this.entries.values()].some((entry) => entry.adding || Boolean(entry.error)); }\n get processing() { return [...this.entries.values()].some((entry) => entry.adding || entry.sending); }\n get sending() { return [...this.entries.values()].some((entry) => entry.sending); }\n preview(id: string) { return this.entries.get(id)?.preview; }\n\n async *add({ file }: { file: File }): AsyncGenerator<PendingAttachment, void> {\n if (this.disposed || this.options === false) throw new Error(\"附件已禁用。\");\n const options = this.options;\n const maxCount = options.maxCount ?? 3;\n if (!Number.isInteger(maxCount) || maxCount <= 0) throw new Error(\"附件数量限制必须是正整数。\");\n if (this.entries.size >= maxCount) throw new Error(\"附件数量超出限制。\");\n const entry: Entry = { id: crypto.randomUUID(), file, controller: new AbortController(), adapter: options.adapter, adding: true, sending: false };\n this.entries.set(entry.id, entry);\n this.changed();\n const base = { id: entry.id, file, name: file.name, contentType: file.type, type: file.type.startsWith(\"image/\") ? \"image\" : \"document\" };\n yield { ...base, status: { type: \"running\", reason: \"uploading\", progress: 0 } };\n try {\n if (entry.adapter) {\n validateAttachment(file, options);\n const result = await abortable(entry.controller.signal, entry.adapter.add({ id: entry.id, file, signal: entry.controller.signal }));\n this.assertLive(entry);\n entry.data = result.data;\n entry.preview = result.preview;\n } else {\n entry.local = await abortable(entry.controller.signal, readAttachment(file, options));\n this.assertLive(entry);\n entry.preview = entry.local.preview;\n }\n yield { ...base, status: { type: \"requires-action\", reason: \"composer-send\" } };\n } catch (error) {\n if (!this.live(entry)) return;\n entry.error = errorText(error);\n yield { ...base, status: { type: \"incomplete\", reason: \"error\", message: entry.error } };\n } finally {\n entry.adding = false;\n if (!this.disposed) this.changed();\n }\n }\n\n async send(attachment: { id: string }): Promise<CompleteAttachment> {\n const entry = this.entries.get(attachment.id);\n if (!entry) throw new Error(\"附件已移除。\");\n this.assertLive(entry);\n if (entry.adding || entry.error) throw new Error(entry.error ?? \"附件尚未准备完成。\");\n entry.sending = true;\n this.changed();\n try {\n let content: AgentInputContent[];\n if (entry.adapter) {\n const result = await abortable(entry.controller.signal, entry.adapter.send({ id: entry.id, file: entry.file, data: entry.data, signal: entry.controller.signal }));\n this.assertLive(entry);\n if (!Array.isArray(result.content) || !result.content.length) throw new Error(\"附件处理必须返回文本或内联图片。\");\n content = result.content.map((part) => {\n if (part.type === \"text\") return TextInputContentSchema.parse(part);\n const image = ImageInputContentSchema.parse(part);\n if (image.source.type !== \"data\") throw new Error(\"附件仅支持内联图片,不支持图片 URL。\");\n return image;\n });\n } else content = attachmentContent(entry.local!);\n this.assertLive(entry);\n const preview = durablePreview(entry.preview);\n entry.result = { id: entry.id, name: entry.file.name, content, ...(preview ? { preview } : {}) };\n return toAssistantAttachment(entry.result);\n } catch (error) {\n if (this.live(entry)) this.notice(errorText(error));\n throw error;\n } finally {\n entry.sending = false;\n if (!this.disposed) this.changed();\n }\n }\n\n // Removal is local-first. Cleanup failures must not resurrect the chip.\n async remove(attachment: { id: string }): Promise<void> {\n const entry = this.entries.get(attachment.id);\n if (!entry) return;\n this.entries.delete(entry.id);\n entry.controller.abort();\n if (!this.disposed) this.changed();\n void Promise.resolve().then(() => entry.adapter?.remove?.({ id: entry.id, file: entry.file, data: entry.data }))\n .catch((error) => { if (!this.disposed) this.notice(`附件清理失败:${errorText(error)}`); });\n }\n\n take(attachments: readonly CompleteAttachment[]): Attachment[] {\n return attachments.map((attachment) => {\n const entry = this.entries.get(attachment.id);\n if (!entry?.result) throw new Error(\"附件尚未准备完成。\");\n return entry.result;\n });\n }\n commit(attachments: readonly CompleteAttachment[]) {\n for (const attachment of attachments) this.entries.delete(attachment.id);\n this.changed();\n }\n dispose() {\n this.disposed = true;\n for (const id of this.entries.keys()) void this.remove({ id });\n }\n private live(entry: Entry) { return !this.disposed && !entry.controller.signal.aborted && this.entries.get(entry.id) === entry; }\n private assertLive(entry: Entry) { if (!this.live(entry)) throw new DOMException(\"附件处理已取消。\", \"AbortError\"); }\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import { type TextMessagePartComponent, type ToolCallMessagePartComponent } from "@assistant-ui/react";
2
+ import type { AssistantBinding } from "./assistant-runtime.js";
3
+ import type { ChatProps } from "./types.js";
4
+ export declare const MarkdownText: TextMessagePartComponent;
5
+ export declare const ToolDetail: ToolCallMessagePartComponent;
6
+ export declare const HiddenTool: ToolCallMessagePartComponent;
7
+ export declare function AttachmentTile({ binding, savedPreview }: {
8
+ binding?: AssistantBinding;
9
+ savedPreview?: string | undefined;
10
+ }): import("react").JSX.Element;
11
+ export declare function AssistantComposer({ binding, options, placeholder, busy, cancelling, cancel }: {
12
+ binding: AssistantBinding;
13
+ options: ChatProps["attachments"];
14
+ placeholder: string;
15
+ busy: boolean;
16
+ cancelling: boolean;
17
+ cancel(): void;
18
+ }): import("react").JSX.Element;
@@ -0,0 +1,36 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useRef } from "react";
3
+ import Markdown from "react-markdown";
4
+ import remarkGfm from "remark-gfm";
5
+ import { AttachmentPrimitive, ComposerPrimitive, useAuiState } from "@assistant-ui/react";
6
+ import { PaperPlaneTiltIcon } from "@phosphor-icons/react/PaperPlaneTilt";
7
+ import { PaperclipIcon } from "@phosphor-icons/react/Paperclip";
8
+ import { attachmentAccept } from "./attachments.js";
9
+ // The default assistant-ui composition, with scoped CSS and Nexface labels.
10
+ export const MarkdownText = ({ text }) => _jsx(Markdown, { remarkPlugins: [remarkGfm], skipHtml: true, children: text });
11
+ export const ToolDetail = ({ toolName, argsText, result, isError }) => _jsxs("details", { className: "nexface-chat__tool", "data-error": isError || undefined, children: [_jsxs("summary", { children: ["\u64CD\u4F5C\u8BB0\u5F55 ", _jsx("span", { "aria-hidden": true, children: "\u203A" })] }), _jsx("strong", { children: toolName }), _jsx("small", { children: result === undefined ? "等待执行结果" : isError ? "未完成" : "已完成" }), _jsxs("div", { children: [_jsx("b", { children: "Input" }), _jsx("pre", { children: argsText })] }), result !== undefined ? _jsxs("div", { children: [_jsx("b", { children: isError ? "Error" : "Output" }), _jsx("pre", { children: typeof result === "string" ? result : JSON.stringify(result) })] }) : null] });
12
+ export const HiddenTool = () => null;
13
+ export function AttachmentTile({ binding, savedPreview }) {
14
+ const attachment = useAuiState((s) => s.attachment);
15
+ const preview = binding?.attachments.preview(attachment.id) ?? savedPreview ?? attachment.content?.find((part) => part.type === "image")?.image;
16
+ return _jsxs(AttachmentPrimitive.Root, { className: "nexface-chat__attachment", children: [preview ? _jsx("img", { src: preview, alt: attachment.name }) : _jsx(PaperclipIcon, {}), _jsx("span", { children: _jsx(AttachmentPrimitive.Name, {}) }), binding && attachment.status.type === "requires-action" ? _jsx("small", { children: "\u5DF2\u5C31\u7EEA" }) : null, attachment.status.type === "running" ? _jsx("small", { children: "\u6B63\u5728\u5904\u7406\u2026" }) : null, attachment.status.type === "incomplete" ? _jsx("small", { role: "alert", children: attachment.status.message ?? "附件处理失败" }) : null, binding ? _jsx(AttachmentPrimitive.Remove, { "aria-label": `移除 ${attachment.name}`, children: "\u00D7" }) : null] });
17
+ }
18
+ export function AssistantComposer({ binding, options, placeholder, busy, cancelling, cancel }) {
19
+ const input = useRef(null);
20
+ const sending = binding.sending;
21
+ const addFiles = (files) => {
22
+ for (const file of files)
23
+ void binding.runtime.thread.composer.addAttachment(file).catch((error) => binding.setNotice(error instanceof Error ? error.message : String(error)));
24
+ };
25
+ return _jsxs(ComposerPrimitive.Root, { className: "nexface-chat__composer", onSubmit: (event) => { event.preventDefault(); void binding.send(); }, onDragOver: (event) => { if (options !== false)
26
+ event.preventDefault(); }, onDrop: (event) => { if (options !== false && !sending) {
27
+ event.preventDefault();
28
+ addFiles(Array.from(event.dataTransfer.files));
29
+ } }, children: [_jsx("div", { className: "nexface-chat__attachments", children: _jsx(ComposerPrimitive.Attachments, { children: () => _jsx(AttachmentTile, { binding: binding }) }) }), sending ? _jsx("small", { role: "status", children: "\u6B63\u5728\u5904\u7406\u9644\u4EF6\u2026" }) : null, _jsx(ComposerPrimitive.Input, { "aria-label": "\u8F93\u5165 Agent \u4EFB\u52A1", placeholder: placeholder, disabled: sending, rows: 1, minRows: 2, maxRows: 7, cancelOnEscape: false, onKeyDown: (event) => { if (event.keyCode === 229)
30
+ event.preventDefault();
31
+ else if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
32
+ event.preventDefault();
33
+ void binding.send();
34
+ } } }), _jsxs("div", { className: "nexface-chat__composer-toolbar", children: [options !== false ? _jsxs(_Fragment, { children: [_jsx("input", { ref: input, type: "file", multiple: true, disabled: sending, accept: options?.accept ?? attachmentAccept, hidden: true, onChange: (event) => { addFiles(Array.from(event.target.files ?? [])); event.target.value = ""; } }), _jsx("button", { type: "button", className: "nexface-chat__icon-button", "aria-label": "\u6DFB\u52A0\u9644\u4EF6", title: "\u6DFB\u52A0\u9644\u4EF6", disabled: sending, onClick: () => input.current?.click(), children: _jsx(PaperclipIcon, {}) })] }) : null, _jsx("span", {}), busy ? _jsx("button", { type: "button", "aria-label": "\u53D6\u6D88\u4EFB\u52A1", className: "nexface-chat__primary nexface-chat__send", disabled: cancelling, onClick: cancel, children: _jsx("span", { className: "nexface-chat__stop" }) }) : null, _jsx(ComposerPrimitive.Send, { disabled: sending, onClick: (event) => { event.preventDefault(); void binding.send(); }, "aria-label": "\u53D1\u9001\u4EFB\u52A1", className: "nexface-chat__primary nexface-chat__send", children: _jsx(PaperPlaneTiltIcon, { weight: "fill" }) })] })] });
35
+ }
36
+ //# sourceMappingURL=assistant-components.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assistant-components.js","sourceRoot":"","sources":["../src/assistant-components.tsx"],"names":[],"mapp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EAAC,SAAS,EAAC,2BAA2B,gBAAY,0BAAM,EAAC,KAAK,EAAC,0BAAM,EAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,YAAE,KAAC,aAAa,KAAG,GAAS,IAAG,CAAC,CAAC,CAAC,IAAI,EAC3L,gBAAQ,EACP,IAAI,CAAC,CAAC,CAAC,iBAAQ,IAAI,EAAC,QAAQ,gBAAY,0BAAM,EAAC,SAAS,EAAC,0CAA0C,EAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAE,eAAM,SAAS,EAAC,oBAAoB,GAAG,GAAS,CAAC,CAAC,CAAC,IAAI,EACnM,KAAC,iBAAiB,CAAC,IAAI,IAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,GAAG,KAAK,CAAC,cAAc,EAAE,CAAC,CAAC,KAAK,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,gBAAa,0BAAM,EAAC,SAAS,EAAC,0CAA0C,YAAC,KAAC,kBAAkB,IAAC,MAAM,EAAC,MAAM,GAAG,GAAyB,IACjP,IACiB,CAAC;AAC5B,CAAC","sourcesContent":["import { useRef } from \"react\";\nimport Markdown from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\nimport { AttachmentPrimitive, ComposerPrimitive, useAuiState, type TextMessagePartComponent, type ToolCallMessagePartComponent } from \"@assistant-ui/react\";\nimport { PaperPlaneTiltIcon } from \"@phosphor-icons/react/PaperPlaneTilt\";\nimport { PaperclipIcon } from \"@phosphor-icons/react/Paperclip\";\nimport type { AssistantBinding } from \"./assistant-runtime.js\";\nimport { attachmentAccept } from \"./attachments.js\";\nimport type { ChatProps } from \"./types.js\";\n\n// The default assistant-ui composition, with scoped CSS and Nexface labels.\nexport const MarkdownText: TextMessagePartComponent = ({ text }) => <Markdown remarkPlugins={[remarkGfm]} skipHtml>{text}</Markdown>;\nexport const ToolDetail: ToolCallMessagePartComponent = ({ toolName, argsText, result, isError }) => <details className=\"nexface-chat__tool\" data-error={isError || undefined}>\n <summary>操作记录 <span aria-hidden>›</span></summary><strong>{toolName}</strong>\n <small>{result === undefined ? \"等待执行结果\" : isError ? \"未完成\" : \"已完成\"}</small>\n <div><b>Input</b><pre>{argsText}</pre></div>\n {result !== undefined ? <div><b>{isError ? \"Error\" : \"Output\"}</b><pre>{typeof result === \"string\" ? result : JSON.stringify(result)}</pre></div> : null}\n</details>;\nexport const HiddenTool: ToolCallMessagePartComponent = () => null;\n\nexport function AttachmentTile({ binding, savedPreview }: { binding?: AssistantBinding; savedPreview?: string | undefined }) {\n const attachment = useAuiState((s) => s.attachment);\n const preview = binding?.attachments.preview(attachment.id) ?? savedPreview ?? attachment.content?.find((part) => part.type === \"image\")?.image;\n return <AttachmentPrimitive.Root className=\"nexface-chat__attachment\">\n {preview ? <img src={preview} alt={attachment.name} /> : <PaperclipIcon />}\n <span><AttachmentPrimitive.Name /></span>\n {binding && attachment.status.type === \"requires-action\" ? <small>已就绪</small> : null}\n {attachment.status.type === \"running\" ? <small>正在处理…</small> : null}\n {attachment.status.type === \"incomplete\" ? <small role=\"alert\">{attachment.status.message ?? \"附件处理失败\"}</small> : null}\n {binding ? <AttachmentPrimitive.Remove aria-label={`移除 ${attachment.name}`}>×</AttachmentPrimitive.Remove> : null}\n </AttachmentPrimitive.Root>;\n}\n\nexport function AssistantComposer({ binding, options, placeholder, busy, cancelling, cancel }: {\n binding: AssistantBinding; options: ChatProps[\"attachments\"]; placeholder: string;\n busy: boolean; cancelling: boolean; cancel(): void;\n}) {\n const input = useRef<HTMLInputElement>(null);\n const sending = binding.sending;\n const addFiles = (files: File[]) => {\n for (const file of files) void binding.runtime.thread.composer.addAttachment(file).catch((error: unknown) => binding.setNotice(error instanceof Error ? error.message : String(error)));\n };\n return <ComposerPrimitive.Root className=\"nexface-chat__composer\" onSubmit={(event) => { event.preventDefault(); void binding.send(); }}\n onDragOver={(event) => { if (options !== false) event.preventDefault(); }}\n onDrop={(event) => { if (options !== false && !sending) { event.preventDefault(); addFiles(Array.from(event.dataTransfer.files)); } }}>\n <div className=\"nexface-chat__attachments\"><ComposerPrimitive.Attachments>{() => <AttachmentTile binding={binding} />}</ComposerPrimitive.Attachments></div>\n {sending ? <small role=\"status\">正在处理附件…</small> : null}\n <ComposerPrimitive.Input aria-label=\"输入 Agent 任务\" placeholder={placeholder} disabled={sending} rows={1} minRows={2} maxRows={7} cancelOnEscape={false}\n onKeyDown={(event) => { if (event.keyCode === 229) event.preventDefault(); else if (event.key === \"Enter\" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void binding.send(); } }} />\n <div className=\"nexface-chat__composer-toolbar\">\n {options !== false ? <><input ref={input} type=\"file\" multiple disabled={sending} accept={options?.accept ?? attachmentAccept} hidden\n onChange={(event) => { addFiles(Array.from(event.target.files ?? [])); event.target.value = \"\"; }} />\n <button type=\"button\" className=\"nexface-chat__icon-button\" aria-label=\"添加附件\" title=\"添加附件\" disabled={sending} onClick={() => input.current?.click()}><PaperclipIcon /></button></> : null}\n <span />\n {busy ? <button type=\"button\" aria-label=\"取消任务\" className=\"nexface-chat__primary nexface-chat__send\" disabled={cancelling} onClick={cancel}><span className=\"nexface-chat__stop\" /></button> : null}\n <ComposerPrimitive.Send disabled={sending} onClick={(event) => { event.preventDefault(); void binding.send(); }} aria-label=\"发送任务\" className=\"nexface-chat__primary nexface-chat__send\"><PaperPlaneTiltIcon weight=\"fill\" /></ComposerPrimitive.Send>\n </div>\n </ComposerPrimitive.Root>;\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import { type ReactNode } from "react";
2
+ import { type AssistantRuntime, type ThreadMessageLike } from "@assistant-ui/react";
3
+ import { AssistantAttachments } from "./assistant-attachments.js";
4
+ import { type useChat, type UIMessage } from "./react.js";
5
+ import type { ChatProps } from "./types.js";
6
+ type ChatState = ReturnType<typeof useChat>;
7
+ export type AssistantBinding = {
8
+ runtime: AssistantRuntime;
9
+ attachments: AssistantAttachments;
10
+ notice: string;
11
+ setNotice(message: string): void;
12
+ sending: boolean;
13
+ send(): Promise<void>;
14
+ };
15
+ export declare function convertMessage(message: UIMessage): ThreadMessageLike;
16
+ export declare function SessionRuntime({ id, chat, options, blocked, active, children }: {
17
+ id: string;
18
+ chat: ChatState;
19
+ options: ChatProps["attachments"];
20
+ blocked: boolean;
21
+ active: boolean;
22
+ children(binding: AssistantBinding): ReactNode;
23
+ }): import("react").JSX.Element;
24
+ export {};
@@ -0,0 +1,104 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "react";
3
+ import { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime } from "@assistant-ui/react";
4
+ import { AssistantAttachments, toAssistantAttachment } from "./assistant-attachments.js";
5
+ import { assertChatSendable } from "./react.js";
6
+ export function convertMessage(message) {
7
+ const content = message.parts.map((part) => part.type === "text" ? part : {
8
+ type: "tool-call", toolCallId: part.toolCallId, toolName: part.name,
9
+ args: {},
10
+ argsText: part.arguments, result: part.result, isError: part.isError,
11
+ });
12
+ if (message.role === "user")
13
+ return { id: message.id, role: "user", content, attachments: message.attachments?.map(toAssistantAttachment) };
14
+ return { id: message.id, role: "assistant", content, status: message.state === "running"
15
+ ? { type: "running" } : message.state === "error" ? { type: "incomplete", reason: "error" } : { type: "complete", reason: "stop" } };
16
+ }
17
+ // Keep one composer per visited Session: switching the external-store thread id
18
+ // would invalidate pending attachment work and discard that Session's draft.
19
+ export function SessionRuntime({ id, chat, options, blocked, active, children }) {
20
+ const latest = useRef(chat);
21
+ useLayoutEffect(() => { latest.current = chat; });
22
+ const messages = useRef([]);
23
+ if (chat.activeSessionId === id)
24
+ messages.current = chat.messages;
25
+ const [, refresh] = useReducer((n) => n + 1, 0);
26
+ const [notice, setNotice] = useState("");
27
+ const [sending, setSending] = useState(false);
28
+ const sendLock = useRef(false);
29
+ const [attachments] = useState(() => new AssistantAttachments(refresh, setNotice));
30
+ attachments.options = options ?? {};
31
+ const alive = useRef(false);
32
+ useEffect(() => {
33
+ alive.current = true;
34
+ return () => {
35
+ alive.current = false;
36
+ queueMicrotask(() => { if (!alive.current)
37
+ attachments.dispose(); });
38
+ };
39
+ }, [attachments]);
40
+ const runtime = useExternalStoreRuntime({
41
+ messages: messages.current,
42
+ convertMessage,
43
+ isRunning: active && chat.status !== "idle" && chat.status !== "error" && chat.status !== "waiting",
44
+ isSendDisabled: !active || blocked || attachments.blocked,
45
+ onNew: async (message) => {
46
+ if (!alive.current || latest.current.activeSessionId !== id)
47
+ throw new MessageNotSentError("会话已切换,请返回原会话重新发送。");
48
+ const files = attachments.take(message.attachments ?? []);
49
+ const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
50
+ attachments.commit(message.attachments ?? []);
51
+ setNotice("");
52
+ await latest.current.sendMessage(text, files);
53
+ },
54
+ onCancel: async () => { latest.current.cancel(); },
55
+ adapters: {
56
+ attachments: options === false ? undefined : attachments,
57
+ threadList: {
58
+ threadId: id,
59
+ threads: chat.sessions.map((session) => ({ id: session.id, title: session.title, status: "regular" })),
60
+ onSwitchToNewThread: () => { latest.current.createSession(); },
61
+ onSwitchToThread: (next) => latest.current.switchSession(next),
62
+ onRename: (target, title) => latest.current.renameSession(target, title),
63
+ onDelete: (target) => latest.current.deleteSession(target),
64
+ },
65
+ },
66
+ });
67
+ const send = async () => {
68
+ const draft = runtime.thread.composer.getState();
69
+ if (!active || blocked || attachments.blocked || sendLock.current || draft.isEmpty)
70
+ return;
71
+ sendLock.current = true;
72
+ setSending(true);
73
+ setNotice("");
74
+ try {
75
+ // Prepare before dispatch: the upstream void send API cannot report upload
76
+ // rejections to its caller. Keep the draft intact until every file settles.
77
+ const results = await Promise.allSettled(draft.attachments.map((attachment) => attachments.send(attachment)));
78
+ const failed = results.find((result) => result.status === "rejected");
79
+ if (failed?.status === "rejected")
80
+ throw failed.reason;
81
+ if (!alive.current)
82
+ return;
83
+ if (latest.current.activeSessionId !== id)
84
+ throw new Error("会话已切换,请返回原会话重新发送。");
85
+ assertChatSendable(latest.current, id);
86
+ const completed = results.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
87
+ const files = attachments.take(completed);
88
+ attachments.commit(completed);
89
+ runtime.thread.composer.reset();
90
+ void latest.current.sendMessage(draft.text, files).catch(() => undefined);
91
+ }
92
+ catch (error) {
93
+ if (alive.current && !(error instanceof DOMException && error.name === "AbortError"))
94
+ setNotice(error instanceof Error ? error.message : String(error));
95
+ }
96
+ finally {
97
+ sendLock.current = false;
98
+ if (alive.current)
99
+ setSending(false);
100
+ }
101
+ };
102
+ return _jsx(AssistantRuntimeProvider, { runtime: runtime, children: active ? children({ runtime, attachments, notice, setNotice, sending, send }) : null });
103
+ }
104
+ //# sourceMappingURL=assistant-runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assistant-runtime.js","sourceRoot":"","sources":["../src/assistant-runtime.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAkB,MAAM,OAAO,CAAC;AACjG,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,uBAAuB,EAAiD,MAAM,qBAAqB,CAAC;AAC5J,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,kBAAkB,EAAgC,MAAM,YAAY,CAAC;AAM9E,MAAM,UAAU,cAAc,CAAC,OAAkB;IAC/C,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAyD,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QAC/H,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,IAAI,CAAC,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,GAA4B,CAAC;AACvK,CAAC","sourcesContent":["import { useEffect, useLayoutEffect, useReducer, useRef, useState, type ReactNode } from \"react\";\nimport { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime, type AssistantRuntime, type ThreadMessageLike } from \"@assistant-ui/react\";\nimport { AssistantAttachments, toAssistantAttachment } from \"./assistant-attachments.js\";\nimport { assertChatSendable, type useChat, type UIMessage } from \"./react.js\";\nimport type { ChatProps } from \"./types.js\";\n\ntype ChatState = ReturnType<typeof useChat>;\nexport type AssistantBinding = { runtime: AssistantRuntime; attachments: AssistantAttachments; notice: string; setNotice(message: string): void; sending: boolean; send(): Promise<void> };\n\nexport function convertMessage(message: UIMessage): ThreadMessageLike {\n const content = message.parts.map((part): Exclude<ThreadMessageLike[\"content\"], string>[number] => part.type === \"text\" ? part : {\n type: \"tool-call\", toolCallId: part.toolCallId, toolName: part.name,\n args: {},\n argsText: part.arguments, result: part.result, isError: part.isError,\n });\n if (message.role === \"user\") return { id: message.id, role: \"user\", content, attachments: message.attachments?.map(toAssistantAttachment) };\n return { id: message.id, role: \"assistant\", content, status: message.state === \"running\"\n ? { type: \"running\" } : message.state === \"error\" ? { type: \"incomplete\", reason: \"error\" } : { type: \"complete\", reason: \"stop\" } };\n}\n\n// Keep one composer per visited Session: switching the external-store thread id\n// would invalidate pending attachment work and discard that Session's draft.\nexport function SessionRuntime({ id, chat, options, blocked, active, children }: {\n id: string; chat: ChatState; options: ChatProps[\"attachments\"]; blocked: boolean; active: boolean;\n children(binding: AssistantBinding): ReactNode;\n}) {\n const latest = useRef(chat);\n useLayoutEffect(() => { latest.current = chat; });\n const messages = useRef<readonly UIMessage[]>([]);\n if (chat.activeSessionId === id) messages.current = chat.messages;\n const [, refresh] = useReducer((n: number) => n + 1, 0);\n const [notice, setNotice] = useState(\"\");\n const [sending, setSending] = useState(false);\n const sendLock = useRef(false);\n const [attachments] = useState(() => new AssistantAttachments(refresh, setNotice));\n attachments.options = options ?? {};\n const alive = useRef(false);\n useEffect(() => {\n alive.current = true;\n return () => {\n alive.current = false;\n queueMicrotask(() => { if (!alive.current) attachments.dispose(); });\n };\n }, [attachments]);\n const runtime = useExternalStoreRuntime<UIMessage>({\n messages: messages.current,\n convertMessage,\n isRunning: active && chat.status !== \"idle\" && chat.status !== \"error\" && chat.status !== \"waiting\",\n isSendDisabled: !active || blocked || attachments.blocked,\n onNew: async (message) => {\n if (!alive.current || latest.current.activeSessionId !== id) throw new MessageNotSentError(\"会话已切换,请返回原会话重新发送。\");\n const files = attachments.take(message.attachments ?? []);\n const text = message.content.flatMap((part) => part.type === \"text\" ? [part.text] : []).join(\"\");\n attachments.commit(message.attachments ?? []);\n setNotice(\"\");\n await latest.current.sendMessage(text, files);\n },\n onCancel: async () => { latest.current.cancel(); },\n adapters: {\n attachments: options === false ? undefined : attachments,\n threadList: {\n threadId: id,\n threads: chat.sessions.map((session) => ({ id: session.id, title: session.title, status: \"regular\" as const })),\n onSwitchToNewThread: () => { latest.current.createSession(); },\n onSwitchToThread: (next) => latest.current.switchSession(next),\n onRename: (target, title) => latest.current.renameSession(target, title),\n onDelete: (target) => latest.current.deleteSession(target),\n },\n },\n });\n const send = async () => {\n const draft = runtime.thread.composer.getState();\n if (!active || blocked || attachments.blocked || sendLock.current || draft.isEmpty) return;\n sendLock.current = true;\n setSending(true);\n setNotice(\"\");\n try {\n // Prepare before dispatch: the upstream void send API cannot report upload\n // rejections to its caller. Keep the draft intact until every file settles.\n const results = await Promise.allSettled(draft.attachments.map((attachment) => attachments.send(attachment)));\n const failed = results.find((result) => result.status === \"rejected\");\n if (failed?.status === \"rejected\") throw failed.reason;\n if (!alive.current) return;\n if (latest.current.activeSessionId !== id) throw new Error(\"会话已切换,请返回原会话重新发送。\");\n assertChatSendable(latest.current, id);\n const completed = results.flatMap((result) => result.status === \"fulfilled\" ? [result.value] : []);\n const files = attachments.take(completed);\n attachments.commit(completed);\n runtime.thread.composer.reset();\n void latest.current.sendMessage(draft.text, files).catch(() => undefined);\n } catch (error) {\n if (alive.current && !(error instanceof DOMException && error.name === \"AbortError\")) setNotice(error instanceof Error ? error.message : String(error));\n } finally {\n sendLock.current = false;\n if (alive.current) setSending(false);\n }\n };\n return <AssistantRuntimeProvider runtime={runtime}>{active ? children({ runtime, attachments, notice, setNotice, sending, send }) : null}</AssistantRuntimeProvider>;\n}\n"]}
@@ -3,8 +3,10 @@ import type { ChatAttachmentOptions } from "./types.js";
3
3
  export interface Attachment {
4
4
  id: string;
5
5
  name: string;
6
- content: AgentInputContent;
6
+ content: AgentInputContent | AgentInputContent[];
7
7
  preview?: string;
8
8
  }
9
9
  export declare const attachmentAccept = ".txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp";
10
+ export declare const attachmentContent: (attachment: Attachment) => AgentInputContent[];
11
+ export declare function validateAttachment(file: File, options: ChatAttachmentOptions): void;
10
12
  export declare function readAttachment(file: File, options: ChatAttachmentOptions): Promise<Attachment>;
@@ -3,6 +3,19 @@ const types = {
3
3
  png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp",
4
4
  };
5
5
  export const attachmentAccept = ".txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp";
6
+ export const attachmentContent = (attachment) => Array.isArray(attachment.content) ? attachment.content : [attachment.content];
7
+ export function validateAttachment(file, options) {
8
+ if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
9
+ throw new Error("附件大小限制必须是正数。");
10
+ if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024))
11
+ throw new Error(`文件过大:${file.name}`);
12
+ const extension = file.name.split(".").at(-1)?.toLowerCase() ?? "";
13
+ const mime = file.type || types[extension] || "";
14
+ const accepted = (options.accept ?? attachmentAccept).split(",").map((part) => part.trim().toLowerCase());
15
+ if (!accepted.some((part) => part === "*" || part === `.${extension}` || part === mime
16
+ || part.endsWith("/*") && mime.startsWith(part.slice(0, -1))))
17
+ throw new Error(`不接受此文件:${file.name}`);
18
+ }
6
19
  export async function readAttachment(file, options) {
7
20
  if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
8
21
  throw new Error("附件大小限制必须是正数。");
@@ -1 +1 @@
1
- {"version":3,"file":"attachments.js","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"AAUA,MAAM,KAAK,GAA2B;IACpC,GAAG,EAAE,YAAY,EAAE,EAAE,EAAE,eAAe,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,kBAAkB;IACjF,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,YAAY;CAC5E,CAAC;AACF,MAAM,CAAC,MAAM,gBAAgB,GAAG,2CAA2C,CAAC;AAE5E,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAU,EAAE,OAA8B;IAC7E,IAAI,OAAO,CAAC,YAAY,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,YAAY,IAAI,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;IACjJ,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC;IACnE,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC;IAC9B,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC,EAAE,CAAC;QACtG,MAAM,IAAI,KAAK,CAAC,WAAW,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IAC1C,CAAC;IAC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IAAU,EAAE,KAAc;IACtC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAChC,MAAM,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;QACrD,MAAM,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,UAAU,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAChE,IAAI,KAAK;YAAE,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;;YACjC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { AgentInputContent } from \"@nexface/agent\";\nimport type { ChatAttachmentOptions } from \"./types.js\";\n\nexport interface Attachment {\n id: string;\n name: string;\n content: AgentInputContent | AgentInputContent[];\n preview?: string;\n}\n\nconst types: Record<string, string> = {\n txt: \"text/plain\", md: \"text/markdown\", csv: \"text/csv\", json: \"application/json\",\n png: \"image/png\", jpg: \"image/jpeg\", jpeg: \"image/jpeg\", webp: \"image/webp\",\n};\nexport const attachmentAccept = \".txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp\";\n\nexport const attachmentContent = (attachment: Attachment): AgentInputContent[] =>\n Array.isArray(attachment.content) ? attachment.content : [attachment.content];\n\nexport function validateAttachment(file: File, options: ChatAttachmentOptions): void {\n if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0)) throw new Error(\"附件大小限制必须是正数。\");\n if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024)) throw new Error(`文件过大:${file.name}`);\n const extension = file.name.split(\".\").at(-1)?.toLowerCase() ?? \"\";\n const mime = file.type || types[extension] || \"\";\n const accepted = (options.accept ?? attachmentAccept).split(\",\").map((part) => part.trim().toLowerCase());\n if (!accepted.some((part) => part === \"*\" || part === `.${extension}` || part === mime\n || part.endsWith(\"/*\") && mime.startsWith(part.slice(0, -1)))) throw new Error(`不接受此文件:${file.name}`);\n}\n\nexport async function readAttachment(file: File, options: ChatAttachmentOptions): Promise<Attachment> {\n if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0)) throw new Error(\"附件大小限制必须是正数。\");\n const extension = file.name.split(\".\").at(-1)?.toLowerCase() ?? \"\";\n const mime = types[extension];\n if (!mime || (file.type && file.type !== mime && !(extension === \"md\" && file.type === \"text/plain\"))) {\n throw new Error(`不支持文件类型:${file.name}`);\n }\n const accepted = (options.accept ?? attachmentAccept).split(\",\").map((part) => part.trim().toLowerCase());\n if (!accepted.some((part) => part === `.${extension}` || part === mime\n || part.endsWith(\"/*\") && mime.startsWith(part.slice(0, -1)))) {\n throw new Error(`不接受此文件:${file.name}`);\n }\n if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024)) throw new Error(`文件过大:${file.name}`);\n const id = globalThis.crypto.randomUUID();\n if (!mime.startsWith(\"image/\")) {\n const value = await read(file, false);\n return { id, name: file.name, content: { type: \"text\", text: `附件 ${file.name}\\n${value}` } };\n }\n const preview = await read(file, true);\n return { id, name: file.name, preview, content: {\n type: \"image\", source: { type: \"data\", value: preview.slice(preview.indexOf(\",\") + 1), mimeType: mime },\n } };\n}\n\nfunction read(file: File, image: boolean): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(String(reader.result));\n reader.onerror = () => reject(new Error(`无法读取文件:${file.name}`));\n if (image) reader.readAsDataURL(file);\n else reader.readAsText(file);\n });\n}\n"]}
package/dist/client.d.ts CHANGED
@@ -55,7 +55,7 @@ declare class ChatClientImplementation implements ChatClient {
55
55
  id: string;
56
56
  readonly agent: Agent | undefined;
57
57
  readonly runtime: ToolRuntime;
58
- constructor(options: ChatClientOptions);
58
+ constructor(options: ChatClientOptions, model?: AgentModelConfig);
59
59
  getMessages: () => readonly Message[];
60
60
  getStatus: () => ChatClientStatus;
61
61
  getApproval: () => ToolApprovalInterruptDescriptor | undefined;
@@ -66,6 +66,7 @@ declare class ChatClientImplementation implements ChatClient {
66
66
  get busy(): boolean;
67
67
  setPageResolver(resolver: (name: string) => boolean): void;
68
68
  restore(messages: UIMessage[], conversation: readonly AgentMessage[]): void;
69
+ recreateBefore(messageId: string): ChatClient;
69
70
  switchModel(model: AgentModelConfig): Promise<void>;
70
71
  sendMessage: (content: string | readonly AgentInputContent[]) => Promise<{
71
72
  readonly outcome: Extract<NonNullable<import("@ag-ui/core").RunFinishedEvent["outcome"]>, {