pi-web-ui 0.114.1 → 0.114.3

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 (130) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +187 -187
  3. package/README.zh-CN.md +227 -227
  4. package/README.zh-TW.md +227 -227
  5. package/bin/device-hub-cli.mjs +577 -577
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -9
  8. package/bin/pi-web-ui.mjs +4081 -4081
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service.js +88 -15
  12. package/dist/server/attachments.js +6 -6
  13. package/dist/server/canvas/canvas-orchestrator.js +3 -3
  14. package/dist/server/communicate-tool.js +37 -11
  15. package/dist/server/compaction-instructions.js +8 -8
  16. package/dist/server/context-usage.js +105 -0
  17. package/dist/server/device-center/desktop-page.js +228 -228
  18. package/dist/server/device-center/hub-page.js +64 -64
  19. package/dist/server/device-center/native-desktop/macos.js +190 -190
  20. package/dist/server/device-center/native-desktop/windows.js +116 -116
  21. package/dist/server/dsh/runtime/cordis.yml +1 -1
  22. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  23. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  24. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  25. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  26. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  27. package/dist/server/durable/durable-event-projector.js +19 -3
  28. package/dist/server/durable/durable-models.js +134 -65
  29. package/dist/server/eval-tool.js +135 -135
  30. package/dist/server/model-resolver.js +4 -1
  31. package/dist/server/patch-bash-process.js +89 -89
  32. package/dist/server/patch-tool.js +9 -9
  33. package/dist/server/patch-turn-end-boundary.js +3 -3
  34. package/dist/server/persona-chain.js +8 -8
  35. package/dist/server/protocol-version.js +1 -1
  36. package/dist/server/remote-ssh-service.js +39 -39
  37. package/dist/server/schedule-agent-tool.js +11 -6
  38. package/dist/server/scheduler-tasks.js +84 -2
  39. package/dist/server/scm-commitmsg.js +10 -10
  40. package/dist/server/setup-page.js +620 -620
  41. package/dist/server/universal/universal-session.js +19 -18
  42. package/dist/server/vision-bridge.js +18 -18
  43. package/docs/device-center.md +148 -148
  44. package/docs/device-desktop.md +48 -48
  45. package/docs/dsh-engine.md +493 -493
  46. package/extensions/webui.ts +335 -335
  47. package/package.json +1 -1
  48. package/plugin-sdk/README.md +174 -174
  49. package/plugin-sdk/client-utils.mjs +279 -279
  50. package/plugin-sdk/import-check.mjs +210 -210
  51. package/plugin-sdk/index.d.ts +698 -698
  52. package/plugin-sdk/index.mjs +696 -696
  53. package/plugin-sdk/package.json +13 -13
  54. package/plugin-sdk/ssh-host-trust.mjs +225 -225
  55. package/themes/aetheris.css +501 -501
  56. package/themes/ayu-light.css +116 -116
  57. package/themes/bases/flow-base.css +1357 -1357
  58. package/themes/bases/obsidian-base.css +895 -895
  59. package/themes/bases/statusbar-flat-base.css +112 -112
  60. package/themes/bases/zhujian-base.css +688 -688
  61. package/themes/bases/zhupi-base.css +660 -660
  62. package/themes/catppuccin-latte.css +119 -119
  63. package/themes/catppuccin.css +116 -116
  64. package/themes/claude-code-dark.css +147 -147
  65. package/themes/codex.css +114 -114
  66. package/themes/cyberpunk.css +50 -50
  67. package/themes/dark-teal.css +264 -264
  68. package/themes/dazzle.css +38 -38
  69. package/themes/everforest-light.css +115 -115
  70. package/themes/flow-light.css +164 -164
  71. package/themes/flow.css +161 -161
  72. package/themes/geist.css +114 -114
  73. package/themes/gruvbox-light.css +115 -115
  74. package/themes/kanagawa-lotus.css +115 -115
  75. package/themes/md-preview.css +24 -24
  76. package/themes/mist.css +166 -166
  77. package/themes/nord.css +107 -107
  78. package/themes/one-dark.css +106 -106
  79. package/themes/paper.css +174 -174
  80. package/themes/rose-pine-dawn.css +114 -114
  81. package/themes/sakura.css +166 -166
  82. package/themes/solarized-light.css +114 -114
  83. package/themes/tokyo-night.css +115 -115
  84. package/themes/translucent.css +85 -85
  85. package/themes/transparent.css +116 -116
  86. package/themes/vs-code-dark.css +147 -147
  87. package/themes/wallpaper-flow.css +382 -382
  88. package/themes/wallpaper-obsidian.css +74 -74
  89. package/themes/white.css +164 -164
  90. package/themes/zhujian-dark.css +115 -115
  91. package/themes/zhujian.css +114 -114
  92. package/themes/zhupi-dark.css +115 -115
  93. package/themes/zhupi.css +114 -114
  94. package/web/dist/.build-assets.json +1 -1
  95. package/web/dist/assets/{BgTasksModal-BcXJ20RO.js → BgTasksModal-BvnUHjFe.js} +1 -1
  96. package/web/dist/assets/{BgTasksModal-DjQmiKnE.js → BgTasksModal-DSC8ncW3.js} +1 -1
  97. package/web/dist/assets/{CanvasStudio-PI9pid0Y.js → CanvasStudio-BSg9ghPV.js} +2 -2
  98. package/web/dist/assets/{CanvasStudio-nf5-HxLM.js → CanvasStudio-DxW7C3Sz.js} +2 -2
  99. package/web/dist/assets/{DeviceCenter-CYttJw2a.js → DeviceCenter-Bmgr-Bwm.js} +1 -1
  100. package/web/dist/assets/{DeviceCenter-DPe4sz74.js → DeviceCenter-Cl9MBXaH.js} +1 -1
  101. package/web/dist/assets/{DeviceGroups-D2rogxEN.js → DeviceGroups-aeLD2msl.js} +1 -1
  102. package/web/dist/assets/{Dropdown-ZLS04O8p.js → Dropdown-D1Jl35dw.js} +1 -1
  103. package/web/dist/assets/{FilePreview-C9Ut4Lq6.js → FilePreview-6CqoDF_P.js} +1 -1
  104. package/web/dist/assets/{FilePreview-CvK3ZzX5.js → FilePreview-CJa27G_Q.js} +1 -1
  105. package/web/dist/assets/{GlobalSearchModal-C5e-OCw2.js → GlobalSearchModal-CJX35rZL.js} +1 -1
  106. package/web/dist/assets/{GlobalSearchModal-H7pFK2UC.js → GlobalSearchModal-CMW0xz0P.js} +1 -1
  107. package/web/dist/assets/{GroupConversation-C2wNM0dQ.js → GroupConversation-Cq4daBFb.js} +1 -1
  108. package/web/dist/assets/{GroupConversation-ChN3TWQK.js → GroupConversation-DoELa83U.js} +1 -1
  109. package/web/dist/assets/{ModelConfigModal-DDZccDYt.js → ModelConfigModal-Bp7tfKYh.js} +1 -1
  110. package/web/dist/assets/{PiSetupModal-DHbqfx8T.js → PiSetupModal-DD8srwBJ.js} +1 -1
  111. package/web/dist/assets/{ProviderOAuthControls-C-MK36Dk.js → ProviderOAuthControls-C6tfXb88.js} +1 -1
  112. package/web/dist/assets/{SCMPanel-kx-SCL2s.js → SCMPanel-CghgsyBN.js} +1 -1
  113. package/web/dist/assets/{SCMPanel-buTGziDB.js → SCMPanel-D8-8aqwC.js} +1 -1
  114. package/web/dist/assets/{SettingsModal-BsUF8jqr.js → SettingsModal-BbBe2rYo.js} +1 -1
  115. package/web/dist/assets/{SettingsModal-D357Ky7P.js → SettingsModal-qETiVPKj.js} +1 -1
  116. package/web/dist/assets/{TerminalPanel-BBuM_Sez.js → TerminalPanel-Da-Xs4Wk.js} +1 -1
  117. package/web/dist/assets/{TerminalPanel-D6x6xz8Q.js → TerminalPanel-DnS4tFQO.js} +1 -1
  118. package/web/dist/assets/{TuiOverlayModal-CdbGV3Za.js → TuiOverlayModal-CGyGkKYl.js} +1 -1
  119. package/web/dist/assets/{TuiOverlayModal-d6x9u25n.js → TuiOverlayModal-CpBKjG6x.js} +1 -1
  120. package/web/dist/assets/{desktop-YguLbrX1.js → desktop-7EvUHhKQ.js} +1 -1
  121. package/web/dist/assets/{fi-DaSO0Q-m.js → fi-NyN-ZrgD.js} +2 -2
  122. package/web/dist/assets/{index-D6u8xH0o.js → index-DK3F5ZJo.js} +50 -50
  123. package/web/dist/assets/{index-BPvpea8t.js → index-DQMii2he.js} +50 -50
  124. package/web/dist/assets/index-vwBnwzkr.css +1 -0
  125. package/web/dist/assets/{plugin-host-BRBg6zmQ.js → plugin-host-BCnX3P8U.js} +1 -1
  126. package/web/dist/assets/{theme-DDl-Oy1b.js → theme-D2DMH6tH.js} +1 -1
  127. package/web/dist/index.html +35 -35
  128. package/web/dist/sw.js +179 -179
  129. package/web/public/sw.js +179 -179
  130. package/web/dist/assets/index-DDZMv6LO.css +0 -1
