@goonnguyen/human-mcp 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +296 -45
  2. package/dist/index.js +2383 -0
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -165962,6 +165962,2388 @@ async function handleVoiceCustomization(geminiClient, args, config) {
165962
165962
  };
165963
165963
  }
165964
165964
 
165965
+ // src/tools/brain/types.ts
165966
+ class ThinkingError extends Error {
165967
+ code;
165968
+ context;
165969
+ constructor(message, code, context) {
165970
+ super(message);
165971
+ this.code = code;
165972
+ this.context = context;
165973
+ this.name = "ThinkingError";
165974
+ }
165975
+ }
165976
+ class InvalidRevisionError extends ThinkingError {
165977
+ constructor(thoughtNumber, maxThoughts) {
165978
+ super(`Cannot revise thought ${thoughtNumber}: out of range (max: ${maxThoughts})`, "INVALID_REVISION", { thoughtNumber, maxThoughts });
165979
+ }
165980
+ }
165981
+
165982
+ class BranchingError extends ThinkingError {
165983
+ constructor(reason) {
165984
+ super(`Branching failed: ${reason}`, "BRANCHING_ERROR", { reason });
165985
+ }
165986
+ }
165987
+
165988
+ // src/tools/brain/utils/thought-manager.ts
165989
+ class ThoughtManager {
165990
+ process;
165991
+ options;
165992
+ constructor(problem, thinkingStyle = "analytical", context, options = {}) {
165993
+ this.options = {
165994
+ maxThoughts: 10,
165995
+ allowRevision: true,
165996
+ enableBranching: true,
165997
+ requireEvidence: false,
165998
+ confidenceThreshold: 0.7,
165999
+ timeLimit: 60,
166000
+ outputDetail: "detailed",
166001
+ ...options
166002
+ };
166003
+ this.process = {
166004
+ id: v4_default(),
166005
+ problem,
166006
+ thoughts: [],
166007
+ currentThought: 0,
166008
+ totalThoughts: this.options.maxThoughts || 10,
166009
+ branches: [],
166010
+ hypotheses: [],
166011
+ conclusions: [],
166012
+ metadata: {
166013
+ startTime: new Date,
166014
+ thinkingStyle,
166015
+ complexity: this.determineComplexity(problem),
166016
+ domain: context?.domain,
166017
+ revisionsCount: 0,
166018
+ branchesCount: 0,
166019
+ hypothesesCount: 0
166020
+ }
166021
+ };
166022
+ logger2.info(`Starting thought process for: ${problem.substring(0, 100)}...`);
166023
+ }
166024
+ addThought(content, confidence = 0.8, options = {}) {
166025
+ const thoughtStep = {
166026
+ id: v4_default(),
166027
+ number: this.process.currentThought + 1,
166028
+ content,
166029
+ confidence: Math.min(Math.max(confidence, 0), 1),
166030
+ timestamp: new Date,
166031
+ isRevision: options.isRevision || false,
166032
+ revisesThought: options.revisesThought,
166033
+ branchId: options.branchId,
166034
+ branchFromThought: options.branchFromThought,
166035
+ dependencies: options.dependencies,
166036
+ tags: options.tags
166037
+ };
166038
+ if (options.isRevision && options.revisesThought) {
166039
+ if (!this.options.allowRevision) {
166040
+ throw new Error("Revision not allowed in current processing mode");
166041
+ }
166042
+ if (options.revisesThought > this.process.thoughts.length) {
166043
+ throw new InvalidRevisionError(options.revisesThought, this.process.thoughts.length);
166044
+ }
166045
+ this.process.metadata.revisionsCount++;
166046
+ thoughtStep.tags = [...thoughtStep.tags || [], "revision"];
166047
+ }
166048
+ if (options.branchId && options.branchFromThought) {
166049
+ if (!this.options.enableBranching) {
166050
+ throw new Error("Branching not allowed in current processing mode");
166051
+ }
166052
+ this.process.metadata.branchesCount++;
166053
+ thoughtStep.tags = [...thoughtStep.tags || [], "branch"];
166054
+ }
166055
+ this.process.thoughts.push(thoughtStep);
166056
+ this.process.currentThought = thoughtStep.number;
166057
+ logger2.debug(`Added thought ${thoughtStep.number}: ${content.substring(0, 100)}...`);
166058
+ return thoughtStep;
166059
+ }
166060
+ createBranch(fromThought, name, initialThought) {
166061
+ if (!this.options.enableBranching) {
166062
+ throw new BranchingError("Branching is disabled");
166063
+ }
166064
+ if (fromThought < 1 || fromThought > this.process.thoughts.length) {
166065
+ throw new BranchingError(`Invalid thought number: ${fromThought}`);
166066
+ }
166067
+ const branch = {
166068
+ id: v4_default(),
166069
+ name,
166070
+ fromThought,
166071
+ thoughts: [],
166072
+ isActive: true,
166073
+ confidence: 0.5
166074
+ };
166075
+ if (initialThought) {
166076
+ const branchThought = this.addThought(initialThought, 0.6, {
166077
+ branchId: branch.id,
166078
+ branchFromThought: fromThought,
166079
+ tags: ["branch_start"]
166080
+ });
166081
+ branch.thoughts.push(branchThought);
166082
+ }
166083
+ this.process.branches.push(branch);
166084
+ logger2.info(`Created branch "${name}" from thought ${fromThought}`);
166085
+ return branch;
166086
+ }
166087
+ addHypothesis(statement, evidence = [], counterEvidence = [], confidence = 0.5) {
166088
+ const hypothesis = {
166089
+ id: v4_default(),
166090
+ statement,
166091
+ evidence,
166092
+ counterEvidence,
166093
+ confidence: Math.min(Math.max(confidence, 0), 1),
166094
+ tested: false,
166095
+ generatedAt: this.process.currentThought
166096
+ };
166097
+ this.process.hypotheses.push(hypothesis);
166098
+ this.process.metadata.hypothesesCount++;
166099
+ logger2.debug(`Added hypothesis: ${statement}`);
166100
+ return hypothesis;
166101
+ }
166102
+ testHypothesis(hypothesisId, result, additionalEvidence) {
166103
+ const hypothesis = this.process.hypotheses.find((h) => h.id === hypothesisId);
166104
+ if (!hypothesis) {
166105
+ throw new Error(`Hypothesis not found: ${hypothesisId}`);
166106
+ }
166107
+ hypothesis.tested = true;
166108
+ hypothesis.result = result;
166109
+ if (additionalEvidence) {
166110
+ if (result === "confirmed") {
166111
+ hypothesis.evidence.push(...additionalEvidence);
166112
+ } else if (result === "rejected") {
166113
+ hypothesis.counterEvidence.push(...additionalEvidence);
166114
+ }
166115
+ }
166116
+ if (result === "confirmed") {
166117
+ hypothesis.confidence = Math.min(hypothesis.confidence + 0.3, 1);
166118
+ } else if (result === "rejected") {
166119
+ hypothesis.confidence = Math.max(hypothesis.confidence - 0.4, 0);
166120
+ }
166121
+ logger2.info(`Tested hypothesis "${hypothesis.statement}": ${result}`);
166122
+ return hypothesis;
166123
+ }
166124
+ addConclusion(statement, supportingThoughts, reasoning, confidence = 0.8, alternatives) {
166125
+ const conclusion = {
166126
+ id: v4_default(),
166127
+ statement,
166128
+ supportingThoughts,
166129
+ confidence: Math.min(Math.max(confidence, 0), 1),
166130
+ reasoning,
166131
+ alternatives
166132
+ };
166133
+ this.process.conclusions.push(conclusion);
166134
+ logger2.info(`Added conclusion: ${statement}`);
166135
+ return conclusion;
166136
+ }
166137
+ getProcess() {
166138
+ return { ...this.process };
166139
+ }
166140
+ getThoughts(filter) {
166141
+ let thoughts = [...this.process.thoughts];
166142
+ if (filter) {
166143
+ if (filter.branchId) {
166144
+ thoughts = thoughts.filter((t) => t.branchId === filter.branchId);
166145
+ }
166146
+ if (filter.tags) {
166147
+ thoughts = thoughts.filter((t) => t.tags && filter.tags.some((tag) => t.tags.includes(tag)));
166148
+ }
166149
+ if (filter.minConfidence !== undefined) {
166150
+ thoughts = thoughts.filter((t) => t.confidence >= filter.minConfidence);
166151
+ }
166152
+ if (filter.isRevision !== undefined) {
166153
+ thoughts = thoughts.filter((t) => t.isRevision === filter.isRevision);
166154
+ }
166155
+ }
166156
+ return thoughts;
166157
+ }
166158
+ getActiveHypotheses() {
166159
+ return this.process.hypotheses.filter((h) => !h.tested);
166160
+ }
166161
+ getTestedHypotheses() {
166162
+ return this.process.hypotheses.filter((h) => h.tested);
166163
+ }
166164
+ needsMoreThoughts() {
166165
+ const avgConfidence = this.getAverageConfidence();
166166
+ const hasConclusions = this.process.conclusions.length > 0;
166167
+ const underThoughtLimit = this.process.currentThought < (this.options.maxThoughts || 10);
166168
+ const underConfidenceThreshold = avgConfidence < (this.options.confidenceThreshold || 0.7);
166169
+ return underThoughtLimit && (underConfidenceThreshold || !hasConclusions);
166170
+ }
166171
+ finalize() {
166172
+ this.process.metadata.endTime = new Date;
166173
+ this.process.metadata.totalDuration = this.process.metadata.endTime.getTime() - this.process.metadata.startTime.getTime();
166174
+ logger2.info(`Finalized thought process with ${this.process.thoughts.length} thoughts`);
166175
+ return this.process;
166176
+ }
166177
+ getAverageConfidence() {
166178
+ if (this.process.thoughts.length === 0)
166179
+ return 0;
166180
+ const totalConfidence = this.process.thoughts.reduce((sum, thought) => sum + thought.confidence, 0);
166181
+ return totalConfidence / this.process.thoughts.length;
166182
+ }
166183
+ determineComplexity(problem) {
166184
+ const length = problem.length;
166185
+ const technicalTerms = this.countTechnicalTerms(problem);
166186
+ const questionComplexity = this.analyzeQuestionComplexity(problem);
166187
+ if (length < 100 && technicalTerms < 2 && questionComplexity === "simple") {
166188
+ return "simple";
166189
+ } else if (length < 300 && technicalTerms < 5 && questionComplexity !== "expert") {
166190
+ return "medium";
166191
+ } else if (length < 800 && technicalTerms < 10) {
166192
+ return "complex";
166193
+ } else {
166194
+ return "expert";
166195
+ }
166196
+ }
166197
+ countTechnicalTerms(text) {
166198
+ const technicalPatterns = [
166199
+ /\b(algorithm|architecture|database|server|client|API|framework|library|protocol|interface|implementation|optimization|performance|scalability|security|authentication|authorization|encryption|deployment|infrastructure|microservice|container|docker|kubernetes|cloud|aws|azure|gcp)\b/gi,
166200
+ /\b[A-Z]{2,}\b/g,
166201
+ /\b\w+\.(js|ts|py|java|cpp|c|go|rust|php|rb|cs)\b/g
166202
+ ];
166203
+ return technicalPatterns.reduce((count, pattern) => {
166204
+ const matches = text.match(pattern);
166205
+ return count + (matches ? matches.length : 0);
166206
+ }, 0);
166207
+ }
166208
+ analyzeQuestionComplexity(text) {
166209
+ const complexKeywords = ["why", "how", "analyze", "compare", "evaluate", "design", "optimize", "troubleshoot"];
166210
+ const expertKeywords = ["architect", "strategy", "paradigm", "methodology", "framework", "ecosystem"];
166211
+ const hasComplexKeywords = complexKeywords.some((keyword) => text.toLowerCase().includes(keyword));
166212
+ const hasExpertKeywords = expertKeywords.some((keyword) => text.toLowerCase().includes(keyword));
166213
+ if (hasExpertKeywords)
166214
+ return "expert";
166215
+ if (hasComplexKeywords)
166216
+ return "complex";
166217
+ if (text.includes("?") || text.includes("explain"))
166218
+ return "medium";
166219
+ return "simple";
166220
+ }
166221
+ }
166222
+
166223
+ // src/tools/brain/utils/reasoning-engine.ts
166224
+ class ReasoningEngine {
166225
+ geminiClient;
166226
+ constructor(geminiClient) {
166227
+ this.geminiClient = geminiClient;
166228
+ }
166229
+ async generateThought(problem, previousThoughts, thinkingStyle, thoughtNumber, context) {
166230
+ const prompt = this.buildThoughtPrompt(problem, previousThoughts, thinkingStyle, thoughtNumber, context);
166231
+ try {
166232
+ const model = this.geminiClient.getModel("detailed");
166233
+ const response = await model.generateContent(prompt);
166234
+ const result = response.response;
166235
+ const content = result.text();
166236
+ if (!content) {
166237
+ throw new APIError("No content generated from reasoning engine");
166238
+ }
166239
+ const confidence = this.extractConfidence(content) || this.estimateConfidence(content, previousThoughts);
166240
+ logger2.debug(`Generated thought ${thoughtNumber}: ${content.substring(0, 100)}...`);
166241
+ return {
166242
+ content: this.cleanThoughtContent(content),
166243
+ confidence
166244
+ };
166245
+ } catch (error) {
166246
+ logger2.error(`Failed to generate thought ${thoughtNumber}:`, error);
166247
+ throw new APIError(`Failed to generate thought: ${error instanceof Error ? error.message : "Unknown error"}`);
166248
+ }
166249
+ }
166250
+ async generateHypothesis(problem, thoughts, thinkingStyle) {
166251
+ const prompt = this.buildHypothesisPrompt(problem, thoughts, thinkingStyle);
166252
+ try {
166253
+ const model = this.geminiClient.getModel("detailed");
166254
+ const response = await model.generateContent(prompt);
166255
+ const result = response.response;
166256
+ const content = result.text();
166257
+ if (!content) {
166258
+ throw new APIError("No hypothesis generated");
166259
+ }
166260
+ const parsed = this.parseHypothesisResponse(content);
166261
+ logger2.debug(`Generated hypothesis: ${parsed.statement}`);
166262
+ return parsed;
166263
+ } catch (error) {
166264
+ logger2.error("Failed to generate hypothesis:", error);
166265
+ throw new APIError(`Failed to generate hypothesis: ${error instanceof Error ? error.message : "Unknown error"}`);
166266
+ }
166267
+ }
166268
+ async testHypothesis(hypothesis, thoughts, additionalContext) {
166269
+ const prompt = this.buildHypothesisTestPrompt(hypothesis, thoughts, additionalContext);
166270
+ try {
166271
+ const model = this.geminiClient.getModel("detailed");
166272
+ const response = await model.generateContent(prompt);
166273
+ const result = response.response;
166274
+ const content = result.text();
166275
+ if (!content) {
166276
+ throw new APIError("No hypothesis test result generated");
166277
+ }
166278
+ const parsed = this.parseHypothesisTestResponse(content);
166279
+ logger2.info(`Tested hypothesis "${hypothesis.statement}": ${parsed.result}`);
166280
+ return parsed;
166281
+ } catch (error) {
166282
+ logger2.error("Failed to test hypothesis:", error);
166283
+ throw new APIError(`Failed to test hypothesis: ${error instanceof Error ? error.message : "Unknown error"}`);
166284
+ }
166285
+ }
166286
+ async synthesizeAnalysis(problem, thoughts, hypotheses, thinkingStyle, context) {
166287
+ const prompt = this.buildSynthesisPrompt(problem, thoughts, hypotheses, thinkingStyle, context);
166288
+ try {
166289
+ const model = this.geminiClient.getModel("detailed");
166290
+ const response = await model.generateContent(prompt);
166291
+ const result = response.response;
166292
+ const content = result.text();
166293
+ if (!content) {
166294
+ throw new APIError("No synthesis generated");
166295
+ }
166296
+ const parsed = this.parseSynthesisResponse(content);
166297
+ logger2.info(`Synthesized analysis with confidence ${parsed.confidence}`);
166298
+ return parsed;
166299
+ } catch (error) {
166300
+ logger2.error("Failed to synthesize analysis:", error);
166301
+ throw new APIError(`Failed to synthesize analysis: ${error instanceof Error ? error.message : "Unknown error"}`);
166302
+ }
166303
+ }
166304
+ buildThoughtPrompt(problem, previousThoughts, thinkingStyle, thoughtNumber, context) {
166305
+ const styleInstructions = this.getStyleInstructions(thinkingStyle);
166306
+ const thoughtsContext = this.formatPreviousThoughts(previousThoughts);
166307
+ const contextInfo = context ? this.formatContext(context) : "";
166308
+ return `You are an expert reasoning system using ${thinkingStyle} thinking to analyze problems step by step.
166309
+
166310
+ ${styleInstructions}
166311
+
166312
+ **Problem to analyze:**
166313
+ ${problem}
166314
+
166315
+ ${contextInfo}
166316
+
166317
+ **Previous thoughts (${previousThoughts.length}):**
166318
+ ${thoughtsContext}
166319
+
166320
+ **Current task:**
166321
+ Generate thought #${thoughtNumber} that builds on previous analysis. Be specific, logical, and provide actionable insights.
166322
+
166323
+ **Requirements:**
166324
+ - Build upon previous thoughts without repeating them
166325
+ - Provide specific, concrete insights
166326
+ - Include confidence assessment
166327
+ - Consider evidence and assumptions
166328
+ - Identify gaps or questions if any
166329
+
166330
+ **Response format:**
166331
+ Provide your thought followed by [Confidence: X.XX] where X.XX is a decimal between 0.00 and 1.00.
166332
+
166333
+ Your thought #${thoughtNumber}:`;
166334
+ }
166335
+ buildHypothesisPrompt(problem, thoughts, thinkingStyle) {
166336
+ const thoughtsContext = this.formatPreviousThoughts(thoughts);
166337
+ return `Based on the analysis so far, generate a testable hypothesis about the problem.
166338
+
166339
+ **Problem:**
166340
+ ${problem}
166341
+
166342
+ **Analysis so far:**
166343
+ ${thoughtsContext}
166344
+
166345
+ **Task:**
166346
+ Generate a specific, testable hypothesis that could explain or solve the problem.
166347
+
166348
+ **Requirements:**
166349
+ - Make it specific and testable
166350
+ - Provide supporting evidence from the analysis
166351
+ - Include confidence level
166352
+ - Suggest how it could be tested
166353
+
166354
+ **Response format:**
166355
+ HYPOTHESIS: [Your hypothesis statement]
166356
+ EVIDENCE: [Supporting evidence points, one per line]
166357
+ CONFIDENCE: [0.00-1.00]
166358
+
166359
+ Your response:`;
166360
+ }
166361
+ buildHypothesisTestPrompt(hypothesis, thoughts, additionalContext) {
166362
+ const thoughtsContext = this.formatPreviousThoughts(thoughts);
166363
+ return `Evaluate the following hypothesis based on available evidence and reasoning.
166364
+
166365
+ **Hypothesis to test:**
166366
+ ${hypothesis.statement}
166367
+
166368
+ **Supporting evidence:**
166369
+ ${hypothesis.evidence.map((e) => `- ${e}`).join(`
166370
+ `)}
166371
+
166372
+ **Counter evidence:**
166373
+ ${hypothesis.counterEvidence.map((e) => `- ${e}`).join(`
166374
+ `)}
166375
+
166376
+ **Analysis context:**
166377
+ ${thoughtsContext}
166378
+
166379
+ ${additionalContext ? `**Additional context:**
166380
+ ${additionalContext}
166381
+ ` : ""}
166382
+
166383
+ **Task:**
166384
+ Evaluate whether this hypothesis is confirmed, rejected, or inconclusive based on the evidence.
166385
+
166386
+ **Response format:**
166387
+ RESULT: [CONFIRMED|REJECTED|INCONCLUSIVE]
166388
+ REASONING: [Detailed reasoning for your conclusion]
166389
+ EVIDENCE: [Additional evidence supporting your conclusion, one per line]
166390
+
166391
+ Your evaluation:`;
166392
+ }
166393
+ buildSynthesisPrompt(problem, thoughts, hypotheses, thinkingStyle, context) {
166394
+ const thoughtsContext = this.formatPreviousThoughts(thoughts);
166395
+ const hypothesesContext = this.formatHypotheses(hypotheses);
166396
+ const contextInfo = context ? this.formatContext(context) : "";
166397
+ return `Synthesize a comprehensive analysis based on all the reasoning completed so far.
166398
+
166399
+ **Original problem:**
166400
+ ${problem}
166401
+
166402
+ ${contextInfo}
166403
+
166404
+ **Complete thought process:**
166405
+ ${thoughtsContext}
166406
+
166407
+ **Hypotheses tested:**
166408
+ ${hypothesesContext}
166409
+
166410
+ **Task:**
166411
+ Provide a comprehensive final analysis that synthesizes all insights, conclusions, and recommendations.
166412
+
166413
+ **Requirements:**
166414
+ - Summarize key findings and insights
166415
+ - Provide clear conclusions with confidence levels
166416
+ - Include actionable recommendations
166417
+ - Suggest logical next steps
166418
+ - Acknowledge limitations or uncertainties
166419
+
166420
+ **Response format:**
166421
+ ANALYSIS: [Comprehensive analysis and conclusions]
166422
+ CONFIDENCE: [0.00-1.00]
166423
+ RECOMMENDATIONS: [Actionable recommendations, one per line]
166424
+ NEXT_STEPS: [Logical next steps, one per line]
166425
+
166426
+ Your synthesis:`;
166427
+ }
166428
+ getStyleInstructions(style) {
166429
+ const instructions = {
166430
+ analytical: "Use logical, step-by-step analysis. Break down complex problems into components. Focus on cause-and-effect relationships.",
166431
+ systematic: "Follow a methodical, structured approach. Use frameworks and established methodologies. Ensure completeness and consistency.",
166432
+ creative: "Think outside the box. Consider unconventional approaches. Generate innovative solutions and alternatives.",
166433
+ scientific: "Use hypothesis-driven investigation. Seek evidence and test assumptions. Apply scientific method principles.",
166434
+ critical: "Question assumptions and evaluate evidence critically. Consider biases and alternative perspectives. Challenge conventional thinking.",
166435
+ strategic: "Think long-term and high-level. Consider broader implications and context. Focus on strategic planning and positioning.",
166436
+ intuitive: "Use pattern recognition and experience-based insights. Trust experienced judgment while validating with evidence.",
166437
+ collaborative: "Consider multiple perspectives and stakeholder viewpoints. Seek consensus and collaborative solutions."
166438
+ };
166439
+ return instructions[style] || instructions.analytical;
166440
+ }
166441
+ formatPreviousThoughts(thoughts) {
166442
+ if (thoughts.length === 0) {
166443
+ return "No previous thoughts yet.";
166444
+ }
166445
+ return thoughts.map((thought) => {
166446
+ const revisionNote = thought.isRevision ? " (REVISION)" : "";
166447
+ const branchNote = thought.branchId ? " (BRANCH)" : "";
166448
+ return `${thought.number}. ${thought.content} [Confidence: ${thought.confidence.toFixed(2)}]${revisionNote}${branchNote}`;
166449
+ }).join(`
166450
+
166451
+ `);
166452
+ }
166453
+ formatHypotheses(hypotheses) {
166454
+ if (hypotheses.length === 0) {
166455
+ return "No hypotheses tested yet.";
166456
+ }
166457
+ return hypotheses.map((hyp) => {
166458
+ const status = hyp.tested ? ` - ${hyp.result?.toUpperCase()}` : " - NOT TESTED";
166459
+ return `- ${hyp.statement} [Confidence: ${hyp.confidence.toFixed(2)}]${status}`;
166460
+ }).join(`
166461
+ `);
166462
+ }
166463
+ formatContext(context) {
166464
+ const parts = [];
166465
+ if (context.domain)
166466
+ parts.push(`**Domain:** ${context.domain}`);
166467
+ if (context.background)
166468
+ parts.push(`**Background:** ${context.background}`);
166469
+ if (context.constraints?.length)
166470
+ parts.push(`**Constraints:** ${context.constraints.join(", ")}`);
166471
+ if (context.requirements?.length)
166472
+ parts.push(`**Requirements:** ${context.requirements.join(", ")}`);
166473
+ if (context.timeframe)
166474
+ parts.push(`**Timeframe:** ${context.timeframe}`);
166475
+ return parts.length > 0 ? parts.join(`
166476
+ `) + `
166477
+ ` : "";
166478
+ }
166479
+ extractConfidence(content) {
166480
+ const confidenceMatch = content.match(/\[Confidence:\s*(\d*\.?\d+)\]/i);
166481
+ if (confidenceMatch && confidenceMatch[1]) {
166482
+ const confidence = parseFloat(confidenceMatch[1]);
166483
+ return Math.min(Math.max(confidence, 0), 1);
166484
+ }
166485
+ return null;
166486
+ }
166487
+ estimateConfidence(content, previousThoughts) {
166488
+ let confidence = 0.5;
166489
+ if (content.length > 200)
166490
+ confidence += 0.1;
166491
+ if (content.length > 500)
166492
+ confidence += 0.1;
166493
+ if (content.includes("specifically") || content.includes("evidence") || content.includes("data")) {
166494
+ confidence += 0.1;
166495
+ }
166496
+ if (previousThoughts.length > 0 && (content.includes("previous") || content.includes("building on"))) {
166497
+ confidence += 0.1;
166498
+ }
166499
+ if (content.includes("might") || content.includes("possibly") || content.includes("unclear")) {
166500
+ confidence -= 0.1;
166501
+ }
166502
+ return Math.min(Math.max(confidence, 0.1), 0.9);
166503
+ }
166504
+ cleanThoughtContent(content) {
166505
+ return content.replace(/\[Confidence:\s*\d*\.?\d+\]/gi, "").replace(/^Your thought #\d+:\s*/i, "").replace(/^Thought #?\d+:?\s*/i, "").trim();
166506
+ }
166507
+ parseHypothesisResponse(content) {
166508
+ const lines = content.split(`
166509
+ `).map((line) => line.trim()).filter((line) => line);
166510
+ let statement = "";
166511
+ let confidence = 0.5;
166512
+ const evidence = [];
166513
+ for (const line of lines) {
166514
+ if (line.startsWith("HYPOTHESIS:")) {
166515
+ statement = line.replace("HYPOTHESIS:", "").trim();
166516
+ } else if (line.startsWith("CONFIDENCE:")) {
166517
+ const confMatch = line.match(/(\d*\.?\d+)/);
166518
+ if (confMatch && confMatch[1]) {
166519
+ confidence = Math.min(Math.max(parseFloat(confMatch[1]), 0), 1);
166520
+ }
166521
+ } else if (line.startsWith("EVIDENCE:")) {
166522
+ continue;
166523
+ } else if (line.startsWith("- ") || line.startsWith("* ")) {
166524
+ evidence.push(line.replace(/^[-*]\s*/, ""));
166525
+ }
166526
+ }
166527
+ return {
166528
+ statement: statement || "Generated hypothesis",
166529
+ confidence,
166530
+ evidence
166531
+ };
166532
+ }
166533
+ parseHypothesisTestResponse(content) {
166534
+ const lines = content.split(`
166535
+ `).map((line) => line.trim()).filter((line) => line);
166536
+ let result = "inconclusive";
166537
+ let reasoning = "";
166538
+ const evidence = [];
166539
+ for (const line of lines) {
166540
+ if (line.startsWith("RESULT:")) {
166541
+ const resultText = line.replace("RESULT:", "").trim().toLowerCase();
166542
+ if (resultText.includes("confirmed"))
166543
+ result = "confirmed";
166544
+ else if (resultText.includes("rejected"))
166545
+ result = "rejected";
166546
+ else
166547
+ result = "inconclusive";
166548
+ } else if (line.startsWith("REASONING:")) {
166549
+ reasoning = line.replace("REASONING:", "").trim();
166550
+ } else if (line.startsWith("EVIDENCE:")) {
166551
+ continue;
166552
+ } else if (line.startsWith("- ") || line.startsWith("* ")) {
166553
+ evidence.push(line.replace(/^[-*]\s*/, ""));
166554
+ }
166555
+ }
166556
+ return { result, evidence, reasoning };
166557
+ }
166558
+ parseSynthesisResponse(content) {
166559
+ const lines = content.split(`
166560
+ `).map((line) => line.trim()).filter((line) => line);
166561
+ let analysis = "";
166562
+ let confidence = 0.7;
166563
+ const recommendations = [];
166564
+ const nextSteps = [];
166565
+ let currentSection = "";
166566
+ for (const line of lines) {
166567
+ if (line.startsWith("ANALYSIS:")) {
166568
+ currentSection = "analysis";
166569
+ analysis = line.replace("ANALYSIS:", "").trim();
166570
+ } else if (line.startsWith("CONFIDENCE:")) {
166571
+ const confMatch = line.match(/(\d*\.?\d+)/);
166572
+ if (confMatch && confMatch[1]) {
166573
+ confidence = Math.min(Math.max(parseFloat(confMatch[1]), 0), 1);
166574
+ }
166575
+ } else if (line.startsWith("RECOMMENDATIONS:")) {
166576
+ currentSection = "recommendations";
166577
+ } else if (line.startsWith("NEXT_STEPS:")) {
166578
+ currentSection = "nextSteps";
166579
+ } else if (line.startsWith("- ") || line.startsWith("* ")) {
166580
+ const item = line.replace(/^[-*]\s*/, "");
166581
+ if (currentSection === "recommendations") {
166582
+ recommendations.push(item);
166583
+ } else if (currentSection === "nextSteps") {
166584
+ nextSteps.push(item);
166585
+ }
166586
+ } else if (currentSection === "analysis" && line) {
166587
+ analysis += (analysis ? " " : "") + line;
166588
+ }
166589
+ }
166590
+ return {
166591
+ analysis: analysis || "Analysis completed",
166592
+ confidence,
166593
+ recommendations,
166594
+ nextSteps
166595
+ };
166596
+ }
166597
+ }
166598
+
166599
+ // src/tools/brain/processors/sequential-thinking.ts
166600
+ class SequentialThinkingProcessor {
166601
+ geminiClient;
166602
+ reasoningEngine;
166603
+ constructor(geminiClient) {
166604
+ this.geminiClient = geminiClient;
166605
+ this.reasoningEngine = new ReasoningEngine(geminiClient);
166606
+ }
166607
+ async process(input) {
166608
+ const startTime = Date.now();
166609
+ try {
166610
+ logger2.info(`Starting sequential thinking for: ${input.problem.substring(0, 100)}...`);
166611
+ const thoughtManager = new ThoughtManager(input.problem, input.thinkingStyle || "analytical", input.context, input.options);
166612
+ await this.generateInitialThoughts(thoughtManager, input);
166613
+ await this.continueThinking(thoughtManager, input);
166614
+ if (input.options?.requireEvidence) {
166615
+ await this.generateHypotheses(thoughtManager, input);
166616
+ }
166617
+ const synthesis = await this.synthesizeFinalAnalysis(thoughtManager, input);
166618
+ const finalProcess = thoughtManager.finalize();
166619
+ const processingTime = Date.now() - startTime;
166620
+ return {
166621
+ thoughtProcess: finalProcess,
166622
+ finalAnswer: synthesis.analysis,
166623
+ confidence: synthesis.confidence,
166624
+ reasoning: this.buildReasoningChain(finalProcess),
166625
+ recommendations: synthesis.recommendations,
166626
+ nextSteps: synthesis.nextSteps,
166627
+ processingInfo: {
166628
+ totalThoughts: finalProcess.thoughts.length,
166629
+ processingTime,
166630
+ revisionsUsed: finalProcess.metadata.revisionsCount,
166631
+ branchesExplored: finalProcess.metadata.branchesCount,
166632
+ hypothesesTested: finalProcess.hypotheses.filter((h) => h.tested).length,
166633
+ finalConfidence: synthesis.confidence
166634
+ }
166635
+ };
166636
+ } catch (error) {
166637
+ logger2.error("Sequential thinking processing failed:", error);
166638
+ throw new APIError(`Sequential thinking failed: ${error instanceof Error ? error.message : "Unknown error"}`);
166639
+ }
166640
+ }
166641
+ async generateInitialThoughts(thoughtManager, input) {
166642
+ logger2.debug(`Generating ${input.initialThoughts} initial thoughts`);
166643
+ for (let i = 1;i <= (input.initialThoughts || 5); i++) {
166644
+ try {
166645
+ const thoughtResult = await this.reasoningEngine.generateThought(input.problem, thoughtManager.getThoughts(), input.thinkingStyle || "analytical", i, input.context);
166646
+ thoughtManager.addThought(thoughtResult.content, thoughtResult.confidence, {
166647
+ tags: ["initial"]
166648
+ });
166649
+ await this.pause(100);
166650
+ } catch (error) {
166651
+ logger2.warn(`Failed to generate initial thought ${i}:`, error);
166652
+ }
166653
+ }
166654
+ }
166655
+ async continueThinking(thoughtManager, input) {
166656
+ const maxThoughts = input.options?.maxThoughts || 10;
166657
+ const timeLimit = (input.options?.timeLimit || 60) * 1000;
166658
+ const startTime = Date.now();
166659
+ while (thoughtManager.needsMoreThoughts() && thoughtManager.getProcess().thoughts.length < maxThoughts && Date.now() - startTime < timeLimit) {
166660
+ try {
166661
+ const currentThoughts = thoughtManager.getThoughts();
166662
+ const nextThoughtNumber = currentThoughts.length + 1;
166663
+ const shouldRevise = this.shouldReviseThought(currentThoughts, input.options);
166664
+ if (shouldRevise && input.options?.allowRevision) {
166665
+ await this.performRevision(thoughtManager, input);
166666
+ } else {
166667
+ const thoughtResult = await this.reasoningEngine.generateThought(input.problem, currentThoughts, input.thinkingStyle || "analytical", nextThoughtNumber, input.context);
166668
+ thoughtManager.addThought(thoughtResult.content, thoughtResult.confidence, {
166669
+ tags: ["continuation"]
166670
+ });
166671
+ }
166672
+ await this.pause(200);
166673
+ } catch (error) {
166674
+ logger2.warn("Failed to continue thinking:", error);
166675
+ break;
166676
+ }
166677
+ }
166678
+ logger2.info(`Completed thinking with ${thoughtManager.getProcess().thoughts.length} thoughts`);
166679
+ }
166680
+ shouldReviseThought(thoughts, options) {
166681
+ if (!options?.allowRevision)
166682
+ return false;
166683
+ if (thoughts.length < 3)
166684
+ return false;
166685
+ const lowConfidenceThoughts = thoughts.filter((t) => t.confidence < 0.6);
166686
+ const hasRecentRevision = thoughts.slice(-2).some((t) => t.isRevision);
166687
+ return lowConfidenceThoughts.length > 0 && !hasRecentRevision;
166688
+ }
166689
+ async performRevision(thoughtManager, input) {
166690
+ const thoughts = thoughtManager.getThoughts();
166691
+ const candidatesForRevision = thoughts.filter((t) => !t.isRevision && t.confidence < 0.7).sort((a, b) => a.confidence - b.confidence);
166692
+ if (candidatesForRevision.length === 0)
166693
+ return;
166694
+ const toRevise = candidatesForRevision[0];
166695
+ try {
166696
+ const revisionPrompt = this.buildRevisionPrompt(toRevise, thoughts, input);
166697
+ const model = this.geminiClient.getModel("detailed");
166698
+ const response = await model.generateContent(revisionPrompt);
166699
+ const content = response.response.text();
166700
+ if (content) {
166701
+ thoughtManager.addThought(content, Math.min((toRevise?.confidence ?? 0.5) + 0.2, 1), {
166702
+ isRevision: true,
166703
+ revisesThought: toRevise?.number,
166704
+ tags: ["revision"]
166705
+ });
166706
+ logger2.debug(`Revised thought ${toRevise?.number}`);
166707
+ }
166708
+ } catch (error) {
166709
+ logger2.warn(`Failed to revise thought ${toRevise?.number}:`, error);
166710
+ }
166711
+ }
166712
+ buildRevisionPrompt(originalThought, allThoughts, input) {
166713
+ return `You are revising and improving a previous thought in a sequential thinking process.
166714
+
166715
+ **Original Problem:**
166716
+ ${input.problem}
166717
+
166718
+ **Original Thought #${originalThought?.number} (Confidence: ${originalThought?.confidence.toFixed(2)}):**
166719
+ ${originalThought?.content}
166720
+
166721
+ **Context from other thoughts:**
166722
+ ${allThoughts.filter((t) => t.number !== originalThought?.number).map((t) => `${t.number}. ${t.content}`).join(`
166723
+ `)}
166724
+
166725
+ **Task:**
166726
+ Revise and improve the original thought. Make it more specific, accurate, and insightful.
166727
+
166728
+ **Focus on:**
166729
+ - Adding more specific details or evidence
166730
+ - Correcting any logical issues
166731
+ - Connecting better with other thoughts
166732
+ - Increasing clarity and actionability
166733
+
166734
+ **Revised thought:`;
166735
+ }
166736
+ async generateHypotheses(thoughtManager, input) {
166737
+ try {
166738
+ const hypothesisResult = await this.reasoningEngine.generateHypothesis(input.problem, thoughtManager.getThoughts(), input.thinkingStyle || "analytical");
166739
+ const hypothesis = thoughtManager.addHypothesis(hypothesisResult.statement, hypothesisResult.evidence, [], hypothesisResult.confidence);
166740
+ const testResult = await this.reasoningEngine.testHypothesis(hypothesis, thoughtManager.getThoughts());
166741
+ thoughtManager.testHypothesis(hypothesis.id, testResult.result, testResult.evidence);
166742
+ logger2.info(`Generated and tested hypothesis: ${testResult.result}`);
166743
+ } catch (error) {
166744
+ logger2.warn("Failed to generate hypotheses:", error);
166745
+ }
166746
+ }
166747
+ async synthesizeFinalAnalysis(thoughtManager, input) {
166748
+ try {
166749
+ return await this.reasoningEngine.synthesizeAnalysis(input.problem, thoughtManager.getThoughts(), thoughtManager.getProcess().hypotheses, input.thinkingStyle || "analytical", input.context);
166750
+ } catch (error) {
166751
+ logger2.error("Failed to synthesize analysis:", error);
166752
+ const thoughts = thoughtManager.getThoughts();
166753
+ const avgConfidence = thoughts.reduce((sum, t) => sum + t.confidence, 0) / thoughts.length;
166754
+ return {
166755
+ analysis: `Based on ${thoughts.length} thoughts, the analysis suggests multiple approaches to the problem. Key insights include the main themes identified through ${input.thinkingStyle} thinking.`,
166756
+ confidence: avgConfidence,
166757
+ recommendations: ["Review the thought process", "Consider implementation"],
166758
+ nextSteps: ["Validate assumptions", "Plan next phase"]
166759
+ };
166760
+ }
166761
+ }
166762
+ buildReasoningChain(process3) {
166763
+ const thoughts = process3.thoughts;
166764
+ if (thoughts.length === 0)
166765
+ return "No reasoning chain available.";
166766
+ const chain = thoughts.map((thought) => {
166767
+ const prefix = thought.isRevision ? "↻ " : "→ ";
166768
+ const confidence = `[${(thought.confidence * 100).toFixed(0)}%]`;
166769
+ return `${prefix}${thought.content} ${confidence}`;
166770
+ }).join(`
166771
+
166772
+ `);
166773
+ const summary = `
166774
+ Reasoning Summary:
166775
+ - Total thoughts: ${thoughts.length}
166776
+ - Revisions: ${process3.metadata.revisionsCount}
166777
+ - Average confidence: ${(thoughts.reduce((sum, t) => sum + t.confidence, 0) / thoughts.length * 100).toFixed(0)}%`;
166778
+ return chain + summary;
166779
+ }
166780
+ async pause(ms) {
166781
+ return new Promise((resolve) => setTimeout(resolve, ms));
166782
+ }
166783
+ }
166784
+
166785
+ // src/tools/brain/processors/analytical-reasoning.ts
166786
+ class AnalyticalReasoningProcessor {
166787
+ geminiClient;
166788
+ reasoningEngine;
166789
+ constructor(geminiClient) {
166790
+ this.geminiClient = geminiClient;
166791
+ this.reasoningEngine = new ReasoningEngine(geminiClient);
166792
+ }
166793
+ async process(input) {
166794
+ const startTime = Date.now();
166795
+ try {
166796
+ logger2.info(`Starting analytical reasoning for: ${input.subject.substring(0, 100)}...`);
166797
+ const thoughtManager = new ThoughtManager(input.subject, input.thinkingStyle, input.context, {
166798
+ ...input.options,
166799
+ enableBranching: input.considerAlternatives
166800
+ });
166801
+ await this.performStructuredAnalysis(thoughtManager, input);
166802
+ if (input.considerAlternatives) {
166803
+ await this.exploreAlternatives(thoughtManager, input);
166804
+ }
166805
+ if (input.trackAssumptions) {
166806
+ await this.analyzeAssumptions(thoughtManager, input);
166807
+ }
166808
+ const synthesis = await this.synthesizeAnalysis(thoughtManager, input);
166809
+ const keyFindings = await this.extractKeyFindings(thoughtManager, input);
166810
+ const evidenceQuality = this.assessEvidenceQuality(thoughtManager.getThoughts());
166811
+ const finalProcess = thoughtManager.finalize();
166812
+ const processingTime = Date.now() - startTime;
166813
+ return {
166814
+ thoughtProcess: finalProcess,
166815
+ finalAnswer: synthesis.analysis,
166816
+ confidence: synthesis.confidence,
166817
+ reasoning: this.buildAnalyticalReasoning(finalProcess),
166818
+ recommendations: synthesis.recommendations,
166819
+ nextSteps: synthesis.nextSteps,
166820
+ keyFindings,
166821
+ assumptions: await this.extractAssumptions(thoughtManager.getThoughts()),
166822
+ evidenceQuality,
166823
+ riskFactors: await this.identifyRiskFactors(thoughtManager, input),
166824
+ opportunities: await this.identifyOpportunities(thoughtManager, input),
166825
+ processingInfo: {
166826
+ totalThoughts: finalProcess.thoughts.length,
166827
+ processingTime,
166828
+ revisionsUsed: finalProcess.metadata.revisionsCount,
166829
+ branchesExplored: finalProcess.metadata.branchesCount,
166830
+ hypothesesTested: finalProcess.hypotheses.filter((h) => h.tested).length,
166831
+ finalConfidence: synthesis.confidence
166832
+ }
166833
+ };
166834
+ } catch (error) {
166835
+ logger2.error("Analytical reasoning processing failed:", error);
166836
+ throw new APIError(`Analytical reasoning failed: ${error instanceof Error ? error.message : "Unknown error"}`);
166837
+ }
166838
+ }
166839
+ async performStructuredAnalysis(thoughtManager, input) {
166840
+ const analysisSteps = this.getAnalysisSteps(input.analysisDepth ?? "detailed", input.focusAreas);
166841
+ for (let i = 0;i < analysisSteps.length; i++) {
166842
+ const step = analysisSteps[i];
166843
+ if (!step)
166844
+ continue;
166845
+ try {
166846
+ const thoughtResult = await this.generateAnalyticalThought(input.subject, step, thoughtManager.getThoughts(), input.thinkingStyle ?? "analytical", input.context);
166847
+ if (step) {
166848
+ thoughtManager.addThought(thoughtResult.content, thoughtResult.confidence, {
166849
+ tags: ["analytical", step.category]
166850
+ });
166851
+ }
166852
+ await this.pause(150);
166853
+ } catch (error) {
166854
+ logger2.warn(`Failed to complete analysis step "${step?.name}":`, error);
166855
+ }
166856
+ }
166857
+ }
166858
+ async exploreAlternatives(thoughtManager, input) {
166859
+ try {
166860
+ const alternativeBranch = thoughtManager.createBranch(thoughtManager.getProcess().currentThought, "Alternative Perspectives");
166861
+ const alternatives = await this.generateAlternativePerspectives(input.subject, thoughtManager.getThoughts(), input.context);
166862
+ for (const alternative of alternatives) {
166863
+ const thoughtResult = await this.generateAnalyticalThought(input.subject, {
166864
+ name: "Alternative Perspective",
166865
+ prompt: alternative.prompt,
166866
+ category: "alternative"
166867
+ }, thoughtManager.getThoughts(), "critical", input.context);
166868
+ thoughtManager.addThought(thoughtResult.content, thoughtResult.confidence, {
166869
+ branchId: alternativeBranch.id,
166870
+ branchFromThought: alternativeBranch.fromThought,
166871
+ tags: ["alternative", alternative.type]
166872
+ });
166873
+ await this.pause(200);
166874
+ }
166875
+ } catch (error) {
166876
+ logger2.warn("Failed to explore alternatives:", error);
166877
+ }
166878
+ }
166879
+ async analyzeAssumptions(thoughtManager, input) {
166880
+ try {
166881
+ const assumptionAnalysisPrompt = this.buildAssumptionAnalysisPrompt(input.subject, thoughtManager.getThoughts());
166882
+ const model = this.geminiClient.getModel("detailed");
166883
+ const response = await model.generateContent(assumptionAnalysisPrompt);
166884
+ const content = response.response.text();
166885
+ if (content) {
166886
+ thoughtManager.addThought(content, 0.8, {
166887
+ tags: ["assumptions", "meta-analysis"]
166888
+ });
166889
+ }
166890
+ } catch (error) {
166891
+ logger2.warn("Failed to analyze assumptions:", error);
166892
+ }
166893
+ }
166894
+ getAnalysisSteps(depth, focusAreas) {
166895
+ const baseSteps = [
166896
+ {
166897
+ name: "Problem Definition",
166898
+ prompt: "Clearly define and scope the subject for analysis",
166899
+ category: "definition"
166900
+ },
166901
+ {
166902
+ name: "Context Analysis",
166903
+ prompt: "Analyze the broader context and environment",
166904
+ category: "context"
166905
+ },
166906
+ {
166907
+ name: "Component Breakdown",
166908
+ prompt: "Break down the subject into key components",
166909
+ category: "breakdown"
166910
+ }
166911
+ ];
166912
+ const detailedSteps = [
166913
+ {
166914
+ name: "Stakeholder Analysis",
166915
+ prompt: "Identify and analyze key stakeholders and their interests",
166916
+ category: "stakeholders"
166917
+ },
166918
+ {
166919
+ name: "Constraint Analysis",
166920
+ prompt: "Identify constraints, limitations, and dependencies",
166921
+ category: "constraints"
166922
+ },
166923
+ {
166924
+ name: "Impact Assessment",
166925
+ prompt: "Assess potential impacts and consequences",
166926
+ category: "impact"
166927
+ }
166928
+ ];
166929
+ const comprehensiveSteps = [
166930
+ {
166931
+ name: "Trend Analysis",
166932
+ prompt: "Analyze relevant trends and patterns",
166933
+ category: "trends"
166934
+ },
166935
+ {
166936
+ name: "Risk Analysis",
166937
+ prompt: "Identify and evaluate potential risks",
166938
+ category: "risks"
166939
+ },
166940
+ {
166941
+ name: "Opportunity Analysis",
166942
+ prompt: "Identify potential opportunities and benefits",
166943
+ category: "opportunities"
166944
+ },
166945
+ {
166946
+ name: "Competitive Analysis",
166947
+ prompt: "Analyze competitive landscape and positioning",
166948
+ category: "competition"
166949
+ }
166950
+ ];
166951
+ let steps = [...baseSteps];
166952
+ if (depth === "detailed" || depth === "comprehensive") {
166953
+ steps.push(...detailedSteps);
166954
+ }
166955
+ if (depth === "comprehensive") {
166956
+ steps.push(...comprehensiveSteps);
166957
+ }
166958
+ if (focusAreas && focusAreas.length > 0) {
166959
+ for (const area of focusAreas) {
166960
+ steps.push({
166961
+ name: `${area} Focus`,
166962
+ prompt: `Provide detailed analysis specifically focused on ${area}`,
166963
+ category: "focus"
166964
+ });
166965
+ }
166966
+ }
166967
+ return steps;
166968
+ }
166969
+ async generateAnalyticalThought(subject, step, previousThoughts, thinkingStyle, context) {
166970
+ const prompt = this.buildStepPrompt(subject, step, previousThoughts, thinkingStyle, context);
166971
+ const model = this.geminiClient.getModel("detailed");
166972
+ const response = await model.generateContent(prompt);
166973
+ const result = response.response;
166974
+ const content = result.text();
166975
+ if (!content) {
166976
+ throw new APIError(`No content generated for analysis step: ${step.name}`);
166977
+ }
166978
+ const confidence = this.estimateStepConfidence(content, step.category);
166979
+ return {
166980
+ content: this.cleanStepContent(content, step.name),
166981
+ confidence
166982
+ };
166983
+ }
166984
+ buildStepPrompt(subject, step, previousThoughts, thinkingStyle, context) {
166985
+ const contextInfo = context ? this.formatContext(context) : "";
166986
+ const thoughtsContext = this.formatPreviousThoughts(previousThoughts);
166987
+ return `You are performing ${step.name} as part of a comprehensive analytical process.
166988
+
166989
+ **Subject for Analysis:**
166990
+ ${subject}
166991
+
166992
+ ${contextInfo}
166993
+
166994
+ **Analysis Step:** ${step.name}
166995
+ **Objective:** ${step.prompt}
166996
+
166997
+ **Previous Analysis:**
166998
+ ${thoughtsContext}
166999
+
167000
+ **Instructions:**
167001
+ - Use ${thinkingStyle} thinking approach
167002
+ - Be specific and evidence-based
167003
+ - Build upon previous analysis without repeating
167004
+ - Identify key insights and patterns
167005
+ - Consider multiple perspectives
167006
+ - Provide actionable insights
167007
+
167008
+ **Your ${step.name} analysis:`;
167009
+ }
167010
+ async generateAlternativePerspectives(subject, thoughts, context) {
167011
+ const alternatives = [
167012
+ {
167013
+ type: "contrarian",
167014
+ prompt: "Challenge the main assumptions and provide a contrarian perspective"
167015
+ },
167016
+ {
167017
+ type: "optimistic",
167018
+ prompt: "Analyze from an optimistic viewpoint, focusing on positive outcomes"
167019
+ },
167020
+ {
167021
+ type: "pessimistic",
167022
+ prompt: "Consider potential negative outcomes and worst-case scenarios"
167023
+ },
167024
+ {
167025
+ type: "outsider",
167026
+ prompt: "Analyze from an external or outsider perspective"
167027
+ }
167028
+ ];
167029
+ return alternatives;
167030
+ }
167031
+ buildAssumptionAnalysisPrompt(subject, thoughts) {
167032
+ const thoughtsText = thoughts.map((t) => t.content).join(`
167033
+
167034
+ `);
167035
+ return `Analyze the assumptions made in the previous analysis.
167036
+
167037
+ **Subject:** ${subject}
167038
+
167039
+ **Analysis so far:**
167040
+ ${thoughtsText}
167041
+
167042
+ **Task:** Identify and evaluate the key assumptions underlying this analysis.
167043
+
167044
+ **Focus on:**
167045
+ - Explicit and implicit assumptions
167046
+ - Validity and strength of each assumption
167047
+ - Potential risks if assumptions are wrong
167048
+ - Evidence supporting or contradicting assumptions
167049
+ - Alternative assumptions that could be considered
167050
+
167051
+ **Your assumption analysis:`;
167052
+ }
167053
+ async synthesizeAnalysis(thoughtManager, input) {
167054
+ return await this.reasoningEngine.synthesizeAnalysis(input.subject, thoughtManager.getThoughts(), thoughtManager.getProcess().hypotheses, input.thinkingStyle ?? "analytical", input.context);
167055
+ }
167056
+ async extractKeyFindings(thoughtManager, input) {
167057
+ try {
167058
+ const findings = [];
167059
+ const thoughts = thoughtManager.getThoughts();
167060
+ const highConfidenceThoughts = thoughts.filter((t) => t.confidence > 0.7);
167061
+ for (const thought of highConfidenceThoughts) {
167062
+ if (thought.content.includes("finding:") || thought.content.includes("insight:")) {
167063
+ findings.push(thought.content);
167064
+ }
167065
+ }
167066
+ const categories = ["definition", "context", "breakdown", "stakeholders", "constraints"];
167067
+ for (const category of categories) {
167068
+ const categoryThoughts = thoughts.filter((t) => t.tags?.includes(category));
167069
+ if (categoryThoughts.length > 0) {
167070
+ const bestThought = categoryThoughts.sort((a, b) => b.confidence - a.confidence)[0];
167071
+ if (bestThought) {
167072
+ findings.push(`${category}: ${bestThought.content.substring(0, 200)}...`);
167073
+ }
167074
+ }
167075
+ }
167076
+ return findings.slice(0, 10);
167077
+ } catch (error) {
167078
+ logger2.warn("Failed to extract key findings:", error);
167079
+ return ["Analysis completed with multiple insights identified"];
167080
+ }
167081
+ }
167082
+ async extractAssumptions(thoughts) {
167083
+ const assumptions = [];
167084
+ for (const thought of thoughts) {
167085
+ if (thought.tags?.includes("assumptions")) {
167086
+ const lines = thought.content.split(`
167087
+ `);
167088
+ for (const line of lines) {
167089
+ if (line.includes("assume") || line.includes("given that") || line.includes("if we consider")) {
167090
+ assumptions.push(line.trim());
167091
+ }
167092
+ }
167093
+ }
167094
+ }
167095
+ return assumptions.slice(0, 8);
167096
+ }
167097
+ assessEvidenceQuality(thoughts) {
167098
+ const evidenceIndicators = {
167099
+ strong: ["data shows", "research indicates", "proven", "demonstrated", "evidence suggests"],
167100
+ moderate: ["likely", "probably", "indicates", "suggests", "appears"],
167101
+ weak: ["might", "could", "possibly", "perhaps", "speculation"]
167102
+ };
167103
+ let strongCount = 0;
167104
+ let moderateCount = 0;
167105
+ let weakCount = 0;
167106
+ for (const thought of thoughts) {
167107
+ const content = thought.content.toLowerCase();
167108
+ for (const indicator of evidenceIndicators.strong) {
167109
+ if (content.includes(indicator))
167110
+ strongCount++;
167111
+ }
167112
+ for (const indicator of evidenceIndicators.moderate) {
167113
+ if (content.includes(indicator))
167114
+ moderateCount++;
167115
+ }
167116
+ for (const indicator of evidenceIndicators.weak) {
167117
+ if (content.includes(indicator))
167118
+ weakCount++;
167119
+ }
167120
+ }
167121
+ const totalIndicators = strongCount + moderateCount + weakCount;
167122
+ if (totalIndicators === 0)
167123
+ return "insufficient";
167124
+ const strongRatio = strongCount / totalIndicators;
167125
+ const moderateRatio = moderateCount / totalIndicators;
167126
+ if (strongRatio > 0.6)
167127
+ return "strong";
167128
+ if (strongRatio + moderateRatio > 0.7)
167129
+ return "moderate";
167130
+ return "weak";
167131
+ }
167132
+ async identifyRiskFactors(thoughtManager, input) {
167133
+ const riskThoughts = thoughtManager.getThoughts().filter((t) => t.tags?.includes("risks") || t.content.toLowerCase().includes("risk") || t.content.toLowerCase().includes("threat") || t.content.toLowerCase().includes("danger"));
167134
+ return riskThoughts.map((t) => this.extractRiskStatements(t.content)).flat().slice(0, 5);
167135
+ }
167136
+ async identifyOpportunities(thoughtManager, input) {
167137
+ const opportunityThoughts = thoughtManager.getThoughts().filter((t) => t.tags?.includes("opportunities") || t.content.toLowerCase().includes("opportunity") || t.content.toLowerCase().includes("benefit") || t.content.toLowerCase().includes("advantage"));
167138
+ return opportunityThoughts.map((t) => this.extractOpportunityStatements(t.content)).flat().slice(0, 5);
167139
+ }
167140
+ extractRiskStatements(content) {
167141
+ const riskKeywords = ["risk of", "threat of", "danger of", "potential for"];
167142
+ const statements = [];
167143
+ for (const keyword of riskKeywords) {
167144
+ const index = content.toLowerCase().indexOf(keyword);
167145
+ if (index !== -1) {
167146
+ const start = Math.max(0, index - 50);
167147
+ const end = Math.min(content.length, index + 150);
167148
+ statements.push(content.substring(start, end).trim());
167149
+ }
167150
+ }
167151
+ return statements;
167152
+ }
167153
+ extractOpportunityStatements(content) {
167154
+ const opportunityKeywords = ["opportunity to", "benefit of", "advantage of", "potential to"];
167155
+ const statements = [];
167156
+ for (const keyword of opportunityKeywords) {
167157
+ const index = content.toLowerCase().indexOf(keyword);
167158
+ if (index !== -1) {
167159
+ const start = Math.max(0, index - 50);
167160
+ const end = Math.min(content.length, index + 150);
167161
+ statements.push(content.substring(start, end).trim());
167162
+ }
167163
+ }
167164
+ return statements;
167165
+ }
167166
+ buildAnalyticalReasoning(process3) {
167167
+ const thoughts = process3.thoughts;
167168
+ const categories = this.groupThoughtsByCategory(thoughts);
167169
+ let reasoning = `Analytical Reasoning Process:
167170
+
167171
+ `;
167172
+ for (const [category, categoryThoughts] of Object.entries(categories)) {
167173
+ reasoning += `${category.toUpperCase()}:
167174
+ `;
167175
+ for (const thought of categoryThoughts) {
167176
+ reasoning += `• ${thought.content.substring(0, 200)}...
167177
+ `;
167178
+ }
167179
+ reasoning += `
167180
+ `;
167181
+ }
167182
+ return reasoning;
167183
+ }
167184
+ groupThoughtsByCategory(thoughts) {
167185
+ const categories = {};
167186
+ for (const thought of thoughts) {
167187
+ const category = thought.tags?.[1] || "general";
167188
+ if (!categories[category]) {
167189
+ categories[category] = [];
167190
+ }
167191
+ categories[category].push(thought);
167192
+ }
167193
+ return categories;
167194
+ }
167195
+ formatContext(context) {
167196
+ return context ? `**Context:** ${JSON.stringify(context)}
167197
+ ` : "";
167198
+ }
167199
+ formatPreviousThoughts(thoughts) {
167200
+ if (thoughts.length === 0)
167201
+ return "No previous analysis yet.";
167202
+ return thoughts.map((t) => `${t.number}. ${t.content}`).join(`
167203
+
167204
+ `);
167205
+ }
167206
+ estimateStepConfidence(content, category) {
167207
+ let confidence = 0.7;
167208
+ if (category === "definition" && content.length > 100)
167209
+ confidence += 0.1;
167210
+ if (category === "breakdown" && content.includes("component"))
167211
+ confidence += 0.1;
167212
+ if (category === "evidence" && content.includes("data"))
167213
+ confidence += 0.2;
167214
+ return Math.min(confidence, 0.95);
167215
+ }
167216
+ cleanStepContent(content, stepName) {
167217
+ return content.replace(new RegExp(`^Your ${stepName} analysis:?\\s*`, "i"), "").replace(/^\s*[\-•]\s*/, "").trim();
167218
+ }
167219
+ async pause(ms) {
167220
+ return new Promise((resolve) => setTimeout(resolve, ms));
167221
+ }
167222
+ }
167223
+
167224
+ // src/tools/brain/processors/problem-solver.ts
167225
+ class ProblemSolverProcessor {
167226
+ geminiClient;
167227
+ reasoningEngine;
167228
+ constructor(geminiClient) {
167229
+ this.geminiClient = geminiClient;
167230
+ this.reasoningEngine = new ReasoningEngine(geminiClient);
167231
+ }
167232
+ async process(input) {
167233
+ const startTime = Date.now();
167234
+ try {
167235
+ logger2.info(`Starting problem solving for: ${input.problemStatement.substring(0, 100)}...`);
167236
+ const thoughtManager = new ThoughtManager(input.problemStatement, this.mapSolutionApproachToThinkingStyle(input.solutionApproach ?? "systematic"), input.context, {
167237
+ ...input.options,
167238
+ requireEvidence: input.verifyHypotheses
167239
+ });
167240
+ await this.defineProblem(thoughtManager, input);
167241
+ await this.generateSolutions(thoughtManager, input);
167242
+ if (input.verifyHypotheses) {
167243
+ await this.testSolutionHypotheses(thoughtManager, input);
167244
+ }
167245
+ const solution = await this.evaluateAndSelectSolution(thoughtManager, input);
167246
+ const implementationPlan = await this.generateImplementationPlan(thoughtManager, input, solution);
167247
+ const finalProcess = thoughtManager.finalize();
167248
+ const processingTime = Date.now() - startTime;
167249
+ return {
167250
+ thoughtProcess: finalProcess,
167251
+ finalAnswer: solution.statement,
167252
+ confidence: solution.confidence,
167253
+ reasoning: this.buildSolutionReasoning(finalProcess),
167254
+ recommendations: solution.recommendations,
167255
+ nextSteps: implementationPlan.steps,
167256
+ proposedSolution: solution.statement,
167257
+ implementationSteps: implementationPlan.steps,
167258
+ potentialObstacles: implementationPlan.obstacles,
167259
+ successCriteria: implementationPlan.successCriteria,
167260
+ testPlan: implementationPlan.testPlan,
167261
+ fallbackOptions: solution.alternatives,
167262
+ processingInfo: {
167263
+ totalThoughts: finalProcess.thoughts.length,
167264
+ processingTime,
167265
+ revisionsUsed: finalProcess.metadata.revisionsCount,
167266
+ branchesExplored: finalProcess.metadata.branchesCount,
167267
+ hypothesesTested: finalProcess.hypotheses.filter((h) => h.tested).length,
167268
+ finalConfidence: solution.confidence
167269
+ }
167270
+ };
167271
+ } catch (error) {
167272
+ logger2.error("Problem solving processing failed:", error);
167273
+ throw new APIError(`Problem solving failed: ${error instanceof Error ? error.message : "Unknown error"}`);
167274
+ }
167275
+ }
167276
+ async defineProblem(thoughtManager, input) {
167277
+ const definitionPrompt = this.buildProblemDefinitionPrompt(input);
167278
+ try {
167279
+ const model = this.geminiClient.getModel("detailed");
167280
+ const response = await model.generateContent(definitionPrompt);
167281
+ const content = response.response.text();
167282
+ if (content) {
167283
+ thoughtManager.addThought(content, 0.9, {
167284
+ tags: ["problem_definition", "foundation"]
167285
+ });
167286
+ }
167287
+ } catch (error) {
167288
+ logger2.warn("Failed to define problem:", error);
167289
+ }
167290
+ }
167291
+ async generateSolutions(thoughtManager, input) {
167292
+ const maxIterations = Math.min(input.maxIterations ?? 5, 10);
167293
+ for (let i = 1;i <= maxIterations; i++) {
167294
+ try {
167295
+ const solutionPrompt = this.buildSolutionGenerationPrompt(input, thoughtManager.getThoughts(), i);
167296
+ const model = this.geminiClient.getModel("detailed");
167297
+ const response = await model.generateContent(solutionPrompt);
167298
+ const content = response.response.text();
167299
+ if (content) {
167300
+ const confidence = this.estimateSolutionConfidence(content, i, maxIterations);
167301
+ thoughtManager.addThought(content, confidence, {
167302
+ tags: ["solution_candidate", `iteration_${i}`]
167303
+ });
167304
+ if (input.verifyHypotheses) {
167305
+ await this.generateSolutionHypothesis(thoughtManager, content, i);
167306
+ }
167307
+ }
167308
+ await this.pause(200);
167309
+ } catch (error) {
167310
+ logger2.warn(`Failed to generate solution iteration ${i}:`, error);
167311
+ }
167312
+ }
167313
+ }
167314
+ async generateSolutionHypothesis(thoughtManager, solutionContent, iteration) {
167315
+ try {
167316
+ const hypothesis = thoughtManager.addHypothesis(`Solution ${iteration} will effectively address the problem`, [solutionContent], [], 0.6);
167317
+ const testResult = await this.reasoningEngine.testHypothesis(hypothesis, thoughtManager.getThoughts());
167318
+ thoughtManager.testHypothesis(hypothesis.id, testResult.result, testResult.evidence);
167319
+ } catch (error) {
167320
+ logger2.warn(`Failed to generate hypothesis for solution ${iteration}:`, error);
167321
+ }
167322
+ }
167323
+ async testSolutionHypotheses(thoughtManager, input) {
167324
+ const untested = thoughtManager.getActiveHypotheses();
167325
+ for (const hypothesis of untested) {
167326
+ try {
167327
+ const testResult = await this.reasoningEngine.testHypothesis(hypothesis, thoughtManager.getThoughts(), `Testing solution viability against constraints: ${input.constraints?.join(", ")}`);
167328
+ thoughtManager.testHypothesis(hypothesis.id, testResult.result, testResult.evidence);
167329
+ await this.pause(150);
167330
+ } catch (error) {
167331
+ logger2.warn(`Failed to test hypothesis ${hypothesis.id}:`, error);
167332
+ }
167333
+ }
167334
+ }
167335
+ async evaluateAndSelectSolution(thoughtManager, input) {
167336
+ const evaluationPrompt = this.buildSolutionEvaluationPrompt(input, thoughtManager);
167337
+ try {
167338
+ const model = this.geminiClient.getModel("detailed");
167339
+ const response = await model.generateContent(evaluationPrompt);
167340
+ const content = response.response.text();
167341
+ if (!content) {
167342
+ throw new Error("No solution evaluation generated");
167343
+ }
167344
+ const evaluation = this.parseSolutionEvaluation(content);
167345
+ thoughtManager.addThought(`Selected solution: ${evaluation.statement}`, evaluation.confidence, { tags: ["final_solution", "decision"] });
167346
+ return evaluation;
167347
+ } catch (error) {
167348
+ logger2.error("Failed to evaluate solutions:", error);
167349
+ const solutions = thoughtManager.getThoughts().filter((t) => t.tags?.includes("solution_candidate"));
167350
+ const bestSolution = solutions.sort((a, b) => b.confidence - a.confidence)[0];
167351
+ return {
167352
+ statement: bestSolution?.content || "Unable to determine optimal solution",
167353
+ confidence: bestSolution?.confidence || 0.5,
167354
+ recommendations: ["Review solution candidates", "Consider additional approaches"],
167355
+ alternatives: solutions.slice(1, 4).map((s) => s.content)
167356
+ };
167357
+ }
167358
+ }
167359
+ async generateImplementationPlan(thoughtManager, input, solution) {
167360
+ const implementationPrompt = this.buildImplementationPrompt(input, solution);
167361
+ try {
167362
+ const model = this.geminiClient.getModel("detailed");
167363
+ const response = await model.generateContent(implementationPrompt);
167364
+ const content = response.response.text();
167365
+ if (!content) {
167366
+ throw new Error("No implementation plan generated");
167367
+ }
167368
+ return this.parseImplementationPlan(content);
167369
+ } catch (error) {
167370
+ logger2.error("Failed to generate implementation plan:", error);
167371
+ return {
167372
+ steps: ["Plan implementation details", "Execute solution", "Monitor results"],
167373
+ obstacles: ["Resource constraints", "Technical challenges"],
167374
+ successCriteria: ["Problem is resolved", "Requirements are met"],
167375
+ testPlan: ["Validate solution", "Monitor outcomes"]
167376
+ };
167377
+ }
167378
+ }
167379
+ buildProblemDefinitionPrompt(input) {
167380
+ const constraintsText = input.constraints?.length ? `
167381
+ **Constraints:** ${input.constraints.join(", ")}` : "";
167382
+ const requirementsText = input.requirements?.length ? `
167383
+ **Requirements:** ${input.requirements.join(", ")}` : "";
167384
+ return `You are defining a problem for systematic solution development.
167385
+
167386
+ **Problem Statement:**
167387
+ ${input.problemStatement}
167388
+ ${constraintsText}
167389
+ ${requirementsText}
167390
+
167391
+ **Context:**
167392
+ ${input.context ? JSON.stringify(input.context) : "No additional context provided"}
167393
+
167394
+ **Task:**
167395
+ Provide a clear, comprehensive problem definition that includes:
167396
+ 1. Core problem description
167397
+ 2. Scope and boundaries
167398
+ 3. Key stakeholders affected
167399
+ 4. Success criteria
167400
+ 5. Critical factors to consider
167401
+
167402
+ **Your problem definition:`;
167403
+ }
167404
+ buildSolutionGenerationPrompt(input, previousThoughts, iteration) {
167405
+ const previousSolutions = previousThoughts.filter((t) => t.tags?.includes("solution_candidate")).map((t) => `- ${t.content}`).join(`
167406
+ `);
167407
+ const approach = this.getSolutionApproachInstructions(input.solutionApproach ?? "systematic");
167408
+ return `Generate solution candidate #${iteration} for the problem.
167409
+
167410
+ **Problem:**
167411
+ ${input.problemStatement}
167412
+
167413
+ **Approach:** ${input.solutionApproach ?? "systematic"}
167414
+ ${approach}
167415
+
167416
+ **Constraints:** ${input.constraints?.join(", ") || "None specified"}
167417
+ **Requirements:** ${input.requirements?.join(", ") || "None specified"}
167418
+
167419
+ **Previous solution candidates:**
167420
+ ${previousSolutions || "None yet"}
167421
+
167422
+ **Task:**
167423
+ Generate a ${iteration === 1 ? "comprehensive" : "alternative"} solution that:
167424
+ - Addresses the core problem
167425
+ - Respects all constraints
167426
+ - Meets specified requirements
167427
+ - ${iteration > 1 ? "Differs meaningfully from previous candidates" : "Provides a solid foundation"}
167428
+ - Is practical and implementable
167429
+
167430
+ **Solution candidate #${iteration}:`;
167431
+ }
167432
+ buildSolutionEvaluationPrompt(input, thoughtManager) {
167433
+ const solutions = thoughtManager.getThoughts().filter((t) => t.tags?.includes("solution_candidate"));
167434
+ const hypotheses = thoughtManager.getTestedHypotheses();
167435
+ const solutionsText = solutions.map((s, i) => `**Solution ${i + 1}** (Confidence: ${s.confidence.toFixed(2)}):
167436
+ ${s.content}`).join(`
167437
+
167438
+ `);
167439
+ const hypothesesText = hypotheses.map((h) => `- ${h.statement}: ${h.result?.toUpperCase()} (${h.confidence.toFixed(2)})`).join(`
167440
+ `);
167441
+ return `Evaluate all solution candidates and select the best one.
167442
+
167443
+ **Problem:**
167444
+ ${input.problemStatement}
167445
+
167446
+ **Solution Candidates:**
167447
+ ${solutionsText}
167448
+
167449
+ **Hypothesis Test Results:**
167450
+ ${hypothesesText || "No hypotheses tested"}
167451
+
167452
+ **Evaluation Criteria:**
167453
+ - Effectiveness in solving the problem
167454
+ - Feasibility and practicality
167455
+ - Resource requirements
167456
+ - Risk level
167457
+ - Alignment with requirements and constraints
167458
+
167459
+ **Task:**
167460
+ Select the best solution and provide:
167461
+
167462
+ SELECTED_SOLUTION: [Your chosen solution statement]
167463
+ CONFIDENCE: [0.00-1.00]
167464
+ REASONING: [Why this solution is best]
167465
+ RECOMMENDATIONS: [Implementation recommendations, one per line]
167466
+ ALTERNATIVES: [Alternative solutions to consider, one per line]
167467
+
167468
+ **Your evaluation:`;
167469
+ }
167470
+ buildImplementationPrompt(input, solution) {
167471
+ return `Create a detailed implementation plan for the selected solution.
167472
+
167473
+ **Problem:**
167474
+ ${input.problemStatement}
167475
+
167476
+ **Selected Solution:**
167477
+ ${solution.statement}
167478
+
167479
+ **Constraints:** ${input.constraints?.join(", ") || "None specified"}
167480
+ **Requirements:** ${input.requirements?.join(", ") || "None specified"}
167481
+
167482
+ **Task:**
167483
+ Create a comprehensive implementation plan with:
167484
+
167485
+ IMPLEMENTATION_STEPS: [Specific actionable steps, one per line]
167486
+ POTENTIAL_OBSTACLES: [Challenges that might arise, one per line]
167487
+ SUCCESS_CRITERIA: [How to measure success, one per line]
167488
+ TEST_PLAN: [How to validate the solution works, one per line]
167489
+
167490
+ **Your implementation plan:`;
167491
+ }
167492
+ mapSolutionApproachToThinkingStyle(approach) {
167493
+ const mapping = {
167494
+ systematic: "systematic",
167495
+ creative: "creative",
167496
+ scientific: "scientific",
167497
+ iterative: "analytical"
167498
+ };
167499
+ return mapping[approach] || "analytical";
167500
+ }
167501
+ getSolutionApproachInstructions(approach) {
167502
+ const instructions = {
167503
+ systematic: "Use structured, methodical problem-solving. Break down into components and address systematically.",
167504
+ creative: "Think outside the box. Consider unconventional approaches and innovative solutions.",
167505
+ scientific: "Use hypothesis-driven approach. Test assumptions and validate solutions with evidence.",
167506
+ iterative: "Build solutions incrementally. Start simple and refine through iterations."
167507
+ };
167508
+ return instructions[approach] || instructions.systematic;
167509
+ }
167510
+ estimateSolutionConfidence(content, iteration, maxIterations) {
167511
+ let confidence = 0.6;
167512
+ if (iteration === 1)
167513
+ confidence += 0.1;
167514
+ if (iteration > maxIterations / 2)
167515
+ confidence += 0.1;
167516
+ if (content.includes("step") || content.includes("phase"))
167517
+ confidence += 0.1;
167518
+ if (content.includes("test") || content.includes("validate"))
167519
+ confidence += 0.1;
167520
+ if (content.length > 300)
167521
+ confidence += 0.05;
167522
+ return Math.min(confidence, 0.9);
167523
+ }
167524
+ parseSolutionEvaluation(content) {
167525
+ const lines = content.split(`
167526
+ `).map((line) => line.trim()).filter((line) => line);
167527
+ let statement = "";
167528
+ let confidence = 0.7;
167529
+ const recommendations = [];
167530
+ const alternatives = [];
167531
+ let currentSection = "";
167532
+ for (const line of lines) {
167533
+ if (line.startsWith("SELECTED_SOLUTION:")) {
167534
+ statement = line.replace("SELECTED_SOLUTION:", "").trim();
167535
+ } else if (line.startsWith("CONFIDENCE:")) {
167536
+ const confMatch = line.match(/(\d*\.?\d+)/);
167537
+ if (confMatch && confMatch[1]) {
167538
+ confidence = Math.min(Math.max(parseFloat(confMatch[1]), 0), 1);
167539
+ }
167540
+ } else if (line.startsWith("RECOMMENDATIONS:")) {
167541
+ currentSection = "recommendations";
167542
+ } else if (line.startsWith("ALTERNATIVES:")) {
167543
+ currentSection = "alternatives";
167544
+ } else if (line.startsWith("- ") || line.startsWith("* ")) {
167545
+ const item = line.replace(/^[-*]\s*/, "");
167546
+ if (currentSection === "recommendations") {
167547
+ recommendations.push(item);
167548
+ } else if (currentSection === "alternatives") {
167549
+ alternatives.push(item);
167550
+ }
167551
+ }
167552
+ }
167553
+ return {
167554
+ statement: statement || "Solution selected based on evaluation",
167555
+ confidence,
167556
+ recommendations,
167557
+ alternatives
167558
+ };
167559
+ }
167560
+ parseImplementationPlan(content) {
167561
+ const lines = content.split(`
167562
+ `).map((line) => line.trim()).filter((line) => line);
167563
+ const steps = [];
167564
+ const obstacles = [];
167565
+ const successCriteria = [];
167566
+ const testPlan = [];
167567
+ let currentSection = "";
167568
+ for (const line of lines) {
167569
+ if (line.startsWith("IMPLEMENTATION_STEPS:")) {
167570
+ currentSection = "steps";
167571
+ } else if (line.startsWith("POTENTIAL_OBSTACLES:")) {
167572
+ currentSection = "obstacles";
167573
+ } else if (line.startsWith("SUCCESS_CRITERIA:")) {
167574
+ currentSection = "criteria";
167575
+ } else if (line.startsWith("TEST_PLAN:")) {
167576
+ currentSection = "test";
167577
+ } else if (line.startsWith("- ") || line.startsWith("* ")) {
167578
+ const item = line.replace(/^[-*]\s*/, "");
167579
+ switch (currentSection) {
167580
+ case "steps":
167581
+ steps.push(item);
167582
+ break;
167583
+ case "obstacles":
167584
+ obstacles.push(item);
167585
+ break;
167586
+ case "criteria":
167587
+ successCriteria.push(item);
167588
+ break;
167589
+ case "test":
167590
+ testPlan.push(item);
167591
+ break;
167592
+ }
167593
+ }
167594
+ }
167595
+ return { steps, obstacles, successCriteria, testPlan };
167596
+ }
167597
+ buildSolutionReasoning(process3) {
167598
+ const solutions = process3.thoughts.filter((t) => t.tags?.includes("solution_candidate"));
167599
+ const hypotheses = process3.hypotheses;
167600
+ let reasoning = `Problem-Solving Process:
167601
+
167602
+ `;
167603
+ reasoning += `SOLUTION CANDIDATES (${solutions.length}):
167604
+ `;
167605
+ solutions.forEach((sol, i) => {
167606
+ reasoning += `${i + 1}. ${sol.content.substring(0, 150)}... [${(sol.confidence * 100).toFixed(0)}%]
167607
+ `;
167608
+ });
167609
+ if (hypotheses.length > 0) {
167610
+ reasoning += `
167611
+ HYPOTHESIS TESTING:
167612
+ `;
167613
+ hypotheses.forEach((hyp) => {
167614
+ const status = hyp.tested ? hyp.result?.toUpperCase() : "NOT_TESTED";
167615
+ reasoning += `• ${hyp.statement} → ${status}
167616
+ `;
167617
+ });
167618
+ }
167619
+ return reasoning;
167620
+ }
167621
+ async pause(ms) {
167622
+ return new Promise((resolve) => setTimeout(resolve, ms));
167623
+ }
167624
+ }
167625
+
167626
+ // src/tools/brain/processors/reflection.ts
167627
+ class ReflectionProcessor {
167628
+ geminiClient;
167629
+ constructor(geminiClient) {
167630
+ this.geminiClient = geminiClient;
167631
+ }
167632
+ async process(input) {
167633
+ const startTime = Date.now();
167634
+ try {
167635
+ logger2.info(`Starting reflection process for analysis of length: ${input.originalAnalysis.length}`);
167636
+ const reflectionResults = await this.performReflection(input);
167637
+ const identifiedIssues = await this.identifyIssues(input, reflectionResults);
167638
+ const improvements = await this.generateImprovements(input, identifiedIssues);
167639
+ const revisedAnalysis = await this.createRevisedAnalysis(input, improvements);
167640
+ const confidence = this.calculateReflectionConfidence(identifiedIssues, improvements);
167641
+ const recommendedActions = await this.generateRecommendedActions(input, improvements);
167642
+ const processingTime = Date.now() - startTime;
167643
+ return {
167644
+ originalAnalysis: input.originalAnalysis,
167645
+ revisedAnalysis: revisedAnalysis || undefined,
167646
+ identifiedIssues,
167647
+ improvements,
167648
+ confidence,
167649
+ recommendedActions
167650
+ };
167651
+ } catch (error) {
167652
+ logger2.error("Reflection processing failed:", error);
167653
+ throw new APIError(`Reflection failed: ${error instanceof Error ? error.message : "Unknown error"}`);
167654
+ }
167655
+ }
167656
+ async performReflection(input) {
167657
+ const results = [];
167658
+ for (const focus of input.reflectionFocus) {
167659
+ try {
167660
+ const reflectionPrompt = this.buildReflectionPrompt(input, focus);
167661
+ const model = this.geminiClient.getModel("detailed");
167662
+ const response = await model.generateContent(reflectionPrompt);
167663
+ const content = response.response.text();
167664
+ if (content) {
167665
+ const parsed = this.parseReflectionResponse(content);
167666
+ results.push({
167667
+ focus,
167668
+ analysis: parsed.analysis,
167669
+ findings: parsed.findings
167670
+ });
167671
+ }
167672
+ await this.pause(150);
167673
+ } catch (error) {
167674
+ logger2.warn(`Failed to perform reflection for ${focus}:`, error);
167675
+ }
167676
+ }
167677
+ return results;
167678
+ }
167679
+ async identifyIssues(input, reflectionResults) {
167680
+ const issues = [];
167681
+ for (const result of reflectionResults) {
167682
+ const issuePrompt = this.buildIssueIdentificationPrompt(input, result);
167683
+ try {
167684
+ const model = this.geminiClient.getModel("detailed");
167685
+ const response = await model.generateContent(issuePrompt);
167686
+ const content = response.response.text();
167687
+ if (content) {
167688
+ const parsedIssues = this.parseIssueResponse(content, result.focus);
167689
+ issues.push(...parsedIssues);
167690
+ }
167691
+ await this.pause(100);
167692
+ } catch (error) {
167693
+ logger2.warn(`Failed to identify issues for ${result.focus}:`, error);
167694
+ }
167695
+ }
167696
+ return issues;
167697
+ }
167698
+ async generateImprovements(input, issues) {
167699
+ if (issues.length === 0) {
167700
+ return ["Analysis appears sound", "Consider additional perspectives if needed"];
167701
+ }
167702
+ const improvementPrompt = this.buildImprovementPrompt(input, issues);
167703
+ try {
167704
+ const model = this.geminiClient.getModel("detailed");
167705
+ const response = await model.generateContent(improvementPrompt);
167706
+ const content = response.response.text();
167707
+ if (content) {
167708
+ return this.parseImprovementResponse(content);
167709
+ }
167710
+ } catch (error) {
167711
+ logger2.warn("Failed to generate improvements:", error);
167712
+ }
167713
+ return issues.filter((issue) => issue.severity === "high" || issue.severity === "medium").map((issue) => issue.suggestion).slice(0, 5);
167714
+ }
167715
+ async createRevisedAnalysis(input, improvements) {
167716
+ const highImpactImprovements = improvements.filter((imp) => imp.includes("significant") || imp.includes("major") || imp.includes("critical"));
167717
+ if (highImpactImprovements.length === 0) {
167718
+ return null;
167719
+ }
167720
+ const revisionPrompt = this.buildRevisionPrompt(input, improvements);
167721
+ try {
167722
+ const model = this.geminiClient.getModel("detailed");
167723
+ const response = await model.generateContent(revisionPrompt);
167724
+ const content = response.response.text();
167725
+ return content || null;
167726
+ } catch (error) {
167727
+ logger2.warn("Failed to create revised analysis:", error);
167728
+ return null;
167729
+ }
167730
+ }
167731
+ async generateRecommendedActions(input, improvements) {
167732
+ const actionPrompt = this.buildActionPrompt(input, improvements);
167733
+ try {
167734
+ const model = this.geminiClient.getModel("detailed");
167735
+ const response = await model.generateContent(actionPrompt);
167736
+ const content = response.response.text();
167737
+ if (content) {
167738
+ return this.parseActionResponse(content);
167739
+ }
167740
+ } catch (error) {
167741
+ logger2.warn("Failed to generate recommended actions:", error);
167742
+ }
167743
+ return [
167744
+ "Review identified issues",
167745
+ "Implement suggested improvements",
167746
+ "Validate revised analysis",
167747
+ "Consider additional perspectives"
167748
+ ];
167749
+ }
167750
+ buildReflectionPrompt(input, focus) {
167751
+ const focusInstructions = this.getFocusInstructions(focus);
167752
+ const contextInfo = this.formatReflectionContext(input);
167753
+ return `You are conducting a reflective analysis focused on ${focus.replace("_", " ")}.
167754
+
167755
+ ${focusInstructions}
167756
+
167757
+ **Original Analysis:**
167758
+ ${input.originalAnalysis}
167759
+
167760
+ ${contextInfo}
167761
+
167762
+ **Task:**
167763
+ Reflect on the original analysis specifically from the ${focus.replace("_", " ")} perspective.
167764
+
167765
+ **Provide:**
167766
+ 1. ANALYSIS: Your reflection on this aspect
167767
+ 2. FINDINGS: Specific findings or concerns (one per line with - prefix)
167768
+
167769
+ **Your reflection on ${focus.replace("_", " ")}:**`;
167770
+ }
167771
+ buildIssueIdentificationPrompt(input, result) {
167772
+ return `Based on the reflection analysis, identify specific issues that need attention.
167773
+
167774
+ **Focus Area:** ${result.focus.replace("_", " ")}
167775
+
167776
+ **Reflection Analysis:**
167777
+ ${result.analysis}
167778
+
167779
+ **Key Findings:**
167780
+ ${result.findings.map((f) => `- ${f}`).join(`
167781
+ `)}
167782
+
167783
+ **Task:**
167784
+ Identify specific issues that need to be addressed.
167785
+
167786
+ **For each issue, provide:**
167787
+ ISSUE: [Description of the issue]
167788
+ SEVERITY: [LOW|MEDIUM|HIGH]
167789
+ SUGGESTION: [How to address this issue]
167790
+
167791
+ **Issues identified:`;
167792
+ }
167793
+ buildImprovementPrompt(input, issues) {
167794
+ const issuesText = issues.map((issue) => `- ${issue.type}: ${issue.description} (${issue.severity}) → ${issue.suggestion}`).join(`
167795
+ `);
167796
+ return `Generate specific improvements based on identified issues.
167797
+
167798
+ **Original Analysis:**
167799
+ ${input.originalAnalysis.substring(0, 500)}...
167800
+
167801
+ **Identified Issues:**
167802
+ ${issuesText}
167803
+
167804
+ **Improvement Goals:**
167805
+ ${input.improvementGoals?.join(", ") || "General improvement"}
167806
+
167807
+ **Task:**
167808
+ Generate specific, actionable improvements to address the identified issues.
167809
+
167810
+ **Improvements (one per line with - prefix):`;
167811
+ }
167812
+ buildRevisionPrompt(input, improvements) {
167813
+ const improvementsText = improvements.map((imp) => `- ${imp}`).join(`
167814
+ `);
167815
+ return `Create a revised version of the original analysis incorporating the suggested improvements.
167816
+
167817
+ **Original Analysis:**
167818
+ ${input.originalAnalysis}
167819
+
167820
+ **Improvements to Incorporate:**
167821
+ ${improvementsText}
167822
+
167823
+ **New Information:**
167824
+ ${input.newInformation || "None provided"}
167825
+
167826
+ **Alternative Viewpoints:**
167827
+ ${input.alternativeViewpoints?.join(", ") || "None provided"}
167828
+
167829
+ **Task:**
167830
+ Create a revised analysis that addresses the identified issues and incorporates the improvements while maintaining the core insights from the original.
167831
+
167832
+ **Revised Analysis:**`;
167833
+ }
167834
+ buildActionPrompt(input, improvements) {
167835
+ const improvementsText = improvements.map((imp) => `- ${imp}`).join(`
167836
+ `);
167837
+ return `Generate recommended actions based on the reflection and improvements.
167838
+
167839
+ **Context:**
167840
+ ${input.context ? JSON.stringify(input.context) : "No context provided"}
167841
+
167842
+ **Identified Improvements:**
167843
+ ${improvementsText}
167844
+
167845
+ **Improvement Goals:**
167846
+ ${input.improvementGoals?.join(", ") || "General improvement"}
167847
+
167848
+ **Task:**
167849
+ Generate specific, actionable recommendations for next steps.
167850
+
167851
+ **Recommended Actions (one per line with - prefix):`;
167852
+ }
167853
+ getFocusInstructions(focus) {
167854
+ const instructions = {
167855
+ assumptions: "Examine the underlying assumptions. Are they valid? Well-supported? What if they are wrong?",
167856
+ logic_gaps: "Look for holes in the logical reasoning. Are there missing steps? Unsupported conclusions?",
167857
+ alternative_approaches: "Consider different methods or perspectives. What other ways could this be approached?",
167858
+ evidence_quality: "Evaluate the strength and reliability of evidence used. Is it sufficient and credible?",
167859
+ bias_detection: "Identify potential biases in reasoning, data selection, or interpretation.",
167860
+ consistency_check: "Check for internal consistency. Are there contradictions or conflicting statements?",
167861
+ completeness: "Assess whether important aspects have been overlooked or inadequately addressed.",
167862
+ feasibility: "Evaluate the practical viability and implementation challenges of conclusions or recommendations."
167863
+ };
167864
+ return instructions[focus] || "Reflect critically on this aspect of the analysis.";
167865
+ }
167866
+ formatReflectionContext(input) {
167867
+ const parts = [];
167868
+ if (input.newInformation) {
167869
+ parts.push(`**New Information:** ${input.newInformation}`);
167870
+ }
167871
+ if (input.alternativeViewpoints?.length) {
167872
+ parts.push(`**Alternative Viewpoints:** ${input.alternativeViewpoints.join(", ")}`);
167873
+ }
167874
+ if (input.improvementGoals?.length) {
167875
+ parts.push(`**Improvement Goals:** ${input.improvementGoals.join(", ")}`);
167876
+ }
167877
+ return parts.length > 0 ? `
167878
+ ` + parts.join(`
167879
+ `) + `
167880
+ ` : "";
167881
+ }
167882
+ parseReflectionResponse(content) {
167883
+ const lines = content.split(`
167884
+ `).map((line) => line.trim()).filter((line) => line);
167885
+ let analysis = "";
167886
+ const findings = [];
167887
+ let currentSection = "";
167888
+ for (const line of lines) {
167889
+ if (line.startsWith("ANALYSIS:")) {
167890
+ currentSection = "analysis";
167891
+ analysis = line.replace("ANALYSIS:", "").trim();
167892
+ } else if (line.startsWith("FINDINGS:")) {
167893
+ currentSection = "findings";
167894
+ } else if (line.startsWith("- ") || line.startsWith("* ")) {
167895
+ if (currentSection === "findings") {
167896
+ findings.push(line.replace(/^[-*]\s*/, ""));
167897
+ }
167898
+ } else if (currentSection === "analysis" && line) {
167899
+ analysis += (analysis ? " " : "") + line;
167900
+ }
167901
+ }
167902
+ return {
167903
+ analysis: analysis || "Reflection completed",
167904
+ findings
167905
+ };
167906
+ }
167907
+ parseIssueResponse(content, focus) {
167908
+ const lines = content.split(`
167909
+ `).map((line) => line.trim()).filter((line) => line);
167910
+ const issues = [];
167911
+ let currentIssue = { type: focus };
167912
+ for (const line of lines) {
167913
+ if (line.startsWith("ISSUE:")) {
167914
+ if (currentIssue.description) {
167915
+ issues.push(currentIssue);
167916
+ }
167917
+ currentIssue = {
167918
+ type: focus,
167919
+ description: line.replace("ISSUE:", "").trim(),
167920
+ severity: "medium",
167921
+ suggestion: ""
167922
+ };
167923
+ } else if (line.startsWith("SEVERITY:")) {
167924
+ const severityText = line.replace("SEVERITY:", "").trim().toLowerCase();
167925
+ if (severityText.includes("high"))
167926
+ currentIssue.severity = "high";
167927
+ else if (severityText.includes("low"))
167928
+ currentIssue.severity = "low";
167929
+ else
167930
+ currentIssue.severity = "medium";
167931
+ } else if (line.startsWith("SUGGESTION:")) {
167932
+ currentIssue.suggestion = line.replace("SUGGESTION:", "").trim();
167933
+ }
167934
+ }
167935
+ if (currentIssue.description) {
167936
+ issues.push(currentIssue);
167937
+ }
167938
+ return issues;
167939
+ }
167940
+ parseImprovementResponse(content) {
167941
+ return content.split(`
167942
+ `).map((line) => line.trim()).filter((line) => line.startsWith("-") || line.startsWith("*")).map((line) => line.replace(/^[-*]\s*/, "")).filter((line) => line.length > 0).slice(0, 8);
167943
+ }
167944
+ parseActionResponse(content) {
167945
+ return content.split(`
167946
+ `).map((line) => line.trim()).filter((line) => line.startsWith("-") || line.startsWith("*")).map((line) => line.replace(/^[-*]\s*/, "")).filter((line) => line.length > 0).slice(0, 6);
167947
+ }
167948
+ calculateReflectionConfidence(issues, improvements) {
167949
+ const highSeverityIssues = issues.filter((i) => i.severity === "high").length;
167950
+ const mediumSeverityIssues = issues.filter((i) => i.severity === "medium").length;
167951
+ let confidence = 0.8;
167952
+ confidence -= highSeverityIssues * 0.2;
167953
+ confidence -= mediumSeverityIssues * 0.1;
167954
+ if (improvements.length > 0)
167955
+ confidence += 0.1;
167956
+ return Math.max(Math.min(confidence, 1), 0.1);
167957
+ }
167958
+ async pause(ms) {
167959
+ return new Promise((resolve) => setTimeout(resolve, ms));
167960
+ }
167961
+ }
167962
+
167963
+ // src/tools/brain/index.ts
167964
+ async function registerBrainTools(server, config) {
167965
+ const geminiClient = new GeminiClient(config);
167966
+ const sequentialThinkingProcessor = new SequentialThinkingProcessor(geminiClient);
167967
+ const analyticalReasoningProcessor = new AnalyticalReasoningProcessor(geminiClient);
167968
+ const problemSolverProcessor = new ProblemSolverProcessor(geminiClient);
167969
+ const reflectionProcessor = new ReflectionProcessor(geminiClient);
167970
+ logger2.info("Registering Brain tools for advanced reasoning capabilities...");
167971
+ server.registerTool("brain_think", {
167972
+ title: "Sequential Thinking Tool",
167973
+ description: "Advanced sequential thinking with dynamic problem-solving and thought revision",
167974
+ inputSchema: {
167975
+ problem: exports_external.string().min(10).max(2000).describe("The problem or question to think through step by step"),
167976
+ initialThoughts: exports_external.number().min(1).max(20).default(5).optional().describe("Number of initial thoughts to generate"),
167977
+ thinkingStyle: exports_external.enum(["analytical", "systematic", "creative", "scientific", "critical", "strategic", "intuitive", "collaborative"]).default("analytical").optional().describe("Approach to use for thinking"),
167978
+ context: exports_external.object({
167979
+ domain: exports_external.string().optional(),
167980
+ background: exports_external.string().optional(),
167981
+ constraints: exports_external.array(exports_external.string()).optional(),
167982
+ requirements: exports_external.array(exports_external.string()).optional(),
167983
+ stakeholders: exports_external.array(exports_external.string()).optional(),
167984
+ timeframe: exports_external.string().optional(),
167985
+ resources: exports_external.array(exports_external.string()).optional()
167986
+ }).optional().describe("Additional context for the problem"),
167987
+ options: exports_external.object({
167988
+ maxThoughts: exports_external.number().min(1).max(50).default(10).optional(),
167989
+ allowRevision: exports_external.boolean().default(true).optional(),
167990
+ enableBranching: exports_external.boolean().default(true).optional(),
167991
+ requireEvidence: exports_external.boolean().default(false).optional(),
167992
+ confidenceThreshold: exports_external.number().min(0).max(1).default(0.7).optional(),
167993
+ timeLimit: exports_external.number().min(5).max(300).default(60).optional(),
167994
+ outputDetail: exports_external.enum(["summary", "detailed", "complete"]).default("detailed").optional()
167995
+ }).optional().describe("Processing options and constraints")
167996
+ }
167997
+ }, async (args) => {
167998
+ try {
167999
+ const input = {
168000
+ problem: args.problem,
168001
+ initialThoughts: args.initialThoughts || 5,
168002
+ thinkingStyle: args.thinkingStyle || "analytical",
168003
+ context: args.context,
168004
+ options: args.options
168005
+ };
168006
+ const result = await sequentialThinkingProcessor.process(input);
168007
+ return {
168008
+ content: [{
168009
+ type: "text",
168010
+ text: formatThinkingResult(result)
168011
+ }],
168012
+ isError: false
168013
+ };
168014
+ } catch (error) {
168015
+ const mcpError = handleError(error);
168016
+ logger2.error("Tool brain_think error:", mcpError);
168017
+ return {
168018
+ content: [{
168019
+ type: "text",
168020
+ text: `Error: ${mcpError.message}`
168021
+ }],
168022
+ isError: true
168023
+ };
168024
+ }
168025
+ });
168026
+ server.registerTool("brain_analyze", {
168027
+ title: "Deep Analytical Reasoning Tool",
168028
+ description: "Comprehensive analysis with branching exploration and assumption tracking",
168029
+ inputSchema: {
168030
+ subject: exports_external.string().min(10).max(2000).describe("The subject or topic to analyze deeply"),
168031
+ analysisDepth: exports_external.enum(["surface", "detailed", "comprehensive"]).default("detailed").optional().describe("Depth of analysis to perform"),
168032
+ focusAreas: exports_external.array(exports_external.string()).optional().describe("Specific areas to focus analysis on"),
168033
+ thinkingStyle: exports_external.enum(["analytical", "systematic", "creative", "scientific", "critical", "strategic", "intuitive", "collaborative"]).default("analytical").optional().describe("Analytical approach to use"),
168034
+ considerAlternatives: exports_external.boolean().default(true).optional().describe("Whether to explore alternative perspectives"),
168035
+ trackAssumptions: exports_external.boolean().default(true).optional().describe("Whether to explicitly track assumptions"),
168036
+ context: exports_external.object({
168037
+ domain: exports_external.string().optional(),
168038
+ background: exports_external.string().optional(),
168039
+ constraints: exports_external.array(exports_external.string()).optional(),
168040
+ requirements: exports_external.array(exports_external.string()).optional(),
168041
+ stakeholders: exports_external.array(exports_external.string()).optional(),
168042
+ timeframe: exports_external.string().optional(),
168043
+ resources: exports_external.array(exports_external.string()).optional()
168044
+ }).optional().describe("Context for the analysis"),
168045
+ options: exports_external.object({
168046
+ maxThoughts: exports_external.number().min(1).max(50).default(10).optional(),
168047
+ allowRevision: exports_external.boolean().default(true).optional(),
168048
+ enableBranching: exports_external.boolean().default(true).optional(),
168049
+ requireEvidence: exports_external.boolean().default(false).optional(),
168050
+ confidenceThreshold: exports_external.number().min(0).max(1).default(0.7).optional(),
168051
+ timeLimit: exports_external.number().min(5).max(300).default(60).optional(),
168052
+ outputDetail: exports_external.enum(["summary", "detailed", "complete"]).default("detailed").optional()
168053
+ }).optional().describe("Processing options and constraints")
168054
+ }
168055
+ }, async (args) => {
168056
+ try {
168057
+ const input = {
168058
+ subject: args.subject,
168059
+ analysisDepth: args.analysisDepth || "detailed",
168060
+ focusAreas: args.focusAreas,
168061
+ thinkingStyle: args.thinkingStyle || "analytical",
168062
+ considerAlternatives: args.considerAlternatives !== false,
168063
+ trackAssumptions: args.trackAssumptions !== false,
168064
+ context: args.context,
168065
+ options: args.options
168066
+ };
168067
+ const result = await analyticalReasoningProcessor.process(input);
168068
+ return {
168069
+ content: [{
168070
+ type: "text",
168071
+ text: formatAnalysisResult(result)
168072
+ }],
168073
+ isError: false
168074
+ };
168075
+ } catch (error) {
168076
+ const mcpError = handleError(error);
168077
+ logger2.error("Tool brain_analyze error:", mcpError);
168078
+ return {
168079
+ content: [{
168080
+ type: "text",
168081
+ text: `Error: ${mcpError.message}`
168082
+ }],
168083
+ isError: true
168084
+ };
168085
+ }
168086
+ });
168087
+ server.registerTool("brain_solve", {
168088
+ title: "Problem Solving Tool",
168089
+ description: "Multi-step problem solving with hypothesis testing and solution evaluation",
168090
+ inputSchema: {
168091
+ problemStatement: exports_external.string().min(10).max(2000).describe("Clear statement of the problem to solve"),
168092
+ solutionApproach: exports_external.enum(["systematic", "creative", "scientific", "iterative"]).default("systematic").optional().describe("Approach to problem solving"),
168093
+ constraints: exports_external.array(exports_external.string()).optional().describe("Constraints that limit possible solutions"),
168094
+ requirements: exports_external.array(exports_external.string()).optional().describe("Requirements the solution must meet"),
168095
+ verifyHypotheses: exports_external.boolean().default(true).optional().describe("Whether to test hypotheses scientifically"),
168096
+ maxIterations: exports_external.number().min(1).max(20).default(10).optional().describe("Maximum solution iterations to attempt"),
168097
+ context: exports_external.object({
168098
+ domain: exports_external.string().optional(),
168099
+ background: exports_external.string().optional(),
168100
+ constraints: exports_external.array(exports_external.string()).optional(),
168101
+ requirements: exports_external.array(exports_external.string()).optional(),
168102
+ stakeholders: exports_external.array(exports_external.string()).optional(),
168103
+ timeframe: exports_external.string().optional(),
168104
+ resources: exports_external.array(exports_external.string()).optional()
168105
+ }).optional().describe("Context for the problem"),
168106
+ options: exports_external.object({
168107
+ maxThoughts: exports_external.number().min(1).max(50).default(10).optional(),
168108
+ allowRevision: exports_external.boolean().default(true).optional(),
168109
+ enableBranching: exports_external.boolean().default(true).optional(),
168110
+ requireEvidence: exports_external.boolean().default(false).optional(),
168111
+ confidenceThreshold: exports_external.number().min(0).max(1).default(0.7).optional(),
168112
+ timeLimit: exports_external.number().min(5).max(300).default(60).optional(),
168113
+ outputDetail: exports_external.enum(["summary", "detailed", "complete"]).default("detailed").optional()
168114
+ }).optional().describe("Processing options and constraints")
168115
+ }
168116
+ }, async (args) => {
168117
+ try {
168118
+ const input = {
168119
+ problemStatement: args.problemStatement,
168120
+ solutionApproach: args.solutionApproach || "systematic",
168121
+ constraints: args.constraints,
168122
+ requirements: args.requirements,
168123
+ verifyHypotheses: args.verifyHypotheses !== false,
168124
+ maxIterations: args.maxIterations || 10,
168125
+ context: args.context,
168126
+ options: args.options
168127
+ };
168128
+ const result = await problemSolverProcessor.process(input);
168129
+ return {
168130
+ content: [{
168131
+ type: "text",
168132
+ text: formatSolutionResult(result)
168133
+ }],
168134
+ isError: false
168135
+ };
168136
+ } catch (error) {
168137
+ const mcpError = handleError(error);
168138
+ logger2.error("Tool brain_solve error:", mcpError);
168139
+ return {
168140
+ content: [{
168141
+ type: "text",
168142
+ text: `Error: ${mcpError.message}`
168143
+ }],
168144
+ isError: true
168145
+ };
168146
+ }
168147
+ });
168148
+ server.registerTool("brain_reflect", {
168149
+ title: "Thought Reflection Tool",
168150
+ description: "Reflect on and improve previous analysis through meta-cognitive examination",
168151
+ inputSchema: {
168152
+ originalAnalysis: exports_external.string().min(50).max(5000).describe("The original analysis or reasoning to reflect on"),
168153
+ reflectionFocus: exports_external.array(exports_external.enum(["assumptions", "logic_gaps", "alternative_approaches", "evidence_quality", "bias_detection", "consistency_check", "completeness", "feasibility"])).min(1).describe("Aspects to focus reflection on"),
168154
+ improvementGoals: exports_external.array(exports_external.string()).optional().describe("Specific goals for improvement"),
168155
+ newInformation: exports_external.string().optional().describe("Any new information to consider"),
168156
+ alternativeViewpoints: exports_external.array(exports_external.string()).optional().describe("Alternative perspectives to consider"),
168157
+ context: exports_external.object({
168158
+ domain: exports_external.string().optional(),
168159
+ background: exports_external.string().optional(),
168160
+ constraints: exports_external.array(exports_external.string()).optional(),
168161
+ requirements: exports_external.array(exports_external.string()).optional(),
168162
+ stakeholders: exports_external.array(exports_external.string()).optional(),
168163
+ timeframe: exports_external.string().optional(),
168164
+ resources: exports_external.array(exports_external.string()).optional()
168165
+ }).optional().describe("Context for the reflection"),
168166
+ options: exports_external.object({
168167
+ maxThoughts: exports_external.number().min(1).max(50).default(10).optional(),
168168
+ allowRevision: exports_external.boolean().default(true).optional(),
168169
+ enableBranching: exports_external.boolean().default(true).optional(),
168170
+ requireEvidence: exports_external.boolean().default(false).optional(),
168171
+ confidenceThreshold: exports_external.number().min(0).max(1).default(0.7).optional(),
168172
+ timeLimit: exports_external.number().min(5).max(300).default(60).optional(),
168173
+ outputDetail: exports_external.enum(["summary", "detailed", "complete"]).default("detailed").optional()
168174
+ }).optional().describe("Processing options and constraints")
168175
+ }
168176
+ }, async (args) => {
168177
+ try {
168178
+ const input = {
168179
+ originalAnalysis: args.originalAnalysis,
168180
+ reflectionFocus: args.reflectionFocus,
168181
+ improvementGoals: args.improvementGoals,
168182
+ newInformation: args.newInformation,
168183
+ alternativeViewpoints: args.alternativeViewpoints,
168184
+ context: args.context,
168185
+ options: args.options
168186
+ };
168187
+ const result = await reflectionProcessor.process(input);
168188
+ return {
168189
+ content: [{
168190
+ type: "text",
168191
+ text: formatReflectionResult(result)
168192
+ }],
168193
+ isError: false
168194
+ };
168195
+ } catch (error) {
168196
+ const mcpError = handleError(error);
168197
+ logger2.error("Tool brain_reflect error:", mcpError);
168198
+ return {
168199
+ content: [{
168200
+ type: "text",
168201
+ text: `Error: ${mcpError.message}`
168202
+ }],
168203
+ isError: true
168204
+ };
168205
+ }
168206
+ });
168207
+ logger2.info("Successfully registered 4 Brain tools: brain_think, brain_analyze, brain_solve, brain_reflect");
168208
+ }
168209
+ function formatThinkingResult(result) {
168210
+ const header = `# Sequential Thinking Results
168211
+
168212
+ `;
168213
+ const summary = `## Summary
168214
+ ` + `**Problem:** ${result.thoughtProcess.problem}
168215
+ ` + `**Final Answer:** ${result.finalAnswer}
168216
+ ` + `**Confidence:** ${(result.confidence * 100).toFixed(1)}%
168217
+ ` + `**Thoughts Generated:** ${result.processingInfo.totalThoughts}
168218
+ ` + `**Processing Time:** ${(result.processingInfo.processingTime / 1000).toFixed(1)}s
168219
+
168220
+ `;
168221
+ const thoughts = `## Thought Process
168222
+ ` + result.thoughtProcess.thoughts.map((thought, index) => {
168223
+ const revisionMark = thought.isRevision ? " ↻" : "";
168224
+ const branchMark = thought.branchId ? " \uD83C\uDF3F" : "";
168225
+ return `**${index + 1}.** ${thought.content} [${(thought.confidence * 100).toFixed(0)}%]${revisionMark}${branchMark}`;
168226
+ }).join(`
168227
+
168228
+ `) + `
168229
+
168230
+ `;
168231
+ const recommendations = result.recommendations?.length > 0 ? `## Recommendations
168232
+ ${result.recommendations.map((rec) => `• ${rec}`).join(`
168233
+ `)}
168234
+
168235
+ ` : "";
168236
+ const nextSteps = result.nextSteps?.length > 0 ? `## Next Steps
168237
+ ${result.nextSteps.map((step) => `• ${step}`).join(`
168238
+ `)}
168239
+
168240
+ ` : "";
168241
+ return header + summary + thoughts + recommendations + nextSteps;
168242
+ }
168243
+ function formatAnalysisResult(result) {
168244
+ const header = `# Deep Analysis Results
168245
+
168246
+ `;
168247
+ const summary = `## Analysis Summary
168248
+ ` + `**Subject:** ${result.thoughtProcess.problem}
168249
+ ` + `**Final Conclusion:** ${result.finalAnswer}
168250
+ ` + `**Confidence:** ${(result.confidence * 100).toFixed(1)}%
168251
+ ` + `**Evidence Quality:** ${result.evidenceQuality.toUpperCase()}
168252
+
168253
+ `;
168254
+ const keyFindings = result.keyFindings?.length > 0 ? `## Key Findings
168255
+ ${result.keyFindings.map((finding) => `• ${finding}`).join(`
168256
+ `)}
168257
+
168258
+ ` : "";
168259
+ const assumptions = result.assumptions?.length > 0 ? `## Key Assumptions
168260
+ ${result.assumptions.map((assumption) => `• ${assumption}`).join(`
168261
+ `)}
168262
+
168263
+ ` : "";
168264
+ const risks = result.riskFactors?.length > 0 ? `## Risk Factors
168265
+ ${result.riskFactors.map((risk) => `⚠️ ${risk}`).join(`
168266
+ `)}
168267
+
168268
+ ` : "";
168269
+ const opportunities = result.opportunities?.length > 0 ? `## Opportunities
168270
+ ${result.opportunities.map((opp) => `✨ ${opp}`).join(`
168271
+ `)}
168272
+
168273
+ ` : "";
168274
+ return header + summary + keyFindings + assumptions + risks + opportunities;
168275
+ }
168276
+ function formatSolutionResult(result) {
168277
+ const header = `# Problem Solving Results
168278
+
168279
+ `;
168280
+ const summary = `## Solution Summary
168281
+ ` + `**Problem:** ${result.thoughtProcess.problem}
168282
+ ` + `**Proposed Solution:** ${result.proposedSolution}
168283
+ ` + `**Confidence:** ${(result.confidence * 100).toFixed(1)}%
168284
+ ` + `**Hypotheses Tested:** ${result.processingInfo.hypothesesTested}
168285
+
168286
+ `;
168287
+ const implementation = result.implementationSteps?.length > 0 ? `## Implementation Steps
168288
+ ${result.implementationSteps.map((step, i) => `${i + 1}. ${step}`).join(`
168289
+ `)}
168290
+
168291
+ ` : "";
168292
+ const obstacles = result.potentialObstacles?.length > 0 ? `## Potential Obstacles
168293
+ ${result.potentialObstacles.map((obs) => `⚠️ ${obs}`).join(`
168294
+ `)}
168295
+
168296
+ ` : "";
168297
+ const success = result.successCriteria?.length > 0 ? `## Success Criteria
168298
+ ${result.successCriteria.map((crit) => `✅ ${crit}`).join(`
168299
+ `)}
168300
+
168301
+ ` : "";
168302
+ const fallbacks = result.fallbackOptions?.length > 0 ? `## Fallback Options
168303
+ ${result.fallbackOptions.map((option) => `• ${option}`).join(`
168304
+ `)}
168305
+
168306
+ ` : "";
168307
+ return header + summary + implementation + obstacles + success + fallbacks;
168308
+ }
168309
+ function formatReflectionResult(result) {
168310
+ const header = `# Reflection Analysis Results
168311
+
168312
+ `;
168313
+ const summary = `## Reflection Summary
168314
+ ` + `**Confidence in Analysis:** ${(result.confidence * 100).toFixed(1)}%
168315
+ ` + `**Issues Identified:** ${result.identifiedIssues.length}
168316
+ ` + `**Improvements Suggested:** ${result.improvements.length}
168317
+
168318
+ `;
168319
+ const issues = result.identifiedIssues?.length > 0 ? `## Identified Issues
168320
+ ` + result.identifiedIssues.map((issue) => {
168321
+ const severity = issue.severity.toUpperCase();
168322
+ const icon = severity === "HIGH" ? "\uD83D\uDD34" : severity === "MEDIUM" ? "\uD83D\uDFE1" : "\uD83D\uDFE2";
168323
+ return `${icon} **${issue.type.replace("_", " ").toUpperCase()}:** ${issue.description}
168324
+ *Suggestion:* ${issue.suggestion}`;
168325
+ }).join(`
168326
+
168327
+ `) + `
168328
+
168329
+ ` : "";
168330
+ const improvements = result.improvements?.length > 0 ? `## Suggested Improvements
168331
+ ${result.improvements.map((imp) => `• ${imp}`).join(`
168332
+ `)}
168333
+
168334
+ ` : "";
168335
+ const revised = result.revisedAnalysis ? `## Revised Analysis
168336
+ ${result.revisedAnalysis}
168337
+
168338
+ ` : "";
168339
+ const actions = result.recommendedActions?.length > 0 ? `## Recommended Actions
168340
+ ${result.recommendedActions.map((action) => `• ${action}`).join(`
168341
+ `)}
168342
+
168343
+ ` : "";
168344
+ return header + summary + issues + improvements + revised + actions;
168345
+ }
168346
+
165965
168347
  // src/prompts/debugging-prompts.ts
165966
168348
  var debuggingPrompts = [
165967
168349
  {
@@ -166668,6 +169050,7 @@ async function createServer() {
166668
169050
  await registerEyesTool(server, config);
166669
169051
  await registerHandsTool(server, config);
166670
169052
  await registerMouthTool(server, config);
169053
+ await registerBrainTools(server, config);
166671
169054
  await registerPrompts(server);
166672
169055
  await registerResources(server);
166673
169056
  return server;