psyclaw 0.34.0-preview.2 → 0.34.0-preview.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/adapters/pi/extension.js +422 -140
- package/dist/src/adapters/pi/extension.js.map +1 -1
- package/dist/src/adapters/pi/observation-mask.js +5 -3
- package/dist/src/adapters/pi/observation-mask.js.map +1 -1
- package/dist/src/analysis/skill-resolution.d.ts +18 -2
- package/dist/src/analysis/skill-resolution.js +32 -17
- package/dist/src/analysis/skill-resolution.js.map +1 -1
- package/dist/src/brain/brain.d.ts +64 -0
- package/dist/src/brain/brain.js +206 -0
- package/dist/src/brain/brain.js.map +1 -0
- package/dist/src/brain/preferences.d.ts +19 -0
- package/dist/src/brain/preferences.js +80 -0
- package/dist/src/brain/preferences.js.map +1 -0
- package/dist/src/branding.d.ts +9 -0
- package/dist/src/branding.js +25 -0
- package/dist/src/branding.js.map +1 -1
- package/dist/src/chat.d.ts +2 -2
- package/dist/src/chat.js +9 -3
- package/dist/src/chat.js.map +1 -1
- package/dist/src/integrations/mcp-config.d.ts +27 -0
- package/dist/src/integrations/mcp-config.js +120 -0
- package/dist/src/integrations/mcp-config.js.map +1 -0
- package/dist/src/panel/server.js +8 -10
- package/dist/src/panel/server.js.map +1 -1
- package/dist/src/router/decision-model.d.ts +23 -4
- package/dist/src/router/decision-model.js +87 -10
- package/dist/src/router/decision-model.js.map +1 -1
- package/dist/src/router/llm-judge.d.ts +13 -0
- package/dist/src/router/llm-judge.js +38 -0
- package/dist/src/router/llm-judge.js.map +1 -0
- package/dist/src/session/help.js +3 -2
- package/dist/src/session/help.js.map +1 -1
- package/dist/src/session/modes.js +2 -2
- package/dist/src/session/modes.js.map +1 -1
- package/dist/src/session/skill-invoke.d.ts +21 -4
- package/dist/src/session/skill-invoke.js +83 -16
- package/dist/src/session/skill-invoke.js.map +1 -1
- package/dist/src/skills/skill-pick.d.ts +25 -0
- package/dist/src/skills/skill-pick.js +83 -0
- package/dist/src/skills/skill-pick.js.map +1 -0
- package/dist/src/skills/user-skills.d.ts +52 -3
- package/dist/src/skills/user-skills.js +96 -23
- package/dist/src/skills/user-skills.js.map +1 -1
- package/dist/src/style/cli-ui.js +3 -2
- package/dist/src/style/cli-ui.js.map +1 -1
- package/dist/src/tui/biosignal-wizard.js +1 -1
- package/dist/src/tui/biosignal-wizard.js.map +1 -1
- package/package.json +4 -4
- package/scripts/psyclaw.mjs +5 -0
- package/scripts/rebrand-pi.mjs +62 -3
- 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 {
|
|
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 {
|
|
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 {
|
|
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,
|
|
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,
|
|
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,
|
|
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"
|
|
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:
|
|
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
|
|
530
|
+
async function mcpManagerRows(root, state) {
|
|
530
531
|
const { items, installPrep } = await recommendedItems("mcp");
|
|
531
|
-
|
|
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
|
|
556
|
-
//
|
|
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
|
-
|
|
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
|
|
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 =
|
|
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
|
|
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)
|
|
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)
|
|
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
|
-
`
|
|
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
|
-
"用户已通过 /
|
|
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
|
|
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)
|
|
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
|
|
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
|
|
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
|
-
"请在交互式终端运行 /
|
|
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
|
|
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,49 @@ export default function psyclawExtension(pi) {
|
|
|
1207
1208
|
},
|
|
1208
1209
|
});
|
|
1209
1210
|
}
|
|
1210
|
-
|
|
1211
|
-
//
|
|
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
|
+
const note = (by, value, usage) => {
|
|
1220
|
+
if (!cwd || !existsSync(join(cwd, ".psyclaw")))
|
|
1221
|
+
return;
|
|
1222
|
+
try {
|
|
1223
|
+
appendFileSync(join(cwd, ".psyclaw", "judge.jsonl"), `${JSON.stringify({ at: new Date().toISOString(), purpose, by, value: value ?? null, ms: Date.now() - started, ...(usage ? { usage } : {}) })}\n`);
|
|
1224
|
+
}
|
|
1225
|
+
catch { /* the log is best effort */ }
|
|
1226
|
+
};
|
|
1227
|
+
const quick = decider.enabled ? await decider.decide(purpose, state, a, b) : undefined;
|
|
1228
|
+
if (quick !== undefined) {
|
|
1229
|
+
note("startlux", quick);
|
|
1230
|
+
return quick;
|
|
1231
|
+
}
|
|
1232
|
+
const registryApi = ctx.modelRegistry;
|
|
1233
|
+
const model = ctx.model;
|
|
1234
|
+
if (!model || typeof registryApi?.complete !== "function") {
|
|
1235
|
+
note("none", undefined);
|
|
1236
|
+
return undefined;
|
|
1237
|
+
}
|
|
1238
|
+
try {
|
|
1239
|
+
const prompt = judgePrompt(a, state);
|
|
1240
|
+
const reply = await Promise.race([
|
|
1241
|
+
registryApi.complete(model, { systemPrompt: prompt.system, messages: [{ role: "user", content: prompt.user, timestamp: Date.now() }] }, { maxTokens: 300 }),
|
|
1242
|
+
new Promise((resolve) => setTimeout(() => resolve(undefined), 30_000)),
|
|
1243
|
+
]);
|
|
1244
|
+
const text = (reply?.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
|
|
1245
|
+
const value = parseJudge(text, a);
|
|
1246
|
+
note("model", value, reply?.usage);
|
|
1247
|
+
return value;
|
|
1248
|
+
}
|
|
1249
|
+
catch {
|
|
1250
|
+
note("none", undefined);
|
|
1251
|
+
return undefined;
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1213
1254
|
// --- analysis (estimand) mode ------------------------------------------------------------
|
|
1214
1255
|
const userTexts = (ctx) => {
|
|
1215
1256
|
try {
|
|
@@ -1273,12 +1314,95 @@ export default function psyclawExtension(pi) {
|
|
|
1273
1314
|
return undefined;
|
|
1274
1315
|
};
|
|
1275
1316
|
setSkillPathResolver((name) => skillRegistry.find((skill) => skill.name === name)?.location ?? bundledSkillFile(name));
|
|
1317
|
+
// --- brain (src/brain): knowledge pages and the researcher's confirmed preferences ------------------
|
|
1318
|
+
const userBrainDir = () => join(homedir(), ".psyclaw", "brain");
|
|
1319
|
+
const STAGE_AREAS = { writing: ["writing", "figures", "reporting"], analysis: ["reporting", "figures"] };
|
|
1320
|
+
/**
|
|
1321
|
+
* What the model gets from the brain each turn (small, stable within a stage): the confirmed preferences
|
|
1322
|
+
* in full (they are short and always apply), and the index of the areas this stage uses; pages load with
|
|
1323
|
+
* psyclaw_brain read.
|
|
1324
|
+
*/
|
|
1325
|
+
const brainPromptBlock = async (cwd, stage) => {
|
|
1326
|
+
const pages = await loadBrain(cwd);
|
|
1327
|
+
if (!pages.length)
|
|
1328
|
+
return "";
|
|
1329
|
+
const prefs = pages.filter((p) => p.status === "confirmed" && areaOf(p.id) === "preferences");
|
|
1330
|
+
const prefText = prefs.map((p) => `- ${p.body.replace(/\s+/g, " ").slice(0, 300)}`).join("\n").slice(0, 1_800);
|
|
1331
|
+
const areas = STAGE_AREAS[stage ?? ""] ?? ["writing", "figures", "reporting"];
|
|
1332
|
+
// The full index (one line with a gist per page) when it fits; else page names per area; never cut mid-list.
|
|
1333
|
+
const full = brainIndex(pages, { areas });
|
|
1334
|
+
const index = full.length <= 2_500 ? full : brainIndex(pages, { areas, titlesOnly: true });
|
|
1335
|
+
if (!prefText && !index)
|
|
1336
|
+
return "";
|
|
1337
|
+
return [
|
|
1338
|
+
"## Brain (what PsyClaw has learned)",
|
|
1339
|
+
...(prefText ? ["The researcher's confirmed preferences (follow them unless they say otherwise now):", prefText] : []),
|
|
1340
|
+
...(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] : []),
|
|
1341
|
+
].join("\n");
|
|
1342
|
+
};
|
|
1343
|
+
let prefNoticeShown = false;
|
|
1344
|
+
// The model sees the user's own skills that were picked for the task (background pick) or chosen by the
|
|
1345
|
+
// researcher; recommended skills they enabled always show. skillRegistry keeps every skill so a named or
|
|
1346
|
+
// searched one can still be loaded.
|
|
1347
|
+
let skillState;
|
|
1348
|
+
const recommendedLocation = (location) => /[\\/]\.psyclaw[\\/]imports[\\/]recommended[\\/]/.test(location) || location.startsWith(join(getAgentDir(), "skills"));
|
|
1349
|
+
const visibleLocal = (skill) => recommendedLocation(skill.location) || (skillState ? localSkillOn(skillState, skill.name) : false);
|
|
1276
1350
|
const registry = (prompt) => {
|
|
1277
|
-
const listed = registrySkillListing(prompt);
|
|
1351
|
+
const listed = registrySkillListing(prompt, visibleLocal);
|
|
1278
1352
|
if (listed.skills.length)
|
|
1279
1353
|
skillRegistry = listed.skills;
|
|
1280
1354
|
return listed.systemPrompt;
|
|
1281
1355
|
};
|
|
1356
|
+
let pickedThisSession = false;
|
|
1357
|
+
/**
|
|
1358
|
+
* Background skill pick (skill-pick.ts): the decision model when it runs, else one side call with the
|
|
1359
|
+
* session's model, else word overlap. Recorded in .psyclaw/user-skills.json (auto) and logged with its
|
|
1360
|
+
* usage in .psyclaw/skill-pick.jsonl. Never used once the researcher has chosen their skills.
|
|
1361
|
+
*/
|
|
1362
|
+
const pickSkillsFor = async (ctx, task) => {
|
|
1363
|
+
const union = (await scanLocalSkills(ctx.cwd, { includeManaged: false })).filter((skill) => !CORE_SKILLS.has(skill.name));
|
|
1364
|
+
if (union.length === 0)
|
|
1365
|
+
return undefined;
|
|
1366
|
+
const rows = union.map((skill) => ({ name: skill.name, description: skill.description }));
|
|
1367
|
+
const names = rows.map((row) => row.name);
|
|
1368
|
+
let picked;
|
|
1369
|
+
let usage;
|
|
1370
|
+
if (decider.enabled) {
|
|
1371
|
+
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)}?` }]));
|
|
1372
|
+
const answers = await decider.ask("skill-pick", { task: task.slice(0, 3000) }, questions);
|
|
1373
|
+
if (answers) {
|
|
1374
|
+
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);
|
|
1375
|
+
picked = { names: scored.slice(0, PICK_LIMIT).map((x) => x.name), by: "decider" };
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
const registryApi = ctx.modelRegistry;
|
|
1379
|
+
const model = ctx.model;
|
|
1380
|
+
if (!picked && model && typeof registryApi?.complete === "function") {
|
|
1381
|
+
try {
|
|
1382
|
+
const prompt = pickPrompt(task, rows);
|
|
1383
|
+
const reply = await Promise.race([
|
|
1384
|
+
registryApi.complete(model, { systemPrompt: prompt.system, messages: [{ role: "user", content: prompt.user, timestamp: Date.now() }] }, { maxTokens: 400 }),
|
|
1385
|
+
new Promise((resolve) => setTimeout(() => resolve(undefined), 30_000)),
|
|
1386
|
+
]);
|
|
1387
|
+
if (reply) {
|
|
1388
|
+
usage = reply.usage;
|
|
1389
|
+
const text = (reply.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
|
|
1390
|
+
if (/\[/.test(text))
|
|
1391
|
+
picked = { names: parsePick(text, names), by: "model" };
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
catch { /* fall back to words */ }
|
|
1395
|
+
}
|
|
1396
|
+
picked ??= { names: keywordPick(task, rows), by: "words" };
|
|
1397
|
+
await recordAutoPick(ctx.cwd, picked.names, picked.by, task.split("\n").find((line) => line.trim()) ?? "");
|
|
1398
|
+
try {
|
|
1399
|
+
mkdirSync(join(ctx.cwd, ".psyclaw"), { recursive: true });
|
|
1400
|
+
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`);
|
|
1401
|
+
}
|
|
1402
|
+
catch { /* the log is a convenience */ }
|
|
1403
|
+
skillState = await readUserSkillState(ctx.cwd);
|
|
1404
|
+
return picked;
|
|
1405
|
+
};
|
|
1282
1406
|
let arsModeEditor;
|
|
1283
1407
|
let arsUiContext;
|
|
1284
1408
|
let sessionMode = startingSessionMode(false);
|
|
@@ -1298,11 +1422,11 @@ export default function psyclawExtension(pi) {
|
|
|
1298
1422
|
// Tools each mode leaves out. basic: only Pi's tools, skills, MCP and the choice box. research: the
|
|
1299
1423
|
// research workflow, no estimand tool. analysis (estimand): data tools and psyclaw_spec, no research
|
|
1300
1424
|
// 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"];
|
|
1425
|
+
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
1426
|
const MODE_TOOLS = {
|
|
1303
1427
|
basic: [],
|
|
1304
1428
|
research: MANAGED_TOOLS.filter((name) => name !== "psyclaw_spec"),
|
|
1305
|
-
estimand: ["psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_spec"],
|
|
1429
|
+
estimand: ["psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_spec", "psyclaw_brain"],
|
|
1306
1430
|
};
|
|
1307
1431
|
let managedAvailable;
|
|
1308
1432
|
const syncModeTools = (mode) => {
|
|
@@ -1367,7 +1491,6 @@ export default function psyclawExtension(pi) {
|
|
|
1367
1491
|
pi.on("session_shutdown", () => {
|
|
1368
1492
|
finishAgentSpan(llmTurnSpan);
|
|
1369
1493
|
llmTurnSpan = undefined;
|
|
1370
|
-
runtimeMcps.close();
|
|
1371
1494
|
void shutdownObservability();
|
|
1372
1495
|
});
|
|
1373
1496
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
@@ -1452,10 +1575,17 @@ export default function psyclawExtension(pi) {
|
|
|
1452
1575
|
});
|
|
1453
1576
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
1454
1577
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
1578
|
+
if (ctx?.cwd)
|
|
1579
|
+
skillState = await readUserSkillState(ctx.cwd).catch(() => skillState);
|
|
1455
1580
|
const restored = restoreSessionMode(ctx?.sessionManager);
|
|
1456
1581
|
sessionMode = restored;
|
|
1457
1582
|
syncModeTools(restored);
|
|
1458
1583
|
let modeBlock = sessionModePrompt(restored, restored === "research" ? restoreStage(ctx?.sessionManager) : undefined);
|
|
1584
|
+
if (ctx?.cwd && restored !== "basic") {
|
|
1585
|
+
const block = await brainPromptBlock(ctx.cwd, restored === "estimand" ? "analysis" : restoreStage(ctx?.sessionManager)).catch(() => "");
|
|
1586
|
+
if (block)
|
|
1587
|
+
modeBlock = `${modeBlock}\n\n${block}`;
|
|
1588
|
+
}
|
|
1459
1589
|
if (restored === "research" && ctx && !ctx.hasUI)
|
|
1460
1590
|
modeBlock = `${modeBlock}\n\n${unattendedAnalysisPrompt()}`;
|
|
1461
1591
|
if (isArsPiTurn(event.systemPrompt) || isArsPiActive(ctx?.sessionManager)) {
|
|
@@ -1487,8 +1617,30 @@ export default function psyclawExtension(pi) {
|
|
|
1487
1617
|
}
|
|
1488
1618
|
catch { /* session may not be open */ }
|
|
1489
1619
|
if (ctx.hasUI) {
|
|
1620
|
+
// Only a real core-name conflict is worth a warning, one per skill name with every path it skipped.
|
|
1621
|
+
// A local copy of an enabled recommended skill is expected and stays in skill-resolution.json only.
|
|
1622
|
+
const byName = new Map();
|
|
1623
|
+
const preset = [];
|
|
1490
1624
|
for (const row of discovered.resolution.skipped.filter((item) => item.reason === "core-name")) {
|
|
1491
|
-
|
|
1625
|
+
if (row.warning) {
|
|
1626
|
+
if (!preset.includes(row.warning))
|
|
1627
|
+
preset.push(row.warning);
|
|
1628
|
+
continue;
|
|
1629
|
+
}
|
|
1630
|
+
const paths = byName.get(row.name) ?? [];
|
|
1631
|
+
if (!paths.includes(row.path))
|
|
1632
|
+
paths.push(row.path);
|
|
1633
|
+
byName.set(row.name, paths);
|
|
1634
|
+
}
|
|
1635
|
+
for (const warning of preset)
|
|
1636
|
+
ctx.ui.notify(warning, "warning");
|
|
1637
|
+
// Local skills are opt-in: until the researcher chooses, none of them loads; say so once per session.
|
|
1638
|
+
const local = await enabledLocalSkillPaths(ctx.cwd, { excludedNames: coreSkillNames() }).catch(() => undefined);
|
|
1639
|
+
if (local && !local.chosen && local.notSelected.length > 0) {
|
|
1640
|
+
ctx.ui.notify(`发现 ${local.notSelected.length} 个本地 skill(各目录同名的只算一个)。收到任务后会在后台挑出可能用到的几个,模型只看到它们的说明;其余的连说明都不载入。/skill 可以自己选,选过之后以你的为准。`, "info");
|
|
1641
|
+
}
|
|
1642
|
+
for (const [name, paths] of byName) {
|
|
1643
|
+
ctx.ui.notify(`核心 skill「${name}」不能被同名 skill 覆盖,已跳过:${paths.join("、")}。请改名后再启用。`, "warning");
|
|
1492
1644
|
}
|
|
1493
1645
|
}
|
|
1494
1646
|
}
|
|
@@ -1582,6 +1734,32 @@ export default function psyclawExtension(pi) {
|
|
|
1582
1734
|
}
|
|
1583
1735
|
const mode = arsModeEditor?.getMode() ?? restoreSessionMode(ctx.sessionManager);
|
|
1584
1736
|
const trimmed = event.text.trim();
|
|
1737
|
+
// Background skill pick on the first task message of a session, while the researcher has not chosen.
|
|
1738
|
+
if (!pickedThisSession && trimmed && !trimmed.startsWith("/") && existsSync(join(ctx.cwd, ".psyclaw"))) {
|
|
1739
|
+
pickedThisSession = true;
|
|
1740
|
+
try {
|
|
1741
|
+
const state = await readUserSkillState(ctx.cwd);
|
|
1742
|
+
if (!state.chosen) {
|
|
1743
|
+
const picked = await pickSkillsFor(ctx, event.text);
|
|
1744
|
+
if (picked && ctx.hasUI)
|
|
1745
|
+
ctx.ui.notify(picked.names.length
|
|
1746
|
+
? `已在后台为这项任务挑出 ${picked.names.length} 个 skill:${picked.names.join("、")}。模型只看到它们的名字和一句话说明,需要时再按节读;其余的连说明都不载入。/skill 可以调整。`
|
|
1747
|
+
: "后台挑选 skill:这项任务没有用得上的本地 skill,都不载入。/skill 可以手动加。", "info");
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
catch { /* the pick never blocks the message */ }
|
|
1751
|
+
}
|
|
1752
|
+
// Brain: lasting instructions in the researcher's words become candidates; nothing is learned until /brain review.
|
|
1753
|
+
if (trimmed && !trimmed.startsWith("/")) {
|
|
1754
|
+
try {
|
|
1755
|
+
const added = await captureCandidates(userBrainDir(), event.text, ctx.cwd);
|
|
1756
|
+
if (added.length && ctx.hasUI && !prefNoticeShown) {
|
|
1757
|
+
prefNoticeShown = true;
|
|
1758
|
+
ctx.ui.notify(`记下 ${added.length} 条可能是你长期偏好的话(如「${added[0].said.slice(0, 30)}」)。确认之前不会用上;/brain review 确认、改写或丢弃。`, "info");
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
catch { /* never blocks the message */ }
|
|
1762
|
+
}
|
|
1585
1763
|
// Research mode: every message of the researcher goes into the intent record word for word (intent.ts),
|
|
1586
1764
|
// before any routing, so the plan is checked against their words and a later session can read them back.
|
|
1587
1765
|
if (mode === "research" && !trimmed.startsWith("/") && existsSync(join(ctx.cwd, ".psyclaw"))) {
|
|
@@ -1615,14 +1793,12 @@ export default function psyclawExtension(pi) {
|
|
|
1615
1793
|
}
|
|
1616
1794
|
// Plan confirmations (0.34): each card settles its own choice; once every choice is settled, a plain yes
|
|
1617
1795
|
// (「可以」「批准」) or the old approval sentence approves the whole plan. No typed ritual is required.
|
|
1618
|
-
|
|
1619
|
-
|
|
1796
|
+
// The typed ritual is a command (exact text); any other reply is judged for its meaning, never by a pattern.
|
|
1797
|
+
let approves = isPlanRitualConfirm(trimmed);
|
|
1798
|
+
if (!approves && mode === "research" && trimmed.length <= 400) {
|
|
1620
1799
|
const pending = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
1621
1800
|
if (pending && ["awaiting-confirm", "ready", "reviewing", "clarifying", "drafting"].includes(pending.status)) {
|
|
1622
|
-
|
|
1623
|
-
const meaning = DecisionModel.confident(answers?.meaning);
|
|
1624
|
-
if (meaning)
|
|
1625
|
-
approves = meaning === "approve";
|
|
1801
|
+
approves = (await judge(ctx, "plan-approval", { reply: trimmed }, APPROVAL_QUESTION, APPROVAL_QUESTION_B)) === "approve";
|
|
1626
1802
|
}
|
|
1627
1803
|
}
|
|
1628
1804
|
// A reply while the restated intent waits for the researcher: confirm it or restate again.
|
|
@@ -1733,31 +1909,26 @@ export default function psyclawExtension(pi) {
|
|
|
1733
1909
|
if (mode !== "research")
|
|
1734
1910
|
return;
|
|
1735
1911
|
// Analysis first: a data-analysis request that also asks for figures or a write-up is still an
|
|
1736
|
-
// analysis
|
|
1737
|
-
// The decision model
|
|
1912
|
+
// analysis.
|
|
1913
|
+
// The meaning is judged (decision model in two wordings, else a large-model side call), never by a pattern.
|
|
1738
1914
|
let routed;
|
|
1739
|
-
if (
|
|
1740
|
-
const
|
|
1741
|
-
const route =
|
|
1742
|
-
if (route) {
|
|
1743
|
-
const skill =
|
|
1744
|
-
routed = { route, ...(skill ? { skill } : {}) };
|
|
1915
|
+
if (!/^\//.test(trimmed)) {
|
|
1916
|
+
const message = { message: trimmed.slice(0, 6_000) };
|
|
1917
|
+
const route = await judge(ctx, "route", message, ROUTE_QUESTION, ROUTE_QUESTION_B);
|
|
1918
|
+
if (typeof route === "string") {
|
|
1919
|
+
const skill = route === "writing" ? await judge(ctx, "writing-skill", message, WRITING_SKILL_QUESTION, WRITING_SKILL_QUESTION_B) : undefined;
|
|
1920
|
+
routed = { route, ...(typeof skill === "string" ? { skill: skill } : {}) };
|
|
1745
1921
|
}
|
|
1746
1922
|
}
|
|
1747
|
-
const wantsStats = routed
|
|
1748
|
-
const wantsAcademic = routed
|
|
1923
|
+
const wantsStats = routed?.route === "analysis";
|
|
1924
|
+
const wantsAcademic = routed?.route === "writing";
|
|
1749
1925
|
if (mode === "research" && (wantsStats || wantsAcademic))
|
|
1750
1926
|
setStage(ctx.sessionManager, wantsStats ? "analysis" : "writing");
|
|
1751
1927
|
// No research question yet: start with academic-grill (brainstorm questions from the data, or grill
|
|
1752
1928
|
// a rough idea) before any plan or writing.
|
|
1753
1929
|
if (mode === "research" && trimmed.length <= 2_000) {
|
|
1754
|
-
|
|
1755
|
-
|
|
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
|
-
}
|
|
1930
|
+
const noQuestion = (wantsStats || wantsAcademic)
|
|
1931
|
+
&& (await judge(ctx, "has-question", { message: trimmed }, HAS_QUESTION_QUESTION, HAS_QUESTION_QUESTION_B)) === false;
|
|
1761
1932
|
if (noQuestion) {
|
|
1762
1933
|
return {
|
|
1763
1934
|
action: "transform",
|
|
@@ -1801,7 +1972,7 @@ export default function psyclawExtension(pi) {
|
|
|
1801
1972
|
if (wantsAcademic) {
|
|
1802
1973
|
const match = routed?.skill
|
|
1803
1974
|
? { skill: routed.skill, reason: "decision model", priority: 0 }
|
|
1804
|
-
:
|
|
1975
|
+
: routed ? { skill: "academic-paper", reason: "decision model (writing)", priority: 0 } : null;
|
|
1805
1976
|
if (!match)
|
|
1806
1977
|
return;
|
|
1807
1978
|
const ranked = rankAcademicSoftRoutes(event.text, 3);
|
|
@@ -1813,9 +1984,7 @@ export default function psyclawExtension(pi) {
|
|
|
1813
1984
|
{
|
|
1814
1985
|
const userSkills = await userSkillsOutsideScriptOnly(ctx.cwd).catch(() => []);
|
|
1815
1986
|
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 });
|
|
1987
|
+
const match = routed?.route === "analysis" ? { kind: "stats-analysis", reason: "decision model", topics: methodTopicsIn(event.text) } : null;
|
|
1819
1988
|
const namesUserSkill = mentionsLoadedSkill(event.text, userSkillNames);
|
|
1820
1989
|
// The task often lives in a document the message names ("Read BRIEF.md"), not in the message itself.
|
|
1821
1990
|
const documents = namesUserSkill
|
|
@@ -2539,11 +2708,35 @@ export default function psyclawExtension(pi) {
|
|
|
2539
2708
|
});
|
|
2540
2709
|
if (!legacyTestApi)
|
|
2541
2710
|
pi.registerCommand("skill", {
|
|
2542
|
-
description: "
|
|
2711
|
+
description: "Skill 管理页(勾选要加载的 skill);/skill pick <研究方向> 由模型挑选;/skill preference [reset] 方法主题的 skill 选择",
|
|
2543
2712
|
handler: async (args, ctx) => {
|
|
2544
2713
|
const [sub = "", ...rest] = args.trim().split(/\s+/);
|
|
2545
2714
|
if (sub === "preference")
|
|
2546
2715
|
return skillPreferenceHandler(rest.join(" "), ctx);
|
|
2716
|
+
if (sub === "pick") {
|
|
2717
|
+
try {
|
|
2718
|
+
let intent = rest.join(" ").trim();
|
|
2719
|
+
if (!intent && ctx.hasUI && typeof ctx.ui.input === "function")
|
|
2720
|
+
intent = ((await ctx.ui.input("你主要做什么研究?(例如:问卷调查的中介分析;EEG 的 ERP 分析)")) ?? "").trim();
|
|
2721
|
+
if (!intent) {
|
|
2722
|
+
ctx.ui.notify("用法:/skill pick 你的研究方向,例如 /skill pick 问卷调查的中介分析", "info");
|
|
2723
|
+
return;
|
|
2724
|
+
}
|
|
2725
|
+
const state = await readUserSkillState(ctx.cwd);
|
|
2726
|
+
if (state.chosen) {
|
|
2727
|
+
ctx.ui.notify("你已经在 /skill 里自己选过 skill,后台挑选不会覆盖它;要改请直接在 /skill 里勾选。", "info");
|
|
2728
|
+
return;
|
|
2729
|
+
}
|
|
2730
|
+
const picked = await pickSkillsFor(ctx, intent);
|
|
2731
|
+
ctx.ui.notify(!picked ? "没有找到本地 skill。" : picked.names.length
|
|
2732
|
+
? `按「${intent}」挑出 ${picked.names.length} 个 skill:${picked.names.join("、")}。模型只看到它们的名字和一句话说明,需要时再按节读;其余的连说明都不载入。`
|
|
2733
|
+
: `按「${intent}」没有挑出用得上的本地 skill。`, "info");
|
|
2734
|
+
}
|
|
2735
|
+
catch (error) {
|
|
2736
|
+
await notifyError(ctx, error);
|
|
2737
|
+
}
|
|
2738
|
+
return;
|
|
2739
|
+
}
|
|
2547
2740
|
try {
|
|
2548
2741
|
await showSkillManager(pi, ctx);
|
|
2549
2742
|
}
|
|
@@ -2654,21 +2847,83 @@ export default function psyclawExtension(pi) {
|
|
|
2654
2847
|
}
|
|
2655
2848
|
},
|
|
2656
2849
|
});
|
|
2850
|
+
// /mcp belongs to Pi's built-in MCP (connections, sign-in, exposure, enable/disable). PsyClaw keeps
|
|
2851
|
+
// its recommended-MCP catalog and the biosignal pack under their own names.
|
|
2657
2852
|
if (!legacyTestApi)
|
|
2658
|
-
pi.registerCommand("
|
|
2659
|
-
description: "
|
|
2853
|
+
pi.registerCommand("brain", {
|
|
2854
|
+
description: "PsyClaw 的记忆:/brain 看概况;/brain review 确认学到的偏好;/brain check 检查链接",
|
|
2660
2855
|
handler: async (args, ctx) => {
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2856
|
+
try {
|
|
2857
|
+
const sub = args.trim().split(/\s+/)[0] ?? "";
|
|
2858
|
+
const pages = await loadBrain(ctx.cwd);
|
|
2859
|
+
if (sub === "review") {
|
|
2860
|
+
const pending = (await readCandidates(userBrainDir())).filter((c) => c.state === "new");
|
|
2861
|
+
if (!pending.length) {
|
|
2862
|
+
ctx.ui.notify("没有待确认的偏好。", "info");
|
|
2863
|
+
return;
|
|
2864
|
+
}
|
|
2865
|
+
let kept = 0;
|
|
2866
|
+
for (const c of pending) {
|
|
2867
|
+
if (!ctx.hasUI || typeof ctx.ui.select !== "function")
|
|
2868
|
+
break;
|
|
2869
|
+
const choice = await ctx.ui.select(`这句话是你的长期偏好吗?\n「${c.said}」\n(${c.at.slice(0, 10)},${c.area})`, ["记住(用原话)", "改写后记住", "丢弃", "先跳过"]);
|
|
2870
|
+
if (!choice || choice === "先跳过")
|
|
2871
|
+
continue;
|
|
2872
|
+
if (choice === "丢弃") {
|
|
2873
|
+
await markCandidate(userBrainDir(), c.id, "discarded");
|
|
2874
|
+
continue;
|
|
2875
|
+
}
|
|
2876
|
+
let text = c.said;
|
|
2877
|
+
if (choice === "改写后记住" && typeof ctx.ui.input === "function")
|
|
2878
|
+
text = ((await ctx.ui.input("用一句话写下这条偏好", c.said)) ?? c.said).trim() || c.said;
|
|
2879
|
+
await writePage(userBrainDir(), {
|
|
2880
|
+
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"],
|
|
2881
|
+
sources: [{ said: c.said, at: c.at }], status: "confirmed", updated_at: new Date().toISOString().slice(0, 10), body: text,
|
|
2882
|
+
}, `confirmed preference (from「${c.said.slice(0, 40)}」)`);
|
|
2883
|
+
await markCandidate(userBrainDir(), c.id, "confirmed");
|
|
2884
|
+
kept += 1;
|
|
2885
|
+
}
|
|
2886
|
+
ctx.ui.notify(`记住了 ${kept} 条偏好;之后每次都会带上。改或删:编辑 ~/.psyclaw/brain/preferences/ 里的页面。`, "info");
|
|
2887
|
+
return;
|
|
2664
2888
|
}
|
|
2665
|
-
|
|
2666
|
-
|
|
2889
|
+
if (sub === "check") {
|
|
2890
|
+
const { broken, backlinks } = checkLinks(pages);
|
|
2891
|
+
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");
|
|
2892
|
+
return;
|
|
2667
2893
|
}
|
|
2668
|
-
|
|
2894
|
+
const byArea = new Map();
|
|
2895
|
+
for (const p of pages)
|
|
2896
|
+
byArea.set(areaOf(p.id), (byArea.get(areaOf(p.id)) ?? 0) + 1);
|
|
2897
|
+
const pending = (await readCandidates(userBrainDir())).filter((c) => c.state === "new").length;
|
|
2898
|
+
ctx.ui.notify([
|
|
2899
|
+
`PsyClaw 的记忆:${pages.length} 页(${[...byArea].map(([a, n]) => `${a} ${n}`).join(",") || "空"})。`,
|
|
2900
|
+
`待你确认的偏好:${pending} 条${pending ? "(/brain review)" : ""}。`,
|
|
2901
|
+
"位置:内置知识随 PsyClaw 发布;你的在 ~/.psyclaw/brain;本项目的在 .psyclaw/brain(同名页以项目为准)。",
|
|
2902
|
+
].join("\n"), "info");
|
|
2903
|
+
}
|
|
2904
|
+
catch (error) {
|
|
2905
|
+
await notifyError(ctx, error);
|
|
2669
2906
|
}
|
|
2907
|
+
},
|
|
2908
|
+
});
|
|
2909
|
+
if (!legacyTestApi)
|
|
2910
|
+
pi.registerCommand("mcp-recommended", {
|
|
2911
|
+
description: "推荐 MCP 目录:查看、安装、启用(连接和登录用 /mcp)",
|
|
2912
|
+
handler: async (_args, ctx) => {
|
|
2913
|
+
try {
|
|
2914
|
+
await showMcpManager(pi, ctx);
|
|
2915
|
+
}
|
|
2916
|
+
catch (error) {
|
|
2917
|
+
await notifyError(ctx, error);
|
|
2918
|
+
}
|
|
2919
|
+
},
|
|
2920
|
+
});
|
|
2921
|
+
if (!legacyTestApi)
|
|
2922
|
+
pi.registerCommand("biosignal", {
|
|
2923
|
+
description: "生理信号分析能力包(EEG/MEG/fNIRS 的 MCP 与 Skill)",
|
|
2924
|
+
handler: async (_args, ctx) => {
|
|
2670
2925
|
try {
|
|
2671
|
-
await
|
|
2926
|
+
await showBiosignalPack(pi, ctx);
|
|
2672
2927
|
}
|
|
2673
2928
|
catch (error) {
|
|
2674
2929
|
await notifyError(ctx, error);
|
|
@@ -2858,50 +3113,6 @@ export default function psyclawExtension(pi) {
|
|
|
2858
3113
|
});
|
|
2859
3114
|
if (typeof pi.registerTool === "function") {
|
|
2860
3115
|
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
3116
|
pi.registerTool({
|
|
2906
3117
|
name: "psyclaw_ars_multi_agent",
|
|
2907
3118
|
label: "ARS multi-agent review bridge",
|
|
@@ -3014,19 +3225,39 @@ export default function psyclawExtension(pi) {
|
|
|
3014
3225
|
label: "Skill",
|
|
3015
3226
|
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
3227
|
parameters: Type.Object({
|
|
3017
|
-
action: Type.Optional(Type.Union([Type.Literal("load"), Type.Literal("find")])),
|
|
3228
|
+
action: Type.Optional(Type.Union([Type.Literal("load"), Type.Literal("find"), Type.Literal("choose")])),
|
|
3018
3229
|
name: Type.Optional(Type.String({ description: "Skill name from available_skills (action=load)" })),
|
|
3230
|
+
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" })),
|
|
3231
|
+
intent: Type.Optional(Type.String({ description: "action=choose: what the researcher said they work on, in their words" })),
|
|
3019
3232
|
query: Type.Optional(Type.String({ description: "A few words about the task (action=find)" })),
|
|
3020
|
-
section: Type.Optional(Type.String({ description: "Load
|
|
3233
|
+
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
3234
|
purpose: Type.Optional(Type.String({ description: "Short user-facing reason for using this skill now" })),
|
|
3022
3235
|
}),
|
|
3023
3236
|
executionMode: "sequential",
|
|
3024
|
-
async execute(_toolCallId, params) {
|
|
3237
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
3238
|
+
if (params.action === "choose") {
|
|
3239
|
+
// The researcher described their work (/skill pick); record the local skills that fit as the selection.
|
|
3240
|
+
const union = await scanLocalSkills(ctx.cwd, { includeManaged: false });
|
|
3241
|
+
const known = new Map(union.map((skill) => [skill.name.toLocaleLowerCase(), skill.name]));
|
|
3242
|
+
const names = (params.names ?? []).map((n) => known.get(n.trim().toLocaleLowerCase())).filter((n) => !!n);
|
|
3243
|
+
const unknown = (params.names ?? []).filter((n) => !known.has(n.trim().toLocaleLowerCase()));
|
|
3244
|
+
if (unknown.length)
|
|
3245
|
+
return { content: [{ type: "text", text: `Not local skills: ${unknown.join(", ")}. Use exact names from the list.` }], details: { status: "failed", name: "" }, isError: true };
|
|
3246
|
+
await chooseLocalSkills(ctx.cwd, names, "auto", params.intent);
|
|
3247
|
+
return {
|
|
3248
|
+
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.` }],
|
|
3249
|
+
details: { status: "chosen", name: names.join(",") },
|
|
3250
|
+
};
|
|
3251
|
+
}
|
|
3025
3252
|
if (params.action === "find" || (!params.name && params.query)) {
|
|
3026
|
-
|
|
3253
|
+
// Skills in the model's list first; only when none fits, the ones not picked for this task.
|
|
3254
|
+
const query = params.query ?? params.name ?? "";
|
|
3255
|
+
const listedHits = findSkills(skillRegistry.filter((skill) => skill.group !== "Yours" || visibleLocal(skill)), query);
|
|
3256
|
+
const hits = listedHits.length ? listedHits : findSkills(skillRegistry, query);
|
|
3257
|
+
const hidden = !listedHits.length && hits.length > 0;
|
|
3027
3258
|
const text = hits.length
|
|
3028
|
-
? hits.map((skill) => `- ${skill.name} (${skill.group}): ${firstSentence(skill.description, 220)}`).join("\n")
|
|
3029
|
-
: "No
|
|
3259
|
+
? `${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")}`
|
|
3260
|
+
: "No skill matches those words. Try other words, or work without a skill.";
|
|
3030
3261
|
return { content: [{ type: "text", text }], details: { status: "found", name: hits.map((skill) => skill.name).join(",") } };
|
|
3031
3262
|
}
|
|
3032
3263
|
const name = (params.name ?? "").trim();
|
|
@@ -3039,13 +3270,21 @@ export default function psyclawExtension(pi) {
|
|
|
3039
3270
|
};
|
|
3040
3271
|
}
|
|
3041
3272
|
try {
|
|
3042
|
-
if (params.section) {
|
|
3273
|
+
if (params.section && params.section.trim().toLowerCase() !== "all") {
|
|
3043
3274
|
const text = readSkillSection(path, params.section);
|
|
3044
3275
|
return {
|
|
3045
3276
|
content: [{ type: "text", text: text ?? `No section starting with "${params.section}" in ${name}.` }],
|
|
3046
3277
|
details: { status: text ? "active" : "failed", name },
|
|
3047
3278
|
};
|
|
3048
3279
|
}
|
|
3280
|
+
// Stage 3: a large skill comes as its index first; its sections load one at a time (section="all": whole).
|
|
3281
|
+
const index = params.section?.trim().toLowerCase() === "all" ? undefined : skillIndexBlock(name, path);
|
|
3282
|
+
if (index) {
|
|
3283
|
+
return {
|
|
3284
|
+
content: [{ type: "text", text: `正在使用 Skill:${name}${params.purpose ? `(${params.purpose})` : ""}\nSkill directory (resolve relative paths against it): ${dirname(path)}\n\n${index}` }],
|
|
3285
|
+
details: { status: "active", name, ...(params.purpose === undefined ? {} : { purpose: params.purpose }) },
|
|
3286
|
+
};
|
|
3287
|
+
}
|
|
3049
3288
|
const instructions = await readFile(path, "utf8");
|
|
3050
3289
|
return {
|
|
3051
3290
|
content: [{ type: "text", text: `正在使用 Skill:${name}${params.purpose ? `(${params.purpose})` : ""}\nSkill directory (resolve relative paths against it): ${dirname(path)}\n\n${instructions}` }],
|
|
@@ -3347,6 +3586,51 @@ export default function psyclawExtension(pi) {
|
|
|
3347
3586
|
}
|
|
3348
3587
|
},
|
|
3349
3588
|
});
|
|
3589
|
+
pi.registerTool({
|
|
3590
|
+
name: "psyclaw_brain",
|
|
3591
|
+
label: "记忆",
|
|
3592
|
+
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).",
|
|
3593
|
+
parameters: Type.Object({
|
|
3594
|
+
action: Type.Union([Type.Literal("index"), Type.Literal("read"), Type.Literal("search"), Type.Literal("remember")]),
|
|
3595
|
+
area: Type.Optional(Type.String()),
|
|
3596
|
+
id: Type.Optional(Type.String()),
|
|
3597
|
+
query: Type.Optional(Type.String()),
|
|
3598
|
+
quote: Type.Optional(Type.String({ description: "remember: the researcher's words, unchanged" })),
|
|
3599
|
+
}),
|
|
3600
|
+
executionMode: "sequential",
|
|
3601
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
3602
|
+
try {
|
|
3603
|
+
const pages = await loadBrain(ctx.cwd);
|
|
3604
|
+
if (params.action === "index") {
|
|
3605
|
+
const text = brainIndex(pages, params.area ? { areas: [params.area] } : {});
|
|
3606
|
+
return { content: [{ type: "text", text: text || "No pages yet." }], details: { pages: pages.length } };
|
|
3607
|
+
}
|
|
3608
|
+
if (params.action === "read") {
|
|
3609
|
+
const page = pages.find((p) => p.id === (params.id ?? "").trim().replace(/^\[\[|\]\]$/g, ""));
|
|
3610
|
+
if (!page)
|
|
3611
|
+
return { content: [{ type: "text", text: `No page ${params.id}. Use action=index or action=search.` }], details: { status: "missing" }, isError: true };
|
|
3612
|
+
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("; ");
|
|
3613
|
+
return { content: [{ type: "text", text: `# ${page.title} [[${page.id}]]\n${sources ? `Source: ${sources}\n` : ""}\n${page.body}` }], details: { id: page.id, layer: page.layer } };
|
|
3614
|
+
}
|
|
3615
|
+
if (params.action === "search") {
|
|
3616
|
+
const hits = searchBrain(pages, params.query ?? "");
|
|
3617
|
+
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) } };
|
|
3618
|
+
}
|
|
3619
|
+
const quote = params.quote?.trim();
|
|
3620
|
+
if (!quote)
|
|
3621
|
+
throw new Error("remember needs quote: the researcher's words, unchanged");
|
|
3622
|
+
const said = userTexts(ctx);
|
|
3623
|
+
if (!said.includes(quote))
|
|
3624
|
+
throw new Error("the quote is not in the researcher's messages; quote them word for word");
|
|
3625
|
+
const added = await captureCandidates(userBrainDir(), quote, ctx.cwd);
|
|
3626
|
+
const already = !added.length && (await readCandidates(userBrainDir())).some((c) => c.id === candidateId(quote));
|
|
3627
|
+
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 } };
|
|
3628
|
+
}
|
|
3629
|
+
catch (error) {
|
|
3630
|
+
return { content: [{ type: "text", text: `记忆操作失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
|
|
3631
|
+
}
|
|
3632
|
+
},
|
|
3633
|
+
});
|
|
3350
3634
|
pi.registerTool({
|
|
3351
3635
|
name: "psyclaw_intent",
|
|
3352
3636
|
label: "研究意图",
|
|
@@ -3547,15 +3831,14 @@ export default function psyclawExtension(pi) {
|
|
|
3547
3831
|
// The decision model may promote a convention to the researcher (never the reverse).
|
|
3548
3832
|
const submitted = (params.decisions ?? []);
|
|
3549
3833
|
const promote = new Set();
|
|
3550
|
-
|
|
3551
|
-
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
}
|
|
3834
|
+
// All analyst decisions are judged at once (side calls run in parallel, so a plan waits for one, not ten).
|
|
3835
|
+
await Promise.all(submitted.map(async (p, i) => {
|
|
3836
|
+
if (p.by !== "analyst" || !p.reason?.trim())
|
|
3837
|
+
return;
|
|
3838
|
+
const state = { question: p.question, choice: p.options?.[(p.recommended ?? 1) - 1] ?? "", reason: p.reason };
|
|
3839
|
+
if ((await judge(ctx, "ask-researcher", state, ASK_RESEARCHER_QUESTION, ASK_RESEARCHER_QUESTION_B)) === true)
|
|
3840
|
+
promote.add(i);
|
|
3841
|
+
}));
|
|
3559
3842
|
const numbered = numberPoints(plan.id, submitted, promote);
|
|
3560
3843
|
// Quotes are checked against their source. by brief: the materials or a message (briefs are often pasted);
|
|
3561
3844
|
// by researcher: their messages or their answers on cards (which live in the decision record).
|
|
@@ -3709,9 +3992,8 @@ export default function psyclawExtension(pi) {
|
|
|
3709
3992
|
// Only ever escalates: a decision the analyst settled that the model judges intent-dependent
|
|
3710
3993
|
// gets a note to ask the researcher. It never cancels a question.
|
|
3711
3994
|
let escalate = "";
|
|
3712
|
-
if (params.by === "analyst"
|
|
3713
|
-
|
|
3714
|
-
if (DecisionModel.yesNo(answers?.intent) === true) {
|
|
3995
|
+
if (params.by === "analyst") {
|
|
3996
|
+
if ((await judge(ctx, "ask-researcher", { question: event.question, choice: event.choice, reason: params.reason ?? "" }, ASK_RESEARCHER_QUESTION, ASK_RESEARCHER_QUESTION_B)) === true) {
|
|
3715
3997
|
escalate = `\n[psyclaw] 这一项看起来取决于研究者的意图,不是惯例:请用 psyclaw_ask 问研究者(id ${event.id}),给出你的推荐。`;
|
|
3716
3998
|
}
|
|
3717
3999
|
}
|