keel-agent 0.124.0 → 0.125.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/packages/keel/src/adapters/sdk/prompt-render.js +5 -2
  3. package/dist/packages/keel/src/app/core-engine.js +16 -0
  4. package/dist/packages/keel/src/app/engine-dismiss.js +44 -0
  5. package/dist/packages/keel/src/app/session-registry.js +7 -1
  6. package/dist/packages/keel/src/app/subagent-runtime.js +8 -1
  7. package/dist/packages/keel/src/tool-catalog.js +5 -5
  8. package/dist/server/core-settings-adapter.js +48 -13
  9. package/dist/server/device-center/bot-chat.js +25 -0
  10. package/dist/server/device-center/bot-home.js +6 -0
  11. package/dist/server/device-center/bot-prompt.js +110 -0
  12. package/dist/server/device-center/bots.js +12 -0
  13. package/dist/server/device-center/execution-system-prompt.js +28 -13
  14. package/dist/server/device-center/local.js +126 -2
  15. package/dist/server/index.js +1 -0
  16. package/dist/server/universal/universal-session.js +8 -1
  17. package/package.json +1 -1
  18. package/web/dist/.build-assets.json +1 -1
  19. package/web/dist/assets/{BgTasksModal-D9NVLipp.js → BgTasksModal-B58Pn34o.js} +1 -1
  20. package/web/dist/assets/{BgTasksModal-CeowQkSk.js → BgTasksModal-DlRMULTX.js} +1 -1
  21. package/web/dist/assets/{BottomDock-DnXJHyg7.js → BottomDock-ix2rdS6N.js} +1 -1
  22. package/web/dist/assets/{CanvasStudio-D_RAeDdS.js → CanvasStudio-BRCkVMbW.js} +1 -1
  23. package/web/dist/assets/{CanvasStudio-BRWqZIVu.js → CanvasStudio-Cjxb3q3B.js} +1 -1
  24. package/web/dist/assets/{DeviceCenter-USAoAkin.js → DeviceCenter-BWMmB-CF.js} +1 -1
  25. package/web/dist/assets/{DeviceCenter-d49w4XXm.js → DeviceCenter-DfLlGGBZ.js} +1 -1
  26. package/web/dist/assets/{DeviceExecutionSettings-2hoZaBQ0.js → DeviceExecutionSettings-BjduyZOy.js} +1 -1
  27. package/web/dist/assets/DeviceGroupSection-B98LzFoj.js +7 -0
  28. package/web/dist/assets/DeviceGroupSection-BD3CKMFH.js +7 -0
  29. package/web/dist/assets/{DeviceGroups-BPE61M6w.js → DeviceGroups-C_lcfK5h.js} +1 -1
  30. package/web/dist/assets/DeviceGroups-ob27f-Ha.js +1 -0
  31. package/web/dist/assets/{Dropdown-DAiTWOzs.js → Dropdown-C8yx9mqF.js} +1 -1
  32. package/web/dist/assets/{FilePreview-CtSZWiJB.js → FilePreview-OxK_pI6p.js} +1 -1
  33. package/web/dist/assets/{FilePreview-xePo9QMY.js → FilePreview-inPVGc1j.js} +1 -1
  34. package/web/dist/assets/{GlobalSearchModal-CQhENYtf.js → GlobalSearchModal-3g1PplIg.js} +1 -1
  35. package/web/dist/assets/GlobalSearchModal-DG-HC0vV.js +1 -0
  36. package/web/dist/assets/{GroupConversation-DXDC1d3x.js → GroupConversation-BJnwTtT2.js} +2 -2
  37. package/web/dist/assets/{GroupConversation-CFv2RYwI.js → GroupConversation-Clt5o_lo.js} +1 -1
  38. package/web/dist/assets/{GroupWorkItems-BeZvaxV9.js → GroupWorkItems-7yTbAr_f.js} +1 -1
  39. package/web/dist/assets/{ModelConfigModal-drDDlawe.js → ModelConfigModal-CNnEGfep.js} +1 -1
  40. package/web/dist/assets/{ModelConfigModal-BI6ekcG4.js → ModelConfigModal-CYqDNXap.js} +1 -1
  41. package/web/dist/assets/{NativeCliPanel-B029dN9l.js → NativeCliPanel-B407C4qC.js} +1 -1
  42. package/web/dist/assets/{NativeCliPanel-BsehkHXc.js → NativeCliPanel-CVbFXUSf.js} +1 -1
  43. package/web/dist/assets/{PiSetupModal-D46ea4Wb.js → PiSetupModal-CrjDf0j6.js} +1 -1
  44. package/web/dist/assets/{ProviderOAuthControls-t8myaqZa.js → ProviderOAuthControls-Crhc6icP.js} +1 -1
  45. package/web/dist/assets/{SCMPanel-DUrKyvGV.js → SCMPanel-DuRJx0nl.js} +1 -1
  46. package/web/dist/assets/{SCMPanel-BKgGm9au.js → SCMPanel-rUAKnxBo.js} +1 -1
  47. package/web/dist/assets/SettingsModal-B3Q5EoVC.js +29 -0
  48. package/web/dist/assets/{SettingsModal-Bn0GTNgo.js → SettingsModal-CnJsUyvi.js} +1 -1
  49. package/web/dist/assets/{TermXterm-2oOzNy1G.js → TermXterm-BDLmWqim.js} +1 -1
  50. package/web/dist/assets/{TermXterm-D_VbvSyY.js → TermXterm-DhbhRp0B.js} +1 -1
  51. package/web/dist/assets/{TerminalPanel-CJ4ykxfy.js → TerminalPanel-D6oMxabb.js} +1 -1
  52. package/web/dist/assets/{TerminalPanel-mTL87sXL.js → TerminalPanel-Ds_hnvxz.js} +1 -1
  53. package/web/dist/assets/{ThemeMarketModal-B55xZq9j.js → ThemeMarketModal-5lH7k1in.js} +1 -1
  54. package/web/dist/assets/{ThemeMarketModal-EahvoJAf.js → ThemeMarketModal-WSOd5c6j.js} +1 -1
  55. package/web/dist/assets/{TuiOverlayModal-B2B5yRVf.js → TuiOverlayModal-Dh_HsAvo.js} +1 -1
  56. package/web/dist/assets/{TuiOverlayModal-C1uwsm1r.js → TuiOverlayModal-dKDCTdt8.js} +1 -1
  57. package/web/dist/assets/{api-client-CGqoOWHJ.js → api-client-BbDlV0jR.js} +1 -1
  58. package/web/dist/assets/{canvas-client-LIotRrYf.js → canvas-client-OwhfLxJx.js} +1 -1
  59. package/web/dist/assets/{desktop-BHN7gNP2.js → desktop-D1lGoY5p.js} +1 -1
  60. package/web/dist/assets/{fi-DjvtEEnZ.js → fi-CcqqfamG.js} +6 -6
  61. package/web/dist/assets/index-BQb8EOhk.js +410 -0
  62. package/web/dist/assets/index-Dbv9RJwm.js +410 -0
  63. package/web/dist/assets/index-xAdOV6os.css +1 -0
  64. package/web/dist/assets/{plugin-host-VdvQxFkv.js → plugin-host-DjGRLyyK.js} +1 -1
  65. package/web/dist/assets/{theme-DGfXszyo.js → theme-Dl8KLbt-.js} +1 -1
  66. package/web/dist/assets/use-copy-feedback-B3di-fnu.js +1 -0
  67. package/web/dist/index.html +11 -10
  68. package/web/dist/sw.js +1 -1
  69. package/web/dist/assets/DeviceGroupSection-CRdMGDwE.js +0 -7
  70. package/web/dist/assets/GlobalSearchModal-DpHvykpb.js +0 -1
  71. package/web/dist/assets/SettingsModal-ComFBXCj.js +0 -29
  72. package/web/dist/assets/index-4-PoF3xB.css +0 -1
  73. package/web/dist/assets/index-CXTnvcJF.js +0 -409
  74. package/web/dist/assets/index-Y0yKgBrc.js +0 -409
