@opentiny/next-sdk 0.2.5 → 0.2.6-beta.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/agent/utils/generateReActPrompt.ts +36 -20
- package/dist/index.d.ts +1 -0
- package/dist/index.es.dev.js +852 -210
- package/dist/index.es.js +11035 -10504
- package/dist/index.js +1433 -1337
- package/dist/index.umd.dev.js +852 -210
- package/dist/index.umd.js +75 -73
- package/dist/page-tool-bridge.d.ts +114 -0
- package/dist/skills/index.d.ts +7 -2
- package/dist/webagent.dev.js +700 -196
- package/dist/webagent.es.dev.js +700 -196
- package/dist/webagent.es.js +11494 -11057
- package/dist/webagent.js +81 -79
- package/index.ts +3 -0
- package/package.json +1 -1
- package/page-tool-bridge.ts +365 -0
- package/skills/index.ts +47 -17
package/index.ts
CHANGED
|
@@ -39,6 +39,9 @@ export { getAISDKTools } from './agent/utils/getAISDKTools'
|
|
|
39
39
|
export { QrCode, type QrCodeOption } from './remoter/QrCode'
|
|
40
40
|
export type * from './agent/type'
|
|
41
41
|
|
|
42
|
+
// Web MCP 页面工具桥接:工具调用自动导航 + 页面消息通信
|
|
43
|
+
export * from './page-tool-bridge'
|
|
44
|
+
|
|
42
45
|
// Web 端 Skill 公共能力:解析 skill 文档、生成 systemPrompt、内置 list_skills / get_skill_content 工具
|
|
43
46
|
export {
|
|
44
47
|
getSkillOverviews,
|
package/package.json
CHANGED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* page-tool-bridge - Web MCP 页面工具桥接模块(框架无关)
|
|
3
|
+
*
|
|
4
|
+
* 解决 Web-MCP 工具动态加载问题:工具定义(mcp-servers/)不直接写业务逻辑,
|
|
5
|
+
* 而是通过 window.postMessage 将调用转发给目标页面,页面处理后返回结果。
|
|
6
|
+
*
|
|
7
|
+
* 核心 API:
|
|
8
|
+
* - setNavigator(fn) 在应用入口注册导航函数
|
|
9
|
+
* - withPageTools(server)
|
|
10
|
+
* 包装 WebMcpServer,让 registerTool 第三个参数
|
|
11
|
+
* 同时支持原始回调函数和路由配置对象(RouteConfig)
|
|
12
|
+
* - registerPageTool() 在目标页面激活工具处理器,返回 cleanup 函数
|
|
13
|
+
*
|
|
14
|
+
* 使用方式:
|
|
15
|
+
* // mcp-servers/index.ts
|
|
16
|
+
* const server = withPageTools(new WebMcpServer())
|
|
17
|
+
*
|
|
18
|
+
* // mcp-servers/product-guide/tools.ts
|
|
19
|
+
* server.registerTool('product-guide', { title, description, inputSchema },
|
|
20
|
+
* { route: '/comprehensive' } // ← 路由配置对象,替代回调函数
|
|
21
|
+
* )
|
|
22
|
+
* // 或仍然使用普通回调(完全兼容)
|
|
23
|
+
* server.registerTool('simple-tool', { ... }, async (input) => { ... })
|
|
24
|
+
*
|
|
25
|
+
* // 目标页面(Vue)— route 可省略,默认取 window.location.pathname
|
|
26
|
+
* onMounted(() => { cleanup = registerPageTool({ handlers }) })
|
|
27
|
+
* onUnmounted(() => cleanup())
|
|
28
|
+
*
|
|
29
|
+
* // 目标页面(Vue)— 当页面路由与 pathname 不一致时,手动指定 route
|
|
30
|
+
* onMounted(() => { cleanup = registerPageTool({ route: '/my-page', handlers }) })
|
|
31
|
+
* onUnmounted(() => cleanup())
|
|
32
|
+
*
|
|
33
|
+
* // 目标页面(React)
|
|
34
|
+
* useEffect(() => registerPageTool({ handlers }), [])
|
|
35
|
+
*
|
|
36
|
+
* // 目标页面(Angular)
|
|
37
|
+
* export class MyComponent implements OnInit, OnDestroy {
|
|
38
|
+
* private cleanupPageTool!: () => void
|
|
39
|
+
* ngOnInit() { this.cleanupPageTool = registerPageTool({ handlers }) }
|
|
40
|
+
* ngOnDestroy() { this.cleanupPageTool() }
|
|
41
|
+
* }
|
|
42
|
+
*
|
|
43
|
+
* setNavigator 在不同框架中的注册方式:
|
|
44
|
+
* // Vue(main.ts)
|
|
45
|
+
* const router = createRouter(...)
|
|
46
|
+
* app.use(router)
|
|
47
|
+
* setNavigator((route) => router.push(route))
|
|
48
|
+
*
|
|
49
|
+
* // React(App.tsx,使用 react-router-dom)
|
|
50
|
+
* function AppNavigator() {
|
|
51
|
+
* const navigate = useNavigate()
|
|
52
|
+
* useEffect(() => { setNavigator((route) => navigate(route)) }, [navigate])
|
|
53
|
+
* return null
|
|
54
|
+
* }
|
|
55
|
+
*
|
|
56
|
+
* // Angular(AppComponent,使用 @angular/router)
|
|
57
|
+
* export class AppComponent {
|
|
58
|
+
* constructor(private router: Router) {
|
|
59
|
+
* setNavigator((route) => this.router.navigateByUrl(route))
|
|
60
|
+
* }
|
|
61
|
+
* }
|
|
62
|
+
*/
|
|
63
|
+
import type { ZodRawShape } from 'zod'
|
|
64
|
+
import type { RegisteredTool } from '@modelcontextprotocol/sdk/server/mcp.js'
|
|
65
|
+
import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js'
|
|
66
|
+
import type { WebMcpServer } from './WebMcpServer'
|
|
67
|
+
import { randomUUID } from './utils/uuid'
|
|
68
|
+
|
|
69
|
+
// 消息类型常量,使用命名空间前缀避免冲突
|
|
70
|
+
const MSG_TOOL_CALL = 'next-sdk:tool-call'
|
|
71
|
+
const MSG_TOOL_RESPONSE = 'next-sdk:tool-response'
|
|
72
|
+
const MSG_PAGE_READY = 'next-sdk:page-ready'
|
|
73
|
+
|
|
74
|
+
// 已激活页面注册表:路由路径 → 是否已挂载
|
|
75
|
+
const activePages = new Map<string, boolean>()
|
|
76
|
+
|
|
77
|
+
// 应用注册的导航函数,由 setNavigator 设置
|
|
78
|
+
let _navigator: ((route: string) => void | Promise<void>) | null = null
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 注册应用的导航函数,通常在应用入口(如 main.ts)调用一次。
|
|
82
|
+
* @param fn 导航函数,接收路由路径并执行跳转(如 router.push)
|
|
83
|
+
*/
|
|
84
|
+
export function setNavigator(fn: (route: string) => void | Promise<void>) {
|
|
85
|
+
_navigator = fn
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* registerTool 第三个参数的路由配置对象类型。
|
|
90
|
+
* 当传入此类型时,工具调用会自动跳转到 route 对应的页面并通过消息通信执行。
|
|
91
|
+
*/
|
|
92
|
+
export type RouteConfig = {
|
|
93
|
+
/** 目标路由路径,如 '/comprehensive' */
|
|
94
|
+
route: string
|
|
95
|
+
/** 等待页面响应的超时时间(ms),默认 30000 */
|
|
96
|
+
timeout?: number
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* PageAwareServer 的 registerTool 配置对象类型,与 WebMcpServer.registerTool 保持一致。
|
|
101
|
+
*/
|
|
102
|
+
type RegisterToolConfig<InputArgs extends ZodRawShape, OutputArgs extends ZodRawShape> = {
|
|
103
|
+
title?: string
|
|
104
|
+
description?: string
|
|
105
|
+
inputSchema?: InputArgs
|
|
106
|
+
outputSchema?: OutputArgs
|
|
107
|
+
annotations?: ToolAnnotations
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 包装 WebMcpServer 后的类型:registerTool 第三个参数额外支持 RouteConfig。
|
|
112
|
+
* 泛型签名与 WebMcpServer.registerTool 对齐,保持完整的类型推导能力。
|
|
113
|
+
* 原有的回调函数写法完全兼容,无需改动。
|
|
114
|
+
*/
|
|
115
|
+
export type PageAwareServer = Omit<WebMcpServer, 'registerTool'> & {
|
|
116
|
+
registerTool<InputArgs extends ZodRawShape, OutputArgs extends ZodRawShape>(
|
|
117
|
+
name: string,
|
|
118
|
+
config: RegisterToolConfig<InputArgs, OutputArgs>,
|
|
119
|
+
// handler 不引入 ToolCallback<InputArgs>:该类型含 MCP SDK 深层泛型,
|
|
120
|
+
// 叠加 ZodRawShape 推断链后会触发"类型实例化过深"。
|
|
121
|
+
// 实际类型安全由 Proxy 内部透传给 WebMcpServer.registerTool 保证。
|
|
122
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
123
|
+
handlerOrRoute: ((...args: any[]) => any) | RouteConfig
|
|
124
|
+
): RegisteredTool
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 内部:根据 name/route/timeout 生成转发给页面的 handler 函数。
|
|
129
|
+
* 调用流程:
|
|
130
|
+
* 1. 若目标路由已激活 → 直接 postMessage 发送工具调用
|
|
131
|
+
* 2. 若未激活 → 调用导航函数跳转,等待 page-ready 信号后再发送
|
|
132
|
+
* 3. 页面处理后回传结果,Promise resolve
|
|
133
|
+
*/
|
|
134
|
+
function buildPageHandler(name: string, route: string, timeout = 30000) {
|
|
135
|
+
return (input: any): Promise<any> => {
|
|
136
|
+
const callId = randomUUID()
|
|
137
|
+
|
|
138
|
+
return new Promise<any>((resolve, reject) => {
|
|
139
|
+
let timer: ReturnType<typeof setTimeout>
|
|
140
|
+
// readyHandler 需在 cleanup 中一并移除,避免导航失败时泄漏监听器
|
|
141
|
+
let readyHandler: ((event: MessageEvent) => void) | undefined
|
|
142
|
+
|
|
143
|
+
const cleanup = () => {
|
|
144
|
+
clearTimeout(timer)
|
|
145
|
+
window.removeEventListener('message', responseHandler)
|
|
146
|
+
if (readyHandler) {
|
|
147
|
+
window.removeEventListener('message', readyHandler)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// 超时兜底,防止页面永远不响应
|
|
152
|
+
timer = setTimeout(() => {
|
|
153
|
+
cleanup()
|
|
154
|
+
reject(new Error(`工具 [${name}] 调用超时 (${timeout}ms),请检查目标页面是否正确调用了 registerPageTool`))
|
|
155
|
+
}, timeout)
|
|
156
|
+
|
|
157
|
+
// 通过 callId 精确匹配响应,避免并发调用互相串扰
|
|
158
|
+
const responseHandler = (event: MessageEvent) => {
|
|
159
|
+
if (event.source === window && event.data?.type === MSG_TOOL_RESPONSE && event.data.callId === callId) {
|
|
160
|
+
cleanup()
|
|
161
|
+
event.data.error ? reject(new Error(event.data.error)) : resolve(event.data.result)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
window.addEventListener('message', responseHandler)
|
|
165
|
+
|
|
166
|
+
const sendCall = () => {
|
|
167
|
+
window.postMessage({ type: MSG_TOOL_CALL, callId, toolName: name, route, input }, window.location.origin || '*')
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 单次发送守卫:readyHandler 与导航后 activePages 补充检查均可触发 sendCall,
|
|
171
|
+
// 用此 flag 确保同一次工具调用只发送一条消息,防止工具被重复执行。
|
|
172
|
+
let callSent = false
|
|
173
|
+
const sendCallOnce = () => {
|
|
174
|
+
if (callSent) return
|
|
175
|
+
callSent = true
|
|
176
|
+
sendCall()
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// 将异步导航逻辑提取为独立 run 函数并用 void 调用,
|
|
180
|
+
// 避免在 Promise executor 中直接使用 async(Biome noAsyncPromiseExecutor 规则)。
|
|
181
|
+
// 导航失败时显式 reject,防止外层 Promise 永远挂起。
|
|
182
|
+
const run = async () => {
|
|
183
|
+
try {
|
|
184
|
+
if (activePages.get(route)) {
|
|
185
|
+
// 页面已激活,直接发送
|
|
186
|
+
sendCallOnce()
|
|
187
|
+
return
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ⚠️ 必须先注册 readyHandler 再触发导航:
|
|
191
|
+
// 若先导航再注册,极快的导航(同步或微任务)可能导致
|
|
192
|
+
// 目标页面已广播 page-ready 而监听器尚未挂载,从而错过信号。
|
|
193
|
+
readyHandler = (event: MessageEvent) => {
|
|
194
|
+
if (event.source === window && event.data?.type === MSG_PAGE_READY && event.data.route === route) {
|
|
195
|
+
window.removeEventListener('message', readyHandler!)
|
|
196
|
+
sendCallOnce()
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
window.addEventListener('message', readyHandler)
|
|
200
|
+
|
|
201
|
+
if (_navigator) {
|
|
202
|
+
await _navigator(route)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// 导航 await 完成后,再次检查 activePages:
|
|
206
|
+
// 若页面在注册监听器与导航之间极短间隙内已激活(极端竞态),
|
|
207
|
+
// message 事件已被 handleMessage 消费但 readyHandler 未执行,
|
|
208
|
+
// 此处补充检查确保不会永久等待。
|
|
209
|
+
// sendCallOnce 保证即使两条路径都触发,消息也只发送一次。
|
|
210
|
+
if (activePages.get(route)) {
|
|
211
|
+
window.removeEventListener('message', readyHandler)
|
|
212
|
+
sendCallOnce()
|
|
213
|
+
}
|
|
214
|
+
} catch (err) {
|
|
215
|
+
// 导航本身抛出异常时,确保 Promise 被 reject 而非永远挂起
|
|
216
|
+
cleanup()
|
|
217
|
+
reject(err instanceof Error ? err : new Error(String(err)))
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
void run()
|
|
221
|
+
})
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* 包装 WebMcpServer,使 registerTool 第三个参数支持 RouteConfig。
|
|
227
|
+
*
|
|
228
|
+
* - 第三个参数为**回调函数**:与原始 registerTool 完全一致,直接透传
|
|
229
|
+
* - 第三个参数为 **RouteConfig 对象**:自动生成转发 handler,工具调用时
|
|
230
|
+
* 先导航到目标路由,再通过 postMessage 与页面通信
|
|
231
|
+
*
|
|
232
|
+
* @example
|
|
233
|
+
* const server = withPageTools(new WebMcpServer())
|
|
234
|
+
*
|
|
235
|
+
* // 路由模式:第三个参数传路由配置
|
|
236
|
+
* server.registerTool('product-guide', { title, inputSchema }, { route: '/comprehensive' })
|
|
237
|
+
*
|
|
238
|
+
* // 普通模式:第三个参数传回调(兼容原有写法)
|
|
239
|
+
* server.registerTool('simple-tool', { title }, async (input) => ({ content: [...] }))
|
|
240
|
+
*/
|
|
241
|
+
export function withPageTools(server: WebMcpServer): PageAwareServer {
|
|
242
|
+
return new Proxy(server, {
|
|
243
|
+
get(target, prop, receiver) {
|
|
244
|
+
if (prop === 'registerTool') {
|
|
245
|
+
return (name: string, config: any, handlerOrRoute: ((...args: any[]) => any) | RouteConfig) => {
|
|
246
|
+
// 第三个参数是函数 → 直接透传,行为与原始 registerTool 完全相同
|
|
247
|
+
// 通过 (target as any) 避免 WebMcpServer.registerTool 深层泛型触发"类型实例化过深"
|
|
248
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
249
|
+
const rawRegister = (target as any).registerTool.bind(target)
|
|
250
|
+
if (typeof handlerOrRoute === 'function') {
|
|
251
|
+
return rawRegister(name, config, handlerOrRoute)
|
|
252
|
+
}
|
|
253
|
+
// 第三个参数是路由配置对象 → 自动生成转发 handler
|
|
254
|
+
const { route, timeout } = handlerOrRoute
|
|
255
|
+
return rawRegister(name, config, buildPageHandler(name, route, timeout))
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return Reflect.get(target, prop, receiver)
|
|
259
|
+
}
|
|
260
|
+
}) as unknown as PageAwareServer
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* 在目标页面激活工具处理器(框架无关的纯 JS 函数)。
|
|
265
|
+
*
|
|
266
|
+
* 调用后立即:
|
|
267
|
+
* - 将路由注册到 activePages(标记页面已激活)
|
|
268
|
+
* - 添加 message 监听,处理来自 buildPageHandler 的工具调用
|
|
269
|
+
* - 广播 page-ready 信号,通知正在等待导航完成的工具
|
|
270
|
+
*
|
|
271
|
+
* 返回 cleanup 函数,页面销毁时调用。
|
|
272
|
+
*
|
|
273
|
+
* @example
|
|
274
|
+
* // Vue(Composition API)— 省略 route,默认读 window.location.pathname
|
|
275
|
+
* let cleanup: () => void
|
|
276
|
+
* onMounted(() => { cleanup = registerPageTool({ handlers: { ... } }) })
|
|
277
|
+
* onUnmounted(() => cleanup())
|
|
278
|
+
*
|
|
279
|
+
* // Vue — 当页面路由与 pathname 不一致时,手动指定 route
|
|
280
|
+
* onMounted(() => { cleanup = registerPageTool({ route: '/comprehensive', handlers: { ... } }) })
|
|
281
|
+
* onUnmounted(() => cleanup())
|
|
282
|
+
*
|
|
283
|
+
* // React(Hooks)
|
|
284
|
+
* useEffect(() => registerPageTool({ handlers: { ... } }), [])
|
|
285
|
+
* // useEffect 直接返回 cleanup 函数,React 会在组件卸载时自动调用
|
|
286
|
+
*
|
|
287
|
+
* // Angular(实现 OnInit / OnDestroy 接口)
|
|
288
|
+
* export class PriceProtectionComponent implements OnInit, OnDestroy {
|
|
289
|
+
* private cleanupPageTool!: () => void
|
|
290
|
+
*
|
|
291
|
+
* ngOnInit(): void {
|
|
292
|
+
* this.cleanupPageTool = registerPageTool({
|
|
293
|
+
* handlers: {
|
|
294
|
+
* 'price-protection-query': async ({ status }) => { ... },
|
|
295
|
+
* }
|
|
296
|
+
* })
|
|
297
|
+
* }
|
|
298
|
+
*
|
|
299
|
+
* ngOnDestroy(): void {
|
|
300
|
+
* this.cleanupPageTool()
|
|
301
|
+
* }
|
|
302
|
+
* }
|
|
303
|
+
*/
|
|
304
|
+
export function registerPageTool(options: {
|
|
305
|
+
/**
|
|
306
|
+
* 目标路由路径,与 RouteConfig.route 保持一致。
|
|
307
|
+
* 省略时自动读取 window.location.pathname。
|
|
308
|
+
* 当页面路由与 pathname 不一致时(如 hash 路由、子路径前缀等),需手动传入。
|
|
309
|
+
*/
|
|
310
|
+
route?: string
|
|
311
|
+
/**
|
|
312
|
+
* 工具名 → 处理函数的映射表。
|
|
313
|
+
*
|
|
314
|
+
* 此处 handler 的 input 参数类型保留 any:
|
|
315
|
+
* 若改为 unknown,TypeScript 函数参数逆变规则会导致用户的具名解构写法
|
|
316
|
+
*(如 `async ({ productId }: { productId: string }) => ...`)无法通过类型检查,
|
|
317
|
+
* 破坏现有调用方代码的开发体验。运行时输入由 MCP inputSchema 保证类型安全。
|
|
318
|
+
*/
|
|
319
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
320
|
+
handlers: Record<string, (input: any) => Promise<any>>
|
|
321
|
+
}): () => void {
|
|
322
|
+
const { route: routeOption, handlers } = options
|
|
323
|
+
// 规范化路由:去除尾部斜杠,空路径兜底为 '/',确保与 buildPageHandler 侧一致
|
|
324
|
+
// 优先使用用户传入的 route,否则回退到 window.location.pathname
|
|
325
|
+
const normalizeRoute = (value: string) => value.replace(/\/+$/, '') || '/'
|
|
326
|
+
const route = normalizeRoute(routeOption ?? window.location.pathname)
|
|
327
|
+
|
|
328
|
+
const handleMessage = async (event: MessageEvent) => {
|
|
329
|
+
// 同时校验 route 字段,防止多页面注册同名工具时发生跨路由串扰
|
|
330
|
+
// 对消息携带的 route 同样规范化,避免因尾部斜杠等差异导致匹配失败
|
|
331
|
+
if (
|
|
332
|
+
event.source !== window ||
|
|
333
|
+
event.data?.type !== MSG_TOOL_CALL ||
|
|
334
|
+
normalizeRoute(String(event.data?.route ?? '')) !== route ||
|
|
335
|
+
!(event.data.toolName in handlers)
|
|
336
|
+
) {
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
const { callId, toolName, input } = event.data
|
|
340
|
+
try {
|
|
341
|
+
const result = await handlers[toolName](input)
|
|
342
|
+
window.postMessage({ type: MSG_TOOL_RESPONSE, callId, result }, window.location.origin || '*')
|
|
343
|
+
} catch (err) {
|
|
344
|
+
window.postMessage(
|
|
345
|
+
{
|
|
346
|
+
type: MSG_TOOL_RESPONSE,
|
|
347
|
+
callId,
|
|
348
|
+
error: err instanceof Error ? err.message : String(err)
|
|
349
|
+
},
|
|
350
|
+
window.location.origin || '*'
|
|
351
|
+
)
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// 注册页面为已激活状态并广播就绪信号
|
|
356
|
+
activePages.set(route, true)
|
|
357
|
+
window.addEventListener('message', handleMessage)
|
|
358
|
+
window.postMessage({ type: MSG_PAGE_READY, route }, window.location.origin || '*')
|
|
359
|
+
|
|
360
|
+
// 返回 cleanup,由各框架在页面销毁时调用
|
|
361
|
+
return () => {
|
|
362
|
+
activePages.delete(route)
|
|
363
|
+
window.removeEventListener('message', handleMessage)
|
|
364
|
+
}
|
|
365
|
+
}
|
package/skills/index.ts
CHANGED
|
@@ -42,21 +42,42 @@ export function parseSkillFrontMatter(content: string): { name: string; descript
|
|
|
42
42
|
return name && description ? { name, description } : null
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
/**
|
|
46
|
+
* 将 Vite import.meta.glob 得到的多种 key 格式统一为「相对 skills 根目录」的路径(如 ./calculator/SKILL.md),
|
|
47
|
+
* 以便 getSkillMdContent / getMainSkillPathByName 等能正确按 path 查找。
|
|
48
|
+
* 兼容任意引入位置:./skills/xxx、../skills/xxx、src/skills/xxx 等,取最后一个 skills/ 后的部分并加上 ./
|
|
49
|
+
*/
|
|
50
|
+
function normalizeSkillModuleKeys(modules: Record<string, string>): Record<string, string> {
|
|
51
|
+
const result: Record<string, string> = {}
|
|
52
|
+
for (const [key, content] of Object.entries(modules)) {
|
|
53
|
+
const normalizedKey = key.replace(/\\/g, '/')
|
|
54
|
+
const skillsIndex = normalizedKey.lastIndexOf('skills/')
|
|
55
|
+
const relativePath = skillsIndex >= 0 ? normalizedKey.slice(skillsIndex + 7) : normalizedKey
|
|
56
|
+
const standardPath = relativePath.startsWith('./') ? relativePath : `./${relativePath}`
|
|
57
|
+
result[standardPath] = content
|
|
58
|
+
}
|
|
59
|
+
return result
|
|
60
|
+
}
|
|
61
|
+
|
|
45
62
|
/**
|
|
46
63
|
* 获取所有「主 SKILL.md」的路径(一级子目录下的 SKILL.md)
|
|
64
|
+
* - 对传入的 modules 先做 normalize,兼容任意 import.meta.glob 写法
|
|
47
65
|
*/
|
|
48
66
|
export function getMainSkillPaths(modules: Record<string, string>): string[] {
|
|
49
|
-
|
|
67
|
+
const normalized = normalizeSkillModuleKeys(modules)
|
|
68
|
+
return Object.keys(normalized).filter((path) => MAIN_SKILL_PATH_REG.test(path))
|
|
50
69
|
}
|
|
51
70
|
|
|
52
71
|
/**
|
|
53
72
|
* 获取所有技能的概况列表(name、description、path),用于 systemPrompt 或列表展示
|
|
73
|
+
* - 内部统一对 modules 做 normalize,避免调用方关心路径细节
|
|
54
74
|
*/
|
|
55
75
|
export function getSkillOverviews(modules: Record<string, string>): SkillMeta[] {
|
|
56
|
-
const
|
|
76
|
+
const normalized = normalizeSkillModuleKeys(modules)
|
|
77
|
+
const mainPaths = Object.keys(normalized).filter((path) => MAIN_SKILL_PATH_REG.test(path))
|
|
57
78
|
const list: SkillMeta[] = []
|
|
58
79
|
for (const path of mainPaths) {
|
|
59
|
-
const content =
|
|
80
|
+
const content = normalized[path]
|
|
60
81
|
if (!content) continue
|
|
61
82
|
const parsed = parseSkillFrontMatter(content)
|
|
62
83
|
if (!parsed) continue
|
|
@@ -80,21 +101,26 @@ export function formatSkillsForSystemPrompt(skills: SkillMeta[]): string {
|
|
|
80
101
|
}
|
|
81
102
|
|
|
82
103
|
/**
|
|
83
|
-
*
|
|
104
|
+
* 获取所有已加载的技能文件路径(含主 SKILL.md 与 reference 下的 .md/.json/.xml 等)
|
|
105
|
+
* - 对 modules 做 normalize 后再返回 key 列表
|
|
84
106
|
*/
|
|
85
107
|
export function getSkillMdPaths(modules: Record<string, string>): string[] {
|
|
86
|
-
|
|
108
|
+
const normalized = normalizeSkillModuleKeys(modules)
|
|
109
|
+
return Object.keys(normalized)
|
|
87
110
|
}
|
|
88
111
|
|
|
89
112
|
/**
|
|
90
|
-
*
|
|
113
|
+
* 根据相对路径获取某个技能文档的原始内容(支持 .md、.json、.xml 等文本格式)
|
|
114
|
+
* - 自动对 modules 做 normalize,再按 path 查找
|
|
91
115
|
*/
|
|
92
116
|
export function getSkillMdContent(modules: Record<string, string>, path: string): string | undefined {
|
|
93
|
-
|
|
117
|
+
const normalized = normalizeSkillModuleKeys(modules)
|
|
118
|
+
return normalized[path]
|
|
94
119
|
}
|
|
95
120
|
|
|
96
121
|
/**
|
|
97
122
|
* 根据技能 name 查找其主 SKILL.md 的路径(name 与目录名一致)
|
|
123
|
+
* - 依赖 getMainSkillPaths,内部已做 normalize
|
|
98
124
|
*/
|
|
99
125
|
export function getMainSkillPathByName(modules: Record<string, string>, name: string): string | undefined {
|
|
100
126
|
return getMainSkillPaths(modules).find((p) => p.startsWith(`./${name}/SKILL.md`))
|
|
@@ -106,32 +132,36 @@ export function getMainSkillPathByName(modules: Record<string, string>, name: st
|
|
|
106
132
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
107
133
|
export type SkillToolsSet = Record<string, any>
|
|
108
134
|
|
|
135
|
+
// 提升为模块级常量:避免 tool() 推断 PARAMETERS 泛型时递归展开 Zod 链导致"类型实例化过深"
|
|
136
|
+
const SKILL_INPUT_SCHEMA = z.object({
|
|
137
|
+
skillName: z.string().optional().describe('技能名称,与目录名一致,如 calculator'),
|
|
138
|
+
path: z.string().optional().describe('文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.json')
|
|
139
|
+
})
|
|
140
|
+
|
|
109
141
|
/**
|
|
110
142
|
* 根据 skillMdModules 创建供 AI 调用的工具集
|
|
111
143
|
* - get_skill_content: 按技能名或路径获取完整文档内容,便于大模型自动识别并加载技能
|
|
112
144
|
* remoter 可将返回的 tools 合并进 extraTools 注入 agent
|
|
113
145
|
*/
|
|
114
146
|
export function createSkillTools(modules: Record<string, string>): SkillToolsSet {
|
|
147
|
+
const normalizedModules = normalizeSkillModuleKeys(modules)
|
|
115
148
|
const getSkillContent = tool({
|
|
116
149
|
description:
|
|
117
|
-
'
|
|
118
|
-
inputSchema:
|
|
119
|
-
|
|
120
|
-
path: z.string().optional().describe('文档相对路径,如 ./calculator/SKILL.md 或 ./product-guide/reference/xxx.md')
|
|
121
|
-
}),
|
|
122
|
-
execute: (args: { skillName?: string; path?: string }) => {
|
|
150
|
+
'根据技能名称或文档路径获取该技能的完整文档内容。传入 skillName(如 calculator)或 path(如 ./calculator/SKILL.md)。支持 .md、.json、.xml 等各类文本格式文件。',
|
|
151
|
+
inputSchema: SKILL_INPUT_SCHEMA,
|
|
152
|
+
execute: (args: { skillName?: string; path?: string }): Record<string, unknown> => {
|
|
123
153
|
const { skillName, path: pathArg } = args
|
|
124
154
|
let content: string | undefined
|
|
125
155
|
if (pathArg) {
|
|
126
|
-
content = getSkillMdContent(
|
|
156
|
+
content = getSkillMdContent(normalizedModules, pathArg)
|
|
127
157
|
} else if (skillName) {
|
|
128
|
-
const mainPath = getMainSkillPathByName(
|
|
129
|
-
content = mainPath ? getSkillMdContent(
|
|
158
|
+
const mainPath = getMainSkillPathByName(normalizedModules, skillName)
|
|
159
|
+
content = mainPath ? getSkillMdContent(normalizedModules, mainPath) : undefined
|
|
130
160
|
}
|
|
131
161
|
if (content === undefined) {
|
|
132
162
|
return { error: '未找到对应技能文档', skillName: skillName ?? pathArg }
|
|
133
163
|
}
|
|
134
|
-
return { content, path: pathArg ?? getMainSkillPathByName(
|
|
164
|
+
return { content, path: pathArg ?? getMainSkillPathByName(normalizedModules, skillName!) }
|
|
135
165
|
}
|
|
136
166
|
})
|
|
137
167
|
|