@njuptlzf/agent-chat-web 0.2.0 → 0.4.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.
- package/dist/AgentChat.d.ts +7 -1
- package/dist/AgentChat.js +35 -5
- package/dist/AgentChatApp.d.ts +4 -1
- package/dist/AgentChatApp.js +2 -2
- package/dist/PersonasPage.js +8 -0
- package/dist/adapter.d.ts +9 -0
- package/dist/adapter.js +15 -0
- package/dist/mount.d.ts +7 -1
- package/dist/mount.js +2 -2
- package/dist/styles.css +1505 -1478
- package/dist/suggestions.d.ts +41 -0
- package/dist/suggestions.js +98 -0
- package/dist/ui/FollowUpSuggestions.d.ts +9 -0
- package/dist/ui/FollowUpSuggestions.js +13 -0
- package/dist/ui/Icon.d.ts +8 -0
- package/dist/ui/Icon.js +26 -0
- package/dist/ui/MemberCards.d.ts +15 -0
- package/dist/ui/MemberCards.js +13 -0
- package/dist/ui/icons.d.ts +19 -0
- package/dist/ui/icons.js +25 -0
- package/dist/ui/members.d.ts +42 -0
- package/dist/ui/members.js +53 -0
- package/dist/ui/slots.d.ts +29 -0
- package/dist/ui/slots.js +14 -0
- package/package.json +71 -72
- package/src/App.tsx +13 -13
- package/src/agent-chat/AgentChat.tsx +741 -692
- package/src/agent-chat/AgentChatApp.tsx +211 -206
- package/src/agent-chat/DockPanel.tsx +73 -73
- package/src/agent-chat/PersonasPage.tsx +705 -678
- package/src/agent-chat/adapter.ts +293 -272
- package/src/agent-chat/app-def-check.ts +215 -215
- package/src/agent-chat/app.tsx +327 -327
- package/src/agent-chat/auth.ts +83 -83
- package/src/agent-chat/dock.ts +161 -161
- package/src/agent-chat/docs.ts +179 -179
- package/src/agent-chat/index.ts +17 -17
- package/src/agent-chat/mount.tsx +130 -123
- package/src/agent-chat/qual.ts +55 -55
- package/src/agent-chat/sse.ts +104 -104
- package/src/agent-chat/suggestions.ts +127 -0
- package/src/agent-chat/theme.ts +23 -23
- package/src/agent-chat/ui/CodeCopyHeader.tsx +29 -29
- package/src/agent-chat/ui/ConfirmCard.tsx +32 -32
- package/src/agent-chat/ui/FollowUpSuggestions.tsx +28 -0
- package/src/agent-chat/ui/Icon.tsx +53 -0
- package/src/agent-chat/ui/Lightbox.tsx +32 -32
- package/src/agent-chat/ui/MemberCards.tsx +46 -0
- package/src/agent-chat/ui/QueueBar.tsx +70 -70
- package/src/agent-chat/ui/Splitter.tsx +81 -81
- package/src/agent-chat/ui/ThemeToggle.tsx +25 -25
- package/src/agent-chat/ui/TierPicker.tsx +112 -112
- package/src/agent-chat/ui/UIPromptCard.tsx +68 -68
- package/src/agent-chat/ui/icons.ts +31 -0
- package/src/agent-chat/ui/members.ts +106 -0
- package/src/agent-chat/ui/slots.tsx +41 -0
- package/src/agent-chat/ui/timefmt.ts +110 -110
- package/src/agent-chat/ui/useNarrow.ts +20 -20
- package/src/fake-product/entry.tsx +63 -54
- package/src/main.tsx +8 -8
- package/src/styles.css +1505 -1478
package/src/agent-chat/mount.tsx
CHANGED
|
@@ -1,123 +1,130 @@
|
|
|
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 AgentChatApp from "./AgentChatApp.tsx";
|
|
18
|
-
import DockPanel from "./DockPanel.tsx";
|
|
19
|
-
import { AppShell, themeVarsOf, useAppHost, type AppDef } from "./app.tsx";
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
persona
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
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 AgentChatApp from "./AgentChatApp.tsx";
|
|
18
|
+
import DockPanel from "./DockPanel.tsx";
|
|
19
|
+
import { AppShell, themeVarsOf, useAppHost, type AppDef } from "./app.tsx";
|
|
20
|
+
import type { Slots } from "./ui/slots.tsx";
|
|
21
|
+
|
|
22
|
+
/** 宿主状态(`useAppHost` 的返回值):插槽从这里取品牌、身份、路由、人格。 */
|
|
23
|
+
export type AppHost = ReturnType<typeof useAppHost>;
|
|
24
|
+
|
|
25
|
+
/** 产品给的界面文案:全由 branding(manifest 声明)与当前人格决定。 */
|
|
26
|
+
export interface AppTexts {
|
|
27
|
+
/** 坞标题(换人格时要换,否则点了「声明人格」还写着「默认助手」)。 */
|
|
28
|
+
title: string;
|
|
29
|
+
/** 助手在界面上的叫法(「正在回答」这类提示语用)。 */
|
|
30
|
+
assistantLabel: string;
|
|
31
|
+
/** 提示条:这个助手是谁、不做什么。 */
|
|
32
|
+
policyNote?: string;
|
|
33
|
+
welcome?: string;
|
|
34
|
+
suggestions?: string[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface AgentAppProps {
|
|
38
|
+
/** 导航注册表(产品事实)。 */
|
|
39
|
+
def: AppDef;
|
|
40
|
+
/** 文案兜底:core 不认得任何人格名,也不写死任何一句话。 */
|
|
41
|
+
texts(branding: BrandingResponse, persona: string): AppTexts;
|
|
42
|
+
/**
|
|
43
|
+
* 视觉件槽位覆盖(可插拔):整体替换 Icon / FollowUpSuggestions 等。
|
|
44
|
+
* 组件写结构兼容的形状即可(类型不导出,避免新增公开符号);不传 = 全默认。
|
|
45
|
+
*/
|
|
46
|
+
slots?: Partial<Slots>;
|
|
47
|
+
/** 侧栏底部的产品入口(声明人格、反馈问题…)。闭包,不能调 hook。 */
|
|
48
|
+
footer?(host: AppHost): ReactNode;
|
|
49
|
+
/** 宿主级组件(每日总结、反馈抽屉…)。闭包,不能调 hook。 */
|
|
50
|
+
extras?(host: AppHost): ReactNode;
|
|
51
|
+
/** 加载失败时给产品的启动提示(core 不知道启动命令长什么样)。 */
|
|
52
|
+
loadErrorHint?: ReactNode;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 产品组合根:branding/whoami → 宿主状态 → 侧栏 + 坞 + 页面。
|
|
57
|
+
*
|
|
58
|
+
* 与改造前 `App.tsx` 的行为逐项对齐(full/compact 的判据、key 重挂、插槽位置),
|
|
59
|
+
* 差别只有一处:人格不再由 core 判断"谁是声明人格"——`host.persona` 原样传给
|
|
60
|
+
* `AgentChatApp`("" 收敛成 undefined = 产品默认助手),文案由 `texts` 决定。
|
|
61
|
+
*/
|
|
62
|
+
export function AgentApp({ def, texts, slots, footer, extras, loadErrorHint }: AgentAppProps) {
|
|
63
|
+
const host = useAppHost(def);
|
|
64
|
+
if (host.loadError) {
|
|
65
|
+
return (
|
|
66
|
+
<div className="center">
|
|
67
|
+
<p>无法连接服务:{host.loadError}</p>
|
|
68
|
+
{loadErrorHint}
|
|
69
|
+
</div>
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
if (!host.ready) return <div className="center">加载中…</div>;
|
|
73
|
+
|
|
74
|
+
const { branding, who, qual, route, shown, onQuals, persona, go, ctx } = host;
|
|
75
|
+
// 坞是否撑满内容区。同一个判据喂给 Dock.full 与 AgentChatApp.compact
|
|
76
|
+
// (2026-11-03:以前 compact 单独判「路由不是聊天页」,漏了选项页这种
|
|
77
|
+
// 「路由还是 chatRoute 但坞不是全屏」的状态,会话侧栏把输入框挤成 56px)。
|
|
78
|
+
const dockFull = !onQuals && route === def.chatRoute;
|
|
79
|
+
const t = texts(branding, persona);
|
|
80
|
+
|
|
81
|
+
return (
|
|
82
|
+
<div className="shell" style={themeVarsOf(branding)}>
|
|
83
|
+
<AppShell
|
|
84
|
+
branding={branding}
|
|
85
|
+
qual={qual}
|
|
86
|
+
route={shown}
|
|
87
|
+
nav={def.navItems(ctx!)}
|
|
88
|
+
who={who}
|
|
89
|
+
// 侧栏导航回聊天路由 = 回**默认人格**(2026-11-04):从声明人格切「默认助手」时只改
|
|
90
|
+
// 路由的话,人格还挂在声明人格上,标题/预备问题都不换。人格化入口(人格化按钮)
|
|
91
|
+
// 走 host.go 自己先 setPersona,不经过这里,所以不会被这条冲掉。
|
|
92
|
+
onRoute={(r) => {
|
|
93
|
+
if (r === def.chatRoute && host.persona) host.setPersona("");
|
|
94
|
+
go(r);
|
|
95
|
+
}}
|
|
96
|
+
onQuals={() => go("quals")}
|
|
97
|
+
switchTitle={def.labels?.switchTitle}
|
|
98
|
+
footer={footer?.(host)}
|
|
99
|
+
>
|
|
100
|
+
<DockPanel
|
|
101
|
+
title={t.title}
|
|
102
|
+
full={dockFull}
|
|
103
|
+
onClose={host.closeChat}
|
|
104
|
+
chat={
|
|
105
|
+
<AgentChatApp
|
|
106
|
+
// key 让切人格时重挂:会话绑死人格,同一个实例换 persona 只会撞 persona_mismatch。
|
|
107
|
+
key={persona}
|
|
108
|
+
branding={branding}
|
|
109
|
+
scope={qual?.id}
|
|
110
|
+
renderCard={def.cardRenderer}
|
|
111
|
+
slots={slots}
|
|
112
|
+
// core 只做形状收敛("" → undefined = 产品默认助手),不认识具体名字。
|
|
113
|
+
persona={persona || undefined}
|
|
114
|
+
title={t.title}
|
|
115
|
+
assistantLabel={t.assistantLabel}
|
|
116
|
+
policyNote={t.policyNote}
|
|
117
|
+
welcome={t.welcome}
|
|
118
|
+
suggestions={t.suggestions}
|
|
119
|
+
compact={!dockFull}
|
|
120
|
+
/>
|
|
121
|
+
}
|
|
122
|
+
>
|
|
123
|
+
{def.page(ctx!)}
|
|
124
|
+
</DockPanel>
|
|
125
|
+
{/* 宿主级、只在 boot 拉一次的东西(每日总结弹窗等):切路由不该让它重挂。 */}
|
|
126
|
+
{extras?.(host)}
|
|
127
|
+
</AppShell>
|
|
128
|
+
</div>
|
|
129
|
+
);
|
|
130
|
+
}
|
package/src/agent-chat/qual.ts
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
|
-
|
|
2
|
-
/**
|
|
3
|
-
* 当前选项的本地偏好(从 <product>/qual.ts 拆入 core):
|
|
4
|
-
* 产品可选项目录是通用协议形状,"记住上次选了哪一项"是壳机制不是产品事实。
|
|
5
|
-
* 存储键保持 `ac.qual` 不变——老用户的偏好直接沿用。
|
|
6
|
-
*
|
|
7
|
-
* 产品侧只留具体选项的语义与路由映射。
|
|
8
|
-
*/
|
|
9
|
-
const KEY = "ac.qual";
|
|
10
|
-
|
|
11
|
-
function loadQual(): string | null {
|
|
12
|
-
try {
|
|
13
|
-
return localStorage.getItem(KEY);
|
|
14
|
-
} catch {
|
|
15
|
-
return null;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export function saveQual(id: string): void {
|
|
20
|
-
try {
|
|
21
|
-
localStorage.setItem(KEY, id);
|
|
22
|
-
} catch {
|
|
23
|
-
// 隐私模式下 localStorage 可能抛错;选项只是偏好,丢了回选择页即可。
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** 可用 = 内容已就绪(`enabled` 不为 false)。 */
|
|
28
|
-
export function isEnabled(q: { enabled?: boolean }): boolean {
|
|
29
|
-
return q.enabled !== false;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/** 当前选项:本地记忆优先,否则回落第一个可用的选项。 */
|
|
33
|
-
export function currentQual<T extends { id: string; enabled?: boolean }>(quals: T[] | undefined): T | null {
|
|
34
|
-
if (!quals || quals.length === 0) return null;
|
|
35
|
-
const saved = loadQual();
|
|
36
|
-
const hit = saved ? quals.find((q) => q.id === saved && isEnabled(q)) : undefined;
|
|
37
|
-
return hit ?? quals.find(isEnabled) ?? null;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* 深链里的选项(`#/<业务页>?qual=<轨道>&id=…`)。
|
|
42
|
-
*
|
|
43
|
-
* 为什么需要:页面记住的选项(ac.qual)与会话的 `AC_SCOPE` 是两件事——助手在
|
|
44
|
-
* system-integration 的会话里给了一张题卡,点进去时页面可能还停在 architect,
|
|
45
|
-
* 结果 404。深链把选项带上,壳静默切过去。
|
|
46
|
-
*
|
|
47
|
-
* 只认 `?` 之后的 query 段:路径里也可能出现 qual 字样(`#/quals`),用 includes
|
|
48
|
-
* 判断会误伤。空值当没写。
|
|
49
|
-
*/
|
|
50
|
-
export function qualFromHash(hash: string): string | null {
|
|
51
|
-
const q = hash.indexOf("?");
|
|
52
|
-
if (q < 0) return null;
|
|
53
|
-
const id = new URLSearchParams(hash.slice(q + 1)).get("qual");
|
|
54
|
-
return id ? id : null;
|
|
55
|
-
}
|
|
1
|
+
|
|
2
|
+
/**
|
|
3
|
+
* 当前选项的本地偏好(从 <product>/qual.ts 拆入 core):
|
|
4
|
+
* 产品可选项目录是通用协议形状,"记住上次选了哪一项"是壳机制不是产品事实。
|
|
5
|
+
* 存储键保持 `ac.qual` 不变——老用户的偏好直接沿用。
|
|
6
|
+
*
|
|
7
|
+
* 产品侧只留具体选项的语义与路由映射。
|
|
8
|
+
*/
|
|
9
|
+
const KEY = "ac.qual";
|
|
10
|
+
|
|
11
|
+
function loadQual(): string | null {
|
|
12
|
+
try {
|
|
13
|
+
return localStorage.getItem(KEY);
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function saveQual(id: string): void {
|
|
20
|
+
try {
|
|
21
|
+
localStorage.setItem(KEY, id);
|
|
22
|
+
} catch {
|
|
23
|
+
// 隐私模式下 localStorage 可能抛错;选项只是偏好,丢了回选择页即可。
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 可用 = 内容已就绪(`enabled` 不为 false)。 */
|
|
28
|
+
export function isEnabled(q: { enabled?: boolean }): boolean {
|
|
29
|
+
return q.enabled !== false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 当前选项:本地记忆优先,否则回落第一个可用的选项。 */
|
|
33
|
+
export function currentQual<T extends { id: string; enabled?: boolean }>(quals: T[] | undefined): T | null {
|
|
34
|
+
if (!quals || quals.length === 0) return null;
|
|
35
|
+
const saved = loadQual();
|
|
36
|
+
const hit = saved ? quals.find((q) => q.id === saved && isEnabled(q)) : undefined;
|
|
37
|
+
return hit ?? quals.find(isEnabled) ?? null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 深链里的选项(`#/<业务页>?qual=<轨道>&id=…`)。
|
|
42
|
+
*
|
|
43
|
+
* 为什么需要:页面记住的选项(ac.qual)与会话的 `AC_SCOPE` 是两件事——助手在
|
|
44
|
+
* system-integration 的会话里给了一张题卡,点进去时页面可能还停在 architect,
|
|
45
|
+
* 结果 404。深链把选项带上,壳静默切过去。
|
|
46
|
+
*
|
|
47
|
+
* 只认 `?` 之后的 query 段:路径里也可能出现 qual 字样(`#/quals`),用 includes
|
|
48
|
+
* 判断会误伤。空值当没写。
|
|
49
|
+
*/
|
|
50
|
+
export function qualFromHash(hash: string): string | null {
|
|
51
|
+
const q = hash.indexOf("?");
|
|
52
|
+
if (q < 0) return null;
|
|
53
|
+
const id = new URLSearchParams(hash.slice(q + 1)).get("qual");
|
|
54
|
+
return id ? id : null;
|
|
55
|
+
}
|
package/src/agent-chat/sse.ts
CHANGED
|
@@ -1,104 +1,104 @@
|
|
|
1
|
-
import type { ChatEvent, ChatRequest, ConfirmDecision } from "@njuptlzf/agent-chat-protocol";
|
|
2
|
-
import { apiHeaders } from "./auth.ts";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Turn a non-2xx response into an Error carrying the server's own message.
|
|
6
|
-
*
|
|
7
|
-
* 服务端的 400 是给人看的(「标签最多 20 个字」「unknown tag "x"」),只抛
|
|
8
|
-
* `HTTP 400` 会把这些话全丢掉,用户只能看到一个状态码。读不出 JSON 就退回状态码。
|
|
9
|
-
*/
|
|
10
|
-
async function fail(res: Response): Promise<Error> {
|
|
11
|
-
let detail = "";
|
|
12
|
-
try {
|
|
13
|
-
const body = (await res.json()) as { error?: { message?: string } };
|
|
14
|
-
detail = body?.error?.message ?? "";
|
|
15
|
-
} catch {
|
|
16
|
-
// 不是 JSON(网关错误页之类)——状态码已经够用。
|
|
17
|
-
}
|
|
18
|
-
return new Error(detail ? `${detail}(HTTP ${res.status})` : `HTTP ${res.status}`);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** GET a JSON API with the optional host auth token; throws on non-2xx. */
|
|
22
|
-
export async function fetchJson<T>(path: string, authHeader?: string): Promise<T> {
|
|
23
|
-
const res = await fetch(path, { headers: apiHeaders(authHeader) });
|
|
24
|
-
if (!res.ok) throw await fail(res);
|
|
25
|
-
return res.json() as Promise<T>;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** POST a JSON body with the optional host auth token; throws on non-2xx. */
|
|
29
|
-
export async function postJson<T>(path: string, body: unknown, authHeader?: string): Promise<T> {
|
|
30
|
-
const res = await fetch(path, {
|
|
31
|
-
method: "POST",
|
|
32
|
-
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
33
|
-
body: JSON.stringify(body),
|
|
34
|
-
});
|
|
35
|
-
if (!res.ok) throw await fail(res);
|
|
36
|
-
return res.json() as Promise<T>;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** DELETE with the optional host auth token; throws on non-2xx. */
|
|
40
|
-
export async function deleteJson<T>(path: string, authHeader?: string): Promise<T> {
|
|
41
|
-
const res = await fetch(path, {
|
|
42
|
-
method: "DELETE",
|
|
43
|
-
headers: apiHeaders(authHeader),
|
|
44
|
-
});
|
|
45
|
-
if (!res.ok) throw await fail(res);
|
|
46
|
-
return res.json() as Promise<T>;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** Answer a `tool_confirm` event; must be called while its run's stream is open. */
|
|
50
|
-
export async function postDecision(dec: ConfirmDecision, authHeader?: string): Promise<boolean> {
|
|
51
|
-
const res = await fetch("/api/decision", {
|
|
52
|
-
method: "POST",
|
|
53
|
-
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
54
|
-
body: JSON.stringify(dec),
|
|
55
|
-
});
|
|
56
|
-
return res.ok;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* POST /api/chat and stream back protocol events. SSE frames are
|
|
61
|
-
* `data: <json>\n\n`; we parse them by hand because EventSource cannot POST.
|
|
62
|
-
*/
|
|
63
|
-
export async function* streamChat(
|
|
64
|
-
req: ChatRequest,
|
|
65
|
-
signal: AbortSignal,
|
|
66
|
-
authHeader?: string,
|
|
67
|
-
): AsyncGenerator<ChatEvent> {
|
|
68
|
-
const res = await fetch("/api/chat", {
|
|
69
|
-
method: "POST",
|
|
70
|
-
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
71
|
-
body: JSON.stringify(req),
|
|
72
|
-
signal,
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
if (!res.ok || !res.body) {
|
|
76
|
-
// Non-SSE error responses (401/404/429/…) carry { error: { code, message } }.
|
|
77
|
-
let message = `HTTP ${res.status}`;
|
|
78
|
-
try {
|
|
79
|
-
const body = (await res.json()) as { error?: { message?: string } };
|
|
80
|
-
if (body.error?.message) message = body.error.message;
|
|
81
|
-
} catch {
|
|
82
|
-
/* keep the status line */
|
|
83
|
-
}
|
|
84
|
-
yield { type: "error", code: res.status === 401 ? "unauthorized" : res.status === 429 ? "quota_exceeded" : "internal", message, retryable: false };
|
|
85
|
-
yield { type: "done", aborted: false, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 } };
|
|
86
|
-
return;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
const reader = res.body.getReader();
|
|
90
|
-
const decoder = new TextDecoder();
|
|
91
|
-
let buf = "";
|
|
92
|
-
while (true) {
|
|
93
|
-
const { value, done } = await reader.read();
|
|
94
|
-
if (done) break;
|
|
95
|
-
buf += decoder.decode(value, { stream: true });
|
|
96
|
-
let idx;
|
|
97
|
-
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
98
|
-
const frame = buf.slice(0, idx);
|
|
99
|
-
buf = buf.slice(idx + 2);
|
|
100
|
-
const line = frame.split("\n").find((l) => l.startsWith("data: "));
|
|
101
|
-
if (line) yield JSON.parse(line.slice(6)) as ChatEvent;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
1
|
+
import type { ChatEvent, ChatRequest, ConfirmDecision } from "@njuptlzf/agent-chat-protocol";
|
|
2
|
+
import { apiHeaders } from "./auth.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Turn a non-2xx response into an Error carrying the server's own message.
|
|
6
|
+
*
|
|
7
|
+
* 服务端的 400 是给人看的(「标签最多 20 个字」「unknown tag "x"」),只抛
|
|
8
|
+
* `HTTP 400` 会把这些话全丢掉,用户只能看到一个状态码。读不出 JSON 就退回状态码。
|
|
9
|
+
*/
|
|
10
|
+
async function fail(res: Response): Promise<Error> {
|
|
11
|
+
let detail = "";
|
|
12
|
+
try {
|
|
13
|
+
const body = (await res.json()) as { error?: { message?: string } };
|
|
14
|
+
detail = body?.error?.message ?? "";
|
|
15
|
+
} catch {
|
|
16
|
+
// 不是 JSON(网关错误页之类)——状态码已经够用。
|
|
17
|
+
}
|
|
18
|
+
return new Error(detail ? `${detail}(HTTP ${res.status})` : `HTTP ${res.status}`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** GET a JSON API with the optional host auth token; throws on non-2xx. */
|
|
22
|
+
export async function fetchJson<T>(path: string, authHeader?: string): Promise<T> {
|
|
23
|
+
const res = await fetch(path, { headers: apiHeaders(authHeader) });
|
|
24
|
+
if (!res.ok) throw await fail(res);
|
|
25
|
+
return res.json() as Promise<T>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** POST a JSON body with the optional host auth token; throws on non-2xx. */
|
|
29
|
+
export async function postJson<T>(path: string, body: unknown, authHeader?: string): Promise<T> {
|
|
30
|
+
const res = await fetch(path, {
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
33
|
+
body: JSON.stringify(body),
|
|
34
|
+
});
|
|
35
|
+
if (!res.ok) throw await fail(res);
|
|
36
|
+
return res.json() as Promise<T>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** DELETE with the optional host auth token; throws on non-2xx. */
|
|
40
|
+
export async function deleteJson<T>(path: string, authHeader?: string): Promise<T> {
|
|
41
|
+
const res = await fetch(path, {
|
|
42
|
+
method: "DELETE",
|
|
43
|
+
headers: apiHeaders(authHeader),
|
|
44
|
+
});
|
|
45
|
+
if (!res.ok) throw await fail(res);
|
|
46
|
+
return res.json() as Promise<T>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Answer a `tool_confirm` event; must be called while its run's stream is open. */
|
|
50
|
+
export async function postDecision(dec: ConfirmDecision, authHeader?: string): Promise<boolean> {
|
|
51
|
+
const res = await fetch("/api/decision", {
|
|
52
|
+
method: "POST",
|
|
53
|
+
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
54
|
+
body: JSON.stringify(dec),
|
|
55
|
+
});
|
|
56
|
+
return res.ok;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* POST /api/chat and stream back protocol events. SSE frames are
|
|
61
|
+
* `data: <json>\n\n`; we parse them by hand because EventSource cannot POST.
|
|
62
|
+
*/
|
|
63
|
+
export async function* streamChat(
|
|
64
|
+
req: ChatRequest,
|
|
65
|
+
signal: AbortSignal,
|
|
66
|
+
authHeader?: string,
|
|
67
|
+
): AsyncGenerator<ChatEvent> {
|
|
68
|
+
const res = await fetch("/api/chat", {
|
|
69
|
+
method: "POST",
|
|
70
|
+
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
71
|
+
body: JSON.stringify(req),
|
|
72
|
+
signal,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
if (!res.ok || !res.body) {
|
|
76
|
+
// Non-SSE error responses (401/404/429/…) carry { error: { code, message } }.
|
|
77
|
+
let message = `HTTP ${res.status}`;
|
|
78
|
+
try {
|
|
79
|
+
const body = (await res.json()) as { error?: { message?: string } };
|
|
80
|
+
if (body.error?.message) message = body.error.message;
|
|
81
|
+
} catch {
|
|
82
|
+
/* keep the status line */
|
|
83
|
+
}
|
|
84
|
+
yield { type: "error", code: res.status === 401 ? "unauthorized" : res.status === 429 ? "quota_exceeded" : "internal", message, retryable: false };
|
|
85
|
+
yield { type: "done", aborted: false, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 } };
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const reader = res.body.getReader();
|
|
90
|
+
const decoder = new TextDecoder();
|
|
91
|
+
let buf = "";
|
|
92
|
+
while (true) {
|
|
93
|
+
const { value, done } = await reader.read();
|
|
94
|
+
if (done) break;
|
|
95
|
+
buf += decoder.decode(value, { stream: true });
|
|
96
|
+
let idx;
|
|
97
|
+
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
98
|
+
const frame = buf.slice(0, idx);
|
|
99
|
+
buf = buf.slice(idx + 2);
|
|
100
|
+
const line = frame.split("\n").find((l) => l.startsWith("data: "));
|
|
101
|
+
if (line) yield JSON.parse(line.slice(6)) as ChatEvent;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|