package/CHANGELOG.md CHANGED
@@ -10,6 +10,27 @@
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.125.0] - 2026-11-27
14
+
15
+ ### Added
16
+
17
+ - **Bot 提示词组成定制与完整预览(`BotEditorForm` / `server/device-center/bot-prompt.ts`)**:支持在 Bot 编辑表单中按来源勾选要注入的系统提示词段落(`promptSections`),一键切换「仅 Bot 提示词」或「恢复默认」,并提供实时生成与复制完整系统提示词的预览能力。
18
+ - **后台任务列表聚类卡片(`BgTaskCluster` / `web/src/bg-task-list.ts`)**:`bg_task` 工具列表结果自动解析并渲染为结构化的后台任务卡片,展示各任务状态、名称与输出摘要,支持切换查看原始文本。
19
+ - **VS Code 编辑器图片预览与文件树快捷打开(`plugins/vscode-editor`)**:支持在内置编辑器标签页中直接预览图片并显示尺寸与格式信息,新增「在编辑器中打开」入口以在当前编辑器中直接打开工作区文件。
20
+
21
+ ### Changed
22
+
23
+ - **Bot 执行与子代理提示词隔离优化**:细化 `execution-system-prompt.ts`、`core-settings-adapter.ts` 与 `subagent-runtime.ts` 的提示词分段装配与工具参数渲染。
24
+
25
+ <!-- auto-i18n:start -->
26
+
27
+ ### i18n
28
+
29
+ - 前端新增 key(17):`fileOpenInEditor`、`localBotPromptComposition`、`localBotPromptPureOnly`、`localBotPromptResetDefault`、`localBotPromptFullPreview`、`localBotPromptPreviewLoading`、`localBotPromptCopy`、`localBotPromptCopied`、`promptTok_execution`、`promptTok_execution_desc`、`promptTok_memory`、`promptTok_memory_desc`、`bgTasksTitle`、`bgTasksSummary`、`bgTasksRunning`、`bgTasksRaw`、`bgTasksHideRaw`
30
+ - 前端删除 key(4):`localBotIdentityHint`、`localBotRuntimeHint`、`localBotPermissionsHint`、`localBotPrivatePrompt`
31
+
32
+ <!-- auto-i18n:end -->
33
+
13
34
  ## [0.124.0] - 2026-11-27
