Skip to main content

@tokenring-ai/thinking

Overview

The @tokenring-ai/thinking package provides a comprehensive suite of 13 structured reasoning tools that implement various thinking methodologies with persistent state management. Each tool guides AI agents through disciplined problem-solving using proven human cognitive frameworks and maintains reasoning sessions across multiple calls.

Key Features

  • 13 Structured Thinking Tools: Scientific method, design thinking, root cause analysis, SWOT analysis, and more
  • State Management: Persistent reasoning sessions that track progress across multiple calls
  • Automatic Integration: Tools automatically register with chat services and agents
  • Session Isolation: Independent session tracking for each reasoning tool
  • Progress Tracking: Monitor completed steps and reasoning progress
  • Session Cleanup: Clear individual or all reasoning sessions
  • Tool Integration: Automatically registered with Token Ring agent chat systems
  • Zod Validation: Typed input schemas for all tools
  • Error Handling: Comprehensive error handling and validation
  • Testing: Full test coverage with vitest

Core Components

ThinkingService

Main service class that manages reasoning sessions and state persistence.

import { ThinkingService } from "@tokenring-ai/thinking";

const thinkingService = new ThinkingService();

Properties:

PropertyTypeDescription
namestringService name ("ThinkingService")
descriptionstringService description ("Provides structured reasoning functionality")

Methods:

MethodParametersReturnsDescription
attachagent: AgentvoidInitializes ThinkingState for agent
processSteptoolName: string, args: any, agent: Agent, processor: (session: ReasoningSession, args: any) => anyReasoningSessionProcesses step in reasoning session and returns updated session
clearSessiontoolName: string, agent: AgentvoidClears specific tool session
clearAllagent: AgentvoidClears all reasoning sessions

ThinkingState

Agent state slice that manages reasoning session persistence.

import { ThinkingState } from "@tokenring-ai/thinking";

// Automatically attached to agents by ThinkingService
const state = agent.getState(ThinkingState);

Properties:

PropertyTypeDescription
namestringState slice name ("ThinkingState")
serializationSchemaZodSchemaZod schema for serialization
sessionsMap<string, ReasoningSession>Active reasoning sessions

Methods:

MethodParametersReturnsDescription
constructordata: Partial<ThinkingState>voidCreate new state instance with optional initial data
transferStateFromParentparent: AgentvoidTransfer state from parent agent
reset-voidReset state (clears all sessions)
serialize-z.output<typeof serializationSchema>Returns serialized state object
deserializedata: z.output<typeof serializationSchema>voidLoad state from serialized data
show-string[]Returns session summary array

ReasoningSession

Individual reasoning session state interface.

interface ReasoningSession {
tool: string; // Tool name
problem: string; // Problem being investigated
stepNumber: number; // Current step count
data: Record<string, any>; // Tool-specific data storage
completedSteps: string[]; // Steps completed
complete: boolean; // Whether reasoning is complete
}

Properties:

PropertyTypeDescription
toolstringTool name (e.g., "scientific-method-reasoning")
problemstringProblem being investigated
stepNumbernumberCurrent step count in the session
dataRecord<string, any>Tool-specific data storage
completedStepsstring[]Array of completed step names
completebooleanWhether reasoning is complete

Services

ThinkingService Implementation

export default class ThinkingService implements TokenRingService {
readonly name = "ThinkingService";
description = "Provides structured reasoning functionality";

attach(agent: Agent): void {
agent.initializeState(ThinkingState, {});
}

processStep(
toolName: string,
args: any,
agent: Agent,
processor: (session: ReasoningSession, args: any) => any
): any {
const state = agent.getState(ThinkingState);
let session = state.sessions.get(toolName);

if (!session) {
if (!args.problem) {
throw new Error("Problem must be defined on first call");
}
session = {
tool: toolName,
problem: args.problem,
stepNumber: 0,
data: {},
completedSteps: [],
complete: false,
};
}

agent.mutateState(ThinkingState, (s: ThinkingState) => {
session!.stepNumber++;
if (args.step && !session!.completedSteps.includes(args.step)) {
session!.completedSteps.push(args.step);
}
const result = processor(session!, args);
session!.complete = args.nextThoughtNeeded === false || args.complete === true;
s.sessions.set(toolName, session!);
return result;
});

return agent.getState(ThinkingState).sessions.get(toolName);
}

clearSession(toolName: string, agent: Agent): void {
agent.mutateState(ThinkingState, (state: ThinkingState) => {
state.sessions.delete(toolName);
});
}

clearAll(agent: Agent): void {
agent.mutateState(ThinkingState, (state: ThinkingState) => {
state.sessions.clear();
});
}
}

