dsh-extra-plan 0.0.0-stage → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -2
  3. package/assets/presets/extra-plan/agent.cordis.yml +580 -0
  4. package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
  5. package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
  6. package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
  7. package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
  8. package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
  9. package/assets/presets/extra-plan/preset.yml +2 -0
  10. package/cordis.patch.yml +7 -0
  11. package/index.js +1671 -0
  12. package/lib/agent-runtime.js +172 -0
  13. package/lib/agent-session.js +65 -0
  14. package/lib/assembly-presentation.js +267 -0
  15. package/lib/client-carrier.js +7 -0
  16. package/lib/client.js +314 -0
  17. package/lib/extra-plan-gate-tool.js +387 -0
  18. package/lib/gate-decisions.js +744 -0
  19. package/lib/gate-words.js +108 -0
  20. package/lib/live-config.js +293 -0
  21. package/lib/log-retention.js +132 -0
  22. package/lib/model-routing.js +648 -0
  23. package/lib/path-policy.js +464 -0
  24. package/lib/plan-draft-tool.js +294 -0
  25. package/lib/planner-budget.js +136 -0
  26. package/lib/preset-defaults.generated.js +17 -0
  27. package/lib/preset-settings.js +3 -0
  28. package/lib/preset-sync.js +809 -0
  29. package/lib/preset-yaml.js +438 -0
  30. package/lib/role-contract.js +11 -0
  31. package/lib/run-code-scanner.js +360 -0
  32. package/lib/run-code-static.js +621 -0
  33. package/lib/runtime-diagnostics.js +89 -0
  34. package/lib/runtime-lifecycle.js +162 -0
  35. package/lib/runtime-static.js +23 -0
  36. package/lib/save-contract.js +263 -0
  37. package/lib/save-persistence.js +223 -0
  38. package/lib/save-plan-markdown-parser.js +369 -0
  39. package/lib/save-plan-validation-diagnostics.js +49 -0
  40. package/lib/save-plan-validation.js +812 -0
  41. package/lib/save-probe-validation.js +173 -0
  42. package/lib/save-source-verification.js +195 -0
  43. package/lib/save-tool-factories.js +270 -0
  44. package/lib/sdk-text-cache.js +161 -0
  45. package/lib/settings-contract.js +191 -0
  46. package/lib/settings.js +369 -0
  47. package/lib/shell-mutation.js +484 -0
  48. package/lib/usage-ledger-background.js +214 -0
  49. package/lib/usage-ledger-worker.js +116 -0
  50. package/lib/usage-ledger.js +1393 -0
  51. package/locale/en.json +6 -0
  52. package/locale/settings/en.json +6 -0
  53. package/locale/settings/zh.json +6 -0
  54. package/locale/zh.json +6 -0
  55. package/package.json +56 -4
  56. package/scripts/generate-runtime-defaults.mjs +796 -0