14
35
 
15
36
  ### Added
@@ -23,13 +23,16 @@ export function createPromptRenderExtension(binding) {
23
23
  deferred: deferredToolNames(inventory),
24
24
  settings: binding.settings(),
25
25
  });
26
- if (!tools)
26
+ const botId = typeof binding.botId === "function" ? binding.botId() : binding.botId;
27
+ const isBot = Boolean(botId) || binding.clientId.startsWith("device-task-");
28
+ if (!tools && !isBot)
27
29
  return undefined;
28
30
  const rendered = binding.port.render({
29
31
  cwd: ctx.cwd,
30
32
  clientId: binding.clientId,
31
33
  conversationId: binding.conversationId,
32
- tools,
34
+ ...(botId ? { botId } : {}),
35
+ ...(tools ? { tools } : {}),
33
36
  });
34
37
  return typeof rendered === "string" && rendered.trim() !== "" ? { systemPrompt: rendered } : undefined;
35
38
  });
@@ -8,6 +8,7 @@ import { SubagentRegistry } from "../domains/subagents/registry.js";
8
8
  import { ClientRuntime } from "./client-runtime.js";
9
9
  import { CoreEngineNotReadyError } from "../contracts/core-engine-errors.js";
10
10
  import { resolvePiEngineAttach } from "./engine-mode.js";
11
+ import { executeDismissConversation } from "./engine-dismiss.js";
11
12
  import { resolveServerLang } from "../i18n.js";
12
13
  import { saveInterruptedRuns } from "./interrupted-runs.js";
13
14
  import { activeConversationsOf, pendingMessagesOf, serviceStatusOf } from "./engine-status.js";
@@ -410,6 +411,21 @@ export class CoreEngine {
410
411
  async takeOverConversation(targetId, ownerId, convId) {
411
412
  await executeTakeOverConversation(this.takeoverDeps, targetId, ownerId, convId);
412
413
  }
414
+ async dismissConversation(clientId, msg) {
415
+ return executeDismissConversation({
416
+ runtimes: this.runtimes,
417
+ sockets: this.sockets,
418
+ deliverTo: (id, payload) => this.deliverTo(id, payload),
419
+ cleanupOfflineRuntime: (ownerId, ownerRuntime) => {
420
+ this.runtimes.delete(ownerId);
421
+ this.connectFrames.delete(ownerId);
422
+ this.askWaiters.delete(ownerId);
423
+ this.clearOffline(ownerId);
424
+ ownerRuntime.dispose();
425
+ },
426
+ notifyExternalRunning: (ownerId) => this.notifyExternalRunning(ownerId),
427
+ }, clientId, msg);
428
+ }
413
429
  async peekElsewhereQuestion(targetId, ownerId, convId) {
414
430
  peekElsewhereQuestion(this.takeoverDeps, targetId, ownerId, convId);
415
431
  }
@@ -0,0 +1,44 @@
1
+ import { isPseudoClientId } from "../client-id-utils.js";
2
+ export async function executeDismissConversation(deps, clientId, msg) {
3
+ const requester = deps.runtimes.get(clientId);
4
+ if (requester?.registry.has(msg.id)) {
5
+ await requester.handlers().dismissConversation(msg.id, msg.withFinishedSubagents);
6
+ return true;
7
+ }
8
+ let ownerId;
9
+ let ownerRuntime;
10
+ if (msg.owner) {
11
+ const candidate = deps.runtimes.get(msg.owner);
12
+ if (candidate?.registry.has(msg.id)) {
13
+ ownerId = msg.owner;
14
+ ownerRuntime = candidate;
15
+ }
16
+ }
17
+ if (!ownerRuntime) {
18
+ for (const [cid, rt] of deps.runtimes) {
19
+ if (rt.registry.has(msg.id)) {
20
+ ownerId = cid;
21
+ ownerRuntime = rt;
22
+ break;
23
+ }
24
+ }
25
+ }
26
+ if (!ownerId || !ownerRuntime) {
27
+ deps.deliverTo(clientId, {
28
+ type: "notice",
29
+ level: "warning",
30
+ text: "该对话不存在或已关闭",
31
+ textEn: "This conversation does not exist or is already closed",
32
+ });
33
+ return false;
34
+ }
35
+ const isOffline = !isPseudoClientId(ownerId) && (deps.sockets.get(ownerId)?.size ?? 0) === 0;
36
+ if (isOffline && ownerRuntime.registry.list().length <= 1) {
37
+ deps.cleanupOfflineRuntime(ownerId, ownerRuntime);
38
+ }
39
+ else {
40
+ await ownerRuntime.handlers().dismissConversation(msg.id, msg.withFinishedSubagents);
41
+ }
42
+ deps.notifyExternalRunning(ownerId);
43
+ return true;
44
+ }
@@ -68,7 +68,13 @@ export class SessionRegistry {
68
68
  // 模板子代理(`kind: "subagent"`)的提示词完全由 loader 的模板槽位决定,组合模板不接进去
69
69
  // (老实现 `pi-webui-persona` 钩子里的 `if (apply) return undefined` 同一语义)。
70
70
  ...(this.promptRender && conv.meta.kind !== "subagent"
71
- ? { promptRender: { ...this.promptRender, conversationId: conv.id } }
71
+ ? {
72
+ promptRender: {
73
+ ...this.promptRender,
74
+ conversationId: conv.id,
75
+ botId: () => conv.meta.botId,
76
+ },
77
+ }
72
78
  : {}),
73
79
  });
