psyclaw 0.34.0-preview.2 → 0.34.0-preview.4

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 (53) hide show
  1. package/dist/src/adapters/pi/extension.js +429 -140
  2. package/dist/src/adapters/pi/extension.js.map +1 -1
  3. package/dist/src/adapters/pi/observation-mask.js +5 -3
  4. package/dist/src/adapters/pi/observation-mask.js.map +1 -1
  5. package/dist/src/analysis/skill-resolution.d.ts +18 -2
  6. package/dist/src/analysis/skill-resolution.js +32 -17
  7. package/dist/src/analysis/skill-resolution.js.map +1 -1
  8. package/dist/src/brain/brain.d.ts +64 -0
  9. package/dist/src/brain/brain.js +206 -0
  10. package/dist/src/brain/brain.js.map +1 -0
  11. package/dist/src/brain/preferences.d.ts +19 -0
  12. package/dist/src/brain/preferences.js +80 -0
  13. package/dist/src/brain/preferences.js.map +1 -0
  14. package/dist/src/branding.d.ts +9 -0
  15. package/dist/src/branding.js +25 -0
  16. package/dist/src/branding.js.map +1 -1
  17. package/dist/src/chat.d.ts +2 -2
  18. package/dist/src/chat.js +9 -3
  19. package/dist/src/chat.js.map +1 -1
  20. package/dist/src/integrations/mcp-config.d.ts +27 -0
  21. package/dist/src/integrations/mcp-config.js +120 -0
  22. package/dist/src/integrations/mcp-config.js.map +1 -0
  23. package/dist/src/panel/server.js +8 -10
  24. package/dist/src/panel/server.js.map +1 -1
  25. package/dist/src/router/decision-model.d.ts +42 -5
  26. package/dist/src/router/decision-model.js +114 -12
  27. package/dist/src/router/decision-model.js.map +1 -1
  28. package/dist/src/router/llm-judge.d.ts +13 -0
  29. package/dist/src/router/llm-judge.js +38 -0
  30. package/dist/src/router/llm-judge.js.map +1 -0
  31. package/dist/src/session/help.js +3 -2
  32. package/dist/src/session/help.js.map +1 -1
  33. package/dist/src/session/modes.js +2 -2
  34. package/dist/src/session/modes.js.map +1 -1
  35. package/dist/src/session/skill-invoke.d.ts +21 -4
  36. package/dist/src/session/skill-invoke.js +83 -16
  37. package/dist/src/session/skill-invoke.js.map +1 -1
  38. package/dist/src/skills/skill-pick.d.ts +25 -0
  39. package/dist/src/skills/skill-pick.js +83 -0
  40. package/dist/src/skills/skill-pick.js.map +1 -0
  41. package/dist/src/skills/user-skills.d.ts +52 -3
  42. package/dist/src/skills/user-skills.js +96 -23
  43. package/dist/src/skills/user-skills.js.map +1 -1
  44. package/dist/src/style/cli-ui.js +3 -2
  45. package/dist/src/style/cli-ui.js.map +1 -1
  46. package/dist/src/tui/biosignal-wizard.js +1 -1
  47. package/dist/src/tui/biosignal-wizard.js.map +1 -1
  48. package/dist/src/updates/registry.js +8 -2
  49. package/dist/src/updates/registry.js.map +1 -1
  50. package/package.json +4 -4
  51. package/scripts/psyclaw.mjs +5 -0
  52. package/scripts/rebrand-pi.mjs +62 -3
  53. package/skills/core/analysis-plan/SKILL.md +67 -41
@@ -1,8 +1,8 @@
1
1
  import { createEditToolDefinition, DefaultPackageManager, getAgentDir, SettingsManager } from "@earendil-works/pi-coding-agent";
2
2
  import { withArgRepair } from "./arg-repair.js";
3
3
  import { applyAnswers, applyReply, ATTR_ZH, cardItems, cardText, planMessage as estimandPlanMessage, toConfirm as estimandsToConfirm, gaps as estimandGaps, loadSpec, MAX_CONFIRMS, materialsText, recordResult, researchQuestionLabels, saveSpec, settleByRecommendation, SPEC_JSON, SPEC_MD, stale as estimandStale, writeSpec } from "../../analysis/estimand.js";
4
- import { APPROVAL_QUESTION, ASK_RESEARCHER_QUESTION, DecisionModel, HAS_QUESTION_QUESTION, ROUTE_QUESTION, WRITING_SKILL_QUESTION } from "../../router/decision-model.js";
5
- import { lacksResearchQuestion } from "../../analysis/stats-router.js";
4
+ import { APPROVAL_QUESTION, APPROVAL_QUESTION_B, ASK_RESEARCHER_QUESTION, ASK_RESEARCHER_QUESTION_B, DecisionModel, HAS_QUESTION_QUESTION, HAS_QUESTION_QUESTION_B, ROUTE_QUESTION, ROUTE_QUESTION_B, WRITING_SKILL_QUESTION, WRITING_SKILL_QUESTION_B, } from "../../router/decision-model.js";
5
+ import { judgePrompt, parseJudge } from "../../router/llm-judge.js";
6
6
  import { isInstructionResult, isObservationEvidence, maskedPlaceholderReason, maskHeavyParts, maskToolObservationsStable, observationSettledLimit } from "./observation-mask.js";
7
7
  import { outputLogFooter, persistToolOutput } from "../../analysis/output-log.js";
8
8
  import { applyShellTimeout, isShellTimeout, moveTimeoutPrefix, scriptInCommand, ShellClock } from "../../analysis/shell-timeout.js";
@@ -38,32 +38,34 @@ import { readBiosignalPackCatalog, resolveBiosignalInstallPlan, } from "../../sk
38
38
  import { WakeOptionsComponent } from "../../tui/wake-options.js";
39
39
  import { applyWakeVerifySync, buildWakePrompt, createWakeVerifyChecklist, formatWakeResult, labelsFor, waitForPanelWakeAnswer, recommendedOptionIndex, } from "../../wake-options/runtime.js";
40
40
  import { panelHub } from "../../panel/hub.js";
41
- import { formatMcpListing, unwrapMcpResult } from "../../integrations/mcp-format.js";
42
- import { branchOf, findSkills, firstSentence, invokeSkill, readSkillSection, registrySkillListing, setSkillPathResolver, skillLoaded } from "../../session/skill-invoke.js";
41
+ import { branchOf, findSkills, firstSentence, invokeSkill, readSkillSection, skillIndexBlock, registrySkillListing, setSkillPathResolver, skillLoaded } from "../../session/skill-invoke.js";
43
42
  import { formatDecisionsBrief, openDecisions, readDecisions, recordAsked, recordDeviation, recordSettled } from "../../research/decisions.js";
44
43
  import { askedRows, checkProblems, PRACTICE_PATH, renderPractice, rowFor } from "../../research/practice.js";
45
44
  import { confirmIntent, INTENT_FIELDS, intentBrief, quoted, readIntent, recordSaid, renderIntent, restateIntent } from "../../research/intent.js";
46
45
  import { isPlanPointId, numberPoints, pointLabel, renderPlanMessage, settleFromReply } from "../../research/plan-message.js";
47
- import { enabledLocalSkillPaths, enabledLocalPromptPaths, readUserSkillState, scanLocalSkills, setLocalSkillEnabled, setLocalSkillsEnabled, skillNamesInPaths, userSkillId, } from "../../skills/user-skills.js";
48
- import { RuntimeMcpRegistry, setUserMcpConfigEnabled, } from "../../integrations/mcp-runtime.js";
46
+ import { enabledLocalSkillPaths, enabledLocalPromptPaths, chooseLocalSkills, localSkillOn, recordAutoPick, readUserSkillState, scanLocalSkills, setLocalSkillEnabled, setLocalSkillsEnabled, skillNamesInPaths, userSkillId, } from "../../skills/user-skills.js";
47
+ import { readMcpServers, setMcpServerEnabled } from "../../integrations/mcp-config.js";
48
+ import { keywordPick, parsePick, pickPrompt, PICK_LIMIT } from "../../skills/skill-pick.js";
49
+ import { areaOf, brainIndex, checkLinks, loadBrain, searchBrain, writePage } from "../../brain/brain.js";
50
+ import { candidateId, captureCandidates, markCandidate, readCandidates } from "../../brain/preferences.js";
49
51
  import { classifyIrreversibleHostCommand, extractToolCommandText, irreversibleHostBlockReason, } from "../../safety/irreversible-host-ops.js";
50
52
  import { SecretInputComponent, TextInputComponent, ProviderPickerComponent, } from "../../tui/provider-picker.js";
51
53
  import { resolveProviderBaseUrl } from "../../core/provider-endpoint.js";
52
54
  import { isArsPiActive, isArsPiTurn, psyclawArsPatch, setArsPiSessionActive } from "../../ars/profile.js";
53
55
  import { buildArsDoctorReport, ensurePdfEngineForExport } from "../../ars/doctor.js";
