@nickyzj2023/ai 1.7.0 → 1.7.1
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/README.md +9 -1
- package/dist/agent.d.mts +9 -0
- package/dist/agent.mjs +1 -0
- package/dist/cli.mjs +2 -597
- package/dist/index.d.mts +6 -168
- package/dist/index.mjs +1 -3
- package/dist/interfaces/setup.mjs +2 -0
- package/dist/interfaces/tui.mjs +6 -0
- package/dist/llm.d.mts +18 -0
- package/dist/llm.mjs +1 -0
- package/dist/tools/get-time.d.mts +5 -0
- package/dist/tools/get-time.mjs +1 -0
- package/dist/tools/get-weather.d.mts +5 -0
- package/dist/tools/get-weather.mjs +1 -0
- package/dist/tools/index.d.mts +3 -0
- package/dist/tools/index.mjs +1 -0
- package/dist/tools/mcp.d.mts +1 -1
- package/dist/tools/mcp.mjs +1 -2
- package/dist/{types-Bwc1Oqk3.d.mts → types.d.mts} +1 -1
- package/dist/utils/clipboard.mjs +1 -0
- package/dist/utils/compact/helper.mjs +1 -0
- package/dist/utils/compact/index.d.mts +15 -0
- package/dist/utils/compact/index.mjs +1 -0
- package/dist/utils/compact/strategy.d.mts +25 -0
- package/dist/utils/compact/strategy.mjs +1 -0
- package/dist/utils/compact/types.d.mts +78 -0
- package/dist/utils/config.mjs +1 -0
- package/dist/utils/helper.d.mts +30 -0
- package/dist/utils/helper.mjs +1 -0
- package/dist/utils/internalHelper.mjs +1 -0
- package/package.json +24 -3
- package/dist/helper-DJw58Gmz.mjs +0 -77
- package/dist/mcp-C22GzADk.mjs +0 -87
- package/dist/src-C1ARVH43.mjs +0 -535
package/README.md
CHANGED
|
@@ -24,10 +24,18 @@ pnpm add @nickyzj2023/ai
|
|
|
24
24
|
### 在项目里使用
|
|
25
25
|
|
|
26
26
|
```typescript
|
|
27
|
-
import { defineModel, runAgent
|
|
27
|
+
import { defineModel, runAgent } from "@nickyzj2023/ai";
|
|
28
|
+
// 内置工具已从主入口拆出,按需引入
|
|
29
|
+
import { getTime, getWeather } from "@nickyzj2023/ai/tools";
|
|
28
30
|
// MCP体积较大(200kb),有需要时单独引入
|
|
29
31
|
import { loadMCPTools } from "@nickyzj2023/ai/mcp";
|
|
30
32
|
|
|
33
|
+
// 也可以按需引入,只加载真正用到的模块(不会带上CLI/TUI或compact等无关代码)
|
|
34
|
+
// import { runAgent } from "@nickyzj2023/ai/agent";
|
|
35
|
+
// import { stream, nonStream } from "@nickyzj2023/ai/llm";
|
|
36
|
+
// import { compact } from "@nickyzj2023/ai/compact";
|
|
37
|
+
// import { getWeather } from "@nickyzj2023/ai/tools/get-weather";
|
|
38
|
+
|
|
31
39
|
const model = defineModel({
|
|
32
40
|
baseUrl: "https://api.deepseek.com/v1",
|
|
33
41
|
apiKey: process.env.APIKEY,
|
package/dist/agent.d.mts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { AgentEvent, Message, Model, RunAgentOptions } from "./types.mjs";
|
|
2
|
+
//#region src/agent.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Agent循环
|
|
5
|
+
* @param options.stream 是否流式输出,默认false(每轮推送一个result事件)
|
|
6
|
+
*/
|
|
7
|
+
declare function runAgent(model: Model, messages: Message[], options?: RunAgentOptions): AsyncGenerator<AgentEvent>;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { runAgent };
|
package/dist/agent.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{nonStream as e,stream as t}from"./llm.mjs";import{estimateFallbackUsage as n,withSpeed as r}from"./utils/internalHelper.mjs";import{to as i}from"@nickyzj2023/utils";async function*a(a,o,s){let{tools:c=[],stream:l=!1}=s??{},u=new Map(c.map(e=>[e.function.name,e]));for(;;){let s=``,d=``,f=[],p=null,m,h=Date.now();if(l)for await(let e of t(a,o,c))switch(e.type){case`reasoning_delta`:yield e,s+=e.delta;break;case`content_delta`:yield e,d+=e.delta;break;case`tool_call`:yield e,f.push({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}});break;case`error`:yield e;return;case`done`:p=e.finishReason,m=e.usage}else{let[t,n]=await i(e(a,o,c));if(t){yield{type:`error`,message:t.message};return}s=n.reasoning??``,d=n.content,f.push(...n.toolCalls),p=n.finishReason,m=n.usage}m=r(m??n(o,d,s),h),yield l?{type:`done`,finishReason:p,usage:m}:{type:`result`,content:d,reasoning:s,finishReason:p,usage:m};let g={role:`assistant`,content:d};if(f.length>0&&(g.tool_calls=f),o.push(g),f.length===0)return;for(let e of f){let{name:t,arguments:n}=e.function,r=u.get(t),a=``;if(!r)a=`不存在工具“${t}”`;else{let[e,o]=await i(r.execute(JSON.parse(n)));a=e?`工具“${t}”执行出错:${e.message}`:JSON.stringify(o)}o.push({role:`tool`,tool_call_id:e.id,content:a}),yield{type:`tool_result`,id:e.id,name:t,result:a}}}}export{a as runAgent};
|
package/dist/cli.mjs
CHANGED
|
@@ -1,603 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { a as listModels, t as defineModel } from "./helper-DJw58Gmz.mjs";
|
|
3
|
-
import { n as listMcpToolNames, r as loadMCPTools } from "./mcp-C22GzADk.mjs";
|
|
4
|
-
import { compactStr, extractErrorMessage, isObject, to } from "@nickyzj2023/utils";
|
|
5
|
-
import readline from "node:readline";
|
|
6
|
-
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
-
import { homedir } from "node:os";
|
|
8
|
-
import { dirname, join } from "node:path";
|
|
9
|
-
import { MarkdownRenderer } from "@wterm/markdown";
|
|
10
|
-
import { execFile } from "node:child_process";
|
|
11
|
-
//#region src/utils/config.ts
|
|
12
|
-
/**
|
|
13
|
-
* 获取全局配置文件路径(Windows/macOS/Linux通用)
|
|
14
|
-
* @returns (Windows下)C:/Users/Administrator/.@nickyzj2023/ai/config.json
|
|
15
|
-
*/
|
|
16
|
-
const getConfigPath = () => {
|
|
17
|
-
return join(homedir(), ".@nickyzj2023", "ai", "config.json");
|
|
18
|
-
};
|
|
19
|
-
/**
|
|
20
|
-
* 读取配置文件
|
|
21
|
-
* @returns 正常返回Config,配置不存在或损坏时返回null
|
|
22
|
-
*/
|
|
23
|
-
const loadConfig = () => {
|
|
24
|
-
try {
|
|
25
|
-
const config = JSON.parse(readFileSync(getConfigPath(), "utf8"));
|
|
26
|
-
if (typeof config.baseUrl !== "string" || typeof config.apiKey !== "string" || typeof config.model !== "string") return null;
|
|
27
|
-
return config;
|
|
28
|
-
} catch {
|
|
29
|
-
return null;
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
/**
|
|
33
|
-
* 将配置写回全局文件(自动创建目录)
|
|
34
|
-
* @remarks 写入失败会抛异常
|
|
35
|
-
*/
|
|
36
|
-
const saveConfig = (config) => {
|
|
37
|
-
const configPath = getConfigPath();
|
|
38
|
-
mkdirSync(dirname(configPath), { recursive: true });
|
|
39
|
-
writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
40
|
-
};
|
|
41
|
-
//#endregion
|
|
42
|
-
//#region src/interfaces/setup.ts
|
|
43
|
-
/**
|
|
44
|
-
* 临时创建readline接口,问答结束就关闭
|
|
45
|
-
* @param question 提问
|
|
46
|
-
* @returns 用户输入的回答
|
|
47
|
-
*/
|
|
48
|
-
const ask = (question) => {
|
|
49
|
-
return new Promise((resolve) => {
|
|
50
|
-
const rl = readline.createInterface({
|
|
51
|
-
input: process.stdin,
|
|
52
|
-
output: process.stdout
|
|
53
|
-
});
|
|
54
|
-
rl.question(question, (answer) => {
|
|
55
|
-
rl.close();
|
|
56
|
-
resolve(answer);
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
};
|
|
60
|
-
/**
|
|
61
|
-
* 询问一个可留空的字段:回车或输入空白时沿用默认值
|
|
62
|
-
* @param question 提问文案
|
|
63
|
-
* @param fallback 默认值
|
|
64
|
-
* @returns 用户输入,空白时返回默认值
|
|
65
|
-
*/
|
|
66
|
-
const askWithDefault = async (question, fallback) => {
|
|
67
|
-
return (await ask(question)).trim() || fallback;
|
|
68
|
-
};
|
|
69
|
-
/**
|
|
70
|
-
* 交互式录入一个MCP服务器配置
|
|
71
|
-
* @param current 编辑时传入现有服务器,回车表示沿用原值;只传name表示配置缺失、重新录入
|
|
72
|
-
* @returns 录入完成的配置;名称/URL为空或类型非法时返回null
|
|
73
|
-
*/
|
|
74
|
-
const askMcpServer = async (current) => {
|
|
75
|
-
const name = await askWithDefault(`名称 [当前为${current?.name ?? "(新)"}]: `, current?.name);
|
|
76
|
-
if (!name) {
|
|
77
|
-
console.log("名称不能为空,已取消");
|
|
78
|
-
return null;
|
|
79
|
-
}
|
|
80
|
-
const defaultType = current?.type ?? "streamable_http";
|
|
81
|
-
const typeInput = await askWithDefault(`类型 streamable_http/sse [当前为${defaultType}]: `, defaultType);
|
|
82
|
-
if (typeInput !== "streamable_http" && typeInput !== "sse") {
|
|
83
|
-
console.log("类型无效,已取消");
|
|
84
|
-
return null;
|
|
85
|
-
}
|
|
86
|
-
const type = typeInput;
|
|
87
|
-
const url = await askWithDefault(`URL [当前为${current?.url ?? "无"}]: `, current?.url);
|
|
88
|
-
if (!url) {
|
|
89
|
-
console.log("URL不能为空,已取消");
|
|
90
|
-
return null;
|
|
91
|
-
}
|
|
92
|
-
let headers = current?.headers;
|
|
93
|
-
const headersInput = (await ask(`headers(JSON对象) [当前为${current?.headers ? JSON.stringify(current.headers) : "无"}]: `)).trim();
|
|
94
|
-
if (headersInput) try {
|
|
95
|
-
const parsed = JSON.parse(headersInput);
|
|
96
|
-
if (isObject(parsed)) headers = parsed;
|
|
97
|
-
else console.log("headers需为JSON对象,已回退到原先的值");
|
|
98
|
-
} catch {
|
|
99
|
-
console.log("headers解析失败,已回退到原先的值");
|
|
100
|
-
}
|
|
101
|
-
let ignoredToolNames = current?.ignoredToolNames;
|
|
102
|
-
const [error, toolNames = []] = await to(listMcpToolNames(url, headers ? { headers } : void 0));
|
|
103
|
-
if (error) console.log(`获取工具列表失败:${extractErrorMessage(error)}`);
|
|
104
|
-
else {
|
|
105
|
-
console.log("该服务器提供的工具:");
|
|
106
|
-
toolNames.forEach((toolName, i) => {
|
|
107
|
-
console.log(`${i + 1}. ${toolName}`);
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
const ignoredInput = (await ask(`忽略的工具(名称或序号,用逗号分隔,也支持1-5这样的连续序号) [当前为${current?.ignoredToolNames?.join(",") ?? "无"}]: `)).trim();
|
|
111
|
-
if (ignoredInput) ignoredToolNames = parseIgnoredToolNames(ignoredInput, toolNames);
|
|
112
|
-
return {
|
|
113
|
-
name,
|
|
114
|
-
type,
|
|
115
|
-
url,
|
|
116
|
-
...headers ? { headers } : {},
|
|
117
|
-
...ignoredToolNames?.length ? { ignoredToolNames } : {}
|
|
118
|
-
};
|
|
119
|
-
};
|
|
120
|
-
/**
|
|
121
|
-
* 把菜单输入的数字解析成对应的名称
|
|
122
|
-
* @param input 用户输入的数字串
|
|
123
|
-
* @param names 当前菜单的名称列表
|
|
124
|
-
* @returns 对应名称;非整数或越界返回undefined
|
|
125
|
-
*/
|
|
126
|
-
const pickByIndex = (input, names) => {
|
|
127
|
-
const index = Number(input) - 1;
|
|
128
|
-
return Number.isInteger(index) ? names[index] : void 0;
|
|
129
|
-
};
|
|
130
|
-
/**
|
|
131
|
-
* 解析“忽略的工具”输入:名称、单个序号、序号段(如1-5,9-12),均可逗号混用
|
|
132
|
-
* @param input 用户输入
|
|
133
|
-
* @param toolNames 该服务器的工具名列表,序号按列表顺序(从1开始)换算
|
|
134
|
-
* @returns 去重后的工具名;越界序号以及无意义的重复会被丢弃
|
|
135
|
-
*/
|
|
136
|
-
const parseIgnoredToolNames = (input, toolNames) => {
|
|
137
|
-
const picked = input.split(",").map((item) => item.trim()).filter(Boolean).flatMap((item) => {
|
|
138
|
-
const range = /^(\d+)\s*-\s*(\d+)$/.exec(item);
|
|
139
|
-
if (!range) return /^\d+$/.test(item) ? [toolNames[Number(item) - 1]] : [item];
|
|
140
|
-
const start = Number(range[1]);
|
|
141
|
-
const end = Number(range[2]);
|
|
142
|
-
if (start > end) return [];
|
|
143
|
-
return Array.from({ length: end - start + 1 }, (_, i) => toolNames[start + i - 1]);
|
|
144
|
-
}).filter((name) => Boolean(name));
|
|
145
|
-
return [...new Set(picked)];
|
|
146
|
-
};
|
|
147
|
-
/**
|
|
148
|
-
* MCP配置菜单:列出现有服务器,数字键编辑、a键添加、d键删除、回车或q结束
|
|
149
|
-
*/
|
|
150
|
-
const configMcp = async (mcpServers) => {
|
|
151
|
-
while (true) {
|
|
152
|
-
const names = Object.keys(mcpServers);
|
|
153
|
-
console.log("\n当前MCP服务器:");
|
|
154
|
-
if (names.length === 0) console.log("(空)");
|
|
155
|
-
else names.forEach((name, i) => {
|
|
156
|
-
const server = mcpServers[name];
|
|
157
|
-
console.log(` ${i + 1}. ${name} ${server ? `(${server.type} ${server.url})` : "(配置缺失)"}`);
|
|
158
|
-
});
|
|
159
|
-
const choice = (await ask("输入数字编辑对应服务器,a添加新服务器,d删除服务器,回车或q结束: ")).trim().toLowerCase();
|
|
160
|
-
if (!choice || choice === "q") break;
|
|
161
|
-
switch (choice) {
|
|
162
|
-
case "a": {
|
|
163
|
-
const result = await askMcpServer();
|
|
164
|
-
if (result) mcpServers[result.name] = result;
|
|
165
|
-
break;
|
|
166
|
-
}
|
|
167
|
-
case "d": {
|
|
168
|
-
const target = (await ask("输入要删除的服务器编号: ")).trim();
|
|
169
|
-
const oldName = pickByIndex(target, names);
|
|
170
|
-
if (!oldName) {
|
|
171
|
-
console.log("无效编号,请输入列表中的数字");
|
|
172
|
-
break;
|
|
173
|
-
}
|
|
174
|
-
if ((await ask(`确认删除${oldName}?(y/n): `)).trim().toLowerCase() === "y") {
|
|
175
|
-
delete mcpServers[oldName];
|
|
176
|
-
console.log(`已删除${oldName}`);
|
|
177
|
-
} else console.log("已取消删除");
|
|
178
|
-
break;
|
|
179
|
-
}
|
|
180
|
-
default: {
|
|
181
|
-
const oldName = pickByIndex(choice, names);
|
|
182
|
-
if (oldName) {
|
|
183
|
-
const server = mcpServers[oldName];
|
|
184
|
-
if (!server) console.log("该服务器配置缺失,将重新录入");
|
|
185
|
-
const result = await askMcpServer({
|
|
186
|
-
name: oldName,
|
|
187
|
-
...server
|
|
188
|
-
});
|
|
189
|
-
if (result) {
|
|
190
|
-
if (result.name !== oldName) console.log(`已重命名 ${oldName} -> ${result.name}`);
|
|
191
|
-
delete mcpServers[oldName];
|
|
192
|
-
mcpServers[result.name] = result;
|
|
193
|
-
}
|
|
194
|
-
} else console.log("无效选择,请输入列表中的数字、a、d或回车");
|
|
195
|
-
break;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
};
|
|
200
|
-
/**
|
|
201
|
-
* 询问MODEL:能连上服务时先列出GET /models的模型,输入序号即可选中,同时也支持直接手输模型名
|
|
202
|
-
* @param baseUrl 刚录入的BASE_URL
|
|
203
|
-
* @param apiKey 刚录入的APIKEY
|
|
204
|
-
* @param fallback 直接回车时沿用的模型
|
|
205
|
-
*/
|
|
206
|
-
const askModel = async (baseUrl, apiKey, fallback) => {
|
|
207
|
-
const [error, models] = await to(baseUrl ? listModels(baseUrl, apiKey) : Promise.resolve([]));
|
|
208
|
-
const names = models ?? [];
|
|
209
|
-
if (error) console.log(`获取模型列表失败:${extractErrorMessage(error)}`);
|
|
210
|
-
else if (names.length === 0) console.log("服务端未返回任何模型,请手动输入模型名");
|
|
211
|
-
else {
|
|
212
|
-
console.log("可用模型(输入序号快速选择,也可直接输入模型名):");
|
|
213
|
-
names.forEach((name, i) => {
|
|
214
|
-
console.log(` ${i + 1}. ${name}`);
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
const input = (await ask(`MODEL [当前为${fallback}]: `)).trim();
|
|
218
|
-
return pickByIndex(input, names) || input || fallback;
|
|
219
|
-
};
|
|
220
|
-
/**
|
|
221
|
-
* setup入口:依次询问BASE_URL / MODEL / APIKEY,确认后写入全局配置
|
|
222
|
-
*/
|
|
223
|
-
async function runSetup() {
|
|
224
|
-
const config = loadConfig();
|
|
225
|
-
const baseUrl = await ask(`BASE_URL [当前为${config?.baseUrl}]: `) || config?.baseUrl;
|
|
226
|
-
const apiKey = await ask(`APIKEY [当前为${config?.apiKey}]: `) || config?.apiKey;
|
|
227
|
-
const model = await askModel(baseUrl, apiKey, config?.model);
|
|
228
|
-
const mcpServers = { ...config?.mcpServers };
|
|
229
|
-
if ((await ask("是否配置MCP服务器?(y/n): ")).trim().toLowerCase() === "y") await configMcp(mcpServers);
|
|
230
|
-
try {
|
|
231
|
-
saveConfig({
|
|
232
|
-
baseUrl,
|
|
233
|
-
apiKey,
|
|
234
|
-
model,
|
|
235
|
-
mcpServers
|
|
236
|
-
});
|
|
237
|
-
console.log(`配置已保存到${getConfigPath()},直接运行ai即可开始对话`);
|
|
238
|
-
} catch (e) {
|
|
239
|
-
console.error(`保存配置失败:${extractErrorMessage(e)}`);
|
|
240
|
-
process.exitCode = 1;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
//#endregion
|
|
244
|
-
//#region src/utils/clipboard.ts
|
|
245
|
-
/** 剪贴板图片的原始字节上限:超过则拒绝,避免把超大图片塞入请求体 */
|
|
246
|
-
const MAX_CLIPBOARD_IMAGE_BYTES = 5242880;
|
|
247
|
-
/**
|
|
248
|
-
* 执行命令并原样取回stdout(二进制安全)
|
|
249
|
-
* @param maxBuffer 允许的最大输出字节数
|
|
250
|
-
*/
|
|
251
|
-
const run = (command, args, maxBuffer) => {
|
|
252
|
-
return new Promise((resolve, reject) => {
|
|
253
|
-
execFile(command, args, {
|
|
254
|
-
encoding: "buffer",
|
|
255
|
-
timeout: 5e3,
|
|
256
|
-
maxBuffer
|
|
257
|
-
}, (error, stdout) => {
|
|
258
|
-
if (error) reject(error);
|
|
259
|
-
else resolve(stdout);
|
|
260
|
-
});
|
|
261
|
-
});
|
|
262
|
-
};
|
|
263
|
-
/** 组装成OpenAI接口能接受的data URL */
|
|
264
|
-
const toDataUrl = (buffer, mime = "image/png") => ({
|
|
265
|
-
url: `data:${mime};base64,${buffer.toString("base64")}`,
|
|
266
|
-
bytes: buffer.length
|
|
267
|
-
});
|
|
268
|
-
/** Windows:用PowerShell把剪贴板里的图片转成base64后读出 */
|
|
269
|
-
const readWindows = async () => {
|
|
270
|
-
const script = [
|
|
271
|
-
"Add-Type -AssemblyName System.Windows.Forms",
|
|
272
|
-
"Add-Type -AssemblyName System.Drawing",
|
|
273
|
-
"$img = [System.Windows.Forms.Clipboard]::GetImage()",
|
|
274
|
-
"if ($img) {",
|
|
275
|
-
"$ms = New-Object System.IO.MemoryStream",
|
|
276
|
-
"$img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)",
|
|
277
|
-
"[Convert]::ToBase64String($ms.ToArray())",
|
|
278
|
-
"}"
|
|
279
|
-
].join("; ");
|
|
280
|
-
const base64 = (await run("powershell.exe", [
|
|
281
|
-
"-NoProfile",
|
|
282
|
-
"-Command",
|
|
283
|
-
script
|
|
284
|
-
], 67108864)).toString("utf8").trim();
|
|
285
|
-
return base64 ? toDataUrl(Buffer.from(base64, "base64")) : null;
|
|
286
|
-
};
|
|
287
|
-
/** Linux:Wayland优先,其次X11,最后用python3的tkinter兜底;命令未安装或剪贴板里不是图片时跳过 */
|
|
288
|
-
const readLinux = async () => {
|
|
289
|
-
for (const candidate of [{
|
|
290
|
-
command: "wl-paste",
|
|
291
|
-
args: [
|
|
292
|
-
"--no-newline",
|
|
293
|
-
"--type",
|
|
294
|
-
"image/png"
|
|
295
|
-
]
|
|
296
|
-
}, {
|
|
297
|
-
command: "xclip",
|
|
298
|
-
args: [
|
|
299
|
-
"-selection",
|
|
300
|
-
"clipboard",
|
|
301
|
-
"-t",
|
|
302
|
-
"image/png",
|
|
303
|
-
"-o"
|
|
304
|
-
]
|
|
305
|
-
}]) try {
|
|
306
|
-
const stdout = await run(candidate.command, candidate.args, MAX_CLIPBOARD_IMAGE_BYTES * 2);
|
|
307
|
-
if (stdout.length === 0) continue;
|
|
308
|
-
return candidate.base64 ? toDataUrl(Buffer.from(stdout.toString("ascii").trim(), "base64")) : toDataUrl(stdout);
|
|
309
|
-
} catch {}
|
|
310
|
-
return null;
|
|
311
|
-
};
|
|
312
|
-
/**
|
|
313
|
-
* 读取系统剪贴板里的图片
|
|
314
|
-
* @returns 剪贴板里没有图片、或当前环境拿不到时返回null
|
|
315
|
-
*/
|
|
316
|
-
const readClipboardImage = async () => {
|
|
317
|
-
try {
|
|
318
|
-
switch (process.platform) {
|
|
319
|
-
case "win32": return await readWindows();
|
|
320
|
-
default: return await readLinux();
|
|
321
|
-
}
|
|
322
|
-
} catch {
|
|
323
|
-
return null;
|
|
324
|
-
}
|
|
325
|
-
};
|
|
326
|
-
//#endregion
|
|
327
|
-
//#region src/interfaces/tui.ts
|
|
328
|
-
var TUI = class {
|
|
329
|
-
rl = null;
|
|
330
|
-
onPrompt = null;
|
|
331
|
-
/**
|
|
332
|
-
* 已粘贴、等待随下次请求一起发出的图片
|
|
333
|
-
* TODO: 改为pendingMedias
|
|
334
|
-
*/
|
|
335
|
-
pendingImages = [];
|
|
336
|
-
/** 剪贴板读取是异步的,回车时要先等它结束,避免漏掉刚粘贴的图片 */
|
|
337
|
-
clipboardTask = Promise.resolve();
|
|
338
|
-
/** content专用的markdown渲染器 */
|
|
339
|
-
md = null;
|
|
340
|
-
/** 是否允许输入 */
|
|
341
|
-
isBusy = false;
|
|
342
|
-
/** 是否正停在提示符上等输入(决定printNotice要不要重绘提示符) */
|
|
343
|
-
isPrompting = false;
|
|
344
|
-
/** 上次打印内容所属的状态(reasoning/content/tool)
|
|
345
|
-
* 用于在新的状态开始时改变样式、打印前缀
|
|
346
|
-
*/
|
|
347
|
-
prevPrintType = void 0;
|
|
348
|
-
/**
|
|
349
|
-
* 实例化TUI时,接收一个“发出用户提示词”的回调函数
|
|
350
|
-
* UI只做UI的事,提示词发给谁让调用方决定
|
|
351
|
-
*/
|
|
352
|
-
constructor(onPrompt) {
|
|
353
|
-
this.onPrompt = onPrompt;
|
|
354
|
-
}
|
|
355
|
-
/**
|
|
356
|
-
* 启动TUI
|
|
357
|
-
* @param initialPrompt 传入时先替用户发出这一轮(ai “提示词”的快捷方式),之后照常等输入
|
|
358
|
-
*/
|
|
359
|
-
start(initialPrompt) {
|
|
360
|
-
this.rl = readline.createInterface({
|
|
361
|
-
input: process.stdin,
|
|
362
|
-
output: process.stdout
|
|
363
|
-
});
|
|
364
|
-
process.stdin.on("keypress", this.onKeypress);
|
|
365
|
-
this.rl.on("close", () => {
|
|
366
|
-
process.stdin.off("keypress", this.onKeypress);
|
|
367
|
-
this.rl?.close();
|
|
368
|
-
this.rl = null;
|
|
369
|
-
});
|
|
370
|
-
if (initialPrompt) {
|
|
371
|
-
process.stdout.write(`> ${initialPrompt}\n`);
|
|
372
|
-
this.submit({
|
|
373
|
-
text: initialPrompt,
|
|
374
|
-
images: []
|
|
375
|
-
});
|
|
376
|
-
} else this.prompting();
|
|
377
|
-
}
|
|
378
|
-
/** 监听用户的特定按键 */
|
|
379
|
-
onKeypress = (_str, key) => {
|
|
380
|
-
if (this.isBusy) return;
|
|
381
|
-
if (key?.ctrl && key?.name === "v") this.clipboardTask = this.clipboardTask.then(() => this.attachImage());
|
|
382
|
-
};
|
|
383
|
-
/** 监听用户输入 */
|
|
384
|
-
prompting() {
|
|
385
|
-
if (this.isBusy) return;
|
|
386
|
-
this.isPrompting = true;
|
|
387
|
-
this.rl?.question("> ", async (answer) => {
|
|
388
|
-
this.isPrompting = false;
|
|
389
|
-
await this.clipboardTask;
|
|
390
|
-
const text = answer.trim();
|
|
391
|
-
const images = this.pendingImages;
|
|
392
|
-
this.pendingImages = [];
|
|
393
|
-
if (!text && images.length === 0) {
|
|
394
|
-
this.prompting();
|
|
395
|
-
return;
|
|
396
|
-
}
|
|
397
|
-
await this.submit({
|
|
398
|
-
text,
|
|
399
|
-
images
|
|
400
|
-
});
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* 走完整的一轮:把输入交给调用方,结束后继续等用户输入
|
|
405
|
-
* @remarks 提示词来源可以是用户敲的,也可以是start()传进来的initialPrompt
|
|
406
|
-
*/
|
|
407
|
-
async submit(input) {
|
|
408
|
-
this.isBusy = true;
|
|
409
|
-
await this.onPrompt?.(input);
|
|
410
|
-
this.isBusy = false;
|
|
411
|
-
this.prompting();
|
|
412
|
-
}
|
|
413
|
-
/** 读取剪贴板图片,推入待发送列表 */
|
|
414
|
-
async attachImage() {
|
|
415
|
-
const image = await readClipboardImage();
|
|
416
|
-
if (!image) {
|
|
417
|
-
this.printNotice("[剪贴板中没有图片]");
|
|
418
|
-
return;
|
|
419
|
-
}
|
|
420
|
-
if (image.bytes > 5242880) {
|
|
421
|
-
this.printNotice(`[图片过大(${humanizeNumber(image.bytes)}B),已忽略]`);
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
this.pendingImages.push({
|
|
425
|
-
type: "image_url",
|
|
426
|
-
image_url: { url: image.url }
|
|
427
|
-
});
|
|
428
|
-
this.printNotice(`[已粘贴图片:共${this.pendingImages.length}张]`);
|
|
429
|
-
}
|
|
430
|
-
/**
|
|
431
|
-
* 所有print方法调用前:
|
|
432
|
-
* 状态切换时打印换行,并记录当前状态
|
|
433
|
-
* @returns 是否发生了状态切换
|
|
434
|
-
*/
|
|
435
|
-
preparePrint(type) {
|
|
436
|
-
if (this.prevPrintType === type) return false;
|
|
437
|
-
if (type === "content_delta" && this.md === null) this.md = new MarkdownRenderer();
|
|
438
|
-
if (this.prevPrintType === "content_delta") {
|
|
439
|
-
const remaining = this.md?.flush();
|
|
440
|
-
if (remaining) process.stdout.write(remaining);
|
|
441
|
-
}
|
|
442
|
-
process.stdout.write("\n");
|
|
443
|
-
this.prevPrintType = type;
|
|
444
|
-
return true;
|
|
445
|
-
}
|
|
446
|
-
/**
|
|
447
|
-
* 为文本添加ANSI颜色;非TTY输出(重定向/管道)时返回原文本,避免日志出现转义码。
|
|
448
|
-
* @param text 原始文本
|
|
449
|
-
* @param ansiCode ANSI颜色代码,如"90"(亮黑,大多数终端显示为灰色)
|
|
450
|
-
*/
|
|
451
|
-
colorize(text, ansiCode) {
|
|
452
|
-
if (!process.stdout.isTTY) return text;
|
|
453
|
-
return `\x1b[${ansiCode}m${text}\x1b[0m`;
|
|
454
|
-
}
|
|
455
|
-
/** 把一个Agent事件分发到对应的print方法上 */
|
|
456
|
-
render(event) {
|
|
457
|
-
switch (event.type) {
|
|
458
|
-
case "reasoning_delta":
|
|
459
|
-
this.printReasoning(event.delta);
|
|
460
|
-
break;
|
|
461
|
-
case "content_delta":
|
|
462
|
-
this.printContent(event.delta);
|
|
463
|
-
break;
|
|
464
|
-
case "tool_call":
|
|
465
|
-
this.printToolCall(event.name, event.args);
|
|
466
|
-
break;
|
|
467
|
-
case "result":
|
|
468
|
-
this.printContent(event.content);
|
|
469
|
-
break;
|
|
470
|
-
case "tool_result":
|
|
471
|
-
this.printToolResult(event.name, event.result);
|
|
472
|
-
break;
|
|
473
|
-
case "error":
|
|
474
|
-
this.printContent(event.message);
|
|
475
|
-
break;
|
|
476
|
-
case "done": this.printFinish(event.finishReason, event.usage);
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
/** 流式打印AI思考内容(灰色) */
|
|
480
|
-
printReasoning(delta) {
|
|
481
|
-
if (this.preparePrint("reasoning_delta")) delta = `[思考内容] ${delta.replaceAll("\n", "")}`;
|
|
482
|
-
process.stdout.write(this.colorize(delta, "90"));
|
|
483
|
-
}
|
|
484
|
-
/** 流式打印AI回复内容 */
|
|
485
|
-
printContent(delta) {
|
|
486
|
-
this.preparePrint("content_delta");
|
|
487
|
-
const rendered = this.md?.push(delta);
|
|
488
|
-
if (rendered) process.stdout.write(rendered);
|
|
489
|
-
}
|
|
490
|
-
/** 打印工具调用 */
|
|
491
|
-
printToolCall(name, args) {
|
|
492
|
-
this.preparePrint("tool_call");
|
|
493
|
-
process.stdout.write(`[工具调用:${name}] ${args}\n`);
|
|
494
|
-
}
|
|
495
|
-
/** 打印工具结果 */
|
|
496
|
-
printToolResult(name, result, options) {
|
|
497
|
-
const { ellipsis = true } = options ?? {};
|
|
498
|
-
const _result = ellipsis ? compactStr(result, {
|
|
499
|
-
maxLength: 100,
|
|
500
|
-
truncateMiddle: true
|
|
501
|
-
}) : result;
|
|
502
|
-
this.preparePrint("tool_result");
|
|
503
|
-
process.stdout.write(this.colorize(`[工具结果:${name}] ${_result}\n`, "90"));
|
|
504
|
-
}
|
|
505
|
-
/** 打印轮次结束原因、token消耗 */
|
|
506
|
-
printFinish(finishReason, usage) {
|
|
507
|
-
this.preparePrint("done");
|
|
508
|
-
process.stdout.write(this.colorize(`[本轮结束:${finishReason}] ${usage ? `输入${humanizeNumber(usage.prompt_tokens)},输出${humanizeNumber(usage.completion_tokens)},总共${humanizeNumber(usage.total_tokens)}` : ""}${usage?.speed ? `,速度${usage.speed}/秒` : ""}${finishReason === "stop" ? "\n\n" : "\n"}`, "90"));
|
|
509
|
-
}
|
|
510
|
-
/** 打印一行黄字提示,正停在提示符上时顺便重绘输入行 */
|
|
511
|
-
printNotice(message) {
|
|
512
|
-
process.stdout.write(`${this.colorize(message, "93")}\n`);
|
|
513
|
-
if (this.isPrompting) this.rl?.prompt(true);
|
|
514
|
-
}
|
|
515
|
-
};
|
|
516
|
-
//#endregion
|
|
517
|
-
//#region src/cli.ts
|
|
518
|
-
/**
|
|
519
|
-
* 组装用户消息的content
|
|
520
|
-
* @remarks 有图片时必须用ContentPart[](OpenAI多模态协议),纯文本则保持字符串
|
|
521
|
-
*/
|
|
522
|
-
const buildUserContent = (text, images) => {
|
|
523
|
-
if (images.length === 0) return text;
|
|
524
|
-
const content = [];
|
|
525
|
-
if (text) content.push({
|
|
526
|
-
type: "text",
|
|
527
|
-
text
|
|
528
|
-
});
|
|
529
|
-
content.push(...images);
|
|
530
|
-
return content;
|
|
531
|
-
};
|
|
532
|
-
/**
|
|
533
|
-
* 启动交互对话:配置来自全局配置文件,环境变量可临时覆盖
|
|
534
|
-
* @param prompt 带上提示词时,先自动发出这一轮,之后照常继续对话
|
|
535
|
-
*/
|
|
536
|
-
const startChat = async (prompt) => {
|
|
537
|
-
const config = loadConfig();
|
|
538
|
-
if (!config) {
|
|
539
|
-
console.error("请先运行 `ai setup` 配置一个模型");
|
|
540
|
-
process.exit(1);
|
|
541
|
-
}
|
|
542
|
-
const model = defineModel(config);
|
|
543
|
-
let mcpReady = false;
|
|
544
|
-
const mcpLoading = loadMCPTools(config.mcpServers).then((tools) => {
|
|
545
|
-
mcpReady = true;
|
|
546
|
-
return tools;
|
|
547
|
-
});
|
|
548
|
-
const messages = [{
|
|
549
|
-
role: "system",
|
|
550
|
-
content: `你是${model.model},当前时间${(/* @__PURE__ */ new Date()).toLocaleString()}`
|
|
551
|
-
}];
|
|
552
|
-
let tools = null;
|
|
553
|
-
const tui = new TUI(async ({ text, images }) => {
|
|
554
|
-
messages.push({
|
|
555
|
-
role: "user",
|
|
556
|
-
content: buildUserContent(text, images)
|
|
557
|
-
});
|
|
558
|
-
if (!mcpReady) tui.printNotice("MCP工具还未加载完成,请稍候……");
|
|
559
|
-
tools ??= [
|
|
560
|
-
get_weather_default,
|
|
561
|
-
get_time_default,
|
|
562
|
-
...await mcpLoading
|
|
563
|
-
];
|
|
564
|
-
for await (const e of runAgent(model, messages, {
|
|
565
|
-
tools,
|
|
566
|
-
stream: true
|
|
567
|
-
})) tui.render(e);
|
|
568
|
-
});
|
|
569
|
-
tui.start(prompt);
|
|
570
|
-
};
|
|
571
|
-
/** 打印命令用法 */
|
|
572
|
-
const printHelp = () => {
|
|
573
|
-
console.log(`用法: ai [命令/提示词]
|
|
1
|
+
import{defineModel as e}from"./utils/helper.mjs";import{runAgent as t}from"./agent.mjs";import n from"./tools/get-time.mjs";import r from"./tools/get-weather.mjs";import{loadMCPTools as i}from"./tools/mcp.mjs";import{loadConfig as a}from"./utils/config.mjs";import{runSetup as o}from"./interfaces/setup.mjs";import{TUI as s}from"./interfaces/tui.mjs";const c=(e,t)=>{if(t.length===0)return e;let n=[];return e&&n.push({type:`text`,text:e}),n.push(...t),n},l=async o=>{let l=a();l||(console.error("请先运行 `ai setup` 配置一个模型"),process.exit(1));let u=e(l),d=!1,f=i(l.mcpServers).then(e=>(d=!0,e)),p=[{role:`system`,content:`你是${u.model},当前时间${(/* @__PURE__ */ new Date()).toLocaleString()}`}],m=null,h=new s(async({text:e,images:i})=>{p.push({role:`user`,content:c(e,i)}),d||h.printNotice(`MCP工具还未加载完成,请稍候……`),m??=[r,n,...await f];for await(let e of t(u,p,{tools:m,stream:!0}))h.render(e)});h.start(o)},u=()=>{console.log(`用法: ai [命令/提示词]
|
|
574
2
|
|
|
575
3
|
命令:
|
|
576
4
|
--help 显示帮助
|
|
577
5
|
setup 交互式配置模型APIKEY / BASE_URL / MODEL(保存到 ~/.@nickyzj2023/ai/config.json)
|
|
578
6
|
|
|
579
7
|
带上提示词时,启动对话的同时先把这段提示词发出去(如\`ai 明天适合洗车吗\`)
|
|
580
|
-
不带参数则直接进入对话`);
|
|
581
|
-
};
|
|
582
|
-
const args = process.argv.slice(2);
|
|
583
|
-
const command = args[0];
|
|
584
|
-
switch (command) {
|
|
585
|
-
case void 0:
|
|
586
|
-
startChat();
|
|
587
|
-
break;
|
|
588
|
-
case "setup":
|
|
589
|
-
await runSetup();
|
|
590
|
-
break;
|
|
591
|
-
case "--help":
|
|
592
|
-
case "-h":
|
|
593
|
-
printHelp();
|
|
594
|
-
break;
|
|
595
|
-
default:
|
|
596
|
-
if (command.startsWith("-")) {
|
|
597
|
-
console.error(`未知命令:${command}(可以运行ai --help查看用法)`);
|
|
598
|
-
process.exit(1);
|
|
599
|
-
}
|
|
600
|
-
startChat(args.join(" ").trim() || void 0);
|
|
601
|
-
}
|
|
602
|
-
//#endregion
|
|
603
|
-
export {};
|
|
8
|
+
不带参数则直接进入对话`)},d=process.argv.slice(2),f=d[0];switch(f){case void 0:l();break;case`setup`:await o();break;case`--help`:case`-h`:u();break;default:f.startsWith(`-`)&&(console.error(`未知命令:${f}(可以运行ai --help查看用法)`),process.exit(1)),l(d.join(` `).trim()||void 0)}export{};
|