@auipage/agent 0.2.0-beta.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.
package/AUTHORS.txt CHANGED
@@ -1,6 +1,6 @@
1
- Authors ordered by first contribution.
2
-
3
- zxl20070701 <1904314465@qq.com> <https://github.com/zxl20070701>
4
-
5
- -----------------------------------------------------
6
- We thank all of them for their contributions!
1
+ Authors ordered by first contribution.
2
+
3
+ zxl20070701 <1904314465@qq.com> <https://github.com/zxl20070701>
4
+
5
+ -----------------------------------------------------
6
+ We thank all of them for their contributions!
package/CHANGELOG CHANGED
@@ -1,30 +1,30 @@
1
- v0.1.0:
2
- date:2026-10-25
3
- changes:
4
- - 初始化版本
5
- v0.2.0:
6
- date:
7
- changes:
8
- - 修复bug:
9
- 1、模型请求 4xx / 网络失败时进程崩溃或请求永久挂起
10
- 2、页面在适配器、前端工具、历史入库任一环节失败后锁死(isExecuting 一直为 true)
11
- 3、工具并行调用分片串味,无参工具的调用直接失败
12
- 4、复用同一 messages 数组时 systemPrompt 重复累积
13
- 5、流式数据含 \r 换行或末尾 [DONE] 时正文被污染、解析提前中断
14
- 6、响应结束后才订阅 error 的监听器收不到终态
15
- - 优化改造:
16
- 1、使用exports和types代替旧的导出方式并优化相关内容
17
- 2、请求支持 timeout 与 signal,可主动取消
18
- 3、非 2xx 响应新增 http-error 事件,不再只有 ok=false
19
- 4、页面历史入库失败会明确报错,不再静默丢弃
20
- 5、监听器异常不再抛出为进程级异常
21
- 6、流式生成器取消后清空挂起队列,不再堆积残留
22
- - 新增功能:
23
- 1、Agent 支持 maxSteps(默认 0,不限制)
24
- 2、新增 toModelMessages,把页面消息转成模型入参
25
- 3、新增 AuiPage.stop():执行中主动结束,内容保留、消息组标记 stopped,sendMessage 正常 resolve
26
- 4、新增 AuiPage.cancel():取消本轮,消息组标记 cancelled,sendMessage 以「已取消」reject
27
- 5、主动结束与取消的那一轮仍入库,存或丢由业务自行决定
28
- 6、task:end 增加 by(user / tool),取消时另带 displayed,列出已显示条目供界面撤销
29
- 7、工具 execute / render 拿到任务控制句柄,可直接 stop() / cancel() 结束整轮
30
- 8、取消信号经 context.signal 透传,Agent / model 均支持中断
1
+ v0.1.0:
2
+ date:2026-10-25
3
+ changes:
4
+ - 初始化版本
5
+ v0.2.0:
6
+ date:2026-12-01
7
+ changes:
8
+ - 修复bug:
9
+ 1、模型请求 4xx / 网络失败时进程崩溃或请求永久挂起
10
+ 2、页面在适配器、前端工具、历史入库任一环节失败后锁死(isExecuting 一直为 true)
11
+ 3、工具并行调用分片串味,无参工具的调用直接失败
12
+ 4、复用同一 messages 数组时 systemPrompt 重复累积
13
+ 5、流式数据含 \r 换行或末尾 [DONE] 时正文被污染、解析提前中断
14
+ 6、响应结束后才订阅 error 的监听器收不到终态
15
+ - 优化改造:
16
+ 1、使用exports和types代替旧的导出方式并优化相关内容
17
+ 2、请求支持 timeout 与 signal,可主动取消
18
+ 3、非 2xx 响应新增 http-error 事件,不再只有 ok=false
19
+ 4、页面历史入库失败会明确报错,不再静默丢弃
20
+ 5、监听器异常不再抛出为进程级异常
21
+ 6、流式生成器取消后清空挂起队列,不再堆积残留
22
+ - 新增功能:
23
+ 1、Agent 支持 maxSteps(默认 0,不限制)
24
+ 2、新增 toModelMessages,把页面消息转成模型入参
25
+ 3、新增 AuiPage.stop():执行中主动结束,内容保留、消息组标记 stopped,sendMessage 正常 resolve
26
+ 4、新增 AuiPage.cancel():取消本轮,消息组标记 cancelled,sendMessage 以「已取消」reject
27
+ 5、主动结束与取消的那一轮仍入库,存或丢由业务自行决定
28
+ 6、task:end 增加 by(user / tool),取消时另带 displayed,列出已显示条目供界面撤销
29
+ 7、工具 execute / render 拿到任务控制句柄,可直接 stop() / cancel() 结束整轮
30
+ 8、取消信号经 context.signal 透传,Agent / model 均支持中断
package/README.md CHANGED
@@ -1,136 +1,136 @@
1
- # [@auipage/agent](https://github.com/handless-ui/auipage)
2
-
3
- 智能体对话循环:模型要调工具 → 执行 → 结果回灌 → 继续生成,直到拿到最终回复。可选地把工具调用桥接到浏览器,让页面来执行。
4
-
5
- <p>
6
- <a href="https://zxl20070701.github.io/toolbox/#/npm-download?packages=@auipage/agent&interval=7">
7
- <img src="https://img.shields.io/npm/dm/@auipage/agent.svg" alt="downloads">
8
- </a>
9
- <a href="https://www.npmjs.com/package/@auipage/agent">
10
- <img src="https://img.shields.io/npm/v/@auipage/agent.svg" alt="npm">
11
- </a>
12
- <a href="https://github.com/handless-ui/auipage" target='_blank'>
13
- <img alt="GitHub repo stars" src="https://img.shields.io/github/stars/handless-ui/auipage?style=social">
14
- </a>
15
- </p>
16
-
17
- ## 它解决什么
18
-
19
- 单轮对话只是“发一条消息、收一段文本”。一旦模型会用工具,循环就变复杂了:
20
-
21
- - 模型返回 `tool_calls` 后,要按名字找到工具、执行、把结果作为 `tool` 消息塞回消息列表;
22
- - 一轮可能调多次工具,也可能调完还要继续调,循环什么时候停要判断对;
23
- - 工具在服务端执行还是浏览器执行,两套路径要分开;
24
- - 浏览器执行的工具,结果还得推回服务端,唤醒挂起的那次调用。
25
-
26
- `@auipage/agent` 把循环和桥接都收进一个 `generate()`,你只需要描述工具。
27
-
28
- ## 30 秒例子
29
-
30
- ```javascript
31
- import { Agent } from "@auipage/agent";
32
-
33
- const getWeather = {
34
- description: {
35
- type: "function",
36
- function: {
37
- name: "getWeather",
38
- description: "查询指定城市的天气",
39
- parameters: {
40
- type: "object",
41
- properties: { city: { type: "string", description: "城市名称,例如:南京" } },
42
- required: ["city"]
43
- }
44
- }
45
- },
46
- execute({ city }) {
47
- return `${city} 今天晴,25°C`; // 也可以 return fetch(...)
48
- }
49
- };
50
-
51
- const agent = new Agent({
52
- model: { model: "qwen3.5", apiKey: "ollama", baseURL: "http://localhost:11434/v1" },
53
- systemPrompt: "你可以使用 getWeather 查询天气。",
54
- tools: [getWeather]
55
- });
56
-
57
- const answer = await agent.generate([
58
- { role: "user", content: "南京今天天气怎么样?" }
59
- ]);
60
-
61
- console.log(answer); // 模型拿到工具结果后给出的最终回复
62
- ```
63
-
64
- `generate(messages, logback?, thinkback?)`:
65
-
66
- - `messages` 是 OpenAI 格式消息数组;构造时配了非空 `systemPrompt` 才会插到队首(**会原地修改数组**);
67
- - `logback(delta)` 收正文增量,`thinkback(reasoning)` 收推理增量;
68
- - 返回 `Promise<string | undefined>`;整轮只有工具调用、没有正文时为 `undefined`。
69
-
70
- 安装:
71
-
72
- ```bash
73
- npm install --save @auipage/agent
74
- ```
75
-
76
- ## 前后端工具桥接
77
-
78
- 工具需要浏览器执行时(比如展示文件、弹窗确认),用 `CreateTool` 包装一个有 `send()` 的消息流:
79
-
80
- ```javascript
81
- import { Agent, CreateTool } from "@auipage/agent";
82
- import { MessageStream } from "@auipage/core";
83
-
84
- const ms = new MessageStream(
85
- data => res.write("data: " + JSON.stringify(data) + "\n\n"),
86
- () => res.end()
87
- );
88
- const ct = new CreateTool(ms);
89
-
90
- const agent = new Agent({
91
- model: { /* 同上 */ },
92
- tools: [
93
- ct.create(readPlain), // 带 execute:服务端执行
94
- ct.create(showPlain) // 不带 execute:下发浏览器执行
95
- ]
96
- });
97
- ```
98
-
99
- - **后端工具**:推 `pending`,同一事件上补 `success` / `error` 和 `result`;
100
- - **前端工具**:只推 `pending`,本次调用挂起;页面执行完把 `{ id, result }` POST 回来,服务端 `globalThis[id](result)` 唤醒,对话继续。
101
-
102
- 页面侧用 `@auipage/core` 的 `defineTool` 注册同名工具即可,详见 [defineTool 参考](https://handless-ui.github.io/auipage/packages/core-utils.html)。
103
-
104
- ## 这个包不是必须的
105
-
106
- | 你的情况 | 可以换成 | 会失去什么 |
107
- | --- | --- | --- |
108
- | 工具都在服务端 | 官方 Agents SDK、LangChain、Vercel AI SDK | 生态更大,但抽象更重、依赖更多 |
109
- | 只有一两个工具 | 自己写 `while` 循环(约 20 行) | 要自己处理 `tool_calls` 回灌和终止条件 |
110
- | 不需要工具 | 直接用 `@auipage/model` 或官方 SDK | 少一层封装,代码更短 |
111
- | 工具要在浏览器执行 | 自己做 SSE 推事件 + 结果回传 | 等价于重写 `CreateTool`,容易漏掉挂起与唤醒 |
112
-
113
- 它最独特的价值是 **`CreateTool` 的前后端桥接**:同一份工具描述,服务端和浏览器各执行各的部分。如果你的工具全在服务端,别的 Agent 框架同样好用。
114
-
115
- ## 配置
116
-
117
- | 字段 | 类型 | 必填 | 说明 |
118
- | --- | --- | --- | --- |
119
- | `model` | `{ model, apiKey, baseURL }` | 是 | 透传给 `@auipage/model` |
120
- | `systemPrompt` | `string` | 否 | 默认空字符串 |
121
- | `stream` | `boolean` | 否 | 默认 `false` |
122
- | `tools` | `AgentTool[]` | 否 | 默认 `[]`;直接给 Agent 的工具必须带 `execute`,省略只在 `CreateTool` 场景合法 |
123
-
124
- ## 它在哪一环
125
-
126
- ```
127
- fetch ← model ← agent
128
- ```
129
-
130
- `@auipage/core` 的 `ChatTransportAdapter` 通常在里面调它。完整事件协议见 [agent 参考](https://handless-ui.github.io/auipage/packages/agent.html)。
131
-
132
- ## 版权
133
-
134
- MIT License
135
-
136
- Copyright (c) [zxl20070701](https://zxl20070701.github.io/notebook/home.html) 走一步,再走一步
1
+ # [@auipage/agent](https://github.com/handless-ui/auipage)
2
+
3
+ 智能体对话循环:模型要调工具 → 执行 → 结果回灌 → 继续生成,直到拿到最终回复。可选地把工具调用桥接到浏览器,让页面来执行。
4
+
5
+ <p>
6
+ <a href="https://zxl20070701.github.io/toolbox/#/npm-download?packages=@auipage/agent&interval=7">
7
+ <img src="https://img.shields.io/npm/dm/@auipage/agent.svg" alt="downloads">
8
+ </a>
9
+ <a href="https://www.npmjs.com/package/@auipage/agent">
10
+ <img src="https://img.shields.io/npm/v/@auipage/agent.svg" alt="npm">
11
+ </a>
12
+ <a href="https://github.com/handless-ui/auipage" target='_blank'>
13
+ <img alt="GitHub repo stars" src="https://img.shields.io/github/stars/handless-ui/auipage?style=social">
14
+ </a>
15
+ </p>
16
+
17
+ ## 它解决什么
18
+
19
+ 单轮对话只是“发一条消息、收一段文本”。一旦模型会用工具,循环就变复杂了:
20
+
21
+ - 模型返回 `tool_calls` 后,要按名字找到工具、执行、把结果作为 `tool` 消息塞回消息列表;
22
+ - 一轮可能调多次工具,也可能调完还要继续调,循环什么时候停要判断对;
23
+ - 工具在服务端执行还是浏览器执行,两套路径要分开;
24
+ - 浏览器执行的工具,结果还得推回服务端,唤醒挂起的那次调用。
25
+
26
+ `@auipage/agent` 把循环和桥接都收进一个 `generate()`,你只需要描述工具。
27
+
28
+ ## 30 秒例子
29
+
30
+ ```javascript
31
+ import { Agent } from "@auipage/agent";
32
+
33
+ const getWeather = {
34
+ description: {
35
+ type: "function",
36
+ function: {
37
+ name: "getWeather",
38
+ description: "查询指定城市的天气",
39
+ parameters: {
40
+ type: "object",
41
+ properties: { city: { type: "string", description: "城市名称,例如:南京" } },
42
+ required: ["city"]
43
+ }
44
+ }
45
+ },
46
+ execute({ city }) {
47
+ return `${city} 今天晴,25°C`; // 也可以 return fetch(...)
48
+ }
49
+ };
50
+
51
+ const agent = new Agent({
52
+ model: { model: "qwen3.5", apiKey: "ollama", baseURL: "http://localhost:11434/v1" },
53
+ systemPrompt: "你可以使用 getWeather 查询天气。",
54
+ tools: [getWeather]
55
+ });
56
+
57
+ const answer = await agent.generate([
58
+ { role: "user", content: "南京今天天气怎么样?" }
59
+ ]);
60
+
61
+ console.log(answer); // 模型拿到工具结果后给出的最终回复
62
+ ```
63
+
64
+ `generate(messages, logback?, thinkback?)`:
65
+
66
+ - `messages` 是 OpenAI 格式消息数组;构造时配了非空 `systemPrompt` 才会插到队首(**会原地修改数组**);
67
+ - `logback(delta)` 收正文增量,`thinkback(reasoning)` 收推理增量;
68
+ - 返回 `Promise<string | undefined>`;整轮只有工具调用、没有正文时为 `undefined`。
69
+
70
+ 安装:
71
+
72
+ ```bash
73
+ npm install --save @auipage/agent
74
+ ```
75
+
76
+ ## 前后端工具桥接
77
+
78
+ 工具需要浏览器执行时(比如展示文件、弹窗确认),用 `CreateTool` 包装一个有 `send()` 的消息流:
79
+
80
+ ```javascript
81
+ import { Agent, CreateTool } from "@auipage/agent";
82
+ import { MessageStream } from "@auipage/core";
83
+
84
+ const ms = new MessageStream(
85
+ data => res.write("data: " + JSON.stringify(data) + "\n\n"),
86
+ () => res.end()
87
+ );
88
+ const ct = new CreateTool(ms);
89
+
90
+ const agent = new Agent({
91
+ model: { /* 同上 */ },
92
+ tools: [
93
+ ct.create(readPlain), // 带 execute:服务端执行
94
+ ct.create(showPlain) // 不带 execute:下发浏览器执行
95
+ ]
96
+ });
97
+ ```
98
+
99
+ - **后端工具**:推 `pending`,同一事件上补 `success` / `error` 和 `result`;
100
+ - **前端工具**:只推 `pending`,本次调用挂起;页面执行完把 `{ id, result }` POST 回来,服务端 `globalThis[id](result)` 唤醒,对话继续。
101
+
102
+ 页面侧用 `@auipage/core` 的 `defineTool` 注册同名工具即可,详见 [defineTool 参考](https://handless-ui.github.io/auipage/packages/core-utils.html)。
103
+
104
+ ## 这个包不是必须的
105
+
106
+ | 你的情况 | 可以换成 | 会失去什么 |
107
+ | --- | --- | --- |
108
+ | 工具都在服务端 | 官方 Agents SDK、LangChain、Vercel AI SDK | 生态更大,但抽象更重、依赖更多 |
109
+ | 只有一两个工具 | 自己写 `while` 循环(约 20 行) | 要自己处理 `tool_calls` 回灌和终止条件 |
110
+ | 不需要工具 | 直接用 `@auipage/model` 或官方 SDK | 少一层封装,代码更短 |
111
+ | 工具要在浏览器执行 | 自己做 SSE 推事件 + 结果回传 | 等价于重写 `CreateTool`,容易漏掉挂起与唤醒 |
112
+
113
+ 它最独特的价值是 **`CreateTool` 的前后端桥接**:同一份工具描述,服务端和浏览器各执行各的部分。如果你的工具全在服务端,别的 Agent 框架同样好用。
114
+
115
+ ## 配置
116
+
117
+ | 字段 | 类型 | 必填 | 说明 |
118
+ | --- | --- | --- | --- |
119
+ | `model` | `{ model, apiKey, baseURL }` | 是 | 透传给 `@auipage/model` |
120
+ | `systemPrompt` | `string` | 否 | 默认空字符串 |
121
+ | `stream` | `boolean` | 否 | 默认 `false` |
122
+ | `tools` | `AgentTool[]` | 否 | 默认 `[]`;直接给 Agent 的工具必须带 `execute`,省略只在 `CreateTool` 场景合法 |
123
+
124
+ ## 它在哪一环
125
+
126
+ ```
127
+ fetch ← model ← agent
128
+ ```
129
+
130
+ `@auipage/core` 的 `ChatTransportAdapter` 通常在里面调它。完整事件协议见 [agent 参考](https://handless-ui.github.io/auipage/packages/agent.html)。
131
+
132
+ ## 版权
133
+
134
+ MIT License
135
+
136
+ Copyright (c) [zxl20070701](https://zxl20070701.github.io/notebook/home.html) 走一步,再走一步
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- /*! @auipage/agent v0.2.0-beta.0 */
1
+ /*! @auipage/agent v0.2.0 */
2
2
  "use strict";class t{constructor(){this._events=Object.create(null)}on(t,e){if("function"!=typeof e)return this;return(this._events[t]||(this._events[t]=[])).push(e),this}off(t,e){const n=this._events[t];if(!n)return this;const r=n.indexOf(e);return r>=0&&n.splice(r,1),0===n.length&&delete this._events[t],this}emit(t,...e){const n=this._events[t];if(!n||0===n.length)return!1;for(const t of n.slice())try{t.apply(null,e)}catch(t){console.error(t)}return!0}}class e extends t{constructor(){super(),this.status=0,this.headers={},this.ok=!1,this._done=!1,this._sseMode=!1,this._sseBuffer="",this._cancel=null,this._errorPending=null}on(t,e){if(super.on(t,e),"error"===t&&this._errorPending){const t=this._errorPending;this._errorPending=null,queueMicrotask(()=>this.emit("error",t))}return this}cancel(){return this._cancel&&this._cancel(),this}header(t){const e=this.headers;if(e)return"function"==typeof e.get?e.get(t)??void 0:e[t]}_push(t,e){if(!this._done||"error"===t){if("data"===t&&this._sseMode){this._sseBuffer+=e;const t=this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);this._sseBuffer=t.pop();for(const e of t){const t=this._extractSSEData(e);null!==t&&this.emit("data",t)}return}if("end"===t){if(this._sseMode&&this._sseBuffer.trim()){const t=this._extractSSEData(this._sseBuffer);null!==t&&this.emit("data",t),this._sseBuffer=""}this._done=!0}if("error"===t){this._done=!0;const t=this._events&&this._events.error;if(!t||0===t.length)return void(this._errorPending=e)}this.emit(t,e)}}_extractSSEData(t){const e=[];for(const n of t.split("\n"))n.startsWith("data:")&&e.push(n.replace(/^data:\s*/,"").replace(/\r$/,""));return 0===e.length?null:e.join("\n")}}const n=function(t){return function(n){return new Promise((r,o)=>{if(!n||!n.url)return void o(new Error("fetch: options.url is required"));var s;s=n.body,"[object Object]"===Object.prototype.toString.call(s)&&(n=Object.assign({},n,{body:JSON.stringify(n.body)}));const i=new e,c="function"==typeof AbortController?new AbortController:null;let a=null,l=!1;i._cancel=()=>{c&&c.abort()},queueMicrotask(()=>r(i));const u=()=>{a&&(clearTimeout(a),a=null)},h={onResponse(t){if(t&&"number"==typeof t.status&&(i.status=t.status,i.ok=t.status>=200&&t.status<300),t&&t.headers){i.headers=t.headers;("function"==typeof t.headers.get&&t.headers.get("content-type")||t.headers["content-type"]||"").includes("text/event-stream")&&(i._sseMode=!0)}i.status>=400&&i.emit("http-error",{status:i.status,headers:i.headers})},onData(t){i._push("data",t)},onEnd(){u(),i._push("end")},onError(t){l||(l=!0,u(),i._push("error",t),o(t))}},f=t=>{c&&c.abort(),h.onError(t)};if(n.timeout>0&&(a=setTimeout(()=>{a=null,f(new Error("fetch: 请求超时("+n.timeout+"ms)"))},n.timeout)),n.signal){if(n.signal.aborted)return void f(new Error("fetch: 请求已取消"));n.signal.addEventListener("abort",()=>{f(new Error("fetch: 请求已取消"))})}const d=c?Object.assign({},n,{signal:c.signal}):n;let m;try{m=t(d,h)}catch(t){return void h.onError(t)}m&&"function"==typeof m.then&&m.then(null,h.onError)})}}("undefined"!=typeof window&&void 0!==window.document?function(t,{onData:e,onEnd:n,onError:r,onResponse:o}){const{url:s,method:i="GET",headers:c={},body:a,signal:l}=t;"function"==typeof fetch?fetch(s,{method:i,headers:c,body:a,signal:l}).then(async t=>{if("function"==typeof o&&o({status:t.status||0,headers:t.headers||{}}),!t.body)return void n();const s=t.body.getReader(),i=new TextDecoder("utf-8");(async()=>{try{for(;;){const{value:t,done:r}=await s.read();if(r)return void n();e(i.decode(t,{stream:!0}))}}catch(t){r(t)}})()}).catch(t=>r(t)):r(new Error("Global fetch is not available in this environment"))}:async function(t,{onData:e,onEnd:n,onError:r,onResponse:o}){const[{default:s},{default:i},{URL:c}]=await Promise.all([import("http"),import("https"),import("url")]),{url:a,method:l="GET",headers:u={},body:h,signal:f}=t;let d;try{d=new c(a)}catch(t){return void r(t)}const m="https:"===d.protocol,p=m?i:s,g={method:l,hostname:d.hostname,port:d.port||(m?443:80),path:d.pathname+d.search,headers:u},y=p.request(g,t=>{"function"==typeof o&&o({status:t.statusCode||0,headers:t.headers||{}}),t.setEncoding("utf8"),t.on("data",t=>e(t)),t.on("end",()=>n()),t.on("error",t=>r(t))});if(y.on("error",t=>r(t)),f){if(f.aborted)return void r(new Error("请求已取消"));f.addEventListener("abort",()=>{y.destroy(new Error("请求已取消"))})}null!=h&&y.write(h),y.end()});function r(t){return t.replace(/^data:\s*/,"")}function o(t){try{return{value:JSON.parse(t)}}catch(t){return null}}function s(t,e){const n=o(r(t.trim()));if(!n)throw new SyntaxError("模型返回无法解析:"+String(e).slice(0,120));return n.value}function i(t){if(Array.isArray(t)){for(const e of t)if(e&&e.error)throw e.error;return t}if(t&&t.error)throw t.error;return t}function c(t){let e=String(null==t?"":t).trim();if(e=e.replace(/data:\s*\[DONE\]$/,"").trim(),""===e||"[DONE]"===e)return[];let n=o(r(e))||o(e);if(n)return i(n.value);const c=e.split(/\r?\n\r?\ndata: /);if(c.length>1)return i(c.map(t=>s(t,e)));const a=e.split(/\r?\n/).filter(t=>t.trim()&&!t.trim().startsWith(":"));if(a.length>1)return i(a.map(t=>s(t,e)));throw new SyntaxError("模型返回无法解析:"+e.slice(0,120))}function a(t,e){if(!/<\/think>/.test(t))return t;const n=t.split("</think>");return{reasoning:n[0].replace("<think>",""),content:n[1]+(e||"")}}const l="<think>",u="</think>";function h(t,e){for(let n=Math.min(e.length-1,t.length);n>0;n--)if(t.endsWith(e.slice(0,n)))return n;return 0}function f(t,e){const n=(e.thinkBuf||"")+t;if(e.thinkBuf="",e.inThink){const t=n.indexOf(u);if(-1===t){const t=h(n,u);return e.thinkBuf=n.slice(n.length-t),{thinking:n.slice(0,n.length-t),content:""}}e.inThink=!1;const r=f(n.slice(t+8),e);return{thinking:n.slice(0,t)+r.thinking,content:r.content}}const r=n.indexOf(l);if(-1===r){const t=h(n,l);return e.thinkBuf=n.slice(n.length-t),{thinking:"",content:n.slice(0,n.length-t)}}const o=n.indexOf(u,r);if(-1!==o){const t=f(n.slice(o+8),e);return{thinking:n.slice(r+7,o)+t.thinking,content:n.slice(0,r)+t.content}}e.inThink=!0;const s=n.slice(r+7),i=h(s,u);return e.thinkBuf=s.slice(s.length-i),{thinking:s.slice(0,s.length-i),content:n.slice(0,r)}}function d(t){const e=t.function||{};return{...t,function:{...e,arguments:"string"==typeof e.arguments?e.arguments:""}}}function m(t,e){t._toolSlots||(t._toolSlots=new Map);const n=t.tool_calls,r="number"==typeof e.index?e.index:null;if("string"==typeof e.id&&""!==e.id){const o=n.find(t=>t.id===e.id);if(o)return void p(o,e);const s=d(e);return n.push(s),void(null!==r&&t._toolSlots.set(r,s))}let o=null!==r?t._toolSlots.get(r):null;if(!o&&n.length&&(o=n[n.length-1]),!o)return o=d(e),n.push(o),void(null!==r&&t._toolSlots.set(r,o));p(o,e)}function p(t,e){const n=e.function||{};n.name&&!t.function.name&&(t.function.name=n.name),"string"==typeof n.arguments&&(t.function.arguments+=n.arguments)}function g(t,{logback:e,thinkback:n},r){if(Array.isArray(t))for(let o=0;o<t.length;o++){const s=t[o].delta;let i=s.reasoning||s.reasoning_content;if(i){const t=a(i,s.content);"object"==typeof t&&(i=t.reasoning,s.content=t.content),n&&n(i)}if(s.content){const t=f(s.content,r);t.thinking&&n&&n(t.thinking),t.content&&(e&&e(t.content),r.content+=t.content)}if(Array.isArray(s.tool_calls))for(const t of s.tool_calls)m(r,t)}}function y(t,e){const n=t&&t.status;let r="";if(e){try{const t=JSON.parse(e),n=t&&t.error;r=n&&(n.message||n)||""}catch(t){r=String(e).slice(0,200)}r&&"string"!=typeof r&&(r=JSON.stringify(r))}return new Error("模型服务返回 HTTP "+n+(r?":"+r:""))}function _(t){this.model=t.model,this.apiKey=t.apiKey,this.baseURL=t.baseURL,this.temperature=t.temperature,this.topP=t.topP,this.maxTokens=t.maxTokens,this.timeout=t.timeout}function k(t,e){const n=(e||[]).map(e=>{const n=e&&e.function||{},r=(t.tools||[]).find(t=>t.description.function.name===n.name);if(!r)return Promise.resolve("工具"+n.name+"不存在");if("function"!=typeof r.execute)return Promise.resolve("工具"+n.name+"缺少 execute");let o;try{o="string"==typeof n.arguments&&n.arguments.trim()?JSON.parse(n.arguments):{}}catch(t){return Promise.resolve("参数解析失败:"+t)}try{return Promise.resolve(r.execute(o)).catch(t=>"运行出错:"+t)}catch(t){return Promise.resolve("运行出错:"+t)}});return Promise.all(n)}function v(t,e){return{role:"tool",tool_call_id:t.id,tool_name:t.function.name,content:"string"==typeof e?e:JSON.stringify(e)+""}}function w(t,e){return e.content&&t.push({role:"assistant",content:e.content}),!!(e.tool_calls&&e.tool_calls.length>0)&&(t.push({role:"assistant",tool_calls:e.tool_calls}),!0)}function b(t){this.ms=t}function E(t){t=t||{},this.model=new _(t.model),this.tools=t.tools||[],this.systemPrompt=t.systemPrompt||"",this.stream=t.stream||!1,this.maxSteps=t.maxSteps>0?t.maxSteps:0,this.signal=t.signal||null}_.prototype.completions=function(t,e,r){return new Promise((o,s)=>{const i={content:"",tool_calls:[]},a={logback:e,thinkback:r};let l="",u=null,h=null,f=!1;const d=(t,e)=>{f||(f=!0,t(e))},m=t=>d(s,function(t,e){if(t instanceof Error)return t;if(t&&"string"==typeof t.message)return new Error(t.message);try{return new Error(String(t))}catch(t){return new Error(e||"模型请求失败")}}(t,"模型请求失败")),p={model:this.model,messages:t.messages,tools:t.tools?t.tools.map(t=>t.description):[],stream:t.stream},_=null!=t.temperature?t.temperature:this.temperature,k=null!=t.topP?t.topP:this.topP,v=null!=t.maxTokens?t.maxTokens:this.maxTokens;null!=_&&(p.temperature=_),null!=k&&(p.top_p=k),null!=v&&(p.max_tokens=v),n({url:`${this.baseURL.replace(/\/+$/,"")}/chat/completions`,method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(p),timeout:null!=t.timeout?t.timeout:this.timeout,signal:t.signal}).then(e=>{e.on("http-error",e=>{u=e,t.stream&&m(y(e))}),e.on("data",e=>{if(f)return;if(!t.stream)return void(l+=e);let n;try{n=c(e.toString())}catch(t){return h=t,void m(t)}try{const t=Array.isArray(n)?n:[n];for(const e of t)g(e.choices,a,i)}catch(t){m(t)}}),e.on("end",()=>{if(t.stream){if(h)return void m(h);if(u)return void m(y(u))}else{if(u)return void m(y(u,l));try{const t=c(l),e=t&&t.choices;if(!e||!e[0]||!e[0].message)throw new Error("模型响应缺少 choices[0].message");g([{delta:e[0].message}],a,i)}catch(t){return void m(t)}}!function(t,{logback:e,thinkback:n}){const r=function(t){const e=t.thinkBuf||"";return t.thinkBuf="",t.inThink?{thinking:e,content:""}:{thinking:"",content:e}}(t);r.thinking&&n&&n(r.thinking),r.content&&(e&&e(r.content),t.content+=r.content)}(i,a),d(o,{content:i.content,tool_calls:i.tool_calls})}),e.on("error",t=>m(t))}).catch(t=>m(t))})},b.prototype.create=function({description:t,execute:e},n){let r=this;const o=n&&n.timeout>0?n.timeout:0;return{description:t,execute:async function(n){let s={type:"tool-call",status:"pending",id:Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),name:t.function.name,caller:e?"backend":"frontend",args:n};if(e){let t,o;r.ms.send(s);try{t=await e(n),o="success"}catch(e){t=e,o="error"}if(r.ms.send(function(t,e){for(const n in t)e[n]=t[n];return e}({status:o,result:t},s)),"error"===o)throw t;return t}let i=null,c=null;const a=()=>{c&&(clearTimeout(c),c=null),delete globalThis[s.id]},l=new Promise((t,e)=>{i={resolve:t,reject:e}});globalThis[s.id]=function(t,e){if(!i)return;const n=i;i=null,a(),"error"===e?n.reject(t):n.resolve(t)},o>0&&(c=setTimeout(()=>{if(!i)return;const e=i;i=null,a(),e.reject(new Error("前端工具调用超时:"+t.function.name))},o));try{r.ms.send(s)}catch(t){throw i=null,a(),t}return l}}},E.prototype.generate=function(t,e,n){if(Array.isArray(t)||(t=[]),this.systemPrompt){let e=t[0];e&&"system"===e.role&&e.content===this.systemPrompt||t.unshift({role:"system",content:this.systemPrompt})}return async function(t,e,n,r){const o=t.maxSteps>0?t.maxSteps:1/0;for(let s=1;s<=o;s++){const o=await t.model.completions({messages:e,tools:t.tools,stream:t.stream,signal:t.signal||void 0},n,r);if(!w(e,o))return o.content;const s=await k(t,o.tool_calls);o.tool_calls.forEach((t,n)=>{e.push(v(t,s[n]))})}throw new Error("工具调用步骤超过 maxSteps 上限:"+t.maxSteps)}(this,t,e,n)},exports.Agent=E,exports.CreateTool=b;