pi-web-ui 0.98.0 → 0.100.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 (69) hide show
  1. package/CHANGELOG.md +85 -5
  2. package/README.md +2 -1
  3. package/README.zh-CN.md +2 -1
  4. package/bin/pi-web-ui.mjs +174 -36
  5. package/dist/server/agent-service.js +1169 -152
  6. package/dist/server/approval-rules.js +95 -23
  7. package/dist/server/attachments.js +55 -0
  8. package/dist/server/bg-servers.js +82 -2
  9. package/dist/server/claim-files-tool.js +4 -4
  10. package/dist/server/client-state.js +41 -0
  11. package/dist/server/compact-context-tool.js +10 -9
  12. package/dist/server/conversation-read-tool.js +7 -8
  13. package/dist/server/conversation-touches.js +19 -0
  14. package/dist/server/delegate-task.js +10 -14
  15. package/dist/server/dsh/dsh-agent-service.js +116 -12
  16. package/dist/server/edit-soft-tool.js +10 -12
  17. package/dist/server/eval-tool.js +26 -6
  18. package/dist/server/goal-evidence.js +173 -0
  19. package/dist/server/goal-service.js +78 -15
  20. package/dist/server/hashline-engine.js +198 -31
  21. package/dist/server/index.js +55 -9
  22. package/dist/server/load-tools-tool.js +100 -0
  23. package/dist/server/lsp-tool.js +10 -16
  24. package/dist/server/marker-service.js +53 -12
  25. package/dist/server/markers/builtins/action.js +108 -0
  26. package/dist/server/markers/index.js +4 -1
  27. package/dist/server/model-enrich.js +2 -0
  28. package/dist/server/patch-remote-catalog.js +28 -10
  29. package/dist/server/patch-tool.js +74 -38
  30. package/dist/server/plan-manager.js +71 -30
  31. package/dist/server/plan-mode.js +7 -6
  32. package/dist/server/plugin-api-catalog.js +10 -3
  33. package/dist/server/plugin-conversation-view.js +47 -0
  34. package/dist/server/plugins.js +113 -26
  35. package/dist/server/present-files-tool.js +10 -11
  36. package/dist/server/preset-fields.js +693 -0
  37. package/dist/server/preset-share.js +1178 -0
  38. package/dist/server/prompt-composer.js +23 -9
  39. package/dist/server/protocol-version.js +1 -1
  40. package/dist/server/read-tool.js +8 -10
  41. package/dist/server/resolve-global-sdk.js +80 -18
  42. package/dist/server/schedule-agent-tool.js +147 -146
  43. package/dist/server/sdk-origin.js +125 -37
  44. package/dist/server/settings-service.js +103 -84
  45. package/dist/server/skill-tool.js +3 -4
  46. package/dist/server/subagents.js +15 -22
  47. package/dist/server/terminals.js +29 -39
  48. package/dist/server/tool-approval.js +3 -1
  49. package/dist/server/tool-manager.js +63 -27
  50. package/dist/server/tool-prompt-overrides.js +158 -0
  51. package/dist/server/tool-prompts.js +42 -0
  52. package/dist/server/tool-signature.js +104 -0
  53. package/dist/server/update-check.js +0 -15
  54. package/dist/server/workspace-snapshot.js +42 -11
  55. package/package.json +5 -3
  56. package/plugin-sdk/README.md +8 -4
  57. package/plugin-sdk/import-check.mjs +210 -0
  58. package/plugin-sdk/index.d.ts +4 -1
  59. package/plugin-sdk/index.mjs +1 -0
  60. package/plugins/catalog.json +33 -2
  61. package/themes/zhupi-dark.css +1 -1
  62. package/themes/zhupi.css +1 -1
  63. package/web/dist/assets/{TerminalPanel-C88r3r3Q.js → TerminalPanel-C3I1Mc-C.js} +2 -2
  64. package/web/dist/assets/index-B-E2EM_0.css +1 -0
  65. package/web/dist/assets/index-BYumAaGi.js +379 -0
  66. package/web/dist/index.html +2 -2
  67. package/web/dist/sw.js +1 -1
  68. package/web/dist/assets/index-2jDtjHvW.css +0 -1
  69. package/web/dist/assets/index-BjdK7s1M.js +0 -368
@@ -29,8 +29,8 @@ import { basename, dirname, join, resolve, sep } from "node:path";
29
29
  import { writeJsonAtomicSync } from "../atomic-file.js";
30
30
  import { randomUUID } from "node:crypto";
31
31
  import { homedir } from "node:os";