@@ -1,1309 +1,1309 @@
1
- /**
2
- * goal-rpc.mjs — pi-web-ui DSH runtime 的 goal RPC 扩展插件。
3
- *
4
- * 在官方 dsh-sdk-jsonrpc-server 之上包一层,为 stdio JSON-RPC 面增加 goal
5
- * 方法(goal/set goal/get goal/clear goal/resume goal/edit),直连 DSH 原生
6
- * goal 域(ctx.goals 服务,dsh-goal)。这样 pi-web-ui 前端的目标条驱动的是
7
- * DSH 自己的持久化目标状态机 + goal-round-driver 自动轮次,而不是另造一套
8
- * 审查会话 —— 审查语义 = DSH 原生(模型自判定 complete/blocked,轮次自动续)。
9
- *
10
- * 与官方插件的差异:inject 增加 "goals"(goal 域服务依赖);handleRequest
11
- * 增加 goal 分支;其余 stdio transport / shutdown 语义原样继承。
12
- *
13
- * 官方入口(做 base 类)从环境变量解析:PI_WEB_DSH_JSONRPC_ENTRY 由 dsh-client
14
- * 注入(指向项目 node_modules 的官方包);兜底从本文件位置向上找项目依赖。
15
- */
16
- import { resolve } from "node:path";
17
- import { dirname, join } from "node:path";
18
- import { fileURLToPath, pathToFileURL } from "node:url";
19
- import { existsSync } from "node:fs";
20
- import { resolveRuntimeBase } from "./runtime-root.mjs";
21
-
22
- const HERE = dirname(fileURLToPath(import.meta.url));
23
-
24
- if (!process.env.PI_WEB_DSH_RUNTIME_BASE) {
25
- try {
26
- const detected = await resolveRuntimeBase();
27
- if (detected) process.env.PI_WEB_DSH_RUNTIME_BASE = detected;
28
- } catch {}
29
- }
30
-
31
- /** 动态解析并加载 DSH 相关模块(优先使用当前正在运行的运行时树,兜底本地依赖) */
32
- async function loadDshModule(pkgName) {
33
- const rt = process.env.PI_WEB_DSH_RUNTIME_BASE;
34
- if (rt) {
35
- const candidate = join(rt, pkgName, "lib", "index.js");
36
- if (existsSync(candidate)) {
37
- return import(pathToFileURL(candidate).href);
38
- }
39
- }
40
- let cur = HERE;
41
- for (let i = 0; i < 6; i++) {
42
- const candidate = join(cur, "node_modules", pkgName, "lib", "index.js");
43
- if (existsSync(candidate)) {
44
- return import(pathToFileURL(candidate).href);
45
- }
46
- cur = dirname(cur);
47
- }
48
- return import(pkgName);
49
- }
50
-
51
- const { JsonRpcLineTransport } = await loadDshModule("@deepseek-ai/dsh-sdk-protocol");
52
- const { defineTool } = await loadDshModule("@deepseek-ai/dsh-tools");
53
-
54
- /** 官方 jsonrpc-server 入口(优先运行时树,次选 env,兜底从项目依赖向上找)。 */
55
- function findOfficialEntry() {
56
- if (process.env.PI_WEB_DSH_RUNTIME_BASE) {
57
- const candidate = join(
58
- process.env.PI_WEB_DSH_RUNTIME_BASE,
59
- "@deepseek-ai",
60
- "dsh-sdk-jsonrpc-server",
61
- "lib",
62
- "index.js",
63
- );
64
- if (existsSync(candidate)) return candidate;
65
- }
66
- if (process.env.PI_WEB_DSH_JSONRPC_ENTRY) return resolve(process.env.PI_WEB_DSH_JSONRPC_ENTRY);
67
- let cur = HERE;
68
- for (let i = 0; i < 6; i++) {
69
- const candidate = join(cur, "node_modules", "@deepseek-ai", "dsh-sdk-jsonrpc-server", "lib", "index.js");
70
- if (existsSync(candidate)) return candidate;
71
- cur = dirname(cur);
72
- }
73
- return join(
74
- resolve(HERE, "..", "..", ".."),
75
- "node_modules",
76
- "@deepseek-ai",
77
- "dsh-sdk-jsonrpc-server",
78
- "lib",
79
- "index.js",
80
- );
81
- }
82
-
83
- const officialEntry = findOfficialEntry();
84
-
85
- const official = await import(pathToFileURL(officialEntry).href);
86
- const { HarnessSdkJsonRpcServer, Config } = official;
87
-
88
- /** 提问桥超时(P0-6):PI_WEB_DSH_QUESTION_TIMEOUT_MS 可配置,默认 10 分钟。 */
89
- const QUESTION_TIMEOUT_MS = Number(process.env.PI_WEB_DSH_QUESTION_TIMEOUT_MS) || 10 * 60_000;
90
-
91
- /** 工具桥超时(#15):服务端跑插件实现的等待上限。PI_WEB_DSH_TOOL_TIMEOUT_MS 可配置,默认 10 分钟。 */
92
- const TOOL_TIMEOUT_MS = Number(process.env.PI_WEB_DSH_TOOL_TIMEOUT_MS) || 10 * 60_000;
93
-
94
- /** 过滤一条 skill-catalog 用户消息:按 disabled 集合剔除条目并重建文本。
95
- * 纯函数(可单测)。条目来自消息的 `source.entries`(`{name,description}`),
96
- * 文本里的 `<available_skills>…</available_skills>` 块按保留条目重建,其余不动。 */
97
- export function filterSkillCatalogMessage(message, disabled) {
98
- if (!message || message?.source?.kind !== "skill-catalog") return message;
99
- const entries = Array.isArray(message.source?.entries) ? message.source.entries : [];
100
- const kept = entries.filter((e) => e && !disabled.has(e.name));
101
- if (kept.length === entries.length) return message;
102
- const original =
103
- (Array.isArray(message.content) ? message.content.find((b) => b?.type === "text")?.text : undefined) ?? "";
104
- const text = rebuildCatalogText(original, kept);
105
- return {
106
- ...message,
107
- source: { ...message.source, entries: kept },
108
- content: [{ type: "text", text }],
109
- };
110
- }
111
-
112
- /** 重建 `<available_skills>` 块的文本(保留块外结构;无条目时给占位)。 */
113
- function rebuildCatalogText(original, entries) {
114
- const startTag = "<available_skills>";
115
- const endTag = "</available_skills>";
116
- const si = original.indexOf(startTag);
117
- const ei = original.indexOf(endTag);
118
- if (si < 0 || ei < 0) return original;
119
- const body = entries.length
120
- ? entries.map((e) => `- \`${e.name}\`: ${escapeTextSimple(e.description ?? "")}`).join("\n")
121
- : "(本会话无可启用技能)";
122
- return `${original.slice(0, si + startTag.length)}\n${body}\n${original.slice(ei)}`;
123
- }
124
-
125
- /** 最小 HTML 实体转义(避免 `<`/`&` 破坏 markdown/目录结构)。 */
126
- function escapeTextSimple(s) {
127
- return String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
128
- }
129
-
130
- const DSH_VALID_TYPES = new Set(["string", "number", "integer", "boolean", "null", "array", "object", "json"]);
131
-
132
- /**
133
- * 把任意 JSON Schema 节点规整为 DSH schema compiler 支持的纯净 value schema。
134
- * @param {unknown} def 原始属性定义
135
- * @param {boolean} [allowRequired=false] 是否允许 required 字段(仅顶层 property-map 允许)
136
- */
137
- function normalizeDshNode(def, allowRequired = false) {
138
- if (!def || typeof def !== "object" || Array.isArray(def)) {
139
- return { type: "string" };
140
- }
141
-
142
- const out = {};
143
-
144
- // 1. 复制合法的 annotations
145
- if (typeof def.description === "string") out.description = def.description;
146
- if (typeof def.title === "string") out.title = def.title;
147
- if (def.default !== undefined) out.default = def.default;
148
- if (Array.isArray(def.examples)) out.examples = def.examples;
149
- if (allowRequired && def.required === true) out.required = true;
150
-
151
- // 2. 处理 oneOf / anyOf(DSH 仅支持 oneOf,且与 type 互斥)
152
- const unionCandidates = Array.isArray(def.oneOf) ? def.oneOf : Array.isArray(def.anyOf) ? def.anyOf : null;
153
-
154
- if (unionCandidates) {
155
- const branches = unionCandidates.map((branch) => normalizeDshNode(branch, false)).filter(Boolean);
156
- if (branches.length >= 2) {
157
- out.oneOf = branches;
158
- return out;
159
- }
160
- if (branches.length === 1) {
161
- return { ...branches[0], ...out };
162
- }
163
- }
164
-
165
- // 3. 处理 type 字段(可能为数组,如 ["string", "null"])
166
- let rawType = def.type;
167
- if (Array.isArray(rawType)) {
168
- const types = rawType
169
- .map((t) => (typeof t === "string" ? t.toLowerCase().trim() : ""))
170
- .filter((t) => DSH_VALID_TYPES.has(t));
171
- if (types.length >= 2) {
172
- out.oneOf = types.map((t) => {
173
- const branch = { type: t };
174
- if (t === "object") branch.additionalProperties = true;
175
- return branch;
176
- });
177
- return out;
178
- }
179
- rawType = types[0];
180
- }
181
-
182
- let type = typeof rawType === "string" ? rawType.toLowerCase().trim() : undefined;
183
- if (type === "float") type = "number";
184
- else if (type === "int") type = "integer";
185
- else if (type === "bool") type = "boolean";
186
-
187
- if (!type) {
188
- if (def.properties && typeof def.properties === "object") type = "object";
189
- else if (def.items) type = "array";
190
- else type = "string";
191
- }
192
-
193
- if (!DSH_VALID_TYPES.has(type)) {
194
- type = "string";
195
- }
196
-
197
- out.type = type;
198
-
199
- // 4. 根据具体 type 补充/规整专属字段(严格限制在 DSH 允许子集,去除 format/pattern 等不支持属性)
200
- switch (type) {
201
- case "object": {
202
- out.additionalProperties = typeof def.additionalProperties === "boolean" ? def.additionalProperties : true;
203
- if (def.properties && typeof def.properties === "object" && !Array.isArray(def.properties)) {
204
- const nestedProps = {};
205
- const reqList = Array.isArray(def.required) ? def.required : [];
206
- for (const [pKey, pDef] of Object.entries(def.properties)) {
207
- const pNode = normalizeDshNode(pDef, true);
208
- if (reqList.includes(pKey)) pNode.required = true;
209
- nestedProps[pKey] = pNode;
210
- }
211
- out.properties = nestedProps;
212
- }
213
- break;
214
- }
215
- case "array": {
216
- if (def.items && typeof def.items === "object" && !Array.isArray(def.items)) {
217
- out.items = normalizeDshNode(def.items, false);
218
- }
219
- break;
220
- }
221
- case "string":
222
- case "number":
223
- case "integer":
224
- case "boolean":
225
- case "null": {
226
- if (Array.isArray(def.enum) && def.enum.length > 0) {
227
- out.enum = def.enum;
228
- }
229
- if (def.const !== undefined) {
230
- out.const = def.const;
231
- }
232
- break;
233
- }
234
- case "json":
235
- break;
236
- }
237
-
238
- return out;
239
- }
240
-
241
- /** 把 pi-web-ui 插件工具的标准 JSON Schema `parameters`(`{type,properties,required[]}`)
242
- * 转成 DSH defineTool 的 per-property 参数映射 spec(`{key:{type,required?,description}}`)。
243
- * DSH 的 parameterSchemaSpecToJsonSchema 需要 property-map 形状(required 挂在每条属性上),
244
- * 而 pi 插件/TypeBox 用的是标准 JSON Schema(required 是对象数组)。纯函数。 */
245
- export function piParamsToDshSpec(parameters) {
246
- if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) return {};
247
- let propSource;
248
- let requiredList = [];
249
- if (parameters.properties && typeof parameters.properties === "object" && !Array.isArray(parameters.properties)) {
250
- propSource = parameters.properties;
251
- if (Array.isArray(parameters.required)) requiredList = parameters.required;
252
- } else if (parameters.type === "object") {
253
- // 标准 JSON Schema 的无属性对象:{ type: "object" }
254
- return {};
255
- } else {
256
- // 已是 DSH property-map 形状
257
- propSource = parameters;
258
- if (Array.isArray(parameters.required)) requiredList = parameters.required;
259
- }
260
- const propMap = {};
261
- for (const [key, def] of Object.entries(propSource)) {
262
- const node = normalizeDshNode(def, true);
263
- if (requiredList.includes(key)) node.required = true;
264
- propMap[key] = node;
265
- }
266
- return propMap;
267
- }
268
-
269
- /** goal view → RPC 载荷(紧凑 JSON;view 是扁平结构,无目标时 get 返回 undefined)。 */
270
- function viewPayload(view) {
271
- if (!view || view.id === undefined) return { goal: null, activation: null };
272
- return {
273
- goal: {
274
- id: view.id,
275
- revision: view.revision,
276
- objective: view.objective,
277
- phase: view.phase,
278
- maxGoalRounds: view.maxGoalRounds,
279
- ...(view.blockedReason === void 0 ? {} : { blockedReason: view.blockedReason }),
280
- roundsStarted: view.roundsStarted ?? 0,
281
- },
282
- activation: view.activation ?? null,
283
- };
284
- }
285
-
286
- /** 取会话的 live agent(不存在则按需创建,与 prompt 的隐式建会话一致)。 */
287
- function agentOf(server, sessionId) {
288
- return server.getOrCreateSession(sessionId).then((rec) => rec.handle.agent);
289
- }
290
-
291
- /**
292
- * 官方 SDK server 的 goal 扩展:goal/* 方法直连 ctx.goals 服务动词。
293
- */
294
- class DshGoalJsonRpcServer extends HarnessSdkJsonRpcServer {
295
- /**
296
- * 官方构造器订阅 session.event / session.status / subagent.*;这里再加**直播流**:
297
- * 新版 DSH 运行时(0.1.1-rc.2 之后)把逐 chunk 的模型输出发成 agent scope 的
298
- * `agent/assistant-stream` 帧(持久的 `assistant/chunk` 事件已取消),host 侧的
299
- * jsonrpc 面收不到 → pi-web-ui 既没有 streamingMessage / 实时速率,也拿不到
300
- * 逐次调用 usage(底栏上下文占用 / 缓存命中)。
301
- *
302
- * 转成 `assistant.stream` 通知:`{ sessionId, frame }`,frame 是运行时的
303
- * start / chunk / end 三态;chunk 形状与旧 `assistant/chunk.data.chunk` 同构。
304
- *
305
- * `{ global: true }` 是必需的:该事件在 agent scope 派发,host 上注册的观察者
306
- * 不加 global 永远收不到(同 dsh-api-session-controller 的写法)。
307
- */
308
- constructor(ctx, transport, options) {
309
- super(ctx, transport, options);
310
- this.disposers.push(
311
- ctx.on(
312
- "agent/assistant-stream",
313
- ({ agent, frame }) => {
314
- this.transport.notify("assistant.stream", {
315
- sessionId: String(agent.session.id),
316
- frame,
317
- });
318
- },
319
- { global: true },
320
- ),
321
- );
322
- }
323
-
324
- /**
325
- * 创建(或替换已完成的)目标并 arm —— round-driver 会在 agent idle 时
326
- * 自动续第一轮,不需要额外 prompt。
327
- */
328
- async goalSet(params) {
329
- if (typeof params?.sessionId !== "string") throw new TypeError("goal/set requires sessionId");
330
- if (typeof params?.objective !== "string" || !params.objective.trim()) {
331
- throw new TypeError("goal/set requires a non-empty objective");
332
- }
333
- const agent = await agentOf(this, params.sessionId);
334
- const request = { objective: params.objective.trim() };
335
- if (Number.isSafeInteger(params.maxGoalRounds) && params.maxGoalRounds > 0) {
336
- request.maxGoalRounds = params.maxGoalRounds;
337
- }
338
- return viewPayload(this.ctx.goals.create(agent, request));
339
- }
340
-
341
- /** 当前目标视图(goal 或 null)。 */
342
- async goalGet(params) {
343
- if (typeof params?.sessionId !== "string") throw new TypeError("goal/get requires sessionId");
344
- const agent = await agentOf(this, params.sessionId);
345
- return viewPayload(this.ctx.goals.get(agent));
346
- }
347
-
348
- /** 清除当前目标(保留 durable 墓碑与历史)。 */
349
- async goalClear(params) {
350
- if (typeof params?.sessionId !== "string") throw new TypeError("goal/clear requires sessionId");
351
- const agent = await agentOf(this, params.sessionId);
352
- const view = this.ctx.goals.get(agent);
353
- if (view === void 0 || view.id === void 0) return { cleared: false };
354
- this.ctx.goals.clear(agent, { id: view.id, revision: view.revision });
355
- return { cleared: true };
356
- }
357
-
358
- /** 恢复被 disarm 的目标(abort 重启运行时后轮次驱动停止,需要 resume 续)。 */
359
- async goalResume(params) {
360
- if (typeof params?.sessionId !== "string") throw new TypeError("goal/resume requires sessionId");
361
- const agent = await agentOf(this, params.sessionId);
362
- const view = this.ctx.goals.get(agent);
363
- if (view === void 0 || view.id === void 0) throw new Error("no current goal to resume");
364
- return viewPayload(this.ctx.goals.resume(agent, { id: view.id, revision: view.revision }));
365
- }
366
-
367
- /** 编辑目标(改客观文本或轮次上限,不改 phase)。 */
368
- async goalEdit(params) {
369
- if (typeof params?.sessionId !== "string") throw new TypeError("goal/edit requires sessionId");
370
- const agent = await agentOf(this, params.sessionId);
371
- const view = this.ctx.goals.get(agent);
372
- if (view === void 0 || view.id === void 0) throw new Error("no current goal to edit");
373
- const request = {};
374
- if (typeof params?.objective === "string" && params.objective.trim()) {
375
- request.objective = params.objective.trim();
376
- }
377
- if (Number.isSafeInteger(params?.maxGoalRounds) && params.maxGoalRounds > 0) {
378
- request.maxGoalRounds = params.maxGoalRounds;
379
- }
380
- if (request.objective === undefined && request.maxGoalRounds === undefined) {
381
- throw new TypeError("goal/edit requires objective and/or maxGoalRounds");
382
- }
383
- return viewPayload(this.ctx.goals.edit(agent, { id: view.id, revision: view.revision }, request));
384
- }
385
-
386
- // -----------------------------------------------------------------------
387
- // Agent 预设(dsh-web 四模式:standard/ptc/minimal/cordis + 用户自建)。
388
- //
389
- // roster 挂了 preset-plane patch 才存在(见 server/dsh/preset-clones.ts 生成的
390
- // preset-plane.patch.yml);legacy 单组合(无 patch)下全部回退:list 报 unavailable,
391
- // assign/select 透过,创建走官方原逻辑,per-agent 钩子照装(问卷 waterfall 修法
392
- // 本就要求 agent scope 注册,与预设有无无关)。
393
- //
394
- // 约定:Node 侧(dsh-agent-service)是 preset 真源 —— 新会话首个 prompt 前调
395
- // preset/assign 登记,会话创建时消费;空白会话切换走 preset/select(首轮后锁,
396
- // 与官方 agent-preset/locked 语义一致)。RPC 错误不抛 domain 码(transport 统一
397
- // 坍缩成 -32603),一律走 {ok:false,code,message} 信封。
398
- // -----------------------------------------------------------------------
399
-
400
- /** 待消费的创建期预设:sessionId → preset id(创建时消费并删除)。 */
401
- pendingPresets = new Map();
402
- /** minimal 下被门禁的 agent id(bridge 工具 + 问卷调用期拒绝,中英双语报错)。 */
403
- minimalAgents = new Set();
404
- /** 技能目录取数 agent(standard 预设,常驻但永不 prompt,零 token)。 */
405
- inventorySessionId = "pi-webui-inventory";
406
-
407
- /** roster 服务(无 preset-plane patch 时 undefined → 全员 legacy)。 */
408
- presetRoster() {
409
- try {
410
- return this.ctx.get("agentPresets") ?? undefined;
411
- } catch {
412
- return undefined;
413
- }
414
- }
415
-
416
- /** 解析一个 preset id(非法/unknown → 默认;roster 缺失 → undefined)。 */
417
- async resolvePresetId(requested) {
418
- const roster = this.presetRoster();
419
- if (!roster) return undefined;
420
- try {
421
- return (await roster.resolve(requested)).id;
422
- } catch {
423
- try {
424
- return (await roster.resolve()).id;
425
- } catch {
426
- return undefined;
427
- }
428
- }
429
- }
430
-
431
- /** preset/list RPC:roster 名录(display 字段以运行时树为准)。 */
432
- async listPresets() {
433
- const roster = this.presetRoster();
434
- if (!roster) return { presets: [], defaultPreset: "standard", authorable: false, unavailable: true };
435
- try {
436
- // service.list() = discovery 数组;isDefault/authorable 走同名的 getter。
437
- const items = await roster.list();
438
- let defaultId = "standard";
439
- try {
440
- defaultId = roster.defaultId ?? defaultId;
441
- } catch {
442
- /* keep */
443
- }
444
- let authorable = false;
445
- try {
446
- authorable = !!roster.authorable;
447
- } catch {
448
- /* keep */
449
- }
450
- return {
451
- presets: (Array.isArray(items) ? items : []).map((p) => ({
452
- id: p.id,
453
- trust: p.trust,
454
- isDefault: p.id === defaultId,
455
- ...(p.name ? { name: p.name } : {}),
456
- ...(p.description ? { description: p.description } : {}),
457
- ...(Number.isSafeInteger(p.order) ? { order: p.order } : {}),
458
- ...(p.broken ? { broken: p.broken } : {}),
459
- })),
460
- defaultPreset: defaultId,
461
- authorable,
462
- };
463
- } catch (err) {
464
- return {
465
- presets: [],
466
- defaultPreset: "standard",
467
- authorable: false,
468
- unavailable: true,
469
- error: err?.message ?? String(err),
470
- };
471
- }
472
- }
473
-
474
- /** preset/assign RPC:登记创建期预设(首个 prompt/goal 前调用,仅创建时消费)。 */
475
- async assignPreset(params) {
476
- if (typeof params?.sessionId !== "string") throw new TypeError("preset/assign requires sessionId");
477
- if (typeof params?.preset !== "string" || !params.preset) throw new TypeError("preset/assign requires preset");
478
- this.pendingPresets.set(params.sessionId, params.preset);
479
- return { ok: true };
480
- }
481
-
482
- /** agent 存活检查(项目依赖的 0.1.1-rc.2 无基类 assertLiveAgent,内联同语义)。 */
483
- liveAgent(rec, sessionId) {
484
- if (!rec || this.ctx.agents.get(rec.handle.agent.id) !== rec.handle.agent) {
485
- throw new Error(`session agent was disposed outside the server: ${sessionId}`);
486
- }
487
- return rec.handle.agent;
488
- }
489
-
490
- /** preset/select RPC:空白会话切换预设(首轮后官方抛 agent-preset/locked)。 */
491
- async selectPreset(params) {
492
- if (typeof params?.sessionId !== "string") throw new TypeError("preset/select requires sessionId");
493
- if (typeof params?.preset !== "string" || !params.preset) throw new TypeError("preset/select requires preset");
494
- const roster = this.presetRoster();
495
- if (!roster)
496
- return { ok: false, code: "agent-preset/unavailable", message: "agent presets unavailable (legacy runtime)" };
497
- try {
498
- const rec = await this.getOrCreateSession(params.sessionId);
499
- const agent = this.liveAgent(rec, params.sessionId);
500
- const id = await roster.select(agent, params.preset);
501
- this.pendingPresets.delete(params.sessionId);
502
- if (id === "minimal") this.minimalAgents.add(agent.id);
503
- else this.minimalAgents.delete(agent.id);
504
- return { ok: true, preset: id };
505
- } catch (err) {
506
- return { ok: false, code: err?.code ?? "agent-preset/error", message: err?.message ?? String(err) };
507
- }
508
- }
509
-
510
- /** permission/get RPC:读一个会话的权限预设 projection(官方 /permission 弹窗同源)。 */
511
- async getPermission(params) {
512
- if (typeof params?.sessionId !== "string") throw new TypeError("permission/get requires sessionId");
513
- const rec = await this.getOrCreateSession(params.sessionId);
514
- const agent = this.liveAgent(rec, params.sessionId);
515
- const permission = this.ctx.permissionPresets;
516
- if (!permission) throw new Error("permission/get: permission service unavailable");
517
- if (typeof permission.selectFor === "function") {
518
- return permission.selectFor(permission.permissionState(agent.session));
519
- }
520
- const cat = typeof permission.catalog === "function" ? permission.catalog() : {};
521
- const cur = typeof permission.current === "function" ? permission.current(agent.session) : undefined;
522
- return { ...cat, currentValue: cur };
523
- }
524
-
525
- /** permission/set RPC:按会话热切换权限预设(写会话日志,无需重启;
526
- * 与官方 /permission 命令同语义:approval 走 live writer,模型会收到一条
527
- * 策略变更的用户消息)。未知预设走 {ok:false} 信封,不抛 domain 错。 */
528
- async setPermission(params) {
529
- if (typeof params?.sessionId !== "string") throw new TypeError("permission/set requires sessionId");
530
- if (typeof params?.preset !== "string" || !params.preset) throw new TypeError("permission/set requires preset");
531
- const permission = this.ctx.permissionPresets;
532
- if (!permission) throw new Error("permission/set: permission service unavailable");
533
- if (!permission.names.includes(params.preset)) {
534
- return {
535
- ok: false,
536
- code: "permission/unknown-preset",
537
- message: `unknown preset "${params.preset}" (known: ${permission.names.join(", ")})`,
538
- };
539
- }
540
- try {
541
- const rec = await this.getOrCreateSession(params.sessionId);
542
- const agent = this.liveAgent(rec, params.sessionId);
543
- permission.apply(agent.session, params.preset, (policy) => this.ctx.approval.setPolicy(agent, policy));
544
- const snapshot =
545
- typeof permission.selectFor === "function"
546
- ? permission.selectFor(permission.permissionState(agent.session))
547
- : {
548
- ...(typeof permission.catalog === "function" ? permission.catalog() : {}),
549
- currentValue:
550
- typeof permission.current === "function" ? permission.current(agent.session) : params.preset,
551
- };
552
- return {
553
- ok: true,
554
- preset: params.preset,
555
- ...snapshot,
556
- };
557
- } catch (err) {
558
- return { ok: false, code: "permission/error", message: err?.message ?? String(err) };
559
- }
560
- }
561
-
562
- /** preset/tools RPC(仅 DEBUG):读一个会话 agent scope 的实际工具名(校验挂载用)。 */
563
- async presetTools(params) {
564
- if (process.env.PI_WEB_DSH_DEBUG !== "1") {
565
- throw new Error("preset/tools 仅调试可用(服务端需设 PI_WEB_DSH_DEBUG=1)");
566
- }
567
- if (typeof params?.sessionId !== "string") throw new TypeError("preset/tools requires sessionId");
568
- const rec = await this.getOrCreateSession(params.sessionId);
569
- const agent = this.liveAgent(rec, params.sessionId);
570
- // agent 视角(scope):preset 层 + host 层合并目录;缺省全局视角只看到 host 层。
571
- const schemas = this.ctx.tools.schemas(agent);
572
- return { tools: schemas.map((s) => s.name).sort() };
573
- }
574
-
575
- /** prompt/inspect RPC:返回系统提示词全文、分段(sections)、上下文(contexts)与工具 schemas。 */
576
- async promptInspect(params) {
577
- let context = {};
578
- if (typeof params?.sessionId === "string" && params.sessionId) {
579
- try {
580
- const rec = await this.getOrCreateSession(params.sessionId);
581
- const agent = this.liveAgent(rec, params.sessionId);
582
- context = { agent, scope: agent };
583
- } catch {
584
- /* ignore */
585
- }
586
- }
587
- if (!context.agent) {
588
- try {
589
- const agent = await this.ensureInventoryAgent();
590
- context = { agent, scope: agent };
591
- } catch {
592
- /* ignore */
593
- }
594
- }
595
- const contexts = context.agent
596
- ? [{ agent: context.agent, scope: context.agent }, { scope: context.agent }, { scope: context.agent.ctx }, {}]
597
- : [{}];
598
- let asm = null;
599
- let lastErr = null;
600
- for (const ctx of contexts) {
601
- try {
602
- asm = await this.ctx.systemPrompt.assemble(ctx);
603
- if (asm) break;
604
- } catch (err) {
605
- lastErr = err;
606
- }
607
- }
608
- if (!asm) {
609
- return {
610
- prompt: "",
611
- sections: [],
612
- contexts: [],
613
- tools: [],
614
- error: String(lastErr?.message ?? lastErr ?? "assembly failed"),
615
- };
616
- }
617
- const sections = Array.isArray(asm.sections)
618
- ? asm.sections.map((s) => ({
619
- name: s.name,
620
- text: typeof s.text === "string" ? s.text : String(s.text ?? ""),
621
- chars: String(s.text ?? "").length,
622
- }))
623
- : [];
624
- const promptContexts = Array.isArray(asm.contexts)
625
- ? asm.contexts.map((c) => ({
626
- name: c.name,
627
- text: typeof c.text === "string" ? c.text : String(c.text ?? ""),
628
- chars: String(c.text ?? "").length,
629
- }))
630
- : [];
631
- const tools = Array.isArray(asm.tools)
632
- ? asm.tools.map((t) => ({
633
- name: t.name,
634
- description: t.description,
635
- parameters: t.parameters,
636
- }))
637
- : [];
638
- const sectionTexts = sections.map((s) => s.text).filter(Boolean);
639
- let fullPrompt = sectionTexts.join("\n\n");
640
- if (promptContexts.length > 0) {
641
- const ctxBody = promptContexts
642
- .map((c) => c.text)
643
- .filter(Boolean)
644
- .join("\n\n");
645
- if (ctxBody) {
646
- fullPrompt +=
647
- (fullPrompt ? "\n\n" : "") +
648
- `Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\n${ctxBody}`;
649
- }
650
- }
651
- return {
652
- prompt: fullPrompt,
653
- sections,
654
- contexts: promptContexts,
655
- tools,
656
- };
657
- }
658
-
659
- /** debug/assemble RPC(仅 DEBUG):读一个会话 agent 视角的系统提示词 section 名录
660
- * (零 token 验证 persona 遮蔽/complete 压制/自定义 section 用;不返回正文)。 */
661
- async debugAssemble(params) {
662
- if (process.env.PI_WEB_DSH_DEBUG !== "1") {
663
- throw new Error("debug/assemble 仅调试可用(服务端需设 PI_WEB_DSH_DEBUG=1)");
664
- }
665
- if (typeof params?.sessionId !== "string") throw new TypeError("debug/assemble requires sessionId");
666
- const rec = await this.getOrCreateSession(params.sessionId);
667
- const agent = this.liveAgent(rec, params.sessionId);
668
- // 组装上下文同 agent-loop(assembleContextFor):{ agent, scope: agent }。
669
- const contexts = [{ agent, scope: agent }, { scope: agent }, { scope: agent.ctx }];
670
- let lastErr = null;
671
- for (const context of contexts) {
672
- try {
673
- const asm = await this.ctx.systemPrompt.assemble(context);
674
- if (asm && Array.isArray(asm.sections)) {
675
- return { sections: asm.sections.map((s) => ({ name: s.name, chars: String(s.text ?? "").length })) };
676
- }
677
- } catch (err) {
678
- lastErr = err;
679
- }
680
- }
681
- throw new Error(`debug/assemble: assembly failed (${lastErr?.message ?? lastErr})`);
682
- }
683
-
684
- /** 会话创建(官方同形 + setup):mount 预设 + 装 per-agent 钩子。
685
- * 磁盘上已有同 id(运行时重启/优雅关闭后重建)→ 转 agents.resume
686
- * (官方恢复路径,自动缝合被中断的 turn;setup 照跑,预设照挂)。 */
687
- async createSession(sessionId, preset) {
688
- const requested = preset ?? this.pendingPresets.get(sessionId);
689
- this.pendingPresets.delete(sessionId);
690
- const resolved = await this.resolvePresetId(requested);
691
- const agentOptions = {
692
- provider: this.provider,
693
- model: this.model,
694
- ...(this.reasoningEffort === void 0 ? {} : { reasoningEffort: this.reasoningEffort }),
695
- ...(this.maxTokens === void 0 ? {} : { maxTokens: this.maxTokens }),
696
- };
697
- const setup = async (agentCtx, agent) => this.agentSetup(agentCtx, agent, resolved);
698
- let handle;
699
- try {
700
- handle = await this.ctx.agents.create({
701
- sessionId,
702
- meta: { cwd: this.cwd, ...(resolved ? { agentPreset: resolved } : {}) },
703
- agentOptions,
704
- setup,
705
- });
706
- } catch (err) {
707
- if (typeof err?.message === "string" && err.message.includes(`session "${sessionId}" already exists`)) {
708
- process.stderr.write(`[pi-web-ui-dsh] 会话 ${sessionId} 已在磁盘,resume 恢复\n`);
709
- handle = await this.ctx.agents.resume({ resumeSessionId: sessionId, agentOptions, setup });
710
- } else {
711
- throw err;
712
- }
713
- }
714
- const rec = { handle };
715
- this.sessions.set(sessionId, rec);
716
- return rec;
717
- }
718
-
719
- /** 官方 getOrCreateSession 同形(多出来的 preset 参数供创建时使用)。 */
720
- async getOrCreateSession(sessionId, preset) {
721
- if (this.shuttingDown) throw new Error("SDK server is shutting down");
722
- const existing = this.sessions.get(sessionId);
723
- if (existing) return existing;
724
- const pending = this.sessionCreations.get(sessionId);
725
- if (pending) return pending;
726
- const creation = this.createSession(sessionId, preset);
727
- this.sessionCreations.set(sessionId, creation);
728
- creation.then(
729
- () => {
730
- this.sessionCreations.delete(sessionId);
731
- },
732
- () => {
733
- this.sessionCreations.delete(sessionId);
734
- },
735
- );
736
- return creation;
737
- }
738
-
739
- /** 每个 agent 出生时跑一次:mount 预设 + 问卷 waterfall + 技能目录过滤。
740
- * 预设优先级:会话记录(header/selected 事件,重启恢复时是唯一真相)>
741
- * 创建参数 > roster 默认。 */
742
- async agentSetup(agentCtx, agent, presetId) {
743
- const roster = this.presetRoster();
744
- let effective = presetId;
745
- if (roster) {
746
- try {
747
- const prior = this.ctx.sessionProjections.stateOf(agent.session, "agentPreset");
748
- if (typeof prior === "string" && prior) effective = prior;
749
- } catch {
750
- /* 无 projection 能力 → 用创建参数 */
751
- }
752
- }
753
- if (roster && effective) {
754
- try {
755
- await roster.mount(agentCtx, effective);
756
- if (effective === "minimal") this.minimalAgents.add(agent.id);
757
- } catch (err) {
758
- process.stderr.write(
759
- `[pi-web-ui-dsh] preset "${effective}" mount 失败,转 host 直连: ${err?.message ?? err}\n`,
760
- );
761
- }
762
- }
763
- // 问卷 waterfall(P0 修法):answerer 必须挂 agent scope —— host 层收不到
764
- // agent-scoped 事件,且新版 UserQuestionService 已删 registerProvider。
765
- // 与官方 ui-user-questions 同构:返回 {answers} 即 short-circuit。
766
- agentCtx.on("user-questions/request", (request, _next) => this.answerScopedQuestion(agent, request));
767
- // 技能目录过滤:与上面同理,host 版已死(收不到事件),改挂 agent scope。
768
- // eslint-disable-next-line no-empty-pattern -- only next is needed
769
- agentCtx.on("agent/pre-step", async ({}, next) => {
770
- const decision = await next();
771
- if (this.disabledSkills.size && decision?.kind === "enter" && Array.isArray(decision.messages)) {
772
- if (decision.messages.some((m) => m?.source?.kind === "skill-catalog")) {
773
- decision.messages = decision.messages.map((m) => filterSkillCatalogMessage(m, this.disabledSkills));
774
- }
775
- }
776
- return decision;
777
- });
778
- }
779
-
780
- /** agent scope 的问卷 answerer:minimal 门禁 → 浏览器桥(复用排队逻辑)。 */
781
- async answerScopedQuestion(agent, request) {
782
- if (this.minimalAgents.has(agent?.id)) {
783
- throw new Error(
784
- "ask_user_question is unavailable under the minimal preset; use the shell instead " +
785
- "(极简模式下不可提问,请直接用 shell 命令推进)",
786
- );
787
- }
788
- if (request?.signal?.aborted) throw new Error("ask_user_question aborted(提问已中止)");
789
- return this.askUser(request ?? {});
790
- }
791
-
792
- /** 技能目录取数 agent(standard 常驻,永不 prompt;roster 缺失时不用)。 */
793
- async ensureInventoryAgent() {
794
- const rec = await this.getOrCreateSession(this.inventorySessionId);
795
- return this.liveAgent(rec, this.inventorySessionId);
796
- }
797
-
798
- /** 方法分发:goal/* 与 attachment/* 走上面/下面,其余交官方。 */
799
- async handleRequest(method, params) {
800
- switch (method) {
801
- case "goal/set":
802
- return this.goalSet(params);
803
- case "goal/get":
804
- return this.goalGet(params);
805
- case "goal/clear":
806
- return this.goalClear(params);
807
- case "goal/resume":
808
- return this.goalResume(params);
809
- case "goal/edit":
810
- return this.goalEdit(params);
811
- case "attachment/save":
812
- return this.attachmentSave(params);
813
- case "attachment/read":
814
- return this.attachmentRead(params);
815
- case "question/answer":
816
- return this.answerQuestion(params);
817
- case "model/list":
818
- return this.listModels(params);
819
- case "tools/sync":
820
- return this.syncTools(params);
821
- case "tools/list":
822
- return this.listTools();
823
- case "tools/call-result":
824
- return this.toolsCallResult(params);
825
- case "tools/invoke":
826
- return this.toolsInvoke(params);
827
- case "skills/list":
828
- return this.listSkills();
829
- case "skills/set-disabled":
830
- return this.setDisabledSkills(params);
831
- case "skills/register":
832
- return this.registerSkill(params);
833
- case "skills/get":
834
- return this.getSkill(params);
835
- case "preset/list":
836
- return this.listPresets();
837
- case "preset/assign":
838
- return this.assignPreset(params);
839
- case "preset/select":
840
- return this.selectPreset(params);
841
- case "permission/get":
842
- return this.getPermission(params);
843
- case "permission/set":
844
- return this.setPermission(params);
845
- case "preset/tools":
846
- return this.presetTools(params);
847
- case "prompt/inspect":
848
- return this.promptInspect(params);
849
- case "debug/assemble":
850
- return this.debugAssemble(params);
851
- default:
852
- return super.handleRequest(method, params);
853
- }
854
- }
855
-
856
- /** P2-17 模型目录动态化:查询 adapter(ctx.llm)的真实模型清单。
857
- * dsh-llm-deepseek 的 listModels 返回模型目录(含 inputModalities),
858
- * 失败时返回空数组(服务端回退本地表)。 */
859
- async listModels(params) {
860
- try {
861
- const providerId = params?.provider ?? "deepseek-official";
862
- const models = await this.ctx.llm.listModels?.(providerId);
863
- if (!Array.isArray(models)) return { models: [] };
864
- return {
865
- models: models.map((m) => ({
866
- id: m.id,
867
- ...(m.name ? { name: m.name } : {}),
868
- ...(Array.isArray(m.inputModalities)
869
- ? { inputModalities: m.inputModalities }
870
- : Array.isArray(m.input)
871
- ? { inputModalities: m.input }
872
- : {}),
873
- })),
874
- };
875
- } catch (err) {
876
- return { models: [], error: err?.message ?? String(err) };
877
- }
878
- }
879
-
880
- // -----------------------------------------------------------------------
881
- // 用户提问桥(交互式调研/确认):模型调 ask_user_question 工具 →
882
- // ctx.userQuestions.ask() 阻塞 → 本 provider 把问题发给浏览器 →
883
- // question/answer RPC 带回答案 → 工具结果恢复模型循环。
884
- // -----------------------------------------------------------------------
885
-
886
- /** 挂起的提问 + 排队(apply 注册 provider 时初始化)。一次只向浏览器展示一个。 */
887
- questionBridge = { pending: null, queue: [] };
888
-
889
- // -----------------------------------------------------------------------
890
- // 工具桥(#15 插件注入点):把 pi-web-ui 插件 AI 工具(registerAgentTool)
891
- // 桥成 DSH 原生工具。服务端 tools/sync 注册 defineTool(trampoline execute),
892
- // 模型调用时 trampoline 发 tools.call.request 通知 → 服务端跑插件实现 →
893
- // tools/call-result RPC 恢复工具结果。
894
- // -----------------------------------------------------------------------
895
-
896
- /** 挂起的桥接调用:callId → { resolve, reject }(超时/中止统一拒)。 */
897
- toolsPending = new Map();
898
- /** 已注册工具的卸装回调(工具列表变化时先卸再重注册,last-write-wins 覆盖)。 */
899
- toolUnregisters = [];
900
-
901
- /** 注册(或替换)一批插件工具为 DSH 原生工具。返回当前注册清单。 */
902
- async syncTools(params) {
903
- const tools = Array.isArray(params?.tools) ? params.tools : [];
904
- for (const off of this.toolUnregisters) {
905
- try {
906
- off();
907
- } catch {
908
- /* re-register 前的卸载不阻断 */
909
- }
910
- }
911
- this.toolUnregisters = [];
912
- const registered = [];
913
- for (const t of tools) {
914
- if (!t || typeof t.name !== "string" || typeof t.description !== "string") continue;
915
- try {
916
- const tool = defineTool({
917
- name: t.name,
918
- description: t.description,
919
- parameters: piParamsToDshSpec(t.parameters),
920
- output: {
921
- schema: { type: "string" },
922
- render: (_args, value) => [{ type: "text", text: String(value ?? "") }],
923
- },
924
- execute: (args, exec) => this.invokeBridgedTool(exec, t.name, args),
925
- });
926
- const off = this.ctx.tools.register(tool);
927
- this.toolUnregisters.push(off);
928
- registered.push(t.name);
929
- } catch (err) {
930
- console.warn(`[dsh] 工具 ${t.name} 注册跳过:`, err?.message ?? err);
931
- }
932
- }
933
- return { registered, count: registered.length };
934
- }
935
-
936
- /** 列出运行时当前可见的工具 schema(供零 key 验证/调试)。 */
937
- async listTools() {
938
- const schemas = this.ctx.tools.schemas();
939
- return {
940
- tools: schemas.map((s) => ({
941
- name: s.name,
942
- description: s.description,
943
- parameters: s.parameters,
944
- })),
945
- };
946
- }
947
-
948
- /** 桥接工具的 execute:minimal 门禁后把调用发给服务端并 await 结果。 */
949
- invokeBridgedTool(exec, name, args) {
950
- const agentId = exec?.agent?.id;
951
- if (agentId !== undefined && this.minimalAgents.has(agentId)) {
952
- return Promise.reject(
953
- new Error(
954
- `工具 ${name} unavailable under the minimal preset; use the shell instead ` +
955
- `(极简模式下该插件工具不可用,请用 shell 命令推进)`,
956
- ),
957
- );
958
- }
959
- const id = `t-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
960
- const sessionId =
961
- exec?.agent?.session?.id && typeof exec.agent.session.id === "string" ? String(exec.agent.session.id) : undefined;
962
- return new Promise((resolve, reject) => {
963
- let done = false;
964
- const cleanup = () => {
965
- if (exec?.signal) exec.signal.removeEventListener("abort", onAbort);
966
- };
967
- const settle = (err, result) => {
968
- if (done) return;
969
- done = true;
970
- cleanup();
971
- clearTimeout(timer);
972
- if (err) reject(err);
973
- else resolve(result);
974
- };
975
- const onAbort = () => {
976
- this.toolsPending.delete(id);
977
- settle(new Error(`工具 ${name} 已中止`));
978
- };
979
- const timer = setTimeout(() => {
980
- this.toolsPending.delete(id);
981
- settle(new Error(`工具 ${name} 执行超时(等待服务端响应)`));
982
- }, TOOL_TIMEOUT_MS);
983
- timer.unref?.();
984
- this.toolsPending.set(id, {
985
- resolve: (result) => settle(null, result),
986
- reject: (err) => settle(err),
987
- });
988
- exec?.signal?.addEventListener("abort", onAbort, { once: true });
989
- this.transport.notify("tools.call.request", {
990
- id,
991
- name,
992
- args,
993
- ...(sessionId ? { sessionId } : {}),
994
- });
995
- });
996
- }
997
-
998
- /** 调试/probe 用:绕过模型直接触发一个已注册桥接工具的完整往返
999
- * (trampoline → tools.call.request → tools/call-result 恢复)。仅 PI_WEB_DSH_DEBUG=1 可用。 */
1000
- async toolsInvoke(params) {
1001
- if (process.env.PI_WEB_DSH_DEBUG !== "1") {
1002
- throw new Error("tools/invoke 仅调试可用(服务端需设 PI_WEB_DSH_DEBUG=1)");
1003
- }
1004
- const name = params?.name;
1005
- if (typeof name !== "string") return { ok: false, error: "tools/invoke requires name" };
1006
- const tool = this.ctx.tools.get(name);
1007
- if (!tool) return { ok: false, error: `tools/invoke: 工具未注册 ${name}` };
1008
- const exec = { signal: new AbortController().signal };
1009
- try {
1010
- const value = await tool.execute(params?.args ?? {}, exec);
1011
- return { ok: true, value };
1012
- } catch (err) {
1013
- return { ok: false, error: err?.message ?? String(err) };
1014
- }
1015
- }
1016
-
1017
- /** tools/call-result RPC:服务端跑完插件实现后回传结果,恢复桥接调用。 */
1018
- async toolsCallResult(params) {
1019
- const id = params?.id;
1020
- if (typeof id !== "string") throw new TypeError("tools/call-result requires id");
1021
- const pending = this.toolsPending.get(id);
1022
- if (!pending) throw new Error(`tools/call-result 无匹配 id=${id}`);
1023
- this.toolsPending.delete(id);
1024
- if (params?.isError) pending.reject(new Error(params?.result ?? "工具执行失败"));
1025
- else pending.resolve(params?.result ?? "");
1026
- return { ok: true };
1027
- }
1028
-
1029
- // -----------------------------------------------------------------------
1030
- // 技能 RPC(#18 技能启停 UI):暴露 SkillRegistry list/get + 设置禁用集合
1031
- // (晚 pre-step 钩子用它过滤 skill-catalog 消息)。
1032
- // -----------------------------------------------------------------------
1033
-
1034
- /** 禁用的技能名集合(skills/set-disabled 更新)。 */
1035
- disabledSkills = new Set();
1036
-
1037
- /** 列出运行时当前可见技能:roster 下读常驻 inventory agent 的合并目录(技能只活在
1038
- * 各预设的 agent 层,host 的 skill-filesystem 已 disable,host 直读恒为空);
1039
- * legacy 下保持原来的 host 直读。零 key 校验/前端显示用。 */
1040
- async listSkills() {
1041
- const roster = this.presetRoster();
1042
- if (roster) {
1043
- try {
1044
- const agent = await this.ensureInventoryAgent();
1045
- // scope 视图:host registry + agent 层合并;cwd 选工作区根。
1046
- const skills = await this.ctx.skills.list({ scope: agent, cwd: this.cwd });
1047
- if (Array.isArray(skills)) {
1048
- return {
1049
- skills: skills.map((s) => ({
1050
- name: s.name,
1051
- description: s.description ?? "",
1052
- ...(s.invocation ? { invocation: s.invocation } : {}),
1053
- })),
1054
- };
1055
- }
1056
- } catch (err) {
1057
- return { skills: [], error: err?.message ?? String(err) };
1058
- }
1059
- return { skills: [] };
1060
- }
1061
- try {
1062
- const skills = await this.ctx.skills.list();
1063
- if (!Array.isArray(skills)) return { skills: [] };
1064
- return {
1065
- skills: skills.map((s) => ({
1066
- name: s.name,
1067
- description: s.description ?? "",
1068
- ...(s.invocation ? { invocation: s.invocation } : {}),
1069
- })),
1070
- };
1071
- } catch (err) {
1072
- return { skills: [], error: err?.message ?? String(err) };
1073
- }
1074
- }
1075
-
1076
- /** 读取单个技能的完整定义(SkillRegistry.get)。 */
1077
- async getSkill(params) {
1078
- if (typeof params?.name !== "string") throw new TypeError("skills/get requires name");
1079
- const skill = await this.ctx.skills.get(params.name);
1080
- return { skill: skill ?? null };
1081
- }
1082
-
1083
- /** 切换一个技能的可见性(服务端 set_settings.disabledSkills 变化时推送)。 */
1084
- async setDisabledSkills(params) {
1085
- const names = Array.isArray(params?.skills) ? params.skills : [];
1086
- this.disabledSkills = new Set(names.map((n) => String(n)));
1087
- return { disabled: [...this.disabledSkills] };
1088
- }
1089
-
1090
- /** 调试/probe 用:注册一个运行时技能(SkillRegistry.register),仅 DEBUG 可用。 */
1091
- async registerSkill(params) {
1092
- if (process.env.PI_WEB_DSH_DEBUG !== "1") throw new Error("skills/register 仅调试可用");
1093
- if (typeof params?.name !== "string" || !params.name.trim()) {
1094
- throw new TypeError("skills/register requires name");
1095
- }
1096
- const reg = this.ctx.skills.register({
1097
- name: params.name.trim(),
1098
- description: typeof params?.description === "string" ? params.description : "",
1099
- invocation: { modelInvocable: true, userInvocable: false },
1100
- source: "runtime",
1101
- content: typeof params?.content === "string" ? params.content : "(test skill)",
1102
- });
1103
- return { ok: true, unregister: typeof reg === "function" };
1104
- }
1105
-
1106
- /** 把队首提问变为 pending(发通知给浏览器)。 */
1107
- dispatchNextQuestion() {
1108
- if (this.questionBridge.pending) return;
1109
- const next = this.questionBridge.queue.shift();
1110
- if (!next) return;
1111
- this.transport.notify("question.pending", {
1112
- id: next.qid,
1113
- questions: next.questions,
1114
- deadline: next.deadline,
1115
- });
1116
- this.questionBridge.pending = { qid: next.qid, resolve: next.resolve, reject: next.reject };
1117
- }
1118
-
1119
- /** ctx.userQuestions provider:把问题桥到客户端并等待答案。
1120
- * P2-20:并发 ask() 排队(深度 3),当前提问回答后自动发下一个。 */
1121
- async askUser(request) {
1122
- const questions = (request?.questions ?? []).map((q) => ({
1123
- id: q.id,
1124
- question: q.question,
1125
- ...(q.detail ? { detail: q.detail } : {}),
1126
- ...(q.header ? { header: q.header } : {}),
1127
- ...(q.options ? { options: q.options } : {}),
1128
- ...(q.multiSelect ? { multiSelect: q.multiSelect } : {}),
1129
- }));
1130
- if (questions.length === 0) throw new Error("ask_user_question requires at least one question");
1131
- const qid = `q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1132
- const deadline = Date.now() + QUESTION_TIMEOUT_MS;
1133
- return new Promise((resolve, reject) => {
1134
- const timer = setTimeout(() => {
1135
- const queued = this.questionBridge.queue.findIndex((q) => q.qid === qid);
1136
- if (queued >= 0) {
1137
- this.questionBridge.queue.splice(queued, 1);
1138
- // #459:排队条目超时也必须 settle——此前只 splice 不 reject,
1139
- // 该 ask 的 Promise 永不落定,agent-loop 卡死在工具调用上。
1140
- reject(new Error("提问超时(等待回答过久)"));
1141
- return;
1142
- }
1143
- if (this.questionBridge.pending?.qid === qid) {
1144
- this.questionBridge.pending = null;
1145
- reject(new Error("提问超时(等待回答过久)"));
1146
- // #459:pending 腾出后必须派发下一个排队提问——否则队列无人派发,
1147
- // 后续条目只能等各自超时且永不 settle,整条提问桥永久停摆。
1148
- this.dispatchNextQuestion();
1149
- }
1150
- }, QUESTION_TIMEOUT_MS);
1151
- timer.unref?.();
1152
- const entry = {
1153
- qid,
1154
- questions,
1155
- deadline,
1156
- resolve: (answers) => {
1157
- clearTimeout(timer);
1158
- resolve(answers);
1159
- },
1160
- reject: (err) => {
1161
- clearTimeout(timer);
1162
- reject(err);
1163
- },
1164
- };
1165
- if (this.questionBridge.pending || this.questionBridge.queue.length > 0) {
1166
- // 已有提问在展示 → 排队;深度 3,满则拒绝(模型会收到工具报错继续)。
1167
- if (this.questionBridge.queue.length >= 3) {
1168
- clearTimeout(timer);
1169
- reject(new Error("提问排队已满(最多 3 个),请先回答当前提问"));
1170
- return;
1171
- }
1172
- this.questionBridge.queue.push(entry);
1173
- } else {
1174
- // 无 pending → 立即发通知并等待。
1175
- this.transport.notify("question.pending", { id: qid, questions, deadline });
1176
- this.questionBridge.pending = { qid, resolve: entry.resolve, reject: entry.reject };
1177
- }
1178
- });
1179
- }
1180
-
1181
- /** question/answer RPC:前端提交答案(或取消)。回答后自动发队列里的下一个。 */
1182
- async answerQuestion(params) {
1183
- const pending = this.questionBridge.pending;
1184
- if (!pending || pending.qid !== params?.id) {
1185
- throw new Error(`question/answer 不匹配(id=${params?.id})`);
1186
- }
1187
- this.questionBridge.pending = null;
1188
- if (params?.cancelled) {
1189
- const reason =
1190
- typeof params?.cancelReason === "string" && params.cancelReason.trim()
1191
- ? `(附言:${params.cancelReason.trim()})`
1192
- : "";
1193
- pending.reject(new Error(`用户取消了提问${reason}`));
1194
- } else {
1195
- const answers = Array.isArray(params?.answers) ? params.answers : [];
1196
- pending.resolve({ answers });
1197
- }
1198
- this.dispatchNextQuestion();
1199
- return { ok: true };
1200
- }
1201
-
1202
- // -----------------------------------------------------------------------
1203
- // 附件 RPC(视觉桥):base64 图片 → durable ref;ref → base64 回读。
1204
- // 模型请求侧的 image 块由 dsh-llm-deepseek adapter 自动解析 ref(file-id/inline)。
1205
- // -----------------------------------------------------------------------
1206
-
1207
- /** 保存一张 base64 图片到附件存储(ctx.attachments,dsh-attachment-local 后端)。 */
1208
- async attachmentSave(params) {
1209
- const mediaType = params?.mediaType;
1210
- if (typeof mediaType !== "string" || !/^image\/(png|jpeg|webp|gif)$/u.test(mediaType)) {
1211
- throw new TypeError("attachment/save requires mediaType (image/png|jpeg|webp|gif)");
1212
- }
1213
- if (typeof params?.data !== "string" || !params.data) {
1214
- throw new TypeError("attachment/save requires base64 data");
1215
- }
1216
- const bytes = new Uint8Array(Buffer.from(params.data, "base64"));
1217
- if (bytes.length === 0) throw new TypeError("attachment/save: empty image data");
1218
- const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024; // 20MB 上限
1219
- if (bytes.length > MAX_ATTACHMENT_BYTES) {
1220
- throw new RangeError(`attachment/save: image data exceeds 20MB limit (${bytes.length} bytes)`);
1221
- }
1222
- const ref = await this.ctx.attachments.saveImage({
1223
- data: bytes,
1224
- mediaType,
1225
- ...(typeof params?.name === "string" && params.name ? { name: params.name } : {}),
1226
- });
1227
- return { ref };
1228
- }
1229
-
1230
- /** 按 ref 回读规范化后的图片字节(base64),供前端回放显示。 */
1231
- async attachmentRead(params) {
1232
- const ref = params?.ref;
1233
- if (!ref || typeof ref?.attachmentId !== "string" || typeof ref?.mediaType !== "string") {
1234
- throw new TypeError("attachment/read requires ref (attachmentId + mediaType)");
1235
- }
1236
- const stored = await this.ctx.attachments.readImage(ref);
1237
- return {
1238
- mediaType: stored.ref?.mediaType ?? ref.mediaType,
1239
- data: Buffer.from(stored.data).toString("base64"),
1240
- };
1241
- }
1242
- }
1243
-
1244
- /**
1245
- * 插件 apply:transport 接线 / shutdown 语义与官方一致,server 换成本地扩展类。
1246
- * 保持 named exports(无 default),Loader unwrapExports 需要 name/inject/Config/apply。
1247
- */
1248
- function apply(ctx, config) {
1249
- const resolvedConfig = config;
1250
- const rootFiber = ctx.root.fiber;
1251
- /* v8 ignore next -- production stdio wiring */
1252
- const input = config.input ?? process.stdin;
1253
- /* v8 ignore next -- production stdio wiring */
1254
- const output = config.output ?? process.stdout;
1255
- /* v8 ignore next -- production exit wiring */
1256
- const exit =
1257
- config.exit ??
1258
- ((code) => {
1259
- process.exit(code);
1260
- });
1261
- const transport = new JsonRpcLineTransport(input, output);
1262
- const server = new DshGoalJsonRpcServer(ctx, transport, {
1263
- maxTokensAsSuccess: resolvedConfig.maxTokensAsSuccess,
1264
- });
1265
- // 问卷/技能目录钩子不再挂 host:agent-scoped 事件 host 收不到(且新版
1266
- // UserQuestionService 已删 registerProvider,旧写法直接导致 boot 失败)。
1267
- // 二者改由每次会话创建的 setup() 挂到 agent scope(见 agentSetup)。
1268
- let exitTask;
1269
- const disposeAndExit = () => {
1270
- exitTask ??= (async () => {
1271
- await Promise.allSettled([Promise.resolve().then(() => transport.flush())]);
1272
- await Promise.allSettled([Promise.resolve().then(() => rootFiber.dispose())]);
1273
- exit(0);
1274
- })();
1275
- return exitTask;
1276
- };
1277
- transport.onRequest(async (method, params) => {
1278
- if (method === "initialize") await ctx.get("loader")?.await();
1279
- const result = await server.handleRequest(method, params);
1280
- if (method === "shutdown")
1281
- setImmediate(() => {
1282
- disposeAndExit();
1283
- });
1284
- return result;
1285
- });
1286
- ctx.effect(() => {
1287
- transport.start();
1288
- return async () => {
1289
- await server.shutdown();
1290
- transport.close();
1291
- };
1292
- }, "jsonrpc.serve");
1293
- }
1294
-
1295
- const name = "sdk-jsonrpc-server";
1296
- const inject = [
1297
- "agents",
1298
- "goals",
1299
- "attachments",
1300
- "userQuestions",
1301
- "llm",
1302
- "tools",
1303
- "skills",
1304
- "systemPrompt",
1305
- "permissionPresets",
1306
- "approval",
1307
- ];
1308
-
1309
- export { Config, apply, inject, name };
1
+ /**
2
+ * goal-rpc.mjs — pi-web-ui DSH runtime 的 goal RPC 扩展插件。
3
+ *
4
+ * 在官方 dsh-sdk-jsonrpc-server 之上包一层,为 stdio JSON-RPC 面增加 goal
5
+ * 方法(goal/set goal/get goal/clear goal/resume goal/edit),直连 DSH 原生
6
+ * goal 域(ctx.goals 服务,dsh-goal)。这样 pi-web-ui 前端的目标条驱动的是
7
+ * DSH 自己的持久化目标状态机 + goal-round-driver 自动轮次,而不是另造一套
8
+ * 审查会话 —— 审查语义 = DSH 原生(模型自判定 complete/blocked,轮次自动续)。
9
+ *
10
+ * 与官方插件的差异:inject 增加 "goals"(goal 域服务依赖);handleRequest
11
+ * 增加 goal 分支;其余 stdio transport / shutdown 语义原样继承。
12
+ *
13
+ * 官方入口(做 base 类)从环境变量解析:PI_WEB_DSH_JSONRPC_ENTRY 由 dsh-client
14
+ * 注入(指向项目 node_modules 的官方包);兜底从本文件位置向上找项目依赖。
15
+ */
16
+ import { resolve } from "node:path";
17
+ import { dirname, join } from "node:path";
18
+ import { fileURLToPath, pathToFileURL } from "node:url";
19
+ import { existsSync } from "node:fs";
20
+ import { resolveRuntimeBase } from "./runtime-root.mjs";
21
+
22
+ const HERE = dirname(fileURLToPath(import.meta.url));
23
+
24
+ if (!process.env.PI_WEB_DSH_RUNTIME_BASE) {
25
+ try {
26
+ const detected = await resolveRuntimeBase();
27
+ if (detected) process.env.PI_WEB_DSH_RUNTIME_BASE = detected;
28
+ } catch {}
29
+ }
30
+
31
+ /** 动态解析并加载 DSH 相关模块(优先使用当前正在运行的运行时树,兜底本地依赖) */
32
+ async function loadDshModule(pkgName) {
33
+ const rt = process.env.PI_WEB_DSH_RUNTIME_BASE;
34
+ if (rt) {
35
+ const candidate = join(rt, pkgName, "lib", "index.js");
36
+ if (existsSync(candidate)) {
37
+ return import(pathToFileURL(candidate).href);
38
+ }
39
+ }
40
+ let cur = HERE;
41
+ for (let i = 0; i < 6; i++) {
42
+ const candidate = join(cur, "node_modules", pkgName, "lib", "index.js");
43
+ if (existsSync(candidate)) {
44
+ return import(pathToFileURL(candidate).href);
45
+ }
46
+ cur = dirname(cur);
47
+ }
48
+ return import(pkgName);
49
+ }
50
+
51
+ const { JsonRpcLineTransport } = await loadDshModule("@deepseek-ai/dsh-sdk-protocol");
52
+ const { defineTool } = await loadDshModule("@deepseek-ai/dsh-tools");
53
+
54
+ /** 官方 jsonrpc-server 入口(优先运行时树,次选 env,兜底从项目依赖向上找)。 */
55
+ function findOfficialEntry() {
56
+ if (process.env.PI_WEB_DSH_RUNTIME_BASE) {
57
+ const candidate = join(
58
+ process.env.PI_WEB_DSH_RUNTIME_BASE,
59
+ "@deepseek-ai",
60
+ "dsh-sdk-jsonrpc-server",
61
+ "lib",
62
+ "index.js",
63
+ );
64
+ if (existsSync(candidate)) return candidate;
65
+ }
66
+ if (process.env.PI_WEB_DSH_JSONRPC_ENTRY) return resolve(process.env.PI_WEB_DSH_JSONRPC_ENTRY);
67
+ let cur = HERE;
68
+ for (let i = 0; i < 6; i++) {
69
+ const candidate = join(cur, "node_modules", "@deepseek-ai", "dsh-sdk-jsonrpc-server", "lib", "index.js");
70
+ if (existsSync(candidate)) return candidate;
71
+ cur = dirname(cur);
72
+ }
73
+ return join(
74
+ resolve(HERE, "..", "..", ".."),
75
+ "node_modules",
76
+ "@deepseek-ai",
77
+ "dsh-sdk-jsonrpc-server",
78
+ "lib",
79
+ "index.js",
80
+ );
81
+ }
82
+
83
+ const officialEntry = findOfficialEntry();
84
+
85
+ const official = await import(pathToFileURL(officialEntry).href);
86
+ const { HarnessSdkJsonRpcServer, Config } = official;
87
+
88
+ /** 提问桥超时(P0-6):PI_WEB_DSH_QUESTION_TIMEOUT_MS 可配置,默认 10 分钟。 */
89
+ const QUESTION_TIMEOUT_MS = Number(process.env.PI_WEB_DSH_QUESTION_TIMEOUT_MS) || 10 * 60_000;
90
+
91
+ /** 工具桥超时(#15):服务端跑插件实现的等待上限。PI_WEB_DSH_TOOL_TIMEOUT_MS 可配置,默认 10 分钟。 */
92
+ const TOOL_TIMEOUT_MS = Number(process.env.PI_WEB_DSH_TOOL_TIMEOUT_MS) || 10 * 60_000;
93
+
94
+ /** 过滤一条 skill-catalog 用户消息:按 disabled 集合剔除条目并重建文本。
95
+ * 纯函数(可单测)。条目来自消息的 `source.entries`(`{name,description}`),
96
+ * 文本里的 `<available_skills>…</available_skills>` 块按保留条目重建,其余不动。 */
97
+ export function filterSkillCatalogMessage(message, disabled) {
98
+ if (!message || message?.source?.kind !== "skill-catalog") return message;
99
+ const entries = Array.isArray(message.source?.entries) ? message.source.entries : [];
100
+ const kept = entries.filter((e) => e && !disabled.has(e.name));
101
+ if (kept.length === entries.length) return message;
102
+ const original =
103
+ (Array.isArray(message.content) ? message.content.find((b) => b?.type === "text")?.text : undefined) ?? "";
104
+ const text = rebuildCatalogText(original, kept);
105
+ return {
106
+ ...message,
107
+ source: { ...message.source, entries: kept },
108
+ content: [{ type: "text", text }],
109
+ };
110
+ }
111
+
112
+ /** 重建 `<available_skills>` 块的文本(保留块外结构;无条目时给占位)。 */
113
+ function rebuildCatalogText(original, entries) {
114
+ const startTag = "<available_skills>";
115
+ const endTag = "</available_skills>";
116
+ const si = original.indexOf(startTag);
117
+ const ei = original.indexOf(endTag);
118
+ if (si < 0 || ei < 0) return original;
119
+ const body = entries.length
120
+ ? entries.map((e) => `- \`${e.name}\`: ${escapeTextSimple(e.description ?? "")}`).join("\n")
121
+ : "(本会话无可启用技能)";
122
+ return `${original.slice(0, si + startTag.length)}\n${body}\n${original.slice(ei)}`;
123
+ }
124
+
125
+ /** 最小 HTML 实体转义(避免 `<`/`&` 破坏 markdown/目录结构)。 */
126
+ function escapeTextSimple(s) {
127
+ return String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
128
+ }
129
+
130
+ const DSH_VALID_TYPES = new Set(["string", "number", "integer", "boolean", "null", "array", "object", "json"]);
131
+
132
+ /**
133
+ * 把任意 JSON Schema 节点规整为 DSH schema compiler 支持的纯净 value schema。
134
+ * @param {unknown} def 原始属性定义
135
+ * @param {boolean} [allowRequired=false] 是否允许 required 字段(仅顶层 property-map 允许)
136
+ */
137
+ function normalizeDshNode(def, allowRequired = false) {
138
+ if (!def || typeof def !== "object" || Array.isArray(def)) {
139
+ return { type: "string" };
140
+ }
141
+
142
+ const out = {};
143
+
144
+ // 1. 复制合法的 annotations
145
+ if (typeof def.description === "string") out.description = def.description;
146
+ if (typeof def.title === "string") out.title = def.title;
147
+ if (def.default !== undefined) out.default = def.default;
148
+ if (Array.isArray(def.examples)) out.examples = def.examples;
149
+ if (allowRequired && def.required === true) out.required = true;
150
+
151
+ // 2. 处理 oneOf / anyOf(DSH 仅支持 oneOf,且与 type 互斥)
152
+ const unionCandidates = Array.isArray(def.oneOf) ? def.oneOf : Array.isArray(def.anyOf) ? def.anyOf : null;
153
+
154
+ if (unionCandidates) {
155
+ const branches = unionCandidates.map((branch) => normalizeDshNode(branch, false)).filter(Boolean);
156
+ if (branches.length >= 2) {
157
+ out.oneOf = branches;
158
+ return out;
159
+ }
160
+ if (branches.length === 1) {
161
+ return { ...branches[0], ...out };
162
+ }
163
+ }
164
+
165
+ // 3. 处理 type 字段(可能为数组,如 ["string", "null"])
166
+ let rawType = def.type;
167
+ if (Array.isArray(rawType)) {
168
+ const types = rawType
169
+ .map((t) => (typeof t === "string" ? t.toLowerCase().trim() : ""))
170
+ .filter((t) => DSH_VALID_TYPES.has(t));
171
+ if (types.length >= 2) {
172
+ out.oneOf = types.map((t) => {
173
+ const branch = { type: t };
174
+ if (t === "object") branch.additionalProperties = true;
175
+ return branch;
176
+ });
177
+ return out;
178
+ }
179
+ rawType = types[0];
180
+ }
181
+
182
+ let type = typeof rawType === "string" ? rawType.toLowerCase().trim() : undefined;
183
+ if (type === "float") type = "number";
184
+ else if (type === "int") type = "integer";
185
+ else if (type === "bool") type = "boolean";
186
+
187
+ if (!type) {
188
+ if (def.properties && typeof def.properties === "object") type = "object";
189
+ else if (def.items) type = "array";
190
+ else type = "string";
191
+ }
192
+
193
+ if (!DSH_VALID_TYPES.has(type)) {
194
+ type = "string";
195
+ }
196
+
197
+ out.type = type;
198
+
199
+ // 4. 根据具体 type 补充/规整专属字段(严格限制在 DSH 允许子集,去除 format/pattern 等不支持属性)
200
+ switch (type) {
201
+ case "object": {
202
+ out.additionalProperties = typeof def.additionalProperties === "boolean" ? def.additionalProperties : true;
203
+ if (def.properties && typeof def.properties === "object" && !Array.isArray(def.properties)) {
204
+ const nestedProps = {};
205
+ const reqList = Array.isArray(def.required) ? def.required : [];
206
+ for (const [pKey, pDef] of Object.entries(def.properties)) {
207
+ const pNode = normalizeDshNode(pDef, true);
208
+ if (reqList.includes(pKey)) pNode.required = true;
209
+ nestedProps[pKey] = pNode;
210
+ }
211
+ out.properties = nestedProps;
212
+ }
213
+ break;
214
+ }
215
+ case "array": {
216
+ if (def.items && typeof def.items === "object" && !Array.isArray(def.items)) {
217
+ out.items = normalizeDshNode(def.items, false);
218
+ }
219
+ break;
220
+ }
221
+ case "string":
222
+ case "number":
223
+ case "integer":
224
+ case "boolean":
225
+ case "null": {
226
+ if (Array.isArray(def.enum) && def.enum.length > 0) {
227
+ out.enum = def.enum;
228
+ }
229
+ if (def.const !== undefined) {
230
+ out.const = def.const;
231
+ }
232
+ break;
233
+ }
234
+ case "json":
235
+ break;
236
+ }
237
+
238
+ return out;
239
+ }
240
+
241
+ /** 把 pi-web-ui 插件工具的标准 JSON Schema `parameters`(`{type,properties,required[]}`)
242
+ * 转成 DSH defineTool 的 per-property 参数映射 spec(`{key:{type,required?,description}}`)。
243
+ * DSH 的 parameterSchemaSpecToJsonSchema 需要 property-map 形状(required 挂在每条属性上),
244
+ * 而 pi 插件/TypeBox 用的是标准 JSON Schema(required 是对象数组)。纯函数。 */
245
+ export function piParamsToDshSpec(parameters) {
246
+ if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) return {};
247
+ let propSource;
248
+ let requiredList = [];
249
+ if (parameters.properties && typeof parameters.properties === "object" && !Array.isArray(parameters.properties)) {
250
+ propSource = parameters.properties;
251
+ if (Array.isArray(parameters.required)) requiredList = parameters.required;
252
+ } else if (parameters.type === "object") {
253
+ // 标准 JSON Schema 的无属性对象:{ type: "object" }
254
+ return {};
255
+ } else {
256
+ // 已是 DSH property-map 形状
257
+ propSource = parameters;
258
+ if (Array.isArray(parameters.required)) requiredList = parameters.required;
259
+ }
260
+ const propMap = {};
261
+ for (const [key, def] of Object.entries(propSource)) {
262
+ const node = normalizeDshNode(def, true);
263
+ if (requiredList.includes(key)) node.required = true;
264
+ propMap[key] = node;
265
+ }
266
+ return propMap;
267
+ }
268
+
269
+ /** goal view → RPC 载荷(紧凑 JSON;view 是扁平结构,无目标时 get 返回 undefined)。 */
270
+ function viewPayload(view) {
271
+ if (!view || view.id === undefined) return { goal: null, activation: null };
272
+ return {
273
+ goal: {
274
+ id: view.id,
275
+ revision: view.revision,
276
+ objective: view.objective,
277
+ phase: view.phase,
278
+ maxGoalRounds: view.maxGoalRounds,
279
+ ...(view.blockedReason === void 0 ? {} : { blockedReason: view.blockedReason }),
280
+ roundsStarted: view.roundsStarted ?? 0,
281
+ },
282
+ activation: view.activation ?? null,
283
+ };
284
+ }
285
+
286
+ /** 取会话的 live agent(不存在则按需创建,与 prompt 的隐式建会话一致)。 */
287
+ function agentOf(server, sessionId) {
288
+ return server.getOrCreateSession(sessionId).then((rec) => rec.handle.agent);
289
+ }
290
+
291
+ /**
292
+ * 官方 SDK server 的 goal 扩展:goal/* 方法直连 ctx.goals 服务动词。
293
+ */
294
+ class DshGoalJsonRpcServer extends HarnessSdkJsonRpcServer {
295
+ /**
296
+ * 官方构造器订阅 session.event / session.status / subagent.*;这里再加**直播流**:
297
+ * 新版 DSH 运行时(0.1.1-rc.2 之后)把逐 chunk 的模型输出发成 agent scope 的
298
+ * `agent/assistant-stream` 帧(持久的 `assistant/chunk` 事件已取消),host 侧的
299
+ * jsonrpc 面收不到 → pi-web-ui 既没有 streamingMessage / 实时速率,也拿不到
300
+ * 逐次调用 usage(底栏上下文占用 / 缓存命中)。
301
+ *
302
+ * 转成 `assistant.stream` 通知:`{ sessionId, frame }`,frame 是运行时的
303
+ * start / chunk / end 三态;chunk 形状与旧 `assistant/chunk.data.chunk` 同构。
304
+ *
305
+ * `{ global: true }` 是必需的:该事件在 agent scope 派发,host 上注册的观察者
306
+ * 不加 global 永远收不到(同 dsh-api-session-controller 的写法)。
307
+ */
308
+ constructor(ctx, transport, options) {
309
+ super(ctx, transport, options);
310
+ this.disposers.push(
311
+ ctx.on(
312
+ "agent/assistant-stream",
313
+ ({ agent, frame }) => {
314
+ this.transport.notify("assistant.stream", {
315
+ sessionId: String(agent.session.id),
316
+ frame,
317
+ });
318
+ },
319
+ { global: true },
320
+ ),
321
+ );
322
+ }
323
+
324
+ /**
325
+ * 创建(或替换已完成的)目标并 arm —— round-driver 会在 agent idle 时
326
+ * 自动续第一轮,不需要额外 prompt。
327
+ */
328
+ async goalSet(params) {
329
+ if (typeof params?.sessionId !== "string") throw new TypeError("goal/set requires sessionId");
330
+ if (typeof params?.objective !== "string" || !params.objective.trim()) {
331
+ throw new TypeError("goal/set requires a non-empty objective");
332
+ }
333
+ const agent = await agentOf(this, params.sessionId);
334
+ const request = { objective: params.objective.trim() };
335
+ if (Number.isSafeInteger(params.maxGoalRounds) && params.maxGoalRounds > 0) {
336
+ request.maxGoalRounds = params.maxGoalRounds;
337
+ }
338
+ return viewPayload(this.ctx.goals.create(agent, request));
339
+ }
340
+
341
+ /** 当前目标视图(goal 或 null)。 */
342
+ async goalGet(params) {
343
+ if (typeof params?.sessionId !== "string") throw new TypeError("goal/get requires sessionId");
344
+ const agent = await agentOf(this, params.sessionId);
345
+ return viewPayload(this.ctx.goals.get(agent));
346
+ }
347
+
348
+ /** 清除当前目标(保留 durable 墓碑与历史)。 */
349
+ async goalClear(params) {
350
+ if (typeof params?.sessionId !== "string") throw new TypeError("goal/clear requires sessionId");
351
+ const agent = await agentOf(this, params.sessionId);
352
+ const view = this.ctx.goals.get(agent);
353
+ if (view === void 0 || view.id === void 0) return { cleared: false };
354
+ this.ctx.goals.clear(agent, { id: view.id, revision: view.revision });
355
+ return { cleared: true };
356
+ }
357
+
358
+ /** 恢复被 disarm 的目标(abort 重启运行时后轮次驱动停止,需要 resume 续)。 */
359
+ async goalResume(params) {
360
+ if (typeof params?.sessionId !== "string") throw new TypeError("goal/resume requires sessionId");
361
+ const agent = await agentOf(this, params.sessionId);
362
+ const view = this.ctx.goals.get(agent);
363
+ if (view === void 0 || view.id === void 0) throw new Error("no current goal to resume");
364
+ return viewPayload(this.ctx.goals.resume(agent, { id: view.id, revision: view.revision }));
365
+ }
366
+
367
+ /** 编辑目标(改客观文本或轮次上限,不改 phase)。 */
368
+ async goalEdit(params) {
369
+ if (typeof params?.sessionId !== "string") throw new TypeError("goal/edit requires sessionId");
370
+ const agent = await agentOf(this, params.sessionId);
371
+ const view = this.ctx.goals.get(agent);
372
+ if (view === void 0 || view.id === void 0) throw new Error("no current goal to edit");
373
+ const request = {};
374
+ if (typeof params?.objective === "string" && params.objective.trim()) {
375
+ request.objective = params.objective.trim();
376
+ }
377
+ if (Number.isSafeInteger(params?.maxGoalRounds) && params.maxGoalRounds > 0) {
378
+ request.maxGoalRounds = params.maxGoalRounds;
379
+ }
380
+ if (request.objective === undefined && request.maxGoalRounds === undefined) {
381
+ throw new TypeError("goal/edit requires objective and/or maxGoalRounds");
382
+ }
383
+ return viewPayload(this.ctx.goals.edit(agent, { id: view.id, revision: view.revision }, request));
384
+ }
385
+
386
+ // -----------------------------------------------------------------------
387
+ // Agent 预设(dsh-web 四模式:standard/ptc/minimal/cordis + 用户自建)。
388
+ //
389
+ // roster 挂了 preset-plane patch 才存在(见 server/dsh/preset-clones.ts 生成的
390
+ // preset-plane.patch.yml);legacy 单组合(无 patch)下全部回退:list 报 unavailable,
391
+ // assign/select 透过,创建走官方原逻辑,per-agent 钩子照装(问卷 waterfall 修法
392
+ // 本就要求 agent scope 注册,与预设有无无关)。
393
+ //
394
+ // 约定:Node 侧(dsh-agent-service)是 preset 真源 —— 新会话首个 prompt 前调
395
+ // preset/assign 登记,会话创建时消费;空白会话切换走 preset/select(首轮后锁,
396
+ // 与官方 agent-preset/locked 语义一致)。RPC 错误不抛 domain 码(transport 统一
397
+ // 坍缩成 -32603),一律走 {ok:false,code,message} 信封。
398
+ // -----------------------------------------------------------------------
399
+
400
+ /** 待消费的创建期预设:sessionId → preset id(创建时消费并删除)。 */
401
+ pendingPresets = new Map();
402
+ /** minimal 下被门禁的 agent id(bridge 工具 + 问卷调用期拒绝,中英双语报错)。 */
403
+ minimalAgents = new Set();
404
+ /** 技能目录取数 agent(standard 预设,常驻但永不 prompt,零 token)。 */
405
+ inventorySessionId = "pi-webui-inventory";
406
+
407
+ /** roster 服务(无 preset-plane patch 时 undefined → 全员 legacy)。 */
408
+ presetRoster() {
409
+ try {
410
+ return this.ctx.get("agentPresets") ?? undefined;
411
+ } catch {
412
+ return undefined;
413
+ }
414
+ }
415
+
416
+ /** 解析一个 preset id(非法/unknown → 默认;roster 缺失 → undefined)。 */
417
+ async resolvePresetId(requested) {
418
+ const roster = this.presetRoster();
419
+ if (!roster) return undefined;
420
+ try {
421
+ return (await roster.resolve(requested)).id;
422
+ } catch {
423
+ try {
424
+ return (await roster.resolve()).id;
425
+ } catch {
426
+ return undefined;
427
+ }
428
+ }
429
+ }
430
+
431
+ /** preset/list RPC:roster 名录(display 字段以运行时树为准)。 */
432
+ async listPresets() {
433
+ const roster = this.presetRoster();
434
+ if (!roster) return { presets: [], defaultPreset: "standard", authorable: false, unavailable: true };
435
+ try {
436
+ // service.list() = discovery 数组;isDefault/authorable 走同名的 getter。
437
+ const items = await roster.list();
438
+ let defaultId = "standard";
439
+ try {
440
+ defaultId = roster.defaultId ?? defaultId;
441
+ } catch {
442
+ /* keep */
443
+ }
444
+ let authorable = false;
445
+ try {
446
+ authorable = !!roster.authorable;
447
+ } catch {
448
+ /* keep */
449
+ }
450
+ return {
451
+ presets: (Array.isArray(items) ? items : []).map((p) => ({
452
+ id: p.id,
453
+ trust: p.trust,
454
+ isDefault: p.id === defaultId,
455
+ ...(p.name ? { name: p.name } : {}),
456
+ ...(p.description ? { description: p.description } : {}),
457
+ ...(Number.isSafeInteger(p.order) ? { order: p.order } : {}),
458
+ ...(p.broken ? { broken: p.broken } : {}),
459
+ })),
460
+ defaultPreset: defaultId,
461
+ authorable,
462
+ };
463
+ } catch (err) {
464
+ return {
465
+ presets: [],
466
+ defaultPreset: "standard",
467
+ authorable: false,
468
+ unavailable: true,
469
+ error: err?.message ?? String(err),
470
+ };
471
+ }
472
+ }
473
+
474
+ /** preset/assign RPC:登记创建期预设(首个 prompt/goal 前调用,仅创建时消费)。 */
475
+ async assignPreset(params) {
476
+ if (typeof params?.sessionId !== "string") throw new TypeError("preset/assign requires sessionId");
477
+ if (typeof params?.preset !== "string" || !params.preset) throw new TypeError("preset/assign requires preset");
478
+ this.pendingPresets.set(params.sessionId, params.preset);
479
+ return { ok: true };
480
+ }
481
+
482
+ /** agent 存活检查(项目依赖的 0.1.1-rc.2 无基类 assertLiveAgent,内联同语义)。 */
483
+ liveAgent(rec, sessionId) {
484
+ if (!rec || this.ctx.agents.get(rec.handle.agent.id) !== rec.handle.agent) {
485
+ throw new Error(`session agent was disposed outside the server: ${sessionId}`);
486
+ }
487
+ return rec.handle.agent;
488
+ }
489
+
490
+ /** preset/select RPC:空白会话切换预设(首轮后官方抛 agent-preset/locked)。 */
491
+ async selectPreset(params) {
492
+ if (typeof params?.sessionId !== "string") throw new TypeError("preset/select requires sessionId");
493
+ if (typeof params?.preset !== "string" || !params.preset) throw new TypeError("preset/select requires preset");
494
+ const roster = this.presetRoster();
495
+ if (!roster)
496
+ return { ok: false, code: "agent-preset/unavailable", message: "agent presets unavailable (legacy runtime)" };
497
+ try {
498
+ const rec = await this.getOrCreateSession(params.sessionId);
499
+ const agent = this.liveAgent(rec, params.sessionId);
500
+ const id = await roster.select(agent, params.preset);
501
+ this.pendingPresets.delete(params.sessionId);
502
+ if (id === "minimal") this.minimalAgents.add(agent.id);
503
+ else this.minimalAgents.delete(agent.id);
504
+ return { ok: true, preset: id };
505
+ } catch (err) {
506
+ return { ok: false, code: err?.code ?? "agent-preset/error", message: err?.message ?? String(err) };
507
+ }
508
+ }
509
+
510
+ /** permission/get RPC:读一个会话的权限预设 projection(官方 /permission 弹窗同源)。 */
511
+ async getPermission(params) {
512
+ if (typeof params?.sessionId !== "string") throw new TypeError("permission/get requires sessionId");
513
+ const rec = await this.getOrCreateSession(params.sessionId);
514
+ const agent = this.liveAgent(rec, params.sessionId);
515
+ const permission = this.ctx.permissionPresets;
516
+ if (!permission) throw new Error("permission/get: permission service unavailable");
517
+ if (typeof permission.selectFor === "function") {
518
+ return permission.selectFor(permission.permissionState(agent.session));
519
+ }
520
+ const cat = typeof permission.catalog === "function" ? permission.catalog() : {};
521
+ const cur = typeof permission.current === "function" ? permission.current(agent.session) : undefined;
522
+ return { ...cat, currentValue: cur };
523
+ }
524
+
525
+ /** permission/set RPC:按会话热切换权限预设(写会话日志,无需重启;
526
+ * 与官方 /permission 命令同语义:approval 走 live writer,模型会收到一条
527
+ * 策略变更的用户消息)。未知预设走 {ok:false} 信封,不抛 domain 错。 */
528
+ async setPermission(params) {
529
+ if (typeof params?.sessionId !== "string") throw new TypeError("permission/set requires sessionId");
530
+ if (typeof params?.preset !== "string" || !params.preset) throw new TypeError("permission/set requires preset");
531
+ const permission = this.ctx.permissionPresets;
532
+ if (!permission) throw new Error("permission/set: permission service unavailable");
533
+ if (!permission.names.includes(params.preset)) {
534
+ return {
535
+ ok: false,
536
+ code: "permission/unknown-preset",
537
+ message: `unknown preset "${params.preset}" (known: ${permission.names.join(", ")})`,
538
+ };
539
+ }
540
+ try {
541
+ const rec = await this.getOrCreateSession(params.sessionId);
542
+ const agent = this.liveAgent(rec, params.sessionId);
543
+ permission.apply(agent.session, params.preset, (policy) => this.ctx.approval.setPolicy(agent, policy));
544
+ const snapshot =
545
+ typeof permission.selectFor === "function"
546
+ ? permission.selectFor(permission.permissionState(agent.session))
547
+ : {
548
+ ...(typeof permission.catalog === "function" ? permission.catalog() : {}),
549
+ currentValue:
550
+ typeof permission.current === "function" ? permission.current(agent.session) : params.preset,
551
+ };
552
+ return {
553
+ ok: true,
554
+ preset: params.preset,
555
+ ...snapshot,
556
+ };
557
+ } catch (err) {
558
+ return { ok: false, code: "permission/error", message: err?.message ?? String(err) };
559
+ }
560
+ }
561
+
562
+ /** preset/tools RPC(仅 DEBUG):读一个会话 agent scope 的实际工具名(校验挂载用)。 */
563
+ async presetTools(params) {
564
+ if (process.env.PI_WEB_DSH_DEBUG !== "1") {
565
+ throw new Error("preset/tools 仅调试可用(服务端需设 PI_WEB_DSH_DEBUG=1)");
566
+ }
567
+ if (typeof params?.sessionId !== "string") throw new TypeError("preset/tools requires sessionId");
568
+ const rec = await this.getOrCreateSession(params.sessionId);
569
+ const agent = this.liveAgent(rec, params.sessionId);
570
+ // agent 视角(scope):preset 层 + host 层合并目录;缺省全局视角只看到 host 层。
571
+ const schemas = this.ctx.tools.schemas(agent);
572
+ return { tools: schemas.map((s) => s.name).sort() };
573
+ }
574
+
575
+ /** prompt/inspect RPC:返回系统提示词全文、分段(sections)、上下文(contexts)与工具 schemas。 */
576
+ async promptInspect(params) {
577
+ let context = {};
578
+ if (typeof params?.sessionId === "string" && params.sessionId) {
579
+ try {
580
+ const rec = await this.getOrCreateSession(params.sessionId);
581
+ const agent = this.liveAgent(rec, params.sessionId);
582
+ context = { agent, scope: agent };
583
+ } catch {
584
+ /* ignore */
585
+ }
586
+ }
587
+ if (!context.agent) {
588
+ try {
589
+ const agent = await this.ensureInventoryAgent();
590
+ context = { agent, scope: agent };
591
+ } catch {
592
+ /* ignore */
593
+ }
594
+ }
595
+ const contexts = context.agent
596
+ ? [{ agent: context.agent, scope: context.agent }, { scope: context.agent }, { scope: context.agent.ctx }, {}]
597
+ : [{}];
598
+ let asm = null;
599
+ let lastErr = null;
600
+ for (const ctx of contexts) {
601
+ try {
602
+ asm = await this.ctx.systemPrompt.assemble(ctx);
603
+ if (asm) break;
604
+ } catch (err) {
605
+ lastErr = err;
606
+ }
607
+ }
608
+ if (!asm) {
609
+ return {
610
+ prompt: "",
611
+ sections: [],
612
+ contexts: [],
613
+ tools: [],
614
+ error: String(lastErr?.message ?? lastErr ?? "assembly failed"),
615
+ };
616
+ }
617
+ const sections = Array.isArray(asm.sections)
618
+ ? asm.sections.map((s) => ({
619
+ name: s.name,
620
+ text: typeof s.text === "string" ? s.text : String(s.text ?? ""),
621
+ chars: String(s.text ?? "").length,
622
+ }))
623
+ : [];
624
+ const promptContexts = Array.isArray(asm.contexts)
625
+ ? asm.contexts.map((c) => ({
626
+ name: c.name,
627
+ text: typeof c.text === "string" ? c.text : String(c.text ?? ""),
628
+ chars: String(c.text ?? "").length,
629
+ }))
630
+ : [];
631
+ const tools = Array.isArray(asm.tools)
632
+ ? asm.tools.map((t) => ({
633
+ name: t.name,
634
+ description: t.description,
635
+ parameters: t.parameters,
636
+ }))
637
+ : [];
638
+ const sectionTexts = sections.map((s) => s.text).filter(Boolean);
639
+ let fullPrompt = sectionTexts.join("\n\n");
640
+ if (promptContexts.length > 0) {
641
+ const ctxBody = promptContexts
642
+ .map((c) => c.text)
643
+ .filter(Boolean)
644
+ .join("\n\n");
645
+ if (ctxBody) {
646
+ fullPrompt +=
647
+ (fullPrompt ? "\n\n" : "") +
648
+ `Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\n${ctxBody}`;
649
+ }
650
+ }
651
+ return {
652
+ prompt: fullPrompt,
653
+ sections,
654
+ contexts: promptContexts,
655
+ tools,
656
+ };
657
+ }
658
+
659
+ /** debug/assemble RPC(仅 DEBUG):读一个会话 agent 视角的系统提示词 section 名录
660
+ * (零 token 验证 persona 遮蔽/complete 压制/自定义 section 用;不返回正文)。 */
661
+ async debugAssemble(params) {
662
+ if (process.env.PI_WEB_DSH_DEBUG !== "1") {
663
+ throw new Error("debug/assemble 仅调试可用(服务端需设 PI_WEB_DSH_DEBUG=1)");
664
+ }
665
+ if (typeof params?.sessionId !== "string") throw new TypeError("debug/assemble requires sessionId");
666
+ const rec = await this.getOrCreateSession(params.sessionId);
667
+ const agent = this.liveAgent(rec, params.sessionId);
668
+ // 组装上下文同 agent-loop(assembleContextFor):{ agent, scope: agent }。
669
+ const contexts = [{ agent, scope: agent }, { scope: agent }, { scope: agent.ctx }];
670
+ let lastErr = null;
671
+ for (const context of contexts) {
672
+ try {
673
+ const asm = await this.ctx.systemPrompt.assemble(context);
674
+ if (asm && Array.isArray(asm.sections)) {
675
+ return { sections: asm.sections.map((s) => ({ name: s.name, chars: String(s.text ?? "").length })) };
676
+ }
677
+ } catch (err) {
678
+ lastErr = err;
679
+ }
680
+ }
681
+ throw new Error(`debug/assemble: assembly failed (${lastErr?.message ?? lastErr})`);
682
+ }
683
+
684
+ /** 会话创建(官方同形 + setup):mount 预设 + 装 per-agent 钩子。
685
+ * 磁盘上已有同 id(运行时重启/优雅关闭后重建)→ 转 agents.resume
686
+ * (官方恢复路径,自动缝合被中断的 turn;setup 照跑,预设照挂)。 */
687
+ async createSession(sessionId, preset) {
688
+ const requested = preset ?? this.pendingPresets.get(sessionId);
689
+ this.pendingPresets.delete(sessionId);
690
+ const resolved = await this.resolvePresetId(requested);
691
+ const agentOptions = {
692
+ provider: this.provider,
693
+ model: this.model,
694
+ ...(this.reasoningEffort === void 0 ? {} : { reasoningEffort: this.reasoningEffort }),
695
+ ...(this.maxTokens === void 0 ? {} : { maxTokens: this.maxTokens }),
696
+ };
697
+ const setup = async (agentCtx, agent) => this.agentSetup(agentCtx, agent, resolved);
698
+ let handle;
699
+ try {
700
+ handle = await this.ctx.agents.create({
701
+ sessionId,
702
+ meta: { cwd: this.cwd, ...(resolved ? { agentPreset: resolved } : {}) },
703
+ agentOptions,
704
+ setup,
705
+ });
706
+ } catch (err) {
707
+ if (typeof err?.message === "string" && err.message.includes(`session "${sessionId}" already exists`)) {
708
+ process.stderr.write(`[pi-web-ui-dsh] 会话 ${sessionId} 已在磁盘,resume 恢复\n`);
709
+ handle = await this.ctx.agents.resume({ resumeSessionId: sessionId, agentOptions, setup });
710
+ } else {
711
+ throw err;
712
+ }
713
+ }
714
+ const rec = { handle };
715
+ this.sessions.set(sessionId, rec);
716
+ return rec;
717
+ }
718
+
719
+ /** 官方 getOrCreateSession 同形(多出来的 preset 参数供创建时使用)。 */
720
+ async getOrCreateSession(sessionId, preset) {
721
+ if (this.shuttingDown) throw new Error("SDK server is shutting down");
722
+ const existing = this.sessions.get(sessionId);
723
+ if (existing) return existing;
724
+ const pending = this.sessionCreations.get(sessionId);
725
+ if (pending) return pending;
726
+ const creation = this.createSession(sessionId, preset);
727
+ this.sessionCreations.set(sessionId, creation);
728
+ creation.then(
729
+ () => {
730
+ this.sessionCreations.delete(sessionId);
731
+ },
732
+ () => {
733
+ this.sessionCreations.delete(sessionId);
734
+ },
735
+ );
736
+ return creation;
737
+ }
738
+
739
+ /** 每个 agent 出生时跑一次:mount 预设 + 问卷 waterfall + 技能目录过滤。
740
+ * 预设优先级:会话记录(header/selected 事件,重启恢复时是唯一真相)>
741
+ * 创建参数 > roster 默认。 */
742
+ async agentSetup(agentCtx, agent, presetId) {
743
+ const roster = this.presetRoster();
744
+ let effective = presetId;
745
+ if (roster) {
746
+ try {
747
+ const prior = this.ctx.sessionProjections.stateOf(agent.session, "agentPreset");
748
+ if (typeof prior === "string" && prior) effective = prior;
749
+ } catch {
750
+ /* 无 projection 能力 → 用创建参数 */
751
+ }
752
+ }
753
+ if (roster && effective) {
754
+ try {
755
+ await roster.mount(agentCtx, effective);
756
+ if (effective === "minimal") this.minimalAgents.add(agent.id);
757
+ } catch (err) {
758
+ process.stderr.write(
759
+ `[pi-web-ui-dsh] preset "${effective}" mount 失败,转 host 直连: ${err?.message ?? err}\n`,
760
+ );
761
+ }
762
+ }
763
+ // 问卷 waterfall(P0 修法):answerer 必须挂 agent scope —— host 层收不到
764
+ // agent-scoped 事件,且新版 UserQuestionService 已删 registerProvider。
765
+ // 与官方 ui-user-questions 同构:返回 {answers} 即 short-circuit。
766
+ agentCtx.on("user-questions/request", (request, _next) => this.answerScopedQuestion(agent, request));
767
+ // 技能目录过滤:与上面同理,host 版已死(收不到事件),改挂 agent scope。
768
+ // eslint-disable-next-line no-empty-pattern -- only next is needed
769
+ agentCtx.on("agent/pre-step", async ({}, next) => {
770
+ const decision = await next();
771
+ if (this.disabledSkills.size && decision?.kind === "enter" && Array.isArray(decision.messages)) {
772
+ if (decision.messages.some((m) => m?.source?.kind === "skill-catalog")) {
773
+ decision.messages = decision.messages.map((m) => filterSkillCatalogMessage(m, this.disabledSkills));
774
+ }
775
+ }
776
+ return decision;
777
+ });
778
+ }
779
+
780
+ /** agent scope 的问卷 answerer:minimal 门禁 → 浏览器桥(复用排队逻辑)。 */
781
+ async answerScopedQuestion(agent, request) {
782
+ if (this.minimalAgents.has(agent?.id)) {
783
+ throw new Error(
784
+ "ask_user_question is unavailable under the minimal preset; use the shell instead " +
785
+ "(极简模式下不可提问,请直接用 shell 命令推进)",
786
+ );
787
+ }
788
+ if (request?.signal?.aborted) throw new Error("ask_user_question aborted(提问已中止)");
789
+ return this.askUser(request ?? {});
790
+ }
791
+
792
+ /** 技能目录取数 agent(standard 常驻,永不 prompt;roster 缺失时不用)。 */
793
+ async ensureInventoryAgent() {
794
+ const rec = await this.getOrCreateSession(this.inventorySessionId);
795
+ return this.liveAgent(rec, this.inventorySessionId);
796
+ }
797
+
798
+ /** 方法分发:goal/* 与 attachment/* 走上面/下面,其余交官方。 */
799
+ async handleRequest(method, params) {
800
+ switch (method) {
801
+ case "goal/set":
802
+ return this.goalSet(params);
803
+ case "goal/get":
804
+ return this.goalGet(params);
805
+ case "goal/clear":
806
+ return this.goalClear(params);
807
+ case "goal/resume":
808
+ return this.goalResume(params);
809
+ case "goal/edit":
810
+ return this.goalEdit(params);
811
+ case "attachment/save":
812
+ return this.attachmentSave(params);
813
+ case "attachment/read":
814
+ return this.attachmentRead(params);
815
+ case "question/answer":
816
+ return this.answerQuestion(params);
817
+ case "model/list":
818
+ return this.listModels(params);
819
+ case "tools/sync":
820
+ return this.syncTools(params);
821
+ case "tools/list":
822
+ return this.listTools();
823
+ case "tools/call-result":
824
+ return this.toolsCallResult(params);
825
+ case "tools/invoke":
826
+ return this.toolsInvoke(params);
827
+ case "skills/list":
828
+ return this.listSkills();
829
+ case "skills/set-disabled":
830
+ return this.setDisabledSkills(params);
831
+ case "skills/register":
832
+ return this.registerSkill(params);
833
+ case "skills/get":
834
+ return this.getSkill(params);
835
+ case "preset/list":
836
+ return this.listPresets();
837
+ case "preset/assign":
838
+ return this.assignPreset(params);
839
+ case "preset/select":
840
+ return this.selectPreset(params);
841
+ case "permission/get":
842
+ return this.getPermission(params);
843
+ case "permission/set":
844
+ return this.setPermission(params);
845
+ case "preset/tools":
846
+ return this.presetTools(params);
847
+ case "prompt/inspect":
848
+ return this.promptInspect(params);
849
+ case "debug/assemble":
850
+ return this.debugAssemble(params);
851
+ default:
852
+ return super.handleRequest(method, params);
853
+ }
854
+ }
855
+
856
+ /** P2-17 模型目录动态化:查询 adapter(ctx.llm)的真实模型清单。
857
+ * dsh-llm-deepseek 的 listModels 返回模型目录(含 inputModalities),
858
+ * 失败时返回空数组(服务端回退本地表)。 */
859
+ async listModels(params) {
860
+ try {
861
+ const providerId = params?.provider ?? "deepseek-official";
862
+ const models = await this.ctx.llm.listModels?.(providerId);
863
+ if (!Array.isArray(models)) return { models: [] };
864
+ return {
865
+ models: models.map((m) => ({
866
+ id: m.id,
867
+ ...(m.name ? { name: m.name } : {}),
868
+ ...(Array.isArray(m.inputModalities)
869
+ ? { inputModalities: m.inputModalities }
870
+ : Array.isArray(m.input)
871
+ ? { inputModalities: m.input }
872
+ : {}),
873
+ })),
874
+ };
875
+ } catch (err) {
876
+ return { models: [], error: err?.message ?? String(err) };
877
+ }
878
+ }
879
+
880
+ // -----------------------------------------------------------------------
881
+ // 用户提问桥(交互式调研/确认):模型调 ask_user_question 工具 →
882
+ // ctx.userQuestions.ask() 阻塞 → 本 provider 把问题发给浏览器 →
883
+ // question/answer RPC 带回答案 → 工具结果恢复模型循环。
884
+ // -----------------------------------------------------------------------
885
+
886
+ /** 挂起的提问 + 排队(apply 注册 provider 时初始化)。一次只向浏览器展示一个。 */
887
+ questionBridge = { pending: null, queue: [] };
888
+
889
+ // -----------------------------------------------------------------------
890
+ // 工具桥(#15 插件注入点):把 pi-web-ui 插件 AI 工具(registerAgentTool)
891
+ // 桥成 DSH 原生工具。服务端 tools/sync 注册 defineTool(trampoline execute),
892
+ // 模型调用时 trampoline 发 tools.call.request 通知 → 服务端跑插件实现 →
893
+ // tools/call-result RPC 恢复工具结果。
894
+ // -----------------------------------------------------------------------
895
+
896
+ /** 挂起的桥接调用:callId → { resolve, reject }(超时/中止统一拒)。 */
897
+ toolsPending = new Map();
898
+ /** 已注册工具的卸装回调(工具列表变化时先卸再重注册,last-write-wins 覆盖)。 */
899
+ toolUnregisters = [];
900
+
901
+ /** 注册(或替换)一批插件工具为 DSH 原生工具。返回当前注册清单。 */
902
+ async syncTools(params) {
903
+ const tools = Array.isArray(params?.tools) ? params.tools : [];
904
+ for (const off of this.toolUnregisters) {
905
+ try {
906
+ off();
907
+ } catch {
908
+ /* re-register 前的卸载不阻断 */
909
+ }
910
+ }
911
+ this.toolUnregisters = [];
912
+ const registered = [];
913
+ for (const t of tools) {
914
+ if (!t || typeof t.name !== "string" || typeof t.description !== "string") continue;
915
+ try {
916
+ const tool = defineTool({
917
+ name: t.name,
918
+ description: t.description,
919
+ parameters: piParamsToDshSpec(t.parameters),
920
+ output: {
921
+ schema: { type: "string" },
922
+ render: (_args, value) => [{ type: "text", text: String(value ?? "") }],
923
+ },
924
+ execute: (args, exec) => this.invokeBridgedTool(exec, t.name, args),
925
+ });
926
+ const off = this.ctx.tools.register(tool);
927
+ this.toolUnregisters.push(off);
928
+ registered.push(t.name);
929
+ } catch (err) {
930
+ console.warn(`[dsh] 工具 ${t.name} 注册跳过:`, err?.message ?? err);
931
+ }
932
+ }
933
+ return { registered, count: registered.length };
934
+ }
935
+
936
+ /** 列出运行时当前可见的工具 schema(供零 key 验证/调试)。 */
937
+ async listTools() {
938
+ const schemas = this.ctx.tools.schemas();
939
+ return {
940
+ tools: schemas.map((s) => ({
941
+ name: s.name,
942
+ description: s.description,
943
+ parameters: s.parameters,
944
+ })),
945
+ };
946
+ }
947
+
948
+ /** 桥接工具的 execute:minimal 门禁后把调用发给服务端并 await 结果。 */
949
+ invokeBridgedTool(exec, name, args) {
950
+ const agentId = exec?.agent?.id;
951
+ if (agentId !== undefined && this.minimalAgents.has(agentId)) {
952
+ return Promise.reject(
953
+ new Error(
954
+ `工具 ${name} unavailable under the minimal preset; use the shell instead ` +
955
+ `(极简模式下该插件工具不可用,请用 shell 命令推进)`,
956
+ ),
957
+ );
958
+ }
959
+ const id = `t-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
960
+ const sessionId =
961
+ exec?.agent?.session?.id && typeof exec.agent.session.id === "string" ? String(exec.agent.session.id) : undefined;
962
+ return new Promise((resolve, reject) => {
963
+ let done = false;
964
+ const cleanup = () => {
965
+ if (exec?.signal) exec.signal.removeEventListener("abort", onAbort);
966
+ };
967
+ const settle = (err, result) => {
968
+ if (done) return;
969
+ done = true;
970
+ cleanup();
971
+ clearTimeout(timer);
972
+ if (err) reject(err);
973
+ else resolve(result);
974
+ };
975
+ const onAbort = () => {
976
+ this.toolsPending.delete(id);
977
+ settle(new Error(`工具 ${name} 已中止`));
978
+ };
979
+ const timer = setTimeout(() => {
980
+ this.toolsPending.delete(id);
981
+ settle(new Error(`工具 ${name} 执行超时(等待服务端响应)`));
982
+ }, TOOL_TIMEOUT_MS);
983
+ timer.unref?.();
984
+ this.toolsPending.set(id, {
985
+ resolve: (result) => settle(null, result),
986
+ reject: (err) => settle(err),
987
+ });
988
+ exec?.signal?.addEventListener("abort", onAbort, { once: true });
989
+ this.transport.notify("tools.call.request", {
990
+ id,
991
+ name,
992
+ args,
993
+ ...(sessionId ? { sessionId } : {}),
994
+ });
995
+ });
996
+ }
997
+
998
+ /** 调试/probe 用:绕过模型直接触发一个已注册桥接工具的完整往返
999
+ * (trampoline → tools.call.request → tools/call-result 恢复)。仅 PI_WEB_DSH_DEBUG=1 可用。 */
1000
+ async toolsInvoke(params) {
1001
+ if (process.env.PI_WEB_DSH_DEBUG !== "1") {
1002
+ throw new Error("tools/invoke 仅调试可用(服务端需设 PI_WEB_DSH_DEBUG=1)");
1003
+ }
1004
+ const name = params?.name;
1005
+ if (typeof name !== "string") return { ok: false, error: "tools/invoke requires name" };
1006
+ const tool = this.ctx.tools.get(name);
1007
+ if (!tool) return { ok: false, error: `tools/invoke: 工具未注册 ${name}` };
1008
+ const exec = { signal: new AbortController().signal };
1009
+ try {
1010
+ const value = await tool.execute(params?.args ?? {}, exec);
1011
+ return { ok: true, value };
1012
+ } catch (err) {
1013
+ return { ok: false, error: err?.message ?? String(err) };
1014
+ }
1015
+ }
1016
+
1017
+ /** tools/call-result RPC:服务端跑完插件实现后回传结果,恢复桥接调用。 */
1018
+ async toolsCallResult(params) {
1019
+ const id = params?.id;
1020
+ if (typeof id !== "string") throw new TypeError("tools/call-result requires id");
1021
+ const pending = this.toolsPending.get(id);
1022
+ if (!pending) throw new Error(`tools/call-result 无匹配 id=${id}`);
1023
+ this.toolsPending.delete(id);
1024
+ if (params?.isError) pending.reject(new Error(params?.result ?? "工具执行失败"));
1025
+ else pending.resolve(params?.result ?? "");
1026
+ return { ok: true };
1027
+ }
1028
+
1029
+ // -----------------------------------------------------------------------
1030
+ // 技能 RPC(#18 技能启停 UI):暴露 SkillRegistry list/get + 设置禁用集合
1031
+ // (晚 pre-step 钩子用它过滤 skill-catalog 消息)。
1032
+ // -----------------------------------------------------------------------
1033
+
1034
+ /** 禁用的技能名集合(skills/set-disabled 更新)。 */
1035
+ disabledSkills = new Set();
1036
+
1037
+ /** 列出运行时当前可见技能:roster 下读常驻 inventory agent 的合并目录(技能只活在
1038
+ * 各预设的 agent 层,host 的 skill-filesystem 已 disable,host 直读恒为空);
1039
+ * legacy 下保持原来的 host 直读。零 key 校验/前端显示用。 */
1040
+ async listSkills() {
1041
+ const roster = this.presetRoster();
1042
+ if (roster) {
1043
+ try {
1044
+ const agent = await this.ensureInventoryAgent();
1045
+ // scope 视图:host registry + agent 层合并;cwd 选工作区根。
1046
+ const skills = await this.ctx.skills.list({ scope: agent, cwd: this.cwd });
1047
+ if (Array.isArray(skills)) {
1048
+ return {
1049
+ skills: skills.map((s) => ({
1050
+ name: s.name,
1051
+ description: s.description ?? "",
1052
+ ...(s.invocation ? { invocation: s.invocation } : {}),
1053
+ })),
1054
+ };
1055
+ }
1056
+ } catch (err) {
1057
+ return { skills: [], error: err?.message ?? String(err) };
1058
+ }
1059
+ return { skills: [] };
1060
+ }
1061
+ try {
1062
+ const skills = await this.ctx.skills.list();
1063
+ if (!Array.isArray(skills)) return { skills: [] };
1064
+ return {
1065
+ skills: skills.map((s) => ({
1066
+ name: s.name,
1067
+ description: s.description ?? "",
1068
+ ...(s.invocation ? { invocation: s.invocation } : {}),
1069
+ })),
1070
+ };
1071
+ } catch (err) {
1072
+ return { skills: [], error: err?.message ?? String(err) };
1073
+ }
1074
+ }
1075
+
1076
+ /** 读取单个技能的完整定义(SkillRegistry.get)。 */
1077
+ async getSkill(params) {
1078
+ if (typeof params?.name !== "string") throw new TypeError("skills/get requires name");
1079
+ const skill = await this.ctx.skills.get(params.name);
1080
+ return { skill: skill ?? null };
1081
+ }
1082
+
1083
+ /** 切换一个技能的可见性(服务端 set_settings.disabledSkills 变化时推送)。 */
1084
+ async setDisabledSkills(params) {
1085
+ const names = Array.isArray(params?.skills) ? params.skills : [];
1086
+ this.disabledSkills = new Set(names.map((n) => String(n)));
1087
+ return { disabled: [...this.disabledSkills] };
1088
+ }
1089
+
1090
+ /** 调试/probe 用:注册一个运行时技能(SkillRegistry.register),仅 DEBUG 可用。 */
1091
+ async registerSkill(params) {
1092
+ if (process.env.PI_WEB_DSH_DEBUG !== "1") throw new Error("skills/register 仅调试可用");
1093
+ if (typeof params?.name !== "string" || !params.name.trim()) {
1094
+ throw new TypeError("skills/register requires name");
1095
+ }
1096
+ const reg = this.ctx.skills.register({
1097
+ name: params.name.trim(),
1098
+ description: typeof params?.description === "string" ? params.description : "",
1099
+ invocation: { modelInvocable: true, userInvocable: false },
1100
+ source: "runtime",
1101
+ content: typeof params?.content === "string" ? params.content : "(test skill)",
1102
+ });
1103
+ return { ok: true, unregister: typeof reg === "function" };
1104
+ }
1105
+
1106
+ /** 把队首提问变为 pending(发通知给浏览器)。 */
1107
+ dispatchNextQuestion() {
1108
+ if (this.questionBridge.pending) return;
1109
+ const next = this.questionBridge.queue.shift();
1110
+ if (!next) return;
1111
+ this.transport.notify("question.pending", {
1112
+ id: next.qid,
1113
+ questions: next.questions,
1114
+ deadline: next.deadline,
1115
+ });
1116
+ this.questionBridge.pending = { qid: next.qid, resolve: next.resolve, reject: next.reject };
1117
+ }
1118
+
1119
+ /** ctx.userQuestions provider:把问题桥到客户端并等待答案。
1120
+ * P2-20:并发 ask() 排队(深度 3),当前提问回答后自动发下一个。 */
1121
+ async askUser(request) {
1122
+ const questions = (request?.questions ?? []).map((q) => ({
1123
+ id: q.id,
1124
+ question: q.question,
1125
+ ...(q.detail ? { detail: q.detail } : {}),
1126
+ ...(q.header ? { header: q.header } : {}),
1127
+ ...(q.options ? { options: q.options } : {}),
1128
+ ...(q.multiSelect ? { multiSelect: q.multiSelect } : {}),
1129
+ }));
1130
+ if (questions.length === 0) throw new Error("ask_user_question requires at least one question");
1131
+ const qid = `q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1132
+ const deadline = Date.now() + QUESTION_TIMEOUT_MS;
1133
+ return new Promise((resolve, reject) => {
1134
+ const timer = setTimeout(() => {
1135
+ const queued = this.questionBridge.queue.findIndex((q) => q.qid === qid);
1136
+ if (queued >= 0) {
1137
+ this.questionBridge.queue.splice(queued, 1);
1138
+ // #459:排队条目超时也必须 settle——此前只 splice 不 reject,
1139
+ // 该 ask 的 Promise 永不落定,agent-loop 卡死在工具调用上。
1140
+ reject(new Error("提问超时(等待回答过久)"));
1141
+ return;
1142
+ }
1143
+ if (this.questionBridge.pending?.qid === qid) {
1144
+ this.questionBridge.pending = null;
1145
+ reject(new Error("提问超时(等待回答过久)"));
1146
+ // #459:pending 腾出后必须派发下一个排队提问——否则队列无人派发,
1147
+ // 后续条目只能等各自超时且永不 settle,整条提问桥永久停摆。
1148
+ this.dispatchNextQuestion();
1149
+ }
1150
+ }, QUESTION_TIMEOUT_MS);
1151
+ timer.unref?.();
1152
+ const entry = {
1153
+ qid,
1154
+ questions,
1155
+ deadline,
1156
+ resolve: (answers) => {
1157
+ clearTimeout(timer);
1158
+ resolve(answers);
1159
+ },
1160
+ reject: (err) => {
1161
+ clearTimeout(timer);
1162
+ reject(err);
1163
+ },
1164
+ };
1165
+ if (this.questionBridge.pending || this.questionBridge.queue.length > 0) {
1166
+ // 已有提问在展示 → 排队;深度 3,满则拒绝(模型会收到工具报错继续)。
1167
+ if (this.questionBridge.queue.length >= 3) {
1168
+ clearTimeout(timer);
1169
+ reject(new Error("提问排队已满(最多 3 个),请先回答当前提问"));
1170
+ return;
1171
+ }
1172
+ this.questionBridge.queue.push(entry);
1173
+ } else {
1174
+ // 无 pending → 立即发通知并等待。
1175
+ this.transport.notify("question.pending", { id: qid, questions, deadline });
1176
+ this.questionBridge.pending = { qid, resolve: entry.resolve, reject: entry.reject };
1177
+ }
1178
+ });
1179
+ }
1180
+
1181
+ /** question/answer RPC:前端提交答案(或取消)。回答后自动发队列里的下一个。 */
1182
+ async answerQuestion(params) {
1183
+ const pending = this.questionBridge.pending;
1184
+ if (!pending || pending.qid !== params?.id) {
1185
+ throw new Error(`question/answer 不匹配(id=${params?.id})`);
1186
+ }
1187
+ this.questionBridge.pending = null;
1188
+ if (params?.cancelled) {
1189
+ const reason =
1190
+ typeof params?.cancelReason === "string" && params.cancelReason.trim()
1191
+ ? `(附言:${params.cancelReason.trim()})`
1192
+ : "";
1193
+ pending.reject(new Error(`用户取消了提问${reason}`));
1194
+ } else {
1195
+ const answers = Array.isArray(params?.answers) ? params.answers : [];
1196
+ pending.resolve({ answers });
1197
+ }
1198
+ this.dispatchNextQuestion();
1199
+ return { ok: true };
1200
+ }
1201
+
1202
+ // -----------------------------------------------------------------------
1203
+ // 附件 RPC(视觉桥):base64 图片 → durable ref;ref → base64 回读。
1204
+ // 模型请求侧的 image 块由 dsh-llm-deepseek adapter 自动解析 ref(file-id/inline)。
1205
+ // -----------------------------------------------------------------------
1206
+
1207
+ /** 保存一张 base64 图片到附件存储(ctx.attachments,dsh-attachment-local 后端)。 */
1208
+ async attachmentSave(params) {
1209
+ const mediaType = params?.mediaType;
1210
+ if (typeof mediaType !== "string" || !/^image\/(png|jpeg|webp|gif)$/u.test(mediaType)) {
1211
+ throw new TypeError("attachment/save requires mediaType (image/png|jpeg|webp|gif)");
1212
+ }
1213
+ if (typeof params?.data !== "string" || !params.data) {
1214
+ throw new TypeError("attachment/save requires base64 data");
1215
+ }
1216
+ const bytes = new Uint8Array(Buffer.from(params.data, "base64"));
1217
+ if (bytes.length === 0) throw new TypeError("attachment/save: empty image data");
1218
+ const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024; // 20MB 上限
1219
+ if (bytes.length > MAX_ATTACHMENT_BYTES) {
1220
+ throw new RangeError(`attachment/save: image data exceeds 20MB limit (${bytes.length} bytes)`);
1221
+ }
1222
+ const ref = await this.ctx.attachments.saveImage({
1223
+ data: bytes,
1224
+ mediaType,
1225
+ ...(typeof params?.name === "string" && params.name ? { name: params.name } : {}),
1226
+ });
1227
+ return { ref };
1228
+ }
1229
+
1230
+ /** 按 ref 回读规范化后的图片字节(base64),供前端回放显示。 */
1231
+ async attachmentRead(params) {
1232
+ const ref = params?.ref;
1233
+ if (!ref || typeof ref?.attachmentId !== "string" || typeof ref?.mediaType !== "string") {
1234
+ throw new TypeError("attachment/read requires ref (attachmentId + mediaType)");
1235
+ }
1236
+ const stored = await this.ctx.attachments.readImage(ref);
1237
+ return {
1238
+ mediaType: stored.ref?.mediaType ?? ref.mediaType,
1239
+ data: Buffer.from(stored.data).toString("base64"),
1240
+ };
1241
+ }
1242
+ }
1243
+
1244
+ /**
1245
+ * 插件 apply:transport 接线 / shutdown 语义与官方一致,server 换成本地扩展类。
1246
+ * 保持 named exports(无 default),Loader unwrapExports 需要 name/inject/Config/apply。
1247
+ */
1248
+ function apply(ctx, config) {
1249
+ const resolvedConfig = config;
1250
+ const rootFiber = ctx.root.fiber;
1251
+ /* v8 ignore next -- production stdio wiring */
1252
+ const input = config.input ?? process.stdin;
1253
+ /* v8 ignore next -- production stdio wiring */
1254
+ const output = config.output ?? process.stdout;
1255
+ /* v8 ignore next -- production exit wiring */
1256
+ const exit =
1257
+ config.exit ??
1258
+ ((code) => {
1259
+ process.exit(code);
1260
+ });
1261
+ const transport = new JsonRpcLineTransport(input, output);
1262
+ const server = new DshGoalJsonRpcServer(ctx, transport, {
1263
+ maxTokensAsSuccess: resolvedConfig.maxTokensAsSuccess,
1264
+ });
1265
+ // 问卷/技能目录钩子不再挂 host:agent-scoped 事件 host 收不到(且新版
1266
+ // UserQuestionService 已删 registerProvider,旧写法直接导致 boot 失败)。
1267
+ // 二者改由每次会话创建的 setup() 挂到 agent scope(见 agentSetup)。
1268
+ let exitTask;
1269
+ const disposeAndExit = () => {
1270
+ exitTask ??= (async () => {
1271
+ await Promise.allSettled([Promise.resolve().then(() => transport.flush())]);
1272
+ await Promise.allSettled([Promise.resolve().then(() => rootFiber.dispose())]);
1273
+ exit(0);
1274
+ })();
1275
+ return exitTask;
1276
+ };
1277
+ transport.onRequest(async (method, params) => {
1278
+ if (method === "initialize") await ctx.get("loader")?.await();
1279
+ const result = await server.handleRequest(method, params);
1280
+ if (method === "shutdown")
1281
+ setImmediate(() => {
1282
+ disposeAndExit();
1283
+ });
1284
+ return result;
1285
+ });
1286
+ ctx.effect(() => {
1287
+ transport.start();
1288
+ return async () => {
1289
+ await server.shutdown();
1290
+ transport.close();
1291
+ };
1292
+ }, "jsonrpc.serve");
1293
+ }
1294
+
1295
+ const name = "sdk-jsonrpc-server";
1296
+ const inject = [
1297
+ "agents",
1298
+ "goals",
1299
+ "attachments",
1300
+ "userQuestions",
1301
+ "llm",
1302
+ "tools",
1303
+ "skills",
1304
+ "systemPrompt",
1305
+ "permissionPresets",
1306
+ "approval",
1307
+ ];
1308
+
1309
+ export { Config, apply, inject, name };