psyclaw 0.33.1 → 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/apps/panel/index.html +16 -16
- package/dist/src/adapters/pi/arg-repair.d.ts +27 -0
- package/dist/src/adapters/pi/arg-repair.js +177 -0
- package/dist/src/adapters/pi/arg-repair.js.map +1 -0
- package/dist/src/adapters/pi/extension.js +1845 -606
- package/dist/src/adapters/pi/extension.js.map +1 -1
- package/dist/src/adapters/pi/observation-mask.d.ts +19 -0
- package/dist/src/adapters/pi/observation-mask.js +107 -2
- package/dist/src/adapters/pi/observation-mask.js.map +1 -1
- package/dist/src/adapters/pi/session.js +1 -1
- package/dist/src/adapters/pi/session.js.map +1 -1
- package/dist/src/analysis/decision-points.d.ts +4 -9
- package/dist/src/analysis/decision-points.js +20 -74
- package/dist/src/analysis/decision-points.js.map +1 -1
- package/dist/src/analysis/estimand.d.ts +127 -0
- package/dist/src/analysis/estimand.js +526 -0
- package/dist/src/analysis/estimand.js.map +1 -0
- package/dist/src/analysis/method-rules.d.ts +6 -0
- package/dist/src/analysis/method-rules.js +20 -3
- package/dist/src/analysis/method-rules.js.map +1 -1
- package/dist/src/analysis/package-net.d.ts +106 -0
- package/dist/src/analysis/package-net.js +277 -0
- package/dist/src/analysis/package-net.js.map +1 -0
- package/dist/src/analysis/plan.d.ts +6 -2
- package/dist/src/analysis/plan.js +34 -17
- package/dist/src/analysis/plan.js.map +1 -1
- package/dist/src/analysis/runtime-tools.d.ts +0 -6
- package/dist/src/analysis/runtime-tools.js +0 -156
- package/dist/src/analysis/runtime-tools.js.map +1 -1
- package/dist/src/analysis/shell-timeout.d.ts +21 -0
- package/dist/src/analysis/shell-timeout.js +87 -1
- package/dist/src/analysis/shell-timeout.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/analysis/stats-router.d.ts +4 -8
- package/dist/src/analysis/stats-router.js +21 -23
- package/dist/src/analysis/stats-router.js.map +1 -1
- package/dist/src/ars/academic-router.d.ts +8 -8
- package/dist/src/ars/academic-router.js +22 -35
- package/dist/src/ars/academic-router.js.map +1 -1
- package/dist/src/ars/doctor.js +1 -2
- package/dist/src/ars/doctor.js.map +1 -1
- package/dist/src/ars/mode-editor.d.ts +7 -2
- package/dist/src/ars/mode-editor.js +15 -16
- package/dist/src/ars/mode-editor.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 +19 -0
- package/dist/src/branding.js +65 -33
- package/dist/src/branding.js.map +1 -1
- package/dist/src/chat.d.ts +2 -2
- package/dist/src/chat.js +20 -4
- package/dist/src/chat.js.map +1 -1
- package/dist/src/index.d.ts +1 -2
- package/dist/src/index.js +1 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/install/installer.js +0 -5
- package/dist/src/install/installer.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/integrations/mcp-format.d.ts +6 -0
- package/dist/src/integrations/mcp-format.js +52 -0
- package/dist/src/integrations/mcp-format.js.map +1 -0
- package/dist/src/orchestration/research-agents.js +1 -1
- package/dist/src/orchestration/research-agents.js.map +1 -1
- package/dist/src/orchestration/runner.d.ts +0 -1
- package/dist/src/orchestration/runner.js +0 -3
- package/dist/src/orchestration/runner.js.map +1 -1
- package/dist/src/orchestration/scheduler.js +0 -31
- package/dist/src/orchestration/scheduler.js.map +1 -1
- package/dist/src/panel/server.js +11 -14
- package/dist/src/panel/server.js.map +1 -1
- package/dist/src/project/hitl.js +3 -3
- package/dist/src/project/hitl.js.map +1 -1
- package/dist/src/project/workspace.js +8 -20
- package/dist/src/project/workspace.js.map +1 -1
- package/dist/src/research/decisions.d.ts +115 -0
- package/dist/src/research/decisions.js +284 -0
- package/dist/src/research/decisions.js.map +1 -0
- package/dist/src/research/intent.d.ts +90 -0
- package/dist/src/research/intent.js +175 -0
- package/dist/src/research/intent.js.map +1 -0
- package/dist/src/research/plan-message.d.ts +117 -0
- package/dist/src/research/plan-message.js +187 -0
- package/dist/src/research/plan-message.js.map +1 -0
- package/dist/src/research/practice.d.ts +33 -0
- package/dist/src/research/practice.js +160 -0
- package/dist/src/research/practice.js.map +1 -0
- package/dist/src/router/decision-model.d.ts +73 -0
- package/dist/src/router/decision-model.js +206 -0
- package/dist/src/router/decision-model.js.map +1 -0
- 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/rules/user-rules.js.map +1 -1
- package/dist/src/safety/data-access.js +4 -4
- package/dist/src/safety/data-access.js.map +1 -1
- package/dist/src/safety/secret-marks.d.ts +44 -0
- package/dist/src/safety/secret-marks.js +88 -0
- package/dist/src/safety/secret-marks.js.map +1 -0
- package/dist/src/session/continuously-work.js +1 -1
- package/dist/src/session/continuously-work.js.map +1 -1
- package/dist/src/session/help.js +30 -38
- package/dist/src/session/help.js.map +1 -1
- package/dist/src/session/modes.d.ts +24 -21
- package/dist/src/session/modes.js +82 -131
- package/dist/src/session/modes.js.map +1 -1
- package/dist/src/session/skill-invoke.d.ts +71 -0
- package/dist/src/session/skill-invoke.js +244 -0
- package/dist/src/session/skill-invoke.js.map +1 -0
- package/dist/src/session/skill-reference.d.ts +15 -0
- package/dist/src/session/skill-reference.js +35 -0
- package/dist/src/session/skill-reference.js.map +1 -0
- package/dist/src/skills/recommended.js +0 -2
- package/dist/src/skills/recommended.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 +107 -23
- package/dist/src/skills/user-skills.js.map +1 -1
- package/dist/src/style/cli-ui.js +16 -13
- package/dist/src/style/cli-ui.js.map +1 -1
- package/dist/src/tui/biosignal-wizard.js +2 -2
- package/dist/src/tui/biosignal-wizard.js.map +1 -1
- package/dist/src/tui/wake-options.d.ts +2 -2
- package/dist/src/tui/wake-options.js +8 -5
- package/dist/src/tui/wake-options.js.map +1 -1
- package/dist/src/updates/check.js +4 -2
- package/dist/src/updates/check.js.map +1 -1
- package/dist/src/updates/registry.d.ts +2 -1
- package/dist/src/updates/registry.js +2 -2
- package/dist/src/updates/registry.js.map +1 -1
- package/dist/src/updates/status.d.ts +9 -2
- package/dist/src/updates/status.js +43 -6
- package/dist/src/updates/status.js.map +1 -1
- package/dist/src/updates/update.js +7 -3
- package/dist/src/updates/update.js.map +1 -1
- package/dist/src/verify/checklist.d.ts +1 -1
- package/dist/src/verify/checklist.js +5 -5
- package/dist/src/verify/checklist.js.map +1 -1
- package/dist/src/wake-options/runtime.d.ts +9 -0
- package/dist/src/wake-options/runtime.js +39 -1
- package/dist/src/wake-options/runtime.js.map +1 -1
- package/dist/src/workflows/academic-export.js.map +1 -1
- package/dist/src/workflows/meta-analysis.js +1 -1
- package/dist/src/workflows/meta-analysis.js.map +1 -1
- package/package.json +5 -4
- package/scripts/psyclaw.mjs +5 -0
- package/scripts/rebrand-pi.mjs +62 -3
- package/skills/core/academic-grill/SKILL.md +3 -3
- package/skills/core/analysis-plan/SKILL.md +64 -35
- package/skills/core/manifest.json +12 -4
- package/skills/core/package-install/SKILL.md +35 -0
- package/skills/core/package-install/pkgnet.py +178 -0
- package/skills/recommended/mcp-catalog.json +1 -1
- package/dist/src/analysis/prior/apply.d.ts +0 -15
- package/dist/src/analysis/prior/apply.js +0 -98
- package/dist/src/analysis/prior/apply.js.map +0 -1
- package/dist/src/analysis/prior/checks.d.ts +0 -21
- package/dist/src/analysis/prior/checks.js +0 -233
- package/dist/src/analysis/prior/checks.js.map +0 -1
- package/dist/src/analysis/prior/constants.d.ts +0 -33
- package/dist/src/analysis/prior/constants.js +0 -117
- package/dist/src/analysis/prior/constants.js.map +0 -1
- package/dist/src/analysis/prior/gate.d.ts +0 -14
- package/dist/src/analysis/prior/gate.js +0 -93
- package/dist/src/analysis/prior/gate.js.map +0 -1
- package/dist/src/analysis/prior/memory.d.ts +0 -8
- package/dist/src/analysis/prior/memory.js +0 -46
- package/dist/src/analysis/prior/memory.js.map +0 -1
- package/dist/src/analysis/prior/reflect.d.ts +0 -6
- package/dist/src/analysis/prior/reflect.js +0 -48
- package/dist/src/analysis/prior/reflect.js.map +0 -1
- package/dist/src/analysis/prior/render.d.ts +0 -20
- package/dist/src/analysis/prior/render.js +0 -159
- package/dist/src/analysis/prior/render.js.map +0 -1
- package/dist/src/analysis/prior/submit.d.ts +0 -32
- package/dist/src/analysis/prior/submit.js +0 -213
- package/dist/src/analysis/prior/submit.js.map +0 -1
- package/dist/src/analysis/prior/tools.d.ts +0 -6
- package/dist/src/analysis/prior/tools.js +0 -38
- package/dist/src/analysis/prior/tools.js.map +0 -1
- package/dist/src/research/choice.d.ts +0 -16
- package/dist/src/research/choice.js +0 -25
- package/dist/src/research/choice.js.map +0 -1
- package/dist/src/skills/registry.d.ts +0 -28
- package/dist/src/skills/registry.js +0 -550
- package/dist/src/skills/registry.js.map +0 -1
- package/skills/core/prior-plan/SKILL.md +0 -53
|
@@ -1,17 +1,21 @@
|
|
|
1
|
-
import { DefaultPackageManager, getAgentDir, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
1
|
+
import { createEditToolDefinition, DefaultPackageManager, getAgentDir, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { withArgRepair } from "./arg-repair.js";
|
|
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, 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
|
+
import { isInstructionResult, isObservationEvidence, maskedPlaceholderReason, maskHeavyParts, maskToolObservationsStable, observationSettledLimit } from "./observation-mask.js";
|
|
3
7
|
import { outputLogFooter, persistToolOutput } from "../../analysis/output-log.js";
|
|
4
|
-
import { applyShellTimeout, isShellTimeout,
|
|
8
|
+
import { applyShellTimeout, isShellTimeout, moveTimeoutPrefix, scriptInCommand, ShellClock } from "../../analysis/shell-timeout.js";
|
|
9
|
+
import { decisionPointsNotice } from "../../analysis/decision-points.js";
|
|
10
|
+
import { backgroundInstallMinutes, condaChannels, condaTargets, cranProfile, cranTargets, describeRoute, fastest, installTimeoutSeconds, isRInstall, PackageNet, parsePipInstall, probeSpeeds, routeCommand, routeCondaCommand, routeRCommand, shellQuote, startBackgroundInstall } from "../../analysis/package-net.js";
|
|
5
11
|
import { registerAnalysisRuntimeTools } from "../../analysis/runtime-tools.js";
|
|
6
|
-
import {
|
|
7
|
-
import { readPriorMemory } from "../../analysis/prior/memory.js";
|
|
8
|
-
import { priorApproved, priorPlanExists, priorRecallExists, recordPriorApproval } from "../../analysis/prior/submit.js";
|
|
9
|
-
import { registerPriorTools } from "../../analysis/prior/tools.js";
|
|
10
|
-
import { PSYCLAW_VERSION } from "../../branding.js";
|
|
12
|
+
import { PSYCLAW_BASIC_PROMPT, PSYCLAW_IDENTITY_PROMPT, PSYCLAW_VERSION, PSYCLAW_WRITING_RULES } from "../../branding.js";
|
|
11
13
|
import { takeWhatsNew } from "../../updates/whats-new.js";
|
|
12
14
|
import { formatDataAccess, loadDataAccess, redactScriptOnlyOutput, scriptOnlyBlock, setDataAccess } from "../../safety/data-access.js";
|
|
13
15
|
import { Type } from "typebox";
|
|
14
|
-
import {
|
|
16
|
+
import { isUserSkillFile, skillCommandName, withResearchSkillNote } from "../../session/skill-reference.js";
|
|
17
|
+
import { markScriptOnly, parseSecretMarks, secretNote } from "../../safety/secret-marks.js";
|
|
18
|
+
import { appendApproval, approvalInputDigest, bootstrapProject, ensureProjectBinding, hasCanonicalWorkspace, runInstitutionalFulltext, runLiteratureReview, runExpertReview, runAnalysisDelegation, runWritingReview, runMetaAnalysis, createStageRunner, exportAcademicDocument, recordCitationUse, runParallelPeerReview } from "../../index.js";
|
|
15
19
|
import { parseInitArgs } from "./init-args.js";
|
|
16
20
|
import { runPlanWithPi } from "../../orchestration/pi-executor.js";
|
|
17
21
|
import { formatEffects, hasElevatedEffects, normalizeEffects, toolsForEffects } from "../../orchestration/effects.js";
|
|
@@ -26,32 +30,42 @@ import { lstat, mkdir, readFile } from "node:fs/promises";
|
|
|
26
30
|
import { PROVIDER_PRESETS, providerCredentialSource, saveProviderConfig } from "../../setup.js";
|
|
27
31
|
import { dirname } from "node:path";
|
|
28
32
|
import { fileURLToPath } from "node:url";
|
|
29
|
-
import { coreSkillNames, enabledRecommendedSkillPaths, normalizeRecommendedSkillId, readRecommendationState, readRecommendedCatalog, recommendedSkillTarget, saveRecommendationState, setRecommendedSkillEnabled, validateModelInstalledRecommendedSkill, RecommendedSkillUnavailableError
|
|
33
|
+
import { coreSkillNames, enabledRecommendedSkillPaths, normalizeRecommendedSkillId, readRecommendationState, readRecommendedCatalog, recommendedSkillTarget, saveRecommendationState, setRecommendedSkillEnabled, validateModelInstalledRecommendedSkill, RecommendedSkillUnavailableError } from "../../skills/recommended.js";
|
|
30
34
|
import { buildRecommendedSkillInstallTask } from "../../skills/install-guidance.js";
|
|
31
35
|
import { SkillManagerComponent } from "../../tui/skill-manager.js";
|
|
32
36
|
import { BiosignalWizardComponent } from "../../tui/biosignal-wizard.js";
|
|
33
37
|
import { readBiosignalPackCatalog, resolveBiosignalInstallPlan, } from "../../skills/biosignal-pack.js";
|
|
34
38
|
import { WakeOptionsComponent } from "../../tui/wake-options.js";
|
|
35
|
-
import { applyWakeVerifySync, buildWakePrompt, createWakeVerifyChecklist, formatWakeResult, labelsFor, waitForPanelWakeAnswer, } from "../../wake-options/runtime.js";
|
|
39
|
+
import { applyWakeVerifySync, buildWakePrompt, createWakeVerifyChecklist, formatWakeResult, labelsFor, waitForPanelWakeAnswer, recommendedOptionIndex, } from "../../wake-options/runtime.js";
|
|
36
40
|
import { panelHub } from "../../panel/hub.js";
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
41
|
+
import { branchOf, findSkills, firstSentence, invokeSkill, readSkillSection, skillIndexBlock, registrySkillListing, setSkillPathResolver, skillLoaded } from "../../session/skill-invoke.js";
|
|
42
|
+
import { formatDecisionsBrief, openDecisions, readDecisions, recordAsked, recordDeviation, recordSettled } from "../../research/decisions.js";
|
|
43
|
+
import { askedRows, checkProblems, PRACTICE_PATH, renderPractice, rowFor } from "../../research/practice.js";
|
|
44
|
+
import { confirmIntent, INTENT_FIELDS, intentBrief, quoted, readIntent, recordSaid, renderIntent, restateIntent } from "../../research/intent.js";
|
|
45
|
+
import { isPlanPointId, numberPoints, pointLabel, renderPlanMessage, settleFromReply } from "../../research/plan-message.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";
|
|
40
51
|
import { classifyIrreversibleHostCommand, extractToolCommandText, irreversibleHostBlockReason, } from "../../safety/irreversible-host-ops.js";
|
|
41
52
|
import { SecretInputComponent, TextInputComponent, ProviderPickerComponent, } from "../../tui/provider-picker.js";
|
|
42
53
|
import { resolveProviderBaseUrl } from "../../core/provider-endpoint.js";
|
|
43
|
-
import { isArsPiActive, isArsPiTurn, psyclawArsPatch, setArsPiSessionActive
|
|
54
|
+
import { isArsPiActive, isArsPiTurn, psyclawArsPatch, setArsPiSessionActive } from "../../ars/profile.js";
|
|
44
55
|
import { buildArsDoctorReport, ensurePdfEngineForExport } from "../../ars/doctor.js";
|
|
45
|
-
import { formatAcademicSoftRouteInvocation, rankAcademicSoftRoutes,
|
|
56
|
+
import { formatAcademicSoftRouteInvocation, rankAcademicSoftRoutes, } from "../../ars/academic-router.js";
|
|
46
57
|
import { advanceAnalysisPlan, createAnalysisPlan, formatAnalysisPlanStatus, readActiveAnalysisPlan, syncHandoffFromAnalysisPlan, writeAnalysisPlan, } from "../../analysis/plan.js";
|
|
47
|
-
import { METHOD_TOPICS, mentionsLoadedSkill, methodTopicsIn } from "../../analysis/method-rules.js";
|
|
58
|
+
import { bundledCoreSkillsDir, METHOD_TOPICS, mentionsLoadedSkill, methodTopicsIn } from "../../analysis/method-rules.js";
|
|
59
|
+
import { appendFileSync, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
|
|
60
|
+
import { homedir, tmpdir } from "node:os";
|
|
61
|
+
import { validateAnalysisPlan } from "../../analysis/hooks.js";
|
|
48
62
|
import { composeMethodInjection, injectedTopicsFor, readSkillPreferences, referencedDocumentTopics, refreshSkillResolution, SKILL_RESOLUTION_ENTRY, userSkillsOutsideScriptOnly, writeSkillPreferences, } from "../../analysis/skill-resolution.js";
|
|
49
|
-
import { formatAnalysisPlanTakeover,
|
|
63
|
+
import { formatAnalysisPlanTakeover, } from "../../analysis/stats-router.js";
|
|
50
64
|
import { arsRoot } from "../../ars/pi-panel-executor.js";
|
|
51
65
|
import { ArsModeEditor, isArsModeEditorText } from "../../ars/mode-editor.js";
|
|
52
|
-
import { MODE_STATUS,
|
|
66
|
+
import { MODE_STATUS, nextSessionMode, parseSessionMode, startingSessionMode, sessionModePrompt, unattendedAnalysisPrompt, } from "../../session/modes.js";
|
|
53
67
|
import { continuouslyWorkWarningText, isContinuouslyWorkEnabled, } from "../../session/continuously-work.js";
|
|
54
|
-
import { assertHumanVerifyGate, formatVerifyChecklist,
|
|
68
|
+
import { assertHumanVerifyGate, formatVerifyChecklist, isPlanRitualConfirm, PLAN_RITUAL_PHRASE, ensureDefaultVerifyChecklist, loadVerifyChecklist, recordHumanVerification } from "../../verify/checklist.js";
|
|
55
69
|
import { formatSessionHelp, formatSessionHelpBrief } from "../../session/help.js";
|
|
56
70
|
import { openResearchWorkbench } from "../../panel/workbench.js";
|
|
57
71
|
import { captureAgentError, extractPiGeneration, finishAgentSpan, initNodeObservability, lastPiGeneration, readTelemetryPreference, shutdownObservability, startAgentSpan, trackGateWaiting, trackLlmGeneration, trackSkillInstall, withAgentSpan, writeTelemetryPreference, } from "../../observability/index.js";
|
|
@@ -110,15 +124,7 @@ async function notifyAfterSkillChange(ctx, summary, level = "info") {
|
|
|
110
124
|
return "manual-reload";
|
|
111
125
|
}
|
|
112
126
|
const activeAgentRuns = new Set();
|
|
113
|
-
const CORE_SKILLS = new Set(["academic-grill", "research-intake", "evidence-capture", "citation-audit", "analysis-plan"
|
|
114
|
-
function findLastMatching(items, predicate) {
|
|
115
|
-
for (let index = items.length - 1; index >= 0; index -= 1) {
|
|
116
|
-
const item = items[index];
|
|
117
|
-
if (item !== undefined && predicate(item))
|
|
118
|
-
return item;
|
|
119
|
-
}
|
|
120
|
-
return undefined;
|
|
121
|
-
}
|
|
127
|
+
const CORE_SKILLS = new Set(["academic-grill", "research-intake", "evidence-capture", "citation-audit", "analysis-plan"]);
|
|
122
128
|
function coreSkillPath(name) {
|
|
123
129
|
return join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "skills", "core", name, "SKILL.md");
|
|
124
130
|
}
|
|
@@ -288,7 +294,7 @@ function academicGrillRequest(subject, mode) {
|
|
|
288
294
|
/** Lightweight ideation path for research directions. */
|
|
289
295
|
function academicBrainstormRequest(subject) {
|
|
290
296
|
return [
|
|
291
|
-
"这是 /brainstorm:做选题向头脑风暴。不要加载 academic-grill,不要进入逐题压力测试或研究规格访谈。",
|
|
297
|
+
"这是 /ars brainstorm:做选题向头脑风暴。不要加载 academic-grill,不要进入逐题压力测试或研究规格访谈。",
|
|
292
298
|
subject
|
|
293
299
|
? `头脑风暴主题:${subject}`
|
|
294
300
|
: "根据当前对话与项目材料确定头脑风暴主题;已有信息不要重复询问。",
|
|
@@ -324,7 +330,7 @@ function toolApprovalSummary(toolName, input) {
|
|
|
324
330
|
return `${toolName}${target ? `: ${target.slice(0, 240)}` : ""}`;
|
|
325
331
|
}
|
|
326
332
|
function toolNeedsApproval(toolName, input) {
|
|
327
|
-
if (["write", "edit", "bash", "powershell", "psyclaw_workbench"
|
|
333
|
+
if (["write", "edit", "bash", "powershell", "psyclaw_workbench"].includes(toolName) || toolName.startsWith("mcp__"))
|
|
328
334
|
return true;
|
|
329
335
|
const action = input && typeof input === "object" && !Array.isArray(input) ? input.action : undefined;
|
|
330
336
|
return typeof action === "string" && /write|save|publish|install|download|execute|call/i.test(action);
|
|
@@ -499,7 +505,6 @@ async function skillManagerRows(root, state) {
|
|
|
499
505
|
// recommended installs are excluded here — they are shown through their
|
|
500
506
|
// recommended rows above (including on-disk-but-unvalidated installs).
|
|
501
507
|
const userState = await readUserSkillState(root);
|
|
502
|
-
const disabled = new Set(userState.disabled);
|
|
503
508
|
const localSkills = await scanLocalSkills(root, { includeManaged: false });
|
|
504
509
|
const localRows = localSkills.map((skill) => ({
|
|
505
510
|
id: userSkillId(skill.name),
|
|
@@ -508,7 +513,7 @@ async function skillManagerRows(root, state) {
|
|
|
508
513
|
sourceRef: skill.path,
|
|
509
514
|
collection: false,
|
|
510
515
|
installed: true,
|
|
511
|
-
enabled:
|
|
516
|
+
enabled: localSkillOn(userState, skill.name),
|
|
512
517
|
scope: "local",
|
|
513
518
|
blocked: false,
|
|
514
519
|
source: "local",
|
|
@@ -522,9 +527,10 @@ async function skillManagerRows(root, state) {
|
|
|
522
527
|
const uniqueLocalRows = localRows.filter((row) => !installedRecommendedNames.has(row.name.toLocaleLowerCase()));
|
|
523
528
|
return [...recommendedRows, ...uniqueLocalRows];
|
|
524
529
|
}
|
|
525
|
-
async function mcpManagerRows(root, state
|
|
530
|
+
async function mcpManagerRows(root, state) {
|
|
526
531
|
const { items, installPrep } = await recommendedItems("mcp");
|
|
527
|
-
|
|
532
|
+
// Servers in Pi's mcp.json (user and project); Pi's built-in MCP connects them.
|
|
533
|
+
const userEntries = await readMcpServers(root, getAgentDir());
|
|
528
534
|
const configuredIds = new Set(userEntries.map((entry) => entry.id));
|
|
529
535
|
const recommendedRows = items.map((item) => {
|
|
530
536
|
const id = String(item.id ?? "");
|
|
@@ -548,9 +554,8 @@ async function mcpManagerRows(root, state, runtime) {
|
|
|
548
554
|
],
|
|
549
555
|
};
|
|
550
556
|
});
|
|
551
|
-
// Merge
|
|
552
|
-
//
|
|
553
|
-
// 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.
|
|
554
559
|
const userRows = userEntries.map((entry) => ({
|
|
555
560
|
id: entry.id,
|
|
556
561
|
name: entry.name,
|
|
@@ -560,7 +565,7 @@ async function mcpManagerRows(root, state, runtime) {
|
|
|
560
565
|
source: "user",
|
|
561
566
|
userEntry: entry,
|
|
562
567
|
details: [
|
|
563
|
-
|
|
568
|
+
`${/^https?:/.test(entry.command) ? "HTTP" : "stdio"} · 范围:${entry.scope === "user" ? "用户级" : "项目级"}`,
|
|
564
569
|
`配置:${entry.path}`,
|
|
565
570
|
],
|
|
566
571
|
}));
|
|
@@ -685,7 +690,7 @@ async function showAgentManager(ctx, statusOnly = false) {
|
|
|
685
690
|
const rows = await agentManagerRows(ctx.cwd);
|
|
686
691
|
if (!ctx.hasUI || typeof ctx.ui.custom !== "function" || statusOnly) {
|
|
687
692
|
ctx.ui.notify(rows.map((row) => `${row.status === "core" ? "◆" : "●"} ${row.id} — ${row.name}(${row.stage})`).join("\n")
|
|
688
|
-
|| "暂无 Subagent。可用 /create
|
|
693
|
+
|| "暂无 Subagent。可用 /create subagent 创建(类似 Claude Code)。", "info");
|
|
689
694
|
return;
|
|
690
695
|
}
|
|
691
696
|
while (true) {
|
|
@@ -734,11 +739,11 @@ async function setRecommendedMcpEnabled(root, id, enabled) {
|
|
|
734
739
|
await saveRecommendationState(root, state);
|
|
735
740
|
}
|
|
736
741
|
async function setUserMcpEnabled(entry, enabled) {
|
|
737
|
-
await
|
|
742
|
+
await setMcpServerEnabled(entry, enabled);
|
|
738
743
|
}
|
|
739
744
|
function modelMcpInstallTask(root, row, plan) {
|
|
740
745
|
const suggestedCommand = typeof plan?.command === "string" ? plan.command : "请根据来源仓库的最新安装说明确定";
|
|
741
|
-
const suggestedTarget =
|
|
746
|
+
const suggestedTarget = `~/.psyclaw/agent/mcp.json 的 mcpServers.${row.id}(与其他条目合并,不要覆盖;项目专用的写到 .psyclaw/mcp.json)`;
|
|
742
747
|
return [
|
|
743
748
|
`安装并配置推荐 MCP:${row.name} (${row.id})。`,
|
|
744
749
|
`来源网址:${row.sourceRef ?? "未提供;请停止并告知用户"}`,
|
|
@@ -766,15 +771,15 @@ async function queueModelMcpInstall(pi, ctx, row, plan) {
|
|
|
766
771
|
queueHiddenInstallTask(pi, ctx, modelMcpInstallTask(ctx.cwd, row, plan));
|
|
767
772
|
ctx.ui.notify(`已将 ${row.name} 的安装任务交给当前模型(指令不展示在对话中;默认启用)。完成后请执行 /reload。`, "info");
|
|
768
773
|
}
|
|
769
|
-
async function showMcpManager(pi, ctx
|
|
774
|
+
async function showMcpManager(pi, ctx) {
|
|
770
775
|
const catalog = await recommendedItems("mcp");
|
|
771
776
|
if (!ctx.hasUI || typeof ctx.ui.custom !== "function") {
|
|
772
|
-
const rows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd)
|
|
777
|
+
const rows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd));
|
|
773
778
|
ctx.ui.notify(rows.map((row) => `${row.enabled ? "[on]" : "[off]"} ${row.id} — ${row.name}${row.source === "user" ? "(用户配置)" : ""}`).join("\n"), "info");
|
|
774
779
|
return;
|
|
775
780
|
}
|
|
776
781
|
while (true) {
|
|
777
|
-
const rows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd)
|
|
782
|
+
const rows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd));
|
|
778
783
|
const action = await openMcpManager(ctx, rows);
|
|
779
784
|
if (action.type === "close")
|
|
780
785
|
return;
|
|
@@ -882,7 +887,7 @@ function modelBiosignalPackInstallTask(root, plan, skillRows, mcpRows, mcpPlans,
|
|
|
882
887
|
`- MCP ${row?.name ?? id} (${id})`,
|
|
883
888
|
` 来源:${row?.sourceRef ?? "未提供"}`,
|
|
884
889
|
` 参考命令:${typeof prep?.command === "string" ? prep.command : "请阅读来源仓库安装说明"}`,
|
|
885
|
-
`
|
|
890
|
+
` 建议配置:~/.psyclaw/agent/mcp.json 的 mcpServers.${id}`,
|
|
886
891
|
].join("\n");
|
|
887
892
|
});
|
|
888
893
|
return [
|
|
@@ -899,7 +904,7 @@ function modelBiosignalPackInstallTask(root, plan, skillRows, mcpRows, mcpPlans,
|
|
|
899
904
|
"Skill 清单:",
|
|
900
905
|
...(skillLines.length > 0 ? skillLines : ["(无)"]),
|
|
901
906
|
"",
|
|
902
|
-
"目录中的版本、命令和依赖只作参考;请先阅读各来源仓库的实际安装说明再落地。各项已在推荐状态中默认启用;全部完成后执行 /reload
|
|
907
|
+
"目录中的版本、命令和依赖只作参考;请先阅读各来源仓库的实际安装说明再落地。各项已在推荐状态中默认启用;全部完成后执行 /reload,并提醒用户:在研究模式里用自然语言描述数据与分析目标即可开始。",
|
|
903
908
|
"若某一条目安装命令本身失败,直接诊断并修复;只有遇到必须由用户提供的凭据或外部软件许可证时才向用户说明。",
|
|
904
909
|
].join("\n");
|
|
905
910
|
}
|
|
@@ -920,7 +925,7 @@ async function markBiosignalPackDesired(root, plan, skillScope) {
|
|
|
920
925
|
state.skillScopes = skillScopes;
|
|
921
926
|
await saveRecommendationState(root, state);
|
|
922
927
|
}
|
|
923
|
-
async function queueBiosignalPackInstall(pi, ctx, plan
|
|
928
|
+
async function queueBiosignalPackInstall(pi, ctx, plan) {
|
|
924
929
|
if (plan.mcpIds.length === 0 && plan.skillIds.length === 0) {
|
|
925
930
|
ctx.ui.notify("所选研究域没有需要安装的 MCP 或 Skill。", "info");
|
|
926
931
|
return;
|
|
@@ -954,7 +959,7 @@ async function queueBiosignalPackInstall(pi, ctx, plan, runtime) {
|
|
|
954
959
|
source: "recommended",
|
|
955
960
|
};
|
|
956
961
|
});
|
|
957
|
-
const mcpRows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd)
|
|
962
|
+
const mcpRows = await mcpManagerRows(ctx.cwd, await readRecommendationState(ctx.cwd));
|
|
958
963
|
const selectedMcp = plan.mcpIds.map((id) => {
|
|
959
964
|
const row = mcpRows.find((candidate) => candidate.id === id);
|
|
960
965
|
if (!row?.sourceRef)
|
|
@@ -967,14 +972,14 @@ async function queueBiosignalPackInstall(pi, ctx, plan, runtime) {
|
|
|
967
972
|
plan.skillIds.length > 0 ? `Skill:${plan.skillIds.join(", ")}` : "Skill:无",
|
|
968
973
|
plan.skillIds.length > 0 ? `Skill 安装位置:${skillScopeLabel(scope)}` : "",
|
|
969
974
|
].filter(Boolean).join("\n");
|
|
970
|
-
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);安装后默认启用。`);
|
|
971
976
|
if (!approved)
|
|
972
977
|
return;
|
|
973
978
|
await markBiosignalPackDesired(ctx.cwd, plan, scope);
|
|
974
979
|
queueHiddenInstallTask(pi, ctx, modelBiosignalPackInstallTask(ctx.cwd, plan, skillRows, selectedMcp, mcpCatalog.installPrep, scope));
|
|
975
|
-
ctx.ui.notify("已将生理信号能力包安装任务交给当前模型(指令不展示在对话中)。完成后请执行 /reload
|
|
980
|
+
ctx.ui.notify("已将生理信号能力包安装任务交给当前模型(指令不展示在对话中)。完成后请执行 /reload,并在研究模式里使用。", "info");
|
|
976
981
|
}
|
|
977
|
-
async function showBiosignalPack(pi, ctx
|
|
982
|
+
async function showBiosignalPack(pi, ctx) {
|
|
978
983
|
const catalog = await readBiosignalPackCatalog();
|
|
979
984
|
if (!ctx.hasUI || typeof ctx.ui.custom !== "function") {
|
|
980
985
|
const lines = [
|
|
@@ -1000,7 +1005,7 @@ async function showBiosignalPack(pi, ctx, runtime) {
|
|
|
1000
1005
|
if (result.type === "close")
|
|
1001
1006
|
return;
|
|
1002
1007
|
const plan = resolveBiosignalInstallPlan(catalog, result.domainIds);
|
|
1003
|
-
await queueBiosignalPackInstall(pi, ctx, plan
|
|
1008
|
+
await queueBiosignalPackInstall(pi, ctx, plan);
|
|
1004
1009
|
}
|
|
1005
1010
|
async function showSkillManager(pi, ctx) {
|
|
1006
1011
|
if (!ctx.hasUI || typeof ctx.ui.custom !== "function") {
|
|
@@ -1190,31 +1195,263 @@ export default function psyclawExtension(pi) {
|
|
|
1190
1195
|
void initNodeObservability();
|
|
1191
1196
|
const developerCommands = process.env.PSYCLAW_DEVELOPER_COMMANDS === "1";
|
|
1192
1197
|
const legacyTestApi = typeof pi.registerTool !== "function";
|
|
1193
|
-
|
|
1198
|
+
if (!legacyTestApi) {
|
|
1199
|
+
// Every PsyClaw tool repairs badly serialised arguments before Pi validates them.
|
|
1200
|
+
const register = pi.registerTool.bind(pi);
|
|
1201
|
+
pi.registerTool = ((tool) => register(withArgRepair(tool)));
|
|
1202
|
+
// The built-in edit tool too: same tool, repaired arguments, run in the session's cwd.
|
|
1203
|
+
const editBase = createEditToolDefinition(process.cwd());
|
|
1204
|
+
pi.registerTool({
|
|
1205
|
+
...editBase,
|
|
1206
|
+
async execute(toolCallId, input, signal, onUpdate, ctx) {
|
|
1207
|
+
return createEditToolDefinition(ctx.cwd).execute(toolCallId, input, signal, onUpdate, ctx);
|
|
1208
|
+
},
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
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.
|
|
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
|
+
};
|
|
1254
|
+
// --- analysis (estimand) mode ------------------------------------------------------------
|
|
1255
|
+
const userTexts = (ctx) => {
|
|
1256
|
+
try {
|
|
1257
|
+
const branch = ctx.sessionManager?.getBranch?.() ?? [];
|
|
1258
|
+
return branch.map((entry) => {
|
|
1259
|
+
const m = entry.message;
|
|
1260
|
+
if (m?.role !== "user")
|
|
1261
|
+
return "";
|
|
1262
|
+
const c = m.content;
|
|
1263
|
+
return typeof c === "string" ? c : Array.isArray(c) ? c.map((x) => x.text ?? "").join("\n") : "";
|
|
1264
|
+
}).join("\n");
|
|
1265
|
+
}
|
|
1266
|
+
catch {
|
|
1267
|
+
return "";
|
|
1268
|
+
}
|
|
1269
|
+
};
|
|
1270
|
+
const estimandRqs = (cwd, ctx) => researchQuestionLabels(`${materialsText(cwd)}\n${userTexts(ctx)}`);
|
|
1271
|
+
const estimandReport = (cwd) => (existsSync(join(cwd, "results", "report.md")) ? "results/report.md" : "analysis/report.md");
|
|
1272
|
+
let estimandNudges = 0;
|
|
1273
|
+
let planSubmitTries = 0;
|
|
1274
|
+
let intentGateTries = 0;
|
|
1275
|
+
let practiceNudges = 0;
|
|
1276
|
+
let askGateTries = 0;
|
|
1277
|
+
let restateGateTries = 0;
|
|
1278
|
+
let estimandWorkStarted = false;
|
|
1279
|
+
// Skills seen in the last system prompt; psyclaw_skill finds and loads from it.
|
|
1280
|
+
let skillRegistry = [];
|
|
1281
|
+
// Research stage (analyst / writer) chosen by routing; it picks the research prompt section.
|
|
1282
|
+
const STAGE_ENTRY = "psyclaw-research-stage";
|
|
1283
|
+
const restoreStage = (sessionManager) => {
|
|
1284
|
+
try {
|
|
1285
|
+
const branch = sessionManager?.getBranch?.() ?? [];
|
|
1286
|
+
for (let i = branch.length - 1; i >= 0; i -= 1) {
|
|
1287
|
+
const entry = branch[i];
|
|
1288
|
+
if (entry?.type === "custom" && entry.customType === STAGE_ENTRY && (entry.data?.stage === "analysis" || entry.data?.stage === "writing"))
|
|
1289
|
+
return entry.data.stage;
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
catch { /* no session yet */ }
|
|
1293
|
+
return undefined;
|
|
1294
|
+
};
|
|
1295
|
+
const setStage = (sessionManager, stage) => {
|
|
1296
|
+
if (restoreStage(sessionManager) === stage)
|
|
1297
|
+
return;
|
|
1298
|
+
try {
|
|
1299
|
+
pi.appendEntry(STAGE_ENTRY, { stage });
|
|
1300
|
+
}
|
|
1301
|
+
catch { /* session may not be open */ }
|
|
1302
|
+
};
|
|
1303
|
+
// Large skills load as a digest: find their SKILL.md from the registry, else the bundled packs.
|
|
1304
|
+
const bundledSkillFile = (name) => {
|
|
1305
|
+
try {
|
|
1306
|
+
const pkg = dirname(dirname(bundledCoreSkillsDir()));
|
|
1307
|
+
for (const dir of [join(pkg, "skills", "core"), join(pkg, "vendor", "ars"), join(pkg, "vendor", "nature-skills"), join(pkg, "vendor", "academic-paper-skills")]) {
|
|
1308
|
+
const candidate = join(dir, name, "SKILL.md");
|
|
1309
|
+
if (existsSync(candidate))
|
|
1310
|
+
return candidate;
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
catch { /* package layout not found */ }
|
|
1314
|
+
return undefined;
|
|
1315
|
+
};
|
|
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);
|
|
1350
|
+
const registry = (prompt) => {
|
|
1351
|
+
const listed = registrySkillListing(prompt, visibleLocal);
|
|
1352
|
+
if (listed.skills.length)
|
|
1353
|
+
skillRegistry = listed.skills;
|
|
1354
|
+
return listed.systemPrompt;
|
|
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
|
+
};
|
|
1194
1406
|
let arsModeEditor;
|
|
1195
1407
|
let arsUiContext;
|
|
1196
|
-
let sessionMode =
|
|
1408
|
+
let sessionMode = startingSessionMode(false);
|
|
1409
|
+
let startingMode;
|
|
1197
1410
|
// Sticky mode as persisted on the session branch. Headless runs have no mode editor, so the input
|
|
1198
1411
|
// handler must read it here too; otherwise a restored analysis session is treated as chat.
|
|
1199
1412
|
const restoreSessionMode = (sessionManager) => {
|
|
1200
1413
|
const modeEntry = [...(sessionManager?.getBranch?.() ?? [])].reverse().find((entry) => entry.type === "custom" && entry.customType === "psyclaw-session-mode");
|
|
1201
1414
|
return parseSessionMode(modeEntry?.data?.mode)
|
|
1202
|
-
??
|
|
1415
|
+
?? startingMode ?? sessionMode;
|
|
1203
1416
|
};
|
|
1204
1417
|
let turnStartedAt;
|
|
1205
1418
|
let llmTurnSpan;
|
|
1206
1419
|
let capturedTurnGeneration = false;
|
|
1420
|
+
// Tools only the research workflow uses; basic mode hides them (Pi's own tools, skills,
|
|
1421
|
+
// MCP and the choice box stay). Other active tools, such as ones added on the command line, are kept.
|
|
1422
|
+
// Tools each mode leaves out. basic: only Pi's tools, skills, MCP and the choice box. research: the
|
|
1423
|
+
// research workflow, no estimand tool. analysis (estimand): data tools and psyclaw_spec, no research
|
|
1424
|
+
// workflow tools. Other active tools, such as ones added on the command line, are kept.
|
|
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"];
|
|
1426
|
+
const MODE_TOOLS = {
|
|
1427
|
+
basic: [],
|
|
1428
|
+
research: MANAGED_TOOLS.filter((name) => name !== "psyclaw_spec"),
|
|
1429
|
+
estimand: ["psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_spec", "psyclaw_brain"],
|
|
1430
|
+
};
|
|
1431
|
+
let managedAvailable;
|
|
1432
|
+
const syncModeTools = (mode) => {
|
|
1433
|
+
const api = pi;
|
|
1434
|
+
if (typeof api.getActiveTools !== "function" || typeof api.setActiveTools !== "function")
|
|
1435
|
+
return;
|
|
1436
|
+
try {
|
|
1437
|
+
const active = api.getActiveTools();
|
|
1438
|
+
managedAvailable ??= MANAGED_TOOLS.filter((name) => active.includes(name));
|
|
1439
|
+
const rest = active.filter((name) => !MANAGED_TOOLS.includes(name));
|
|
1440
|
+
const next = [...rest, ...managedAvailable.filter((name) => MODE_TOOLS[mode].includes(name))];
|
|
1441
|
+
if (next.length !== active.length || next.some((name) => !active.includes(name)))
|
|
1442
|
+
api.setActiveTools(next);
|
|
1443
|
+
}
|
|
1444
|
+
catch { /* session not ready: the next switch applies it */ }
|
|
1445
|
+
};
|
|
1207
1446
|
const applySessionMode = (mode, opts) => {
|
|
1208
1447
|
sessionMode = mode;
|
|
1448
|
+
syncModeTools(mode);
|
|
1209
1449
|
arsModeEditor?.setMode(mode);
|
|
1210
1450
|
arsUiContext?.ui.setStatus("mode", MODE_STATUS[mode]);
|
|
1211
1451
|
// Clear legacy ars status key so it never duplicates with "mode".
|
|
1212
1452
|
arsUiContext?.ui.setStatus("ars", undefined);
|
|
1213
1453
|
if (opts?.syncSession === false || !arsUiContext)
|
|
1214
1454
|
return;
|
|
1215
|
-
setArsPiSessionActive(typeof pi.appendEntry === "function"
|
|
1216
|
-
? pi.appendEntry.bind(pi)
|
|
1217
|
-
: undefined, mode === "academic");
|
|
1218
1455
|
if (typeof pi.appendEntry === "function") {
|
|
1219
1456
|
pi.appendEntry("psyclaw-session-mode", { mode });
|
|
1220
1457
|
}
|
|
@@ -1222,11 +1459,11 @@ export default function psyclawExtension(pi) {
|
|
|
1222
1459
|
const cycleSessionMode = () => {
|
|
1223
1460
|
const next = nextSessionMode(arsModeEditor?.getMode() ?? sessionMode);
|
|
1224
1461
|
applySessionMode(next);
|
|
1225
|
-
arsUiContext?.ui.setStatus("mode", MODE_STATUS[next]
|
|
1462
|
+
arsUiContext?.ui.setStatus("mode", MODE_STATUS[next]);
|
|
1226
1463
|
};
|
|
1227
1464
|
if (!legacyTestApi && typeof pi.registerShortcut === "function") {
|
|
1228
1465
|
pi.registerShortcut("shift+tab", {
|
|
1229
|
-
description: "
|
|
1466
|
+
description: "Switch between basic mode and research mode",
|
|
1230
1467
|
handler: () => {
|
|
1231
1468
|
cycleSessionMode();
|
|
1232
1469
|
},
|
|
@@ -1254,7 +1491,6 @@ export default function psyclawExtension(pi) {
|
|
|
1254
1491
|
pi.on("session_shutdown", () => {
|
|
1255
1492
|
finishAgentSpan(llmTurnSpan);
|
|
1256
1493
|
llmTurnSpan = undefined;
|
|
1257
|
-
runtimeMcps.close();
|
|
1258
1494
|
void shutdownObservability();
|
|
1259
1495
|
});
|
|
1260
1496
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
@@ -1288,6 +1524,34 @@ export default function psyclawExtension(pi) {
|
|
|
1288
1524
|
});
|
|
1289
1525
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
1290
1526
|
pi.on("agent_end", async (event, ctx) => {
|
|
1527
|
+
// Analysis mode end gate: once a specification exists, list what is missing (at most 6 times).
|
|
1528
|
+
try {
|
|
1529
|
+
if (restoreSessionMode(ctx?.sessionManager) === "estimand" && ctx?.cwd && (estimandWorkStarted || existsSync(join(ctx.cwd, SPEC_JSON))) && estimandNudges < 6) {
|
|
1530
|
+
const left = estimandGaps(ctx.cwd, loadSpec(ctx.cwd), estimandRqs(ctx.cwd, ctx), estimandReport(ctx.cwd));
|
|
1531
|
+
if (left.length) {
|
|
1532
|
+
estimandNudges += 1;
|
|
1533
|
+
pi.sendUserMessage(`[psyclaw] The analysis is not finished yet:\n- ${left.join("\n- ")}`, { deliverAs: "followUp" });
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
catch { /* the gate never blocks the turn's bookkeeping */ }
|
|
1538
|
+
// Research mode: a report without 做法对照 (or with one older than the decision record) gets a nudge, twice at most.
|
|
1539
|
+
try {
|
|
1540
|
+
if (restoreSessionMode(ctx?.sessionManager) === "research" && ctx?.cwd && practiceNudges < 2) {
|
|
1541
|
+
const plan = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
1542
|
+
const report = ["results/report.md", "analysis/report.md", "analysis/HANDOFF.md"].find((f) => existsSync(join(ctx.cwd, f)));
|
|
1543
|
+
if (plan && (plan.status === "running" || plan.status === "completed") && report) {
|
|
1544
|
+
const practice = join(ctx.cwd, PRACTICE_PATH);
|
|
1545
|
+
const record = join(ctx.cwd, ".psyclaw", "decisions.jsonl");
|
|
1546
|
+
const stale = existsSync(practice) && existsSync(record) && statSync(record).mtimeMs > statSync(practice).mtimeMs + 1000;
|
|
1547
|
+
if (!existsSync(practice) || stale) {
|
|
1548
|
+
practiceNudges += 1;
|
|
1549
|
+
pi.sendUserMessage(`[psyclaw] ${stale ? "做法对照 is older than the decision record" : `${report} has no 做法对照 yet`}: call psyclaw_plan action=compare with one check per item the researcher asked for, and put the section it returns at the top of ${report}.`, { deliverAs: "followUp" });
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
catch { /* never blocks */ }
|
|
1291
1555
|
const fallback = ctxProviderModel(ctx);
|
|
1292
1556
|
finishAgentSpan(llmTurnSpan, piTurnSpanAttributes(fallback));
|
|
1293
1557
|
llmTurnSpan = undefined;
|
|
@@ -1311,34 +1575,40 @@ export default function psyclawExtension(pi) {
|
|
|
1311
1575
|
});
|
|
1312
1576
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
1313
1577
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
1578
|
+
if (ctx?.cwd)
|
|
1579
|
+
skillState = await readUserSkillState(ctx.cwd).catch(() => skillState);
|
|
1314
1580
|
const restored = restoreSessionMode(ctx?.sessionManager);
|
|
1315
1581
|
sessionMode = restored;
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1582
|
+
syncModeTools(restored);
|
|
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
|
+
}
|
|
1589
|
+
if (restored === "research" && ctx && !ctx.hasUI)
|
|
1321
1590
|
modeBlock = `${modeBlock}\n\n${unattendedAnalysisPrompt()}`;
|
|
1322
|
-
if (
|
|
1323
|
-
modeBlock = `${modeBlock}\n\n${unattendedPriorPrompt()}`;
|
|
1324
|
-
if (priorMemory && restored === "chat") {
|
|
1325
|
-
modeBlock = `## PsyClaw mode: chat\nPlain assistant on the Pi harness. Follow the prior plan memory below for later analysis. Do not ask for a mode switch.\n\n${priorMemory}`;
|
|
1326
|
-
}
|
|
1327
|
-
if (priorMemory && restored === "analysis")
|
|
1328
|
-
modeBlock = `${modeBlock}\n\n${analysisFollowsPriorPrompt(priorMemory)}`;
|
|
1329
|
-
if (restored === "academic" || isArsPiTurn(event.systemPrompt) || isArsPiActive(ctx?.sessionManager)) {
|
|
1591
|
+
if (isArsPiTurn(event.systemPrompt) || isArsPiActive(ctx?.sessionManager)) {
|
|
1330
1592
|
return {
|
|
1331
|
-
systemPrompt: `${event.systemPrompt}\n\n${modeBlock}\n\n${psyclawArsPatch({
|
|
1593
|
+
systemPrompt: `${registry(event.systemPrompt)}\n\n${modeBlock}\n\n${PSYCLAW_WRITING_RULES}\n\n${psyclawArsPatch({
|
|
1332
1594
|
skills: event.systemPromptOptions?.skills,
|
|
1333
1595
|
systemPrompt: event.systemPrompt,
|
|
1334
1596
|
})}`,
|
|
1335
1597
|
};
|
|
1336
1598
|
}
|
|
1337
|
-
|
|
1599
|
+
if (restored === "basic") {
|
|
1600
|
+
// Basic mode: Pi with a three-line prompt in place of the research identity prompt; skills by first sentence.
|
|
1601
|
+
return { systemPrompt: `${registry(event.systemPrompt.replace(PSYCLAW_IDENTITY_PROMPT, PSYCLAW_BASIC_PROMPT))}\n\n${modeBlock}` };
|
|
1602
|
+
}
|
|
1603
|
+
return { systemPrompt: `${registry(event.systemPrompt)}\n\n${modeBlock}` };
|
|
1338
1604
|
});
|
|
1339
1605
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
1340
1606
|
pi.on("session_start", async (_event, ctx) => {
|
|
1341
1607
|
arsUiContext = ctx;
|
|
1608
|
+
if (typeof ctx.cwd === "string") {
|
|
1609
|
+
const hasWorkspace = await hasCanonicalWorkspace(ctx.cwd).catch(() => false) || Boolean(await readActiveProject(ctx.cwd).catch(() => undefined));
|
|
1610
|
+
startingMode = startingSessionMode(hasWorkspace);
|
|
1611
|
+
}
|
|
1342
1612
|
if (typeof ctx.cwd === "string") {
|
|
1343
1613
|
try {
|
|
1344
1614
|
const discovered = await refreshSkillResolution(ctx.cwd);
|
|
@@ -1347,8 +1617,30 @@ export default function psyclawExtension(pi) {
|
|
|
1347
1617
|
}
|
|
1348
1618
|
catch { /* session may not be open */ }
|
|
1349
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 = [];
|
|
1350
1624
|
for (const row of discovered.resolution.skipped.filter((item) => item.reason === "core-name")) {
|
|
1351
|
-
|
|
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");
|
|
1352
1644
|
}
|
|
1353
1645
|
}
|
|
1354
1646
|
}
|
|
@@ -1371,6 +1663,8 @@ export default function psyclawExtension(pi) {
|
|
|
1371
1663
|
ctx.ui.setEditorComponent((tui, theme, keybindings) => {
|
|
1372
1664
|
const editor = new ArsModeEditor(tui, theme, keybindings);
|
|
1373
1665
|
arsModeEditor = editor;
|
|
1666
|
+
editor.cwd = ctx.cwd;
|
|
1667
|
+
void loadDataAccess(ctx.cwd).then((loaded) => { editor.secretEntries = loaded.entries; }).catch(() => undefined);
|
|
1374
1668
|
editor.onModeChange = (mode) => {
|
|
1375
1669
|
sessionMode = mode;
|
|
1376
1670
|
ctx.ui.setStatus("mode", MODE_STATUS[mode]);
|
|
@@ -1381,7 +1675,7 @@ export default function psyclawExtension(pi) {
|
|
|
1381
1675
|
};
|
|
1382
1676
|
const modeEntry = [...ctx.sessionManager.getBranch()].reverse().find((entry) => entry.type === "custom" && entry.customType === "psyclaw-session-mode");
|
|
1383
1677
|
const restore = parseSessionMode(modeEntry?.data?.mode)
|
|
1384
|
-
??
|
|
1678
|
+
?? startingMode ?? sessionMode;
|
|
1385
1679
|
editor.setMode(restore);
|
|
1386
1680
|
sessionMode = restore;
|
|
1387
1681
|
ctx.ui.setStatus("mode", MODE_STATUS[restore]);
|
|
@@ -1389,6 +1683,31 @@ export default function psyclawExtension(pi) {
|
|
|
1389
1683
|
return editor;
|
|
1390
1684
|
});
|
|
1391
1685
|
});
|
|
1686
|
+
const refreshEditorSecrets = async (cwd) => {
|
|
1687
|
+
if (!arsModeEditor)
|
|
1688
|
+
return;
|
|
1689
|
+
try {
|
|
1690
|
+
arsModeEditor.secretEntries = (await loadDataAccess(cwd)).entries;
|
|
1691
|
+
}
|
|
1692
|
+
catch { /* keep the old list */ }
|
|
1693
|
+
};
|
|
1694
|
+
// `@path:s` in a message marks that file script-only before anything else sees the message (secret-marks.ts).
|
|
1695
|
+
// Pi chains input handlers, so the main handler below receives the cleaned text.
|
|
1696
|
+
if (!legacyTestApi && typeof pi.on === "function")
|
|
1697
|
+
pi.on("input", async (event, ctx) => {
|
|
1698
|
+
if (event.source === "extension")
|
|
1699
|
+
return;
|
|
1700
|
+
const marks = parseSecretMarks(event.text);
|
|
1701
|
+
if (!marks.paths.length)
|
|
1702
|
+
return;
|
|
1703
|
+
const result = await markScriptOnly(ctx.cwd, marks.paths);
|
|
1704
|
+
if (result.marked.length)
|
|
1705
|
+
ctx.ui.notify(`已设为只许脚本读(模型不能读内容,分析脚本可以打开):${result.marked.join("、")}`, "info");
|
|
1706
|
+
for (const failed of result.failed)
|
|
1707
|
+
ctx.ui.notify(`没能标记 ${failed.path}:${failed.reason}`, "warning");
|
|
1708
|
+
await refreshEditorSecrets(ctx.cwd);
|
|
1709
|
+
return { action: "transform", text: result.marked.length ? `${marks.text}\n\n${secretNote(result.marked)}` : marks.text };
|
|
1710
|
+
});
|
|
1392
1711
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
1393
1712
|
pi.on("input", async (event, ctx) => {
|
|
1394
1713
|
if (event.source === "extension")
|
|
@@ -1415,14 +1734,52 @@ export default function psyclawExtension(pi) {
|
|
|
1415
1734
|
}
|
|
1416
1735
|
const mode = arsModeEditor?.getMode() ?? restoreSessionMode(ctx.sessionManager);
|
|
1417
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
|
+
}
|
|
1763
|
+
// Research mode: every message of the researcher goes into the intent record word for word (intent.ts),
|
|
1764
|
+
// before any routing, so the plan is checked against their words and a later session can read them back.
|
|
1765
|
+
if (mode === "research" && !trimmed.startsWith("/") && existsSync(join(ctx.cwd, ".psyclaw"))) {
|
|
1766
|
+
await recordSaid(ctx.cwd, event.text).catch(() => false);
|
|
1767
|
+
}
|
|
1768
|
+
// Research mode: a user-installed skill opened with /skill:<name> is reference material (skill-reference.ts).
|
|
1769
|
+
const named = mode === "research" ? skillCommandName(trimmed) : undefined;
|
|
1770
|
+
if (named) {
|
|
1771
|
+
const local = await enabledLocalSkillPaths(ctx.cwd, { excludedNames: coreSkillNames() }).catch(() => undefined);
|
|
1772
|
+
if (local?.loaded.some((skill) => skill.name === named))
|
|
1773
|
+
return { action: "transform", text: withResearchSkillNote(event.text) };
|
|
1774
|
+
}
|
|
1418
1775
|
// A direct user statement is a valid human-review route when Panel is unavailable.
|
|
1419
1776
|
// Do not infer approval from assistant output, quoted text, or a question about verification.
|
|
1420
1777
|
if (/^我(?:已核验|已核实|已审阅并确认|核验了)(?:分析报告|论文定稿)?[。!!]?$/u.test(trimmed)) {
|
|
1421
1778
|
const scope = trimmed.includes("论文定稿") ? "academic-finalize"
|
|
1422
1779
|
: trimmed.includes("分析报告") ? "analysis-complete"
|
|
1423
|
-
:
|
|
1780
|
+
: "analysis-complete";
|
|
1424
1781
|
if (!scope || !(await readActiveProject(ctx.cwd))) {
|
|
1425
|
-
ctx.ui.notify("
|
|
1782
|
+
ctx.ui.notify("请先在已初始化的项目里操作,并明确说「我已核验分析报告」或「我已核验论文定稿」。", "warning");
|
|
1426
1783
|
return { action: "handled" };
|
|
1427
1784
|
}
|
|
1428
1785
|
try {
|
|
@@ -1434,42 +1791,64 @@ export default function psyclawExtension(pi) {
|
|
|
1434
1791
|
}
|
|
1435
1792
|
return { action: "handled" };
|
|
1436
1793
|
}
|
|
1437
|
-
//
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1794
|
+
// Plan confirmations (0.34): each card settles its own choice; once every choice is settled, a plain yes
|
|
1795
|
+
// (「可以」「批准」) or the old approval sentence approves the whole plan. No typed ritual is required.
|
|
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) {
|
|
1799
|
+
const pending = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
1800
|
+
if (pending && ["awaiting-confirm", "ready", "reviewing", "clarifying", "drafting"].includes(pending.status)) {
|
|
1801
|
+
approves = (await judge(ctx, "plan-approval", { reply: trimmed }, APPROVAL_QUESTION, APPROVAL_QUESTION_B)) === "approve";
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
// A reply while the restated intent waits for the researcher: confirm it or restate again.
|
|
1805
|
+
if (mode === "research" && !trimmed.startsWith("/") && existsSync(join(ctx.cwd, ".psyclaw"))) {
|
|
1806
|
+
const intent = await readIntent(ctx.cwd).catch(() => undefined);
|
|
1807
|
+
if (intent?.current && !intent.current.confirmed) {
|
|
1442
1808
|
return {
|
|
1443
1809
|
action: "transform",
|
|
1444
|
-
text:
|
|
1810
|
+
text: [
|
|
1811
|
+
event.text,
|
|
1812
|
+
"",
|
|
1813
|
+
`[psyclaw] This is the researcher's reply to the restated intent (v${intent.current.version}). If it confirms it, call psyclaw_intent action=confirm with quote = the reply unchanged (and corrections = their corrections, if any, in their words). If it corrects or adds something substantial, restate again with psyclaw_intent action=restate, post the new message and wait. Do not submit the plan before the intent is confirmed.`,
|
|
1814
|
+
].join("\n"),
|
|
1445
1815
|
};
|
|
1446
1816
|
}
|
|
1447
1817
|
}
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
: "
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
};
|
|
1818
|
+
// The researcher's reply to the numbered plan message settles every point at once (plan-message.ts).
|
|
1819
|
+
if (mode === "research" && !trimmed.startsWith("/")) {
|
|
1820
|
+
const pending = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
1821
|
+
const points = pending && ["awaiting-confirm", "ready", "reviewing"].includes(pending.status)
|
|
1822
|
+
? (await openDecisions(ctx.cwd, pending.id)).filter((d) => isPlanPointId(d.id))
|
|
1823
|
+
: [];
|
|
1824
|
+
if (pending && points.length > 0) {
|
|
1825
|
+
return {
|
|
1826
|
+
action: "transform",
|
|
1827
|
+
text: [
|
|
1828
|
+
event.text,
|
|
1829
|
+
"",
|
|
1830
|
+
`[psyclaw] This is the researcher's reply to the numbered plan (open: ${points.map((d) => pointLabel(d.id)).join(", ")}). Record it now with one psyclaw_plan action=answers call: quote = the reply unchanged; answers = one entry per point it names (option number, or text for their own approach); rest = recommended if it accepts the recommendations for the rest, else open; approved = ${approves ? "true (it reads as an approval)" : "true only if it approves the plan"}; additions = analyses it says are missing. Ask a psyclaw_ask card only for a point the reply leaves unclear.`,
|
|
1831
|
+
].join("\n"),
|
|
1832
|
+
};
|
|
1833
|
+
}
|
|
1465
1834
|
}
|
|
1466
|
-
|
|
1467
|
-
if (mode === "analysis" && (isPlanRitualConfirm(trimmed) || isNaturalPlanConfirm(trimmed))) {
|
|
1835
|
+
if (mode === "research" && approves) {
|
|
1468
1836
|
const plan = await readActiveAnalysisPlan(ctx.cwd);
|
|
1837
|
+
if (plan && (plan.status === "clarifying" || plan.status === "drafting")) {
|
|
1838
|
+
// A yes before the plan was submitted: nothing to approve yet.
|
|
1839
|
+
return {
|
|
1840
|
+
action: "transform",
|
|
1841
|
+
text: invokeSkill("analysis-plan", [
|
|
1842
|
+
`The researcher said "${trimmed}", but plan ${plan.id} has not been submitted yet (status: ${plan.status}).`,
|
|
1843
|
+
"Submit the proposal with psyclaw_plan action=submit, every decision point in decisions, and post the numbered message it returns. Do not run the confirmatory analysis yet.",
|
|
1844
|
+
].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")),
|
|
1845
|
+
};
|
|
1846
|
+
}
|
|
1469
1847
|
if (plan && (plan.status === "awaiting-confirm" || plan.status === "ready" || plan.status === "reviewing")) {
|
|
1470
1848
|
const method = plan.confirmedMethod || plan.primaryAnalysis || plan.proposedMethods[0] || "按当前方案执行";
|
|
1471
|
-
|
|
1472
|
-
const
|
|
1849
|
+
// Open questions come from the one decision record (psyclaw_ask / psyclaw_decide).
|
|
1850
|
+
const pendingChoices = await openDecisions(ctx.cwd, plan.id);
|
|
1851
|
+
const ritual = isPlanRitualConfirm(trimmed) || pendingChoices.length === 0;
|
|
1473
1852
|
if (!ritual) {
|
|
1474
1853
|
// Soft acknowledge only — never jump to run-now.
|
|
1475
1854
|
let next = plan.status === "awaiting-confirm" && !plan.confirmedMethod
|
|
@@ -1477,33 +1856,29 @@ export default function psyclawExtension(pi) {
|
|
|
1477
1856
|
: plan;
|
|
1478
1857
|
next = await writeAnalysisPlan(ctx.cwd, next);
|
|
1479
1858
|
const needChoices = pendingChoices.length > 0
|
|
1480
|
-
? `仍有 ${pendingChoices.length}
|
|
1481
|
-
:
|
|
1482
|
-
ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n${needChoices}`, "info");
|
|
1859
|
+
? `仍有 ${pendingChoices.length} 项决定待定:${pendingChoices.map((d) => d.question).join(";")}。请先逐项确认。`
|
|
1860
|
+
: "方法已记下。";
|
|
1861
|
+
ctx.ui.notify(`${formatAnalysisPlanStatus(next, pendingChoices.length)}\n${needChoices}`, "info");
|
|
1483
1862
|
return {
|
|
1484
1863
|
action: "transform",
|
|
1485
|
-
text: [
|
|
1486
|
-
"/skill:analysis-plan",
|
|
1487
|
-
"",
|
|
1864
|
+
text: invokeSkill("analysis-plan", [
|
|
1488
1865
|
`User soft-acknowledged ("${trimmed}"). Do NOT run scripts yet.`,
|
|
1489
1866
|
`Confirmed method so far: ${next.confirmedMethod ?? method}`,
|
|
1490
1867
|
pendingChoices.length > 0
|
|
1491
|
-
? `
|
|
1492
|
-
:
|
|
1493
|
-
"Do not start /
|
|
1494
|
-
].join("\n"),
|
|
1868
|
+
? `Open decisions in the decision record: ${pendingChoices.map((d) => `${d.id} (${d.question})`).join(", ")}. Ask the next one with psyclaw_ask (same id) and wait; if the researcher already answered in text, record it with psyclaw_decide.`
|
|
1869
|
+
: "All listed choices are decided. Ask the user to approve the whole plan (a plain yes is enough).",
|
|
1870
|
+
"Do not start /check quick or /check full until the user explicitly agrees to open that block.",
|
|
1871
|
+
].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")),
|
|
1495
1872
|
};
|
|
1496
1873
|
}
|
|
1497
1874
|
if (pendingChoices.length > 0) {
|
|
1498
|
-
ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n
|
|
1875
|
+
ctx.ui.notify(`${formatAnalysisPlanStatus(plan, pendingChoices.length)}\n已收到批准,但还有 ${pendingChoices.length} 项决定待定,请先逐项定完。`, "warning");
|
|
1499
1876
|
return {
|
|
1500
1877
|
action: "transform",
|
|
1501
|
-
text: [
|
|
1502
|
-
|
|
1503
|
-
"",
|
|
1504
|
-
|
|
1505
|
-
"Present the next undecided choice card and wait. Do not execute.",
|
|
1506
|
-
].join("\n"),
|
|
1878
|
+
text: invokeSkill("analysis-plan", [
|
|
1879
|
+
`User approved the plan but ${pendingChoices.length} decision(s) are still open: ${pendingChoices.map((d) => `${d.id} (${d.question})`).join(", ")}.`,
|
|
1880
|
+
"Ask the next one with psyclaw_ask (same id) and wait. Do not execute.",
|
|
1881
|
+
].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")),
|
|
1507
1882
|
};
|
|
1508
1883
|
}
|
|
1509
1884
|
let next = plan.status === "awaiting-confirm"
|
|
@@ -1516,25 +1891,55 @@ export default function psyclawExtension(pi) {
|
|
|
1516
1891
|
next = advanceAnalysisPlan(next, { type: "run-now" });
|
|
1517
1892
|
next = await writeAnalysisPlan(ctx.cwd, next);
|
|
1518
1893
|
if (next.status !== "running") {
|
|
1519
|
-
ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n
|
|
1894
|
+
ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n未能进入执行(检查子项是否都已确认)。`, "warning");
|
|
1520
1895
|
return { action: "handled" };
|
|
1521
1896
|
}
|
|
1522
|
-
ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n
|
|
1897
|
+
ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n已记录方案批准并开始执行。`, "info");
|
|
1523
1898
|
return {
|
|
1524
1899
|
action: "transform",
|
|
1525
|
-
text: [
|
|
1526
|
-
"
|
|
1527
|
-
"",
|
|
1528
|
-
`User completed plan ritual ("${PLAN_RITUAL_PHRASE}"). Execute plan ${next.id} now.`,
|
|
1900
|
+
text: invokeSkill("analysis-plan", [
|
|
1901
|
+
`User approved the plan ("${trimmed}"). Execute plan ${next.id} now.`,
|
|
1529
1902
|
`Confirmed method: ${next.confirmedMethod ?? method}`,
|
|
1530
|
-
next.approvalMode === "auto" ? "approvalMode=auto: label outputs as 未经人审批." : "Human
|
|
1531
|
-
"Do NOT auto-start /
|
|
1532
|
-
].join("\n"),
|
|
1903
|
+
next.approvalMode === "auto" ? "approvalMode=auto: label outputs as 未经人审批." : "Human plan approval recorded.",
|
|
1904
|
+
"Do NOT auto-start /check quick or /check full. After scripts finish, ask whether to open those blocks; only proceed if the user agrees.",
|
|
1905
|
+
].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")),
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
if (mode !== "research")
|
|
1910
|
+
return;
|
|
1911
|
+
// Analysis first: a data-analysis request that also asks for figures or a write-up is still an
|
|
1912
|
+
// analysis.
|
|
1913
|
+
// The meaning is judged (decision model in two wordings, else a large-model side call), never by a pattern.
|
|
1914
|
+
let routed;
|
|
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 } : {}) };
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
const wantsStats = routed?.route === "analysis";
|
|
1924
|
+
const wantsAcademic = routed?.route === "writing";
|
|
1925
|
+
if (mode === "research" && (wantsStats || wantsAcademic))
|
|
1926
|
+
setStage(ctx.sessionManager, wantsStats ? "analysis" : "writing");
|
|
1927
|
+
// No research question yet: start with academic-grill (brainstorm questions from the data, or grill
|
|
1928
|
+
// a rough idea) before any plan or writing.
|
|
1929
|
+
if (mode === "research" && trimmed.length <= 2_000) {
|
|
1930
|
+
const noQuestion = (wantsStats || wantsAcademic)
|
|
1931
|
+
&& (await judge(ctx, "has-question", { message: trimmed }, HAS_QUESTION_QUESTION, HAS_QUESTION_QUESTION_B)) === false;
|
|
1932
|
+
if (noQuestion) {
|
|
1933
|
+
return {
|
|
1934
|
+
action: "transform",
|
|
1935
|
+
text: invokeSkill("academic-grill", [
|
|
1936
|
+
"The researcher has no research question yet. Follow academic-grill: look at the available data or materials once, then propose 2-4 answerable questions with psyclaw_ask (recommend one), or, if they already have a rough idea, grill it one point at a time. Do not build an analysis plan or write until a question is chosen.",
|
|
1937
|
+
"User request:",
|
|
1938
|
+
trimmed,
|
|
1939
|
+
].join("\n"), skillLoaded(branchOf(ctx), "academic-grill")),
|
|
1533
1940
|
};
|
|
1534
1941
|
}
|
|
1535
1942
|
}
|
|
1536
|
-
const wantsStats = mode === "analysis" && Boolean(resolveStatsIntent(trimmed));
|
|
1537
|
-
const wantsAcademic = mode === "academic" && Boolean(resolveAcademicSoftRoute(trimmed));
|
|
1538
1943
|
if ((wantsStats || wantsAcademic) && !(await readActiveProject(ctx.cwd))) {
|
|
1539
1944
|
if (await hasCanonicalWorkspace(ctx.cwd)) {
|
|
1540
1945
|
// Heal binding silently — prior /init layout already present.
|
|
@@ -1544,36 +1949,42 @@ export default function psyclawExtension(pi) {
|
|
|
1544
1949
|
return {
|
|
1545
1950
|
action: "transform",
|
|
1546
1951
|
text: [
|
|
1547
|
-
"
|
|
1952
|
+
"No PsyClaw workspace here yet. Handle the request; mention once that /init sets up the research folders.",
|
|
1548
1953
|
"User request:",
|
|
1549
1954
|
trimmed,
|
|
1550
1955
|
].join("\n"),
|
|
1551
1956
|
};
|
|
1552
1957
|
}
|
|
1553
1958
|
else {
|
|
1554
|
-
const choice = await ctx.ui.select("
|
|
1555
|
-
if (choice === "取消"
|
|
1959
|
+
const choice = await ctx.ui.select("这个文件夹还没有研究工作区。要在这里建立吗?(data/、analysis/、literature/、paper/,原始数据只读保护)", ["在这里建立(推荐)", "不建,直接继续", "取消"], { timeout: 120_000 });
|
|
1960
|
+
if (choice === "取消")
|
|
1556
1961
|
return { action: "handled" };
|
|
1557
|
-
if (choice === "
|
|
1558
|
-
|
|
1962
|
+
if (choice === "在这里建立(推荐)") {
|
|
1963
|
+
// Build it here, then carry on with this same request (no /init text sent to the model).
|
|
1964
|
+
const project = await bootstrapProject({ root: ctx.cwd });
|
|
1965
|
+
applySessionMode("research");
|
|
1966
|
+
ctx.ui.notify(`已建立研究工作区:${project.id}。继续处理你的请求。`, "info");
|
|
1559
1967
|
}
|
|
1560
|
-
|
|
1968
|
+
else if (choice !== undefined)
|
|
1969
|
+
ctx.ui.notify("继续本次请求;需要时可以用 /init 建立工作区。", "info");
|
|
1561
1970
|
}
|
|
1562
1971
|
}
|
|
1563
|
-
if (
|
|
1564
|
-
const match =
|
|
1972
|
+
if (wantsAcademic) {
|
|
1973
|
+
const match = routed?.skill
|
|
1974
|
+
? { skill: routed.skill, reason: "decision model", priority: 0 }
|
|
1975
|
+
: routed ? { skill: "academic-paper", reason: "decision model (writing)", priority: 0 } : null;
|
|
1565
1976
|
if (!match)
|
|
1566
1977
|
return;
|
|
1567
1978
|
const ranked = rankAcademicSoftRoutes(event.text, 3);
|
|
1568
1979
|
return {
|
|
1569
1980
|
action: "transform",
|
|
1570
|
-
text: formatAcademicSoftRouteInvocation(match, event.text, ranked.slice(1)),
|
|
1981
|
+
text: formatAcademicSoftRouteInvocation(match, event.text, ranked.slice(1), { skillLoaded: skillLoaded(branchOf(ctx), match.skill) }),
|
|
1571
1982
|
};
|
|
1572
1983
|
}
|
|
1573
|
-
|
|
1984
|
+
{
|
|
1574
1985
|
const userSkills = await userSkillsOutsideScriptOnly(ctx.cwd).catch(() => []);
|
|
1575
1986
|
const userSkillNames = userSkills.map((skill) => skill.name);
|
|
1576
|
-
const match =
|
|
1987
|
+
const match = routed?.route === "analysis" ? { kind: "stats-analysis", reason: "decision model", topics: methodTopicsIn(event.text) } : null;
|
|
1577
1988
|
const namesUserSkill = mentionsLoadedSkill(event.text, userSkillNames);
|
|
1578
1989
|
// The task often lives in a document the message names ("Read BRIEF.md"), not in the message itself.
|
|
1579
1990
|
const documents = namesUserSkill
|
|
@@ -1611,7 +2022,20 @@ export default function psyclawExtension(pi) {
|
|
|
1611
2022
|
}
|
|
1612
2023
|
catch { /* the process takeover still applies */ }
|
|
1613
2024
|
if (match) {
|
|
1614
|
-
|
|
2025
|
+
// Research mode: the takeover opens a plan in code, so approval and the run gate apply.
|
|
2026
|
+
let planLine = "";
|
|
2027
|
+
if (await readActiveProject(ctx.cwd).catch(() => null)) {
|
|
2028
|
+
const active = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
2029
|
+
if (!active || active.status === "completed") {
|
|
2030
|
+
const created = await writeAnalysisPlan(ctx.cwd, createAnalysisPlan({ goal: event.text.trim().slice(0, 300) }));
|
|
2031
|
+
planLine = `Plan ${created.id} is open for this request.`;
|
|
2032
|
+
}
|
|
2033
|
+
else {
|
|
2034
|
+
planLine = `Plan ${active.id} is open (status: ${active.status}).`;
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
const takeover = formatAnalysisPlanTakeover(event.text, block || undefined, { skillLoaded: skillLoaded(branchOf(ctx), "analysis-plan") });
|
|
2038
|
+
return { action: "transform", text: planLine ? `${takeover}\n\n${planLine}` : takeover };
|
|
1615
2039
|
}
|
|
1616
2040
|
if (block)
|
|
1617
2041
|
return { action: "transform", text: `${event.text.trim()}\n\n${block}` };
|
|
@@ -1620,13 +2044,146 @@ export default function psyclawExtension(pi) {
|
|
|
1620
2044
|
});
|
|
1621
2045
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
1622
2046
|
pi.on("context", (event) => {
|
|
1623
|
-
const messages = maskToolObservationsStable(event.messages);
|
|
2047
|
+
const messages = maskHeavyParts(maskToolObservationsStable(event.messages));
|
|
1624
2048
|
if (messages === event.messages)
|
|
1625
2049
|
return;
|
|
1626
2050
|
return { messages };
|
|
1627
2051
|
});
|
|
1628
2052
|
let dataAccessWarningShown = false;
|
|
1629
2053
|
const shellClock = new ShellClock();
|
|
2054
|
+
// Research mode: running a project script waits for plan approval. Exploration scripts
|
|
2055
|
+
// (explore/eda/profile/check/inspect/codebook in the name) still run; unattended runs are not gated.
|
|
2056
|
+
/** Approve the active plan from an approval card: same steps as a typed yes. Returns the new status. */
|
|
2057
|
+
async function approvePlanFromCard(cwd) {
|
|
2058
|
+
const plan = await readActiveAnalysisPlan(cwd).catch(() => null);
|
|
2059
|
+
if (!plan || !["awaiting-confirm", "ready", "reviewing"].includes(plan.status))
|
|
2060
|
+
return undefined;
|
|
2061
|
+
if ((await openDecisions(cwd, plan.id)).length > 0)
|
|
2062
|
+
return undefined;
|
|
2063
|
+
const method = plan.confirmedMethod || plan.primaryAnalysis || plan.proposedMethods[0] || "按当前方案执行";
|
|
2064
|
+
let next = plan.status === "awaiting-confirm" ? advanceAnalysisPlan(plan, { type: "confirm", method, backend: "local-script" }) : plan;
|
|
2065
|
+
next = advanceAnalysisPlan(next, { type: "ritual-approve", text: PLAN_RITUAL_PHRASE });
|
|
2066
|
+
if (next.status === "reviewing" || next.status === "awaiting-confirm")
|
|
2067
|
+
next = advanceAnalysisPlan(next, { type: "review" });
|
|
2068
|
+
next = advanceAnalysisPlan(next, { type: "run-now" });
|
|
2069
|
+
next = await writeAnalysisPlan(cwd, next);
|
|
2070
|
+
return next.status;
|
|
2071
|
+
}
|
|
2072
|
+
async function confirmatoryRunGate(ctx, script) {
|
|
2073
|
+
const mode = ctx.sessionManager ? restoreSessionMode(ctx.sessionManager) : sessionMode;
|
|
2074
|
+
if (mode !== "research" || ctx.hasUI !== true)
|
|
2075
|
+
return undefined;
|
|
2076
|
+
if (/explor|eda|profile|check|inspect|codebook/i.test(script))
|
|
2077
|
+
return undefined;
|
|
2078
|
+
const plan = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
2079
|
+
if (!plan || plan.status === "running" || plan.status === "completed" || (plan.approvalMode ?? "human") === "auto")
|
|
2080
|
+
return undefined;
|
|
2081
|
+
const open = await openDecisions(ctx.cwd, plan.id);
|
|
2082
|
+
return [
|
|
2083
|
+
`方案 ${plan.id} 还没批准(状态:${plan.status}),${script} 这类正式分析脚本先不跑。`,
|
|
2084
|
+
plan.status === "clarifying" || plan.status === "drafting"
|
|
2085
|
+
? "先用 psyclaw_plan action=submit 提交方案(主要结果、主分析、缺失值、多重比较、排除标准)。"
|
|
2086
|
+
: "",
|
|
2087
|
+
open.length ? `还有 ${open.length} 项决定待定:${open.map((d) => `${d.id}(${d.question})`).join(";")},用 psyclaw_ask 问研究者。` : "",
|
|
2088
|
+
"全部定好后请研究者回复「可以」批准方案。探索性脚本(文件名含 explore、eda、profile、check、inspect)可以照常跑。",
|
|
2089
|
+
].filter(Boolean).join("\n");
|
|
2090
|
+
}
|
|
2091
|
+
const scriptRuns = new Set(); // tool calls that ran a project script, for the decision-points notice
|
|
2092
|
+
const packageNet = new PackageNet();
|
|
2093
|
+
const installNotes = new Map();
|
|
2094
|
+
const installsRunning = new Map(); // package set -> log path
|
|
2095
|
+
// R (CRAN) and conda installs: same idea as pip/uv, the fastest route for this command only.
|
|
2096
|
+
const speedCache = new Map();
|
|
2097
|
+
const bestRoute = async (key, targets) => {
|
|
2098
|
+
const hit = speedCache.get(key);
|
|
2099
|
+
if (hit && Date.now() - hit.at < 30 * 60_000)
|
|
2100
|
+
return hit.best;
|
|
2101
|
+
const best = fastest(await probeSpeeds(targets).catch(() => []));
|
|
2102
|
+
speedCache.set(key, { at: Date.now(), best });
|
|
2103
|
+
return best;
|
|
2104
|
+
};
|
|
2105
|
+
async function routeOtherInstall(ctx, toolCallId, input, command) {
|
|
2106
|
+
if (typeof input.command !== "string")
|
|
2107
|
+
return;
|
|
2108
|
+
if (isRInstall(command)) {
|
|
2109
|
+
ctx.ui.notify("装包前测速:CRAN 和国内镜像…", "info");
|
|
2110
|
+
const best = await bestRoute("cran", cranTargets());
|
|
2111
|
+
if (!best || /cloud\.r-project\.org/.test(best.base) && !best.direct)
|
|
2112
|
+
return;
|
|
2113
|
+
const profile = join(tmpdir(), `psyclaw-cran-${best.base.replace(/[^a-z0-9]+/gi, "_")}.R`);
|
|
2114
|
+
writeFileSync(profile, cranProfile(best.base), "utf8");
|
|
2115
|
+
input.command = routeRCommand(command, best, profile);
|
|
2116
|
+
installNotes.set(toolCallId, `[psyclaw] 这次 R 装包走的是 ${best.route}(${best.base},实测 ${best.kb_s} KB/s;只对这条命令生效,你的 .Rprofile 照常读取)。`);
|
|
2117
|
+
return;
|
|
2118
|
+
}
|
|
2119
|
+
const channels = condaChannels(command);
|
|
2120
|
+
if (channels.length) {
|
|
2121
|
+
ctx.ui.notify("装包前测速:conda 频道和国内镜像…", "info");
|
|
2122
|
+
const best = await bestRoute(`conda:${channels[0]}`, condaTargets(channels[0]));
|
|
2123
|
+
if (!best || /anaconda\.org/.test(best.base) && !best.direct)
|
|
2124
|
+
return;
|
|
2125
|
+
input.command = /anaconda\.org/.test(best.base) ? `unset HTTPS_PROXY HTTP_PROXY https_proxy http_proxy ALL_PROXY all_proxy; ${command}` : routeCondaCommand(command, best);
|
|
2126
|
+
installNotes.set(toolCallId, `[psyclaw] 这次 conda 装包走的是 ${best.route}(实测 ${best.kb_s} KB/s;只对这条命令生效,频道不变)。`);
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
// Package installs: measure PyPI and mirrors once, run this command through the fastest route,
|
|
2130
|
+
// and ask the researcher first when it would still be slow. No global pip/uv config is written.
|
|
2131
|
+
async function routePackageInstall(ctx, toolCallId, input, command, install) {
|
|
2132
|
+
if (typeof input.command !== "string")
|
|
2133
|
+
return undefined;
|
|
2134
|
+
const names = install.packages.join(" ") || "(包名未解析)";
|
|
2135
|
+
const key = [...install.packages].sort().join(" ");
|
|
2136
|
+
const running = key ? installsRunning.get(key) : undefined;
|
|
2137
|
+
if (running) {
|
|
2138
|
+
input.command = `echo ${shellQuote(`[psyclaw] ${names} 已在后台安装中(日志 ${running})。装完会自动通知你;先做不依赖它们的工作,不要重复安装,也不要 sleep 等待。`)}`;
|
|
2139
|
+
return undefined;
|
|
2140
|
+
}
|
|
2141
|
+
ctx.ui.notify("装包前测速:PyPI 和国内镜像…", "info");
|
|
2142
|
+
const report = await packageNet.check(install).catch(() => undefined);
|
|
2143
|
+
if (!report)
|
|
2144
|
+
return undefined;
|
|
2145
|
+
if (!report.best) {
|
|
2146
|
+
return { block: true, reason: `[psyclaw] 装包前测速:PyPI 和镜像都连不上(${names})。不要重试;告诉研究者,或用已有的退回方案继续。` };
|
|
2147
|
+
}
|
|
2148
|
+
const routed = routeCommand(command, report.best);
|
|
2149
|
+
if (report.ask_researcher_first && ctx.hasUI) {
|
|
2150
|
+
const now = `现在装(${describeRoute(report)})`;
|
|
2151
|
+
const skip = "跳过,用退回方案";
|
|
2152
|
+
const later = "我以后自己装";
|
|
2153
|
+
const choice = await ctx.ui.select(`装包前确认:${names}`, [now, skip, later], { timeout: 120_000 });
|
|
2154
|
+
if (choice === skip) {
|
|
2155
|
+
return { block: true, reason: `[psyclaw] 研究者选择不装 ${names}。不要再尝试安装;用退回方案继续,并在小结里说明。` };
|
|
2156
|
+
}
|
|
2157
|
+
if (choice === later) {
|
|
2158
|
+
return { block: true, reason: `[psyclaw] 研究者会以后自己装 ${names}。不要再尝试安装;把这条命令写进小结:${routed}` };
|
|
2159
|
+
}
|
|
2160
|
+
}
|
|
2161
|
+
if (ctx.hasUI && key && (report.best.minutes ?? 0) >= backgroundInstallMinutes()) {
|
|
2162
|
+
const log = join(ctx.cwd, ".psyclaw", "installs", `${toolCallId.replace(/[^\w-]/g, "_")}.log`);
|
|
2163
|
+
installsRunning.set(key, log);
|
|
2164
|
+
const route = describeRoute(report);
|
|
2165
|
+
startBackgroundInstall(routed, ctx.cwd, log, (result) => {
|
|
2166
|
+
installsRunning.delete(key);
|
|
2167
|
+
const ok = result.code === 0;
|
|
2168
|
+
const text = ok
|
|
2169
|
+
? `[psyclaw] 后台安装完成:${names}(${route},用时 ${result.seconds} 秒)。现在可以使用这些包;先导入一次确认。`
|
|
2170
|
+
: `[psyclaw] 后台安装失败:${names}(退出码 ${result.code ?? "无"},用时 ${result.seconds} 秒)。日志末尾:\n${result.tail}\n不要原样重试;告诉研究者,或用退回方案继续。`;
|
|
2171
|
+
ctx.ui.notify(ok ? `后台安装完成:${names}` : `后台安装失败:${names}`, ok ? "info" : "warning");
|
|
2172
|
+
try {
|
|
2173
|
+
pi.sendMessage({ customType: "psyclaw-install-done", content: text, display: true }, ctx.isIdle() ? { triggerTurn: true } : { deliverAs: "steer" });
|
|
2174
|
+
}
|
|
2175
|
+
catch { /* session closed: the notify above is enough */ }
|
|
2176
|
+
});
|
|
2177
|
+
input.command = `echo ${shellQuote(`[psyclaw] 已在后台开始安装 ${names}(${route},只对这条命令生效;日志 ${log})。装完会自动通知你。在那之前先做不依赖这些包的工作;不要 sleep 等待,不要重复安装,也不要导入它们。`)}`;
|
|
2178
|
+
return undefined;
|
|
2179
|
+
}
|
|
2180
|
+
input.command = routed;
|
|
2181
|
+
const seconds = installTimeoutSeconds(report.best.minutes);
|
|
2182
|
+
if (seconds !== undefined)
|
|
2183
|
+
input.timeout = Math.max(typeof input.timeout === "number" ? input.timeout : 0, seconds);
|
|
2184
|
+
installNotes.set(toolCallId, `[psyclaw] 这次装包走的是 ${describeRoute(report)}(只对这条命令生效)。`);
|
|
2185
|
+
return undefined;
|
|
2186
|
+
}
|
|
1630
2187
|
if (!legacyTestApi && typeof pi.on === "function")
|
|
1631
2188
|
pi.on("tool_call", async (event, ctx) => {
|
|
1632
2189
|
// Host-teardown hard block runs even without /init — project approvals do not cover this.
|
|
@@ -1639,8 +2196,46 @@ export default function psyclawExtension(pi) {
|
|
|
1639
2196
|
return { block: true, terminate: true, reason };
|
|
1640
2197
|
}
|
|
1641
2198
|
}
|
|
2199
|
+
const placeholder = maskedPlaceholderReason(event.toolName, event.input);
|
|
2200
|
+
if (placeholder)
|
|
2201
|
+
return { block: true, reason: placeholder };
|
|
2202
|
+
// analysis/spec.json and spec.md are written by code only (psyclaw_spec).
|
|
2203
|
+
const specPath = /analysis\/spec\.(json|md)/;
|
|
2204
|
+
const writesSpec = (event.toolName === "write" || event.toolName === "edit")
|
|
2205
|
+
? specPath.test(String(event.input?.path ?? ""))
|
|
2206
|
+
: event.toolName === "bash" && specPath.test(commandText ?? "") && /(>|\btee\b|\bsed\s+-i|\bmv\b|\bcp\b|\brm\b|open\([^)]*["']w)/.test(commandText ?? "");
|
|
2207
|
+
if (writesSpec)
|
|
2208
|
+
return { block: true, reason: `${SPEC_JSON} and ${SPEC_MD} are written by code; use psyclaw_spec.` };
|
|
2209
|
+
moveTimeoutPrefix(event.toolName, event.input);
|
|
1642
2210
|
applyShellTimeout(event.toolName, event.input);
|
|
2211
|
+
const script = event.toolName === "bash" && commandText ? scriptInCommand(commandText) : undefined;
|
|
2212
|
+
const currentMode = restoreSessionMode(ctx.sessionManager);
|
|
2213
|
+
if (currentMode === "estimand" && ["bash", "write", "edit"].includes(event.toolName))
|
|
2214
|
+
estimandWorkStarted = true;
|
|
2215
|
+
if (script) {
|
|
2216
|
+
const refusal = await confirmatoryRunGate(ctx, script);
|
|
2217
|
+
if (refusal)
|
|
2218
|
+
return { block: true, reason: refusal };
|
|
2219
|
+
// Analysis mode: analysis scripts wait until at least one estimand is confirmed (exploration still runs).
|
|
2220
|
+
if (currentMode === "estimand" && !/explor|eda|profile|check|inspect|codebook/i.test(script)) {
|
|
2221
|
+
const spec = loadSpec(ctx.cwd);
|
|
2222
|
+
const confirmed = spec ? Object.values(spec.estimands).some((e) => e.confirmed_at) : false;
|
|
2223
|
+
if (!confirmed) {
|
|
2224
|
+
return { block: true, reason: `[psyclaw] Analysis mode: write the estimands with psyclaw_spec action=write and confirm them with action=confirm before running analysis scripts such as ${script}. Exploration scripts (explore, eda, profile, check in the name) can run now.` };
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
scriptRuns.add(event.toolCallId);
|
|
2228
|
+
}
|
|
1643
2229
|
shellClock.start(event.toolName, event.toolCallId, commandText);
|
|
2230
|
+
const install = event.toolName === "bash" && commandText ? parsePipInstall(commandText) : undefined;
|
|
2231
|
+
if (install && commandText) {
|
|
2232
|
+
const routed = await routePackageInstall(ctx, event.toolCallId, event.input, commandText, install);
|
|
2233
|
+
if (routed)
|
|
2234
|
+
return routed;
|
|
2235
|
+
}
|
|
2236
|
+
else if (event.toolName === "bash" && commandText) {
|
|
2237
|
+
await routeOtherInstall(ctx, event.toolCallId, event.input, commandText);
|
|
2238
|
+
}
|
|
1644
2239
|
try {
|
|
1645
2240
|
const access = await loadDataAccess(ctx.cwd);
|
|
1646
2241
|
if (access.warning && !dataAccessWarningShown) {
|
|
@@ -1656,22 +2251,6 @@ export default function psyclawExtension(pi) {
|
|
|
1656
2251
|
catch {
|
|
1657
2252
|
// A broken checker must not take down unrelated tools. Defaults still apply on the next call.
|
|
1658
2253
|
}
|
|
1659
|
-
if (sessionMode === "prior") {
|
|
1660
|
-
try {
|
|
1661
|
-
const priorReason = priorToolBlock(sessionMode, event.toolName, event.input, {
|
|
1662
|
-
recallReady: await priorRecallExists(ctx.cwd),
|
|
1663
|
-
planReady: await priorPlanExists(ctx.cwd),
|
|
1664
|
-
approved: await priorApproved(ctx.cwd),
|
|
1665
|
-
});
|
|
1666
|
-
if (priorReason) {
|
|
1667
|
-
ctx.ui.notify(priorReason, "warning");
|
|
1668
|
-
return { block: true, reason: priorReason };
|
|
1669
|
-
}
|
|
1670
|
-
}
|
|
1671
|
-
catch {
|
|
1672
|
-
// A broken prior gate must not take down unrelated tools.
|
|
1673
|
-
}
|
|
1674
|
-
}
|
|
1675
2254
|
const run = await readActiveProject(ctx.cwd);
|
|
1676
2255
|
if (!run || !toolNeedsApproval(event.toolName, event.input))
|
|
1677
2256
|
return;
|
|
@@ -1721,10 +2300,14 @@ export default function psyclawExtension(pi) {
|
|
|
1721
2300
|
const timedOutIndex = content.findIndex((part) => part.type === "text" && isShellTimeout(event.toolName, part.text));
|
|
1722
2301
|
const timedOut = content[timedOutIndex];
|
|
1723
2302
|
if (timedOut?.type === "text") {
|
|
1724
|
-
content[timedOutIndex] = { ...timedOut, text: `${timedOut.text}\n${
|
|
2303
|
+
content[timedOutIndex] = { ...timedOut, text: `${timedOut.text}\n${shellClock.timeoutHint(event.toolCallId)}` };
|
|
1725
2304
|
changed = true;
|
|
1726
2305
|
}
|
|
1727
|
-
const
|
|
2306
|
+
const installNote = installNotes.get(event.toolCallId);
|
|
2307
|
+
installNotes.delete(event.toolCallId);
|
|
2308
|
+
const ranScript = scriptRuns.delete(event.toolCallId);
|
|
2309
|
+
const decisionNote = ranScript ? await decisionPointsNotice(ctx.cwd).catch(() => undefined) : undefined;
|
|
2310
|
+
const timing = [installNote, shellClock.finish(event.toolCallId), decisionNote, shellClock.budgetNote()].filter(Boolean).join("\n") || undefined;
|
|
1728
2311
|
const lastText = content.map((part) => part.type).lastIndexOf("text");
|
|
1729
2312
|
const last = content[lastText];
|
|
1730
2313
|
if (timing && last?.type === "text") {
|
|
@@ -1746,6 +2329,19 @@ export default function psyclawExtension(pi) {
|
|
|
1746
2329
|
}
|
|
1747
2330
|
}
|
|
1748
2331
|
}
|
|
2332
|
+
// Research mode: reading a user-installed skill's SKILL.md gets the reference-material note.
|
|
2333
|
+
if (sessionMode === "research" && event.toolName === "read" && !event.isError) {
|
|
2334
|
+
const path = String(event.input?.path ?? "");
|
|
2335
|
+
if (/SKILL\.md$/i.test(path)) {
|
|
2336
|
+
const local = await enabledLocalSkillPaths(ctx.cwd, { excludedNames: coreSkillNames() }).catch(() => undefined);
|
|
2337
|
+
const at = content.map((part) => part.type).lastIndexOf("text");
|
|
2338
|
+
const part = content[at];
|
|
2339
|
+
if (local && isUserSkillFile(ctx.cwd, path, local.paths) && part?.type === "text") {
|
|
2340
|
+
content[at] = { ...part, text: withResearchSkillNote(part.text) };
|
|
2341
|
+
changed = true;
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
1749
2345
|
if (!changed)
|
|
1750
2346
|
return;
|
|
1751
2347
|
return { content };
|
|
@@ -1776,21 +2372,23 @@ export default function psyclawExtension(pi) {
|
|
|
1776
2372
|
...(parsed.goal === undefined ? {} : { goal: parsed.goal }),
|
|
1777
2373
|
...(parsed.paradigm === undefined ? {} : { paradigm: parsed.paradigm }),
|
|
1778
2374
|
});
|
|
2375
|
+
applySessionMode("research");
|
|
1779
2376
|
if (already || hadProject) {
|
|
1780
2377
|
ctx.ui.notify([
|
|
1781
2378
|
`已检测到既有工作区,无需重新建仓:${project.id}`,
|
|
1782
|
-
"规范目录与 psyclaw.md
|
|
1783
|
-
"
|
|
2379
|
+
"规范目录与 psyclaw.md 已存在;跨会话可直接继续分析或写作。",
|
|
2380
|
+
"还没想好研究问题?/ars brainstorm 一起想问题;/ars grill 把想法逐条问清楚。",
|
|
2381
|
+
"当前为研究模式;Shift+Tab 切换基础模式 / 研究模式。输入 /help 查看速览。",
|
|
1784
2382
|
].join("\n"), "info");
|
|
1785
2383
|
return;
|
|
1786
2384
|
}
|
|
1787
2385
|
ctx.ui.notify([
|
|
1788
2386
|
`工作仓库已初始化:${project.id}`,
|
|
1789
2387
|
"已创建 data/raw|clean|secret、analysis/、literature/、paper/、psyclaw.md、.psyclaw/",
|
|
1790
|
-
"data/secret 默认 script-only:模型不能直接读内容,分析脚本可以打开。/
|
|
1791
|
-
"
|
|
1792
|
-
"
|
|
1793
|
-
"
|
|
2388
|
+
"data/secret 默认 script-only:模型不能直接读内容,分析脚本可以打开。/secret 可改级别或指定其他文件。",
|
|
2389
|
+
"研究模式:分析、写作、审稿都在同一个对话里,按你说的事走对应流程。",
|
|
2390
|
+
"还没想好研究问题?/ars brainstorm 从数据里一起想几个可做的问题;/ars grill 把一个初步想法逐条问清楚。直接说“想用这份数据写文章”也会先走这一步。",
|
|
2391
|
+
"Shift+Tab:基础模式 / 研究模式 · Thinking:Ctrl+Shift+T · /help 查看速览。",
|
|
1794
2392
|
].join("\n"), "info");
|
|
1795
2393
|
}
|
|
1796
2394
|
catch (error) {
|
|
@@ -1798,23 +2396,40 @@ export default function psyclawExtension(pi) {
|
|
|
1798
2396
|
}
|
|
1799
2397
|
},
|
|
1800
2398
|
});
|
|
1801
|
-
pi.registerCommand("
|
|
1802
|
-
description: "
|
|
2399
|
+
pi.registerCommand("secret", {
|
|
2400
|
+
description: "数据文件只许脚本读:/secret <文件> 设置,/secret off <文件> 取消,/secret list 查看全部;消息里写 @文件:s 也可以",
|
|
1803
2401
|
handler: async (args, ctx) => {
|
|
1804
2402
|
try {
|
|
1805
2403
|
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
1806
2404
|
if (parts.length === 0) {
|
|
2405
|
+
const loaded = await loadDataAccess(ctx.cwd);
|
|
2406
|
+
const secret = loaded.entries.filter((entry) => entry.access === "script-only").map((entry) => entry.path);
|
|
2407
|
+
ctx.ui.notify([`只许脚本读的文件:${secret.join("、") || "无"}`, "设置:/secret <文件>;取消:/secret off <文件>;全部访问级别:/secret list;消息里写 @文件:s 也可以。", loaded.warning].filter(Boolean).join("\n"), loaded.warning ? "warning" : "info");
|
|
2408
|
+
return;
|
|
2409
|
+
}
|
|
2410
|
+
if (parts[0] === "list" && parts.length === 1) {
|
|
1807
2411
|
const loaded = await loadDataAccess(ctx.cwd);
|
|
1808
2412
|
ctx.ui.notify([formatDataAccess(loaded.entries), loaded.warning].filter(Boolean).join("\n"), loaded.warning ? "warning" : "info");
|
|
1809
2413
|
return;
|
|
1810
2414
|
}
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
2415
|
+
if (parts[0] === "off" || parts[0] === "full") {
|
|
2416
|
+
const targets = parts.slice(1).map((p) => p.replace(/^@/, "").replace(/:s$/, ""));
|
|
2417
|
+
if (!targets.length) {
|
|
2418
|
+
ctx.ui.notify("用法:/secret off <文件>", "error");
|
|
2419
|
+
return;
|
|
2420
|
+
}
|
|
2421
|
+
for (const target of targets)
|
|
2422
|
+
await setDataAccess(ctx.cwd, target, "full");
|
|
2423
|
+
await refreshEditorSecrets(ctx.cwd);
|
|
2424
|
+
ctx.ui.notify(`已取消只许脚本读:${targets.join("、")}`, "info");
|
|
1814
2425
|
return;
|
|
1815
2426
|
}
|
|
1816
|
-
const
|
|
1817
|
-
ctx.
|
|
2427
|
+
const result = await markScriptOnly(ctx.cwd, parts.map((p) => p.replace(/^@/, "").replace(/:s$/, "")));
|
|
2428
|
+
await refreshEditorSecrets(ctx.cwd);
|
|
2429
|
+
if (result.marked.length)
|
|
2430
|
+
ctx.ui.notify(`已设为只许脚本读:${result.marked.join("、")}`, "info");
|
|
2431
|
+
for (const failed of result.failed)
|
|
2432
|
+
ctx.ui.notify(`没能标记 ${failed.path}:${failed.reason}`, "warning");
|
|
1818
2433
|
}
|
|
1819
2434
|
catch (error) {
|
|
1820
2435
|
await notifyError(ctx, error);
|
|
@@ -1828,13 +2443,14 @@ export default function psyclawExtension(pi) {
|
|
|
1828
2443
|
if (!focus) {
|
|
1829
2444
|
ctx.ui.notify([
|
|
1830
2445
|
formatVerifyChecklist(await loadVerifyChecklist(ctx.cwd)),
|
|
1831
|
-
"/
|
|
1832
|
-
"
|
|
2446
|
+
"/check quick <焦点>:过程核对(数据、引文是否真实存在、格式/报告要求等)。",
|
|
2447
|
+
"/check full <焦点>:整体验证(分析结果是否成立、引文是否合理、方法是否合理)。",
|
|
2448
|
+
"人审不经斜杠命令:收尾门禁会要求 Panel「核实」或选择框。",
|
|
1833
2449
|
].join("\n"), "info");
|
|
1834
2450
|
return;
|
|
1835
2451
|
}
|
|
1836
2452
|
pi.sendUserMessage([
|
|
1837
|
-
"/
|
|
2453
|
+
"/check quick — 过程性交叉核对(AI)。",
|
|
1838
2454
|
`焦点:${focus}`,
|
|
1839
2455
|
"范围重点:",
|
|
1840
2456
|
"1) 数据与表:字段、N、表内数值与脚本/输出是否过程一致;",
|
|
@@ -1842,9 +2458,9 @@ export default function psyclawExtension(pi) {
|
|
|
1842
2458
|
"3) 格式与报告要求:APA/三线表/必备报告字段、清单项是否齐;",
|
|
1843
2459
|
"4) 过程产物:脚本入口、中间文件、可复现痕迹是否齐全。",
|
|
1844
2460
|
"执行方式:派出至少两个独立审查视角(例如:数据一致性;引文存在性;格式/报告合同),各自给出发现后再合并为一份报告;标出一致项与冲突项。",
|
|
1845
|
-
"不得自称已过人审。不要在用户未明确同意前自动启动本核对。人审由系统在交接/定稿门禁自动要求,经 Panel
|
|
2461
|
+
"不得自称已过人审。不要在用户未明确同意前自动启动本核对。人审由系统在交接/定稿门禁自动要求,经 Panel「核实」或选择框完成。",
|
|
1846
2462
|
].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
1847
|
-
ctx.ui.notify(
|
|
2463
|
+
ctx.ui.notify(`已启动过程核对 /check quick(焦点:${focus})。大段核对应先征得用户同意。`, "info");
|
|
1848
2464
|
}
|
|
1849
2465
|
catch (error) {
|
|
1850
2466
|
await notifyError(ctx, error);
|
|
@@ -1857,13 +2473,13 @@ export default function psyclawExtension(pi) {
|
|
|
1857
2473
|
if (!focus) {
|
|
1858
2474
|
ctx.ui.notify([
|
|
1859
2475
|
formatVerifyChecklist(await loadVerifyChecklist(ctx.cwd)),
|
|
1860
|
-
"/
|
|
1861
|
-
"人审不经斜杠命令:Panel
|
|
2476
|
+
"/check full <焦点>:整体验证(分析结果是否属实/成立、引文是否合理、方法是否合理)。",
|
|
2477
|
+
"人审不经斜杠命令:Panel「核实」或选择框。",
|
|
1862
2478
|
].join("\n"), "info");
|
|
1863
2479
|
return;
|
|
1864
2480
|
}
|
|
1865
2481
|
pi.sendUserMessage([
|
|
1866
|
-
"/
|
|
2482
|
+
"/check full — 整体性实质验证(AI)。",
|
|
1867
2483
|
`焦点:${focus}`,
|
|
1868
2484
|
"范围重点:",
|
|
1869
2485
|
"1) 分析结果是否属实、是否成立:效应方向/量级、不确定性、与脚本输出是否支持正文主张;",
|
|
@@ -1871,21 +2487,30 @@ export default function psyclawExtension(pi) {
|
|
|
1871
2487
|
"3) 方法是否合理:设计、估计目标、检验/模型选择与研究问题是否匹配;",
|
|
1872
2488
|
"4) 解释边界:相关≠因果、探索/确证区分、过度声称。",
|
|
1873
2489
|
"给出可核对的判断(成立 / 存疑 / 不成立)及依据;不得自称已过人审。",
|
|
1874
|
-
"人审由交接/定稿门禁自动要求,经 Panel
|
|
2490
|
+
"人审由交接/定稿门禁自动要求,经 Panel「核实」或选择框完成。",
|
|
1875
2491
|
].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
1876
|
-
ctx.ui.notify(
|
|
2492
|
+
ctx.ui.notify(`已启动整体验证 /check full(焦点:${focus})。人审由收尾门禁自动要求。`, "info");
|
|
1877
2493
|
}
|
|
1878
2494
|
catch (error) {
|
|
1879
2495
|
await notifyError(ctx, error);
|
|
1880
2496
|
}
|
|
1881
2497
|
};
|
|
1882
|
-
pi.registerCommand("
|
|
1883
|
-
description: "
|
|
1884
|
-
handler: async (args, ctx) =>
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
2498
|
+
pi.registerCommand("check", {
|
|
2499
|
+
description: "AI 核对:/check quick <焦点> 查数据、引文、格式;/check full <焦点> 查结果、引文、方法是否成立",
|
|
2500
|
+
handler: async (args, ctx) => {
|
|
2501
|
+
const trimmed = args.trim();
|
|
2502
|
+
const [sub = "", ...rest] = trimmed.split(/\s+/);
|
|
2503
|
+
const focus = rest.join(" ");
|
|
2504
|
+
if (sub === "quick")
|
|
2505
|
+
return handleCrosscheck(focus, ctx);
|
|
2506
|
+
if (sub === "full")
|
|
2507
|
+
return handleVerify(focus, ctx);
|
|
2508
|
+
if (trimmed) {
|
|
2509
|
+
ctx.ui.notify("用法:/check quick <焦点>(过程核对)或 /check full <焦点>(整体验证);只输入 /check 查看核对清单。", "error");
|
|
2510
|
+
return;
|
|
2511
|
+
}
|
|
2512
|
+
return handleCrosscheck("", ctx);
|
|
2513
|
+
},
|
|
1889
2514
|
});
|
|
1890
2515
|
pi.registerCommand("help", {
|
|
1891
2516
|
description: "打开 Panel 使用速览",
|
|
@@ -1906,27 +2531,37 @@ export default function psyclawExtension(pi) {
|
|
|
1906
2531
|
},
|
|
1907
2532
|
});
|
|
1908
2533
|
pi.registerCommand("plan", {
|
|
1909
|
-
description: "
|
|
2534
|
+
description: "分析方案:/plan 查看状态,/plan <目标> 新建,/plan auto 不经人审批,/plan human 恢复人审",
|
|
1910
2535
|
handler: async (args, ctx) => {
|
|
1911
2536
|
try {
|
|
1912
2537
|
const goal = args.trim();
|
|
2538
|
+
if (goal === "auto" || goal === "human") {
|
|
2539
|
+
const active = await readActiveAnalysisPlan(ctx.cwd);
|
|
2540
|
+
if (!active) {
|
|
2541
|
+
ctx.ui.notify("没有活跃分析方案。先在研究模式里说要分析什么,或 /plan <目标>。", "info");
|
|
2542
|
+
return;
|
|
2543
|
+
}
|
|
2544
|
+
const next = await writeAnalysisPlan(ctx.cwd, advanceAnalysisPlan(active, { type: "set-approval-mode", mode: goal }));
|
|
2545
|
+
ctx.ui.notify(goal === "auto"
|
|
2546
|
+
? `${formatAnalysisPlanStatus(next)}\n已改为不经人审批:正式分析不再等你批准,所有结果都会标注「未经人审批」。/plan human 恢复。`
|
|
2547
|
+
: `${formatAnalysisPlanStatus(next)}\n已恢复人审:正式分析要等你批准方案。`, "info");
|
|
2548
|
+
return;
|
|
2549
|
+
}
|
|
1913
2550
|
if (goal) {
|
|
1914
2551
|
const plan = await writeAnalysisPlan(ctx.cwd, createAnalysisPlan({ goal }));
|
|
1915
2552
|
ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已按目标创建。用自然语言确认方法(如「可以」);完成后用 /handoff 交接。`, "info");
|
|
1916
|
-
pi.sendUserMessage([
|
|
1917
|
-
"/skill:analysis-plan",
|
|
1918
|
-
"",
|
|
2553
|
+
pi.sendUserMessage(invokeSkill("analysis-plan", [
|
|
1919
2554
|
`Active plan ${plan.id} created for goal: ${goal}`,
|
|
1920
2555
|
"Clarify methods with the researcher; prefer natural-language confirmation. Do not invent numbers.",
|
|
1921
|
-
].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
2556
|
+
].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")), { expandPromptTemplates: true, ...(ctx.isIdle() ? {} : { deliverAs: "followUp" }) });
|
|
1922
2557
|
return;
|
|
1923
2558
|
}
|
|
1924
2559
|
const plan = await readActiveAnalysisPlan(ctx.cwd);
|
|
1925
2560
|
if (!plan) {
|
|
1926
|
-
ctx.ui.notify("没有活跃分析 Plan。用 /plan <目标>
|
|
2561
|
+
ctx.ui.notify("没有活跃分析 Plan。用 /plan <目标> 创建,或在研究模式里直接说要分析什么。", "info");
|
|
1927
2562
|
return;
|
|
1928
2563
|
}
|
|
1929
|
-
ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n确认与执行请用自然语言;交接用 /handoff。`, "info");
|
|
2564
|
+
ctx.ui.notify(`${formatAnalysisPlanStatus(plan, (await openDecisions(ctx.cwd, plan.id)).length)}\n${formatDecisionsBrief(await readDecisions(ctx.cwd))}\n确认与执行请用自然语言;交接用 /handoff。`, "info");
|
|
1930
2565
|
}
|
|
1931
2566
|
catch (error) {
|
|
1932
2567
|
await notifyError(ctx, error);
|
|
@@ -1944,7 +2579,7 @@ export default function psyclawExtension(pi) {
|
|
|
1944
2579
|
}
|
|
1945
2580
|
let plan = await readActiveAnalysisPlan(ctx.cwd);
|
|
1946
2581
|
if (!plan) {
|
|
1947
|
-
ctx.ui.notify("没有活跃分析 Plan,无法交接。先 /plan
|
|
2582
|
+
ctx.ui.notify("没有活跃分析 Plan,无法交接。先 /plan <目标>,或在研究模式里推进分析。", "warning");
|
|
1948
2583
|
return;
|
|
1949
2584
|
}
|
|
1950
2585
|
const path = await syncHandoffFromAnalysisPlan(ctx.cwd, plan);
|
|
@@ -1954,131 +2589,154 @@ export default function psyclawExtension(pi) {
|
|
|
1954
2589
|
: { type: "complete" });
|
|
1955
2590
|
plan = await writeAnalysisPlan(ctx.cwd, plan);
|
|
1956
2591
|
}
|
|
1957
|
-
ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已写入 ${path}
|
|
2592
|
+
ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已写入 ${path}。可以接着写论文。`, "info");
|
|
1958
2593
|
}
|
|
1959
2594
|
catch (error) {
|
|
1960
2595
|
await notifyError(ctx, error);
|
|
1961
2596
|
}
|
|
1962
2597
|
},
|
|
1963
2598
|
});
|
|
2599
|
+
const ars_grillCommand = {
|
|
2600
|
+
description: "逐题追问并压力测试学术研究方案",
|
|
2601
|
+
handler: async (args, ctx) => {
|
|
2602
|
+
const subject = args.trim();
|
|
2603
|
+
pi.sendUserMessage(academicGrillRequest(subject, "review"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
2604
|
+
ctx.ui.notify("已启动学术追问。完成后会先展示文档更新建议,并询问是否写回。", "info");
|
|
2605
|
+
},
|
|
2606
|
+
};
|
|
2607
|
+
const ars_brainstormCommand = {
|
|
2608
|
+
description: "研究方向头脑风暴:提出并比较可选问题",
|
|
2609
|
+
handler: async (args, ctx) => {
|
|
2610
|
+
const subject = args.trim();
|
|
2611
|
+
pi.sendUserMessage(academicBrainstormRequest(subject), ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
2612
|
+
ctx.ui.notify("已启动研究方向头脑风暴。", "info");
|
|
2613
|
+
},
|
|
2614
|
+
};
|
|
2615
|
+
const ars_reviewCommand = {
|
|
2616
|
+
description: "并发运行多角色模拟同行评审",
|
|
2617
|
+
handler: async (_args, ctx) => {
|
|
2618
|
+
if (activeAgentRuns.has(ctx.cwd)) {
|
|
2619
|
+
ctx.ui.notify("当前项目已有一个多智能体任务正在运行", "warning");
|
|
2620
|
+
return;
|
|
2621
|
+
}
|
|
2622
|
+
try {
|
|
2623
|
+
const project = await readProject(ctx.cwd);
|
|
2624
|
+
if (!(await readActiveProject(ctx.cwd))) {
|
|
2625
|
+
ctx.ui.notify("请先使用 /init 初始化研究项目;未建仓时不会自动执行同行评审。", "warning");
|
|
2626
|
+
return;
|
|
2627
|
+
}
|
|
2628
|
+
const reviewSkill = _args.trim();
|
|
2629
|
+
activeAgentRuns.add(ctx.cwd);
|
|
2630
|
+
ctx.ui.notify(`正在使用${reviewSkill?.trim() ? ` Skill“${reviewSkill.trim()}”辅助的` : "默认"} 4 角色并发模拟评审;不会自动改稿。`, "info");
|
|
2631
|
+
const result = await runParallelPeerReview({
|
|
2632
|
+
root: ctx.cwd,
|
|
2633
|
+
project,
|
|
2634
|
+
...(ctx.model?.provider === undefined ? {} : { provider: ctx.model.provider }),
|
|
2635
|
+
...(ctx.model?.id === undefined ? {} : { model: ctx.model.id }),
|
|
2636
|
+
env: providerEnvironment(ctx.model?.provider),
|
|
2637
|
+
...(reviewSkill ? { skillGuidance: reviewSkill } : {}),
|
|
2638
|
+
onEvent: async (event) => { await new RunEventLog(ctx.cwd, event.runId).append(event); },
|
|
2639
|
+
});
|
|
2640
|
+
pi.appendEntry("psyclaw:multi-agent-review", {
|
|
2641
|
+
runId: result.runId,
|
|
2642
|
+
status: result.status,
|
|
2643
|
+
outputPath: result.outputPath,
|
|
2644
|
+
adoption: "review-output-only",
|
|
2645
|
+
recordedAt: new Date().toISOString(),
|
|
2646
|
+
});
|
|
2647
|
+
ctx.ui.notify(`模拟审稿${result.status === "completed" ? "已完成" : "未完整完成"}:${result.outputPath}。审稿意见仅供研究者决定是否采纳。`, result.status === "completed" ? "info" : "warning");
|
|
2648
|
+
}
|
|
2649
|
+
catch (error) {
|
|
2650
|
+
await notifyError(ctx, error);
|
|
2651
|
+
}
|
|
2652
|
+
finally {
|
|
2653
|
+
activeAgentRuns.delete(ctx.cwd);
|
|
2654
|
+
}
|
|
2655
|
+
},
|
|
2656
|
+
};
|
|
2657
|
+
const ars_loopCommand = {
|
|
2658
|
+
description: "按计划循环推进当前研究阶段",
|
|
2659
|
+
handler: async (args, ctx) => {
|
|
2660
|
+
const requested = args.trim();
|
|
2661
|
+
if (requested.toLowerCase() === "stop") {
|
|
2662
|
+
if (ctx.isIdle())
|
|
2663
|
+
ctx.ui.notify("当前没有正在运行的研究循环", "info");
|
|
2664
|
+
else {
|
|
2665
|
+
ctx.abort();
|
|
2666
|
+
ctx.ui.notify("已请求停止当前研究循环", "warning");
|
|
2667
|
+
}
|
|
2668
|
+
return;
|
|
2669
|
+
}
|
|
2670
|
+
let project;
|
|
2671
|
+
try {
|
|
2672
|
+
project = await readProject(ctx.cwd);
|
|
2673
|
+
}
|
|
2674
|
+
catch {
|
|
2675
|
+
ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /ars loop", "warning");
|
|
2676
|
+
return;
|
|
2677
|
+
}
|
|
2678
|
+
if (!(await readActiveProject(ctx.cwd))) {
|
|
2679
|
+
ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /ars loop。", "warning");
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
const objective = requested || project.goal;
|
|
2683
|
+
const request = [
|
|
2684
|
+
"运行一个有边界的 PsyClaw 研究循环,采用计划、执行、检查、修正的顺序推进当前研究阶段。",
|
|
2685
|
+
`本轮目标:${objective}`,
|
|
2686
|
+
"开始前读取 .psyclaw/project.json、notes/goal.md 和 notes/plan.md;如果当前对话或项目中存在经研究者确认的 /ars grill 研究规格,以该规格细化初始计划,但不得违反系统规则、AGENTS.md 或研究门禁。",
|
|
2687
|
+
"先识别当前最高优先级且前提已满足的一个任务,再使用可用工具实际推进。不要只描述准备做什么。普通项目文件写入、脚本和可恢复工具调用在已 /init 的项目中连续推进;原始数据覆盖、凭据、外部发布、破坏性操作仍遵守单独的安全边界。",
|
|
2688
|
+
"每完成一个实质步骤就检查产物、证据和计划是否一致。缺失信息若能检索、计算、重跑、改写或明确标注,应先自行修复。只有存在会改变研究问题、样本处理、操作化、估计目标、方法或解释的实质分歧时才请求研究者取舍;权限边界、不可恢复错误或当前阶段完成时停止。不得为了继续循环而虚构输入或结论。",
|
|
2689
|
+
"本次最多推进一个可验收的研究阶段。结束时简要报告已完成、已核验、阻塞、计划变化和下一步;规划内容不得表述为已有研究证据。",
|
|
2690
|
+
].join("\n");
|
|
2691
|
+
pi.sendUserMessage(request, ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
2692
|
+
ctx.ui.notify("已启动有界研究循环;使用 /ars loop stop 可请求中止", "info");
|
|
2693
|
+
},
|
|
2694
|
+
};
|
|
1964
2695
|
if (!legacyTestApi)
|
|
1965
|
-
pi.registerCommand("
|
|
1966
|
-
description: "
|
|
2696
|
+
pi.registerCommand("create", {
|
|
2697
|
+
description: "预览并创建项目级 skill、hook、rule 或 subagent:/create <种类> <名称与需求>",
|
|
1967
2698
|
handler: async (args, ctx) => {
|
|
1968
|
-
const
|
|
1969
|
-
|
|
1970
|
-
|
|
2699
|
+
const [kind = "", ...rest] = args.trim().split(/\s+/);
|
|
2700
|
+
const requirements = rest.join(" ").trim();
|
|
2701
|
+
const kinds = ["skill", "hook", "rule", "subagent"];
|
|
2702
|
+
if (!kinds.includes(kind) || !requirements) {
|
|
2703
|
+
ctx.ui.notify("请使用 /create <skill|hook|rule|subagent> <名称与需求描述>", "info");
|
|
2704
|
+
return;
|
|
2705
|
+
}
|
|
2706
|
+
pi.sendUserMessage(creationCommandPrompt(kind, requirements), ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
1971
2707
|
},
|
|
1972
2708
|
});
|
|
1973
2709
|
if (!legacyTestApi)
|
|
1974
|
-
pi.registerCommand("
|
|
1975
|
-
description: "
|
|
2710
|
+
pi.registerCommand("skill", {
|
|
2711
|
+
description: "Skill 管理页(勾选要加载的 skill);/skill pick <研究方向> 由模型挑选;/skill preference [reset] 方法主题的 skill 选择",
|
|
1976
2712
|
handler: async (args, ctx) => {
|
|
1977
|
-
const
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
2713
|
+
const [sub = "", ...rest] = args.trim().split(/\s+/);
|
|
2714
|
+
if (sub === "preference")
|
|
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
|
+
}
|
|
1988
2738
|
return;
|
|
1989
2739
|
}
|
|
1990
|
-
try {
|
|
1991
|
-
const project = await readProject(ctx.cwd);
|
|
1992
|
-
if (!(await readActiveProject(ctx.cwd))) {
|
|
1993
|
-
ctx.ui.notify("请先使用 /init 初始化研究项目;未建仓时不会自动执行同行评审。", "warning");
|
|
1994
|
-
return;
|
|
1995
|
-
}
|
|
1996
|
-
const reviewSkill = _args.trim();
|
|
1997
|
-
activeAgentRuns.add(ctx.cwd);
|
|
1998
|
-
ctx.ui.notify(`正在使用${reviewSkill?.trim() ? ` Skill“${reviewSkill.trim()}”辅助的` : "默认"} 4 角色并发模拟评审;不会自动改稿。`, "info");
|
|
1999
|
-
const result = await runParallelPeerReview({
|
|
2000
|
-
root: ctx.cwd,
|
|
2001
|
-
project,
|
|
2002
|
-
...(ctx.model?.provider === undefined ? {} : { provider: ctx.model.provider }),
|
|
2003
|
-
...(ctx.model?.id === undefined ? {} : { model: ctx.model.id }),
|
|
2004
|
-
env: providerEnvironment(ctx.model?.provider),
|
|
2005
|
-
...(reviewSkill ? { skillGuidance: reviewSkill } : {}),
|
|
2006
|
-
onEvent: async (event) => { await new RunEventLog(ctx.cwd, event.runId).append(event); },
|
|
2007
|
-
});
|
|
2008
|
-
pi.appendEntry("psyclaw:multi-agent-review", {
|
|
2009
|
-
runId: result.runId,
|
|
2010
|
-
status: result.status,
|
|
2011
|
-
outputPath: result.outputPath,
|
|
2012
|
-
adoption: "review-output-only",
|
|
2013
|
-
recordedAt: new Date().toISOString(),
|
|
2014
|
-
});
|
|
2015
|
-
ctx.ui.notify(`模拟审稿${result.status === "completed" ? "已完成" : "未完整完成"}:${result.outputPath}。审稿意见仅供研究者决定是否采纳。`, result.status === "completed" ? "info" : "warning");
|
|
2016
|
-
}
|
|
2017
|
-
catch (error) {
|
|
2018
|
-
await notifyError(ctx, error);
|
|
2019
|
-
}
|
|
2020
|
-
finally {
|
|
2021
|
-
activeAgentRuns.delete(ctx.cwd);
|
|
2022
|
-
}
|
|
2023
|
-
},
|
|
2024
|
-
});
|
|
2025
|
-
if (!legacyTestApi)
|
|
2026
|
-
pi.registerCommand("loop", {
|
|
2027
|
-
description: "按计划循环推进当前研究阶段",
|
|
2028
|
-
handler: async (args, ctx) => {
|
|
2029
|
-
const requested = args.trim();
|
|
2030
|
-
if (requested.toLowerCase() === "stop") {
|
|
2031
|
-
if (ctx.isIdle())
|
|
2032
|
-
ctx.ui.notify("当前没有正在运行的研究循环", "info");
|
|
2033
|
-
else {
|
|
2034
|
-
ctx.abort();
|
|
2035
|
-
ctx.ui.notify("已请求停止当前研究循环", "warning");
|
|
2036
|
-
}
|
|
2037
|
-
return;
|
|
2038
|
-
}
|
|
2039
|
-
let project;
|
|
2040
|
-
try {
|
|
2041
|
-
project = await readProject(ctx.cwd);
|
|
2042
|
-
}
|
|
2043
|
-
catch {
|
|
2044
|
-
ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /loop", "warning");
|
|
2045
|
-
return;
|
|
2046
|
-
}
|
|
2047
|
-
if (!(await readActiveProject(ctx.cwd))) {
|
|
2048
|
-
ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /loop。", "warning");
|
|
2049
|
-
return;
|
|
2050
|
-
}
|
|
2051
|
-
const objective = requested || project.goal;
|
|
2052
|
-
const request = [
|
|
2053
|
-
"运行一个有边界的 PsyClaw 研究循环,采用计划、执行、检查、修正的顺序推进当前研究阶段。",
|
|
2054
|
-
`本轮目标:${objective}`,
|
|
2055
|
-
"开始前读取 .psyclaw/project.json、notes/goal.md 和 notes/plan.md;如果当前对话或项目中存在经研究者确认的 /grill 研究规格,以该规格细化初始计划,但不得违反系统规则、AGENTS.md 或研究门禁。",
|
|
2056
|
-
"先识别当前最高优先级且前提已满足的一个任务,再使用可用工具实际推进。不要只描述准备做什么。普通项目文件写入、脚本和可恢复工具调用在已 /init 的项目中连续推进;原始数据覆盖、凭据、外部发布、破坏性操作仍遵守单独的安全边界。",
|
|
2057
|
-
"每完成一个实质步骤就检查产物、证据和计划是否一致。缺失信息若能检索、计算、重跑、改写或明确标注,应先自行修复。只有存在会改变研究问题、样本处理、操作化、估计目标、方法或解释的实质分歧时才请求研究者取舍;权限边界、不可恢复错误或当前阶段完成时停止。不得为了继续循环而虚构输入或结论。",
|
|
2058
|
-
"本次最多推进一个可验收的研究阶段。结束时简要报告已完成、已核验、阻塞、计划变化和下一步;规划内容不得表述为已有研究证据。",
|
|
2059
|
-
].join("\n");
|
|
2060
|
-
pi.sendUserMessage(request, ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
2061
|
-
ctx.ui.notify("已启动有界研究循环;使用 /loop stop 可请求中止", "info");
|
|
2062
|
-
},
|
|
2063
|
-
});
|
|
2064
|
-
for (const kind of ["skill", "hook", "rule", "subagent"]) {
|
|
2065
|
-
if (!legacyTestApi)
|
|
2066
|
-
pi.registerCommand(`create-${kind}`, {
|
|
2067
|
-
description: `预览并创建项目级 ${kind}(附带名称与需求文本)`,
|
|
2068
|
-
handler: async (args, ctx) => {
|
|
2069
|
-
const requirements = args.trim();
|
|
2070
|
-
if (!requirements) {
|
|
2071
|
-
ctx.ui.notify(`请使用 /create-${kind} <名称与需求描述>`, "info");
|
|
2072
|
-
return;
|
|
2073
|
-
}
|
|
2074
|
-
pi.sendUserMessage(creationCommandPrompt(kind, requirements), ctx.isIdle() ? {} : { deliverAs: "followUp" });
|
|
2075
|
-
},
|
|
2076
|
-
});
|
|
2077
|
-
}
|
|
2078
|
-
if (!legacyTestApi)
|
|
2079
|
-
pi.registerCommand("skill", {
|
|
2080
|
-
description: "打开 Skill 管理页",
|
|
2081
|
-
handler: async (_args, ctx) => {
|
|
2082
2740
|
try {
|
|
2083
2741
|
await showSkillManager(pi, ctx);
|
|
2084
2742
|
}
|
|
@@ -2087,60 +2745,57 @@ export default function psyclawExtension(pi) {
|
|
|
2087
2745
|
}
|
|
2088
2746
|
},
|
|
2089
2747
|
});
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
await notifyError(ctx, error);
|
|
2106
|
-
}
|
|
2107
|
-
},
|
|
2108
|
-
});
|
|
2109
|
-
if (!legacyTestApi)
|
|
2110
|
-
pi.registerCommand("biosignal", {
|
|
2111
|
-
description: "生理信号分析能力包:选型研究域并安装 MCP/Skill",
|
|
2112
|
-
handler: async (_args, ctx) => {
|
|
2113
|
-
try {
|
|
2114
|
-
await showBiosignalPack(pi, ctx, runtimeMcps);
|
|
2115
|
-
}
|
|
2116
|
-
catch (error) {
|
|
2117
|
-
await notifyError(ctx, error);
|
|
2118
|
-
}
|
|
2119
|
-
},
|
|
2120
|
-
});
|
|
2748
|
+
const skillPreferenceHandler = async (args, ctx) => {
|
|
2749
|
+
try {
|
|
2750
|
+
if (args.trim() === "reset") {
|
|
2751
|
+
await writeSkillPreferences(ctx.cwd, { schemaVersion: "psyclaw/skill-preferences/v1", choices: {} });
|
|
2752
|
+
ctx.ui.notify("已重置方法主题的 skill 选择。下次冲突会再问。", "info");
|
|
2753
|
+
return;
|
|
2754
|
+
}
|
|
2755
|
+
const preferences = await readSkillPreferences(ctx.cwd);
|
|
2756
|
+
const lines = Object.entries(preferences.choices);
|
|
2757
|
+
ctx.ui.notify(lines.length === 0 ? "没有已保存的方法 skill 选择。" : lines.map(([key, value]) => `${key}: ${value}`).join("\n"), "info");
|
|
2758
|
+
}
|
|
2759
|
+
catch (error) {
|
|
2760
|
+
await notifyError(ctx, error);
|
|
2761
|
+
}
|
|
2762
|
+
};
|
|
2121
2763
|
if (!legacyTestApi)
|
|
2122
2764
|
pi.registerCommand("ars", {
|
|
2123
|
-
description: "
|
|
2765
|
+
description: "学术流程:/ars 开启,/ars stop 关闭,/ars <任务> 走完整流程;子命令 grill、brainstorm、review、loop",
|
|
2124
2766
|
handler: async (args, ctx) => {
|
|
2125
2767
|
try {
|
|
2126
2768
|
const trailing = args.trim();
|
|
2769
|
+
const [first = "", ...restWords] = trailing.split(/\s+/);
|
|
2770
|
+
const subcommands = {
|
|
2771
|
+
grill: ars_grillCommand,
|
|
2772
|
+
brainstorm: ars_brainstormCommand,
|
|
2773
|
+
review: ars_reviewCommand,
|
|
2774
|
+
loop: ars_loopCommand,
|
|
2775
|
+
};
|
|
2776
|
+
const sub = subcommands[first.toLowerCase()];
|
|
2777
|
+
if (sub) {
|
|
2778
|
+
await sub.handler(restWords.join(" "), ctx);
|
|
2779
|
+
return;
|
|
2780
|
+
}
|
|
2127
2781
|
if (!trailing) {
|
|
2128
2782
|
if (!ctx.hasUI) {
|
|
2129
|
-
ctx.ui.notify("
|
|
2783
|
+
ctx.ui.notify("当前环境无编辑器;请直接用 /ars <任务> 启动学术流程。", "info");
|
|
2130
2784
|
return;
|
|
2131
2785
|
}
|
|
2132
2786
|
arsUiContext = ctx;
|
|
2133
|
-
|
|
2787
|
+
setArsPiSessionActive(pi.appendEntry.bind(pi), true);
|
|
2788
|
+
ctx.ui.notify("已开启学术流程(ARS);/ars stop 关闭。", "info");
|
|
2134
2789
|
return;
|
|
2135
2790
|
}
|
|
2136
2791
|
const lower = trailing.toLowerCase();
|
|
2137
2792
|
if (lower === "stop") {
|
|
2138
2793
|
arsUiContext = ctx;
|
|
2139
|
-
|
|
2794
|
+
setArsPiSessionActive(pi.appendEntry.bind(pi), false);
|
|
2140
2795
|
if (ctx.hasUI && isArsModeEditorText(ctx.ui.getEditorText?.() ?? "")) {
|
|
2141
2796
|
ctx.ui.setEditorText("");
|
|
2142
2797
|
}
|
|
2143
|
-
ctx.ui.notify("
|
|
2798
|
+
ctx.ui.notify("已关闭学术流程(ARS)", "info");
|
|
2144
2799
|
return;
|
|
2145
2800
|
}
|
|
2146
2801
|
if (lower === "doctor") {
|
|
@@ -2192,12 +2847,83 @@ export default function psyclawExtension(pi) {
|
|
|
2192
2847
|
}
|
|
2193
2848
|
},
|
|
2194
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.
|
|
2852
|
+
if (!legacyTestApi)
|
|
2853
|
+
pi.registerCommand("brain", {
|
|
2854
|
+
description: "PsyClaw 的记忆:/brain 看概况;/brain review 确认学到的偏好;/brain check 检查链接",
|
|
2855
|
+
handler: async (args, ctx) => {
|
|
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;
|
|
2888
|
+
}
|
|
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;
|
|
2893
|
+
}
|
|
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);
|
|
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
|
+
});
|
|
2195
2921
|
if (!legacyTestApi)
|
|
2196
|
-
pi.registerCommand("
|
|
2197
|
-
description: "
|
|
2922
|
+
pi.registerCommand("biosignal", {
|
|
2923
|
+
description: "生理信号分析能力包(EEG/MEG/fNIRS 的 MCP 与 Skill)",
|
|
2198
2924
|
handler: async (_args, ctx) => {
|
|
2199
2925
|
try {
|
|
2200
|
-
await
|
|
2926
|
+
await showBiosignalPack(pi, ctx);
|
|
2201
2927
|
}
|
|
2202
2928
|
catch (error) {
|
|
2203
2929
|
await notifyError(ctx, error);
|
|
@@ -2333,217 +3059,60 @@ export default function psyclawExtension(pi) {
|
|
|
2333
3059
|
}
|
|
2334
3060
|
},
|
|
2335
3061
|
});
|
|
3062
|
+
const petCommand = {
|
|
3063
|
+
description: "启动横幅宠物:单独查看状态,或附带 on/off",
|
|
3064
|
+
handler: async (args, ctx) => {
|
|
3065
|
+
const action = args.trim().toLowerCase() || "status";
|
|
3066
|
+
if (action === "status") {
|
|
3067
|
+
ctx.ui.notify(`启动横幅宠物:${await petPreference() ? "已开启" : "已关闭(默认)"}`, "info");
|
|
3068
|
+
return;
|
|
3069
|
+
}
|
|
3070
|
+
if (action !== "on" && action !== "off") {
|
|
3071
|
+
ctx.ui.notify("请使用 /prefs pet,或 /prefs pet on|off", "error");
|
|
3072
|
+
return;
|
|
3073
|
+
}
|
|
3074
|
+
await setPetPreference(action === "on");
|
|
3075
|
+
ctx.ui.notify(`启动横幅宠物已${action === "on" ? "开启" : "关闭"},下次启动生效`, "info");
|
|
3076
|
+
},
|
|
3077
|
+
};
|
|
3078
|
+
const telemetryCommand = {
|
|
3079
|
+
description: "查看或关闭匿名产品遥测",
|
|
3080
|
+
handler: async (args, ctx) => {
|
|
3081
|
+
const action = args.trim().toLowerCase() || "status";
|
|
3082
|
+
if (action === "status") {
|
|
3083
|
+
const preference = await readTelemetryPreference();
|
|
3084
|
+
ctx.ui.notify(preference.enabled
|
|
3085
|
+
? "匿名产品遥测:开启(默认)。采集粗粒度使用与错误,不含研究正文。关闭:/prefs telemetry off"
|
|
3086
|
+
: "匿名产品遥测:已关闭。重新开启:/prefs telemetry on", "info");
|
|
3087
|
+
return;
|
|
3088
|
+
}
|
|
3089
|
+
if (action !== "on" && action !== "off") {
|
|
3090
|
+
ctx.ui.notify("用法:/prefs telemetry on|off", "error");
|
|
3091
|
+
return;
|
|
3092
|
+
}
|
|
3093
|
+
await writeTelemetryPreference({ enabled: action === "on", noticeAcknowledged: true });
|
|
3094
|
+
ctx.ui.notify(action === "on" ? "已开启匿名产品遥测。下次启动生效。" : "已关闭匿名产品遥测。下次启动不再发送。", "info");
|
|
3095
|
+
},
|
|
3096
|
+
};
|
|
2336
3097
|
if (!legacyTestApi)
|
|
2337
|
-
pi.registerCommand("
|
|
2338
|
-
description: "
|
|
2339
|
-
handler: async (args, ctx) => {
|
|
2340
|
-
const action = args.trim().toLowerCase() || "status";
|
|
2341
|
-
if (action === "status") {
|
|
2342
|
-
ctx.ui.notify(`启动横幅宠物:${await petPreference() ? "已开启" : "已关闭(默认)"}`, "info");
|
|
2343
|
-
return;
|
|
2344
|
-
}
|
|
2345
|
-
if (action !== "on" && action !== "off") {
|
|
2346
|
-
ctx.ui.notify("请使用 /pet,或 /pet on|off", "error");
|
|
2347
|
-
return;
|
|
2348
|
-
}
|
|
2349
|
-
await setPetPreference(action === "on");
|
|
2350
|
-
ctx.ui.notify(`启动横幅宠物已${action === "on" ? "开启" : "关闭"},下次启动生效`, "info");
|
|
2351
|
-
},
|
|
2352
|
-
});
|
|
2353
|
-
if (!legacyTestApi)
|
|
2354
|
-
pi.registerCommand("telemetry", {
|
|
2355
|
-
description: "查看或关闭匿名产品遥测",
|
|
3098
|
+
pi.registerCommand("prefs", {
|
|
3099
|
+
description: "偏好设置:/prefs pet [on|off] 启动横幅宠物,/prefs telemetry [on|off] 匿名产品遥测",
|
|
2356
3100
|
handler: async (args, ctx) => {
|
|
2357
|
-
const
|
|
2358
|
-
if (
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
}
|
|
2365
|
-
if (action !== "on" && action !== "off") {
|
|
2366
|
-
ctx.ui.notify("Usage: /telemetry on|off|status", "error");
|
|
3101
|
+
const [sub = "", ...rest] = args.trim().split(/\s+/);
|
|
3102
|
+
if (sub === "pet")
|
|
3103
|
+
return petCommand.handler(rest.join(" "), ctx);
|
|
3104
|
+
if (sub === "telemetry")
|
|
3105
|
+
return telemetryCommand.handler(rest.join(" "), ctx);
|
|
3106
|
+
if (sub) {
|
|
3107
|
+
ctx.ui.notify("用法:/prefs pet [on|off] 或 /prefs telemetry [on|off]", "error");
|
|
2367
3108
|
return;
|
|
2368
3109
|
}
|
|
2369
|
-
await
|
|
2370
|
-
|
|
3110
|
+
await petCommand.handler("", ctx);
|
|
3111
|
+
await telemetryCommand.handler("", ctx);
|
|
2371
3112
|
},
|
|
2372
3113
|
});
|
|
2373
3114
|
if (typeof pi.registerTool === "function") {
|
|
2374
3115
|
registerAnalysisRuntimeTools(pi);
|
|
2375
|
-
registerPriorTools(pi, () => sessionMode);
|
|
2376
|
-
pi.registerTool({
|
|
2377
|
-
name: "psyclaw_research_decision",
|
|
2378
|
-
label: "Research decision",
|
|
2379
|
-
description: "Request researcher input only for an unresolved substantive research trade-off. Never use this for software, formatting, missing reporting fields, recoverable errors, evidence collection, credentials, publication, or other operational authorization.",
|
|
2380
|
-
parameters: Type.Object({
|
|
2381
|
-
id: Type.String({ minLength: 1 }),
|
|
2382
|
-
question: Type.String({ minLength: 1 }),
|
|
2383
|
-
options: Type.Array(Type.Object({
|
|
2384
|
-
id: Type.String({ minLength: 1 }),
|
|
2385
|
-
label: Type.String({ minLength: 1 }),
|
|
2386
|
-
rationale: Type.String({ minLength: 1 }),
|
|
2387
|
-
consequences: Type.Array(Type.String()),
|
|
2388
|
-
evidenceRefs: Type.Array(Type.String()),
|
|
2389
|
-
}), { minItems: 2 }),
|
|
2390
|
-
affectedAreas: Type.Array(Type.Union([
|
|
2391
|
-
Type.Literal("research-question"),
|
|
2392
|
-
Type.Literal("sample-treatment"),
|
|
2393
|
-
Type.Literal("operationalization"),
|
|
2394
|
-
Type.Literal("estimand"),
|
|
2395
|
-
Type.Literal("analysis-method"),
|
|
2396
|
-
Type.Literal("interpretation"),
|
|
2397
|
-
]), { minItems: 1 }),
|
|
2398
|
-
evidenceCannotResolve: Type.Boolean(),
|
|
2399
|
-
evidenceReviewed: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
2400
|
-
methodsChecked: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
2401
|
-
unresolvedReason: Type.String({ minLength: 1 }),
|
|
2402
|
-
recommendation: Type.String({ minLength: 1 }),
|
|
2403
|
-
}),
|
|
2404
|
-
executionMode: "sequential",
|
|
2405
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
2406
|
-
const run = await readActiveProject(ctx.cwd);
|
|
2407
|
-
if (!run) {
|
|
2408
|
-
return {
|
|
2409
|
-
content: [{ type: "text", text: "当前目录尚未 /init,不能进入研究决策状态。请先执行 /init。" }],
|
|
2410
|
-
details: { status: "general-mode" },
|
|
2411
|
-
isError: true,
|
|
2412
|
-
};
|
|
2413
|
-
}
|
|
2414
|
-
const request = {
|
|
2415
|
-
schemaVersion: "psyclaw/research-decision/v1",
|
|
2416
|
-
id: params.id,
|
|
2417
|
-
question: params.question,
|
|
2418
|
-
options: params.options,
|
|
2419
|
-
affectedAreas: params.affectedAreas,
|
|
2420
|
-
evidenceCannotResolve: params.evidenceCannotResolve,
|
|
2421
|
-
evidenceReviewed: params.evidenceReviewed,
|
|
2422
|
-
methodsChecked: params.methodsChecked,
|
|
2423
|
-
unresolvedReason: params.unresolvedReason,
|
|
2424
|
-
recommendation: params.recommendation,
|
|
2425
|
-
};
|
|
2426
|
-
try {
|
|
2427
|
-
assertResearchDecision(request);
|
|
2428
|
-
}
|
|
2429
|
-
catch (error) {
|
|
2430
|
-
return {
|
|
2431
|
-
content: [{ type: "text", text: `该事项不符合研究取舍条件:${error instanceof Error ? error.message : String(error)}。请继续检索、计算、修复,或按单独的安全授权边界处理。` }],
|
|
2432
|
-
details: { status: "not-a-research-decision", runId: run.runId },
|
|
2433
|
-
isError: true,
|
|
2434
|
-
};
|
|
2435
|
-
}
|
|
2436
|
-
const eventLog = new RunEventLog(ctx.cwd, run.runId);
|
|
2437
|
-
const events = await eventLog.snapshot();
|
|
2438
|
-
const resolvedIds = new Set(events
|
|
2439
|
-
.filter((event) => event.type === "decision-resolved" && event.researchDecisionResolution)
|
|
2440
|
-
.map((event) => event.researchDecisionResolution.decisionId));
|
|
2441
|
-
const pending = findLastMatching(events, (event) => event.type === "awaiting-human" && Boolean(event.researchDecision && !resolvedIds.has(event.researchDecision.id)));
|
|
2442
|
-
if (pending?.researchDecision) {
|
|
2443
|
-
return {
|
|
2444
|
-
content: [{ type: "text", text: `当前已有一项待研究者取舍的问题:${pending.researchDecision.question}。请先处理该问题,不能同时创建第二项。` }],
|
|
2445
|
-
details: { status: "research-decision-already-pending", runId: run.runId, decisionId: pending.researchDecision.id },
|
|
2446
|
-
isError: true,
|
|
2447
|
-
};
|
|
2448
|
-
}
|
|
2449
|
-
if (events.some((event) => event.researchDecision?.id === request.id || event.researchDecisionResolution?.decisionId === request.id)) {
|
|
2450
|
-
return {
|
|
2451
|
-
content: [{ type: "text", text: `研究取舍编号已使用:${request.id}` }],
|
|
2452
|
-
details: { status: "duplicate-research-decision", runId: run.runId, decisionId: request.id },
|
|
2453
|
-
isError: true,
|
|
2454
|
-
};
|
|
2455
|
-
}
|
|
2456
|
-
await eventLog.append({
|
|
2457
|
-
type: "awaiting-human",
|
|
2458
|
-
at: new Date().toISOString(),
|
|
2459
|
-
researchDecision: request,
|
|
2460
|
-
message: request.question,
|
|
2461
|
-
});
|
|
2462
|
-
return {
|
|
2463
|
-
content: [{ type: "text", text: JSON.stringify({ status: "需要研究者取舍", runId: run.runId, decision: request }, null, 2) }],
|
|
2464
|
-
details: { status: "awaiting-human", runId: run.runId, decisionId: request.id },
|
|
2465
|
-
};
|
|
2466
|
-
},
|
|
2467
|
-
});
|
|
2468
|
-
pi.registerTool({
|
|
2469
|
-
name: "psyclaw_resolve_research_decision",
|
|
2470
|
-
label: "Resolve research decision",
|
|
2471
|
-
description: "Record the researcher's answer to the current substantive research trade-off and resume the controlled workflow. This is not an operational approval tool.",
|
|
2472
|
-
parameters: Type.Object({
|
|
2473
|
-
decisionId: Type.String({ minLength: 1 }),
|
|
2474
|
-
selectedOption: Type.String({ minLength: 1 }),
|
|
2475
|
-
rationale: Type.String({ minLength: 1 }),
|
|
2476
|
-
}),
|
|
2477
|
-
executionMode: "sequential",
|
|
2478
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
2479
|
-
const run = await readActiveProject(ctx.cwd);
|
|
2480
|
-
if (!run) {
|
|
2481
|
-
return { content: [{ type: "text", text: "当前目录尚未 /init,没有有效的研究项目。" }], details: { status: "general-mode" }, isError: true };
|
|
2482
|
-
}
|
|
2483
|
-
const eventLog = new RunEventLog(ctx.cwd, run.runId);
|
|
2484
|
-
const events = await eventLog.snapshot();
|
|
2485
|
-
const resolvedIds = new Set(events
|
|
2486
|
-
.filter((event) => event.type === "decision-resolved" && event.researchDecisionResolution)
|
|
2487
|
-
.map((event) => event.researchDecisionResolution.decisionId));
|
|
2488
|
-
const pending = findLastMatching(events, (event) => event.type === "awaiting-human" && event.researchDecision?.id === params.decisionId && !resolvedIds.has(params.decisionId));
|
|
2489
|
-
if (!pending?.researchDecision) {
|
|
2490
|
-
return { content: [{ type: "text", text: `未找到待处理的研究取舍:${params.decisionId}` }], details: { status: "not-found", runId: run.runId }, isError: true };
|
|
2491
|
-
}
|
|
2492
|
-
try {
|
|
2493
|
-
const resolution = resolveResearchDecision(pending.researchDecision, {
|
|
2494
|
-
selectedOption: params.selectedOption,
|
|
2495
|
-
rationale: params.rationale,
|
|
2496
|
-
});
|
|
2497
|
-
await eventLog.append({ type: "decision-resolved", at: resolution.resolvedAt, researchDecisionResolution: resolution });
|
|
2498
|
-
return {
|
|
2499
|
-
content: [{ type: "text", text: JSON.stringify({ status: "executing", runId: run.runId, resolution }, null, 2) }],
|
|
2500
|
-
details: { status: "executing", runId: run.runId, decisionId: resolution.decisionId },
|
|
2501
|
-
};
|
|
2502
|
-
}
|
|
2503
|
-
catch (error) {
|
|
2504
|
-
return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], details: { status: "invalid-resolution", runId: run.runId }, isError: true };
|
|
2505
|
-
}
|
|
2506
|
-
},
|
|
2507
|
-
});
|
|
2508
|
-
pi.registerTool({
|
|
2509
|
-
name: "psyclaw_mcp",
|
|
2510
|
-
label: "MCP tools",
|
|
2511
|
-
description: "List and call tools from MCP servers enabled in .psyclaw/mcp/*.json. Use action=list first, then action=call with the exact server and tool names.",
|
|
2512
|
-
promptSnippet: "Discover and call enabled MCP servers such as MNE through PsyClaw.",
|
|
2513
|
-
parameters: Type.Object({
|
|
2514
|
-
action: Type.Union([Type.Literal("list"), Type.Literal("call")]),
|
|
2515
|
-
server: Type.Optional(Type.String({ description: "Configured MCP server id, for example mne-mcp" })),
|
|
2516
|
-
tool: Type.Optional(Type.String({ description: "Exact MCP tool name returned by action=list" })),
|
|
2517
|
-
input: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
2518
|
-
}),
|
|
2519
|
-
executionMode: "sequential",
|
|
2520
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
2521
|
-
try {
|
|
2522
|
-
if (params.action === "list") {
|
|
2523
|
-
const servers = await runtimeMcps.list(ctx.cwd, params.server);
|
|
2524
|
-
return { content: [{ type: "text", text: JSON.stringify({ servers }, null, 2) }], details: { action: "list", servers: servers.length } };
|
|
2525
|
-
}
|
|
2526
|
-
if (!(await readActiveProject(ctx.cwd))) {
|
|
2527
|
-
return {
|
|
2528
|
-
content: [{ type: "text", text: "当前目录尚未 /init。可以查看 MCP 工具,但实际调用需先运行 /init。" }],
|
|
2529
|
-
details: { action: "call", status: "general-mode" },
|
|
2530
|
-
isError: true,
|
|
2531
|
-
};
|
|
2532
|
-
}
|
|
2533
|
-
if (!params.server || !params.tool)
|
|
2534
|
-
throw new Error("server and tool are required for action=call");
|
|
2535
|
-
const result = await runtimeMcps.call(ctx.cwd, params.server, params.tool, params.input ?? {});
|
|
2536
|
-
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], details: { action: "call", server: params.server, tool: params.tool } };
|
|
2537
|
-
}
|
|
2538
|
-
catch (error) {
|
|
2539
|
-
return {
|
|
2540
|
-
content: [{ type: "text", text: `MCP call failed: ${error instanceof Error ? error.message : String(error)}` }],
|
|
2541
|
-
details: { action: params.action, status: "failed" },
|
|
2542
|
-
isError: true,
|
|
2543
|
-
};
|
|
2544
|
-
}
|
|
2545
|
-
},
|
|
2546
|
-
});
|
|
2547
3116
|
pi.registerTool({
|
|
2548
3117
|
name: "psyclaw_ars_multi_agent",
|
|
2549
3118
|
label: "ARS multi-agent review bridge",
|
|
@@ -2653,25 +3222,72 @@ export default function psyclawExtension(pi) {
|
|
|
2653
3222
|
});
|
|
2654
3223
|
pi.registerTool({
|
|
2655
3224
|
name: "psyclaw_skill",
|
|
2656
|
-
label: "
|
|
2657
|
-
description: "
|
|
3225
|
+
label: "Skill",
|
|
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.",
|
|
2658
3227
|
parameters: Type.Object({
|
|
2659
|
-
|
|
3228
|
+
action: Type.Optional(Type.Union([Type.Literal("load"), Type.Literal("find"), Type.Literal("choose")])),
|
|
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" })),
|
|
3232
|
+
query: Type.Optional(Type.String({ description: "A few words about the task (action=find)" })),
|
|
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" })),
|
|
2660
3234
|
purpose: Type.Optional(Type.String({ description: "Short user-facing reason for using this skill now" })),
|
|
2661
3235
|
}),
|
|
2662
3236
|
executionMode: "sequential",
|
|
2663
|
-
async execute(_toolCallId, params) {
|
|
2664
|
-
|
|
2665
|
-
|
|
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);
|
|
2666
3247
|
return {
|
|
2667
|
-
content: [{ type: "text", text:
|
|
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
|
+
}
|
|
3252
|
+
if (params.action === "find" || (!params.name && params.query)) {
|
|
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;
|
|
3258
|
+
const text = hits.length
|
|
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.";
|
|
3261
|
+
return { content: [{ type: "text", text }], details: { status: "found", name: hits.map((skill) => skill.name).join(",") } };
|
|
3262
|
+
}
|
|
3263
|
+
const name = (params.name ?? "").trim();
|
|
3264
|
+
const listed = skillRegistry.find((skill) => skill.name === name);
|
|
3265
|
+
const path = CORE_SKILLS.has(name) ? coreSkillPath(name) : listed?.location;
|
|
3266
|
+
if (!path) {
|
|
3267
|
+
return {
|
|
3268
|
+
content: [{ type: "text", text: `No skill named ${name || "(none)"}. Use action=find to look one up.` }],
|
|
2668
3269
|
details: { status: "blocked", name },
|
|
2669
3270
|
};
|
|
2670
3271
|
}
|
|
2671
3272
|
try {
|
|
2672
|
-
|
|
3273
|
+
if (params.section && params.section.trim().toLowerCase() !== "all") {
|
|
3274
|
+
const text = readSkillSection(path, params.section);
|
|
3275
|
+
return {
|
|
3276
|
+
content: [{ type: "text", text: text ?? `No section starting with "${params.section}" in ${name}.` }],
|
|
3277
|
+
details: { status: text ? "active" : "failed", name },
|
|
3278
|
+
};
|
|
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
|
+
}
|
|
3288
|
+
const instructions = await readFile(path, "utf8");
|
|
2673
3289
|
return {
|
|
2674
|
-
content: [{ type: "text", text: `正在使用 Skill:${name}${params.purpose ? `(${params.purpose})` : ""}\n\n${instructions}` }],
|
|
3290
|
+
content: [{ type: "text", text: `正在使用 Skill:${name}${params.purpose ? `(${params.purpose})` : ""}\nSkill directory (resolve relative paths against it): ${dirname(path)}\n\n${instructions}` }],
|
|
2675
3291
|
details: { status: "active", name, ...(params.purpose === undefined ? {} : { purpose: params.purpose }) },
|
|
2676
3292
|
};
|
|
2677
3293
|
}
|
|
@@ -2701,7 +3317,7 @@ export default function psyclawExtension(pi) {
|
|
|
2701
3317
|
const project = await readActiveProject(ctx.cwd);
|
|
2702
3318
|
const softNote = project
|
|
2703
3319
|
? undefined
|
|
2704
|
-
: "尚未 /init(软门禁):继续执行;收尾前须 AI /
|
|
3320
|
+
: "尚未 /init(软门禁):继续执行;收尾前须 AI /check quick 后人审。建议先 /init 建仓。";
|
|
2705
3321
|
const request = params.request.trim();
|
|
2706
3322
|
const combined = `${request} ${params.identifier ?? ""}`;
|
|
2707
3323
|
const explicitWorkflow = params.workflow?.trim();
|
|
@@ -2820,40 +3436,584 @@ export default function psyclawExtension(pi) {
|
|
|
2820
3436
|
},
|
|
2821
3437
|
});
|
|
2822
3438
|
pi.registerTool({
|
|
2823
|
-
name: "
|
|
2824
|
-
label: "
|
|
2825
|
-
description: "
|
|
3439
|
+
name: "psyclaw_spec",
|
|
3440
|
+
label: "估计量说明书",
|
|
3441
|
+
description: "The analysis specification (analysis mode): analysis/spec.json, one estimand per quantity the study reports. action=write: estimands {E1: {rq, quantity, shell, attrs: {population, outcome, contrast, summary, model, adjustment, missing, interval}}}, each attribute {value, by: brief|researcher, quote} or {by: analyst|open, options: [...], recommended: <number>, reason}; estimands not given are kept, null removes one without a result. action=confirm (no id): code returns one numbered message with every open choice of every estimand still to confirm; post it as your whole reply and stop. action=answers: the researcher's one reply (quote, answers [{item: E1.2, option or text}], rest, additions). action=confirm id=E1: choice boxes for an estimand the reply left unclear. action=record id, values, evidence_file: the numbers of a confirmed estimand and the output file that holds them. action=waive id, reason. action=status: what is still missing.",
|
|
2826
3442
|
parameters: Type.Object({
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
3443
|
+
action: Type.Union([Type.Literal("write"), Type.Literal("confirm"), Type.Literal("answers"), Type.Literal("record"), Type.Literal("waive"), Type.Literal("status")]),
|
|
3444
|
+
answers: Type.Optional(Type.Array(Type.Object({ item: Type.String({ description: "E1.2" }), option: Type.Optional(Type.Number({ description: "1-based option number" })), text: Type.Optional(Type.String({ description: "The researcher's own approach, in their words" })) }))),
|
|
3445
|
+
rest: Type.Optional(Type.Union([Type.Literal("recommended"), Type.Literal("open")])),
|
|
3446
|
+
quote: Type.Optional(Type.String({ description: "answers: the researcher's reply, unchanged" })),
|
|
3447
|
+
additions: Type.Optional(Type.Array(Type.String())),
|
|
3448
|
+
estimands: Type.Optional(Type.Object({}, { additionalProperties: true })),
|
|
3449
|
+
id: Type.Optional(Type.String()),
|
|
3450
|
+
values: Type.Optional(Type.Object({}, { additionalProperties: true })),
|
|
3451
|
+
evidence_file: Type.Optional(Type.String()),
|
|
3452
|
+
reason: Type.Optional(Type.String()),
|
|
2833
3453
|
}),
|
|
2834
3454
|
executionMode: "sequential",
|
|
2835
3455
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
3456
|
+
const out = (text, isError = false) => ({ content: [{ type: "text", text }], details: undefined, ...(isError ? { isError: true } : {}) });
|
|
2836
3457
|
try {
|
|
2837
|
-
const
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
3458
|
+
const cwd = ctx.cwd;
|
|
3459
|
+
if (params.action === "write") {
|
|
3460
|
+
return out(writeSpec(cwd, params.estimands, estimandRqs(cwd, ctx), `${materialsText(cwd)}\n${userTexts(ctx)}`, userTexts(ctx)));
|
|
3461
|
+
}
|
|
3462
|
+
if (params.action === "status") {
|
|
3463
|
+
const left = estimandGaps(cwd, loadSpec(cwd), estimandRqs(cwd, ctx), estimandReport(cwd));
|
|
3464
|
+
return out(left.length ? `Still missing:\n- ${left.join("\n- ")}` : "The specification is complete: every estimand confirmed and recorded, and the report holds every number.");
|
|
3465
|
+
}
|
|
3466
|
+
const s = loadSpec(cwd);
|
|
3467
|
+
const id = String(params.id ?? "").trim();
|
|
3468
|
+
if (s && params.action === "confirm" && !id) {
|
|
3469
|
+
const ids = estimandsToConfirm(s);
|
|
3470
|
+
if (!ids.length)
|
|
3471
|
+
return out("Every estimand is confirmed.");
|
|
3472
|
+
const share = shellClock.budgetLeftShare();
|
|
3473
|
+
if (share !== undefined && share < 0.4) {
|
|
3474
|
+
const notes = ids.flatMap((x) => settleByRecommendation(s, x, "not put to the researcher because of the time limit"));
|
|
3475
|
+
saveSpec(cwd, s);
|
|
3476
|
+
return out([`${ids.join(", ")}: confirmed without asking (time budget nearly used).`, ...notes, "Run the analysis and record the results now; say in the report which choices the researcher did not see."].join("\n"));
|
|
3477
|
+
}
|
|
3478
|
+
return out([`Post the message below to the researcher as your whole reply, unchanged, then stop and wait. Record their reply with psyclaw_spec action=answers.`, "", estimandPlanMessage(s, ids)].join("\n"));
|
|
3479
|
+
}
|
|
3480
|
+
if (s && params.action === "answers") {
|
|
3481
|
+
const quote = String(params.quote ?? "").trim();
|
|
3482
|
+
if (!quote)
|
|
3483
|
+
throw new Error("answers needs quote: the researcher's reply, unchanged");
|
|
3484
|
+
const ids = estimandsToConfirm(s);
|
|
3485
|
+
const r = applyReply(s, ids, (params.answers ?? []), params.rest === "recommended" ? "recommended" : "open");
|
|
3486
|
+
saveSpec(cwd, s);
|
|
3487
|
+
for (const x of r.settled) {
|
|
3488
|
+
await recordSettled(cwd, { id: `${x.id}.${x.attr}`, question: `${x.id} ${ATTR_ZH[x.attr]}`, by: "researcher", choice: x.choice, quote, via: "text" }).catch(() => undefined);
|
|
3489
|
+
}
|
|
3490
|
+
const additions = (params.additions ?? []).map((a) => String(a).trim()).filter(Boolean);
|
|
3491
|
+
return out([
|
|
3492
|
+
...r.notes,
|
|
3493
|
+
...(additions.length ? [`The researcher wants these too: ${additions.join("; ")}. Add them as estimands (action=write, by "researcher" with their words) or to the shells, and report them.`] : []),
|
|
3494
|
+
r.left.length ? `Still unconfirmed: ${r.left.join(", ")}. Ask only what the reply left unclear (action=confirm id=…).` : "Every estimand is confirmed. Run the analysis now; do not ask the researcher again before the deliverables are done.",
|
|
3495
|
+
].join("\n"));
|
|
3496
|
+
}
|
|
3497
|
+
const e = s?.estimands[id];
|
|
3498
|
+
if (!s || !e)
|
|
3499
|
+
throw new Error(`No estimand ${id || "(id missing)"}. Write the specification with action=write first.`);
|
|
3500
|
+
if (params.action === "waive") {
|
|
3501
|
+
if (String(params.reason ?? "").trim().length < 12)
|
|
3502
|
+
throw new Error("Give the reason it cannot be computed.");
|
|
3503
|
+
e.waived = String(params.reason).trim();
|
|
3504
|
+
saveSpec(cwd, s);
|
|
3505
|
+
return out(`Waived ${id}.`);
|
|
3506
|
+
}
|
|
3507
|
+
if (params.action === "record") {
|
|
3508
|
+
const msg = recordResult(cwd, s, id, params.values, String(params.evidence_file ?? ""));
|
|
3509
|
+
saveSpec(cwd, s);
|
|
3510
|
+
return out(msg);
|
|
3511
|
+
}
|
|
3512
|
+
// confirm: one choice box per open item, recommendation first so Enter takes it.
|
|
3513
|
+
if (e.confirmed_at && !estimandStale(e))
|
|
3514
|
+
return out(`${id} is already confirmed.`);
|
|
3515
|
+
if ((e.confirms ?? 0) >= MAX_CONFIRMS)
|
|
3516
|
+
throw new Error(`${id} was already put to the researcher ${MAX_CONFIRMS} times. Use your recommendation for what is still open (by "analyst" with the reason "the researcher did not choose") and go on.`);
|
|
3517
|
+
// Time budget: with under 40% left, settle the rest by recommendation so the analysis can run.
|
|
3518
|
+
const share = shellClock.budgetLeftShare();
|
|
3519
|
+
if (share !== undefined && share < 0.4) {
|
|
3520
|
+
const notes = settleByRecommendation(s, id, "not put to the researcher because of the time limit");
|
|
3521
|
+
saveSpec(cwd, s);
|
|
3522
|
+
return out([`${id}: confirmed without a card (time budget nearly used).`, ...notes, "Run the analysis and record the results now; say in the report which choices the researcher did not see."].join("\n"));
|
|
3523
|
+
}
|
|
3524
|
+
// The researcher's own words come first: no confirmation before they have answered once (in chat, or on a card).
|
|
3525
|
+
const userTurns = (() => {
|
|
3526
|
+
try {
|
|
3527
|
+
const branch = ctx.sessionManager?.getBranch?.() ?? [];
|
|
3528
|
+
// Only the researcher's own messages count, not PsyClaw's own nudges ("[psyclaw] ...").
|
|
3529
|
+
return branch.filter((entry) => {
|
|
3530
|
+
const m = entry.message;
|
|
3531
|
+
if (m?.role !== "user")
|
|
3532
|
+
return false;
|
|
3533
|
+
const c = m.content;
|
|
3534
|
+
const text = typeof c === "string" ? c : Array.isArray(c) ? c.map((x) => x.text ?? "").join("") : "";
|
|
3535
|
+
return !text.trimStart().startsWith("[psyclaw]");
|
|
3536
|
+
}).length;
|
|
3537
|
+
}
|
|
3538
|
+
catch {
|
|
3539
|
+
return 2;
|
|
3540
|
+
}
|
|
3541
|
+
})();
|
|
3542
|
+
const answeredOnCard = (await readDecisions(cwd).catch(() => [])).some((d) => d.by === "researcher");
|
|
3543
|
+
if (ctx.hasUI && userTurns < 2 && !answeredOnCard) {
|
|
3544
|
+
return out("Before the first confirmation, ask the researcher in chat, openly, how they planned to analyse each research question (sample, outcome coding, model, covariates, what to report), and stop until they answer. Then put their words into the specification (by \"researcher\" with the quote) and confirm what is still open.", true);
|
|
3545
|
+
}
|
|
3546
|
+
const items = cardItems(e);
|
|
3547
|
+
if (!ctx.hasUI) {
|
|
3548
|
+
return out(`No terminal to show the confirmation. Ask the researcher in chat, then write their answers with action=write (by "researcher", their words as the quote):\n${cardText(id, e, items)}`, true);
|
|
3549
|
+
}
|
|
3550
|
+
const card = `C${s.cards + 1}`;
|
|
3551
|
+
const answers = [];
|
|
3552
|
+
for (const it of items) {
|
|
3553
|
+
const title = it.attr === "report"
|
|
3554
|
+
? `${id}(${e.rq})报告:${e.shell}`
|
|
3555
|
+
: `${id}(${e.rq})${e.quantity}\n${ATTR_ZH[it.attr]}:选一项(第一项是推荐)`;
|
|
3556
|
+
const order = it.attr === "report" ? [0] : [it.recommended - 1, ...it.options.map((_o, i) => i).filter((i) => i !== it.recommended - 1)];
|
|
3557
|
+
const labels = order.map((i, k) => `${it.options[i]}${k === 0 ? "(推荐)" : ""}`);
|
|
3558
|
+
const other = it.attr === "report" ? "还要补报别的(我来写)" : "别的做法(我来写)";
|
|
3559
|
+
const picked = await ctx.ui.select(title, [...labels, other], { timeout: 300_000 });
|
|
3560
|
+
if (picked === undefined) {
|
|
3561
|
+
answers.push({ kind: "none" });
|
|
3562
|
+
continue;
|
|
3563
|
+
}
|
|
3564
|
+
if (picked === other) {
|
|
3565
|
+
const text = (await ctx.ui.input(`${id} ${it.attr === "report" ? "还要报告什么" : ATTR_ZH[it.attr]}:写明你要的做法`, "", { timeout: 300_000 }))?.trim() ?? "";
|
|
3566
|
+
answers.push({ kind: "other", text });
|
|
3567
|
+
continue;
|
|
3568
|
+
}
|
|
3569
|
+
answers.push({ kind: "option", index: order[labels.indexOf(picked)] });
|
|
3570
|
+
}
|
|
3571
|
+
s.cards += 1;
|
|
3572
|
+
e.confirms = (e.confirms ?? 0) + 1;
|
|
3573
|
+
const notes = applyAnswers(s, id, card, items, answers);
|
|
3574
|
+
saveSpec(cwd, s);
|
|
3575
|
+
for (const [i, it] of items.entries()) {
|
|
3576
|
+
const a = answers[i];
|
|
3577
|
+
if (it.attr === "report" || !a || a.kind === "none")
|
|
3578
|
+
continue;
|
|
3579
|
+
const choice = a.kind === "option" ? it.options[a.index] : a.text || "(别的,没写明)";
|
|
3580
|
+
await recordSettled(cwd, { id: `${id}.${it.attr}`, question: `${id} ${ATTR_ZH[it.attr]}`, by: "researcher", choice, quote: choice, via: "terminal" }).catch(() => undefined);
|
|
3581
|
+
}
|
|
3582
|
+
return out(notes.join("\n"));
|
|
3583
|
+
}
|
|
3584
|
+
catch (error) {
|
|
3585
|
+
return out(error instanceof Error ? error.message : String(error), true);
|
|
3586
|
+
}
|
|
3587
|
+
},
|
|
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
|
+
});
|
|
3634
|
+
pi.registerTool({
|
|
3635
|
+
name: "psyclaw_intent",
|
|
3636
|
+
label: "研究意图",
|
|
3637
|
+
description: "The researcher's intent, kept in the project (.psyclaw/intent.jsonl). Research mode, before the plan: first ask the researcher openly (no options) what they want to find out, what outcome matters most and how they planned to analyse it. Then action=restate with items (field question|outcome|approach|hypothesis|data|scope, optional label such as RQ1, text, and quote = their words or the materials' words unchanged; leave quote out for what you infer) and flow (theory: hypotheses first, then data; data: explore first, then literature). Code returns one message: post it as your whole reply and wait. When they reply, action=confirm with quote = the reply unchanged; if they correct something substantial, restate again. action=status shows the record. psyclaw_plan action=submit waits until the intent is confirmed.",
|
|
3638
|
+
parameters: Type.Object({
|
|
3639
|
+
action: Type.Union([Type.Literal("restate"), Type.Literal("confirm"), Type.Literal("status")]),
|
|
3640
|
+
items: Type.Optional(Type.Array(Type.Object({
|
|
3641
|
+
field: Type.String({ description: INTENT_FIELDS.join(" | ") }),
|
|
3642
|
+
label: Type.Optional(Type.String({ description: "Research-question label, e.g. RQ1 or H2" })),
|
|
3643
|
+
text: Type.String({ description: "The point, in research language" }),
|
|
3644
|
+
quote: Type.Optional(Type.String({ description: "The researcher's or the materials' words, unchanged; leave out for your inference" })),
|
|
3645
|
+
}))),
|
|
3646
|
+
flow: Type.Optional(Type.Union([Type.Literal("theory"), Type.Literal("data")])),
|
|
3647
|
+
quote: Type.Optional(Type.String({ description: "confirm: the researcher's reply, unchanged" })),
|
|
3648
|
+
corrections: Type.Optional(Type.String({ description: "confirm: their corrections, in their words" })),
|
|
3649
|
+
}),
|
|
3650
|
+
executionMode: "sequential",
|
|
3651
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
3652
|
+
try {
|
|
3653
|
+
if (params.action === "status") {
|
|
3654
|
+
const state = await readIntent(ctx.cwd);
|
|
3655
|
+
return { content: [{ type: "text", text: intentBrief(state) || "还没有复述过研究意图。" }], details: { version: state.current?.version ?? 0, confirmed: !!state.current?.confirmed } };
|
|
3656
|
+
}
|
|
3657
|
+
if (params.action === "confirm") {
|
|
3658
|
+
const { version } = await confirmIntent(ctx.cwd, params.quote ?? "", params.corrections);
|
|
3659
|
+
return { content: [{ type: "text", text: `研究意图 v${version} 已由研究者确认。${params.corrections?.trim() ? "Take their corrections into the plan. " : ""}Now build the plan against it: psyclaw_plan action=submit.` }], details: { version } };
|
|
3660
|
+
}
|
|
3661
|
+
const state = await readIntent(ctx.cwd);
|
|
3662
|
+
// Ask openly before restating: with only the brief on record, "how they planned to analyse it" would be a guess.
|
|
3663
|
+
if (ctx.hasUI && restoreSessionMode(ctx.sessionManager) === "research" && !state.current && state.said.length <= 1 && restateGateTries < 2) {
|
|
3664
|
+
restateGateTries += 1;
|
|
3665
|
+
return { content: [{ type: "text", text: "研究意图还没复述:研究者只发了任务说明。First ask them openly, with no options, in one message: what they most want to find out, the outcome that matters most, how they themselves planned to analyse it, and anything the brief leaves out. Restate after their answer." }], details: { status: "refused" }, isError: true };
|
|
3666
|
+
}
|
|
3667
|
+
const said = [state.said.map((x) => x.text).join("\n"), userTexts(ctx)].join("\n");
|
|
3668
|
+
const result = await restateIntent(ctx.cwd, { items: (params.items ?? []), ...(params.flow ? { flow: params.flow } : {}), materials: materialsText(ctx.cwd), said });
|
|
3669
|
+
if (result.problems.length) {
|
|
3670
|
+
return { content: [{ type: "text", text: ["研究意图还没记下:", ...result.problems.map((p) => `- ${p}`), "Fix these and restate again."].join("\n") }], details: { status: "refused" }, isError: true };
|
|
3671
|
+
}
|
|
3672
|
+
return {
|
|
3673
|
+
content: [{ type: "text", text: [`研究意图 v${result.version} 已记下。Post the message below to the researcher as your whole reply, unchanged, then stop and wait.`, "", renderIntent(result.items, params.flow)].join("\n") }],
|
|
3674
|
+
details: { version: result.version },
|
|
3675
|
+
};
|
|
3676
|
+
}
|
|
3677
|
+
catch (error) {
|
|
3678
|
+
return { content: [{ type: "text", text: `研究意图记录失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
|
|
3679
|
+
}
|
|
3680
|
+
},
|
|
3681
|
+
});
|
|
3682
|
+
pi.registerTool({
|
|
3683
|
+
name: "psyclaw_plan",
|
|
3684
|
+
label: "分析方案",
|
|
3685
|
+
description: "The analysis plan for this project (research mode). action=submit records the proposal (primary outcome, primary analysis, methods, missing data, multiplicity, exclusions) with every decision point in `decisions`; code numbers them D1…Dn and returns one message for the researcher, which you post as your whole reply, then stop. action=answers records the researcher's one reply to that message (all points in one call) and approves the plan when they approved and nothing is left open. action=status shows the plan, its open decisions and what is missing. Running project scripts (other than explore/eda/profile/check ones) waits until the plan is approved.",
|
|
3686
|
+
parameters: Type.Object({
|
|
3687
|
+
action: Type.Union([Type.Literal("submit"), Type.Literal("answers"), Type.Literal("status"), Type.Literal("compare")]),
|
|
3688
|
+
goal: Type.Optional(Type.String({ description: "Research goal; used when no plan exists yet" })),
|
|
3689
|
+
decisions: Type.Optional(Type.Array(Type.Object({
|
|
3690
|
+
rq: Type.Optional(Type.String({ description: "Research-question label, e.g. RQ2" })),
|
|
3691
|
+
question: Type.String(),
|
|
3692
|
+
options: Type.Optional(Type.Array(Type.String())),
|
|
3693
|
+
recommended: Type.Optional(Type.Number({ description: "1-based index of your recommended option" })),
|
|
3694
|
+
by: Type.Optional(Type.Union([Type.Literal("open"), Type.Literal("brief"), Type.Literal("researcher"), Type.Literal("analyst")], { description: "open (default): the researcher decides; brief: the materials settle it (quote them); researcher: the researcher already said it (quote their words); analyst: a convention settles it (reason)" })),
|
|
3695
|
+
quote: Type.Optional(Type.String()),
|
|
3696
|
+
reason: Type.Optional(Type.String()),
|
|
3697
|
+
impact: Type.Optional(Type.Union([Type.Literal("key"), Type.Literal("intent"), Type.Literal("convention")], { description: "key: the choice changes the answer to a research question or the conclusion (at most 4 shown in full); intent: depends on what the researcher wants; convention: the field settles it" })),
|
|
3698
|
+
why: Type.Optional(Type.String({ description: "key points: one line on what changes in the result depending on the choice" })),
|
|
3699
|
+
}), { description: "submit: every decision point of the plan, per research question (sample and exclusions, outcome coding, contrast, summary measure, model, covariates and reference groups, missing data, intervals and multiplicity, what to report)" })),
|
|
3700
|
+
answers: Type.Optional(Type.Array(Type.Object({
|
|
3701
|
+
d: Type.String({ description: "The point, e.g. D3" }),
|
|
3702
|
+
option: Type.Optional(Type.Number({ description: "1-based option number the researcher picked" })),
|
|
3703
|
+
text: Type.Optional(Type.String({ description: "The researcher's own approach, in their words" })),
|
|
3704
|
+
}), { description: "answers: one entry per point the researcher's reply names" })),
|
|
3705
|
+
rest: Type.Optional(Type.Union([Type.Literal("recommended"), Type.Literal("open")], { description: "answers: recommended when the reply accepts the recommendations for the points it does not name (e.g. 全部按推荐, 其余同意, approve as proposed); open otherwise" })),
|
|
3706
|
+
approved: Type.Optional(Type.Boolean({ description: "answers: true when the reply approves the plan" })),
|
|
3707
|
+
quote: Type.Optional(Type.String({ description: "answers: the researcher's reply, unchanged" })),
|
|
3708
|
+
additions: Type.Optional(Type.Array(Type.String(), { description: "answers: analyses the researcher says the plan missed; they are added to the plan" })),
|
|
3709
|
+
agentAdditions: Type.Optional(Type.Array(Type.Object({ analysis: Type.String(), reason: Type.String() }), { description: "submit: analyses you add beyond what the brief and the researcher asked for, each with the reason; shown to the researcher as 我打算补的分析" })),
|
|
3710
|
+
checks: Type.Optional(Type.Array(Type.Object({
|
|
3711
|
+
d: Type.String({ description: "The label of what the researcher asked for (D3, A1, I1 …)" }),
|
|
3712
|
+
status: Type.Union([Type.Literal("done"), Type.Literal("changed"), Type.Literal("not-done")]),
|
|
3713
|
+
where: Type.Optional(Type.String({ description: "done: the script(s) or table(s) that show it, comma-separated, relative paths" })),
|
|
3714
|
+
evidence: Type.Optional(Type.String({ description: "done: words copied verbatim from that file that show it was done as decided (the code line, the column, the row)" })),
|
|
3715
|
+
to: Type.Optional(Type.String({ description: "changed: what was done instead" })),
|
|
3716
|
+
note: Type.Optional(Type.String({ description: "changed / not-done: why" })),
|
|
3717
|
+
}), { description: "compare: one check per item the researcher asked for" })),
|
|
3718
|
+
primaryOutcome: Type.Optional(Type.String()),
|
|
3719
|
+
primaryAnalysis: Type.Optional(Type.String()),
|
|
3720
|
+
proposedMethods: Type.Optional(Type.Array(Type.String())),
|
|
3721
|
+
exploratoryAnalyses: Type.Optional(Type.Array(Type.String())),
|
|
3722
|
+
missingDataPlan: Type.Optional(Type.String()),
|
|
3723
|
+
multiplicityPlan: Type.Optional(Type.String()),
|
|
3724
|
+
exclusionCriteria: Type.Optional(Type.String()),
|
|
3725
|
+
}),
|
|
3726
|
+
executionMode: "sequential",
|
|
3727
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
3728
|
+
try {
|
|
3729
|
+
let plan = await readActiveAnalysisPlan(ctx.cwd);
|
|
3730
|
+
if (params.action === "status") {
|
|
3731
|
+
if (!plan)
|
|
3732
|
+
return { content: [{ type: "text", text: "还没有分析方案。用 psyclaw_plan action=submit 提交。" }], details: { status: "none" } };
|
|
3733
|
+
const open = await openDecisions(ctx.cwd, plan.id);
|
|
3734
|
+
const findings = validateAnalysisPlan(plan).findings.map((f) => `- ${f.severity}: ${f.message}`);
|
|
3735
|
+
return { content: [{ type: "text", text: [formatAnalysisPlanStatus(plan, open.length), ...(findings.length ? ["缺口:", ...findings] : [])].join("\n") }], details: { planId: plan.id, status: plan.status } };
|
|
3736
|
+
}
|
|
3737
|
+
if (params.action === "compare") {
|
|
3738
|
+
// 做法对照 (practice.ts): what the researcher asked for against what was done, from the records.
|
|
3739
|
+
const intent = await readIntent(ctx.cwd).catch(() => undefined);
|
|
3740
|
+
const planDecisions = async () => (await readDecisions(ctx.cwd)).filter((d) => !plan || !d.planId || d.planId === plan.id);
|
|
3741
|
+
let decisions = await planDecisions();
|
|
3742
|
+
const checks = (params.checks ?? []);
|
|
3743
|
+
const rows = askedRows(decisions, intent);
|
|
3744
|
+
const problems = checkProblems(ctx.cwd, rows, checks);
|
|
3745
|
+
if (problems.length) {
|
|
3746
|
+
return { content: [{ type: "text", text: [
|
|
3747
|
+
"做法对照还没生成:", ...problems.map((p) => `- ${p}`), "",
|
|
3748
|
+
"Items the researcher asked for (use these labels):", ...rows.map((r) => `- ${r.label}: ${r.asked}`),
|
|
3749
|
+
"Give one check per item and call compare again.",
|
|
3750
|
+
].join("\n") }], details: { status: "refused" }, isError: true };
|
|
3751
|
+
}
|
|
3752
|
+
for (const c of checks) {
|
|
3753
|
+
const row = rowFor(rows, c.d);
|
|
3754
|
+
if (c.status === "changed" && row?.decisionId)
|
|
3755
|
+
await recordDeviation(ctx.cwd, { id: row.decisionId, choice: c.to, reason: c.note, ...(plan ? { planId: plan.id } : {}) });
|
|
3756
|
+
}
|
|
3757
|
+
decisions = await planDecisions();
|
|
3758
|
+
const markdown = renderPractice(decisions, askedRows(decisions, intent), checks);
|
|
3759
|
+
mkdirSync(join(ctx.cwd, "analysis"), { recursive: true });
|
|
3760
|
+
writeFileSync(join(ctx.cwd, PRACTICE_PATH), markdown);
|
|
3761
|
+
return { content: [{ type: "text", text: [`已写入 ${PRACTICE_PATH}。Put this section at the top of the report, unchanged, and tell the researcher about every item under 我改的.`, "", markdown].join("\n") }], details: { path: PRACTICE_PATH } };
|
|
3762
|
+
}
|
|
3763
|
+
if (params.action === "answers") {
|
|
3764
|
+
if (!plan || !["awaiting-confirm", "ready", "reviewing"].includes(plan.status)) {
|
|
3765
|
+
return { content: [{ type: "text", text: `没有等研究者回复的方案(状态:${plan?.status ?? "无"})。` }], details: { status: plan?.status ?? "none" }, isError: true };
|
|
3766
|
+
}
|
|
3767
|
+
const quote = params.quote?.trim();
|
|
3768
|
+
if (!quote)
|
|
3769
|
+
throw new Error("answers needs quote: the researcher's reply, unchanged");
|
|
3770
|
+
const open = (await openDecisions(ctx.cwd, plan.id)).filter((d) => isPlanPointId(d.id));
|
|
3771
|
+
const { settle, left, problems } = settleFromReply(open, params.answers ?? [], params.rest ?? "open");
|
|
3772
|
+
for (const step of settle) {
|
|
3773
|
+
await recordSettled(ctx.cwd, { id: step.id, by: "researcher", choice: step.choice, quote, via: "text", planId: plan.id });
|
|
3774
|
+
}
|
|
3775
|
+
const additions = (params.additions ?? []).map((a) => a.trim()).filter(Boolean);
|
|
3776
|
+
if (additions.length) {
|
|
3777
|
+
plan = await writeAnalysisPlan(ctx.cwd, advanceAnalysisPlan(plan, { type: "draft", exploratoryAnalyses: [...(plan.exploratoryAnalyses ?? []), ...additions] }));
|
|
3778
|
+
// The researcher's own additions are decisions they made: they go into 做法对照 as 你要的.
|
|
3779
|
+
const prior = (await readDecisions(ctx.cwd)).filter((d) => new RegExp(`^${plan.id}:A\\d+$`).test(d.id)).length;
|
|
3780
|
+
for (const [k, a] of additions.entries()) {
|
|
3781
|
+
await recordSettled(ctx.cwd, { id: `${plan.id}:A${prior + k + 1}`, question: "研究者要补的分析", by: "researcher", choice: a, quote, via: "text", planId: plan.id });
|
|
3782
|
+
}
|
|
3783
|
+
}
|
|
3784
|
+
const stillOpen = await openDecisions(ctx.cwd, plan.id);
|
|
3785
|
+
const lines = [
|
|
3786
|
+
`记下 ${settle.length} 项(${settle.filter((x) => x.named).length} 项研究者点名,${settle.filter((x) => !x.named).length} 项按推荐)。`,
|
|
3787
|
+
...(additions.length ? [`研究者要补的分析已加进方案:${additions.join(";")}。Run them and report them like the planned ones.`] : []),
|
|
3788
|
+
...problems.map((p) => `- ${p}`),
|
|
3789
|
+
];
|
|
3790
|
+
if (stillOpen.length) {
|
|
3791
|
+
lines.push(`还没定:${stillOpen.map((d) => `${pointLabel(d.id)}(${d.question})`).join(";")}。The reply leaves these unclear: ask only these, one psyclaw_ask card each (same id), then wait.`);
|
|
3792
|
+
if (left.length === 0 && problems.length === 0)
|
|
3793
|
+
lines.push("(这些不是本条方案消息里的点。)");
|
|
3794
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { planId: plan.id, open: stillOpen.map((d) => d.id) } };
|
|
3795
|
+
}
|
|
3796
|
+
if (params.approved) {
|
|
3797
|
+
const status = await approvePlanFromCard(ctx.cwd);
|
|
3798
|
+
if (status === "running") {
|
|
3799
|
+
lines.push(`方案 ${plan.id} 已批准,开始执行。Run the analysis as decided now; do not ask the researcher again before the deliverables are done.`);
|
|
3800
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { planId: plan.id, status } };
|
|
3801
|
+
}
|
|
3802
|
+
}
|
|
3803
|
+
lines.push("全部定下了。Ask the researcher to approve the plan with a plain yes (可以 / 批准), then stop.");
|
|
3804
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { planId: plan.id, status: plan.status } };
|
|
3805
|
+
}
|
|
3806
|
+
if (!plan || plan.status === "completed") {
|
|
3807
|
+
plan = createAnalysisPlan({ goal: params.goal?.trim() || params.primaryAnalysis?.trim() || "analysis" });
|
|
3808
|
+
}
|
|
3809
|
+
if (plan.status === "running") {
|
|
3810
|
+
return { content: [{ type: "text", text: `方案 ${plan.id} 已批准并在执行。要改方案,先把改动告诉研究者;改了的决定用 psyclaw_decide 记录(同一个 id)。` }], details: { planId: plan.id, status: plan.status }, isError: true };
|
|
3811
|
+
}
|
|
3812
|
+
// The plan is built on the researcher's confirmed intent (intent.ts). Interactive sessions only;
|
|
3813
|
+
// after two refusals it goes through, with the gap stated.
|
|
3814
|
+
if (ctx.hasUI && restoreSessionMode(ctx.sessionManager) === "research") {
|
|
3815
|
+
const intent = await readIntent(ctx.cwd).catch(() => undefined);
|
|
3816
|
+
if (!intent?.current?.confirmed) {
|
|
3817
|
+
intentGateTries += 1;
|
|
3818
|
+
if (intentGateTries <= 2) {
|
|
3819
|
+
return { content: [{ type: "text", text: [
|
|
3820
|
+
"方案还没提交:研究者还没确认研究意图。",
|
|
3821
|
+
intent?.current
|
|
3822
|
+
? `Restated intent v${intent.current.version} is waiting for the researcher's reply: wait for it, then psyclaw_intent action=confirm.`
|
|
3823
|
+
: "First ask the researcher openly (no options) what they want to find out, the outcome that matters most and how they planned to analyse it; then psyclaw_intent action=restate, post the message and wait.",
|
|
3824
|
+
].join("\n") }], details: { planId: plan.id, status: plan.status, intent: "unconfirmed" }, isError: true };
|
|
3825
|
+
}
|
|
3826
|
+
}
|
|
3827
|
+
}
|
|
3828
|
+
// Decision coverage: each research question needs its analysis choices settled before the plan
|
|
3829
|
+
// goes to the researcher (the 11-29 PI run asked 4 cards for 5 RQs and scored lowest).
|
|
3830
|
+
// Asked twice already: let it through, with the gap stated.
|
|
3831
|
+
// The decision model may promote a convention to the researcher (never the reverse).
|
|
3832
|
+
const submitted = (params.decisions ?? []);
|
|
3833
|
+
const promote = new Set();
|
|
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
|
+
}));
|
|
3842
|
+
const numbered = numberPoints(plan.id, submitted, promote);
|
|
3843
|
+
// Quotes are checked against their source. by brief: the materials or a message (briefs are often pasted);
|
|
3844
|
+
// by researcher: their messages or their answers on cards (which live in the decision record).
|
|
3845
|
+
{
|
|
3846
|
+
const messages = [(await readIntent(ctx.cwd).catch(() => undefined))?.said.map((x) => x.text).join("\n") ?? "", userTexts(ctx)].join("\n");
|
|
3847
|
+
const answers = (await readDecisions(ctx.cwd).catch(() => [])).filter((d) => d.status === "settled" && d.by === "researcher").map((d) => `${d.choice ?? ""}\n${d.quote ?? ""}`).join("\n");
|
|
3848
|
+
const briefText = `${materialsText(ctx.cwd)}\n${messages}`;
|
|
3849
|
+
const researcherText = `${messages}\n${answers}`;
|
|
3850
|
+
submitted.forEach((p, i) => {
|
|
3851
|
+
const quote = p.quote?.trim();
|
|
3852
|
+
if (!quote || (p.by !== "brief" && p.by !== "researcher"))
|
|
3853
|
+
return;
|
|
3854
|
+
if (p.by === "brief" && !quoted(quote, briefText)) {
|
|
3855
|
+
numbered.problems.push(`point ${i + 1} (${p.question}): the quote is not found word for word in the materials or the messages.${quoted(quote, answers) ? " It is the researcher's answer on a card: use by researcher." : " Quote them exactly, or make the point open."}`);
|
|
3856
|
+
}
|
|
3857
|
+
if (p.by === "researcher" && !quoted(quote, researcherText)) {
|
|
3858
|
+
numbered.problems.push(`point ${i + 1} (${p.question}): the quote is not found word for word in the researcher's messages or answers. Quote them exactly, or make the point open.`);
|
|
3859
|
+
}
|
|
3860
|
+
});
|
|
3861
|
+
}
|
|
3862
|
+
if (numbered.problems.length) {
|
|
3863
|
+
return { content: [{ type: "text", text: ["方案还没提交:", ...numbered.problems.map((p) => `- ${p}`), "Fix these points and submit again."].join("\n") }], details: { planId: plan.id, status: plan.status }, isError: true };
|
|
3864
|
+
}
|
|
3865
|
+
const labels = researchQuestionLabels(`${materialsText(ctx.cwd)}\n${userTexts(ctx)}`);
|
|
3866
|
+
if (labels.length > 0) {
|
|
3867
|
+
const recorded = await readDecisions(ctx.cwd).catch(() => []);
|
|
3868
|
+
const text = (d) => JSON.stringify(d).toUpperCase().replace(/\s+/g, "");
|
|
3869
|
+
const all = [...recorded.filter((d) => !isPlanPointId(d.id)), ...numbered.points];
|
|
3870
|
+
const thin = labels.filter((label) => all.filter((d) => text(d).includes(label) || /ALLRQ|EVERYRQ|所有研究问题|全部研究问题/.test(text(d))).length < 3);
|
|
3871
|
+
planSubmitTries += 1;
|
|
3872
|
+
if (thin.length > 0 && planSubmitTries <= 2) {
|
|
3873
|
+
return { content: [{ type: "text", text: [
|
|
3874
|
+
`方案还没提交:这些研究问题的决定点少于 3 项:${thin.join("、")}。`,
|
|
3875
|
+
"For each of them, go through population (sample, exclusions, subgroups), outcome coding, contrast, summary measure, model, covariates and reference groups, missing data, and intervals / multiplicity.",
|
|
3876
|
+
"Put every one into `decisions` with its rq label (e.g. RQ2): open ones with options and your recommendation, brief-settled ones with by brief and the quote, conventions with by analyst and the reason. Then submit again.",
|
|
3877
|
+
].join("\n") }], details: { planId: plan.id, status: plan.status, thin }, isError: true };
|
|
3878
|
+
}
|
|
3879
|
+
}
|
|
3880
|
+
plan = advanceAnalysisPlan(plan, {
|
|
3881
|
+
type: "draft",
|
|
3882
|
+
...(params.primaryOutcome === undefined ? {} : { primaryOutcome: params.primaryOutcome }),
|
|
3883
|
+
...(params.primaryAnalysis === undefined ? {} : { primaryAnalysis: params.primaryAnalysis }),
|
|
3884
|
+
...(params.proposedMethods === undefined ? {} : { proposedMethods: params.proposedMethods }),
|
|
3885
|
+
...(params.exploratoryAnalyses === undefined ? {} : { exploratoryAnalyses: params.exploratoryAnalyses }),
|
|
3886
|
+
...(params.missingDataPlan === undefined ? {} : { missingDataPlan: params.missingDataPlan }),
|
|
3887
|
+
...(params.multiplicityPlan === undefined ? {} : { multiplicityPlan: params.multiplicityPlan }),
|
|
3888
|
+
...(params.exclusionCriteria === undefined ? {} : { exclusionCriteria: params.exclusionCriteria }),
|
|
3889
|
+
});
|
|
3890
|
+
plan = await writeAnalysisPlan(ctx.cwd, plan);
|
|
3891
|
+
if (numbered.points.length) {
|
|
3892
|
+
// A resubmission replaces the earlier numbering: points the researcher already settled keep their answer.
|
|
3893
|
+
const settledBefore = new Map((await readDecisions(ctx.cwd).catch(() => [])).filter((d) => d.status === "settled" && d.by === "researcher").map((d) => [d.id, d]));
|
|
3894
|
+
for (const p of numbered.points) {
|
|
3895
|
+
const options = p.options.map((label, i) => ({ id: String(i + 1), label }));
|
|
3896
|
+
const question = `${p.rq ? `${p.rq} ` : ""}${p.question}`;
|
|
3897
|
+
if (settledBefore.get(p.id)?.question === question)
|
|
3898
|
+
continue;
|
|
3899
|
+
if (!p.open) {
|
|
3900
|
+
await recordSettled(ctx.cwd, { id: p.id, question, by: p.by, choice: p.options[p.recommended - 1] ?? p.quote ?? p.reason, ...(p.quote ? { quote: p.quote } : {}), ...(p.reason ? { reason: p.reason } : {}), ...(p.by === "researcher" ? { via: "text" } : {}), options, planId: plan.id });
|
|
3901
|
+
}
|
|
3902
|
+
else {
|
|
3903
|
+
await recordAsked(ctx.cwd, { id: p.id, question, options, recommendation: p.options[p.recommended - 1], planId: plan.id, context: "plan-message" });
|
|
3904
|
+
}
|
|
3905
|
+
}
|
|
3906
|
+
const kept = new Set(numbered.points.map((p) => p.id));
|
|
3907
|
+
for (const d of await openDecisions(ctx.cwd, plan.id)) {
|
|
3908
|
+
if (isPlanPointId(d.id) && !kept.has(d.id))
|
|
3909
|
+
await recordSettled(ctx.cwd, { id: d.id, by: "analyst", choice: "(不再需要)", reason: "removed from the resubmitted plan", planId: plan.id });
|
|
3910
|
+
}
|
|
3911
|
+
const agentAdditions = (params.agentAdditions ?? []).map((a) => ({ analysis: a.analysis.trim(), reason: a.reason.trim() })).filter((a) => a.analysis && a.reason);
|
|
3912
|
+
for (const [k, a] of agentAdditions.entries()) {
|
|
3913
|
+
await recordSettled(ctx.cwd, { id: `${plan.id}:X${k + 1}`, question: "分析者补充的分析", by: "added", choice: a.analysis, reason: a.reason, planId: plan.id });
|
|
3914
|
+
}
|
|
3915
|
+
const message = renderPlanMessage(plan, numbered.points, agentAdditions);
|
|
3916
|
+
return {
|
|
3917
|
+
content: [{ type: "text", text: [
|
|
3918
|
+
`方案 ${plan.id} 已提交。Post the message below to the researcher as your whole reply, unchanged, then stop and wait. Do not ask cards before their reply.`,
|
|
3919
|
+
...(numbered.promoted.length ? [`(${numbered.promoted.join(", ")} ${numbered.promoted.length === 1 ? "depends" : "depend"} on the researcher's intent, so ${numbered.promoted.length === 1 ? "it is" : "they are"} put to the researcher with your choice as the recommendation.)`] : []),
|
|
3920
|
+
"",
|
|
3921
|
+
message,
|
|
3922
|
+
].join("\n") }],
|
|
3923
|
+
details: { planId: plan.id, status: plan.status, points: numbered.points.map((p) => p.id) },
|
|
3924
|
+
};
|
|
3925
|
+
}
|
|
3926
|
+
const open = await openDecisions(ctx.cwd, plan.id);
|
|
3927
|
+
const findings = validateAnalysisPlan(plan).findings.filter((f) => f.rule.startsWith("missing-")).map((f) => `- ${f.message}`);
|
|
3928
|
+
return {
|
|
3929
|
+
content: [{ type: "text", text: [
|
|
3930
|
+
`方案 ${plan.id} 已提交,等研究者批准。`,
|
|
3931
|
+
open.length ? `还有 ${open.length} 项决定待定:${open.map((d) => d.id).join("、")}。先用 psyclaw_ask 逐项问完。` : "没有待定的决定:请研究者看一下方案,回复「可以」即批准。",
|
|
3932
|
+
...(findings.length ? ["还缺:", ...findings] : []),
|
|
3933
|
+
].join("\n") }],
|
|
3934
|
+
details: { planId: plan.id, status: plan.status, open: open.map((d) => d.id) },
|
|
3935
|
+
};
|
|
3936
|
+
}
|
|
3937
|
+
catch (error) {
|
|
3938
|
+
return { content: [{ type: "text", text: `方案提交失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
|
|
3939
|
+
}
|
|
3940
|
+
},
|
|
3941
|
+
});
|
|
3942
|
+
pi.registerTool({
|
|
3943
|
+
name: "psyclaw_decide",
|
|
3944
|
+
label: "记录决定",
|
|
3945
|
+
description: "Record a research decision in the project's one decision record (.psyclaw/decisions.jsonl; notes/decisions.md is written from it). Use it when the researcher answered in text instead of through psyclaw_ask (by=researcher, quote their words, reuse the id psyclaw_ask gave), when the materials settle a choice (by=brief, quote them), or when you settle it by a stated convention (by=analyst, give the reason). Answers given through psyclaw_ask are recorded by code; do not record them again. Call with action=list to see every decision and which are still open.",
|
|
3946
|
+
parameters: Type.Object({
|
|
3947
|
+
action: Type.Optional(Type.Union([Type.Literal("record"), Type.Literal("list"), Type.Literal("add"), Type.Literal("change")], { description: "record (default), list, add (an analysis you add beyond the request: question = the analysis, reason = why), or change (you change a decision the researcher or the brief settled: id, choice = what you do instead, reason = why; tell the researcher in your next message)" })),
|
|
3948
|
+
id: Type.Optional(Type.String({ description: "The decision id (from psyclaw_ask, or an earlier record) to settle or change" })),
|
|
3949
|
+
question: Type.Optional(Type.String({ description: "What was decided; required for a new decision" })),
|
|
3950
|
+
by: Type.Optional(Type.Union([Type.Literal("researcher"), Type.Literal("brief"), Type.Literal("analyst")])),
|
|
3951
|
+
choice: Type.Optional(Type.String({ description: "The decision itself" })),
|
|
3952
|
+
quote: Type.Optional(Type.String({ description: "by=researcher: the researcher's words, unchanged; by=brief: the words in the materials" })),
|
|
3953
|
+
reason: Type.Optional(Type.String({ description: "by=analyst: the convention followed and its source" })),
|
|
3954
|
+
context: Type.Optional(Type.String()),
|
|
3955
|
+
}),
|
|
3956
|
+
executionMode: "sequential",
|
|
3957
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
3958
|
+
try {
|
|
3959
|
+
if (params.action === "list") {
|
|
3960
|
+
const decisions = await readDecisions(ctx.cwd);
|
|
3961
|
+
return { content: [{ type: "text", text: formatDecisionsBrief(decisions) }], details: { decisions } };
|
|
3962
|
+
}
|
|
3963
|
+
const plan = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
3964
|
+
const planRef = plan && plan.status !== "completed" ? { planId: plan.id } : {};
|
|
3965
|
+
if (params.action === "add") {
|
|
3966
|
+
const analysis = (params.question ?? params.choice ?? "").trim();
|
|
3967
|
+
if (!analysis || !params.reason?.trim())
|
|
3968
|
+
throw new Error("add needs question (the analysis you add) and reason (why)");
|
|
3969
|
+
const event = await recordSettled(ctx.cwd, { question: "分析者补充的分析", by: "added", choice: analysis, reason: params.reason, ...planRef });
|
|
3970
|
+
return { content: [{ type: "text", text: `已记录 ${event.id}(我补的):${analysis}。It is listed under 我补的 in 做法对照.` }], details: { event } };
|
|
3971
|
+
}
|
|
3972
|
+
if (params.action === "change") {
|
|
3973
|
+
if (!params.id || !params.choice || !params.reason)
|
|
3974
|
+
throw new Error("change needs id, choice (what you do instead) and reason");
|
|
3975
|
+
const event = await recordDeviation(ctx.cwd, { id: params.id, choice: params.choice, reason: params.reason, ...planRef });
|
|
3976
|
+
return { content: [{ type: "text", text: `已记录改动 ${event.id}:${event.deviatesFrom?.choice} → ${event.choice}。Tell the researcher in your next message: what they decided, what you do instead and why; it stays under 我改的 until they settle it again.` }], details: { event } };
|
|
3977
|
+
}
|
|
3978
|
+
if (!params.by || !params.choice)
|
|
3979
|
+
throw new Error("record needs by and choice");
|
|
3980
|
+
const event = await recordSettled(ctx.cwd, {
|
|
3981
|
+
...(params.id === undefined ? {} : { id: params.id }),
|
|
3982
|
+
...(params.question === undefined ? {} : { question: params.question }),
|
|
3983
|
+
by: params.by,
|
|
3984
|
+
choice: params.choice,
|
|
3985
|
+
...(params.quote === undefined ? {} : { quote: params.quote }),
|
|
3986
|
+
...(params.reason === undefined ? {} : { reason: params.reason }),
|
|
3987
|
+
via: params.by === "researcher" ? "text" : undefined,
|
|
3988
|
+
...planRef,
|
|
2843
3989
|
...(params.context === undefined ? {} : { context: params.context }),
|
|
2844
3990
|
});
|
|
2845
|
-
|
|
3991
|
+
const open = await openDecisions(ctx.cwd);
|
|
3992
|
+
// Only ever escalates: a decision the analyst settled that the model judges intent-dependent
|
|
3993
|
+
// gets a note to ask the researcher. It never cancels a question.
|
|
3994
|
+
let escalate = "";
|
|
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) {
|
|
3997
|
+
escalate = `\n[psyclaw] 这一项看起来取决于研究者的意图,不是惯例:请用 psyclaw_ask 问研究者(id ${event.id}),给出你的推荐。`;
|
|
3998
|
+
}
|
|
3999
|
+
}
|
|
4000
|
+
return {
|
|
4001
|
+
content: [{ type: "text", text: `已记录 ${event.id}:${event.question} → ${event.choice}${open.length ? `\n还有 ${open.length} 项待定:${open.map((d) => d.id).join("、")}` : ""}${escalate}` }],
|
|
4002
|
+
details: { event, open: open.map((d) => d.id) },
|
|
4003
|
+
};
|
|
2846
4004
|
}
|
|
2847
4005
|
catch (error) {
|
|
2848
|
-
return { content: [{ type: "text", text:
|
|
4006
|
+
return { content: [{ type: "text", text: `决定记录失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
|
|
2849
4007
|
}
|
|
2850
4008
|
},
|
|
2851
4009
|
});
|
|
2852
4010
|
pi.registerTool({
|
|
2853
|
-
name: "
|
|
2854
|
-
label: "
|
|
2855
|
-
description: "
|
|
4011
|
+
name: "psyclaw_ask",
|
|
4012
|
+
label: "询问研究者",
|
|
4013
|
+
description: "Put one question to the researcher as a choice (or a checklist) in the terminal and the Panel. Code records the question and the answer in the project's decision record, so do not record it again. If the researcher does not answer here (no terminal, cancelled, timed out), the question stays open: ask in text and record their answer with psyclaw_decide using the returned id. Give a recommendation when you have one. Do not use free text like 'reply with an option number' instead of this tool.",
|
|
2856
4014
|
parameters: Type.Object({
|
|
4015
|
+
id: Type.Optional(Type.String({ description: "Stable id for this decision; reuse it to ask about the same decision again" })),
|
|
4016
|
+
recommendation: Type.Optional(Type.String({ description: "The option you recommend and why, in one line" })),
|
|
2857
4017
|
title: Type.String({ minLength: 1, description: "弹窗标题,例如「选择下一步」或「分析前核对」" }),
|
|
2858
4018
|
prompt: Type.Optional(Type.String({ description: "可选说明文字" })),
|
|
2859
4019
|
mode: Type.Union([Type.Literal("choice"), Type.Literal("checklist")], {
|
|
@@ -2873,16 +4033,45 @@ export default function psyclawExtension(pi) {
|
|
|
2873
4033
|
executionMode: "sequential",
|
|
2874
4034
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
2875
4035
|
try {
|
|
4036
|
+
// Research mode (11-29): analysis decisions go into the one plan message, not cards. While the restated
|
|
4037
|
+
// intent waits for the researcher, or after it is confirmed and before the plan is submitted, a choice
|
|
4038
|
+
// card is refused (three times at most); checklists and cards after the plan's reply stay allowed.
|
|
4039
|
+
if (ctx.hasUI && params.mode === "choice" && restoreSessionMode(ctx.sessionManager) === "research" && existsSync(join(ctx.cwd, ".psyclaw")) && askGateTries < 3) {
|
|
4040
|
+
const intent = await readIntent(ctx.cwd).catch(() => undefined);
|
|
4041
|
+
const pending = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
4042
|
+
const beforePlan = !pending || pending.status === "clarifying" || pending.status === "drafting" || pending.status === "completed";
|
|
4043
|
+
const reason = intent?.current && !intent.current.confirmed
|
|
4044
|
+
? "The restated intent is waiting for the researcher's reply. Wait for it; if something is unclear, ask in your text reply, not on a card."
|
|
4045
|
+
: intent?.current?.confirmed && beforePlan
|
|
4046
|
+
? "The intent is confirmed and the plan is not submitted yet: put this decision into the plan (psyclaw_plan action=submit, in decisions, with options and your recommendation). Cards are only for what the researcher's reply to the plan leaves unclear."
|
|
4047
|
+
: "";
|
|
4048
|
+
if (reason) {
|
|
4049
|
+
askGateTries += 1;
|
|
4050
|
+
return { content: [{ type: "text", text: `没有发卡片。${reason}` }], details: { status: "refused" }, isError: true };
|
|
4051
|
+
}
|
|
4052
|
+
}
|
|
4053
|
+
// An approval card is one decision: approve, or revise one element. Never a checklist.
|
|
4054
|
+
const approveOption = params.options.find((option) => /^approve$/i.test(option.id) || /^(批准|approve)\b/i.test(option.label));
|
|
4055
|
+
// A single choice always ends with "write my own": the researcher's plan may not be among the options.
|
|
4056
|
+
const mode = approveOption ? "choice" : params.mode;
|
|
4057
|
+
const OWN = "__own";
|
|
4058
|
+
const withOwn = mode === "choice" && !params.options.some((option) => option.id === OWN);
|
|
2876
4059
|
const wakePrompt = buildWakePrompt({
|
|
2877
4060
|
title: params.title,
|
|
2878
|
-
mode
|
|
2879
|
-
options:
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
4061
|
+
mode,
|
|
4062
|
+
options: [
|
|
4063
|
+
...params.options.map((option) => ({
|
|
4064
|
+
id: option.id,
|
|
4065
|
+
label: option.label,
|
|
4066
|
+
...(option.description === undefined ? {} : { description: option.description }),
|
|
4067
|
+
...(option.checked === undefined ? {} : { checked: option.checked }),
|
|
4068
|
+
})),
|
|
4069
|
+
...(withOwn ? [{ id: OWN, label: "别的做法(我来写)" }] : []),
|
|
4070
|
+
],
|
|
4071
|
+
// Show the recommendation in the box itself (the record keeps it as a separate field).
|
|
4072
|
+
...(params.prompt === undefined && params.recommendation === undefined ? {} : {
|
|
4073
|
+
prompt: [params.prompt, params.recommendation ? `推荐:${params.recommendation}` : undefined].filter(Boolean).join("\n"),
|
|
4074
|
+
}),
|
|
2886
4075
|
...(params.allowMultiple === undefined ? {} : { allowMultiple: params.allowMultiple }),
|
|
2887
4076
|
...(params.minSelections === undefined ? {} : { minSelections: params.minSelections }),
|
|
2888
4077
|
...(params.syncVerify === undefined ? {} : { syncVerify: params.syncVerify }),
|
|
@@ -2891,12 +4080,26 @@ export default function psyclawExtension(pi) {
|
|
|
2891
4080
|
if (wakePrompt.mode === "checklist") {
|
|
2892
4081
|
await createWakeVerifyChecklist(ctx.cwd, wakePrompt);
|
|
2893
4082
|
}
|
|
4083
|
+
const activePlan = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
|
|
4084
|
+
const planId = activePlan && activePlan.status !== "completed" ? activePlan.id : undefined;
|
|
4085
|
+
const asked = await recordAsked(ctx.cwd, {
|
|
4086
|
+
...(params.id === undefined ? {} : { id: params.id }),
|
|
4087
|
+
question: [wakePrompt.title, params.prompt].filter(Boolean).join(":") || wakePrompt.title,
|
|
4088
|
+
options: wakePrompt.options.map((option) => ({
|
|
4089
|
+
id: option.id,
|
|
4090
|
+
label: option.label,
|
|
4091
|
+
...(option.description === undefined ? {} : { description: option.description }),
|
|
4092
|
+
})),
|
|
4093
|
+
...(params.recommendation === undefined ? {} : { recommendation: params.recommendation }),
|
|
4094
|
+
...(planId ? { planId } : {}),
|
|
4095
|
+
});
|
|
4096
|
+
const stillOpen = `决定 ${asked.id} 仍待定:研究者没有在这里作答。请用文字问研究者,然后用 psyclaw_decide(id=${asked.id},by=researcher,quote=研究者原话)记录。`;
|
|
2894
4097
|
const timeoutMs = Math.max(5_000, new Date(wakePrompt.expiresAt).getTime() - Date.now());
|
|
2895
4098
|
const panelClients = panelHub.subscriberCount();
|
|
2896
4099
|
if (ctx.hasUI) {
|
|
2897
4100
|
ctx.ui.notify(panelClients > 0
|
|
2898
|
-
?
|
|
2899
|
-
:
|
|
4101
|
+
? `问题已推送到 Panel(${wakePrompt.title});终端里也可以作答`
|
|
4102
|
+
: `请作答:${wakePrompt.title}`, "info");
|
|
2900
4103
|
}
|
|
2901
4104
|
const panelPromise = waitForPanelWakeAnswer(wakePrompt, timeoutMs).then((answer) => ({ ...answer, raced: "panel" }));
|
|
2902
4105
|
const cliPromise = (async () => {
|
|
@@ -2912,7 +4115,9 @@ export default function psyclawExtension(pi) {
|
|
|
2912
4115
|
});
|
|
2913
4116
|
return { promptId: wakePrompt.id, selectedIds: [], source: "cancel", raced: "cli" };
|
|
2914
4117
|
}
|
|
2915
|
-
const uiResult = await ctx.ui.custom((tui, theme, keybindings, done) => new WakeOptionsComponent(wakePrompt.title, wakePrompt.prompt, wakePrompt.mode, wakePrompt.options, Boolean(wakePrompt.allowMultiple), wakePrompt.minSelections ?? 0, tui, theme, keybindings, done
|
|
4118
|
+
const uiResult = await ctx.ui.custom((tui, theme, keybindings, done) => new WakeOptionsComponent(wakePrompt.title, wakePrompt.prompt, wakePrompt.mode, wakePrompt.options, Boolean(wakePrompt.allowMultiple), wakePrompt.minSelections ?? 0, tui, theme, keybindings, done,
|
|
4119
|
+
// Start on the recommended option, so Enter takes the recommendation.
|
|
4120
|
+
recommendedOptionIndex(wakePrompt.options, params.recommendation)), { overlay: true });
|
|
2916
4121
|
if (!uiResult || uiResult.type === "cancel") {
|
|
2917
4122
|
return { promptId: wakePrompt.id, selectedIds: [], source: "cancel", raced: "cli" };
|
|
2918
4123
|
}
|
|
@@ -2930,13 +4135,13 @@ export default function psyclawExtension(pi) {
|
|
|
2930
4135
|
}
|
|
2931
4136
|
if (signal?.aborted) {
|
|
2932
4137
|
return {
|
|
2933
|
-
content: [{ type: "text", text: formatWakeResult({
|
|
4138
|
+
content: [{ type: "text", text: `${formatWakeResult({
|
|
2934
4139
|
status: "cancelled",
|
|
2935
4140
|
source: "cancel",
|
|
2936
4141
|
selectedIds: [],
|
|
2937
4142
|
selectedLabels: [],
|
|
2938
4143
|
panelClients,
|
|
2939
|
-
}) }],
|
|
4144
|
+
})}\n${stillOpen}` }],
|
|
2940
4145
|
details: { status: "cancelled" },
|
|
2941
4146
|
isError: true,
|
|
2942
4147
|
};
|
|
@@ -2960,19 +4165,53 @@ export default function psyclawExtension(pi) {
|
|
|
2960
4165
|
};
|
|
2961
4166
|
if (result.status !== "answered") {
|
|
2962
4167
|
return {
|
|
2963
|
-
content: [{ type: "text", text: formatWakeResult(result) }],
|
|
2964
|
-
details: result,
|
|
4168
|
+
content: [{ type: "text", text: `${formatWakeResult(result)}\n${stillOpen}` }],
|
|
4169
|
+
details: { ...result, decisionId: asked.id },
|
|
4170
|
+
isError: true,
|
|
4171
|
+
};
|
|
4172
|
+
}
|
|
4173
|
+
// "Write my own": ask for the researcher's words and record them as their answer.
|
|
4174
|
+
if (result.selectedIds.includes(OWN)) {
|
|
4175
|
+
const own = ctx.hasUI ? (await ctx.ui.input(`${wakePrompt.title}:写明你要的做法`, "", { timeout: 300_000 }))?.trim() : "";
|
|
4176
|
+
if (own) {
|
|
4177
|
+
await recordSettled(ctx.cwd, { id: asked.id, by: "researcher", choice: own, quote: own, via: "terminal", ...(planId ? { planId } : {}) });
|
|
4178
|
+
return {
|
|
4179
|
+
content: [{ type: "text", text: `研究者没有选列出的选项,写的是:「${own}」\n已记入决定 ${asked.id}。照研究者的原话做;原话没说清的地方再问。` }],
|
|
4180
|
+
details: { ...result, decisionId: asked.id, own },
|
|
4181
|
+
};
|
|
4182
|
+
}
|
|
4183
|
+
return {
|
|
4184
|
+
content: [{ type: "text", text: `研究者选了"别的做法"但没有写内容。决定 ${asked.id} 仍待定:用文字问研究者想怎么做,再用 psyclaw_decide(by=researcher)记录。` }],
|
|
4185
|
+
details: { ...result, decisionId: asked.id },
|
|
2965
4186
|
isError: true,
|
|
2966
4187
|
};
|
|
2967
4188
|
}
|
|
4189
|
+
const choice = result.selectedLabels.join("; ") || (wakePrompt.mode === "checklist" ? "(一项都没勾)" : "");
|
|
4190
|
+
await recordSettled(ctx.cwd, {
|
|
4191
|
+
id: asked.id,
|
|
4192
|
+
by: "researcher",
|
|
4193
|
+
choice: [choice, result.notes].filter(Boolean).join(" — ") || "(未选择)",
|
|
4194
|
+
quote: [choice, result.notes].filter(Boolean).join(" — ") || "(未选择)",
|
|
4195
|
+
selectedIds: result.selectedIds,
|
|
4196
|
+
via: result.source === "panel" ? "panel" : "terminal",
|
|
4197
|
+
...(planId ? { planId } : {}),
|
|
4198
|
+
});
|
|
4199
|
+
let planNote = "";
|
|
4200
|
+
if (approveOption && result.selectedIds.includes(approveOption.id)) {
|
|
4201
|
+
const status = await approvePlanFromCard(ctx.cwd);
|
|
4202
|
+
if (status === "running")
|
|
4203
|
+
planNote = "\n方案已批准,状态改为 running:现在执行正式分析。";
|
|
4204
|
+
else if (status === undefined && planId)
|
|
4205
|
+
planNote = "\n还有待定的决定,方案暂未改为 running:先逐项定完。";
|
|
4206
|
+
}
|
|
2968
4207
|
return {
|
|
2969
|
-
content: [{ type: "text", text: formatWakeResult(result) }],
|
|
2970
|
-
details: result,
|
|
4208
|
+
content: [{ type: "text", text: `${formatWakeResult(result)}\n已记入决定 ${asked.id}。${planNote}` }],
|
|
4209
|
+
details: { ...result, decisionId: asked.id },
|
|
2971
4210
|
};
|
|
2972
4211
|
}
|
|
2973
4212
|
catch (error) {
|
|
2974
4213
|
return {
|
|
2975
|
-
content: [{ type: "text", text:
|
|
4214
|
+
content: [{ type: "text", text: `询问失败:${error instanceof Error ? error.message : String(error)}` }],
|
|
2976
4215
|
details: { status: "failed" },
|
|
2977
4216
|
isError: true,
|
|
2978
4217
|
};
|