32
- import { BgServerTracker } from "../bg-servers.js";
33
- import { ClientStateStore, DEFAULT_RETRY_MAX_ATTEMPTS, normalizePathKey, normalizeToolWatchdogTimeoutMs, } from "../client-state.js";
32
+ import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "../bg-servers.js";
33
+ import { ClientStateStore, DEFAULT_RETRY_MAX_ATTEMPTS, normalizeBgCleanupMinutes, normalizePathKey, normalizeToolWatchdogTimeoutMs, settingsPresetToUi, } from "../client-state.js";
34
34
  import { normalizeUiLayout } from "../client-state.js";
35
35
  import { PLAN_MODE_SYSTEM_PROMPT } from "../plan-mode.js";
36
36
  import { FilesService, workspacePath, desktopDirWire } from "../files-service.js";
@@ -51,6 +51,7 @@ import { DshStreamAccumulator, assistantMessageEventToUiMessage, toolResultEvent
51
51
  import { firstUserText, findSessionFilesForCwd, readSessionLog, replayEventsToMessages, sessionLogPermission, sessionLogPreset, } from "./dsh-sessions.js";
52
52
  import { generatePresetClones, PRESET_DEFAULT_ID } from "./preset-clones.js";
53
53
  import { dshContextUsage, lastUsageFromEvents, normalizeDshUsage } from "./dsh-usage.js";
54
+ import { exportPresetVia, importPresetFromUrlVia, importPresetVia, packageVersion, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
54
55
  const SNAPSHOT_INTERVAL_MS = 60;
55
56
  /** 用户主目录(wire 格式):进程内不变,模块加载时求值一次(右栏 🏠)。 */
56
57
  const HOME_WIRE = homedir().replace(/\\/g, "/");
@@ -129,6 +130,7 @@ const DEFAULT_SETTINGS = {
129
130
  terminalBashIdleMs: 15_000,
130
131
  terminalBashMaxForegroundMs: 60_000,
131
132
  toolWatchdogTimeoutMs: 20 * 60_000,
133
+ bgAutoCleanupMin: 0,
132
134
  editSoftEnabled: false,
133
135
  questionnaireEnabled: true,
134
136
  toolApprovalEnabled: true,
@@ -144,6 +146,8 @@ const DEFAULT_SETTINGS = {
144
146
  defaultPermissionPreset: PERMISSION_DEFAULT_PRESET,
145
147
  quickPhrases: [],
146
148
  quickPhrasesEnabled: true,
149
+ promptTemplate: "",
150
+ promptOverrides: {},
147
151
  };
148
152
  // ---------------------------------------------------------------------------
149
153
  // DshClientSession — 一个浏览器客户端
@@ -251,6 +255,7 @@ export class DshClientSession {
251
255
  flushSnapshot: () => this.flushSnapshot(),
252
256
  isDisposed: () => this.disposed,
253
257
  pluginTasks: () => this.pluginBgTasksProvider?.() ?? [],
258
+ cleanupMinutes: () => Number(this.settings.bgAutoCleanupMin ?? 0),
254
259
  });
255
260
  }
256
261
  static create(clientId, cwd, stateStore, dataDir, agentDir) {
@@ -278,6 +283,7 @@ export class DshClientSession {
278
283
  terminalBashIdleMs: savedSettings.terminalBashIdleMs,
279
284
  terminalBashMaxForegroundMs: savedSettings.terminalBashMaxForegroundMs ?? 60_000,
280
285
  toolWatchdogTimeoutMs: savedSettings.toolWatchdogTimeoutMs ?? 20 * 60_000,
286
+ bgAutoCleanupMin: Number(savedSettings.bgAutoCleanupMin ?? 0),
281
287
  editSoftEnabled: savedSettings.editSoftEnabled,
282
288
  questionnaireEnabled: savedSettings.questionnaireEnabled ?? true,
283
289
  toolApprovalEnabled: savedSettings.toolApprovalEnabled ?? true,
@@ -291,6 +297,8 @@ export class DshClientSession {
291
297
  reviewPrompt: savedSettings.reviewPrompt,
292
298
  quickPhrases: savedSettings.quickPhrases ?? [],
293
299
  quickPhrasesEnabled: savedSettings.quickPhrasesEnabled ?? true,
300
+ promptTemplate: savedSettings.promptTemplate ?? "",
301
+ promptOverrides: savedSettings.promptOverrides ?? {},
294
302
  defaultAgentPreset: savedSettings.defaultAgentPreset ?? PRESET_DEFAULT_ID,
295
303
  defaultPermissionPreset: savedSettings.defaultPermissionPreset && PERMISSION_OFFERED.includes(savedSettings.defaultPermissionPreset)
296
304
  ? savedSettings.defaultPermissionPreset
@@ -1262,6 +1270,7 @@ export class DshClientSession {
1262
1270
  permission: conv.permissionPreset ?? null,
1263
1271
  queue: { steering: conv.queue.steering, followUp: conv.queue.followUp },
1264
1272
  pendingQuestion: this.pendingQuestionForSnapshot(),
1273
+ actionSuggestions: null,
1265
1274
  tools: [],
1266
1275
  version: ++this.version,
1267
1276
  piConfigured: this.isDshConfigured(),
@@ -2036,6 +2045,18 @@ export class DshClientSession {
2036
2045
  this.bg.push();
2037
2046
  return killed;
2038
2047
  }
2048
+ /** 钉住 / 取消钉住(DSH 引擎同样有后台任务面板,行为与 pi 引擎一致)。 */
2049
+ setBackgroundKeep(port, keep) {
2050
+ return this.bg.setKeep(port, keep);
2051
+ }
2052
+ /** 手动「立即清理」(阈值策略与 pi 引擎同源:设置里的 bgAutoCleanupMin,关时兼底 30 分钟)。 */
2053
+ async cleanBackgroundLeftovers(minutesOverride) {
2054
+ const override = Number(minutesOverride);
2055
+ const policy = Number(this.settings.bgAutoCleanupMin ?? 0);
2056
+ const minutes = Number.isFinite(override) && override > 0 ? override : policy;
2057
+ const thresholdMs = (minutes > 0 ? minutes : BG_CLEANUP_FALLBACK_MIN) * 60_000;
2058
+ return this.bg.cleanStale(thresholdMs, { manual: true });
2059
+ }
2039
2060
  // -----------------------------------------------------------------------
2040
2061
  // 会话列表 / 切换 / 删除
2041
2062
  // -----------------------------------------------------------------------
@@ -2630,6 +2651,9 @@ export class DshClientSession {
2630
2651
  toolWatchdogTimeoutMs: this.settings.toolWatchdogTimeoutMs,
2631
2652
  // DSH 引擎无 customTool 注册面(工具来自 shipped preset),read 目录覆盖面不存在。
2632
2653
  readDirEnabled: true,
2654
+ bgAutoCleanupMin: Number(this.settings.bgAutoCleanupMin ?? 0),
2655
+ // DSH 无 pi 工具注册面,不适用延迟加载;保协议完整。
2656
+ toolLazyLoading: true,
2633
2657
  editSoftEnabled: this.settings.editSoftEnabled,
2634
2658
  // DSH 无独立重试配置(pi 引擎才暴露),保持默认。
2635
2659
  retryMaxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,
@@ -2663,8 +2687,10 @@ export class DshClientSession {
2663
2687
  reviewDisabledSkills: [],
2664
2688
  disabledPlugins: this.settings.disabledPlugins,
2665
2689
  uiLayout: normalizeUiLayout(this.settings.uiLayout),
2666
- promptTemplate: "",
2667
- promptOverrides: {},
2690
+ promptTemplate: this.settings.promptTemplate ?? "",
2691
+ promptOverrides: this.settings.promptOverrides ?? {},
2692
+ // DSH 无 pi 工具注册表面,逐工具文案覆盖不适用;保协议完整。
2693
+ toolPromptOverrides: {},
2668
2694
  effectiveSystemPrompt: this.settings.customSystemPrompt,
2669
2695
  promptSourceDefaults: {},
2670
2696
  // DSH 引擎不接标准 pi 的 customTool 工具 schema(走 goal-rpc),此处给空。
@@ -2675,7 +2701,7 @@ export class DshClientSession {
2675
2701
  skills: this.skillsCache,
2676
2702
  reviewSkills: [],
2677
2703
  extensions: [],
2678
- presets: this.stateStore.getPresets(this.clientId),
2704
+ presets: this.stateStore.getPresets(this.clientId).map(settingsPresetToUi),
2679
2705
  markersEnabled: true,
2680
2706
  disabledMarkers: [],
2681
2707
  markers: [],
@@ -2696,6 +2722,10 @@ export class DshClientSession {
2696
2722
  this.settings.promptMode = partial.promptMode;
2697
2723
  if (partial.customSystemPrompt !== undefined)
2698
2724
  this.settings.customSystemPrompt = partial.customSystemPrompt;
2725
+ if (partial.promptTemplate !== undefined)
2726
+ this.settings.promptTemplate = partial.promptTemplate;
2727
+ if (partial.promptOverrides !== undefined)
2728
+ this.settings.promptOverrides = partial.promptOverrides;
2699
2729
  if (partial.disabledSkills !== undefined)
2700
2730
  this.settings.disabledSkills = partial.disabledSkills;
2701
2731
  if (partial.disabledExtensions !== undefined)
@@ -2710,6 +2740,8 @@ export class DshClientSession {
2710
2740
  this.settings.terminalBashMaxForegroundMs = partial.terminalBashMaxForegroundMs;
2711
2741
  if (partial.toolWatchdogTimeoutMs !== undefined)
2712
2742
  this.settings.toolWatchdogTimeoutMs = normalizeToolWatchdogTimeoutMs(partial.toolWatchdogTimeoutMs);
2743
+ if (partial.bgAutoCleanupMin !== undefined)
2744
+ this.settings.bgAutoCleanupMin = normalizeBgCleanupMinutes(partial.bgAutoCleanupMin);
2713
2745
  if (partial.editSoftEnabled !== undefined)
2714
2746
  this.settings.editSoftEnabled = partial.editSoftEnabled;
2715
2747
  if (partial.questionnaireEnabled !== undefined)
@@ -2770,6 +2802,8 @@ export class DshClientSession {
2770
2802
  quickPhrases: this.settings.quickPhrases,
2771
2803
  quickPhrasesEnabled: this.settings.quickPhrasesEnabled,
2772
2804
  defaultAgentPreset: this.settings.defaultAgentPreset,
2805
+ promptTemplate: this.settings.promptTemplate ?? "",
2806
+ promptOverrides: this.settings.promptOverrides ?? {},
2773
2807
  });
2774
2808
  // 仅系统提示词变化才重启运行时(DSH_PERSONA 由 launcher env 注入);
2775
2809
  // 其他设置(开关/隐藏插件等)只存不回写运行时。
@@ -3127,13 +3161,13 @@ export class DshClientSession {
3127
3161
  });
3128
3162
  return;
3129
3163
  }
3130
- this.settings.promptMode = preset.promptMode;
3131
- this.settings.customSystemPrompt = preset.customSystemPrompt;
3164
+ this.settings.promptMode = preset.promptMode === "replace" ? "replace" : "append";
3165
+ this.settings.customSystemPrompt = preset.customSystemPrompt ?? "";
3132
3166
  this.settings.disabledSkills = preset.disabledSkills ?? [];
3133
3167
  this.settings.disabledExtensions = preset.disabledExtensions ?? [];
3134
- this.settings.terminalToolsEnabled = preset.terminalToolsEnabled;
3135
- this.settings.terminalBash = preset.terminalBash;
3136
- this.settings.terminalBashIdleMs = preset.terminalBashIdleMs;
3168
+ this.settings.terminalToolsEnabled = preset.terminalToolsEnabled ?? this.settings.terminalToolsEnabled;
3169
+ this.settings.terminalBash = preset.terminalBash ?? this.settings.terminalBash;
3170
+ this.settings.terminalBashIdleMs = preset.terminalBashIdleMs ?? this.settings.terminalBashIdleMs;
3137
3171
  this.settings.terminalBashMaxForegroundMs =
3138
3172
  preset.terminalBashMaxForegroundMs ?? this.settings.terminalBashMaxForegroundMs;
3139
3173
  this.settings.editSoftEnabled = preset.editSoftEnabled ?? this.settings.editSoftEnabled;
@@ -3164,6 +3198,70 @@ export class DshClientSession {
3164
3198
  this.stateStore.savePresets(this.clientId, presets.filter((p) => p.name !== name));
3165
3199
  this.pushSettings();
3166
3200
  }
3201
+ /* -----------------------------------------------------------------------
3202
+ * 预设分享(server/preset-share.ts)—— 与 pi 引擎同一份编排,只换适配层。
3203
+ * DSH 的预设存储/应用语义不同,所以把「取/存/应用」按 DSH 的做法接上。
3204
+ * --------------------------------------------------------------------- */
3205
+ /** 分享编排需要的最小能力集合(DSH 侧)。 */
3206
+ sharePort() {
3207
+ return {
3208
+ lang: () => this.getLang(),
3209
+ appVersion: () => packageVersion(),
3210
+ presets: () => this.stateStore.getPresets(this.clientId),
3211
+ currentSettings: () => {
3212
+ const s = this.settings;
3213
+ // DSH 的预设记录字段与 ClientSettings 不完全一致(没有 promptTemplate/
3214
+ // promptOverrides 等),导出时按预设形状给默认值(应用侧只读它认识的)。
3215
+ return {
3216
+ promptMode: s.promptMode,
3217
+ customSystemPrompt: s.customSystemPrompt,
3218
+ promptTemplate: "",
3219
+ promptOverrides: {},
3220
+ disabledSkills: [...(s.disabledSkills ?? [])],
3221
+ disabledExtensions: [...(s.disabledExtensions ?? [])],
3222
+ disabledAgentTools: [],
3223
+ disabledPluginTools: [],
3224
+ terminalToolsEnabled: s.terminalToolsEnabled,
3225
+ terminalBash: s.terminalBash,
3226
+ terminalBashIdleMs: s.terminalBashIdleMs,
3227
+ terminalBashMaxForegroundMs: s.terminalBashMaxForegroundMs,
3228
+ editSoftEnabled: s.editSoftEnabled,
3229
+ skillsFullText: [],
3230
+ reviewPrompt: s.reviewPrompt ?? "",
3231
+ reviewDisabledSkills: [],
3232
+ };
3233
+ },
3234
+ upsertPreset: (preset) => {
3235
+ const presets = this.stateStore.getPresets(this.clientId);
3236
+ this.stateStore.savePresets(this.clientId, presets.some((p) => p.name === preset.name)
3237
+ ? presets.map((p) => (p.name === preset.name ? preset : p))
3238
+ : [...presets, preset]);
3239
+ },
3240
+ applyPreset: (name) => this.applyPreset(name),
3241
+ pushSettings: () => this.pushSettings(),
3242
+ emit: (msg) => this.emit(msg),
3243
+ };
3244
+ }
3245
+ /** 导出预设/当前设置为可分享的 JSON(服务端 preset-share.ts)。 */
3246
+ async exportPreset(msg) {
3247
+ exportPresetVia(this.sharePort(), msg);
3248
+ }
3249
+ /** 解析导入的预设 JSON(dryRun = 只预览)。 */
3250
+ async importPreset(msg) {
3251
+ await importPresetVia(this.sharePort(), msg);
3252
+ }
3253
+ /** 按网址导入预设(服务端抓取)。 */
3254
+ async importPresetFromUrl(msg) {
3255
+ await importPresetFromUrlVia(this.sharePort(), msg);
3256
+ }
3257
+ /** 拉社区共享预设目录。 */
3258
+ async pushPresetCatalog(msg) {
3259
+ await pushPresetCatalogVia(this.sharePort(), msg);
3260
+ }
3261
+ /** 一键分享预设到社区共享仓库。 */
3262
+ async sharePreset(msg) {
3263
+ await sharePresetVia(this.sharePort(), msg);
3264
+ }
3167
3265
  // -----------------------------------------------------------------------
3168
3266
  // 子代理模板(DSH 引擎无子代理概念 —— 设置面板分区由前端 isDsh 隐藏)
3169
3267
  // -----------------------------------------------------------------------
@@ -3990,8 +4088,14 @@ export class DshClientSession {
3990
4088
  const newSessionId = `fork-${randomUUID().slice(0, 12)}`;
3991
4089
  const fresh = this.addConversation(newSessionId, this.cwd, false);
3992
4090
  // 回放编辑点之前的消息(作为会话初始上下文:DSH 无 seed 机制,v1 用
3993
- // 简化——直接把历史作为一条提示词说明附上)。
3994
- const head = conv.messages.slice(0, idx);
4091
+ // 简化——直接把历史作为一条提示词说明附上)。跳过紧挨在当前提问前面的前置附件卡片。
4092
+ let cutIdx = idx;
4093
+ while (cutIdx > 0 &&
4094
+ conv.messages[cutIdx - 1]?.role === "custom" &&
4095
+ conv.messages[cutIdx - 1]?.customType === "file") {
4096
+ cutIdx--;
4097
+ }
4098
+ const head = conv.messages.slice(0, cutIdx);
3995
4099
  // 把编辑前的对话内容写进新会话的 prompt(尽力保留上下文)。
3996
4100
  const contextNote = head
3997
4101
  .map((m) => {
@@ -32,11 +32,11 @@ import { EDIT_SOFT_TOOL_NAME } from "./tool-manager.js";
32
32
  export const SOFT_EDIT_TOOL_NAME = EDIT_SOFT_TOOL_NAME;
33
33
  const replaceEditSchema = Type.Object({
34
34
  oldText: Type.String({
35
- description: "Text to replace. Loose matching: the content of each non-empty line (trimmed of leading/trailing whitespace) must match the corresponding file lines; " +
36
- "leading-indentation (spaces/tabs) differences are ignored. Prefer whole lines/blocks.",
35
+ description: "Text to replace. Loose matching: each non-empty line must match by trimmed content, so leading-indentation (spaces/tabs) differences are ignored. " +
36
+ "Prefer whole lines/blocks.",
37
37
  }),
38
38
  newText: Type.String({
39
- description: "Replacement text (written verbatim; the indentation you provide is final).",
39
+ description: "Replacement text (written verbatim).",
40
40
  }),
41
41
  }, {});
42
42
  const editSoftSchema = Type.Object({
@@ -44,8 +44,8 @@ const editSoftSchema = Type.Object({
44
44
  description: "Path of the file to edit (relative or absolute).",
45
45
  }),
46
46
  edits: Type.Array(replaceEditSchema, {
47
- description: "One or more targeted replacements. Each edit matches against the original file (not incrementally); " +
48
- "do not include overlapping/nested edits; merge edits touching the same block or nearby lines into one.",
47
+ description: "One or more targeted replacements, matched against the original file (not incrementally); " +
48
+ "do not include overlapping/nested edits.",
49
49
  }),
50
50
  }, {});
51
51
  function isSingleEditInput(value) {
@@ -304,14 +304,12 @@ export function makeEditSoftTool(fallbackCwd, getLang) {
304
304
  return defineTool({
305
305
  name: SOFT_EDIT_TOOL_NAME,
306
306
  label: "Edit (indentation-insensitive)",
307
- description: "Edit a single file with text replacement tolerant of indentation: oldText is matched by line content, ignoring leading-whitespace differences, so edits don't fail on indentation mismatch. " +
308
- "Use when the built-in edit rejects oldText due to whitespace (common in JS/JSON). Prefer whole-line/whole-block oldText; newText is written exactly as provided.",
309
- promptSnippet: "edit a file tolerating indentation differences (whitespace-insensitive match)",
307
+ description: "Edit a single file with text replacement tolerant of indentation: oldText matches by trimmed line content, " +
308
+ "so leading-whitespace drift (common in JS/JSON) does not fail the edit.",
309
+ promptSnippet: "edit a file when whitespace/indentation makes the built-in edit fail",
310
310
  promptGuidelines: [
311
- "Use edit_soft when edit fails because the oldText indentation/spacing differs from the file",
312
- "Each edits[].oldText is matched to whole lines by trimmed content; leading whitespace is ignored",
313
- "newText is written verbatim — the indentation you provide is the final indentation in the file",
314
- "Keep edits[].oldText as small as possible while still being unique; " + "merge nearby changes into one edit",
311
+ "Use edit_soft when edit rejects oldText on an indentation/spacing mismatch",
312
+ "Keep edits[].oldText as small as possible while still being unique; merge nearby changes into one edit",
315
313
  ],
316
314
  parameters: editSoftSchema,
317
315
  prepareArguments: prepareSoftEditArguments,
@@ -497,12 +497,11 @@ export function makeEvalTool(opts) {
497
497
  name: EVAL_TOOL_NAME,
498
498
  label: "Execute code in persistent sandbox",
499
499
  description: "Execute Python or JavaScript/TypeScript code in an isolated evaluation sandbox. " +
500
- "Variables and imported modules persist across calls within the conversation. " +
501
- "Ideal for quick calculations, data transformations, algorithm verification, and inspecting outputs without creating temporary script files.",
502
- promptSnippet: "evaluate Python or JS/TS code with persistent state (default-off sandbox)",
500
+ "Variables and imported modules persist across calls within the conversation.",
501
+ promptSnippet: "run a code snippet without creating a script file",
503
502
  parameters: Type.Object({
504
503
  code: Type.String({
505
- description: "The code snippet to evaluate. Top-level variables and functions are preserved across calls.",
504
+ description: "The code snippet to evaluate. Top-level variables and functions persist across calls.",
506
505
  }),
507
506
  language: Type.Optional(Type.Unsafe({
508
507
  type: "string",
@@ -510,7 +509,7 @@ export function makeEvalTool(opts) {
510
509
  description: 'Target language: "py" for Python (default), "js" or "ts" for Node.js sandbox.',
511
510
  })),
512
511
  title: Type.Optional(Type.String({
513
- description: 'Optional short label for this step (e.g. "Calculate metrics", "Parse payload").',
512
+ description: "Optional short label for this step.",
514
513
  })),
515
514
  timeout: Type.Optional(Type.Integer({
516
515
  minimum: 1,
@@ -523,7 +522,28 @@ export function makeEvalTool(opts) {
523
522
  }),
524
523
  execute: async (_id, params) => {
525
524
  const lang = getLang();
526
- const language = params.language ?? "py";
525
+ let language = params.language ?? "py";
526
+ if (language === "python")
527
+ language = "py"; // 常见笔误别名(issue #462)
528
+ if (language !== "py" && language !== "js" && language !== "ts") {
529
+ // schema 已声明 enum(["py","js","ts"])(#417),但那只影响提示不拦运行时;
530
+ // getKernel 的 normLang 只映射 ts,其余任意值会原样建出名为它的 Node 内核,
531
+ // Python 代码被 node 执行报 JS 语法错且模型无从知道是键写错。
532
+ const text = pick(lang, `错误:language 仅支持 py / js / ts,收到「${language}」。`, `Error: language must be one of py / js / ts; got "${language}".`);
533
+ return {
534
+ content: [{ type: "text", text }],
535
+ details: {
536
+ language,
537
+ durationMs: 0,
538
+ ok: false,
539
+ stdout: "",
540
+ stderr: "",
541
+ result: null,
542
+ error: text,
543
+ reset: params.reset ?? false,
544
+ },
545
+ };
546
+ }
527
547
  const timeoutSec = Math.min(Math.max(1, params.timeout ?? DEFAULT_TIMEOUT_SECONDS), MAX_TIMEOUT_SECONDS);
528
548
  const timeoutMs = timeoutSec * 1000;
529
549
  const startTime = Date.now();
@@ -0,0 +1,173 @@
1
+ /**
2
+ * 目标审查的「执行证据」摘要(issue #543 §1,纯函数,无宿主/会话依赖)。
3
+ *
4
+ * 委托执行下「执行者」与「审查者」是两条会话:审查者(主对话)的输入原本只有目标、
5
+ * 轮次、执行者本轮自述和计划看板 —— 执行者实际跑过哪些命令、输出的尾部是什么,一概
6
+ * 不在输入里。远程部署类目标于是只能靠猜,或者让审查者自己重跑一遍。
7
+ *
8
+ * 这里把执行者会话里最近的工具事件(`bashExecution` 的命令与输出 / `toolResult` 的
9
+ * 工具名、参数提示与结果尾部)压成一段可直接进审查提示词的文本。只读消息数组、
10
+ * 只看尾部、全程封顶,避免把审查回合的上下文撑爆。
11
+ *
12
+ * 消息形状与 `lastToolNameOfSession` / `extractErrorSnippetFromSession` 同源:
13
+ * - `{role:"bashExecution", command, output, exitCode}`(`!` 命令与持久 shell 的转录)
14
+ * - `{role:"toolResult", toolName, toolCallId, isError, content:[{type:"text", text}]}`
15
+ * - `{role:"assistant", content:[{type:"toolCall", toolCallId, name, args}]}`(取参数提示用)
16
+ */
17
+ import { checkBashCommandDanger } from "./approval-rules.js";
18
+ const DEFAULT_MAX_ENTRIES = 8;
19
+ const DEFAULT_MAX_TAIL_CHARS = 400;
20
+ const DEFAULT_MAX_TOTAL_CHARS = 6000;
21
+ const DEFAULT_WINDOW = 200;
22
+ /** 参数提示里优先取用的字段(顺序即优先级:命令 > 路径 > 查询)。 */
23
+ const HINT_KEYS = ["command", "path", "file_path", "filePath", "pattern", "query", "url", "name"];
24
+ function isRecord(v) {
25
+ return typeof v === "object" && v !== null;
26
+ }
27
+ /** 压成一行并封顶(提示是给人/模型扫的,不做换行)。 */
28
+ function oneLine(v, max = 120) {
29
+ if (typeof v !== "string")
30
+ return "";
31
+ const s = v.trim().replace(/\s+/g, " ");
32
+ if (!s)
33
+ return "";
34
+ return s.length > max ? `${s.slice(0, max)}…` : s;
35
+ }
36
+ /** 输出尾部(尾部才是错误所在);超出预算时留一个省略号标记。 */
37
+ function tailOf(v, max) {
38
+ if (typeof v !== "string")
39
+ return "";
40
+ const s = v.trim();
41
+ if (!s)
42
+ return "";
43
+ return s.length > max ? `…${s.slice(-max)}` : s;
44
+ }
45
+ /** toolResult 的正文(content 文本块拼接;兼容纯字符串的简化形态)。 */
46
+ function resultText(content) {
47
+ if (typeof content === "string")
48
+ return content;
49
+ if (!Array.isArray(content))
50
+ return "";
51
+ return content
52
+ .map((c) => (isRecord(c) && typeof c.text === "string" ? c.text : ""))
53
+ .filter(Boolean)
54
+ .join("\n");
55
+ }
56
+ /**
57
+ * 执行者会话消息 → 证据条目(从最新往前取,返回时按时间正序)。
58
+ * 非数组 / 形状不认识 → 空数组(旧 host / 空会话照常工作)。
59
+ */
60
+ export function collectToolEvidence(messages, opts = {}) {
61
+ if (!Array.isArray(messages) || messages.length === 0)
62
+ return [];
63
+ const maxEntries = Math.max(1, opts.maxEntries ?? DEFAULT_MAX_ENTRIES);
64
+ const maxTail = Math.max(40, opts.maxTailChars ?? DEFAULT_MAX_TAIL_CHARS);
65
+ const window = Math.max(1, opts.window ?? DEFAULT_WINDOW);
66
+ const recent = messages.slice(-window);
67
+ // toolResult 不带参数:先按 toolCallId 建索引,才能给出「跑了什么」的提示。
68
+ const calls = new Map();
69
+ for (const m of recent) {
70
+ if (!isRecord(m) || m.role !== "assistant" || !Array.isArray(m.content))
71
+ continue;
72
+ for (const b of m.content) {
73
+ if (!isRecord(b) || b.type !== "toolCall")
74
+ continue;
75
+ const id = typeof b.toolCallId === "string" ? b.toolCallId : typeof b.id === "string" ? b.id : "";
76
+ if (!id)
77
+ continue;
78
+ const args = isRecord(b.args) ? b.args : undefined;
79
+ let hint = "";
80
+ if (args) {
81
+ for (const k of HINT_KEYS) {
82
+ hint = oneLine(args[k]);
83
+ if (hint)
84
+ break;
85
+ }
86
+ }
87
+ calls.set(id, { name: typeof b.name === "string" ? b.name : "", hint });
88
+ }
89
+ }
90
+ const out = [];
91
+ for (let i = recent.length - 1; i >= 0 && out.length < maxEntries; i--) {
92
+ const m = recent[i];
93
+ if (!isRecord(m))
94
+ continue;
95
+ if (m.role === "bashExecution") {
96
+ const cmd = typeof m.command === "string" ? m.command : "";
97
+ const dangerHits = checkBashCommandDanger(cmd);
98
+ const prefix = dangerHits.length > 0 ? `⚠️ [${dangerHits[0].label}] ` : "";
99
+ out.push({
100
+ tool: "bash",
101
+ hint: `${prefix}${oneLine(m.command)}`,
102
+ tail: tailOf(m.output, maxTail),
103
+ error: typeof m.exitCode === "number" && m.exitCode !== 0,
104
+ });
105
+ continue;
106
+ }
107
+ if (m.role !== "toolResult")
108
+ continue;
109
+ const id = typeof m.toolCallId === "string" ? m.toolCallId : "";
110
+ const call = id ? calls.get(id) : undefined;
111
+ const toolName = typeof m.toolName === "string" ? m.toolName.trim() : "";
112
+ const effectiveTool = toolName || call?.name || "tool";
113
+ let hint = call?.hint ?? "";
114
+ if (effectiveTool === "bash" && hint) {
115
+ const dangerHits = checkBashCommandDanger(hint);
116
+ if (dangerHits.length > 0) {
117
+ hint = `⚠️ [${dangerHits[0].label}] ${hint}`;
118
+ }
119
+ }
120
+ out.push({
121
+ tool: effectiveTool,
122
+ hint,
123
+ tail: tailOf(resultText(m.content), maxTail),
124
+ error: m.isError === true,
125
+ });
126
+ }
127
+ out.reverse();
128
+ return out;
129
+ }
130
+ /**
131
+ * 证据条目 → 可直接注入审查提示词的文本块(纯文本,不带标题:标题由提示词模板按语言给)。
132
+ * 空条目返回空串(调用方据此跳过整段,不注入空标题)。
133
+ */
134
+ export function formatEvidenceDigest(entries, opts = {}) {
135
+ if (entries.length === 0)
136
+ return "";
137
+ const maxTotal = Math.max(200, opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS);
138
+ const bodies = [];
139
+ let used = 0;
140
+ let omitted = 0;
141
+ // 从最新往前堆,预算用完即止 —— 丢的永远是最早的(审查关心「刚才跑了什么」)。
142
+ // 编号留到最终顺序确定后再加(否则反向堆出来的编号与显示顺序相反)。
143
+ for (let i = entries.length - 1; i >= 0; i--) {
144
+ const e = entries[i];
145
+ const head = `${e.tool}${e.error ? " (failed)" : ""}${e.hint ? `: ${e.hint}` : ""}`;
146
+ const body = e.tail ? `${head}\n out: ${e.tail}` : head;
147
+ if (used + body.length + 4 > maxTotal) {
148
+ omitted = i + 1;
149
+ break;
150
+ }
151
+ bodies.push(body);
152
+ used += body.length + 4; // +4 = 「N. 」编号占位
153
+ }
154
+ bodies.reverse();
155
+ const blocks = bodies.map((b, idx) => `${idx + 1}. ${b}`);
156
+ const head = omitted > 0 ? `(${omitted} earlier event(s) omitted for brevity)\n` : "";
157
+ return head + blocks.join("\n");
158
+ }
159
+ /** 会话 → 原始消息数组(与 `lastToolNameOfSession` 同口径;读不到即空数组)。 */
160
+ export function sessionMessagesOf(session) {
161
+ try {
162
+ const s = session;
163
+ const msgs = s?.messages ?? s?.agent?.state?.messages;
164
+ return Array.isArray(msgs) ? msgs : [];
165
+ }
166
+ catch {
167
+ return [];
168
+ }
169
+ }
170
+ /** 一步到位:会话消息 → 证据文本(空会话/空证据返回空串)。 */
171
+ export function buildEvidenceDigest(messages, opts = {}) {
172
+ return formatEvidenceDigest(collectToolEvidence(messages, opts), opts);
173
+ }