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