74
80
  if (opened.sessionFile && opened.sessionFile !== conv.meta.sessionFile)
@@ -141,9 +141,16 @@ export function createSubagentRuntime(options) {
141
141
  // 子代理会话的档位必须在第一轮之前落到 SDK 会话上:否则跑的是 SDK 默认档(不是模板、也不是派发者)。
142
142
  applyThinkingLevel(opened.session, parentId, spec);
143
143
  void ownerRuntime.turns.start(child, opened.session, spec.prompt).then(() => {
144
+ const settled = registry.get(child.id);
145
+ if (settled?.state === "stopped")
146
+ return;
144
147
  registry.settle(child.id, { state: "done" });
145
148
  }, (error) => {
146
- registry.settle(child.id, { state: "failed", error: String(error) });
149
+ const settled = registry.get(child.id);
150
+ if (settled?.state === "stopped")
151
+ return;
152
+ const msg = error instanceof Error ? error.message : String(error);
153
+ registry.settle(child.id, { state: "failed", error: msg });
147
154
  });
148
155
  }
149
156
  catch (error) {
@@ -367,22 +367,22 @@ export function applyAgentToolsGating(session, disabled, preset, options) {
367
367
  const off = new Set(disabled);
368
368
  const allNames = session.getAllTools().map((t) => t.name);
369
369
  const initialActiveNames = new Set(session.getActiveToolNames());
370
+ const registeredExtensionToolNames = new Set((session.extensionRunner?.getAllRegisteredTools?.() ?? [])
371
+ .map((tool) => tool?.definition?.name)
372
+ .filter((name) => typeof name === "string" && name.length > 0));
370
373
  const names = new Set();
371
374
  for (const name of allNames) {
372
375
  if (isHostManagedTool(name)) {
373
376
  names.add(name);
374
377
  }
375
- else if (initialActiveNames.has(name) && !off.has(name)) {
378
+ else if ((initialActiveNames.has(name) || registeredExtensionToolNames.has(name)) && !off.has(name)) {
376
379
  names.add(name);
377
380
  }
378
381
  }
379
382
  for (const t of AGENT_TOOL_CATALOG) {
380
383
  if (off.has(t.name)) {
381
384
  const isShadowedCustomTool = t.name === toolNames.CONVERSATION_TOOL_NAME;
382
- const hasExtensionTool = isShadowedCustomTool &&
383
- Boolean(session?.extensionRunner
384
- ?.getAllRegisteredTools?.()
385
- ?.some((tool) => tool.definition?.name === t.name));
385
+ const hasExtensionTool = isShadowedCustomTool && registeredExtensionToolNames.has(t.name);
386
386
  if (!hasExtensionTool) {
387
387
  names.delete(t.name);
388
388
  }
@@ -12,7 +12,10 @@ import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, softCapReserveFor
12
12
  import { applyAgentToolsGating, effectiveDisabledAgentTools, normalizeLazyOnDemandList, lazyLoadingDisabledTools, presetShowsSkillCatalog, } from "../packages/keel/src/tool-catalog.js";
13
13
  import { LOAD_TOOLS_TOOL_NAME } from "../packages/keel/src/tool-names.js";
14
14
  import { applyToolPromptOverrides, effectiveToolPrompt, toolPromptOverrideOf, } from "./tool-prompt-overrides.js";
15
- import { BUILTIN_SOUL, buildToolsSchemaText, resolveSectionTexts, } from "./prompt-composer.js";
15
+ import { BUILTIN_SOUL, buildToolsSchemaText, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
16
+ import { getBotExecution } from "./device-center/bot-execution.js";
17
+ import { getBotChatCapability } from "./device-center/bot-chat.js";
18
+ import { composeBotSystemPrompt, resolveBotPromptSections } from "./device-center/bot-prompt.js";
16
19
  import { renderMainCompose } from "./prompt-assembler.js";
17
20
  import { formatCompactSignature } from "./tool-signature.js";
18
21
  import { readPromptBase } from "./prompt-base-store.js";
@@ -178,11 +181,15 @@ function computePromptSnapshot(options, sessionArg, target) {
178
181
  signatures[name] = sig;
179
182
  }
180
183
  }
181
- const rawSkills = loader?.getSkills?.()?.skills?.map((s) => ({
184
+ const rawSkillsAll = loader?.getSkills?.()?.skills?.map((s) => ({
182
185
  name: s.name,
183
186
  description: s.description ?? "",
184
187
  filePath: s.filePath ?? "",
185
188
  })) ?? [];
189
+ const allowedSkillSet = target?.allowedSkills ? new Set(target.allowedSkills) : undefined;
190
+ const rawSkills = allowedSkillSet
191
+ ? rawSkillsAll.filter((s) => allowedSkillSet.has(s.name))
192
+ : rawSkillsAll;
186
193
  const showSkills = presetShowsSkillCatalog(preset);
187
194
  const effectiveSkills = showSkills
188
195
  ? fillSkillContents(rawSkills, settings.skillsFullText, {
@@ -211,16 +218,18 @@ function computePromptSnapshot(options, sessionArg, target) {
211
218
  skillsCatalogBudget: settings.skillsCatalogBudget,
212
219
  };
213
220
  const texts = resolveSectionTexts(inputs);
214
- const rendered = renderMainCompose(inputs, {
215
- promptTemplate: settings.promptTemplate,
216
- promptOverrides: settings.promptOverrides,
217
- promptDisabled: settings.promptDisabled ?? [],
218
- preset,
219
- disabledToolCount: effectiveDisabledAgentTools(settings).length,
220
- isLazy: lazyOn,
221
- hasSkills: effectiveSkills.length > 0,
222
- hasSkillsFullText: (settings.skillsFullText?.length ?? 0) > 0,
223
- });
221
+ const rendered = target?.skipGlobalPrompt
222
+ ? renderPromptTemplate("{{tools}}\n\n{{skills}}\n\n{{cwd}}", texts, undefined)
223
+ : renderMainCompose(inputs, {
224
+ promptTemplate: settings.promptTemplate,
225
+ promptOverrides: settings.promptOverrides,
226
+ promptDisabled: settings.promptDisabled ?? [],
227
+ preset,
228
+ disabledToolCount: effectiveDisabledAgentTools(settings).length,
229
+ isLazy: lazyOn,
230
+ hasSkills: effectiveSkills.length > 0,
231
+ hasSkillsFullText: (settings.skillsFullText?.length ?? 0) > 0,
232
+ });
224
233
  const constraints = buildPlatformConstraints({
225
234
  remoteCwd: isRemoteWorkspaceUri(realCwd) ? realCwd : undefined,
226
235
  planMode: false,
@@ -241,11 +250,37 @@ function computePromptSnapshot(options, sessionArg, target) {
241
250
  */
242
251
  function renderTurnPrompt(options, input) {
243
252
  const settings = options.stateStore.getSettings(options.clientId);
244
- if (!lazyEffectiveOf(settings))
253
+ const botExecution = getBotExecution(input.clientId) ?? (input.botId ? getBotChatCapability(input.botId) : undefined);
254
+ if (!botExecution && !lazyEffectiveOf(settings))
245
255
  return undefined;
246
256
  const session = sessionOfConversation(options, input.conversationId);
247
257
  if (!session)
248
258
  return undefined;
259
+ if (botExecution) {
260
+ const selectedSections = resolveBotPromptSections(botExecution.bot);
261
+ const snapshot = computePromptSnapshot(options, session, {
262
+ cwd: input.cwd,
263
+ tools: input.tools,
264
+ allowedSkills: botExecution.bot.skills,
265
+ });
266
+ const realCwd = restoreWorkspaceUriFromSessionDir(input.cwd);
267
+ const constraints = buildPlatformConstraints({
268
+ remoteCwd: isRemoteWorkspaceUri(realCwd) ? realCwd : undefined,
269
+ planMode: false,
270
+ delegateMode: false,
271
+ planPrompt: { mode: settings.planModePromptMode, custom: settings.planModePrompt },
272
+ });
273
+ const result = composeBotSystemPrompt({
274
+ sectionTexts: snapshot.texts,
275
+ promptOverrides: settings.promptOverrides,
276
+ botSystemPrompt: botExecution.bot.systemPrompt,
277
+ executionInstructions: botExecution.instructions,
278
+ memoryBlock: botExecution.memoryBlock,
279
+ constraints,
280
+ selectedSections,
281
+ });
282
+ return result.full || undefined;
283
+ }
249
284
  const snapshot = computePromptSnapshot(options, session, { cwd: input.cwd, tools: input.tools });
250
285
  return snapshot.full.trim() === "" ? undefined : snapshot.full;
251
286
  }
@@ -291,6 +291,29 @@ export function pickBotChatConversation(conversations, botId, activeId) {
291
291
  }
292
292
  return best;
293
293
  }
294
+ const chatCapabilitiesByBotId = new Map();
295
+ /** 获取私聊会话的 Bot 提示词上下文(优先读取注册表最新配置,改完 Bot 提示词下一轮即生效)。 */
296
+ export function getBotChatCapability(botId) {
297
+ const cached = chatCapabilitiesByBotId.get(botId);
298
+ let latest;
299
+ try {
300
+ const resolved = host?.resolve(botId);
301
+ if (resolved && typeof resolved.then !== "function") {
302
+ const candidate = resolved;
303
+ if (candidate.enabled)
304
+ latest = candidate;
305
+ }
306
+ }
307
+ catch { }
308
+ const bot = latest ?? cached?.bot;
309
+ if (!bot)
310
+ return undefined;
311
+ return {
312
+ bot,
313
+ instructions: cached?.instructions ?? "",
314
+ memoryBlock: cached?.memoryBlock,
315
+ };
316
+ }
294
317
  /**
295
318
  * 为一个私聊会话准备常驻的 Bot 能力(工具白名单 / 技能过滤 / 记忆 / 模型)。
296
319
  * 返回的 capability 会活到进程结束:不像设备任务那样一轮一 release——私聊会话要一直能接着聊。
@@ -322,5 +345,7 @@ export async function createBotChatCapability(botId) {
322
345
  memoryRoot,
323
346
  memoryBlock,
324
347
  });
348
+ chatCapabilitiesByBotId.get(bot.id)?.revoke();
349
+ chatCapabilitiesByBotId.set(bot.id, binding.capability);
325
350
  return { bot, capability: binding.capability };
326
351
  }
@@ -44,6 +44,8 @@ export async function exportBotHome(dataDir, bot) {
44
44
  name: bot.name,
45
45
  description: bot.description,
46
46
  systemPrompt: bot.systemPrompt,
47
+ ...(bot.useGlobalPrompt !== undefined ? { useGlobalPrompt: bot.useGlobalPrompt } : {}),
48
+ ...(bot.promptSections !== undefined ? { promptSections: [...bot.promptSections] } : {}),
47
49
  cwd: bot.cwd,
48
50
  ...(bot.model ? { model: { provider: bot.model.provider, modelId: bot.model.modelId } } : {}),
49
51
  tools: [...bot.tools],
@@ -112,6 +114,10 @@ export function parseBotHomeBundle(raw) {
112
114
  name: text(botDef.name, 200, "name"),
113
115
  description: typeof botDef.description === "string" ? botDef.description.slice(0, 4000) : "",
114
116
  systemPrompt: typeof botDef.systemPrompt === "string" ? botDef.systemPrompt.slice(0, 32 * 1024) : "",
117
+ ...(typeof botDef.useGlobalPrompt === "boolean" ? { useGlobalPrompt: botDef.useGlobalPrompt } : {}),
118
+ ...(Array.isArray(botDef.promptSections)
119
+ ? { promptSections: list(botDef.promptSections, "promptSections") }
120
+ : {}),
115
121
  cwd: typeof botDef.cwd === "string" ? botDef.cwd : "",
116
122
  ...(model && typeof model.provider === "string" && typeof model.modelId === "string"
117
123
  ? { model: { provider: model.provider, modelId: model.modelId } }
@@ -0,0 +1,110 @@
1
+ import { estimateTokens } from "@earendil-works/pi-coding-agent";
2
+ import { appendConstraints } from "../platform-constraints.js";
3
+ import { DEFAULT_PROMPT_TEMPLATE, PROMPT_TOKENS, renderPromptTemplate } from "../prompt-composer.js";
4
+ import { appendBotExecutionSections } from "./execution-system-prompt.js";
5
+ /** Bot 提示词可勾选的所有来源段(与主提示词 token 保持同源,外加 Bot 专属的执行策略与记忆)。 */
6
+ export const BOT_PROMPT_SECTIONS = [...PROMPT_TOKENS, "execution", "memory"];
7
+ export const DEFAULT_BOT_PROMPT_SECTIONS_WITH_GLOBAL = [
8
+ "soul",
9
+ "context",
10
+ "tools",
11
+ "skills",
12
+ "cwd",
13
+ "append",
14
+ "execution",
15
+ "memory",
16
+ ];
17
+ export const DEFAULT_BOT_PROMPT_SECTIONS_WITHOUT_GLOBAL = [
18
+ "tools",
19
+ "skills",
20
+ "cwd",
21
+ "memory",
22
+ ];
23
+ export function isBotPromptSection(value) {
24
+ return BOT_PROMPT_SECTIONS.includes(value);
25
+ }
26
+ /** 根据 Bot 配置解析当前启用的提示词段集合。 */
27
+ export function resolveBotPromptSections(bot) {
28
+ if (Array.isArray(bot.promptSections)) {
29
+ const valid = [];
30
+ for (const item of bot.promptSections) {
31
+ if (isBotPromptSection(item) && !valid.includes(item))
32
+ valid.push(item);
33
+ }
34
+ return valid;
35
+ }
36
+ return bot.useGlobalPrompt === false
37
+ ? [...DEFAULT_BOT_PROMPT_SECTIONS_WITHOUT_GLOBAL]
38
+ : [...DEFAULT_BOT_PROMPT_SECTIONS_WITH_GLOBAL];
39
+ }
40
+ function estimateSectionTokens(text) {
41
+ const trimmed = text.trim();
42
+ if (!trimmed)
43
+ return 0;
44
+ try {
45
+ return estimateTokens({ role: "user", content: trimmed, timestamp: 0 });
46
+ }
47
+ catch {
48
+ return Math.ceil(trimmed.length / 4);
49
+ }
50
+ }
51
+ /**
52
+ * 组装 Bot 最终系统提示词(运行时与设置预览共用同一份纯函数,确保所见即所得)。
53
+ */
54
+ export function composeBotSystemPrompt(input) {
55
+ const selectedSet = new Set(input.selectedSections);
56
+ const useSoul = selectedSet.has("soul");
57
+ const disabledTokens = new Set(PROMPT_TOKENS.filter((t) => !selectedSet.has(t)));
58
+ const effectiveOverrides = input.promptOverrides && useSoul
59
+ ? input.promptOverrides
60
+ : input.promptOverrides
61
+ ? Object.fromEntries(Object.entries(input.promptOverrides).filter(([k]) => selectedSet.has(k)))
62
+ : undefined;
63
+ const envRendered = renderPromptTemplate(DEFAULT_PROMPT_TEMPLATE, input.sectionTexts, effectiveOverrides, disabledTokens);
64
+ const withConstraints = input.constraints ? appendConstraints(envRendered, input.constraints) : envRendered;
65
+ const botPrompt = input.botSystemPrompt?.trim() ?? "";
66
+ const execText = selectedSet.has("execution") ? (input.executionInstructions?.trim() ?? "") : "";
67
+ const memText = selectedSet.has("memory") ? (input.memoryBlock?.trim() ?? "") : "";
68
+ let full;
69
+ if (!useSoul) {
70
+ // 未启用全局 soul 时,Bot 自身提示词直接作为核心主体前置,不额外包 <device_bot> 壳子。
71
+ const base = [botPrompt, withConstraints.trim()].filter(Boolean).join("\n\n");
72
+ full = appendBotExecutionSections(base, {
73
+ bot: {},
74
+ instructions: execText,
75
+ memoryBlock: memText,
76
+ });
77
+ }
78
+ else {
79
+ full = appendBotExecutionSections(withConstraints, {
80
+ bot: { systemPrompt: botPrompt },
81
+ instructions: execText,
82
+ memoryBlock: memText,
83
+ });
84
+ }
85
+ const sections = BOT_PROMPT_SECTIONS.map((id) => {
86
+ let text = "";
87
+ if (id === "execution") {
88
+ text = input.executionInstructions?.trim() ?? "";
89
+ }
90
+ else if (id === "memory") {
91
+ text = input.memoryBlock?.trim() ?? "";
92
+ }
93
+ else {
94
+ const ov = effectiveOverrides?.[id]?.trim();
95
+ text = ov || (input.sectionTexts[id]?.trim() ?? "");
96
+ }
97
+ return {
98
+ id,
99
+ enabled: selectedSet.has(id),
100
+ text,
101
+ tokens: estimateSectionTokens(text),
102
+ };
103
+ });
104
+ return {
105
+ full: full.trim(),
106
+ sections,
107
+ selectedSections: [...selectedSet],
108
+ totalTokens: estimateSectionTokens(full),
109
+ };
110
+ }
@@ -3,6 +3,7 @@ import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/p
3
3
  import { join } from "node:path";
4
4
  import { DeviceWorkspaceError, validateDeviceProject } from "./workspaces.js";
5
5
  import { isBotToolHighPrivilege } from "./bot-execution.js";
6
+ import { isBotPromptSection } from "./bot-prompt.js";
6
7
  function fail(status, code, message) {
7
8
  throw new DeviceWorkspaceError(status, code, message);
8
9
  }
@@ -38,6 +39,15 @@ function validate(input) {
38
39
  }
39
40
  if (input.trigger !== undefined && !["on_demand", "always_on", "scheduled"].includes(input.trigger))
40
41
  fail(400, "BOT_INVALID", "Invalid Bot trigger");
42
+ if (input.useGlobalPrompt !== undefined && typeof input.useGlobalPrompt !== "boolean")
43
+ fail(400, "BOT_INVALID", "Invalid Bot useGlobalPrompt");
44
+ if (input.promptSections !== undefined) {
45
+ if (!Array.isArray(input.promptSections) ||
46
+ input.promptSections.length > 32 ||
47
+ input.promptSections.some((v) => typeof v !== "string" || !isBotPromptSection(v)) ||
48
+ new Set(input.promptSections).size !== input.promptSections.length)
49
+ fail(400, "BOT_INVALID", "Invalid Bot promptSections");
50
+ }
41
51
  if (input.identity !== undefined &&
42
52
  (!input.identity ||
43
53
  (input.identity.authoredBy !== "human" && input.identity.authoredBy !== "model") ||
@@ -56,6 +66,8 @@ function validate(input) {
56
66
  skills: [...input.skills],
57
67
  mcpServers: [...input.mcpServers],
58
68
  enabled: input.enabled,
69
+ ...(input.useGlobalPrompt !== undefined ? { useGlobalPrompt: input.useGlobalPrompt } : {}),
70
+ ...(input.promptSections !== undefined ? { promptSections: [...input.promptSections] } : {}),
59
71
  revision: input.revision,
60
72
  ...(input.trigger ? { trigger: input.trigger } : {}),
61
73
  ...(input.identity
@@ -1,9 +1,12 @@
1
1
  import { splitAgentStartPrompt } from "../persona-chain.js";
2
2
  const ownedSections = ["device_bot", "device_execution", "device_memory"];
3
- export function prepareBotExecutionSystemPrompt(event, execution) {
4
- const { pre, core, post } = splitAgentStartPrompt(event);
5
- if (!execution)
6
- return { core, rewrap: (next) => pre + next + post };
3
+ function stripOwnedSections(text) {
4
+ for (const name of ownedSections) {
5
+ text = text.replace(new RegExp(`<${name}>\\n[\\s\\S]*?\\n</${name}>`, "g"), "");
6
+ }
7
+ return text;
8
+ }
9
+ function buildExecutionSections(execution) {
7
10
  const sections = {};
8
11
  if (execution.bot.systemPrompt?.trim())
9
12
  sections.device_bot = execution.bot.systemPrompt.trim();
@@ -11,21 +14,33 @@ export function prepareBotExecutionSystemPrompt(event, execution) {
11
14
  sections.device_execution = execution.instructions.trim();
12
15
  if (execution.memoryBlock?.trim())
13
16
  sections.device_memory = execution.memoryBlock.trim();
17
+ return sections;
18
+ }
19
+ function renderExecutionSections(sections) {
20
+ return Object.entries(sections)
21
+ .map(([name, content]) => `<${name}>\n${content}\n</${name}>`)
22
+ .join("\n\n");
23
+ }
24
+ /** 将 Bot 自身提示词、执行指令与记忆块追加到系统提示词末尾(幂等替换同名标签段)。 */
25
+ export function appendBotExecutionSections(base, execution) {
26
+ const cleaned = stripOwnedSections(base).trimEnd();
27
+ const rendered = renderExecutionSections(buildExecutionSections(execution));
28
+ if (!rendered)
29
+ return cleaned;
30
+ return cleaned ? `${cleaned}\n\n${rendered}` : rendered;
31
+ }
32
+ export function prepareBotExecutionSystemPrompt(event, execution) {
33
+ const { pre, core, post } = splitAgentStartPrompt(event);
34
+ if (!execution)
35
+ return { core, rewrap: (next) => pre + next + post };
36
+ const sections = buildExecutionSections(execution);
14
37
  if (event.systemPromptOptions) {
15
38
  const target = (event.systemPromptOptions.sections ??= {});
16
39
  for (const name of ownedSections)
17
40
  delete target[name];
18
41
  Object.assign(target, sections);
19
42
  }
20
- const stripOwnedSections = (text) => {
21
- for (const name of ownedSections) {
22
- text = text.replace(new RegExp(`<${name}>\\n[\\s\\S]*?\\n</${name}>`, "g"), "");
23
- }
24
- return text;
25
- };
26
- const rendered = Object.entries(sections)
27
- .map(([name, content]) => `<${name}>\n${content}\n</${name}>`)
28
- .join("\n\n");
43
+ const rendered = renderExecutionSections(sections);
29
44
  const rewrap = (next) => {
30
45
  const wrapped = stripOwnedSections(pre + next + post);
31
46
  return rendered ? `${wrapped.trimEnd()}\n\n${rendered}` : wrapped;