Provider Documentation

This package does not implement a provider architecture.

RPC Endpoints

This package does not define any RPC endpoints.

Chat Commands

This package does not define any chat commands. Tools are accessed via agent.executeTool().

Configuration

No additional configuration required. The package uses sensible defaults and automatically integrates with the Token Ring framework.

Plugin Configuration

import packageConfigSchema from "@tokenring-ai/thinking/plugin";

// Schema is empty as no configuration is needed
const schema = z.object({});

Integration

The package automatically integrates with the Token Ring application through the plugin system:

import thinkingPlugin from "@tokenring-ai/thinking/plugin";

// Automatically registered in plugin.ts
// No manual registration needed

Service Registration

The ThinkingService is automatically registered with the application's service registry and can be accessed by agents:

const thinkingService = agent.requireServiceByType(ThinkingService);

Tool Registration

All 13 reasoning tools are automatically registered with the chat system:

await agent.executeTool('scientific-method-reasoning', {...});
await agent.executeTool('first-principles', {...});
// ... etc for all 13 tools

Usage Examples

Scientific Method

The scientific method tool enforces strict adherence to the scientific method with hypothesis tracking.

// First call - initialize with problem and observation
const result1 = await agent.executeTool('scientific-method-reasoning', {
problem: "Why does water boil at different temperatures at different altitudes?",
step: "question_observation",
content: "Water boils at 100°C at sea level but at lower temperatures at higher altitudes.",
nextThoughtNeeded: true
});

// Formulate hypothesis
const result2 = await agent.executeTool('scientific-method-reasoning', {
step: "hypothesis_formulation",
content: "Lower atmospheric pressure at higher altitudes reduces the boiling point.",
hypothesis_update: {
new_hypothesis_text: "Reduced atmospheric pressure causes water to boil at lower temperatures",
action: "propose"
},
nextThoughtNeeded: true
});

// Test the hypothesis
const result3 = await agent.executeTool('scientific-method-reasoning', {
step: "testing_experimentation",
content: "At 3000m altitude, atmospheric pressure is ~70% of sea level, and water boils at ~90°C.",
targets_hypothesis_id: ["h1"],
nextThoughtNeeded: true
});

// Final conclusion
const result4 = await agent.executeTool('scientific-method-reasoning', {
step: "conclusion",
content: "Evidence confirms that reduced atmospheric pressure at higher altitudes causes water to boil at lower temperatures.",
nextThoughtNeeded: false,
final_answer: "Reduced atmospheric pressure at higher altitudes causes water to boil at lower temperatures."
});

Decision Matrix

Structured multi-criteria decision making with weighted criteria.

// Define decision
await agent.executeTool('decision-matrix', {
problem: "Which cloud provider should we choose?",
step: "define_decision",
content: "Select the most effective cloud provider for our project",
nextThoughtNeeded: true
});

// Add options
await agent.executeTool('decision-matrix', {
step: "list_options",
content: "AWS",
nextThoughtNeeded: true
});

await agent.executeTool('decision-matrix', {
step: "list_options",
content: "Azure",
nextThoughtNeeded: true
});

// Define criteria with weights
await agent.executeTool('decision-matrix', {
step: "define_criteria",
content: "Performance",
weight: 3,
nextThoughtNeeded: true
});

await agent.executeTool('decision-matrix', {
step: "define_criteria",
content: "Cost",
weight: 1,
nextThoughtNeeded: true
});

// Score options
await agent.executeTool('decision-matrix', {
step: "score_options",
option: "AWS",
criterion: "Performance",
score: 8,
nextThoughtNeeded: true
});

await agent.executeTool('decision-matrix', {
step: "score_options",
option: "AWS",
criterion: "Cost",
score: 5,
nextThoughtNeeded: true
});