@@ -0,0 +1,387 @@
1
+ // 闸门专用工具 extra_plan_gate:route/规划目的两类提问的选项由插件生成,clarify 类由模型提供、插件原样转交,
2
+ // 模型不再手写 ask_user_question 的选项文案,插件事后校验也随之退化为只读派生。
3
+ // 每次 apply 由 createGateToolFactories 绑定当前 gateRuntime 词表、注入的 ask 通道与 getState 状态读取闭包;
4
+ // get 到的 defineGateTool(agent) 只产出工具定义,执行期任何失败都以普通对象返回。
5
+ // outcome 的取值集合恰为四种:answered、skipped、cancelled、channel-error;主会话据此区分
6
+ // route/purpose 无主选项时 outcome='skipped'(purpose 在 route 非 plan 或状态不可用时也 skipped);clarify 仅在所有答复均无选中项且无自定义文本(含空答复)时 skipped;
7
+ // 其余正常答复为 answered。取消类错误 → cancelled,其余错误 → channel-error 并附 error.code。
8
+ // route/purpose 分支的选项文案一律取自 gateRuntime.words 词表;clarify 分支的 questions/header/options 由模型提供;route/purpose 的 header、问题正文与 noteLabel 是固定提示语,可硬编码。
9
+ // 结果的 content 固定为一个 text ContentBlock、正文是返回值整体 JSON:宿主 spill-policy 的 post-execute 与 PTC 提交都按数组消费 content,状态机只解析这块 JSON。
10
+
11
+ import { errorCodeOf } from './runtime-static.js'
12
+ import { normalizeGateLabel } from './gate-words.js'
13
+
14
+ const GATE_TOOL_NAME = 'extra_plan_gate'
15
+ // 宿主 ask 的「推荐」是 label 后缀约定(Web 端 parseRecommendedLabel 剥离后缀后渲染「推荐」徽标),
16
+ // 这里的后缀只作用于展示用 label;返回值与闸门词匹配一律按纯词值处理。
17
+ const RECOMMEND_SUFFIX = '(推荐)'
18
+
19
+ // 固定提示语(不是闸门选项文案):三问的 header、问题正文与 note 标签。
20
+ const CHOICE_ID = 'extra_plan_gate_0'
21
+ const NOTE_ID = 'extra_plan_gate_1'
22
+ const ROUTE_HEADER = '路线确认'
23
+ const ROUTE_QUESTION = '这次任务走哪条路线?'
24
+ const NOTE_HEADER = '其他说明'
25
+ const NOTE_QUESTION = '其他说明:如转交规划者等。可置空'
26
+ const NOTE_LABEL = '其他说明'
27
+ // 两个自由文本标签分属 route 的两问、互不合并:CHOICE_NOTE_LABEL 是第一问(路线四选一)外可填的自由输入,
28
+ // NOTE_LABEL 是第二问「其他说明」。
29
+ const CHOICE_NOTE_LABEL = '路线自由输入'
30
+ const PURPOSE_HEADER = '规划目的'
31
+ const PURPOSE_QUESTION = '这次让规划者分析的目的?'
32
+ const PURPOSE_DETAIL = '完善方案=在已有方案基础上修改;重新规划=把原始需求交给规划者重新理解'
33
+
34
+ // 取消类错误码:命中即按用户取消处理(不算通道故障),execute 以 outcome='cancelled' 返回。
35
+ const CANCEL_CODES = new Set(['ASK_CANCELLED', 'CANCELLED', 'CANCELED', 'ABORTED', 'ABORT_ERR', 'ERR_CANCELED'])
36
+
37
+ // 取消判别:只认取消类错误码、AbortError 名或宿主的取消句(cancel/abort 文案);
38
+ // 通道码(NO_PROVIDER/CALLER_NOT_LIVE/DELEGATED_CALLER 等)不含这些词,仍落 channel-error。
39
+ function isCancelError(error) {
40
+ if (error === null || typeof error !== 'object') return false
41
+ if (typeof error.name === 'string' && error.name === 'AbortError') return true
42
+ if (CANCEL_CODES.has(errorCodeOf(error))) return true
43
+ const message = typeof error.message === 'string' ? error.message.toLowerCase() : ''
44
+ return message.includes('cancelled') || message.includes('canceled') || message.includes('aborted')
45
+ }
46
+
47
+ // ask 成功返回:宿主给 { answers },个别通道直接回传数组;两种都接收,其余按空答复处理。
48
+ function answersOf(asked) {
49
+ if (Array.isArray(asked)) return asked
50
+ if (asked !== null && typeof asked === 'object' && Array.isArray(asked.answers)) return asked.answers
51
+ return []
52
+ }
53
+
54
+ // recommended 归一:undefined/null 视为不标记(空串);字符串 trim 后返回;非字符串原样返回交给校验。
55
+ function recommendValueOf(raw) {
56
+ if (raw === undefined || raw === null) return ''
57
+ if (typeof raw !== 'string') return raw
58
+ return raw.trim()
59
+ }
60
+
61
+ // 展示标签:recommended 与当前选项词全等时追加推荐后缀,其余原样返回(不改顺序、不改描述)。
62
+ function askLabelOf(label, recommended) {
63
+ return recommended !== '' && recommended === label ? label + RECOMMEND_SUFFIX : label
64
+ }
65
+
66
+ // recommended 校验:route 只接受当前四个路线词、purpose 只接受当前两个目的词,空串表示不标记。
67
+ // 非法值不抛出、不弹卡,直接返回可用的 channel-error 对象;gateOptions 取不到时提示里容忍为空串。
68
+ function recommendedOrError(gate, raw, words, gateOptions) {
69
+ const value = recommendValueOf(raw)
70
+ if (value === '') return ''
71
+ const legal = gate === 'purpose'
72
+ ? [words.purposeRefine, words.purposeRedo]
73
+ : [words.routeMain, words.routeExecutor, words.routePlan, words.routeDisagree]
74
+ if (legal.includes(value)) return value
75
+ const options = gateOptions !== null && typeof gateOptions === 'object' ? gateOptions : {}
76
+ const listed = gate === 'purpose'
77
+ ? (typeof options.purpose === 'string' ? options.purpose : '')
78
+ : (typeof options.route === 'string' ? options.route : '')
79
+ const branch = gate === 'purpose' ? 'purpose' : 'route'
80
+ const kind = gate === 'purpose' ? '当前目的词之一' : '当前路线词之一'
81
+ const message = 'recommended 取值无效:' + branch + ' 闸门只接受' + kind + '(' + listed + ');不传或传空串表示不标记'
82
+ return { gate, outcome: 'channel-error', error: { code: 'INVALID_RECOMMENDED', message } }
83
+ }
84
+
85
+ // 单条答复的选中标签(宿主可能回传 selected 为空数组或非字符串项)。
86
+ function selectedLabelsOf(answer) {
87
+ const labels = []
88
+ if (answer === null || typeof answer !== 'object' || !Array.isArray(answer.selected)) return labels
89
+ for (const label of answer.selected) if (typeof label === 'string') labels.push(label)
90
+ return labels
91
+ }
92
+
93
+ // 单条答复的自由文本原文(route 第二问「其他说明」用 custom);缺失一律空串。
94
+ function customTextOf(answer) {
95
+ if (answer === null || typeof answer !== 'object') return ''
96
+ return typeof answer.custom === 'string' ? answer.custom : ''
97
+ }
98
+
99
+ // 路线四选项:数组顺序即 ask 返回的序号口径(0 main、1 executor、2 plan、3 none)。
100
+ // label 只取词表;description 是固定提示语,不参与闸门词的精确匹配。
101
+ function routeOptionsOf(words) {
102
+ return [
103
+ { route: 'main', label: words.routeMain, description: '本次会话直接动手执行' },
104
+ { route: 'executor', label: words.routeExecutor, description: '按已有方案转交执行者落地' },
105
+ { route: 'plan', label: words.routePlan, description: '先转交规划者出方案,再按方案动手' },
106
+ { route: 'none', label: words.routeDisagree, description: '暂不推进,先澄清方向' },
107
+ ]
108
+ }
109
+
110
+ // 规划目的两选项:顺序即序号口径(0 refine、1 redo),解释统一放在问题的 detail 里。
111
+ function purposeOptionsOf(words) {
112
+ return [
113
+ { purpose: 'refine', label: words.purposeRefine },
114
+ { purpose: 'redo', label: words.purposeRedo },
115
+ ]
116
+ }
117
+
118
+ // 按选中标签回查选项:标签由本插件生成,按精确值比对;未选/跳过返回 null。
119
+ function pickBySelected(options, labels) {
120
+ if (labels.length === 0) return null
121
+ for (const option of options) if (labels.includes(option.label)) return option
122
+ return null
123
+ }
124
+
125
+ // 失败返回:取消类 → cancelled(保留已填字段);其余 → channel-error 并附 error.code。
126
+ // 无论哪种分支都返回普通对象,绝不向外抛错。
127
+ function failResult(result, error) {
128
+ if (isCancelError(error)) {
129
+ result.outcome = 'cancelled'
130
+ return result
131
+ }
132
+ result.outcome = 'channel-error'
133
+ result.error = { code: errorCodeOf(error) }
134
+ return result
135
+ }
136
+
137
+ function badAnswer(result) {
138
+ return failResult(result, Object.assign(new Error('用户答复与问题或选项不匹配'), { code: 'BAD_ANSWER' }))
139
+ }
140
+
141
+ // 私有绑定:校验依赖,把本次 apply 的词表、ask 通道与 getState 状态读取绑到三支分支上,返回 { defineGateTool }。
142
+ // 依赖不合法在创建期同步报错(apply 期问题),execute 内不再抛错。
143
+ function boundGateTool(gateRuntime, ask, getState) {
144
+ if (gateRuntime === null || typeof gateRuntime !== 'object' || gateRuntime.words === null || typeof gateRuntime.words !== 'object') {
145
+ throw new Error('extra-plan: extra_plan_gate 需要含 words 词表的 gateRuntime')
146
+ }
147
+ if (typeof ask !== 'function') throw new Error('extra-plan: extra_plan_gate 需要注入 ask 通道函数')
148
+ const words = gateRuntime.words
149
+ // 选项词串只用于 recommended 非法值的中文提示:缺字段时回落空对象,不抛错。
150
+ const gateOptions = gateRuntime.options !== null && typeof gateRuntime.options === 'object' ? gateRuntime.options : {}
151
+
152
+ // route 分支:两问(路线四选一 + 其他说明可空),返回中文 routeLabel 供主会话直接读。
153
+ async function askRoute(execAgent, signal, recommendedArg) {
154
+ // recommended 先校验:非法值直接返回 channel-error(不弹卡);空串表示本次不标记推荐项。
155
+ const recommended = recommendedOrError('route', recommendedArg, words, gateOptions)
156
+ // 合法词与「不标记」都是字符串;只有校验失败才返回对象 → 直接回传,不调用 ask。
157
+ if (typeof recommended !== 'string') return recommended
158
+ const options = routeOptionsOf(words)
159
+ const result = {
160
+ gate: 'route',
161
+ route: null,
162
+ routeLabel: null,
163
+ purpose: null,
164
+ note: '',
165
+ noteLabel: NOTE_LABEL,
166
+ choiceNote: '',
167
+ choiceNoteLabel: CHOICE_NOTE_LABEL,
168
+ outcome: 'answered',
169
+ }
170
+ let answers
171
+ try {
172
+ const asked = await ask({
173
+ questions: [
174
+ {
175
+ id: CHOICE_ID,
176
+ header: ROUTE_HEADER,
177
+ question: ROUTE_QUESTION,
178
+ options: options.map((option) => ({ label: askLabelOf(option.label, recommended), description: option.description })),
179
+ },
180
+ { id: NOTE_ID, header: NOTE_HEADER, question: NOTE_QUESTION },
181
+ ],
182
+ agent: execAgent,
183
+ signal,
184
+ })
185
+ answers = answersOf(asked)
186
+ } catch (error) {
187
+ return failResult(result, error)
188
+ }
189
+ const choiceAnswer = answers.find((answer) => answer?.id === CHOICE_ID)
190
+ const noteAnswer = answers.find((answer) => answer?.id === NOTE_ID)
191
+ if (answers.length !== 2 || choiceAnswer === undefined || noteAnswer === undefined) return badAnswer(result)
192
+ result.note = customTextOf(noteAnswer)
193
+ result.choiceNote = customTextOf(choiceAnswer)
194
+ // 宿主可能回传带推荐后缀的原 label:先剥离后缀,再与当前词值精确比对(返回的 label 仍是纯词值)。
195
+ const selected = selectedLabelsOf(choiceAnswer).map((label) => normalizeGateLabel(label))
196
+ // 第一问未选中(用户跳过,selected 为空)→ outcome='skipped':route 仍落 none(与旧机制同口径),
197
+ // routeLabel 置空串,绝不回填 disagree 词值,避免把「没作答」误报成「不同意」。
198
+ // selected 为空仍判 skipped,但两个自由文本字段保留原文(note 与 choiceNote 均在上面赋值,不回退为空串)。
199
+ if (selected.length === 0) {
200
+ result.route = 'none'
201
+ result.routeLabel = ''
202
+ result.outcome = 'skipped'
203
+ return result
204
+ }
205
+ // 选中项按选项序号落 route;选中 disagree 项 → route=none、routeLabel 回填该词值、outcome 仍 answered。
206
+ const chosen = pickBySelected(options, selected)
207
+ if (chosen === null) return badAnswer(result)
208
+ result.route = chosen.route
209
+ result.routeLabel = chosen.label
210
+ return result
211
+ }
212
+
213
+ // purpose 分支:单问两选一(目的解释在 detail 里),返回中文 purposeLabel。
214
+ async function askPurpose(execAgent, signal, recommendedArg) {
215
+ // 路线前置守卫(2c):purpose 只在 route=plan 路线成立;非 plan 或状态不可判定一律不弹卡、
216
+ // 直接以 skipped 返回(applyGateOutcome 对 skipped 不改动任何字段),避免用户被问无效问题。
217
+ let state = null
218
+ let stateUnavailable = false
219
+ if (typeof getState === 'function') {
220
+ try { state = getState(execAgent) } catch (error) { stateUnavailable = true }
221
+ } else { stateUnavailable = true }
222
+ if (stateUnavailable || state === null || typeof state !== 'object' || state.route !== 'plan') {
223
+ return { gate: 'purpose', purpose: null, purposeLabel: null, outcome: 'skipped', reason: stateUnavailable ? 'state-unavailable' : 'route-not-plan' }
224
+ }
225
+ // recommended 校验排在路线守卫之后(非 plan 路线本就不弹卡);非法值直接返回 channel-error,不调用 ask。
226
+ const recommended = recommendedOrError('purpose', recommendedArg, words, gateOptions)
227
+ // 同上:校验失败返回对象 → 直接回传,不弹卡。
228
+ if (typeof recommended !== 'string') return recommended
229
+ const options = purposeOptionsOf(words)
230
+ const result = { gate: 'purpose', purpose: null, purposeLabel: null, outcome: 'answered' }
231
+ let answers
232
+ try {
233
+ const asked = await ask({
234
+ questions: [
235
+ {
236
+ id: CHOICE_ID,
237
+ header: PURPOSE_HEADER,
238
+ question: PURPOSE_QUESTION,
239
+ detail: PURPOSE_DETAIL,
240
+ options: options.map((option) => ({ label: askLabelOf(option.label, recommended) })),
241
+ },
242
+ ],
243
+ agent: execAgent,
244
+ signal,
245
+ })
246
+ answers = answersOf(asked)
247
+ } catch (error) {
248
+ return failResult(result, error)
249
+ }
250
+ // 同 route 分支:选中标签先剥离推荐后缀再匹配,purposeLabel 仍取纯词值。
251
+ const [answer] = answers
252
+ if (answers.length !== 1 || answer?.id !== CHOICE_ID) return badAnswer(result)
253
+ const selected = selectedLabelsOf(answer).map((label) => normalizeGateLabel(label))
254
+ // 未选中(用户跳过)→ outcome='skipped',purpose 保持 null,purposeLabel 置空串。
255
+ if (selected.length === 0) {
256
+ result.purposeLabel = ''
257
+ result.outcome = 'skipped'
258
+ return result
259
+ }
260
+ // 选中任一项 → outcome 保持 answered 并回填对应词值。
261
+ const chosen = pickBySelected(options, selected)
262
+ if (chosen === null) return badAnswer(result)
263
+ result.purpose = chosen.purpose
264
+ result.purposeLabel = chosen.label
265
+ return result
266
+ }
267
+
268
+ // clarify 分支:questions 原样透传给 ask,答复原样回传,不在插件侧构造任何选项。
269
+ async function askClarify(questions, execAgent, signal) {
270
+ let answers
271
+ try {
272
+ const asked = await ask({ questions, agent: execAgent, signal })
273
+ answers = answersOf(asked)
274
+ } catch (error) {
275
+ return failResult({ gate: 'clarify', answers: [], outcome: 'answered' }, error)
276
+ }
277
+ // 全空答复(所有问题都没选中项且没有自定义文本,含 answers 为空数组)→ skipped;否则 answered。
278
+ const hasAnswer = answers.some((answer) => selectedLabelsOf(answer).length > 0 || customTextOf(answer) !== '')
279
+ return { gate: 'clarify', answers, outcome: hasAnswer ? 'answered' : 'skipped' }
280
+ }
281
+
282
+ // defineGateTool(agent):返回工具定义。agent 只作为注册锚点透传,工具行为不依赖具体会话
283
+ // (词表、ask 通道与 getState 已在工厂创建时绑定)。
284
+ function defineGateTool(agent) {
285
+ return {
286
+ name: GATE_TOOL_NAME,
287
+ description: '闸门提问。gate=route 路线确认;gate=purpose 规划目的;gate=clarify 意图澄清:在 questions 里给 1-3 个问题(header/question/options),插件原样转交用户;可选 recommended 指定本次推荐项、插件只给该选项加(推荐)标记、不改选项顺序与文案',
288
+ parameters: {
289
+ type: 'object',
290
+ properties: {
291
+ gate: {
292
+ type: 'string',
293
+ enum: ['route', 'purpose', 'clarify'],
294
+ description: 'route=路线确认;purpose=规划目的确认;clarify=意图澄清问答',
295
+ },
296
+ recommended: {
297
+ type: 'string',
298
+ description: '仅 route/purpose:本次要推荐的选项原文,route 取当前四个路线词之一、purpose 取当前两个目的词之一,与卡片选项文字一致;不传或空串表示不标记;填错返回 INVALID_RECOMMENDED;clarify 忽略本参数',
299
+ },
300
+ questions: {
301
+ type: 'array',
302
+ minItems: 1,
303
+ maxItems: 3,
304
+ items: { type: 'object' },
305
+ description: '仅 gate=clarify:1-3 个澄清问题(header/question/options),原样转交;route/purpose 不传',
306
+ },
307
+ },
308
+ required: ['gate'],
309
+ additionalProperties: false,
310
+ },
311
+ output: {
312
+ schema: {
313
+ type: 'object',
314
+ properties: {
315
+ gate: { type: 'string', description: '回填入参 gate 取值(route/purpose/clarify)' },
316
+ reason: { type: 'string', description: '仅 outcome=skipped 时可能出现:route-not-plan=purpose 前置守卫因路线非 plan 未弹卡;state-unavailable=状态读取不可用未弹卡' },
317
+ outcome: { type: 'string', enum: ['answered', 'skipped', 'cancelled', 'channel-error'], description: 'answered=用户作答;skipped=用户跳过未作答(route/purpose 的 label 为空串、route 恒为 none);cancelled=用户取消;channel-error=提问通道失败或参数校验失败(见 error.code)' },
318
+ route: { description: 'route 分支:main/executor/plan/none 之一(跳过时仍为 none);其它分支不返回' },
319
+ routeLabel: { description: 'route 分支:route 对应的中文路线词(取自 gateRuntime 词表);跳过时为空串;其它分支为 null' },
320
+ purpose: { description: 'purpose 分支:refine/redo,未选中为 null;route 分支恒为 null' },
321
+ purposeLabel: { description: 'purpose 分支:purpose 对应的中文目的词(取自 gateRuntime 词表);跳过时为空串' },
322
+ note: { type: 'string', description: 'route 分支:第二问「其他说明」的原文,未填为空串' },
323
+ noteLabel: { type: 'string', description: 'route 分支:note 的固定标签(其他说明)' },
324
+ choiceNote: { type: 'string', description: 'route 分支:第一问(路线四选一)自由输入的原文,未填为空串;与 note 分属两问,不合并' },
325
+ choiceNoteLabel: { type: 'string', description: 'route 分支:choiceNote 的固定标签(路线自由输入)' },
326
+ answers: { type: 'array', items: { type: 'object' }, description: 'clarify 分支:宿主原样返回的答复数组' },
327
+ error: {
328
+ type: 'object',
329
+ description: 'channel-error 时的错误摘要',
330
+ properties: {
331
+ code: { type: 'string', description: '宿主错误码,缺失时为空串' },
332
+ message: { type: 'string', description: '面向模型的中文说明,缺失时为空串' },
333
+ },
334
+ required: ['code'],
335
+ additionalProperties: false,
336
+ },
337
+ },
338
+ required: ['gate', 'outcome'],
339
+ additionalProperties: false,
340
+ },
341
+ // 结果 content 必须恰为一个 text ContentBlock、正文是返回值整体 JSON:
342
+ // 宿主按数组消费 content(spill-policy 的 post-execute 与 PTC 提交都对 content 调 .some),
343
+ // 状态机只解析这块 JSON 的 outcome 与 route/purpose;裸字符串会崩宿主,人类摘要会让三锚点停在原地。
344
+ render(_args, value) {
345
+ return [{ type: 'text', text: JSON.stringify(value) }]
346
+ },
347
+ },
348
+ async execute(args, exec) {
349
+ const gate = args !== null && typeof args === 'object' && typeof args.gate === 'string' ? args.gate : ''
350
+ // recommended 只对 route/purpose 生效;clarify 分支不读取该参数,保持原样透传。
351
+ const recommendedArg = args !== null && typeof args === 'object' ? args.recommended : undefined
352
+ const execAgent = exec !== null && typeof exec === 'object' ? exec.agent : undefined
353
+ const signal = exec !== null && typeof exec === 'object' ? exec.signal : undefined
354
+ try {
355
+ if (gate === 'route') return await askRoute(execAgent, signal, recommendedArg)
356
+ if (gate === 'purpose') return await askPurpose(execAgent, signal, recommendedArg)
357
+ if (gate === 'clarify') {
358
+ const questions = args !== null && typeof args === 'object' ? args.questions : undefined
359
+ // clarify 要求非空数组;参数 schema 的 minItems 已拦截,此处只做不抛错的兜底。
360
+ if (!Array.isArray(questions) || questions.length === 0) {
361
+ return { gate: 'clarify', answers: [], outcome: 'channel-error', error: { code: 'INVALID_QUESTIONS' } }
362
+ }
363
+ return await askClarify(questions, execAgent, signal)
364
+ }
365
+ // 非法 gate(schema enum 已拦截)同样不抛错,保留原值便于诊断。
366
+ return { gate: gate === '' ? 'unknown' : gate, outcome: 'channel-error', error: { code: 'INVALID_GATE' } }
367
+ } catch (error) {
368
+ // 兜底:任何未预期异常都收敛成普通对象,不让 execute 向外抛错。
369
+ return { gate: gate === '' ? 'unknown' : gate, outcome: 'channel-error', error: { code: errorCodeOf(error) } }
370
+ }
371
+ },
372
+ }
373
+ }
374
+
375
+ return Object.freeze({ defineGateTool })
376
+ }
377
+
378
+ // 工具工厂:绑定本次 apply 的词表、ask 通道与 getState,返回 { defineGateTool }。
379
+ // 与 createSaveToolFactories 同形,便于后续按 agent 注册时统一取定义。
380
+ export function createGateToolFactories({ gateRuntime, ask, getState } = {}) {
381
+ return boundGateTool(gateRuntime, ask, getState)
382
+ }
383
+
384
+ // 直取定义的便捷出口:defineGateTool(agent, { gateRuntime, ask, getState }) 与工厂返回值同一实现。
385
+ export function defineGateTool(agent, { gateRuntime, ask, getState } = {}) {
386
+ return boundGateTool(gateRuntime, ask, getState).defineGateTool(agent)
387
+ }