pi-web-ui 0.99.0 → 0.101.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 (109) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.md +48 -45
  3. package/README.zh-CN.md +43 -40
  4. package/bin/pi-web-ui.mjs +172 -40
  5. package/dist/server/agent-formatters.js +191 -0
  6. package/dist/server/agent-service-daemon.js +1266 -0
  7. package/dist/server/agent-service.js +9851 -11892
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +130 -184
  10. package/dist/server/ask-user-question-tool.js +94 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/attachments.js +55 -0
  13. package/dist/server/bash-tool.js +83 -0
  14. package/dist/server/bg-servers.js +82 -2
  15. package/dist/server/browser-page-tool.js +207 -0
  16. package/dist/server/claim-files-tool.js +4 -4
  17. package/dist/server/client-id-utils.js +51 -0
  18. package/dist/server/client-state.js +63 -1
  19. package/dist/server/compact-context-tool.js +10 -9
  20. package/dist/server/compaction-markers.js +34 -1
  21. package/dist/server/context-budget-runner.js +43 -0
  22. package/dist/server/conversation-read-tool.js +7 -8
  23. package/dist/server/conversation-touches.js +19 -0
  24. package/dist/server/dangling-tools.js +18 -5
  25. package/dist/server/delegate-mode.js +1 -0
  26. package/dist/server/delegate-task.js +10 -14
  27. package/dist/server/dispatch-domain-handlers.js +631 -0
  28. package/dist/server/dispatch-plugin-handlers.js +300 -0
  29. package/dist/server/dsh/dsh-agent-service.js +125 -13
  30. package/dist/server/edit-soft-tool.js +10 -12
  31. package/dist/server/eval-tool.js +4 -5
  32. package/dist/server/goal-evidence.js +180 -0
  33. package/dist/server/goal-service.js +49 -9
  34. package/dist/server/hashline-engine.js +199 -32
  35. package/dist/server/index.js +212 -944
  36. package/dist/server/left-panel-running.js +115 -0
  37. package/dist/server/load-tools-tool.js +100 -0
  38. package/dist/server/lsp-tool.js +50 -28
  39. package/dist/server/marker-service.js +53 -12
  40. package/dist/server/markers/builtins/action.js +108 -0
  41. package/dist/server/markers/index.js +4 -1
  42. package/dist/server/markers-list-tool.js +34 -0
  43. package/dist/server/market-service.js +277 -0
  44. package/dist/server/mcp-bridge.js +137 -30
  45. package/dist/server/mcp-hot-reload.js +84 -27
  46. package/dist/server/mcp-manager.js +215 -0
  47. package/dist/server/message-entry-resolver.js +32 -0
  48. package/dist/server/orphan-manager.js +44 -0
  49. package/dist/server/patch-remote-catalog.js +28 -10
  50. package/dist/server/patch-tool.js +9 -8
  51. package/dist/server/persona-chain.js +63 -0
  52. package/dist/server/plan-mode.js +9 -6
  53. package/dist/server/plan-update-tool.js +96 -0
  54. package/dist/server/plugin-api-catalog.js +30 -3
  55. package/dist/server/plugin-conversation-view.js +47 -0
  56. package/dist/server/plugin-facilities.js +13 -3
  57. package/dist/server/plugin-ui-slots.js +39 -0
  58. package/dist/server/plugins.js +183 -63
  59. package/dist/server/present-files-tool.js +10 -11
  60. package/dist/server/preset-fields.js +700 -0
  61. package/dist/server/preset-share.js +1179 -0
  62. package/dist/server/process-utils.js +30 -0
  63. package/dist/server/prompt-assembler.js +80 -0
  64. package/dist/server/prompt-composer.js +23 -9
  65. package/dist/server/protocol-version.js +1 -1
  66. package/dist/server/read-tool.js +8 -10
  67. package/dist/server/resolve-global-sdk.js +80 -18
  68. package/dist/server/schedule-agent-tool.js +147 -146
  69. package/dist/server/scm-commitmsg.js +74 -0
  70. package/dist/server/sdk-origin.js +125 -37
  71. package/dist/server/serialize.js +97 -7
  72. package/dist/server/session-branch.js +367 -0
  73. package/dist/server/session-parser.js +235 -0
  74. package/dist/server/session-search.js +158 -0
  75. package/dist/server/settings-service.js +115 -84
  76. package/dist/server/skill-content-filler.js +33 -0
  77. package/dist/server/skill-tool.js +3 -4
  78. package/dist/server/subagent-handoff.js +18 -0
  79. package/dist/server/subagent-helpers.js +88 -0
  80. package/dist/server/subagents.js +15 -22
  81. package/dist/server/terminals.js +171 -91
  82. package/dist/server/tool-approval.js +3 -1
  83. package/dist/server/tool-guards.js +527 -0
  84. package/dist/server/tool-host-factories.js +217 -0
  85. package/dist/server/tool-manager.js +84 -23
  86. package/dist/server/tool-prompt-overrides.js +158 -0
  87. package/dist/server/tool-prompts.js +42 -0
  88. package/dist/server/tool-signature.js +104 -0
  89. package/dist/server/wait-subscription-scan.js +46 -1
  90. package/dist/server/workspace-snapshot.js +60 -11
  91. package/extensions/webui.ts +90 -24
  92. package/package.json +5 -3
  93. package/plugin-sdk/README.md +25 -4
  94. package/plugin-sdk/import-check.mjs +210 -0
  95. package/plugin-sdk/index.d.ts +21 -1
  96. package/plugin-sdk/index.mjs +6 -0
  97. package/plugins/catalog.json +53 -2
  98. package/themes/aetheris.css +3 -1
  99. package/themes/translucent.css +8 -1
  100. package/themes/transparent.css +9 -1
  101. package/themes/zhupi-dark.css +1 -1
  102. package/themes/zhupi.css +1 -1
  103. package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-DD7I5_aC.js} +2 -2
  104. package/web/dist/assets/index-CpjA1YdT.css +1 -0
  105. package/web/dist/assets/index-nKn87VuM.js +678 -0
  106. package/web/dist/index.html +2 -2
  107. package/web/dist/sw.js +1 -1
  108. package/web/dist/assets/index-BdMaGCcs.css +0 -1
  109. package/web/dist/assets/index-ByCBN4Kt.js +0 -368