// Get final recommendation
const finalResult = await agent.executeTool('decision-matrix', {
step: "calculate_decide",
content: "AWS offers the best balance of performance and cost",
nextThoughtNeeded: false
});

Design Thinking

Human-centered problem solving process.

// Empathize phase
await agent.executeTool('design-thinking', {
problem: "Improve user onboarding flow",
step: "empathize",
content: "Users feel overwhelmed during first-time setup",
nextThoughtNeeded: true
});

// Define problem
await agent.executeTool('design-thinking', {
step: "define",
content: "Users need a simplified, step-by-step onboarding experience",
nextThoughtNeeded: true
});

// Ideate solutions
await agent.executeTool('design-thinking', {
step: "ideate",
content: "Create a guided tour with interactive elements",
nextThoughtNeeded: true
});

// Prototype solution
await agent.executeTool('design-thinking', {
step: "prototype",
content: "Create a Figma prototype with onboarding flow",
nextThoughtNeeded: true
});

// Test prototype
await agent.executeTool('design-thinking', {
step: "test",
content: "User testing shows 40% improvement in completion rate",
nextThoughtNeeded: true
});

// Iterate based on feedback
await agent.executeTool('design-thinking', {
step: "iterate",
content: "Add video tutorials and reduce required steps by 50%",
nextThoughtNeeded: false
});

Pre-Mortem Analysis

Imagining failure to prevent it.

await agent.executeTool('pre-mortem', {
problem: "Launching our new product feature",
step: "assume_failure",
content: "The feature launch failed to meet adoption targets",
nextThoughtNeeded: true
});

await agent.executeTool('pre-mortem', {
step: "list_failure_reasons",
content: "Users don't understand how to use the new feature",
likelihood: "high",
nextThoughtNeeded: true
});

await agent.executeTool('pre-mortem', {
step: "develop_mitigations",
content: "Create onboarding tutorial and in-app guidance",
targets_scenario: "Users don't understand how to use the new feature",
nextThoughtNeeded: true
});

Six Thinking Hats

Parallel thinking from different perspectives.

await agent.executeTool('six-thinking-hats', {
problem: "Should we implement mandatory remote work?",
step: "think",
hat: "white",
content: "Facts: 70% of employees prefer remote work options",
nextThoughtNeeded: true
});

await agent.executeTool('six-thinking-hats', {
step: "think",
hat: "black",
content: "Risks: Reduced collaboration, potential security concerns",
nextThoughtNeeded: true
});

await agent.executeTool('six-thinking-hats', {
step: "think",
hat: "yellow",
content: "Benefits: Increased productivity, better work-life balance",
nextThoughtNeeded: true
});

await agent.executeTool('six-thinking-hats', {
step: "synthesize",
content: "Hybrid model balances collaboration needs with flexibility preferences",
nextThoughtNeeded: false
});

Checking Session Progress

const state = agent.getState(ThinkingState);
console.log(state.show());
// Output: ["Active Sessions: 1", " scientific-method-reasoning: 3 steps, in progress"]

Clearing Sessions

// Clear a specific tool's session
thinkingService.clearSession('scientific-method-reasoning', agent);

// Clear all reasoning sessions
thinkingService.clearAll(agent);

State Transfer Between Agents

const childAgent = new Agent();
const parentAgent = new Agent();

// Transfer state from parent to child
const childThinkingState = new ThinkingState();
childThinkingState.transferStateFromParent(parentAgent);

// Now child agent has the same reasoning sessions as parent

State Serialization and Deserialization

// Serialize state
const state = agent.getState(ThinkingState);
const serialized = state.serialize();

// Save to storage (e.g., database, file)
const savedState = JSON.stringify(serialized);

// Later, deserialize state
const savedData = JSON.parse(savedState);
const newState = new ThinkingState(savedData);

State Reset

const state = agent.getState(ThinkingState);

// Reset state (clears all sessions)
state.reset();

Best Practices

Session Management

  1. Always provide problem on first call: The problem field is required on the first call to any tool
  2. Track step progress: Use agent.getState(ThinkingState).show() to monitor session progress
  3. Complete sessions properly: Set nextThoughtNeeded: false only when the reasoning is complete
  4. Clear sessions when done: Use clearSession() or clearAll() to free memory

