@philomelcc/dsh-interaction 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +123 -2
- package/cordis.patch.yml +13 -0
- package/index.js +289 -0
- package/lib/ask.js +205 -0
- package/lib/flow.js +203 -0
- package/lib/sessions.js +260 -0
- package/lib/tool.js +134 -0
- package/package.json +45 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 philomelcc
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,124 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-interaction · 交互增强
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
两块能力,一个插件:
|
|
4
|
+
|
|
5
|
+
1. **分支式提问**(`ask_flow`)—— 声明一张问题图,按依赖分波提问。选了 A 就只问 A 那条线,选了 B 就问 B 那条线。
|
|
6
|
+
2. **跨会话消息**(`session_list` / `session_send` / `session_peek`)—— 主动向另一个会话发消息并唤醒它,发完还能回读对方回复。
|
|
7
|
+
|
|
8
|
+
## 安装
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
# 从 npm 装(装到要用的 profile,一般是 web)
|
|
12
|
+
dsh plugin --profile web add @philomelcc/dsh-interaction
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
本地开发时可以直接 link 一个目录:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
dsh plugin --profile web add ./dsh-interaction
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
装完需要重启一次宿主(加载 Host 半),之后改代码可以用
|
|
22
|
+
`plugin_manager set_plugin target=include:interaction enabled=false/true` 热重载。
|
|
23
|
+
|
|
24
|
+
> 依赖的服务:`ctx.userQuestions`(提问链路)和 `ctx.sessionController`(跨会话)都是
|
|
25
|
+
> web / desktop 装配层才有的能力;纯 CLI profile 里跨会话工具会给出明确报错。
|
|
26
|
+
|
|
27
|
+
## 为什么这么做
|
|
28
|
+
|
|
29
|
+
- 官方 `ask_user_question` 是「一次请求、一次答案」,问题数组里没有分支表达能力。这个插件在**同一个工具调用内多次调用官方 `ctx.userQuestions.ask()`**,逐波收答案再决定下一波问什么。
|
|
30
|
+
- 好处:提问面板完全复用官方 UI,样式、多选、自定义输入、键盘操作原生一致,零前端代码,DSH 升级不易坏。
|
|
31
|
+
- 代价:翻页之间面板会闪一下(官方机制是请求结束即移除卡片)。
|
|
32
|
+
- 官方 `ctx.sessionController.prompt()` 本来就支持「向任意会话投递 prompt 并自动 resume 冷会话」(网页切换会话发消息走的就是它)。插件只是把它包成模型能调的工具,再补上防环、限频等护栏。
|
|
33
|
+
|
|
34
|
+
## 工具
|
|
35
|
+
|
|
36
|
+
### ask_flow
|
|
37
|
+
|
|
38
|
+
```jsonc
|
|
39
|
+
{
|
|
40
|
+
"intro": "先把部署方式定下来", // 可选,第一张卡片顶部说明
|
|
41
|
+
"steps": [
|
|
42
|
+
{ "id": "deploy", "question": "你打算怎么部署?", "header": "部署方式",
|
|
43
|
+
"options": [{ "label": "A 本地部署" }, { "label": "B 云端部署" }] },
|
|
44
|
+
{ "id": "vram", "question": "本地显存多少?", "when": { "id": "deploy", "in": ["A 本地部署"] } },
|
|
45
|
+
{ "id": "cloud", "question": "用哪家云?", "when": { "id": "deploy", "in": ["B 云端部署"] } }
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`when` 支持的写法:
|
|
51
|
+
|
|
52
|
+
| 写法 | 含义 |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `{ id: 'q1', in: ['A'] }` | 前一步选了 A(多选时任一命中即可) |
|
|
55
|
+
| `{ id: 'q1', not_in: ['A'] }` | 前一步没选 A |
|
|
56
|
+
| `{ id: 'q1', answered: true }` | 前一步答过就问 |
|
|
57
|
+
| `[condA, condB]` | 多个条件同时满足 |
|
|
58
|
+
|
|
59
|
+
- 没有依赖的问题会在同一波一起问;有依赖的排到后面的波次。
|
|
60
|
+
- 用户自定义输入的文本也参与 `in` 匹配。
|
|
61
|
+
- 用户关面板 → 整条流程中止,返回 `cancelled: true` 和已经答到的部分。
|
|
62
|
+
- 每个问题带 `第 N 步 · 短标题` 的进度 header;第二波起的 `detail` 里会列出「目前已确认」的选项。
|
|
63
|
+
- **波内点选项自动跳下一题**(官方卡片行为):一波 N 题只需最后一次提交,所以无依赖的问题尽量放同层。
|
|
64
|
+
- **跨波返回**:第二波起,每个问题的选项末尾会多一项「← 返回上一题」。选了它,当前波作废、退回上一波重问(重问时会提示上次选了什么);第一波没有上一波所以不显示;最多回退 20 次。回退时会清空 skipped 缓存,让原先被跳过的分支按新答案重新判定。
|
|
65
|
+
|
|
66
|
+
### session_list / session_send / session_peek
|
|
67
|
+
|
|
68
|
+
- `session_list`:列会话(标题、id、是否运行、工作区),排除子代理会话和空会话。
|
|
69
|
+
- `session_send`:向目标会话投递消息。返回 `accepted`、`mode`、`depth`。
|
|
70
|
+
- 走 `sessionController.resolveAgent()`(冷会话会被 resume)拿到 agent,再用 `agent.followup()` 投递。
|
|
71
|
+
- 消息 source 是 `plugin:interaction`(不是 `user`),所以客户端把它渲染成**可折叠的通知卡片**(默认分支文案「收到执行请求」),一眼能区分是 AI 发的还是用户本人说的;和 dsh-plugin-memory 的做法一致。
|
|
72
|
+
- `mode: 'queue'`(默认)走 `followup`(下一轮);`mode: 'steer'` 走 `steer`(插进当前回合)。
|
|
73
|
+
- `session_peek`:只读目标会话最近几条消息,会过滤掉 runtime-context / time-context 这类系统注入噪声,跨会话消息标成「跨会话」角色。
|
|
74
|
+
|
|
75
|
+
投递的消息带来源标记,目标会话里看到的是:
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
【跨会话消息 #depth=1 from=session-ab12cd34】
|
|
79
|
+
来自会话「交互增强」
|
|
80
|
+
目标工作区:C:\...
|
|
81
|
+
|
|
82
|
+
(正文)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## 护栏
|
|
86
|
+
|
|
87
|
+
| 闸门 | 默认值 | 说明 |
|
|
88
|
+
|---|---|---|
|
|
89
|
+
| 链路深度 | 3 | 目标会话再往外发会 +1,超过就拒绝,防两个会话无限互叫 |
|
|
90
|
+
| 限频 | 3 条 / 60 秒 / 每对会话 | 防止刷屏和烧 token |
|
|
91
|
+
| 允许跨工作区 | 是 | 用户 2026-11-17 拍板放开,不再限制同 cwd |
|
|
92
|
+
| 整块开关 | 开 | `crossSession.enabled: false` 只关跨会话,`ask_flow` 不受影响 |
|
|
93
|
+
|
|
94
|
+
## 配置
|
|
95
|
+
|
|
96
|
+
`cordis.patch.yml`:
|
|
97
|
+
|
|
98
|
+
```yaml
|
|
99
|
+
- insert:
|
|
100
|
+
- id: interaction
|
|
101
|
+
name: '@local/dsh-interaction'
|
|
102
|
+
config:
|
|
103
|
+
crossSession:
|
|
104
|
+
enabled: true
|
|
105
|
+
maxDepth: 3
|
|
106
|
+
rateLimit: 3
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## 测试
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
node --test test/flow.test.mjs test/interaction.test.mjs
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
纯逻辑(依赖解析、成环检测、波次选择)和工具层(假 ctx 跑 execute、防环、限频)都有覆盖。
|
|
116
|
+
|
|
117
|
+
## 已知限制
|
|
118
|
+
|
|
119
|
+
- 提问翻页时面板会闪一下(官方卡片机制)。
|
|
120
|
+
- 跨波返回要重新选一次上一波的题(官方卡片提交即结束,没法回填旧答案)。
|
|
121
|
+
- legacy 阻塞提问不写进 session projection,聊天记录回看只见工具结果,不见中间卡片。
|
|
122
|
+
- 跨会话会真的让目标会话跑一轮,消耗 token;目标会话正在跑时 queue 模式可能要排队。
|
|
123
|
+
- 跨会话只支持纯文本。
|
|
124
|
+
- 「收到执行请求」这个卡片标题来自官方 locale 的默认分支,插件无法自定义文案。
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# 交互增强:分支提问 + 跨会话消息
|
|
2
|
+
#
|
|
3
|
+
# crossSession.enabled: false 可以整块关掉跨会话工具(ask_flow 不受影响)。
|
|
4
|
+
# crossSession.maxDepth: 跨会话链路最多转几层,防止两个会话无限互叫。
|
|
5
|
+
# crossSession.rateLimit: 同一对会话 60 秒内最多发几条。
|
|
6
|
+
- insert:
|
|
7
|
+
- id: interaction
|
|
8
|
+
name: '@philomelcc/dsh-interaction'
|
|
9
|
+
config:
|
|
10
|
+
crossSession:
|
|
11
|
+
enabled: true
|
|
12
|
+
maxDepth: 3
|
|
13
|
+
rateLimit: 3
|
package/index.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-interaction · 交互增强
|
|
3
|
+
*
|
|
4
|
+
* 两块能力:
|
|
5
|
+
* 1. ask_flow —— 分支式提问:声明一张问题图,按依赖分波提问,选 A 就只问 A 那条线。
|
|
6
|
+
* 2. session_* —— 跨会话消息:列会话、投递消息(会唤醒冷会话)、回读对方回复。
|
|
7
|
+
*
|
|
8
|
+
* Host 半只有工具,没有前端。提问面板复用官方 UI(ctx.userQuestions.ask),
|
|
9
|
+
* 跨会话投递复用官方通道(ctx.sessionController.prompt)。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
defineTool,
|
|
14
|
+
textOutput,
|
|
15
|
+
toLosslessJson,
|
|
16
|
+
} from './lib/tool.js'
|
|
17
|
+
import { normalizeSteps } from './lib/flow.js'
|
|
18
|
+
import { runAskFlow } from './lib/ask.js'
|
|
19
|
+
import { createSessionBridge } from './lib/sessions.js'
|
|
20
|
+
|
|
21
|
+
export const name = 'interaction'
|
|
22
|
+
// 只 inject 一定存在的服务;userQuestions / sessionController / sessionTitle
|
|
23
|
+
// 都是运行时 ctx.get() 取,缺了对应工具给一条明确报错,不影响插件加载。
|
|
24
|
+
export const inject = ['tools']
|
|
25
|
+
|
|
26
|
+
const DEFAULTS = {
|
|
27
|
+
crossSession: {
|
|
28
|
+
enabled: true,
|
|
29
|
+
maxDepth: 3,
|
|
30
|
+
rateLimit: 3,
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 配置容错:cordis.patch.yml 里写错类型不该让插件起不来。 */
|
|
35
|
+
export function normalizeConfig(raw) {
|
|
36
|
+
const input = raw && typeof raw === 'object' ? raw : {}
|
|
37
|
+
const cross = input.crossSession && typeof input.crossSession === 'object' ? input.crossSession : {}
|
|
38
|
+
return {
|
|
39
|
+
crossSession: {
|
|
40
|
+
enabled: cross.enabled === undefined ? DEFAULTS.crossSession.enabled : cross.enabled !== false,
|
|
41
|
+
maxDepth: Number.isFinite(cross.maxDepth) ? cross.maxDepth : DEFAULTS.crossSession.maxDepth,
|
|
42
|
+
rateLimit: Number.isFinite(cross.rateLimit) ? cross.rateLimit : DEFAULTS.crossSession.rateLimit,
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 从 agent 上读会话标题,读不到就给个短 id。 */
|
|
48
|
+
function titleOf(ctx, agent) {
|
|
49
|
+
if (agent === undefined || agent === null) return undefined
|
|
50
|
+
try {
|
|
51
|
+
const titles = ctx.get('sessionTitle')
|
|
52
|
+
const snapshot = titles?.get?.(agent.session)
|
|
53
|
+
if (typeof snapshot?.title === 'string' && snapshot.title.trim()) return snapshot.title.trim()
|
|
54
|
+
} catch {
|
|
55
|
+
// 标题读不到不影响功能
|
|
56
|
+
}
|
|
57
|
+
return undefined
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function apply(ctx, rawConfig = {}) {
|
|
61
|
+
const config = normalizeConfig(rawConfig)
|
|
62
|
+
const log = (message) => {
|
|
63
|
+
try { ctx?.logger?.info?.(`[interaction] ${message}`) } catch { /* logger 不可用就静默 */ }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const bridge = createSessionBridge({ ctx, config: config.crossSession, log })
|
|
67
|
+
|
|
68
|
+
const tools = []
|
|
69
|
+
|
|
70
|
+
// ---------------------------------------------------------------- 分支提问
|
|
71
|
+
|
|
72
|
+
tools.push(defineTool({
|
|
73
|
+
name: 'ask_flow',
|
|
74
|
+
description:
|
|
75
|
+
'分支式提问:一次声明整张问题图,按依赖分波向用户提问——先问第一层,拿到答案后再决定该问哪几道。'
|
|
76
|
+
+ '用户的选择会决定后续问题的走向(例如「选了 A 才问 A 的细节,选了 B 就问 B 的细节」)。'
|
|
77
|
+
+ '当一个问题的后续问题取决于前面怎么答时用它;一批互不相关的独立问题用 ask_user_question 就行。'
|
|
78
|
+
+ '每一步是 ProblemItem:{ id, question, options?, header?, detail?, multi_select?, when? }。'
|
|
79
|
+
+ 'when 用来声明「前面选了某个选项才问这题」,写法 { id: 前一个步骤的id, in: [选项label] },'
|
|
80
|
+
+ '也支持 not_in: [...](选了别的才问)和 answered: true(只要答过就问)。多个条件传数组表示同时满足。'
|
|
81
|
+
+ '同一个 when 依赖的题会在后续波次出现,没有依赖的题会在同一波一起问。'
|
|
82
|
+
+ '【交互要点】一波里有多个问题时,用户点单选题的选项会自动跳到下一题,只有这一波的最后一题才需要点提交;'
|
|
83
|
+
+ '所以凡是互不依赖的问题都放进同一层(别人为串成一条链),用户能少点很多次提交。'
|
|
84
|
+
+ '每一波之间用户看得到进度(第 N 步),但跨波无法回退改答案,所以依赖关系要设计得有必要、别分层太碎。',
|
|
85
|
+
parameters: {
|
|
86
|
+
intro: { type: 'string', description: '第一张卡片顶部的说明,可选;写一句这次要确认什么' },
|
|
87
|
+
steps: {
|
|
88
|
+
type: 'array',
|
|
89
|
+
required: true,
|
|
90
|
+
description: '问题图,按提问顺序排列(最多 20 个);有依赖的题会自动排到后面的波次',
|
|
91
|
+
items: {
|
|
92
|
+
type: 'object',
|
|
93
|
+
additionalProperties: true,
|
|
94
|
+
properties: {
|
|
95
|
+
id: { type: 'string', required: true, description: '稳定 id,答案按它回传,when 也引用它' },
|
|
96
|
+
question: { type: 'string', required: true, description: '要问用户的问题' },
|
|
97
|
+
header: { type: 'string', description: '短标题,会显示成「第 N 步 · 短标题」' },
|
|
98
|
+
detail: { type: 'string', description: '补充说明(markdown),渲染在问题下方' },
|
|
99
|
+
options: {
|
|
100
|
+
type: 'array',
|
|
101
|
+
description: '选项;留空则让用户自由输入',
|
|
102
|
+
items: {
|
|
103
|
+
type: 'object',
|
|
104
|
+
additionalProperties: true,
|
|
105
|
+
properties: {
|
|
106
|
+
label: { type: 'string', required: true, description: '选项文本,when.in 要精确匹配它' },
|
|
107
|
+
description: { type: 'string', description: '一句话说明这个选项的后果或取舍' },
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
multi_select: { type: 'boolean', description: '是否允许多选,默认否' },
|
|
112
|
+
when: {
|
|
113
|
+
type: 'object',
|
|
114
|
+
additionalProperties: true,
|
|
115
|
+
description: "依赖条件,如 { id: 'deploy', in: ['A 本地部署'] };满足才问这道题",
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
output: textOutput({
|
|
122
|
+
answers: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
123
|
+
skipped: { type: 'array', items: { type: 'string' } },
|
|
124
|
+
waves: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
125
|
+
cancelled: { type: 'boolean' },
|
|
126
|
+
}),
|
|
127
|
+
async execute(args, exec) {
|
|
128
|
+
const userQuestions = ctx.get('userQuestions')
|
|
129
|
+
if (userQuestions === undefined) {
|
|
130
|
+
throw new Error('当前部署没有 userQuestions 服务,没有可用的提问界面')
|
|
131
|
+
}
|
|
132
|
+
const steps = normalizeSteps(args.steps)
|
|
133
|
+
const result = await runAskFlow({
|
|
134
|
+
userQuestions,
|
|
135
|
+
agent: exec?.agent,
|
|
136
|
+
signal: exec?.signal,
|
|
137
|
+
steps,
|
|
138
|
+
intro: typeof args.intro === 'string' ? args.intro.trim() : undefined,
|
|
139
|
+
log,
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
const answered = result.answers.length
|
|
143
|
+
const lines = result.answers.map((item) => {
|
|
144
|
+
const picked = item.selected.length > 0 ? item.selected.join('、') : ''
|
|
145
|
+
const custom = item.custom ? `${picked ? ' + ' : ''}${item.custom}` : ''
|
|
146
|
+
return `- ${item.question} → ${picked}${custom}`
|
|
147
|
+
})
|
|
148
|
+
const waveCount = result.waves.length
|
|
149
|
+
let text
|
|
150
|
+
if (result.cancelled) {
|
|
151
|
+
text = `提问中途被打断(可能是关掉了面板),已收到 ${answered} 个回答${answered > 0 ? `:\n${lines.join('\n')}` : '。'}`
|
|
152
|
+
} else if (answered === 0) {
|
|
153
|
+
text = '没有问到任何问题(所有步骤的条件都不成立)。'
|
|
154
|
+
} else {
|
|
155
|
+
text = `已收到 ${answered} 个回答(分 ${waveCount} 波提问):\n${lines.join('\n')}`
|
|
156
|
+
}
|
|
157
|
+
if (result.skipped.length > 0) {
|
|
158
|
+
const byId = new Map(steps.map((step) => [step.id, step]))
|
|
159
|
+
const skippedText = result.skipped.map((id) => byId.get(id)?.question ?? id).join('、')
|
|
160
|
+
text += `\n\n因不满足条件而跳过:${skippedText}`
|
|
161
|
+
}
|
|
162
|
+
if (result.backs > 0) text += `\n\n(中途回退了 ${result.backs} 次)`
|
|
163
|
+
return toLosslessJson({
|
|
164
|
+
text,
|
|
165
|
+
answers: result.answers,
|
|
166
|
+
skipped: result.skipped,
|
|
167
|
+
waves: result.waves,
|
|
168
|
+
cancelled: result.cancelled,
|
|
169
|
+
})
|
|
170
|
+
},
|
|
171
|
+
}))
|
|
172
|
+
|
|
173
|
+
// ---------------------------------------------------------------- 跨会话
|
|
174
|
+
|
|
175
|
+
if (config.crossSession.enabled) {
|
|
176
|
+
tools.push(defineTool({
|
|
177
|
+
name: 'session_list',
|
|
178
|
+
description:
|
|
179
|
+
'列出本机其他会话(标题、id、是否正在跑、工作区)。要给另一个会话发消息前先用它查准 session_id。'
|
|
180
|
+
+ '不包含子代理会话和空会话。',
|
|
181
|
+
parameters: {
|
|
182
|
+
query: { type: 'string', description: '关键词,匹配标题 / 工作区路径 / id,可省略' },
|
|
183
|
+
limit: { type: 'integer', description: '最多返回多少条,默认 20,上限 100' },
|
|
184
|
+
},
|
|
185
|
+
output: textOutput({
|
|
186
|
+
sessions: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
187
|
+
total: { type: 'integer' },
|
|
188
|
+
}),
|
|
189
|
+
async execute(args, exec) {
|
|
190
|
+
const selfId = exec?.agent?.id
|
|
191
|
+
const { sessions, total } = await bridge.listSessions({
|
|
192
|
+
query: args.query,
|
|
193
|
+
limit: args.limit,
|
|
194
|
+
signal: exec?.signal,
|
|
195
|
+
excludeSelf: true,
|
|
196
|
+
selfId: selfId === undefined ? undefined : String(selfId),
|
|
197
|
+
})
|
|
198
|
+
const lines = sessions.map((row) => {
|
|
199
|
+
const running = row.running ? ' · 正在运行' : ''
|
|
200
|
+
const cwd = row.cwd ? ` · ${row.cwd}` : ''
|
|
201
|
+
return `- ${row.title} [${row.sessionId}]${running}${cwd}`
|
|
202
|
+
})
|
|
203
|
+
return toLosslessJson({
|
|
204
|
+
text: sessions.length === 0
|
|
205
|
+
? '没有找到符合条件的会话。'
|
|
206
|
+
: `找到 ${sessions.length} 个会话(共 ${total} 个):\n${lines.join('\n')}`,
|
|
207
|
+
sessions,
|
|
208
|
+
total,
|
|
209
|
+
})
|
|
210
|
+
},
|
|
211
|
+
}))
|
|
212
|
+
|
|
213
|
+
tools.push(defineTool({
|
|
214
|
+
name: 'session_send',
|
|
215
|
+
description:
|
|
216
|
+
'向另一个会话主动发一条消息并唤醒它(它冷着会自动恢复,正在跑就排进它的队列)。'
|
|
217
|
+
+ '这就是跨会话唤醒:另一个会话会像收到用户消息一样开始干活。'
|
|
218
|
+
+ '对方看不到本会话的上下文,所以消息里要写清楚你是谁、要它做什么、需要它回什么。'
|
|
219
|
+
+ '默认 mode=queue(等它当前回合跑完再处理),mode=steer 会插进它当前回合——除非用户明确要求打断,否则别用 steer。'
|
|
220
|
+
+ '发完可以用 session_peek 看它回了什么。探测到会话之间互相来回超过 3 层会被拒绝,别自己跟自己绕圈。',
|
|
221
|
+
parameters: {
|
|
222
|
+
session_id: { type: 'string', required: true, description: '目标会话 id,从 session_list 拿' },
|
|
223
|
+
text: { type: 'string', required: true, description: '消息正文,写给对方会话看的' },
|
|
224
|
+
mode: { type: 'string', description: "queue(默认,排队)或 steer(打断当前回合)" },
|
|
225
|
+
},
|
|
226
|
+
output: textOutput({
|
|
227
|
+
accepted: { type: 'boolean' },
|
|
228
|
+
sessionId: { type: 'string' },
|
|
229
|
+
mode: { type: 'string' },
|
|
230
|
+
depth: { type: 'integer' },
|
|
231
|
+
}),
|
|
232
|
+
async execute(args, exec) {
|
|
233
|
+
const agent = exec?.agent
|
|
234
|
+
const result = await bridge.sendMessage({
|
|
235
|
+
fromAgent: agent,
|
|
236
|
+
fromTitle: titleOf(ctx, agent),
|
|
237
|
+
sessionId: args.session_id,
|
|
238
|
+
text: args.text,
|
|
239
|
+
mode: args.mode,
|
|
240
|
+
signal: exec?.signal,
|
|
241
|
+
})
|
|
242
|
+
const modeText = result.mode === 'steer' ? '已插进它的当前回合' : '已排进它的队列'
|
|
243
|
+
return toLosslessJson({
|
|
244
|
+
text: `已投递给「${result.title}」(${result.sessionId}),${modeText}。链路深度 ${result.depth}。`
|
|
245
|
+
+ `想看它回了什么就用 session_peek。`,
|
|
246
|
+
...result,
|
|
247
|
+
})
|
|
248
|
+
},
|
|
249
|
+
}))
|
|
250
|
+
|
|
251
|
+
tools.push(defineTool({
|
|
252
|
+
name: 'session_peek',
|
|
253
|
+
description:
|
|
254
|
+
'读另一个会话最近几条用户/助手消息,用来确认跨会话消息发出去之后对方回了什么。'
|
|
255
|
+
+ '只读,不会唤醒对方,也不改动它的内容。',
|
|
256
|
+
parameters: {
|
|
257
|
+
session_id: { type: 'string', required: true, description: '目标会话 id' },
|
|
258
|
+
limit: { type: 'integer', description: '最多读几条消息,默认 6,上限 30' },
|
|
259
|
+
},
|
|
260
|
+
output: textOutput({
|
|
261
|
+
messages: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
262
|
+
}),
|
|
263
|
+
async execute(args, exec) {
|
|
264
|
+
const { messages } = await bridge.peekSession({
|
|
265
|
+
sessionId: args.session_id,
|
|
266
|
+
limit: args.limit,
|
|
267
|
+
signal: exec?.signal,
|
|
268
|
+
})
|
|
269
|
+
const lines = messages.map((message) => {
|
|
270
|
+
const when = message.at ? new Date(message.at).toISOString().slice(11, 19) : ''
|
|
271
|
+
return `[${message.role}${when ? ` ${when}` : ''}] ${message.text}`
|
|
272
|
+
})
|
|
273
|
+
return toLosslessJson({
|
|
274
|
+
text: messages.length === 0
|
|
275
|
+
? '这个会话里没读到用户/助手消息。'
|
|
276
|
+
: `最近 ${messages.length} 条:\n${lines.join('\n\n')}`,
|
|
277
|
+
messages,
|
|
278
|
+
})
|
|
279
|
+
},
|
|
280
|
+
}))
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const disposers = tools.map((tool) => ctx.tools.register(tool))
|
|
284
|
+
ctx.effect(() => () => {
|
|
285
|
+
for (const dispose of disposers) {
|
|
286
|
+
try { dispose?.() } catch { /* 卸载阶段吞掉 */ }
|
|
287
|
+
}
|
|
288
|
+
}, 'interaction: tools')
|
|
289
|
+
}
|
package/lib/ask.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 分支提问的编排层:把「波次」交给官方 ctx.userQuestions.ask(),逐波收答案。
|
|
3
|
+
*
|
|
4
|
+
* 为什么走官方 ask:
|
|
5
|
+
* - 卡片样式、多选、自定义输入、键盘操作全部直接用官方 UI,零前端代码;
|
|
6
|
+
* - 只依赖 ctx.userQuestions.ask 这个稳定服务方法,DSH 升级不易坏。
|
|
7
|
+
*
|
|
8
|
+
* 跨波返回:官方卡片提交即结束,没法回退到上一波。这里用「往选项里加一个
|
|
9
|
+
* 返回项」的办法补:用户选了它,当前波作废、退回上一波重问。第一波没有上一波,
|
|
10
|
+
* 所以不显示返回项;另有次数上限防止来回刷。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { createFlowState, recordAnswer, selectWave } from './flow.js'
|
|
14
|
+
|
|
15
|
+
/** 返回上一波的哨兵选项文案。用户可见,所以写成正常人话。 */
|
|
16
|
+
export const BACK_LABEL = '← 返回上一题'
|
|
17
|
+
|
|
18
|
+
/** 同一轮里最多允许回退几次(防死循环)。 */
|
|
19
|
+
export const MAX_BACKS = 20
|
|
20
|
+
|
|
21
|
+
/** 用户关掉了提问面板(或被中止):不是错误,是「不想继续」。 */
|
|
22
|
+
export function isCancellation(error) {
|
|
23
|
+
const code = error?.code
|
|
24
|
+
return code === 'NO_PROVIDER' || code === 'ASK_ABORTED' || code === 'ASK_TIMED_OUT'
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 已答问题的前情摘要,放问题的 detail 里(官方会渲染成 markdown)。 */
|
|
28
|
+
function contextLines(steps, state) {
|
|
29
|
+
const lines = []
|
|
30
|
+
for (const step of steps) {
|
|
31
|
+
const entry = state.answers.get(step.id)
|
|
32
|
+
if (entry === undefined) continue
|
|
33
|
+
const picked = entry.selected.length > 0 ? entry.selected.join('、') : ''
|
|
34
|
+
const custom = entry.custom ? `${picked ? ' + ' : ''}${entry.custom}` : ''
|
|
35
|
+
if (picked || custom) lines.push(`- **${step.question}** → ${picked}${custom}`)
|
|
36
|
+
}
|
|
37
|
+
return lines
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 回退后重问时,把上一轮的选择提示出来,免得用户以为答案丢了。 */
|
|
41
|
+
function backHintLine(step, backHints) {
|
|
42
|
+
const old = backHints?.get(step.id)
|
|
43
|
+
if (old === undefined) return undefined
|
|
44
|
+
const picked = old.selected.filter((label) => label !== BACK_LABEL).join('、')
|
|
45
|
+
const text = picked || old.custom
|
|
46
|
+
if (!text) return undefined
|
|
47
|
+
return `> 上次你选的是「${text}」,重新选一次即可修改。`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 组装一次 ask 的单个问题条目。 */
|
|
51
|
+
function buildQuestion(step, waveIndex, steps, state, intro, canGoBack, backHints) {
|
|
52
|
+
const headerBits = [`第 ${waveIndex} 步`]
|
|
53
|
+
if (step.header) headerBits.push(step.header)
|
|
54
|
+
|
|
55
|
+
const detailParts = []
|
|
56
|
+
if (waveIndex === 1 && intro) detailParts.push(intro)
|
|
57
|
+
if (waveIndex > 1) {
|
|
58
|
+
const lines = contextLines(steps, state)
|
|
59
|
+
if (lines.length > 0) detailParts.push(['**目前已确认:**', ...lines].join('\n'))
|
|
60
|
+
}
|
|
61
|
+
const hint = backHintLine(step, backHints)
|
|
62
|
+
if (hint !== undefined) detailParts.push(hint)
|
|
63
|
+
if (step.detail) detailParts.push(step.detail)
|
|
64
|
+
|
|
65
|
+
const item = {
|
|
66
|
+
id: step.id,
|
|
67
|
+
question: step.question,
|
|
68
|
+
header: headerBits.join(' · '),
|
|
69
|
+
}
|
|
70
|
+
const options = step.options === undefined ? [] : [...step.options]
|
|
71
|
+
if (canGoBack) {
|
|
72
|
+
options.push({ label: BACK_LABEL, description: '回到上一波重新回答(当前这波的选择会作废)' })
|
|
73
|
+
}
|
|
74
|
+
if (options.length > 0) item.options = options
|
|
75
|
+
if (step.multiSelect) item.multiSelect = true
|
|
76
|
+
if (detailParts.length > 0) item.detail = detailParts.join('\n\n')
|
|
77
|
+
return item
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 要求稳定的一波:条件判否的步骤会被标成跳过,跳过之后可能又有关键依赖变得可判定。 */
|
|
81
|
+
function stableWave(steps, state) {
|
|
82
|
+
let selection = selectWave(steps, state)
|
|
83
|
+
while (selection.wave.length === 0 && selection.changed) {
|
|
84
|
+
selection = selectWave(steps, state)
|
|
85
|
+
}
|
|
86
|
+
return selection
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 跑完一张问题图。
|
|
91
|
+
*
|
|
92
|
+
* @param {object} options
|
|
93
|
+
* @param {object} options.userQuestions - ctx.userQuestions 服务。
|
|
94
|
+
* @param {object} [options.agent] - 调用者 agent(live root 才有资格提问)。
|
|
95
|
+
* @param {AbortSignal} [options.signal] - 工具调用的取消信号。
|
|
96
|
+
* @param {Array} options.steps - normalizeSteps 的结果。
|
|
97
|
+
* @param {string} [options.intro] - 第一张卡片的顶部说明。
|
|
98
|
+
* @param {(message: string) => void} [options.log] - 诊断日志。
|
|
99
|
+
* @returns {Promise<{answers: Array, skipped: string[], waves: Array, cancelled: boolean, backs: number}>}
|
|
100
|
+
*/
|
|
101
|
+
export async function runAskFlow({ userQuestions, agent, signal, steps, intro, log }) {
|
|
102
|
+
const state = createFlowState()
|
|
103
|
+
/** 已完成的波次栈:回退就是弹它。 */
|
|
104
|
+
const history = []
|
|
105
|
+
/** 回退后暂存的旧答案,只用于给用户提示,不参与条件判定。 */
|
|
106
|
+
const backHints = new Map()
|
|
107
|
+
let backs = 0
|
|
108
|
+
|
|
109
|
+
for (;;) {
|
|
110
|
+
const selection = stableWave(steps, state)
|
|
111
|
+
if (selection.wave.length === 0) break
|
|
112
|
+
|
|
113
|
+
const waveIndex = history.length + 1
|
|
114
|
+
const canGoBack = history.length > 0 && backs < MAX_BACKS
|
|
115
|
+
const questions = selection.wave.map(
|
|
116
|
+
(step) => buildQuestion(step, waveIndex, steps, state, intro, canGoBack, backHints),
|
|
117
|
+
)
|
|
118
|
+
log?.(`第 ${waveIndex} 波:${selection.wave.map((step) => step.id).join(', ')}`)
|
|
119
|
+
|
|
120
|
+
let answer
|
|
121
|
+
try {
|
|
122
|
+
answer = await userQuestions.ask({
|
|
123
|
+
questions,
|
|
124
|
+
...(agent === undefined ? {} : { agent }),
|
|
125
|
+
...(signal === undefined ? {} : { signal }),
|
|
126
|
+
})
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (isCancellation(error)) {
|
|
129
|
+
return {
|
|
130
|
+
answers: snapshotAnswers(steps, state),
|
|
131
|
+
skipped: [...state.skipped],
|
|
132
|
+
waves: history.map((entry, index) => ({ index: index + 1, ids: entry.ids })),
|
|
133
|
+
cancelled: true,
|
|
134
|
+
backs,
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
throw error
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const wantsBack = backs < MAX_BACKS
|
|
141
|
+
&& history.length > 0
|
|
142
|
+
&& (answer?.answers ?? []).some(
|
|
143
|
+
(item) => Array.isArray(item?.selected) && item.selected.includes(BACK_LABEL),
|
|
144
|
+
)
|
|
145
|
+
if (wantsBack) {
|
|
146
|
+
backs += 1
|
|
147
|
+
const previous = history.pop()
|
|
148
|
+
for (const id of previous.ids) {
|
|
149
|
+
const old = state.answers.get(id)
|
|
150
|
+
state.answers.delete(id)
|
|
151
|
+
if (old !== undefined) backHints.set(id, old)
|
|
152
|
+
}
|
|
153
|
+
// skipped 是由「条件不成立」派生出来的缓存。回退改了前面的答案之后,
|
|
154
|
+
// 原来被跳过的分支可能重新成立,必须清掉重新判定,否则会永久漏问。
|
|
155
|
+
state.skipped.clear()
|
|
156
|
+
log?.(`用户要求返回上一波(第 ${previous.ids.join(', ')} 题)`)
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
for (const item of answer?.answers ?? []) {
|
|
161
|
+
const step = selection.wave.find((candidate) => candidate.id === item?.id)
|
|
162
|
+
if (step !== undefined) {
|
|
163
|
+
// 返回哨兵永远不该落进最终答案:它只是一个导航动作。
|
|
164
|
+
recordAnswer(state, step.id, {
|
|
165
|
+
selected: (Array.isArray(item?.selected) ? item.selected : []).filter((label) => label !== BACK_LABEL),
|
|
166
|
+
...(item?.custom === undefined ? {} : { custom: item.custom }),
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// 官方承诺一道题一个答案;万一某个没回来,也记成「空答案」避免死循环。
|
|
171
|
+
for (const step of selection.wave) {
|
|
172
|
+
if (!state.answers.has(step.id)) recordAnswer(state, step.id, { selected: [] })
|
|
173
|
+
}
|
|
174
|
+
for (const step of selection.wave) backHints.delete(step.id)
|
|
175
|
+
|
|
176
|
+
history.push({
|
|
177
|
+
ids: selection.wave.map((step) => step.id),
|
|
178
|
+
answers: new Map(selection.wave.map((step) => [step.id, state.answers.get(step.id)])),
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
answers: snapshotAnswers(steps, state),
|
|
184
|
+
skipped: [...state.skipped],
|
|
185
|
+
waves: history.map((entry, index) => ({ index: index + 1, ids: entry.ids })),
|
|
186
|
+
cancelled: false,
|
|
187
|
+
backs,
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 把内部状态摊平成工具输出。 */
|
|
192
|
+
function snapshotAnswers(steps, state) {
|
|
193
|
+
const out = []
|
|
194
|
+
for (const step of steps) {
|
|
195
|
+
const entry = state.answers.get(step.id)
|
|
196
|
+
if (entry === undefined) continue
|
|
197
|
+
out.push({
|
|
198
|
+
id: step.id,
|
|
199
|
+
question: step.question,
|
|
200
|
+
selected: [...entry.selected],
|
|
201
|
+
...(entry.custom === undefined ? {} : { custom: entry.custom }),
|
|
202
|
+
})
|
|
203
|
+
}
|
|
204
|
+
return out
|
|
205
|
+
}
|
package/lib/flow.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 分支提问的纯逻辑层:条件解析、依赖成环检测、波次选择。
|
|
3
|
+
*
|
|
4
|
+
* 这一层不碰任何 DSH 服务,全部可单测。ask.js 只负责把选出来的波次
|
|
5
|
+
* 交给 ctx.userQuestions.ask()。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** 一条条件规则:某个问题的答案是否命中一组取值。 */
|
|
9
|
+
export const RULE_MODES = ['in', 'not_in', 'answered']
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 把一个 when 声明摊平成规则数组(多个条件之间是 AND)。
|
|
13
|
+
*
|
|
14
|
+
* 支持的写法:
|
|
15
|
+
* { id: 'q1', in: ['A'] }
|
|
16
|
+
* { id: 'q1', not_in: ['A'] }
|
|
17
|
+
* { id: 'q1', answered: true }
|
|
18
|
+
* [ { id: 'q1', in: ['A'] }, { id: 'q2', in: ['B'] } ] // AND
|
|
19
|
+
*/
|
|
20
|
+
export function normalizeWhen(when) {
|
|
21
|
+
if (when === undefined || when === null) return []
|
|
22
|
+
if (Array.isArray(when)) return when.flatMap((item) => normalizeWhen(item))
|
|
23
|
+
if (typeof when !== 'object') return []
|
|
24
|
+
const id = typeof when.id === 'string' ? when.id.trim() : ''
|
|
25
|
+
if (!id) return []
|
|
26
|
+
if (Array.isArray(when.in)) return [{ id, mode: 'in', values: when.in.map((value) => String(value)) }]
|
|
27
|
+
if (Array.isArray(when.not_in)) return [{ id, mode: 'not_in', values: when.not_in.map((value) => String(value)) }]
|
|
28
|
+
if (when.answered === true) return [{ id, mode: 'answered', values: [] }]
|
|
29
|
+
if (when.answered === false) return [{ id, mode: 'in', values: [] }]
|
|
30
|
+
return []
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 校验并规范化 steps。
|
|
35
|
+
* @param {unknown} raw - 模型传进来的 steps 参数。
|
|
36
|
+
* @returns {Array<{id: string, question: string, header?: string, detail?: string, options?: Array<{label: string, description?: string}>, multiSelect?: boolean, rules: Array}>}
|
|
37
|
+
* @throws {Error} 参数不合法时抛出带中文原因的错误。
|
|
38
|
+
*/
|
|
39
|
+
export function normalizeSteps(raw) {
|
|
40
|
+
if (!Array.isArray(raw) || raw.length === 0) throw new Error('steps 不能为空,至少给一个问题')
|
|
41
|
+
if (raw.length > 20) throw new Error(`steps 最多 20 个问题,收到 ${raw.length} 个`)
|
|
42
|
+
|
|
43
|
+
const steps = raw.map((item, index) => {
|
|
44
|
+
if (item === null || typeof item !== 'object') throw new Error(`steps[${index}] 不是对象`)
|
|
45
|
+
const id = typeof item.id === 'string' ? item.id.trim() : ''
|
|
46
|
+
if (!id) throw new Error(`steps[${index}] 缺少 id`)
|
|
47
|
+
const question = typeof item.question === 'string' ? item.question.trim() : ''
|
|
48
|
+
if (!question) throw new Error(`步骤 "${id}" 缺少 question`)
|
|
49
|
+
|
|
50
|
+
let options
|
|
51
|
+
if (Array.isArray(item.options)) {
|
|
52
|
+
if (item.options.length > 12) throw new Error(`步骤 "${id}" 的 options 最多 12 个`)
|
|
53
|
+
options = item.options.map((option, optionIndex) => {
|
|
54
|
+
const label = typeof option?.label === 'string' ? option.label.trim() : ''
|
|
55
|
+
if (!label) throw new Error(`步骤 "${id}" 的 options[${optionIndex}] 缺少 label`)
|
|
56
|
+
const view = { label }
|
|
57
|
+
if (typeof option.description === 'string' && option.description.trim()) {
|
|
58
|
+
view.description = option.description.trim()
|
|
59
|
+
}
|
|
60
|
+
return view
|
|
61
|
+
})
|
|
62
|
+
if (options.length === 0) options = undefined
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const step = {
|
|
66
|
+
id,
|
|
67
|
+
question,
|
|
68
|
+
rules: normalizeWhen(item.when),
|
|
69
|
+
}
|
|
70
|
+
if (typeof item.header === 'string' && item.header.trim()) step.header = item.header.trim()
|
|
71
|
+
if (typeof item.detail === 'string' && item.detail.trim()) step.detail = item.detail.trim()
|
|
72
|
+
if (options !== undefined) step.options = options
|
|
73
|
+
if (item.multi_select === true) step.multiSelect = true
|
|
74
|
+
return step
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
const byId = new Map()
|
|
78
|
+
for (const step of steps) {
|
|
79
|
+
if (byId.has(step.id)) throw new Error(`步骤 id 重复:"${step.id}"`)
|
|
80
|
+
byId.set(step.id, step)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
for (const step of steps) {
|
|
84
|
+
for (const rule of step.rules) {
|
|
85
|
+
if (rule.id === step.id) throw new Error(`步骤 "${step.id}" 不能依赖自己`)
|
|
86
|
+
if (!byId.has(rule.id)) throw new Error(`步骤 "${step.id}" 的 when 引用了不存在的步骤 "${rule.id}"`)
|
|
87
|
+
// 不能既依赖又要求条件永不成立(无意义的空 in)
|
|
88
|
+
if (rule.mode === 'in' && rule.values.length === 0) {
|
|
89
|
+
throw new Error(`步骤 "${step.id}" 的 when.in 是空数组,这个条件永远不会成立`)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
assertAcyclic(steps)
|
|
95
|
+
return steps
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** DFS 检测依赖环,顺便保证依赖链不会无限深。 */
|
|
99
|
+
function assertAcyclic(steps) {
|
|
100
|
+
const refs = new Map(steps.map((step) => [step.id, step.rules.map((rule) => rule.id)]))
|
|
101
|
+
const visiting = new Set()
|
|
102
|
+
const done = new Set()
|
|
103
|
+
|
|
104
|
+
const visit = (id, path) => {
|
|
105
|
+
if (done.has(id)) return
|
|
106
|
+
if (visiting.has(id)) {
|
|
107
|
+
throw new Error(`步骤依赖成环:${[...path, id].join(' → ')}`)
|
|
108
|
+
}
|
|
109
|
+
visiting.add(id)
|
|
110
|
+
for (const ref of refs.get(id) ?? []) {
|
|
111
|
+
if (refs.has(ref)) visit(ref, [...path, id])
|
|
112
|
+
}
|
|
113
|
+
visiting.delete(id)
|
|
114
|
+
done.add(id)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
for (const step of steps) visit(step.id, [])
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 一条规则在给定状态下的判定结果:true / false / 'pending'(依赖还没答案)。 */
|
|
121
|
+
function evaluateRule(rule, state) {
|
|
122
|
+
const known = state.answers.has(rule.id) || state.skipped.has(rule.id)
|
|
123
|
+
if (!known) return 'pending'
|
|
124
|
+
// 依赖的问题被跳过了,依赖它的分支也就不成立。
|
|
125
|
+
if (state.skipped.has(rule.id)) return false
|
|
126
|
+
const entry = state.answers.get(rule.id)
|
|
127
|
+
const picked = entry?.selected ?? []
|
|
128
|
+
const custom = entry?.custom
|
|
129
|
+
const hits = rule.values.some((value) => picked.includes(value) || (custom !== undefined && custom === value))
|
|
130
|
+
if (rule.mode === 'in') return hits
|
|
131
|
+
if (rule.mode === 'not_in') return !hits
|
|
132
|
+
return true
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 判定一个步骤的 when 条件。
|
|
137
|
+
* @returns {true | false | 'pending'}
|
|
138
|
+
*/
|
|
139
|
+
export function evaluateWhen(rules, state) {
|
|
140
|
+
if (!rules || rules.length === 0) return true
|
|
141
|
+
let pending = false
|
|
142
|
+
for (const rule of rules) {
|
|
143
|
+
const verdict = evaluateRule(rule, state)
|
|
144
|
+
if (verdict === false) return false
|
|
145
|
+
if (verdict === 'pending') pending = true
|
|
146
|
+
}
|
|
147
|
+
return pending ? 'pending' : true
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 新建一份流程状态。 */
|
|
151
|
+
export function createFlowState() {
|
|
152
|
+
return {
|
|
153
|
+
answers: new Map(),
|
|
154
|
+
skipped: new Set(),
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 选出当前能问的一波问题。
|
|
160
|
+
*
|
|
161
|
+
* 能进同一波的条件:自身没答没跳过,且所有前置依赖都已定(有答案或已跳过)。
|
|
162
|
+
* 条件判否的步骤会被就地标成 skipped(永久跳过)。
|
|
163
|
+
*
|
|
164
|
+
* @param {Array} steps - normalizeSteps 的结果。
|
|
165
|
+
* @param {{answers: Map, skipped: Set}} state - 会被就地修改。
|
|
166
|
+
* @returns {{wave: Array, changed: boolean, remaining: number}}
|
|
167
|
+
*/
|
|
168
|
+
export function selectWave(steps, state) {
|
|
169
|
+
const wave = []
|
|
170
|
+
let changed = false
|
|
171
|
+
for (const step of steps) {
|
|
172
|
+
if (state.answers.has(step.id) || state.skipped.has(step.id)) continue
|
|
173
|
+
const verdict = evaluateWhen(step.rules, state)
|
|
174
|
+
if (verdict === true) wave.push(step)
|
|
175
|
+
else if (verdict === false) {
|
|
176
|
+
state.skipped.add(step.id)
|
|
177
|
+
changed = true
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const remaining = steps.filter((step) => !state.answers.has(step.id) && !state.skipped.has(step.id)).length
|
|
181
|
+
return { wave, changed, remaining }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 把答案条目记进状态。 */
|
|
185
|
+
export function recordAnswer(state, id, entry) {
|
|
186
|
+
state.answers.set(id, {
|
|
187
|
+
selected: Array.isArray(entry?.selected) ? entry.selected.map((value) => String(value)) : [],
|
|
188
|
+
...(typeof entry?.custom === 'string' && entry.custom.trim() ? { custom: entry.custom.trim() } : {}),
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 给模型看的答案摘要行。 */
|
|
193
|
+
export function summarizeAnswers(steps, state) {
|
|
194
|
+
const lines = []
|
|
195
|
+
for (const step of steps) {
|
|
196
|
+
const entry = state.answers.get(step.id)
|
|
197
|
+
if (entry === undefined) continue
|
|
198
|
+
const picked = entry.selected.length > 0 ? entry.selected.join('、') : ''
|
|
199
|
+
const custom = entry.custom ? `${picked ? ';' : ''}自定义:${entry.custom}` : ''
|
|
200
|
+
lines.push(`- ${step.question} → ${picked}${custom}`.trim())
|
|
201
|
+
}
|
|
202
|
+
return lines
|
|
203
|
+
}
|
package/lib/sessions.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 跨会话消息:列表、投递、回读,外加防环与限频。
|
|
3
|
+
*
|
|
4
|
+
* 官方通道:ctx.sessionController.prompt() —— 它会 resolveAgent,目标会话冷着
|
|
5
|
+
* 就自动 resume 再把消息投进 inbox。我们只负责「谁能发、发给谁、发什么」。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
|
|
10
|
+
/** 跨会话消息的标记行,插件靠它认出「这条是别的会话发来的」并算链路深度。 */
|
|
11
|
+
export const CROSS_SESSION_MARK = /^【跨会话消息 #depth=(\d+) from=([^】\s]+)】/
|
|
12
|
+
|
|
13
|
+
const DEFAULT_MAX_DEPTH = 3
|
|
14
|
+
const DEFAULT_RATE_LIMIT = 3
|
|
15
|
+
const RATE_WINDOW_MS = 60_000
|
|
16
|
+
|
|
17
|
+
/** 会话桥:一次插件生命周期内复用,内存状态(重启清零,正好不误伤)。 */
|
|
18
|
+
export function createSessionBridge({ ctx, config = {}, log }) {
|
|
19
|
+
const maxDepth = Number.isFinite(config.maxDepth) ? Math.max(1, Math.trunc(config.maxDepth)) : DEFAULT_MAX_DEPTH
|
|
20
|
+
const rateLimit = Number.isFinite(config.rateLimit) ? Math.max(1, Math.trunc(config.rateLimit)) : DEFAULT_RATE_LIMIT
|
|
21
|
+
/** `${from}>${to}` → 最近一次发送时间戳数组。 */
|
|
22
|
+
const sentAt = new Map()
|
|
23
|
+
|
|
24
|
+
const controller = () => ctx.get('sessionController')
|
|
25
|
+
|
|
26
|
+
function requireController() {
|
|
27
|
+
const service = controller()
|
|
28
|
+
if (service === undefined) {
|
|
29
|
+
throw new Error('当前部署没有 sessionController(跨会话功能需要 web/desktop 装配),无法发送')
|
|
30
|
+
}
|
|
31
|
+
return service
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 读会话列表(读不到标题不要紧,至少给 id)。 */
|
|
35
|
+
async function listSessions({ query = '', limit = 20, signal, excludeSelf = false, selfId } = {}) {
|
|
36
|
+
const service = requireController()
|
|
37
|
+
const value = await service.list({}, signal)
|
|
38
|
+
const items = Array.isArray(value?.items) ? value.items : []
|
|
39
|
+
const keyword = String(query || '').trim().toLowerCase()
|
|
40
|
+
|
|
41
|
+
const rows = []
|
|
42
|
+
for (const item of items) {
|
|
43
|
+
if (item === null || typeof item !== 'object') continue
|
|
44
|
+
if (item.origin === 'subagent') continue
|
|
45
|
+
if (item.blank === true) continue
|
|
46
|
+
if (excludeSelf && selfId !== undefined && item.sessionId === selfId) continue
|
|
47
|
+
const title = item.projections?.values?.title ?? null
|
|
48
|
+
const row = {
|
|
49
|
+
sessionId: String(item.sessionId),
|
|
50
|
+
title: typeof title === 'string' && title.trim() ? title.trim() : '(无标题)',
|
|
51
|
+
running: item.running === true,
|
|
52
|
+
agentAvailable: item.agentAvailable === true,
|
|
53
|
+
cwd: typeof item.cwd === 'string' ? item.cwd : undefined,
|
|
54
|
+
updatedAt: Number.isFinite(item.updatedAt) ? item.updatedAt : undefined,
|
|
55
|
+
}
|
|
56
|
+
if (keyword) {
|
|
57
|
+
const haystack = `${row.title} ${row.sessionId} ${row.cwd ?? ''}`.toLowerCase()
|
|
58
|
+
if (!haystack.includes(keyword)) continue
|
|
59
|
+
}
|
|
60
|
+
rows.push(row)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
rows.sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0))
|
|
64
|
+
const capped = rows.slice(0, Math.max(1, Math.min(Number(limit) || 20, 100)))
|
|
65
|
+
return { sessions: capped, total: rows.length }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 目标会话是否存在(不激活它,只读列表)。 */
|
|
69
|
+
async function findSession(sessionId, signal) {
|
|
70
|
+
const { sessions } = await listSessions({ limit: 100, signal })
|
|
71
|
+
return sessions.find((row) => row.sessionId === sessionId)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 从当前会话最近的历史里找「别的会话发来的跨会话消息」,据此算链路深度。
|
|
76
|
+
* 找不到就是 0(本次是新一轮跨会话对话)。
|
|
77
|
+
*/
|
|
78
|
+
function inboundDepth(agent) {
|
|
79
|
+
const session = agent?.session
|
|
80
|
+
if (session === undefined || session === null) return 0
|
|
81
|
+
try {
|
|
82
|
+
const end = typeof session.seq === 'number' ? session.seq : 0
|
|
83
|
+
const floor = Math.max(0, end - 300)
|
|
84
|
+
for (let seq = end - 1; seq >= floor; seq -= 1) {
|
|
85
|
+
const event = session.eventAt(seq)
|
|
86
|
+
if (event?.type !== 'user/message') continue
|
|
87
|
+
const content = event.data?.content
|
|
88
|
+
if (!Array.isArray(content)) continue
|
|
89
|
+
for (const block of content) {
|
|
90
|
+
if (block?.type !== 'text' || typeof block.text !== 'string') continue
|
|
91
|
+
const match = block.text.match(CROSS_SESSION_MARK)
|
|
92
|
+
if (match) return Number.parseInt(match[1], 10) || 0
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
} catch {
|
|
96
|
+
// 读历史失败不影响发送,当 0 处理(宁可少拦一次,也不让功能整块挂掉)。
|
|
97
|
+
}
|
|
98
|
+
return 0
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 限频检查:同一对会话 60 秒内最多 rateLimit 条。 */
|
|
102
|
+
function checkRate(fromId, toId) {
|
|
103
|
+
const key = `${fromId}>${toId}`
|
|
104
|
+
const now = Date.now()
|
|
105
|
+
const recent = (sentAt.get(key) ?? []).filter((at) => now - at < RATE_WINDOW_MS)
|
|
106
|
+
if (recent.length >= rateLimit) {
|
|
107
|
+
const waitSeconds = Math.max(1, Math.ceil((RATE_WINDOW_MS - (now - recent[0])) / 1000))
|
|
108
|
+
throw new Error(`发得太频繁了:同一会话 60 秒内最多 ${rateLimit} 条,请等约 ${waitSeconds} 秒再发`)
|
|
109
|
+
}
|
|
110
|
+
recent.push(now)
|
|
111
|
+
sentAt.set(key, recent)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 向目标会话投递一条消息。
|
|
116
|
+
* @returns {Promise<{accepted: boolean, sessionId: string, mode: string, depth: number}>}
|
|
117
|
+
*/
|
|
118
|
+
async function sendMessage({ fromAgent, fromTitle, sessionId, text, mode = 'queue', signal }) {
|
|
119
|
+
const service = requireController()
|
|
120
|
+
const target = String(sessionId || '').trim()
|
|
121
|
+
if (!target) throw new Error('session_id 不能为空')
|
|
122
|
+
const body = String(text || '').trim()
|
|
123
|
+
if (!body) throw new Error('text 不能为空,写清楚要对方做什么')
|
|
124
|
+
if (body.length > 8000) throw new Error('text 太长(上限 8000 字),请精简')
|
|
125
|
+
|
|
126
|
+
const fromId = String(fromAgent?.id ?? '')
|
|
127
|
+
if (fromId && target === fromId) throw new Error('不能给自己发跨会话消息,直接说话就行')
|
|
128
|
+
|
|
129
|
+
const delivery = mode === 'steer' ? 'steer' : 'queue'
|
|
130
|
+
const session = await findSession(target, signal)
|
|
131
|
+
if (session === undefined) {
|
|
132
|
+
throw new Error(`找不到会话 "${target}",先用 session_list 查一下准确 id`)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const depth = inboundDepth(fromAgent) + 1
|
|
136
|
+
if (depth > maxDepth) {
|
|
137
|
+
throw new Error(`跨会话链路已经到第 ${depth} 层(上限 ${maxDepth} 层),拒绝继续转发,避免两个会话无限互叫`)
|
|
138
|
+
}
|
|
139
|
+
checkRate(fromId || 'unknown', target)
|
|
140
|
+
|
|
141
|
+
const fromLabel = String(fromTitle || '').trim() || (fromId ? fromId.slice(0, 18) : '另一个会话')
|
|
142
|
+
const headerLines = [`【跨会话消息 #depth=${depth} from=${fromId || 'unknown'}】`, `来自会话「${fromLabel}」`]
|
|
143
|
+
if (session.cwd) headerLines.push(`目标工作区:${session.cwd}`)
|
|
144
|
+
const marked = `${headerLines.join('\n')}\n\n${body}`
|
|
145
|
+
|
|
146
|
+
// 走 agent.followup 而不是 sessionController.prompt:
|
|
147
|
+
// 后者的 source 固定是 'user',在目标会话里会伪装成用户本人说话。
|
|
148
|
+
// followup 带上生产者自有的 source.kind(不是 'user'),客户端就会把这条消息
|
|
149
|
+
// 渲染成「收到执行请求」折叠卡片(turn-trigger 的默认分支),一眼能看出是 AI 发的。
|
|
150
|
+
const agent = await resolveTargetAgent(service, target)
|
|
151
|
+
const message = {
|
|
152
|
+
id: `cross-session-${randomUUID()}`,
|
|
153
|
+
role: 'user',
|
|
154
|
+
content: [{ type: 'text', text: marked }],
|
|
155
|
+
source: { kind: 'plugin:interaction' },
|
|
156
|
+
}
|
|
157
|
+
if (delivery === 'steer') agent.steer(message)
|
|
158
|
+
else agent.followup(message)
|
|
159
|
+
|
|
160
|
+
log?.(`跨会话投递 ${fromId || '?'} → ${target}(depth=${depth}, mode=${delivery})`)
|
|
161
|
+
return { accepted: true, sessionId: target, mode: delivery, depth, title: session.title }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* 拿到目标会话的 live agent(冷会话会被 resume)。
|
|
166
|
+
* @returns {Promise<{followup: Function, steer: Function}>}
|
|
167
|
+
*/
|
|
168
|
+
async function resolveTargetAgent(service, target) {
|
|
169
|
+
if (typeof service.resolveAgent !== 'function') {
|
|
170
|
+
throw new Error('当前 dsh 版本的 sessionController 没有 resolveAgent,跨会话投递不可用')
|
|
171
|
+
}
|
|
172
|
+
const found = await service.resolveAgent(target)
|
|
173
|
+
if (found === undefined || found === null) {
|
|
174
|
+
throw new Error(`会话 "${target}" 没有可用的 agent`)
|
|
175
|
+
}
|
|
176
|
+
if (typeof found === 'object' && 'error' in found && found.error) throw found.error
|
|
177
|
+
const agent = typeof found === 'object' && 'agent' in found ? found.agent : found
|
|
178
|
+
if (agent === undefined || agent === null || typeof agent.followup !== 'function') {
|
|
179
|
+
throw new Error(`会话 "${target}" 拿不到可投递的 agent`)
|
|
180
|
+
}
|
|
181
|
+
return agent
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 读目标会话最近的消息,看对方回了什么。
|
|
186
|
+
*
|
|
187
|
+
* 必须过滤掉系统注入的 user 消息(runtime-context 快照、time-context 时间戳之类):
|
|
188
|
+
* 它们也是 user/message,但 source.kind 不是 `user`,内容又长得离谱,
|
|
189
|
+
* 不过滤的话 peek 出来全是噪声,根本看不到真正的对话。
|
|
190
|
+
* @returns {Promise<{messages: Array<{role: string, seq: number, at: number, text: string}>}>}
|
|
191
|
+
*/
|
|
192
|
+
async function peekSession({ sessionId, limit = 6, signal }) {
|
|
193
|
+
const service = requireController()
|
|
194
|
+
const target = String(sessionId || '').trim()
|
|
195
|
+
if (!target) throw new Error('session_id 不能为空')
|
|
196
|
+
const want = Math.max(1, Math.min(Number(limit) || 6, 30))
|
|
197
|
+
// 系统注入消息会占名额,所以多读一截再过滤。
|
|
198
|
+
const page = await service.events({
|
|
199
|
+
address: { kind: 'session', sessionId: target },
|
|
200
|
+
maxMessages: Math.min(want * 6 + 10, 120),
|
|
201
|
+
}, signal)
|
|
202
|
+
|
|
203
|
+
const records = Array.isArray(page?.records) ? page.records : []
|
|
204
|
+
const messages = []
|
|
205
|
+
for (const record of records) {
|
|
206
|
+
const event = record?.event ?? record
|
|
207
|
+
const type = event?.type
|
|
208
|
+
const sourceKind = event?.data?.source?.kind
|
|
209
|
+
const role = type === 'user/message'
|
|
210
|
+
? (sourceKind === CROSS_SESSION_SOURCE ? '跨会话' : '用户')
|
|
211
|
+
: type === 'assistant/message' ? '助手' : null
|
|
212
|
+
if (role === null) continue
|
|
213
|
+
if (type === 'user/message' && !isConversationMessage(event?.data)) continue
|
|
214
|
+
const text = extractText(event?.data)
|
|
215
|
+
if (!text) continue
|
|
216
|
+
// 长得离谱的防御性丢弃:真对话不会单条上万字,系统快照会。
|
|
217
|
+
if (text.length > 6000) continue
|
|
218
|
+
messages.push({
|
|
219
|
+
role,
|
|
220
|
+
seq: Number(event.seq) || 0,
|
|
221
|
+
at: Number(event.time) || 0,
|
|
222
|
+
text: text.length > 1200 ? `${text.slice(0, 1200)}…` : text,
|
|
223
|
+
})
|
|
224
|
+
}
|
|
225
|
+
return { messages: messages.slice(-want) }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return { listSessions, sendMessage, peekSession, findSession }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 跨会话消息在目标会话里的 source.kind(不是 'user',所以客户端渲染成折叠卡片)。 */
|
|
232
|
+
export const CROSS_SESSION_SOURCE = 'plugin:interaction'
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* 这条 user 消息是不是「真对话」里的一条。
|
|
236
|
+
*
|
|
237
|
+
* 系统注入的上下文(runtime-context 快照、time-context 读数)也是 user/message,
|
|
238
|
+
* 但 source.kind 不是 `user`。真实的用户输入是 `user`;别的会话发来的是
|
|
239
|
+
* `plugin:interaction`(我们自己的)。
|
|
240
|
+
*/
|
|
241
|
+
export function isConversationMessage(data) {
|
|
242
|
+
const kind = data?.source?.kind
|
|
243
|
+
return kind === undefined || kind === 'user' || kind === CROSS_SESSION_SOURCE
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** 从一条 user/assistant 消息事件里抠出纯文本。结构有几种写法,挨个试。 */
|
|
247
|
+
export function extractText(data) {
|
|
248
|
+
if (data === null || typeof data !== 'object') return ''
|
|
249
|
+
const candidates = [data.content, data.message?.content, data.blocks]
|
|
250
|
+
for (const content of candidates) {
|
|
251
|
+
if (!Array.isArray(content)) continue
|
|
252
|
+
const parts = []
|
|
253
|
+
for (const block of content) {
|
|
254
|
+
if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
255
|
+
}
|
|
256
|
+
if (parts.length > 0) return parts.join('\n').trim()
|
|
257
|
+
}
|
|
258
|
+
if (typeof data.text === 'string') return data.text.trim()
|
|
259
|
+
return ''
|
|
260
|
+
}
|
package/lib/tool.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工具定义的小工具。
|
|
3
|
+
*
|
|
4
|
+
* 刻意不 import @deepseek-ai/dsh-tools:本地 link 安装的插件解析不到
|
|
5
|
+
* profile 里的包(真实踩过的坑)。这里只造 DSH 认的最小形状。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 递归编译简写参数表。
|
|
10
|
+
*
|
|
11
|
+
* 简写约定:值里写 `required: true` 表示这个 key 必填。
|
|
12
|
+
* 注意必须递归进 `items`——模型 API 只认 JSON Schema 的
|
|
13
|
+
* `required: ['a','b']`(父对象上的数组),property 里残留一个
|
|
14
|
+
* `required: true` 会被判成 "true is not of type array" 直接整条工具作废。
|
|
15
|
+
*/
|
|
16
|
+
function compilePropertyTable(parameters) {
|
|
17
|
+
const properties = {}
|
|
18
|
+
const required = []
|
|
19
|
+
for (const [key, spec] of Object.entries(parameters ?? {})) {
|
|
20
|
+
const { required: isRequired, ...rest } = spec ?? {}
|
|
21
|
+
properties[key] = compileValueSpec(rest)
|
|
22
|
+
if (isRequired === true) required.push(key)
|
|
23
|
+
}
|
|
24
|
+
return { properties, required }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 编译单个参数 / 数组项的 schema,递归处理 items。 */
|
|
28
|
+
function compileValueSpec(spec) {
|
|
29
|
+
const out = { ...spec }
|
|
30
|
+
if (out.items !== undefined && out.items !== null && typeof out.items === 'object') {
|
|
31
|
+
const items = { ...out.items }
|
|
32
|
+
if (items.properties !== undefined && typeof items.properties === 'object') {
|
|
33
|
+
const nested = compilePropertyTable(items.properties)
|
|
34
|
+
items.properties = nested.properties
|
|
35
|
+
if (nested.required.length > 0) items.required = nested.required
|
|
36
|
+
else delete items.required
|
|
37
|
+
}
|
|
38
|
+
out.items = items
|
|
39
|
+
}
|
|
40
|
+
return out
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 把简写参数表编译成 JSON Schema。 */
|
|
44
|
+
export function compileParameters(parameters = {}) {
|
|
45
|
+
const { properties, required } = compilePropertyTable(parameters)
|
|
46
|
+
return {
|
|
47
|
+
type: 'object',
|
|
48
|
+
properties,
|
|
49
|
+
...(required.length > 0 ? { required } : {}),
|
|
50
|
+
additionalProperties: false,
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function typeOf(value) {
|
|
55
|
+
if (value === null) return 'null'
|
|
56
|
+
if (Array.isArray(value)) return 'array'
|
|
57
|
+
if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'number'
|
|
58
|
+
return typeof value
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 按 schema 校验入参类型(DSH 只做基础校验,这里补一层)。 */
|
|
62
|
+
export function validateArguments(schema, args) {
|
|
63
|
+
const violations = []
|
|
64
|
+
const value = args && typeof args === 'object' ? args : {}
|
|
65
|
+
for (const key of schema.required ?? []) {
|
|
66
|
+
if (value[key] === undefined || value[key] === null) violations.push(`缺少必填参数: ${key}`)
|
|
67
|
+
}
|
|
68
|
+
for (const [key, propSchema] of Object.entries(schema.properties ?? {})) {
|
|
69
|
+
const given = value[key]
|
|
70
|
+
if (given === undefined || given === null) continue
|
|
71
|
+
const expected = propSchema.type
|
|
72
|
+
if (!expected) continue
|
|
73
|
+
const actual = typeOf(given)
|
|
74
|
+
const ok = expected === 'number'
|
|
75
|
+
? actual === 'number' || actual === 'integer'
|
|
76
|
+
: expected === 'integer'
|
|
77
|
+
? actual === 'integer'
|
|
78
|
+
: actual === expected
|
|
79
|
+
if (!ok) violations.push(`参数 ${key} 应为 ${expected},收到 ${actual}`)
|
|
80
|
+
}
|
|
81
|
+
return violations
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 定义一个工具:参数校验 + 错误码 + output 声明。
|
|
86
|
+
* DSH 要求每个工具都声明 output { schema, render },缺了插件直接加载失败。
|
|
87
|
+
*/
|
|
88
|
+
export function defineTool(options) {
|
|
89
|
+
const schema = compileParameters(options.parameters)
|
|
90
|
+
return {
|
|
91
|
+
name: options.name,
|
|
92
|
+
description: options.description,
|
|
93
|
+
parameters: schema,
|
|
94
|
+
output: options.output,
|
|
95
|
+
async execute(args, exec) {
|
|
96
|
+
const violations = validateArguments(schema, args)
|
|
97
|
+
if (violations.length > 0) {
|
|
98
|
+
const error = new Error(`参数不合法: ${violations.join('; ')}`)
|
|
99
|
+
error.code = 'invalid_arguments'
|
|
100
|
+
throw error
|
|
101
|
+
}
|
|
102
|
+
return await options.execute(args ?? {}, exec)
|
|
103
|
+
},
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 统一输出形状:text 给模型读,结构化字段自己留着。 */
|
|
108
|
+
export function textOutput(properties = {}) {
|
|
109
|
+
return {
|
|
110
|
+
schema: {
|
|
111
|
+
type: 'object',
|
|
112
|
+
additionalProperties: true,
|
|
113
|
+
properties: {
|
|
114
|
+
text: { type: 'string' },
|
|
115
|
+
...properties,
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
render(_args, value) {
|
|
119
|
+
const text = typeof value?.text === 'string' ? value.text : JSON.stringify(value ?? null)
|
|
120
|
+
return [{ type: 'text', text }]
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 把任意值收敛成可持久化 JSON(丢掉 undefined / NaN)。 */
|
|
126
|
+
export function toLosslessJson(value) {
|
|
127
|
+
if (value === undefined || value === null) return null
|
|
128
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : null
|
|
129
|
+
if (typeof value !== 'object') return value
|
|
130
|
+
if (Array.isArray(value)) return value.map(toLosslessJson)
|
|
131
|
+
const out = {}
|
|
132
|
+
for (const [key, item] of Object.entries(value)) out[key] = toLosslessJson(item)
|
|
133
|
+
return out
|
|
134
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@philomelcc/dsh-interaction",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "DSH 交互增强:分支式提问(选 A 才问 A 的后续,支持跨波返回)+ 跨会话唤醒(向其它会话发消息并读取回复)。",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.js",
|
|
9
|
+
"./package.json": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"lib",
|
|
14
|
+
"cordis.patch.yml",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"keywords": [
|
|
19
|
+
"dsh",
|
|
20
|
+
"deepseek-harness",
|
|
21
|
+
"cordis",
|
|
22
|
+
"plugin",
|
|
23
|
+
"ask-user",
|
|
24
|
+
"question",
|
|
25
|
+
"cross-session",
|
|
26
|
+
"agent"
|
|
27
|
+
],
|
|
28
|
+
"dsh": {
|
|
29
|
+
"bundle": {
|
|
30
|
+
"patch": "./cordis.patch.yml"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/philomelcc/dsh-interaction.git"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/philomelcc/dsh-interaction#readme",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/philomelcc/dsh-interaction/issues"
|
|
40
|
+
},
|
|
41
|
+
"author": "philomelcc",
|
|
42
|
+
"license": "MIT",
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public",
|
|
45
|
+
"registry": "https://registry.npmjs.org"
|
|
46
|
+
}
|
|
47
|
+
}
|