@@ -9,13 +9,16 @@
9
9
  import { existsSync, readdirSync, readFileSync } from "node:fs";
10
10
  import { basename, dirname, join } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
- import { extensionKey, normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeSkillList, normalizeToolWatchdogTimeoutMs, normalizeUiLayout, } from "./client-state.js";
12
+ import { extensionKey, normalizeBgCleanupMinutes, normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeKeepRecentMessages, normalizeSkillList, normalizeToolWatchdogTimeoutMs, normalizeUiLayout, settingsPresetToUi, } from "./client-state.js";
13
13
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
14
  import { findVisionModels, SYSTEM_PROMPT } from "./vision-bridge.js";
15
15
  import { COMMITMSG_SYSTEM_PROMPT } from "./scm-commitmsg.js";
16
16
  import { PLAN_MODE_SYSTEM_PROMPT } from "./plan-mode.js";
17
17
  import { DEFAULT_TEMPLATES } from "./subagent-templates.js";
18
18
  import { deriveLegacy, foldLegacyIntoDisabled, normalizeDisabledAgentTools } from "./tool-manager.js";
19
+ import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
20
+ import { resolveServerLang } from "./i18n.js";
21
+ import { exportPresetVia, importPresetFromUrlVia, importPresetVia, packageVersion, pushPresetCatalogVia, sharePresetVia, } from "./preset-share.js";
19
22
  export class SettingsService {
20
23
  host;
21
24
  templates;
@@ -276,6 +279,11 @@ export class SettingsService {
276
279
  const legacyTools = deriveLegacy(this.settings.disabledAgentTools ?? []);
277
280
  // 当前会话提示词快照:完整生效文本 + 各来源默认(自动)内容(只读预览)。
278
281
  const promptSnap = this.host.promptSnapshot();
282
+ const mcp = this.host.getMcpServers?.() ?? {
283
+ servers: [],
284
+ globalPath: "",
285
+ projectPath: "",
286
+ };
279
287
  this.host.emit({
280
288
  type: "settings_state",
281
289
  settings: {
@@ -283,6 +291,7 @@ export class SettingsService {
283
291
  customSystemPrompt: this.settings.customSystemPrompt,
284
292
  promptTemplate: this.settings.promptTemplate ?? "",
285
293
  promptOverrides: { ...this.settings.promptOverrides },
294
+ toolPromptOverrides: { ...this.settings.toolPromptOverrides },
286
295
  disabledAgentTools: [...normalizeDisabledAgentTools(this.settings.disabledAgentTools)],
287
296
  disabledPluginTools: [...normalizeDisabledPluginTools(this.settings.disabledPluginTools)],
288
297
  terminalToolsEnabled: legacyTools.terminalToolsEnabled,
@@ -291,6 +300,8 @@ export class SettingsService {
291
300
  terminalBashMaxForegroundMs: this.settings.terminalBashMaxForegroundMs,
292
301
  toolWatchdogTimeoutMs: this.settings.toolWatchdogTimeoutMs,
293
302
  readDirEnabled: this.settings.readDirEnabled !== false,
303
+ bgAutoCleanupMin: normalizeBgCleanupMinutes(this.settings.bgAutoCleanupMin),
304
+ toolLazyLoading: this.settings.toolLazyLoading !== false,
294
305
  toolApprovalEnabled: this.settings.toolApprovalEnabled !== false,
295
306
  approvalPolicy: this.host.getApprovalPolicy?.() ?? { allowAll: false, categories: [] },
296
307
  approvalRules: this.approvalRules?.list() ?? [],
@@ -303,6 +314,7 @@ export class SettingsService {
303
314
  thinkingWrap: this.settings.thinkingWrap,
304
315
  toolsWrap: this.settings.toolsWrap,
305
316
  toolImagesEnabled: this.settings.toolImagesEnabled ?? true,
317
+ keepRecentMessages: normalizeKeepRecentMessages(this.settings.keepRecentMessages),
306
318
  visionBridgeEnabled: this.settings.visionBridgeEnabled,
307
319
  visionBridgeModel: this.settings.visionBridgeModel,
308
320
  visionBridgePromptMode: this.settings.visionBridgePromptMode,
@@ -331,7 +343,7 @@ export class SettingsService {
331
343
  skills,
332
344
  reviewSkills,
333
345
  extensions,
334
- presets: this.presets.map((p) => ({ ...p })),
346
+ presets: this.presets.map(settingsPresetToUi),
335
347
  ...(this.host.getMarkerState
336
348
  ? this.host.getMarkerState()
337
349
  : {
@@ -349,6 +361,9 @@ export class SettingsService {
349
361
  quickPhrases: [...this.settings.quickPhrases],
350
362
  quickPhrasesEnabled: this.settings.quickPhrasesEnabled,
351
363
  quickPhrasesSeeded: this.host.stateStore.getQuickPhrasesSeeded(),
364
+ mcpServers: mcp.servers,
365
+ mcpGlobalConfigPath: mcp.globalPath,
366
+ mcpProjectConfigPath: mcp.projectPath,
352
367
  },
353
368
  });
354
369
  }
@@ -405,7 +420,9 @@ export class SettingsService {
405
420
  partial.disabledPlugins !== undefined ||
406
421
  partial.terminalToolsEnabled !== undefined ||
407
422
  partial.editSoftEnabled !== undefined ||
408
- partial.questionnaireEnabled !== undefined;
423
+ partial.questionnaireEnabled !== undefined ||
424
+ partial.toolPromptOverrides !== undefined ||
425
+ partial.toolLazyLoading !== undefined;
409
426
  if (partial.promptMode !== undefined)
410
427
  this.settings.promptMode = partial.promptMode;
411
428
  if (partial.customSystemPrompt !== undefined) {
@@ -425,6 +442,18 @@ export class SettingsService {
425
442
  }
426
443
  this.settings.promptOverrides = next;
427
444
  }
445
+ if (partial.toolPromptOverrides !== undefined) {
446
+ // 逐工具合并:给出的键整体替换(归一化后为空 = 清除该工具覆盖)。
447
+ const next = { ...this.settings.toolPromptOverrides };
448
+ const normalized = normalizeToolPromptOverrides(partial.toolPromptOverrides);
449
+ for (const key of Object.keys(partial.toolPromptOverrides)) {
450
+ if (normalized[key])
451
+ next[key] = normalized[key];
452
+ else
453
+ delete next[key];
454
+ }
455
+ this.settings.toolPromptOverrides = normalizeToolPromptOverrides(next);
456
+ }
428
457
  if (partial.disabledSkills !== undefined) {
429
458
  this.settings.disabledSkills = partial.disabledSkills;
430
459
  }
@@ -478,6 +507,16 @@ export class SettingsService {
478
507
  if (partial.readDirEnabled !== undefined) {
479
508
  this.settings.readDirEnabled = partial.readDirEnabled;
480
509
  }
510
+ // 「后台任务」自动清理阈值(分钟;0 = 关):bg-servers 的定时器每轮实时读,即时生效。
511
+ if (partial.bgAutoCleanupMin !== undefined) {
512
+ this.settings.bgAutoCleanupMin = normalizeBgCleanupMinutes(partial.bgAutoCleanupMin);
513
+ }
514
+ // 工具延迟加载开关(默认开):门控每次实时读取,改动经 applyToolGating 重放生效
515
+ // (见 toolGatingChanged)——**只影响新会话与之后的门控重放**,已有对话的已加载
516
+ // 集合不会被反向清空(不想让在跑的对话凭空丢掉工具)。
517
+ if (partial.toolLazyLoading !== undefined) {
518
+ this.settings.toolLazyLoading = partial.toolLazyLoading !== false;
519
+ }
481
520
  // 工具执行审批总开关:审批入口每次实时读取(askApproval 顶部门禁),无需 reload。
482
521
  if (partial.toolApprovalEnabled !== undefined) {
483
522
  this.settings.toolApprovalEnabled = partial.toolApprovalEnabled;
@@ -509,6 +548,9 @@ export class SettingsService {
509
548
  if (partial.toolImagesEnabled !== undefined) {
510
549
  this.settings.toolImagesEnabled = partial.toolImagesEnabled;
511
550
  }
551
+ if (partial.keepRecentMessages !== undefined) {
552
+ this.settings.keepRecentMessages = normalizeKeepRecentMessages(partial.keepRecentMessages);
553
+ }
512
554
  // 编排模式 / skill 全文注入:before_agent_start 逐 run 实时读取(agent-service
513
555
  // composeInputs + 指导块追加),开关下一轮即生效,无需 reload runtime。
514
556
  if (partial.skillsFullText !== undefined) {
@@ -588,7 +630,7 @@ export class SettingsService {
588
630
  if (needsReload)
589
631
  await this.applyRuntime();
590
632
  }
591
- /** Save the CURRENT settings as a named preset (overwrites if exists). */
633
+ /** 保存当前设置为命名预设(同名覆盖)。 */
592
634
  async savePreset(name) {
593
635
  const n = name.trim();
594
636
  if (!n) {
@@ -600,28 +642,7 @@ export class SettingsService {
600
642
  });
601
643
  return;
602
644
  }
603
- const preset = {
604
- name: n,
605
- promptMode: this.settings.promptMode,
606
- customSystemPrompt: this.settings.customSystemPrompt,
607
- promptTemplate: this.settings.promptTemplate ?? "",
608
- promptOverrides: { ...this.settings.promptOverrides },
609
- disabledSkills: [...this.settings.disabledSkills],
610
- disabledExtensions: [...this.settings.disabledExtensions],
611
- disabledAgentTools: [...normalizeDisabledAgentTools(this.settings.disabledAgentTools)],
612
- disabledPluginTools: [...normalizeDisabledPluginTools(this.settings.disabledPluginTools)],
613
- terminalToolsEnabled: this.settings.terminalToolsEnabled,
614
- terminalBash: this.settings.terminalBash,
615
- terminalBashIdleMs: this.settings.terminalBashIdleMs,
616
- terminalBashMaxForegroundMs: this.settings.terminalBashMaxForegroundMs,
617
- editSoftEnabled: this.settings.editSoftEnabled,
618
- retryMaxAttempts: this.settings.retryMaxAttempts,
619
- softCapTokens: this.settings.softCapTokens,
620
- softCapByModel: { ...this.settings.softCapByModel },
621
- reviewPrompt: this.settings.reviewPrompt,
622
- reviewDisabledSkills: [...this.settings.reviewDisabledSkills],
623
- skillsFullText: [...normalizeSkillList(this.settings.skillsFullText)],
624
- };
645
+ const preset = this.snapshotPreset(n);
625
646
  const existing = this.presets.findIndex((p) => p.name === n);
626
647
  if (existing >= 0)
627
648
  this.presets[existing] = preset;
@@ -630,6 +651,13 @@ export class SettingsService {
630
651
  this.host.stateStore.savePresets(this.host.clientId, this.presets);
631
652
  this.push();
632
653
  }
654
+ /** 把当前设置快照成一条预设(名字由调用方给定)。
655
+ * **全量**:`ClientSettings` 的每个字段都进预设(字段清单/分组见 `server/preset-fields.ts`),
656
+ * 导出/分享/导入共用同一张白名单;深层对象做一份拷贝,避免与当前设置共享引用。 */
657
+ snapshotPreset(name) {
658
+ const s = structuredClone(this.settings);
659
+ return { ...s, name };
660
+ }
633
661
  /** Replace the current settings with the named preset and apply it. */
634
662
  async applyPreset(name) {
635
663
  const p = this.presets.find((x) => x.name === name);
@@ -642,74 +670,27 @@ export class SettingsService {
642
670
  });
643
671
  return;
644
672
  }
645
- // 统一工具开关随预设走;旧预设缺新字段时按遗留两开关折算(问卷不进预设,
646
- // 从当前禁用名单继承,即保留当前问卷状态)。
673
+ // 统一工具开关:新预设直接用它;旧预设(只有遗留两开关)按当前禁用名单折算。
647
674
  const presetDisabled = normalizeDisabledAgentTools(p.disabledAgentTools ??
648
675
  foldLegacyIntoDisabled(this.settings.disabledAgentTools ?? [], {
649
676
  terminalToolsEnabled: p.terminalToolsEnabled,
650
677
  editSoftEnabled: p.editSoftEnabled,
651
678
  }));
652
679
  const presetLegacy = deriveLegacy(presetDisabled);
680
+ // 全量预设 = 当前设置叠加预设里**实际存在**的字段(缺字段保持当前值)。
681
+ // 旧预设(19 字段)、以及导入时只勾了一部分的预设,都靠这个 merge 落地。
682
+ const patch = { ...p };
683
+ delete patch.name;
684
+ for (const k of Object.keys(patch))
685
+ if (patch[k] === undefined)
686
+ delete patch[k];
653
687
  this.settings = {
654
- promptMode: p.promptMode,
655
- customSystemPrompt: p.customSystemPrompt,
656
- promptTemplate: p.promptTemplate ?? this.settings.promptTemplate ?? "",
657
- promptOverrides: { ...(p.promptOverrides ?? this.settings.promptOverrides) },
658
- disabledSkills: [...p.disabledSkills],
659
- disabledExtensions: [...p.disabledExtensions],
688
+ ...this.settings,
689
+ ...patch,
690
+ // 工具开关与两个遗留别名以派生结果为准(单源:disabledAgentTools)。
660
691
  disabledAgentTools: presetDisabled,
661
- disabledPluginTools: normalizeDisabledPluginTools(p.disabledPluginTools ?? this.settings.disabledPluginTools),
662
692
  terminalToolsEnabled: presetLegacy.terminalToolsEnabled,
663
- // 终端接管偏好随预设走;旧预设缺字段时保留当前值。
664
- terminalBash: p.terminalBash ?? this.settings.terminalBash,
665
- terminalBashIdleMs: p.terminalBashIdleMs ?? this.settings.terminalBashIdleMs,
666
- terminalBashMaxForegroundMs: p.terminalBashMaxForegroundMs ?? this.settings.terminalBashMaxForegroundMs,
667
- // read 读目录是纯运行行为开关,不进预设——保留当前值。
668
- readDirEnabled: this.settings.readDirEnabled !== false,
669
- // 工具审批总开关同样是纯运行开关,不进预设——保留当前值。
670
- toolApprovalEnabled: this.settings.toolApprovalEnabled !== false,
671
- // toolWatchdogTimeoutMs 是纯运行行为参数,不进预设——保留当前值。
672
- toolWatchdogTimeoutMs: this.settings.toolWatchdogTimeoutMs,
673
693
  editSoftEnabled: presetLegacy.editSoftEnabled,
674
- // 重试次数随预设走;旧预设缺字段时保留当前值,应用后即时注入各会话。
675
- retryMaxAttempts: p.retryMaxAttempts ?? this.settings.retryMaxAttempts,
676
- // 压缩软上限同样随预设走(issue #229);旧预设缺字段时保留当前值。
677
- softCapTokens: normalizeSoftCapTokens(p.softCapTokens ?? this.settings.softCapTokens),
678
- softCapByModel: normalizeSoftCapByModel(p.softCapByModel ?? this.settings.softCapByModel),
679
- // 问卷开关不进预设——保留当前值。
680
- questionnaireEnabled: this.settings.questionnaireEnabled,
681
- // 同项目并行提醒开关不进预设——保留当前值。
682
- parallelReminderEnabled: this.settings.parallelReminderEnabled ?? true,
683
- // 目标模式总开关不进预设——保留当前值。
684
- goalModeEnabled: this.settings.goalModeEnabled,
685
- reviewPrompt: p.reviewPrompt ?? this.settings.reviewPrompt,
686
- reviewDisabledSkills: [...(p.reviewDisabledSkills ?? this.settings.reviewDisabledSkills)],
687
- // 全文注入名单随预设走;旧预设缺字段时保留当前值。
688
- skillsFullText: normalizeSkillList(p.skillsFullText ?? this.settings.skillsFullText),
689
- // 纯 UI 偏好不进预设——保留当前值。
690
- devNoCache: this.settings.devNoCache,
691
- autoReload: this.settings.autoReload,
692
- thinkingWrap: this.settings.thinkingWrap,
693
- toolsWrap: this.settings.toolsWrap,
694
- toolImagesEnabled: this.settings.toolImagesEnabled ?? true,
695
- // UI 布局偏好也不进预设——保留当前值。
696
- uiLayout: normalizeUiLayout(this.settings.uiLayout),
697
- // Presets don't capture vision-bridge prefs — keep the current ones.
698
- visionBridgeEnabled: this.settings.visionBridgeEnabled,
699
- visionBridgeModel: this.settings.visionBridgeModel,
700
- visionBridgePromptMode: this.settings.visionBridgePromptMode,
701
- visionBridgePrompt: this.settings.visionBridgePrompt,
702
- // 「AI 提交信息」提示词同样不进预设——保留当前值。
703
- scmCommitMsgPromptMode: this.settings.scmCommitMsgPromptMode,
704
- scmCommitMsgPrompt: this.settings.scmCommitMsgPrompt,
705
- // 计划模式提示词同样不进预设——保留当前值。
706
- planModePromptMode: this.settings.planModePromptMode,
707
- planModePrompt: this.settings.planModePrompt,
708
- // 子代理默认模型也不进预设——保留当前值。
709
- subagentDefaultModel: this.settings.subagentDefaultModel,
710
- // 快捷短语是纯 UI 偏好,不进预设——保留当前值。
711
- quickPhrases: [...this.settings.quickPhrases],
712
- quickPhrasesEnabled: this.settings.quickPhrasesEnabled,
713
694
  };
714
695
  this.host.stateStore.saveSettings(this.host.clientId, this.settings);
715
696
  // 预设可能改了重试次数:即时注入(流式中延迟的 reload 之后还会由调用方重放)。
@@ -725,6 +706,56 @@ export class SettingsService {
725
706
  this.host.stateStore.savePresets(this.host.clientId, this.presets);
726
707
  this.push();
727
708
  }
709
+ /* ---------------------------------------------------------------- */
710
+ /* 预设分享:导出 / 导入 / 分享 / 社区目录(server/preset-share.ts) */
711
+ /* ---------------------------------------------------------------- */
712
+ /** 当前客户端语言(服务端文案用;与 agent-service 同源)。 */
713
+ get lang() {
714
+ return resolveServerLang(this.host.stateStore.get(this.host.clientId).locale);
715
+ }
716
+ /** 分享编排(server/preset-share.ts)需要的最小能力集合。 */
717
+ sharePort() {
718
+ return {
719
+ lang: () => this.lang,
720
+ appVersion: () => packageVersion(),
721
+ presets: () => this.presets,
722
+ currentSettings: () => {
723
+ const { name: _drop, ...rest } = this.snapshotPreset("");
724
+ return { ...rest };
725
+ },
726
+ upsertPreset: (preset) => {
727
+ const i = this.presets.findIndex((p) => p.name === preset.name);
728
+ if (i >= 0)
729
+ this.presets[i] = preset;
730
+ else
731
+ this.presets.push(preset);
732
+ this.host.stateStore.savePresets(this.host.clientId, this.presets);
733
+ },
734
+ applyPreset: (name) => this.applyPreset(name),
735
+ pushSettings: () => this.push(),
736
+ emit: (msg) => this.host.emit(msg),
737
+ };
738
+ }
739
+ /** 导出预设(name 命名的预设)或当前设置(source=current)为 JSON 文本。 */
740
+ async exportPreset(msg) {
741
+ exportPresetVia(this.sharePort(), msg);
742
+ }
743
+ /** 解析导入的预设 JSON:dryRun = 只回预览(不落盘);apply = 导入后立即应用。 */
744
+ async importPreset(msg) {
745
+ await importPresetVia(this.sharePort(), msg);
746
+ }
747
+ /** 按网址导入(服务端抓取:避开浏览器 CORS;内网地址已拦截)。 */
748
+ async importPresetFromUrl(msg) {
749
+ await importPresetFromUrlVia(this.sharePort(), msg);
750
+ }
751
+ /** 一键分享到社区共享仓库(gh issue create;gh 不可用时回落预填网页)。 */
752
+ async sharePreset(msg) {
753
+ await sharePresetVia(this.sharePort(), msg);
754
+ }
755
+ /** 拉社区共享目录(5 分钟缓存;失败保留上一次成功的列表)。 */
756
+ async pushPresetCatalog(msg) {
757
+ await pushPresetCatalogVia(this.sharePort(), msg);
758
+ }
728
759
  /** Upsert 一个子代理模板(全局共享)。模板只影响未来派生的子代理,
729
760
  * 不需要 reload runtime —— 直接推送新设置状态即可。 */
730
761
  async saveTemplate(template) {
@@ -0,0 +1,33 @@
1
+ /**
2
+ * skill-content-filler — 技能全文注入({{skills}} 全文模式)内容填充器。
3
+ *
4
+ * 负责读取名单里技能的文件正文。
5
+ * 单文件 8KB、总量 32KB 封顶,失败/超限/不在名单回落名录(无 content)。
6
+ * 名单为空时零开销:原样返回,不碰磁盘。
7
+ *
8
+ * 从 agent-service.ts 抽出为独立模块。
9
+ */
10
+ import { readFileSync, statSync } from "node:fs";
11
+ import { decodeText } from "./text-sniff.js";
12
+ import { normalizeSkillList } from "./client-state.js";
13
+ export function fillSkillContents(skills, skillsFullTextConfig) {
14
+ const wanted = new Set(normalizeSkillList(skillsFullTextConfig));
15
+ if (wanted.size === 0)
16
+ return skills;
17
+ let budget = 32 * 1024;
18
+ return skills.map((s) => {
19
+ if (!wanted.has(s.name) || !s.filePath || budget <= 0)
20
+ return s;
21
+ try {
22
+ const st = statSync(s.filePath);
23
+ if (!st.isFile() || st.size <= 0 || st.size > 8192)
24
+ return s;
25
+ const raw = decodeText(readFileSync(s.filePath).subarray(0, Math.min(st.size, budget))).trim();
26
+ budget -= raw.length;
27
+ return raw ? { ...s, content: raw } : s;
28
+ }
29
+ catch {
30
+ return s;
31
+ }
32
+ });
33
+ }
@@ -61,10 +61,9 @@ export function makeSkillTool(host, lang) {
61
61
  return defineTool({
62
62
  name: SKILL_TOOL_NAME,
63
63
  label: "Load a skill",
64
- description: "Load a skill's full text by its exact name (see the <available_skills> catalog in the system prompt). " +
65
- "Prefer this over reading the skill file with the read tool — no path guessing needed. " +
66
- "Call without a name to list the current catalog.",
67
- promptSnippet: "load a skill's full text by name (skill tool, preferred over read)",
64
+ description: "Load a skill's full text by its exact name (see the <available_skills> catalog). " +
65
+ "Prefer this over reading the skill file with read — no path guessing.",
66
+ promptSnippet: "use a skill from <available_skills> by name",
68
67
  parameters: Type.Object({
69
68
  name: Type.Optional(Type.String({
70
69
  description: "Exact skill name from the catalog. Omit to list the current catalog.",
@@ -0,0 +1,18 @@
1
+ /**
2
+ * subagent-handoff — 子代理对等直接交接消息格式化与历史记录工具。
3
+ *
4
+ * 负责:
5
+ * - formatSubagentHandoffMessage: 格式化带角色与源 ID 的交接指令
6
+ * - recordSubagentHandoff: 维护限制容量的交接历史时间戳队列
7
+ *
8
+ * 从 agent-service.ts 抽出为独立模块。
9
+ */
10
+ /** 格式化对等交接注入给目标子代理的消息 */
11
+ export function formatSubagentHandoffMessage(fromType, fromRunId, payload) {
12
+ return `[Peer Hand-off from ${fromType} subagent (${fromRunId.slice(0, 8)})]:\n\n${payload}`;
13
+ }
14
+ /** 追加交接记录并维持最近 N 条的滑动窗口 */
15
+ export function recordSubagentHandoff(history, record, maxHistory = 50) {
16
+ const next = [...history, record];
17
+ return next.length > maxHistory ? next.slice(-maxHistory) : next;
18
+ }
@@ -0,0 +1,88 @@
1
+ import { SUBAGENT_PROMPT_SNAPSHOT_CAP } from "./agent-formatters.js";
2
+ /** 子代理最近一次运行的结局:最后一条 assistant 消息的 errorMessage / stopReason。
3
+ * 报错 > 中止 > 正常,三者互斥;无 assistant 消息时返回空。 */
4
+ export function subagentRunOutcome(conv) {
5
+ // 自动重试等待期结局未定:瞬时 error 不算失败,避免向主对话误报
6
+ // 「子代理运行失败」(耗尽后 auto_retry_end 清旗,真正失败照常通知)。
7
+ if (conv.retryState)
8
+ return {};
9
+ try {
10
+ const msgs = conv.session.agent.state.messages;
11
+ for (let i = msgs.length - 1; i >= 0; i--) {
12
+ const m = msgs[i];
13
+ if (m.role !== "assistant")
14
+ continue;
15
+ const err = m.errorMessage;
16
+ if (typeof err === "string" && err.trim()) {
17
+ return { error: err.trim() };
18
+ }
19
+ const stop = m.stopReason;
20
+ if (stop === "aborted" || stop === "cancelled") {
21
+ return { canceled: true };
22
+ }
23
+ break;
24
+ }
25
+ }
26
+ catch {
27
+ // session being replaced — treat as no outcome yet
28
+ }
29
+ return {};
30
+ }
31
+ /** 对话结局 → 角色轮结局(报错 > 中止 > 正常)。 */
32
+ export function roleOutcomeOf(conv) {
33
+ const { error, canceled } = subagentRunOutcome(conv);
34
+ if (error)
35
+ return "error";
36
+ if (canceled)
37
+ return "canceled";
38
+ return "done";
39
+ }
40
+ /** 序列化对话为前端可消费的子代理快照 */
41
+ export function toSubagentSnapshot(conv) {
42
+ const streaming = conv.session.isStreaming;
43
+ const { error, canceled } = subagentRunOutcome(conv);
44
+ const state = streaming ? "running" : canceled ? "canceled" : "done";
45
+ let messageCount = 0;
46
+ try {
47
+ messageCount = conv.session.getSessionStats().totalMessages;
48
+ }
49
+ catch {
50
+ // session being replaced — report defaults
51
+ }
52
+ const fullPrompt = conv.subagentPrompt ?? "";
53
+ const sm = conv.session.sessionManager;
54
+ const isPersisted = !conv.isSubagent || (typeof sm?.isPersisted === "function" && sm.isPersisted());
55
+ return {
56
+ convId: conv.id,
57
+ type: conv.subagentType ?? "general",
58
+ title: conv.title,
59
+ prompt: fullPrompt.length > SUBAGENT_PROMPT_SNAPSHOT_CAP
60
+ ? `${fullPrompt.slice(0, SUBAGENT_PROMPT_SNAPSHOT_CAP)}\n… [truncated]`
61
+ : fullPrompt,
62
+ state,
63
+ streaming,
64
+ error,
65
+ canceled,
66
+ messageCount,
67
+ model: conv.session.model?.id,
68
+ output: conv.session.getLastAssistantText() ?? "",
69
+ parentId: conv.parentId,
70
+ persisted: isPersisted,
71
+ handoffTo: conv.peerHandoffTo ? [...conv.peerHandoffTo] : undefined,
72
+ handoffFrom: conv.peerHandoffFrom ? [...conv.peerHandoffFrom] : undefined,
73
+ };
74
+ }
75
+ /** 列举并排序子代理快照集合 */
76
+ export function listSubagentSnapshots(convs, scope) {
77
+ return [...convs]
78
+ .filter((c) => {
79
+ const isPersisted = !c.isSubagent;
80
+ if (scope === "subagent")
81
+ return c.isSubagent;
82
+ if (scope === "persistent")
83
+ return isPersisted;
84
+ return c.isSubagent || Boolean(c.parentId) || Boolean(c.subagentPrompt);
85
+ })
86
+ .sort((a, b) => a.createdAt - b.createdAt)
87
+ .map((c) => toSubagentSnapshot(c));
88
+ }
@@ -107,16 +107,9 @@ export function makeSubagentTool(host, lang, selfConvId) {
107
107
  return defineTool({
108
108
  name: SUBAGENT_TOOL_NAME,
109
109
  label: "Subagent manager",
110
- description: "Manage background subagent conversations for parallel delegation, research, and execution. Actions:\n" +
111
- "- `spawn`: start a subagent with `prompt` (optional `template`, `type`, `model`, `cwd`, `persist`).\n" +
112
- "- `get_result`: inspect status/output with `runId`.\n" +
113
- "- `steer`: inject a `message` into a running subagent with `runId`.\n" +
114
- "- `list`: list managed subagents (optional `kind`).\n" +
115
- "- `stop`: abort a running subagent with `runId`.\n" +
116
- "- `wait_all`: block until subagents finish (optional `runIds`, `timeoutSeconds`).\n" +
117
- "- `templates`: list available subagent templates.\n" +
118
- "- `handoff`: transfer `payload` to peer subagent with `toRunId` (optional `fromRunId`).",
119
- promptSnippet: "manage background subagents: spawn, get_result, steer, list, stop, wait_all, templates, handoff",
110
+ description: "Manage background subagent conversations for parallel delegation, research, and execution. " +
111
+ "Each action's arguments are documented on the parameters below.",
112
+ promptSnippet: "manage background subagents (spawn/steer/wait/templates)",
120
113
  parameters: Type.Object({
121
114
  action: Type.Unsafe({
122
115
  type: "string",
@@ -124,47 +117,47 @@ export function makeSubagentTool(host, lang, selfConvId) {
124
117
  description: "The subagent action to perform.",
125
118
  }),
126
119
  prompt: Type.Optional(Type.String({
127
- description: "spawn: instructions for the subagent (goal, constraints, expected output).",
120
+ description: "spawn: instructions (goal, constraints, expected output).",
128
121
  })),
129
122
  runId: Type.Optional(Type.String({
130
- description: "get_result/steer/stop: target subagent conversation ID.",
123
+ description: "get_result/steer/stop: target conversation ID.",
131
124
  })),
132
125
  runIds: Type.Optional(Type.Array(Type.String(), {
133
- description: "wait_all: subagent conversation IDs to wait for (omit for all active).",
126
+ description: "wait_all: conversation IDs to wait for (omit = all active).",
134
127
  })),
135
128
  message: Type.Optional(Type.String({
136
- description: "steer: follow-up instruction to inject into the subagent.",
129
+ description: "steer: follow-up instruction.",
137
130
  })),
138
131
  payload: Type.Optional(Type.String({
139
- description: "handoff: artifact, data, or instructions to transfer to peer subagent.",
132
+ description: "handoff: what to transfer to the peer.",
140
133
  })),
141
134
  toRunId: Type.Optional(Type.String({
142
- description: "handoff: target peer subagent conversation ID.",
135
+ description: "handoff: target peer ID.",
143
136
  })),
144
137
  fromRunId: Type.Optional(Type.String({
145
- description: "handoff: source subagent ID (defaults to current subagent).",
138
+ description: "handoff: source ID (default = this subagent).",
146
139
  })),
147
140
  type: Type.Optional(Type.String({
148
- description: "spawn: role/type name (e.g. explore/implement/review, default: general).",
141
+ description: "spawn: role/type (e.g. explore/implement/review, default: general).",
149
142
  })),
150
143
  template: Type.Optional(Type.String({
151
- description: "spawn: subagent template name (see action=templates).",
144
+ description: "spawn: template name (see action=templates).",
152
145
  })),
153
146
  model: Type.Optional(Type.String({
154
147
  description: 'spawn: model override "provider/id".',
155
148
  })),
156
149
  cwd: Type.Optional(Type.String({
157
- description: "spawn: working directory (defaults to current cwd).",
150
+ description: "spawn: working directory (default = current).",
158
151
  })),
159
152
  persist: Type.Optional(Type.Boolean({
160
- description: "spawn: persist as a regular session instead of ephemeral subagent.",
153
+ description: "spawn: persist as a regular session (default = ephemeral).",
161
154
  })),
162
155
  kind: Type.Optional(Type.String({
163
156
  enum: ["all", "subagent", "persistent"],
164
157
  description: "list: filter subagents by kind (default: all).",
165
158
  })),
166
159
  timeoutSeconds: Type.Optional(Type.Integer({
167
- description: `wait_all: max wait in seconds (1-${capSeconds}, default: ${capSeconds}s).`,
160
+ description: `wait_all: max wait in seconds (default: ${capSeconds}s).`,
168
161
  minimum: 1,
169
162
  maximum: capSeconds,
170
163
  })),