Tool Selection

  1. Use scientific method for hypothesis-driven investigations
  2. Use design thinking for user-centered problems
  3. Use decision matrix for multi-criteria decisions
  4. Use pre-mortem for risk analysis
  5. Use six thinking hats for comprehensive perspective analysis

Integration Patterns

  1. Automatic registration: No manual registration needed - tools are automatically available
  2. Service access: Access ThinkingService via agent.requireServiceByType(ThinkingService)
  3. State persistence: Sessions persist across multiple calls and agent restarts

Testing

Unit Tests

The package includes comprehensive unit tests for all tools:

# Run all tests
bun test

# Run tests in watch mode
bun test --watch

# Run tests with coverage
bun test --coverage

Test Coverage

  • ThinkingService: All service methods tested
  • ThinkingState: State management, serialization, and transfer tested
  • All 13 tools: Tool execution and state management tested
  • Integration tests: Full workflow scenarios tested

Example Test Pattern

import { describe, it, expect, beforeEach } from "vitest";
import Agent from "@tokenring-ai/agent";
import ThinkingService from "../../ThinkingService.ts";
import { ThinkingState } from "../../state/thinkingState.ts";

describe("ThinkingService", () => {
let agent: Agent;
let thinkingService: ThinkingService;

beforeEach(() => {
agent = new Agent({
workHandler: async (work) => {
// Handle work requests
}
});
thinkingService = new ThinkingService();
thinkingService.attach(agent);
});

it("processes scientific method steps correctly", async () => {
// First call - initialize session
const result1 = await thinkingService.processStep(
'scientific-method-reasoning',
{
problem: "Test problem",
step: "question_observation",
content: "Test content",
nextThoughtNeeded: true
},
agent,
(session, args) => {
return { type: "json", data: { step: args.step } };
}
);

expect(result1).toBeDefined();
expect(result1!.stepNumber).toBe(1);
expect(result1!.problem).toBe("Test problem");

// Second call - continue session
const result2 = await thinkingService.processStep(
'scientific-method-reasoning',
{
step: "background_research",
content: "More content",
nextThoughtNeeded: false
},
agent,
(session, args) => {
return { type: "json", data: { step: args.step } };
}
);

expect(result2!.stepNumber).toBe(2);
expect(result2!.complete).toBe(true);
});
});

Dependencies

Production Dependencies

  • @tokenring-ai/app (0.2.0) - Application framework and service management
  • @tokenring-ai/chat (0.2.0) - Chat service and tool definitions
  • @tokenring-ai/agent (0.2.0) - Agent system and state management
  • zod (^4.3.6) - Schema validation

Development Dependencies

  • vitest (^4.0.18) - Testing framework
  • typescript (^5.9.3) - TypeScript compiler

Package Structure

pkg/thinking/
├── index.ts # Package exports
├── plugin.ts # Auto-registration plugin
├── ThinkingService.ts # Core service implementation
├── tools.ts # Tool exports and registry
├── state/
│ └── thinkingState.ts # State management for sessions
├── tools/ # Individual tool implementations
│ ├── scientificMethod.ts
│ ├── socraticDialogue.ts
│ ├── designThinking.ts
│ ├── rootCauseAnalysis.ts
│ ├── swotAnalysis.ts
│ ├── preMortem.ts
│ ├── dialecticalReasoning.ts
│ ├── firstPrinciples.ts
│ ├── decisionMatrix.ts
│ ├── lateralThinking.ts
│ ├── agileSprint.ts
│ ├── feynmanTechnique.ts
│ └── sixThinkingHats.ts
├── test/ # Test suite
│ ├── tools.test.ts
│ ├── integration.test.ts
│ ├── firstPrinciples.test.ts
│ ├── decisionMatrix.test.ts
│ ├── scientificMethod.test.ts
│ ├── thinkingState.test.ts
│ └── thinkingService.test.ts
└── vitest.config.ts # Test configuration

Development

Building

bun run build

Testing

bun run test

Watch Tests

bun run test:watch

Coverage

bun run test:coverage

License

MIT