54
- import { formatAcademicSoftRouteInvocation, rankAcademicSoftRoutes, resolveAcademicSoftRoute, } from "../../ars/academic-router.js";
56
+ import { formatAcademicSoftRouteInvocation, rankAcademicSoftRoutes, } from "../../ars/academic-router.js";
55
57
  import { advanceAnalysisPlan, createAnalysisPlan, formatAnalysisPlanStatus, readActiveAnalysisPlan, syncHandoffFromAnalysisPlan, writeAnalysisPlan, } from "../../analysis/plan.js";
56
58
  import { bundledCoreSkillsDir, METHOD_TOPICS, mentionsLoadedSkill, methodTopicsIn } from "../../analysis/method-rules.js";
57
- import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
58
- import { tmpdir } from "node:os";
59
+ import { appendFileSync, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
60
+ import { homedir, tmpdir } from "node:os";
59
61
  import { validateAnalysisPlan } from "../../analysis/hooks.js";
60
62
  import { composeMethodInjection, injectedTopicsFor, readSkillPreferences, referencedDocumentTopics, refreshSkillResolution, SKILL_RESOLUTION_ENTRY, userSkillsOutsideScriptOnly, writeSkillPreferences, } from "../../analysis/skill-resolution.js";
61
- import { formatAnalysisPlanTakeover, resolveStatsIntent, } from "../../analysis/stats-router.js";
63
+ import { formatAnalysisPlanTakeover, } from "../../analysis/stats-router.js";
62
64
  import { arsRoot } from "../../ars/pi-panel-executor.js";
63
65
  import { ArsModeEditor, isArsModeEditorText } from "../../ars/mode-editor.js";
64
66
  import { MODE_STATUS, nextSessionMode, parseSessionMode, startingSessionMode, sessionModePrompt, unattendedAnalysisPrompt, } from "../../session/modes.js";
65
67
  import { continuouslyWorkWarningText, isContinuouslyWorkEnabled, } from "../../session/continuously-work.js";
66
- import { assertHumanVerifyGate, formatVerifyChecklist, isNaturalPlanConfirm, isPlanRitualConfirm, PLAN_RITUAL_PHRASE, ensureDefaultVerifyChecklist, loadVerifyChecklist, recordHumanVerification } from "../../verify/checklist.js";
68
+ import { assertHumanVerifyGate, formatVerifyChecklist, isPlanRitualConfirm, PLAN_RITUAL_PHRASE, ensureDefaultVerifyChecklist, loadVerifyChecklist, recordHumanVerification } from "../../verify/checklist.js";
67
69
  import { formatSessionHelp, formatSessionHelpBrief } from "../../session/help.js";
68
70
  import { openResearchWorkbench } from "../../panel/workbench.js";
69
71
  import { captureAgentError, extractPiGeneration, finishAgentSpan, initNodeObservability, lastPiGeneration, readTelemetryPreference, shutdownObservability, startAgentSpan, trackGateWaiting, trackLlmGeneration, trackSkillInstall, withAgentSpan, writeTelemetryPreference, } from "../../observability/index.js";
@@ -328,7 +330,7 @@ function toolApprovalSummary(toolName, input) {
328
330
  return `${toolName}${target ? `: ${target.slice(0, 240)}` : ""}`;
329
331
  }
330
332
  function toolNeedsApproval(toolName, input) {
331
- if (["write", "edit", "bash", "powershell", "psyclaw_workbench", "psyclaw_mcp"].includes(toolName))
333
+ if (["write", "edit", "bash", "powershell", "psyclaw_workbench"].includes(toolName) || toolName.startsWith("mcp__"))
332
334
  return true;
333
335
  const action = input && typeof input === "object" && !Array.isArray(input) ? input.action : undefined;
334
336
  return typeof action === "string" && /write|save|publish|install|download|execute|call/i.test(action);
@@ -503,7 +505,6 @@ async function skillManagerRows(root, state) {
503
505
  // recommended installs are excluded here — they are shown through their
504
506
  // recommended rows above (including on-disk-but-unvalidated installs).
505
507
  const userState = await readUserSkillState(root);
506
- const disabled = new Set(userState.disabled);
507
508
  const localSkills = await scanLocalSkills(root, { includeManaged: false });
508
509
  const localRows = localSkills.map((skill) => ({
509
510
  id: userSkillId(skill.name),
@@ -512,7 +513,7 @@ async function skillManagerRows(root, state) {
512
513
  sourceRef: skill.path,
513
514
  collection: false,
514
515
  installed: true,
515
- enabled: !disabled.has(skill.name),
516
+ enabled: localSkillOn(userState, skill.name),
516
517
  scope: "local",
517
518
  blocked: false,
518
519
  source: "local",
@@ -526,9 +527,10 @@ async function skillManagerRows(root, state) {
526
527
  const uniqueLocalRows = localRows.filter((row) => !installedRecommendedNames.has(row.name.toLocaleLowerCase()));
527
528
  return [...recommendedRows, ...uniqueLocalRows];
528
529
  }
529
- async function mcpManagerRows(root, state, runtime) {
530
+ async function mcpManagerRows(root, state) {
530
531
  const { items, installPrep } = await recommendedItems("mcp");
531
- const userEntries = await runtime.listUserConfigs(root);
532
+ // Servers in Pi's mcp.json (user and project); Pi's built-in MCP connects them.
533
+ const userEntries = await readMcpServers(root, getAgentDir());
532
534
  const configuredIds = new Set(userEntries.map((entry) => entry.id));
533
535
  const recommendedRows = items.map((item) => {
534
536
  const id = String(item.id ?? "");
@@ -552,9 +554,8 @@ async function mcpManagerRows(root, state, runtime) {
552
554
  ],
553
555
  };
554
556
  });
555
- // Merge user-configured MCP servers (`.psyclaw/mcp/*.json` and
556
- // `~/.psyclaw/mcp/*.json`) so the management page shows them too, even when
557
- // disabled. User rows win over a same-id recommended row.
557
+ // Merge the servers configured in mcp.json so the page shows them too, even when disabled.
558
+ // A configured server wins over a recommended row with the same id.
558
559
  const userRows = userEntries.map((entry) => ({
559
560
  id: entry.id,
560
561
  name: entry.name,
@@ -564,7 +565,7 @@ async function mcpManagerRows(root, state, runtime) {
564
565
  source: "user",
565
566
  userEntry: entry,
566
567
  details: [
567
- `传输:stdio · 范围:${entry.scope === "user" ? "用户级" : "项目级"}`,
568
+ `${/^https?:/.test(entry.command) ? "HTTP" : "stdio"} · 范围:${entry.scope === "user" ? "用户级" : "项目级"}`,
568
569
  `配置:${entry.path}`,
569
570
  ],
570
571
  }));
@@ -738,11 +739,11 @@ async function setRecommendedMcpEnabled(root, id, enabled) {
738
739
  await saveRecommendationState(root, state);
739
740
  }
740
741
  async function setUserMcpEnabled(entry, enabled) {
741
- await setUserMcpConfigEnabled(entry, enabled);
742
+ await setMcpServerEnabled(entry, enabled);
742
743
  }
743
744
  function modelMcpInstallTask(root, row, plan) {
744
745
  const suggestedCommand = typeof plan?.command === "string" ? plan.command : "请根据来源仓库的最新安装说明确定";
745
- const suggestedTarget = typeof plan?.target === "string" ? plan.target : `.psyclaw/mcp/${row.id}.json`;
746
+ const suggestedTarget = `~/.psyclaw/agent/mcp.json 的 mcpServers.${row.id}(与其他条目合并,不要覆盖;项目专用的写到 .psyclaw/mcp.json)`;
746
747
  return [
747
748
  `安装并配置推荐 MCP:${row.name} (${row.id})。`,
748
749
  `来源网址:${row.sourceRef ?? "未提供;请停止并告知用户"}`,
@@ -770,15 +771,15 @@ async function queueModelMcpInstall(pi, ctx, row, plan) {
770
771
  queueHiddenInstallTask(pi, ctx, modelMcpInstallTask(ctx.cwd, row, plan));
771
772
  ctx.ui.notify(`已将 ${row.name} 的安装任务交给当前模型(指令不展示在对话中;默认启用)。完成后请执行 /reload。`, "info");
772
773
  }
773
- async function showMcpManager(pi, ctx, runtime) {
774
+ async function showMcpManager(pi, ctx) {
774
775
  const catalog = await recommendedItems("mcp");
775
776
  if (!ctx.hasUI || typeof ctx.ui.custom !== "function") {
776
- const rows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd), runtime);
777
+ const rows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd));
777
778
  ctx.ui.notify(rows.map((row) => `${row.enabled ? "[on]" : "[off]"} ${row.id} — ${row.name}${row.source === "user" ? "(用户配置)" : ""}`).join("\n"), "info");
778
779
  return;
779
780
  }
780
781
  while (true) {
781
- const rows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd), runtime);
782
+ const rows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd));
782
783
  const action = await openMcpManager(ctx, rows);
783
784
  if (action.type === "close")
784
785
  return;
@@ -886,7 +887,7 @@ function modelBiosignalPackInstallTask(root, plan, skillRows, mcpRows, mcpPlans,
886
887
  `- MCP ${row?.name ?? id} (${id})`,
887
888
  ` 来源:${row?.sourceRef ?? "未提供"}`,
888
889
  ` 参考命令:${typeof prep?.command === "string" ? prep.command : "请阅读来源仓库安装说明"}`,
889
- ` 建议配置:${typeof prep?.target === "string" ? prep.target : `.psyclaw/mcp/${id}.json`}`,
890
+ ` 建议配置:~/.psyclaw/agent/mcp.json 的 mcpServers.${id}`,
890
891
  ].join("\n");
891
892
  });
892
893
  return [
@@ -894,7 +895,7 @@ function modelBiosignalPackInstallTask(root, plan, skillRows, mcpRows, mcpPlans,
894
895
  `研究域:${plan.domainNames.join("、")}(${plan.domainIds.join(", ")})`,
895
896
  `当前项目:${root}`,
896
897
  `Skill 安装位置:${skillScopeLabel(skillScope)}。`,
897
- "用户已通过 /mcp biosignal 向导明确授权本次打包安装。你可以直接联网、克隆或下载来源、使用所需包管理器安装依赖、执行安装命令,并写入与清单有关的项目或用户级配置;不要再次要求用户批准这些安装步骤。",
898
+ "用户已通过 /biosignal 向导明确授权本次打包安装。你可以直接联网、克隆或下载来源、使用所需包管理器安装依赖、执行安装命令,并写入与清单有关的项目或用户级配置;不要再次要求用户批准这些安装步骤。",
898
899
  "不要写入 data/raw、.git、凭据或符号链接目标。不要把模型口头声称当作完成证据;每个条目安装后检查目标目录或 MCP 配置是否存在。",
899
900
  "",
900
901
  "MCP 清单:",
@@ -924,7 +925,7 @@ async function markBiosignalPackDesired(root, plan, skillScope) {
924
925
  state.skillScopes = skillScopes;
925
926
  await saveRecommendationState(root, state);
926
927
  }
927
- async function queueBiosignalPackInstall(pi, ctx, plan, runtime) {
928
+ async function queueBiosignalPackInstall(pi, ctx, plan) {
928
929
  if (plan.mcpIds.length === 0 && plan.skillIds.length === 0) {
929
930
  ctx.ui.notify("所选研究域没有需要安装的 MCP 或 Skill。", "info");
930
931
  return;
@@ -958,7 +959,7 @@ async function queueBiosignalPackInstall(pi, ctx, plan, runtime) {
958
959
  source: "recommended",
959
960
  };
960
961
  });
961
- const mcpRows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd), runtime);
962
+ const mcpRows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd));
962
963
  const selectedMcp = plan.mcpIds.map((id) => {
963
964
  const row = mcpRows.find((candidate) => candidate.id === id);
964
965
  if (!row?.sourceRef)
@@ -971,20 +972,20 @@ async function queueBiosignalPackInstall(pi, ctx, plan, runtime) {
971
972
  plan.skillIds.length > 0 ? `Skill:${plan.skillIds.join(", ")}` : "Skill:无",
972
973
  plan.skillIds.length > 0 ? `Skill 安装位置:${skillScopeLabel(scope)}` : "",
973
974
  ].filter(Boolean).join("\n");
974
- const approved = await ctx.ui.confirm("交给当前模型安装生理信号能力包?", `${summary}\n\n模型将按现有 /mcp 与 /skill 约定完成下载与配置;安装后默认启用。`);
975
+ const approved = await ctx.ui.confirm("交给当前模型安装生理信号能力包?", `${summary}\n\n模型将按 /mcp-recommended 与 /skill 的约定完成下载与配置(MCP 写入 mcp.json);安装后默认启用。`);
975
976
  if (!approved)
976
977
  return;
977
978
  await markBiosignalPackDesired(ctx.cwd, plan, scope);
978
979
  queueHiddenInstallTask(pi, ctx, modelBiosignalPackInstallTask(ctx.cwd, plan, skillRows, selectedMcp, mcpCatalog.installPrep, scope));
979
980
  ctx.ui.notify("已将生理信号能力包安装任务交给当前模型(指令不展示在对话中)。完成后请执行 /reload,并在研究模式里使用。", "info");
980
981
  }
981
- async function showBiosignalPack(pi, ctx, runtime) {
982
+ async function showBiosignalPack(pi, ctx) {
982
983
  const catalog = await readBiosignalPackCatalog();
983
984
  if (!ctx.hasUI || typeof ctx.ui.custom !== "function") {
984
985
  const lines = [
985
986
  "生理信号分析能力包(无交互 UI 时仅列出研究域):",
986
987
  ...catalog.domains.map((domain) => `- ${domain.id}: ${domain.name} — ${domain.description}`),
987
- "请在交互式终端运行 /mcp biosignal 完成选型与安装。",
988
+ "请在交互式终端运行 /biosignal 完成选型与安装。",
988
989
  ];
989
990
  ctx.ui.notify(lines.join("\n"), "info");
990
991
  return;
@@ -1004,7 +1005,7 @@ async function showBiosignalPack(pi, ctx, runtime) {
1004
1005
  if (result.type === "close")
1005
1006
  return;
1006
1007
  const plan = resolveBiosignalInstallPlan(catalog, result.domainIds);
1007
- await queueBiosignalPackInstall(pi, ctx, plan, runtime);
1008
+ await queueBiosignalPackInstall(pi, ctx, plan);
1008
1009
  }
1009
1010
  async function showSkillManager(pi, ctx) {
1010
1011
  if (!ctx.hasUI || typeof ctx.ui.custom !== "function") {
@@ -1207,9 +1208,53 @@ export default function psyclawExtension(pi) {
1207
1208
  },
1208
1209
  });
1209
1210
  }
1210
- const runtimeMcps = new RuntimeMcpRegistry();
1211
- // Optional small decision model (PSYCLAW_DECIDER_URL); every use below falls back to the regex rule.
1211
+ // Judging what a message means (11-30): no regular expression decides it. The small decision model (StartLux,
1212
+ // local server on 127.0.0.1:8090 by default; PSYCLAW_DECIDER_URL=off turns it off) answers each question in
1213
+ // two wordings at once; when they disagree or are unsure, or the server is not running, the session's model
1214
+ // answers in a side call that sees only the question and the text. Each judgment is logged to .psyclaw/judge.jsonl.
1212
1215
  const decider = new DecisionModel();
1216
+ const judge = async (ctx, purpose, state, a, b) => {
1217
+ const started = Date.now();
1218
+ const cwd = ctx.cwd;
1219
+ let startlux;
1220
+ const note = (by, value, usage) => {
1221
+ if (!cwd || !existsSync(join(cwd, ".psyclaw")))
1222
+ return;
1223
+ try {
1224
+ // startlux: what the small model said to each wording (or why it did not answer), whoever decided.
1225
+ const small = startlux ? { status: startlux.status, ms: startlux.ms, ...(startlux.error ? { error: startlux.error } : {}), ...(startlux.a !== undefined ? { a: startlux.a, b: startlux.b } : {}) } : undefined;
1226
+ appendFileSync(join(cwd, ".psyclaw", "judge.jsonl"), `${JSON.stringify({ at: new Date().toISOString(), purpose, by, value: value ?? null, ms: Date.now() - started, ...(small ? { startlux: small } : {}), ...(usage ? { usage } : {}) })}\n`);
1227
+ }
1228
+ catch { /* the log is best effort */ }
1229
+ };
1230
+ startlux = await decider.check(purpose, state, a, b);
1231
+ const quick = startlux.value;
1232
+ if (quick !== undefined) {
1233
+ note("startlux", quick);
1234
+ return quick;
1235
+ }
1236
+ const registryApi = ctx.modelRegistry;
1237
+ const model = ctx.model;
1238
+ if (!model || typeof registryApi?.complete !== "function") {
1239
+ note("none", undefined);
1240
+ return undefined;
1241
+ }
1242
+ try {
1243
+ const prompt = judgePrompt(a, state);
1244
+ const reply = await Promise.race([
1245
+ registryApi.complete(model, { systemPrompt: prompt.system, messages: [{ role: "user", content: prompt.user, timestamp: Date.now() }] }, { maxTokens: 300 }),
1246
+ new Promise((resolve) => setTimeout(() => resolve(undefined), 30_000)),
1247
+ ]);
1248
+ const text = (reply?.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
1249
+ const value = parseJudge(text, a);
1250
+ note("model", value, reply?.usage);
1251
+ return value;
1252
+ }
1253
+ catch {
1254
+ note("none", undefined);
1255
+ return undefined;
1256
+ }
1257
+ };
1213
1258
  // --- analysis (estimand) mode ------------------------------------------------------------
1214
1259
  const userTexts = (ctx) => {
1215
1260
  try {
@@ -1273,12 +1318,95 @@ export default function psyclawExtension(pi) {
1273
1318
  return undefined;
1274
1319
  };
1275
1320
  setSkillPathResolver((name) => skillRegistry.find((skill) => skill.name === name)?.location ?? bundledSkillFile(name));
1321
+ // --- brain (src/brain): knowledge pages and the researcher's confirmed preferences ------------------
1322
+ const userBrainDir = () => join(homedir(), ".psyclaw", "brain");
1323
+ const STAGE_AREAS = { writing: ["writing", "figures", "reporting"], analysis: ["reporting", "figures"] };
1324
+ /**
1325
+ * What the model gets from the brain each turn (small, stable within a stage): the confirmed preferences
1326
+ * in full (they are short and always apply), and the index of the areas this stage uses; pages load with
1327
+ * psyclaw_brain read.
1328
+ */
1329
+ const brainPromptBlock = async (cwd, stage) => {
1330
+ const pages = await loadBrain(cwd);
1331
+ if (!pages.length)
1332
+ return "";
1333
+ const prefs = pages.filter((p) => p.status === "confirmed" && areaOf(p.id) === "preferences");
1334
+ const prefText = prefs.map((p) => `- ${p.body.replace(/\s+/g, " ").slice(0, 300)}`).join("\n").slice(0, 1_800);
1335
+ const areas = STAGE_AREAS[stage ?? ""] ?? ["writing", "figures", "reporting"];
1336
+ // The full index (one line with a gist per page) when it fits; else page names per area; never cut mid-list.
1337
+ const full = brainIndex(pages, { areas });
1338
+ const index = full.length <= 2_500 ? full : brainIndex(pages, { areas, titlesOnly: true });
1339
+ if (!prefText && !index)
1340
+ return "";
1341
+ return [
1342
+ "## Brain (what PsyClaw has learned)",
1343
+ ...(prefText ? ["The researcher's confirmed preferences (follow them unless they say otherwise now):", prefText] : []),
1344
+ ...(index ? [`Know-how for this stage (${full.length <= 2_500 ? "one line per page" : "page names by area; psyclaw_brain action=index area=<area> gives a line each"}); read a page with psyclaw_brain action=read id=<area>/<name> when the task needs it, and follow its [[links]] only as far as needed:`, index] : []),
1345
+ ].join("\n");
1346
+ };
1347
+ let prefNoticeShown = false;
1348
+ // The model sees the user's own skills that were picked for the task (background pick) or chosen by the
1349
+ // researcher; recommended skills they enabled always show. skillRegistry keeps every skill so a named or
1350
+ // searched one can still be loaded.
1351
+ let skillState;
1352
+ const recommendedLocation = (location) => /[\\/]\.psyclaw[\\/]imports[\\/]recommended[\\/]/.test(location) || location.startsWith(join(getAgentDir(), "skills"));
1353
+ const visibleLocal = (skill) => recommendedLocation(skill.location) || (skillState ? localSkillOn(skillState, skill.name) : false);
1276
1354
  const registry = (prompt) => {
1277
- const listed = registrySkillListing(prompt);
1355
+ const listed = registrySkillListing(prompt, visibleLocal);
1278
1356
  if (listed.skills.length)
1279
1357
  skillRegistry = listed.skills;
1280
1358
  return listed.systemPrompt;
1281
1359
  };
1360
+ let pickedThisSession = false;
1361
+ /**
1362
+ * Background skill pick (skill-pick.ts): the decision model when it runs, else one side call with the
1363
+ * session's model, else word overlap. Recorded in .psyclaw/user-skills.json (auto) and logged with its
1364
+ * usage in .psyclaw/skill-pick.jsonl. Never used once the researcher has chosen their skills.
1365
+ */
1366
+ const pickSkillsFor = async (ctx, task) => {
1367
+ const union = (await scanLocalSkills(ctx.cwd, { includeManaged: false })).filter((skill) => !CORE_SKILLS.has(skill.name));
1368
+ if (union.length === 0)
1369
+ return undefined;
1370
+ const rows = union.map((skill) => ({ name: skill.name, description: skill.description }));
1371
+ const names = rows.map((row) => row.name);
1372
+ let picked;
1373
+ let usage;
1374
+ if (decider.enabled) {
1375
+ const questions = Object.fromEntries(rows.map((row, i) => [`s${i}`, { type: "noul", instructions: `Is this task likely to use the skill "${row.name}": ${row.description.slice(0, 200)}?` }]));
1376
+ const answers = await decider.ask("skill-pick", { task: task.slice(0, 3000) }, questions);
1377
+ if (answers) {
1378
+ const scored = rows.map((row, i) => ({ name: row.name, p: answers[`s${i}`]?.noul ?? 0 })).filter((x) => x.p >= 0.5).sort((a, b) => b.p - a.p);
1379
+ picked = { names: scored.slice(0, PICK_LIMIT).map((x) => x.name), by: "decider" };
1380
+ }
1381
+ }
1382
+ const registryApi = ctx.modelRegistry;
1383
+ const model = ctx.model;
1384
+ if (!picked && model && typeof registryApi?.complete === "function") {
1385
+ try {
1386
+ const prompt = pickPrompt(task, rows);
1387
+ const reply = await Promise.race([
1388
+ registryApi.complete(model, { systemPrompt: prompt.system, messages: [{ role: "user", content: prompt.user, timestamp: Date.now() }] }, { maxTokens: 400 }),
1389
+ new Promise((resolve) => setTimeout(() => resolve(undefined), 30_000)),
1390
+ ]);
1391
+ if (reply) {
1392
+ usage = reply.usage;
1393
+ const text = (reply.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
1394
+ if (/\[/.test(text))
1395
+ picked = { names: parsePick(text, names), by: "model" };
1396
+ }
1397
+ }
1398
+ catch { /* fall back to words */ }
1399
+ }
1400
+ picked ??= { names: keywordPick(task, rows), by: "words" };
1401
+ await recordAutoPick(ctx.cwd, picked.names, picked.by, task.split("\n").find((line) => line.trim()) ?? "");
1402
+ try {
1403
+ mkdirSync(join(ctx.cwd, ".psyclaw"), { recursive: true });
1404
+ appendFileSync(join(ctx.cwd, ".psyclaw", "skill-pick.jsonl"), `${JSON.stringify({ at: new Date().toISOString(), by: picked.by, of: union.length, names: picked.names, ...(usage ? { usage } : {}) })}\n`);
1405
+ }
1406
+ catch { /* the log is a convenience */ }
1407
+ skillState = await readUserSkillState(ctx.cwd);
1408
+ return picked;
1409
+ };
1282
1410
  let arsModeEditor;
1283
1411
  let arsUiContext;
1284
1412
  let sessionMode = startingSessionMode(false);
@@ -1298,11 +1426,11 @@ export default function psyclawExtension(pi) {
1298
1426
  // Tools each mode leaves out. basic: only Pi's tools, skills, MCP and the choice box. research: the
1299
1427
  // research workflow, no estimand tool. analysis (estimand): data tools and psyclaw_spec, no research
1300
1428
  // workflow tools. Other active tools, such as ones added on the command line, are kept.
1301
- const MANAGED_TOOLS = ["psyclaw_workbench", "psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_plan", "psyclaw_cite", "psyclaw_ars_multi_agent", "psyclaw_ensure_pdf_engine", "psyclaw_spec", "psyclaw_intent"];
1429
+ const MANAGED_TOOLS = ["psyclaw_workbench", "psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_plan", "psyclaw_cite", "psyclaw_ars_multi_agent", "psyclaw_ensure_pdf_engine", "psyclaw_spec", "psyclaw_intent", "psyclaw_brain"];
1302
1430
  const MODE_TOOLS = {
1303
1431
  basic: [],
1304
1432
  research: MANAGED_TOOLS.filter((name) => name !== "psyclaw_spec"),
1305
- estimand: ["psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_spec"],
1433
+ estimand: ["psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_spec", "psyclaw_brain"],
1306
1434
  };
1307
1435
  let managedAvailable;
1308
1436
  const syncModeTools = (mode) => {
@@ -1367,7 +1495,6 @@ export default function psyclawExtension(pi) {
1367
1495
  pi.on("session_shutdown", () => {
1368
1496
  finishAgentSpan(llmTurnSpan);
1369
1497
  llmTurnSpan = undefined;
1370
- runtimeMcps.close();
1371
1498
  void shutdownObservability();
1372
1499
  });
1373
1500
  if (!legacyTestApi && typeof pi.on === "function")
@@ -1452,10 +1579,17 @@ export default function psyclawExtension(pi) {
1452
1579
  });
1453
1580
  if (!legacyTestApi && typeof pi.on === "function")
1454
1581
  pi.on("before_agent_start", async (event, ctx) => {
1582
+ if (ctx?.cwd)
1583
+ skillState = await readUserSkillState(ctx.cwd).catch(() => skillState);
1455
1584
  const restored = restoreSessionMode(ctx?.sessionManager);
1456
1585
  sessionMode = restored;
1457
1586
  syncModeTools(restored);
1458
1587
  let modeBlock = sessionModePrompt(restored, restored === "research" ? restoreStage(ctx?.sessionManager) : undefined);
1588
+ if (ctx?.cwd && restored !== "basic") {
1589
+ const block = await brainPromptBlock(ctx.cwd, restored === "estimand" ? "analysis" : restoreStage(ctx?.sessionManager)).catch(() => "");
1590
+ if (block)
1591
+ modeBlock = `${modeBlock}\n\n${block}`;
1592
+ }
1459
1593
  if (restored === "research" && ctx && !ctx.hasUI)
1460
1594
  modeBlock = `${modeBlock}\n\n${unattendedAnalysisPrompt()}`;
1461
1595
  if (isArsPiTurn(event.systemPrompt) || isArsPiActive(ctx?.sessionManager)) {
@@ -1475,6 +1609,9 @@ export default function psyclawExtension(pi) {
1475
1609
  if (!legacyTestApi && typeof pi.on === "function")
1476
1610
  pi.on("session_start", async (_event, ctx) => {
1477
1611
  arsUiContext = ctx;
1612
+ // Warm the decision model now (not awaited), so the first real judgment does not pay its cold start.
1613
+ if (decider.enabled)
1614
+ void decider.warm().catch(() => undefined);
1478
1615
  if (typeof ctx.cwd === "string") {
1479
1616
  const hasWorkspace = await hasCanonicalWorkspace(ctx.cwd).catch(() => false) || Boolean(await readActiveProject(ctx.cwd).catch(() => undefined));
1480
1617
  startingMode = startingSessionMode(hasWorkspace);
@@ -1487,8 +1624,30 @@ export default function psyclawExtension(pi) {
1487
1624
  }
1488
1625
  catch { /* session may not be open */ }
1489
1626
  if (ctx.hasUI) {
1627
+ // Only a real core-name conflict is worth a warning, one per skill name with every path it skipped.
1628
+ // A local copy of an enabled recommended skill is expected and stays in skill-resolution.json only.
1629
+ const byName = new Map();
1630
+ const preset = [];
1490
1631
  for (const row of discovered.resolution.skipped.filter((item) => item.reason === "core-name")) {
1491
- ctx.ui.notify(row.warning ?? `核心 skill「${row.name}」不能被同名 skill 覆盖,已跳过 ${row.path}。请改名后再启用。`, "warning");
1632
+ if (row.warning) {
1633
+ if (!preset.includes(row.warning))
1634
+ preset.push(row.warning);
1635
+ continue;
1636
+ }
1637
+ const paths = byName.get(row.name) ?? [];
1638
+ if (!paths.includes(row.path))
1639
+ paths.push(row.path);
1640
+ byName.set(row.name, paths);
1641
+ }
1642
+ for (const warning of preset)
1643
+ ctx.ui.notify(warning, "warning");
1644
+ // Local skills are opt-in: until the researcher chooses, none of them loads; say so once per session.
1645
+ const local = await enabledLocalSkillPaths(ctx.cwd, { excludedNames: coreSkillNames() }).catch(() => undefined);
1646
+ if (local && !local.chosen && local.notSelected.length > 0) {
1647
+ ctx.ui.notify(`发现 ${local.notSelected.length} 个本地 skill(各目录同名的只算一个)。收到任务后会在后台挑出可能用到的几个,模型只看到它们的说明;其余的连说明都不载入。/skill 可以自己选,选过之后以你的为准。`, "info");
1648
+ }
1649
+ for (const [name, paths] of byName) {
1650
+ ctx.ui.notify(`核心 skill「${name}」不能被同名 skill 覆盖,已跳过:${paths.join("、")}。请改名后再启用。`, "warning");
1492
1651
  }
1493
1652
  }
1494
1653
  }
@@ -1582,6 +1741,32 @@ export default function psyclawExtension(pi) {
1582
1741
  }
1583
1742
  const mode = arsModeEditor?.getMode() ?? restoreSessionMode(ctx.sessionManager);
1584
1743
  const trimmed = event.text.trim();
1744
+ // Background skill pick on the first task message of a session, while the researcher has not chosen.
1745
+ if (!pickedThisSession && trimmed && !trimmed.startsWith("/") && existsSync(join(ctx.cwd, ".psyclaw"))) {
1746
+ pickedThisSession = true;
1747
+ try {
1748
+ const state = await readUserSkillState(ctx.cwd);
1749
+ if (!state.chosen) {
1750
+ const picked = await pickSkillsFor(ctx, event.text);
1751
+ if (picked && ctx.hasUI)
1752
+ ctx.ui.notify(picked.names.length
1753
+ ? `已在后台为这项任务挑出 ${picked.names.length} 个 skill:${picked.names.join("、")}。模型只看到它们的名字和一句话说明,需要时再按节读;其余的连说明都不载入。/skill 可以调整。`
1754
+ : "后台挑选 skill:这项任务没有用得上的本地 skill,都不载入。/skill 可以手动加。", "info");
1755
+ }
1756
+ }
1757
+ catch { /* the pick never blocks the message */ }
1758
+ }
1759
+ // Brain: lasting instructions in the researcher's words become candidates; nothing is learned until /brain review.
1760
+ if (trimmed && !trimmed.startsWith("/")) {
1761
+ try {
1762
+ const added = await captureCandidates(userBrainDir(), event.text, ctx.cwd);
1763
+ if (added.length && ctx.hasUI && !prefNoticeShown) {
1764
+ prefNoticeShown = true;
1765
+ ctx.ui.notify(`记下 ${added.length} 条可能是你长期偏好的话(如「${added[0].said.slice(0, 30)}」)。确认之前不会用上;/brain review 确认、改写或丢弃。`, "info");
1766
+ }
1767
+ }
1768
+ catch { /* never blocks the message */ }
1769
+ }
1585
1770
  // Research mode: every message of the researcher goes into the intent record word for word (intent.ts),
1586
1771
  // before any routing, so the plan is checked against their words and a later session can read them back.
1587
1772
  if (mode === "research" && !trimmed.startsWith("/") && existsSync(join(ctx.cwd, ".psyclaw"))) {
@@ -1615,14 +1800,12 @@ export default function psyclawExtension(pi) {
1615
1800
  }
1616
1801
  // Plan confirmations (0.34): each card settles its own choice; once every choice is settled, a plain yes
1617
1802
  // (「可以」「批准」) or the old approval sentence approves the whole plan. No typed ritual is required.
1618
- let approves = isPlanRitualConfirm(trimmed) || isNaturalPlanConfirm(trimmed);
1619
- if (mode === "research" && decider.enabled && trimmed.length <= 400 && !isPlanRitualConfirm(trimmed)) {
1803
+ // The typed ritual is a command (exact text); any other reply is judged for its meaning, never by a pattern.
1804
+ let approves = isPlanRitualConfirm(trimmed);
1805
+ if (!approves && mode === "research" && trimmed.length <= 400) {
1620
1806
  const pending = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
1621
1807
  if (pending && ["awaiting-confirm", "ready", "reviewing", "clarifying", "drafting"].includes(pending.status)) {
1622
- const answers = await decider.ask("plan-approval", { reply: trimmed }, { meaning: APPROVAL_QUESTION });
1623
- const meaning = DecisionModel.confident(answers?.meaning);
1624
- if (meaning)
1625
- approves = meaning === "approve";
1808
+ approves = (await judge(ctx, "plan-approval", { reply: trimmed }, APPROVAL_QUESTION, APPROVAL_QUESTION_B)) === "approve";
1626
1809
  }
1627
1810
  }
1628
1811
  // A reply while the restated intent waits for the researcher: confirm it or restate again.
@@ -1733,31 +1916,26 @@ export default function psyclawExtension(pi) {
1733
1916
  if (mode !== "research")
1734
1917
  return;
1735
1918
  // Analysis first: a data-analysis request that also asks for figures or a write-up is still an
1736
- // analysis (resolveStatsIntent already steps aside for writing-dominant requests such as 写论文).
1737
- // The decision model routes when it is on and confident; otherwise the regex rules do.
1919
+ // analysis.
1920
+ // The meaning is judged (decision model in two wordings, else a large-model side call), never by a pattern.
1738
1921
  let routed;
1739
- if (decider.enabled && !/^\//.test(trimmed)) {
1740
- const answers = await decider.ask("route", { message: trimmed.slice(0, 6_000) }, { route: ROUTE_QUESTION, writing_skill: WRITING_SKILL_QUESTION });
1741
- const route = DecisionModel.confident(answers?.route);
1742
- if (route) {
1743
- const skill = DecisionModel.confident(answers?.writing_skill, 0.6);
1744
- routed = { route, ...(skill ? { skill } : {}) };
1922
+ if (!/^\//.test(trimmed)) {
1923
+ const message = { message: trimmed.slice(0, 6_000) };
1924
+ const route = await judge(ctx, "route", message, ROUTE_QUESTION, ROUTE_QUESTION_B);
1925
+ if (typeof route === "string") {
1926
+ const skill = route === "writing" ? await judge(ctx, "writing-skill", message, WRITING_SKILL_QUESTION, WRITING_SKILL_QUESTION_B) : undefined;
1927
+ routed = { route, ...(typeof skill === "string" ? { skill: skill } : {}) };
1745
1928
  }
1746
1929
  }
1747
- const wantsStats = routed ? routed.route === "analysis" : Boolean(resolveStatsIntent(trimmed));
1748
- const wantsAcademic = routed ? routed.route === "writing" : !wantsStats && Boolean(resolveAcademicSoftRoute(trimmed));
1930
+ const wantsStats = routed?.route === "analysis";
1931
+ const wantsAcademic = routed?.route === "writing";
1749
1932
  if (mode === "research" && (wantsStats || wantsAcademic))
1750
1933
  setStage(ctx.sessionManager, wantsStats ? "analysis" : "writing");
1751
1934
  // No research question yet: start with academic-grill (brainstorm questions from the data, or grill
1752
1935
  // a rough idea) before any plan or writing.
1753
1936
  if (mode === "research" && trimmed.length <= 2_000) {
1754
- let noQuestion = lacksResearchQuestion(trimmed);
1755
- if (decider.enabled && (wantsStats || wantsAcademic || noQuestion)) {
1756
- const answers = await decider.ask("has-question", { message: trimmed }, { has_question: HAS_QUESTION_QUESTION });
1757
- const has = DecisionModel.yesNo(answers?.has_question);
1758
- if (has !== undefined)
1759
- noQuestion = !has;
1760
- }
1937
+ const noQuestion = (wantsStats || wantsAcademic)
1938
+ && (await judge(ctx, "has-question", { message: trimmed }, HAS_QUESTION_QUESTION, HAS_QUESTION_QUESTION_B)) === false;
1761
1939
  if (noQuestion) {
1762
1940
  return {
1763
1941
  action: "transform",
@@ -1801,7 +1979,7 @@ export default function psyclawExtension(pi) {
1801
1979
  if (wantsAcademic) {
1802
1980
  const match = routed?.skill
1803
1981
  ? { skill: routed.skill, reason: "decision model", priority: 0 }
1804
- : resolveAcademicSoftRoute(event.text) ?? (routed ? { skill: "academic-paper", reason: "decision model (writing)", priority: 0 } : null);
1982
+ : routed ? { skill: "academic-paper", reason: "decision model (writing)", priority: 0 } : null;
1805
1983
  if (!match)
1806
1984
  return;
1807
1985
  const ranked = rankAcademicSoftRoutes(event.text, 3);
@@ -1813,9 +1991,7 @@ export default function psyclawExtension(pi) {
1813
1991
  {
1814
1992
  const userSkills = await userSkillsOutsideScriptOnly(ctx.cwd).catch(() => []);
1815
1993
  const userSkillNames = userSkills.map((skill) => skill.name);
1816
- const match = routed
1817
- ? (routed.route === "analysis" ? { kind: "stats-analysis", reason: "decision model", topics: methodTopicsIn(event.text) } : null)
1818
- : resolveStatsIntent(event.text, { userSkillNames });
1994
+ const match = routed?.route === "analysis" ? { kind: "stats-analysis", reason: "decision model", topics: methodTopicsIn(event.text) } : null;
1819
1995
  const namesUserSkill = mentionsLoadedSkill(event.text, userSkillNames);
1820
1996
  // The task often lives in a document the message names ("Read BRIEF.md"), not in the message itself.
1821
1997
  const documents = namesUserSkill
@@ -2539,11 +2715,35 @@ export default function psyclawExtension(pi) {
2539
2715
  });
2540
2716
  if (!legacyTestApi)
2541
2717
  pi.registerCommand("skill", {
2542
- description: "打开 Skill 管理页;/skill preference [reset] 查看或重置方法主题的 skill 选择",
2718
+ description: "Skill 管理页(勾选要加载的 skill);/skill pick <研究方向> 由模型挑选;/skill preference [reset] 方法主题的 skill 选择",
2543
2719
  handler: async (args, ctx) => {
2544
2720
  const [sub = "", ...rest] = args.trim().split(/\s+/);
2545
2721
  if (sub === "preference")
2546
2722
  return skillPreferenceHandler(rest.join(" "), ctx);
2723
+ if (sub === "pick") {
2724
+ try {
2725
+ let intent = rest.join(" ").trim();
2726
+ if (!intent && ctx.hasUI && typeof ctx.ui.input === "function")
2727
+ intent = ((await ctx.ui.input("你主要做什么研究?(例如:问卷调查的中介分析;EEG 的 ERP 分析)")) ?? "").trim();
2728
+ if (!intent) {
2729
+ ctx.ui.notify("用法:/skill pick 你的研究方向,例如 /skill pick 问卷调查的中介分析", "info");
2730
+ return;
2731
+ }
2732
+ const state = await readUserSkillState(ctx.cwd);
2733
+ if (state.chosen) {
2734
+ ctx.ui.notify("你已经在 /skill 里自己选过 skill,后台挑选不会覆盖它;要改请直接在 /skill 里勾选。", "info");
2735
+ return;
2736
+ }
2737
+ const picked = await pickSkillsFor(ctx, intent);
2738
+ ctx.ui.notify(!picked ? "没有找到本地 skill。" : picked.names.length
2739
+ ? `按「${intent}」挑出 ${picked.names.length} 个 skill:${picked.names.join("、")}。模型只看到它们的名字和一句话说明,需要时再按节读;其余的连说明都不载入。`
2740
+ : `按「${intent}」没有挑出用得上的本地 skill。`, "info");
2741
+ }
2742
+ catch (error) {
2743
+ await notifyError(ctx, error);
2744
+ }
2745
+ return;
2746
+ }
2547
2747
  try {
2548
2748
  await showSkillManager(pi, ctx);
2549
2749
  }
@@ -2654,21 +2854,83 @@ export default function psyclawExtension(pi) {
2654
2854
  }
2655
2855
  },
2656
2856
  });
2857
+ // /mcp belongs to Pi's built-in MCP (connections, sign-in, exposure, enable/disable). PsyClaw keeps
2858
+ // its recommended-MCP catalog and the biosignal pack under their own names.
2657
2859
  if (!legacyTestApi)
2658
- pi.registerCommand("mcp", {
2659
- description: "打开 MCP 安装与配置管理页;/mcp biosignal 打开生理信号分析能力包",
2860
+ pi.registerCommand("brain", {
2861
+ description: "PsyClaw 的记忆:/brain 看概况;/brain review 确认学到的偏好;/brain check 检查链接",
2660
2862
  handler: async (args, ctx) => {
2661
- if (args.trim() === "biosignal") {
2662
- try {
2663
- await showBiosignalPack(pi, ctx, runtimeMcps);
2863
+ try {
2864
+ const sub = args.trim().split(/\s+/)[0] ?? "";
2865
+ const pages = await loadBrain(ctx.cwd);
2866
+ if (sub === "review") {
2867
+ const pending = (await readCandidates(userBrainDir())).filter((c) => c.state === "new");
2868
+ if (!pending.length) {
2869
+ ctx.ui.notify("没有待确认的偏好。", "info");
2870
+ return;
2871
+ }
2872
+ let kept = 0;
2873
+ for (const c of pending) {
2874
+ if (!ctx.hasUI || typeof ctx.ui.select !== "function")
2875
+ break;
2876
+ const choice = await ctx.ui.select(`这句话是你的长期偏好吗?\n「${c.said}」\n(${c.at.slice(0, 10)},${c.area})`, ["记住(用原话)", "改写后记住", "丢弃", "先跳过"]);
2877
+ if (!choice || choice === "先跳过")
2878
+ continue;
2879
+ if (choice === "丢弃") {
2880
+ await markCandidate(userBrainDir(), c.id, "discarded");
2881
+ continue;
2882
+ }
2883
+ let text = c.said;
2884
+ if (choice === "改写后记住" && typeof ctx.ui.input === "function")
2885
+ text = ((await ctx.ui.input("用一句话写下这条偏好", c.said)) ?? c.said).trim() || c.said;
2886
+ await writePage(userBrainDir(), {
2887
+ id: `preferences/${c.area}-${c.id}`, type: "preference", title: text.slice(0, 40), applies_to: c.area === "general" ? [] : [c.area === "figure" ? "figure" : c.area === "writing" ? "write" : "analysis"],
2888
+ sources: [{ said: c.said, at: c.at }], status: "confirmed", updated_at: new Date().toISOString().slice(0, 10), body: text,
2889
+ }, `confirmed preference (from「${c.said.slice(0, 40)}」)`);
2890
+ await markCandidate(userBrainDir(), c.id, "confirmed");
2891
+ kept += 1;
2892
+ }
2893
+ ctx.ui.notify(`记住了 ${kept} 条偏好;之后每次都会带上。改或删:编辑 ~/.psyclaw/brain/preferences/ 里的页面。`, "info");
2894
+ return;
2664
2895
  }
2665
- catch (error) {
2666
- await notifyError(ctx, error);
2896
+ if (sub === "check") {
2897
+ const { broken, backlinks } = checkLinks(pages);
2898
+ ctx.ui.notify(broken.length ? `断开的链接 ${broken.length} 个:\n${broken.map((b) => `- ${b.from} → [[${b.to}]]`).join("\n")}` : `链接都正常(${pages.length} 页,${[...backlinks.values()].reduce((n, v) => n + v.length, 0)} 条引用)。`, broken.length ? "warning" : "info");
2899
+ return;
2667
2900
  }
2668
- return;
2901
+ const byArea = new Map();
2902
+ for (const p of pages)
2903
+ byArea.set(areaOf(p.id), (byArea.get(areaOf(p.id)) ?? 0) + 1);
2904
+ const pending = (await readCandidates(userBrainDir())).filter((c) => c.state === "new").length;
2905
+ ctx.ui.notify([
2906
+ `PsyClaw 的记忆:${pages.length} 页(${[...byArea].map(([a, n]) => `${a} ${n}`).join(",") || "空"})。`,
2907
+ `待你确认的偏好:${pending} 条${pending ? "(/brain review)" : ""}。`,
2908
+ "位置:内置知识随 PsyClaw 发布;你的在 ~/.psyclaw/brain;本项目的在 .psyclaw/brain(同名页以项目为准)。",
2909
+ ].join("\n"), "info");
2910
+ }
2911
+ catch (error) {
2912
+ await notifyError(ctx, error);
2669
2913
  }
2914
+ },
2915
+ });
2916
+ if (!legacyTestApi)
2917
+ pi.registerCommand("mcp-recommended", {
2918
+ description: "推荐 MCP 目录:查看、安装、启用(连接和登录用 /mcp)",
2919
+ handler: async (_args, ctx) => {
2920
+ try {
2921
+ await showMcpManager(pi, ctx);
2922
+ }
2923
+ catch (error) {
2924
+ await notifyError(ctx, error);
2925
+ }
2926
+ },
2927
+ });
2928
+ if (!legacyTestApi)
2929
+ pi.registerCommand("biosignal", {
2930
+ description: "生理信号分析能力包(EEG/MEG/fNIRS 的 MCP 与 Skill)",
2931
+ handler: async (_args, ctx) => {
2670
2932
  try {
2671
- await showMcpManager(pi, ctx, runtimeMcps);
2933
+ await showBiosignalPack(pi, ctx);
2672
2934
  }
2673
2935
  catch (error) {
2674
2936
  await notifyError(ctx, error);
@@ -2858,50 +3120,6 @@ export default function psyclawExtension(pi) {
2858
3120
  });
2859
3121
  if (typeof pi.registerTool === "function") {
2860
3122
  registerAnalysisRuntimeTools(pi);
2861
- pi.registerTool({
2862
- name: "psyclaw_mcp",
2863
- label: "MCP tools",
2864
- description: "List and call tools from MCP servers enabled in .psyclaw/mcp/*.json. action=list gives one line per tool (name, what it does, parameters; * = required); action=list with server and tool gives that tool's full input schema. Then action=call with the exact server and tool names.",
2865
- promptSnippet: "Discover and call enabled MCP servers such as MNE through PsyClaw.",
2866
- parameters: Type.Object({
2867
- action: Type.Union([Type.Literal("list"), Type.Literal("call")]),
2868
- server: Type.Optional(Type.String({ description: "Configured MCP server id, for example mne-mcp" })),
2869
- tool: Type.Optional(Type.String({ description: "Exact MCP tool name returned by action=list (with action=list: show its full schema)" })),
2870
- input: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
2871
- }),
2872
- executionMode: "sequential",
2873
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2874
- try {
2875
- if (params.action === "list") {
2876
- const servers = await runtimeMcps.list(ctx.cwd, params.server);
2877
- return { content: [{ type: "text", text: formatMcpListing(servers, params.tool) }], details: { action: "list", servers: servers.length } };
2878
- }
2879
- if (!(await readActiveProject(ctx.cwd))) {
2880
- return {
2881
- content: [{ type: "text", text: "当前目录尚未 /init。可以查看 MCP 工具,但实际调用需先运行 /init。" }],
2882
- details: { action: "call", status: "general-mode" },
2883
- isError: true,
2884
- };
2885
- }
2886
- if (!params.server || !params.tool)
2887
- throw new Error("server and tool are required for action=call");
2888
- const result = await runtimeMcps.call(ctx.cwd, params.server, params.tool, params.input ?? {});
2889
- const unwrapped = unwrapMcpResult(result);
2890
- return {
2891
- content: [{ type: "text", text: unwrapped.text }],
2892
- details: { action: "call", server: params.server, tool: params.tool },
2893
- ...(unwrapped.isError ? { isError: true } : {}),
2894
- };
2895
- }
2896
- catch (error) {
2897
- return {
2898
- content: [{ type: "text", text: `MCP call failed: ${error instanceof Error ? error.message : String(error)}` }],
2899
- details: { action: params.action, status: "failed" },
2900
- isError: true,
2901
- };
2902
- }
2903
- },
2904
- });
2905
3123
  pi.registerTool({
2906
3124
  name: "psyclaw_ars_multi_agent",
2907
3125
  label: "ARS multi-agent review bridge",
@@ -3014,19 +3232,39 @@ export default function psyclawExtension(pi) {
3014
3232
  label: "Skill",
3015
3233
  description: "Find or load a skill. action=find with a few words about the task lists the skills that fit, with what each does. name=<skill> loads that skill's instructions (any skill listed in available_skills). Load a skill only when the task needs it; do not read skill files directly.",
3016
3234
  parameters: Type.Object({
3017
- action: Type.Optional(Type.Union([Type.Literal("load"), Type.Literal("find")])),
3235
+ action: Type.Optional(Type.Union([Type.Literal("load"), Type.Literal("find"), Type.Literal("choose")])),
3018
3236
  name: Type.Optional(Type.String({ description: "Skill name from available_skills (action=load)" })),
3237
+ names: Type.Optional(Type.Array(Type.String(), { description: "action=choose: the local skills that fit the researcher's work (exact names from the list you were given); the others are not loaded" })),
3238
+ intent: Type.Optional(Type.String({ description: "action=choose: what the researcher said they work on, in their words" })),
3019
3239
  query: Type.Optional(Type.String({ description: "A few words about the task (action=find)" })),
3020
- section: Type.Optional(Type.String({ description: "Load only this section of the skill (its heading), e.g. one listed under 'Sections loaded on demand'" })),
3240
+ section: Type.Optional(Type.String({ description: "Load one section of the skill by its heading (as listed in the skill's index); \"all\" loads the whole skill" })),
3021
3241
  purpose: Type.Optional(Type.String({ description: "Short user-facing reason for using this skill now" })),
3022
3242
  }),
3023
3243
  executionMode: "sequential",
3024
- async execute(_toolCallId, params) {
3244
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3245
+ if (params.action === "choose") {
3246
+ // The researcher described their work (/skill pick); record the local skills that fit as the selection.
3247
+ const union = await scanLocalSkills(ctx.cwd, { includeManaged: false });
3248
+ const known = new Map(union.map((skill) => [skill.name.toLocaleLowerCase(), skill.name]));
3249
+ const names = (params.names ?? []).map((n) => known.get(n.trim().toLocaleLowerCase())).filter((n) => !!n);
3250
+ const unknown = (params.names ?? []).filter((n) => !known.has(n.trim().toLocaleLowerCase()));
3251
+ if (unknown.length)
3252
+ return { content: [{ type: "text", text: `Not local skills: ${unknown.join(", ")}. Use exact names from the list.` }], details: { status: "failed", name: "" }, isError: true };
3253
+ await chooseLocalSkills(ctx.cwd, names, "auto", params.intent);
3254
+ return {
3255
+ content: [{ type: "text", text: `已按研究方向启用 ${names.length} 个本地 skill:${names.join("、") || "(无)"};其余 ${union.length - names.length} 个不加载。Tell the researcher which ones and why in one short list; they take effect after /reload, and /skill changes them at any time. Also tell them that a chosen skill is not put into the conversation whole: only its name is listed, and its description, body or one section is read when a task needs it.` }],
3256
+ details: { status: "chosen", name: names.join(",") },
3257
+ };
3258
+ }
3025
3259
  if (params.action === "find" || (!params.name && params.query)) {
3026
- const hits = findSkills(skillRegistry, params.query ?? params.name ?? "");
3260
+ // Skills in the model's list first; only when none fits, the ones not picked for this task.
3261
+ const query = params.query ?? params.name ?? "";
3262
+ const listedHits = findSkills(skillRegistry.filter((skill) => skill.group !== "Yours" || visibleLocal(skill)), query);
3263
+ const hits = listedHits.length ? listedHits : findSkills(skillRegistry, query);
3264
+ const hidden = !listedHits.length && hits.length > 0;
3027
3265
  const text = hits.length
3028
- ? hits.map((skill) => `- ${skill.name} (${skill.group}): ${firstSentence(skill.description, 220)}`).join("\n")
3029
- : "No listed skill matches those words. Try other words, or work without a skill.";
3266
+ ? `${hidden ? "None of the skills picked for this task fits; these were not picked (load one only if the task really needs it):\n" : ""}${hits.map((skill) => `- ${skill.name} (${skill.group}): ${firstSentence(skill.description, 220)}`).join("\n")}`
3267
+ : "No skill matches those words. Try other words, or work without a skill.";
3030
3268
  return { content: [{ type: "text", text }], details: { status: "found", name: hits.map((skill) => skill.name).join(",") } };
3031
3269
  }
3032
3270
  const name = (params.name ?? "").trim();
@@ -3039,13 +3277,21 @@ export default function psyclawExtension(pi) {
3039
3277
  };
3040
3278
  }
3041
3279
  try {
3042
- if (params.section) {
3280
+ if (params.section && params.section.trim().toLowerCase() !== "all") {
3043
3281
  const text = readSkillSection(path, params.section);
3044
3282
  return {
3045
3283
  content: [{ type: "text", text: text ?? `No section starting with "${params.section}" in ${name}.` }],
3046
3284
  details: { status: text ? "active" : "failed", name },
3047
3285
  };
3048
3286
  }
3287
+ // Stage 3: a large skill comes as its index first; its sections load one at a time (section="all": whole).
3288
+ const index = params.section?.trim().toLowerCase() === "all" ? undefined : skillIndexBlock(name, path);
3289
+ if (index) {
3290
+ return {
3291
+ content: [{ type: "text", text: `正在使用 Skill:${name}${params.purpose ? `(${params.purpose})` : ""}\nSkill directory (resolve relative paths against it): ${dirname(path)}\n\n${index}` }],
3292
+ details: { status: "active", name, ...(params.purpose === undefined ? {} : { purpose: params.purpose }) },
3293
+ };
3294
+ }
3049
3295
  const instructions = await readFile(path, "utf8");
3050
3296
  return {
3051
3297
  content: [{ type: "text", text: `正在使用 Skill:${name}${params.purpose ? `(${params.purpose})` : ""}\nSkill directory (resolve relative paths against it): ${dirname(path)}\n\n${instructions}` }],
@@ -3347,6 +3593,51 @@ export default function psyclawExtension(pi) {
3347
3593
  }
3348
3594
  },
3349
3595
  });
3596
+ pi.registerTool({
3597
+ name: "psyclaw_brain",
3598
+ label: "记忆",
3599
+ description: "PsyClaw's brain: know-how pages (writing, figures, reporting) and the researcher's confirmed preferences, one concept per page. action=index (area writing|figures|reporting|preferences, optional) lists pages one line each; action=read id=<id> gives one page (follow its [[links]] only as far as needed); action=search query=<words>; action=remember quote=<the researcher's words> when they state a lasting preference (it becomes a candidate they confirm with /brain review; never record your own guesses).",
3600
+ parameters: Type.Object({
3601
+ action: Type.Union([Type.Literal("index"), Type.Literal("read"), Type.Literal("search"), Type.Literal("remember")]),
3602
+ area: Type.Optional(Type.String()),
3603
+ id: Type.Optional(Type.String()),
3604
+ query: Type.Optional(Type.String()),
3605
+ quote: Type.Optional(Type.String({ description: "remember: the researcher's words, unchanged" })),
3606
+ }),
3607
+ executionMode: "sequential",
3608
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3609
+ try {
3610
+ const pages = await loadBrain(ctx.cwd);
3611
+ if (params.action === "index") {
3612
+ const text = brainIndex(pages, params.area ? { areas: [params.area] } : {});
3613
+ return { content: [{ type: "text", text: text || "No pages yet." }], details: { pages: pages.length } };
3614
+ }
3615
+ if (params.action === "read") {
3616
+ const page = pages.find((p) => p.id === (params.id ?? "").trim().replace(/^\[\[|\]\]$/g, ""));
3617
+ if (!page)
3618
+ return { content: [{ type: "text", text: `No page ${params.id}. Use action=index or action=search.` }], details: { status: "missing" }, isError: true };
3619
+ const sources = page.sources.map((src) => src.skill ? `from ${src.skill}` : src.said ? `the researcher said「${src.said}」${src.at ? ` (${src.at})` : ""}` : "").filter(Boolean).join("; ");
3620
+ return { content: [{ type: "text", text: `# ${page.title} [[${page.id}]]\n${sources ? `Source: ${sources}\n` : ""}\n${page.body}` }], details: { id: page.id, layer: page.layer } };
3621
+ }
3622
+ if (params.action === "search") {
3623
+ const hits = searchBrain(pages, params.query ?? "");
3624
+ return { content: [{ type: "text", text: hits.length ? hits.map((p) => `- [[${p.id}]] ${p.title}`).join("\n") : "No page matches." }], details: { hits: hits.map((p) => p.id) } };
3625
+ }
3626
+ const quote = params.quote?.trim();
3627
+ if (!quote)
3628
+ throw new Error("remember needs quote: the researcher's words, unchanged");
3629
+ const said = userTexts(ctx);
3630
+ if (!said.includes(quote))
3631
+ throw new Error("the quote is not in the researcher's messages; quote them word for word");
3632
+ const added = await captureCandidates(userBrainDir(), quote, ctx.cwd);
3633
+ const already = !added.length && (await readCandidates(userBrainDir())).some((c) => c.id === candidateId(quote));
3634
+ return { content: [{ type: "text", text: added.length ? "Noted as a preference candidate; the researcher confirms it with /brain review." : already ? "Already noted." : "That does not read as a lasting preference; nothing recorded." }], details: { added: added.length } };
3635
+ }
3636
+ catch (error) {
3637
+ return { content: [{ type: "text", text: `记忆操作失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
3638
+ }
3639
+ },
3640
+ });
3350
3641
  pi.registerTool({
3351
3642
  name: "psyclaw_intent",
3352
3643
  label: "研究意图",
@@ -3547,15 +3838,14 @@ export default function psyclawExtension(pi) {
3547
3838
  // The decision model may promote a convention to the researcher (never the reverse).
3548
3839
  const submitted = (params.decisions ?? []);
3549
3840
  const promote = new Set();
3550
- if (decider.enabled) {
3551
- for (const [i, p] of submitted.entries()) {
3552
- if (p.by !== "analyst" || !p.reason?.trim())
3553
- continue;
3554
- const answers = await decider.ask("ask-researcher", { question: p.question, choice: p.options?.[(p.recommended ?? 1) - 1] ?? "", reason: p.reason }, { intent: ASK_RESEARCHER_QUESTION });
3555
- if (DecisionModel.yesNo(answers?.intent) === true)
3556
- promote.add(i);
3557
- }
3558
- }
3841
+ // All analyst decisions are judged at once (side calls run in parallel, so a plan waits for one, not ten).
3842
+ await Promise.all(submitted.map(async (p, i) => {
3843
+ if (p.by !== "analyst" || !p.reason?.trim())
3844
+ return;
3845
+ const state = { question: p.question, choice: p.options?.[(p.recommended ?? 1) - 1] ?? "", reason: p.reason };
3846
+ if ((await judge(ctx, "ask-researcher", state, ASK_RESEARCHER_QUESTION, ASK_RESEARCHER_QUESTION_B)) === true)
3847
+ promote.add(i);
3848
+ }));
3559
3849
  const numbered = numberPoints(plan.id, submitted, promote);
3560
3850
  // Quotes are checked against their source. by brief: the materials or a message (briefs are often pasted);
3561
3851
  // by researcher: their messages or their answers on cards (which live in the decision record).
@@ -3709,9 +3999,8 @@ export default function psyclawExtension(pi) {
3709
3999
  // Only ever escalates: a decision the analyst settled that the model judges intent-dependent
3710
4000
  // gets a note to ask the researcher. It never cancels a question.
3711
4001
  let escalate = "";
3712
- if (params.by === "analyst" && decider.enabled) {
3713
- const answers = await decider.ask("ask-researcher", { question: event.question, choice: event.choice, reason: params.reason ?? "" }, { intent: ASK_RESEARCHER_QUESTION });
3714
- if (DecisionModel.yesNo(answers?.intent) === true) {
4002
+ if (params.by === "analyst") {
4003
+ if ((await judge(ctx, "ask-researcher", { question: event.question, choice: event.choice, reason: params.reason ?? "" }, ASK_RESEARCHER_QUESTION, ASK_RESEARCHER_QUESTION_B)) === true) {
3715
4004
  escalate = `\n[psyclaw] 这一项看起来取决于研究者的意图,不是惯例:请用 psyclaw_ask 问研究者(id ${event.id}),给出你的推荐。`;
3716
4005
  }
3717
4006
  }