@cogitator-ai/types 0.3.1 → 0.5.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 (54) hide show
  1. package/README.md +829 -16
  2. package/dist/causal.d.ts +325 -0
  3. package/dist/causal.d.ts.map +1 -0
  4. package/dist/causal.js +26 -0
  5. package/dist/causal.js.map +1 -0
  6. package/dist/constitutional.d.ts +83 -0
  7. package/dist/constitutional.d.ts.map +1 -0
  8. package/dist/constitutional.js +32 -0
  9. package/dist/constitutional.js.map +1 -0
  10. package/dist/cost-routing.d.ts +46 -0
  11. package/dist/cost-routing.d.ts.map +1 -0
  12. package/dist/cost-routing.js +8 -0
  13. package/dist/cost-routing.js.map +1 -0
  14. package/dist/index.d.ts +9 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +9 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/knowledge-graph.d.ts +235 -0
  19. package/dist/knowledge-graph.d.ts.map +1 -0
  20. package/dist/knowledge-graph.js +22 -0
  21. package/dist/knowledge-graph.js.map +1 -0
  22. package/dist/learning.d.ts.map +1 -1
  23. package/dist/learning.js.map +1 -1
  24. package/dist/llm.d.ts +3 -0
  25. package/dist/llm.d.ts.map +1 -1
  26. package/dist/memory.d.ts +9 -0
  27. package/dist/memory.d.ts.map +1 -1
  28. package/dist/negotiation.d.ts +163 -0
  29. package/dist/negotiation.d.ts.map +1 -0
  30. package/dist/negotiation.js +14 -0
  31. package/dist/negotiation.js.map +1 -0
  32. package/dist/neuro-symbolic.d.ts +424 -0
  33. package/dist/neuro-symbolic.d.ts.map +1 -0
  34. package/dist/neuro-symbolic.js +41 -0
  35. package/dist/neuro-symbolic.js.map +1 -0
  36. package/dist/prompt-optimization.d.ts +229 -0
  37. package/dist/prompt-optimization.d.ts.map +1 -0
  38. package/dist/prompt-optimization.js +27 -0
  39. package/dist/prompt-optimization.js.map +1 -0
  40. package/dist/reasoning.d.ts.map +1 -1
  41. package/dist/reasoning.js.map +1 -1
  42. package/dist/runtime.d.ts +14 -0
  43. package/dist/runtime.d.ts.map +1 -1
  44. package/dist/self-modifying.d.ts +396 -0
  45. package/dist/self-modifying.d.ts.map +1 -0
  46. package/dist/self-modifying.js +52 -0
  47. package/dist/self-modifying.js.map +1 -0
  48. package/dist/swarm.d.ts +8 -2
  49. package/dist/swarm.d.ts.map +1 -1
  50. package/dist/time-travel.d.ts +119 -0
  51. package/dist/time-travel.d.ts.map +1 -0
  52. package/dist/time-travel.js +16 -0
  53. package/dist/time-travel.js.map +1 -0
  54. package/package.json +1 -1
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # @cogitator-ai/types
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@cogitator-ai/types.svg)](https://www.npmjs.com/package/@cogitator-ai/types)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
3
6
  Shared TypeScript types for the Cogitator AI agent runtime.
4
7
 
5
8
  ## Installation
@@ -8,31 +11,841 @@ Shared TypeScript types for the Cogitator AI agent runtime.
8
11
  pnpm add @cogitator-ai/types
9
12
  ```
10
13
 
11
- ## Usage
14
+ ## Quick Start
15
+
16
+ ```typescript
17
+ import type {
18
+ Agent,
19
+ AgentConfig,
20
+ Tool,
21
+ ToolConfig,
22
+ Message,
23
+ RunResult,
24
+ CogitatorConfig,
25
+ } from '@cogitator-ai/types';
26
+ ```
27
+
28
+ ## Type Categories
29
+
30
+ | Category | Description |
31
+ | ------------------------------------------------- | --------------------------------------- |
32
+ | [Message](#message-types) | Chat messages, tool calls, tool results |
33
+ | [Tool](#tool-types) | Tool definitions with Zod schemas |
34
+ | [Agent](#agent-types) | Agent configuration and interface |
35
+ | [LLM](#llm-types) | LLM backend and provider types |
36
+ | [Runtime](#runtime-types) | Cogitator config, run options, results |
37
+ | [Errors](#error-types) | Structured error handling |
38
+ | [Reflection](#reflection-types) | Self-analyzing agent types |
39
+ | [Reasoning](#reasoning-types) | Tree-of-Thought reasoning |
40
+ | [Learning](#learning-types) | DSPy-style optimization |
41
+ | [Time Travel](#time-travel-types) | Execution debugging |
42
+ | [Knowledge Graph](#knowledge-graph-types) | Entity-relationship memory |
43
+ | [Prompt Optimization](#prompt-optimization-types) | A/B testing, monitoring, rollback |
44
+
45
+ ---
46
+
47
+ ## Message Types
48
+
49
+ Types for LLM conversations and tool interactions.
50
+
51
+ ```typescript
52
+ import type {
53
+ Message,
54
+ MessageRole,
55
+ ToolCall,
56
+ ToolResult,
57
+ ToolCallMessage,
58
+ ToolResultMessage,
59
+ } from '@cogitator-ai/types';
60
+
61
+ // Basic message
62
+ const userMessage: Message = {
63
+ role: 'user',
64
+ content: 'What is 2 + 2?',
65
+ };
66
+
67
+ // Assistant message with tool calls
68
+ const assistantMessage: ToolCallMessage = {
69
+ role: 'assistant',
70
+ content: '',
71
+ toolCalls: [
72
+ {
73
+ id: 'call_123',
74
+ name: 'calculator',
75
+ arguments: { expression: '2 + 2' },
76
+ },
77
+ ],
78
+ };
79
+
80
+ // Tool result message
81
+ const toolResult: ToolResultMessage = {
82
+ role: 'tool',
83
+ content: '4',
84
+ toolCallId: 'call_123',
85
+ name: 'calculator',
86
+ };
87
+ ```
88
+
89
+ ### Message Interfaces
90
+
91
+ | Type | Description |
92
+ | ------------------- | --------------------------------------------------------- |
93
+ | `MessageRole` | `'system' \| 'user' \| 'assistant' \| 'tool'` |
94
+ | `Message` | Base message with role, content, optional name/toolCallId |
95
+ | `ToolCallMessage` | Assistant message containing tool calls |
96
+ | `ToolResultMessage` | Tool execution result |
97
+ | `ToolCall` | Tool invocation with id, name, arguments |
98
+ | `ToolResult` | Tool execution result with callId, name, result, error |
99
+
100
+ ---
101
+
102
+ ## Tool Types
103
+
104
+ Types for defining agent tools with Zod schemas.
105
+
106
+ ```typescript
107
+ import type { Tool, ToolConfig, ToolContext, ToolSchema } from '@cogitator-ai/types';
108
+ import { z } from 'zod';
109
+
110
+ // Tool configuration
111
+ const calculatorConfig: ToolConfig<{ expression: string }, number> = {
112
+ name: 'calculator',
113
+ description: 'Evaluate mathematical expressions',
114
+ category: 'math',
115
+ parameters: z.object({
116
+ expression: z.string().describe('Math expression to evaluate'),
117
+ }),
118
+ execute: async (params, context) => {
119
+ console.log(`Run ${context.runId} executing calculator`);
120
+ return eval(params.expression);
121
+ },
122
+ timeout: 5000,
123
+ sideEffects: [],
124
+ };
125
+
126
+ // Tool context available during execution
127
+ interface ToolContext {
128
+ agentId: string;
129
+ runId: string;
130
+ signal: AbortSignal;
131
+ }
132
+ ```
133
+
134
+ ### Tool Interfaces
135
+
136
+ | Type | Description |
137
+ | ------------------------------ | ------------------------------------------------------------------ |
138
+ | `ToolConfig<TParams, TResult>` | Tool definition with execute function |
139
+ | `Tool<TParams, TResult>` | Full tool with toJSON() method |
140
+ | `ToolContext` | Execution context with agentId, runId, signal |
141
+ | `ToolSchema` | JSON Schema representation for LLM |
142
+ | `ToolCategory` | `'math' \| 'text' \| 'file' \| 'network' \| 'system' \| 'utility'` |
143
+
144
+ ### Tool Options
145
+
146
+ ```typescript
147
+ const advancedTool: ToolConfig = {
148
+ name: 'file_write',
149
+ description: 'Write content to a file',
150
+ parameters: z.object({
151
+ path: z.string(),
152
+ content: z.string(),
153
+ }),
154
+ execute: async (params) => {
155
+ /* ... */
156
+ },
157
+
158
+ // Optional configuration
159
+ category: 'file',
160
+ tags: ['io', 'filesystem'],
161
+ sideEffects: ['filesystem'],
162
+ requiresApproval: true, // or (params) => params.path.includes('/etc')
163
+ timeout: 10000,
164
+ sandbox: { type: 'docker', image: 'node:20' },
165
+ };
166
+ ```
167
+
168
+ ---
169
+
170
+ ## Agent Types
171
+
172
+ Types for agent configuration.
173
+
174
+ ```typescript
175
+ import type { Agent, AgentConfig, ResponseFormat } from '@cogitator-ai/types';
176
+
177
+ const config: AgentConfig = {
178
+ name: 'research-agent',
179
+ model: 'openai/gpt-4o',
180
+ instructions: 'You are a research assistant...',
181
+
182
+ // Optional settings
183
+ description: 'Helps with research tasks',
184
+ tools: [calculatorTool],
185
+ temperature: 0.7,
186
+ topP: 0.9,
187
+ maxTokens: 4096,
188
+ stopSequences: ['END'],
189
+ maxIterations: 10,
190
+ timeout: 60000,
191
+
192
+ // Response format
193
+ responseFormat: { type: 'json' },
194
+ };
195
+
196
+ // Response format options
197
+ const textFormat: ResponseFormat = { type: 'text' };
198
+ const jsonFormat: ResponseFormat = { type: 'json' };
199
+ const schemaFormat: ResponseFormat = {
200
+ type: 'json_schema',
201
+ schema: z.object({ answer: z.string() }),
202
+ };
203
+ ```
204
+
205
+ ---
206
+
207
+ ## LLM Types
208
+
209
+ Types for LLM backends and providers.
210
+
211
+ ```typescript
212
+ import type {
213
+ LLMProvider,
214
+ LLMConfig,
215
+ LLMBackend,
216
+ ChatRequest,
217
+ ChatResponse,
218
+ ChatStreamChunk,
219
+ } from '@cogitator-ai/types';
220
+
221
+ // Supported providers
222
+ type LLMProvider = 'ollama' | 'openai' | 'anthropic' | 'google' | 'vllm';
223
+
224
+ // LLM configuration
225
+ const llmConfig: LLMConfig = {
226
+ provider: 'openai',
227
+ model: 'gpt-4o',
228
+ temperature: 0.7,
229
+ maxTokens: 4096,
230
+ };
231
+
232
+ // Chat request
233
+ const request: ChatRequest = {
234
+ model: 'gpt-4o',
235
+ messages: [{ role: 'user', content: 'Hello' }],
236
+ tools: [{ name: 'calc', description: '...', parameters: { type: 'object', properties: {} } }],
237
+ stream: true,
238
+ };
239
+
240
+ // Chat response
241
+ const response: ChatResponse = {
242
+ id: 'chatcmpl-123',
243
+ content: 'Hello! How can I help?',
244
+ finishReason: 'stop',
245
+ usage: { inputTokens: 10, outputTokens: 20, totalTokens: 30 },
246
+ };
247
+ ```
248
+
249
+ ---
250
+
251
+ ## Runtime Types
252
+
253
+ Types for Cogitator runtime configuration and execution.
254
+
255
+ ```typescript
256
+ import type { CogitatorConfig, RunOptions, RunResult, Span } from '@cogitator-ai/types';
257
+
258
+ // Cogitator configuration
259
+ const config: CogitatorConfig = {
260
+ llm: {
261
+ defaultProvider: 'openai',
262
+ defaultModel: 'gpt-4o',
263
+ providers: {
264
+ openai: { apiKey: process.env.OPENAI_API_KEY! },
265
+ ollama: { baseUrl: 'http://localhost:11434' },
266
+ anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
267
+ },
268
+ },
269
+ limits: {
270
+ maxConcurrentRuns: 10,
271
+ defaultTimeout: 30000,
272
+ maxTokensPerRun: 100000,
273
+ },
274
+ memory: { type: 'redis', redis: { host: 'localhost' } },
275
+ sandbox: { type: 'docker', image: 'node:20-alpine' },
276
+ reflection: { enabled: true, reflectAfterError: true },
277
+ };
278
+
279
+ // Run options with callbacks
280
+ const runOptions: RunOptions = {
281
+ input: 'Calculate 2 + 2',
282
+ context: { userId: '123' },
283
+ threadId: 'thread_abc',
284
+ timeout: 30000,
285
+ stream: true,
286
+
287
+ // Callbacks
288
+ onToken: (token) => process.stdout.write(token),
289
+ onToolCall: (call) => console.log('Tool called:', call.name),
290
+ onToolResult: (result) => console.log('Tool result:', result.result),
291
+ onRunStart: ({ runId }) => console.log('Started:', runId),
292
+ onRunComplete: (result) => console.log('Done:', result.output),
293
+ onRunError: (error) => console.error('Error:', error),
294
+ onSpan: (span) => console.log('Span:', span.name),
295
+
296
+ // Memory options
297
+ useMemory: true,
298
+ loadHistory: true,
299
+ saveHistory: true,
300
+ };
301
+ ```
302
+
303
+ ### RunResult
304
+
305
+ ```typescript
306
+ const result: RunResult = {
307
+ output: 'The answer is 4',
308
+ structured: { answer: 4 }, // if responseFormat was json_schema
309
+ runId: 'run_123',
310
+ agentId: 'agent_456',
311
+ threadId: 'thread_789',
312
+ usage: {
313
+ inputTokens: 100,
314
+ outputTokens: 50,
315
+ totalTokens: 150,
316
+ cost: 0.0023,
317
+ duration: 1500,
318
+ },
319
+ toolCalls: [{ id: 'call_1', name: 'calculator', arguments: { expression: '2+2' } }],
320
+ messages: [
321
+ /* conversation history */
322
+ ],
323
+ trace: {
324
+ traceId: 'trace_abc',
325
+ spans: [
326
+ /* execution spans */
327
+ ],
328
+ },
329
+ reflections: [
330
+ /* if reflection enabled */
331
+ ],
332
+ reflectionSummary: {
333
+ /* summary stats */
334
+ },
335
+ };
336
+ ```
337
+
338
+ ---
339
+
340
+ ## Error Types
341
+
342
+ Structured error handling with typed error codes.
343
+
344
+ ```typescript
345
+ import {
346
+ CogitatorError,
347
+ ErrorCode,
348
+ ERROR_STATUS_CODES,
349
+ isRetryableError,
350
+ getRetryDelay,
351
+ } from '@cogitator-ai/types';
352
+
353
+ // Create a structured error
354
+ const error = new CogitatorError({
355
+ message: 'LLM backend unavailable',
356
+ code: ErrorCode.LLM_UNAVAILABLE,
357
+ details: { provider: 'openai', endpoint: 'https://api.openai.com' },
358
+ retryable: true,
359
+ retryAfter: 5000,
360
+ });
361
+
362
+ // Check error type
363
+ if (CogitatorError.isCogitatorError(error)) {
364
+ console.log(error.code); // 'LLM_UNAVAILABLE'
365
+ console.log(error.statusCode); // 503
366
+ console.log(error.retryable); // true
367
+ }
368
+
369
+ // Wrap any error
370
+ const wrapped = CogitatorError.wrap(new Error('timeout'), ErrorCode.LLM_TIMEOUT);
371
+
372
+ // Check if retryable
373
+ if (isRetryableError(error)) {
374
+ const delay = getRetryDelay(error, 1000);
375
+ await sleep(delay);
376
+ }
377
+ ```
378
+
379
+ ### Error Codes
380
+
381
+ | Domain | Codes |
382
+ | -------- | ----------------------------------------------------------------------------------------------------------------------------------- |
383
+ | LLM | `LLM_UNAVAILABLE`, `LLM_RATE_LIMITED`, `LLM_TIMEOUT`, `LLM_INVALID_RESPONSE`, `LLM_CONTEXT_LENGTH_EXCEEDED`, `LLM_CONTENT_FILTERED` |
384
+ | Sandbox | `SANDBOX_UNAVAILABLE`, `SANDBOX_TIMEOUT`, `SANDBOX_OOM`, `SANDBOX_EXECUTION_FAILED`, `SANDBOX_INVALID_MODULE` |
385
+ | Tool | `TOOL_NOT_FOUND`, `TOOL_INVALID_ARGS`, `TOOL_EXECUTION_FAILED`, `TOOL_TIMEOUT` |
386
+ | Memory | `MEMORY_UNAVAILABLE`, `MEMORY_WRITE_FAILED`, `MEMORY_READ_FAILED` |
387
+ | Agent | `AGENT_NOT_FOUND`, `AGENT_ALREADY_RUNNING`, `AGENT_MAX_ITERATIONS` |
388
+ | Workflow | `WORKFLOW_NOT_FOUND`, `WORKFLOW_STEP_FAILED`, `WORKFLOW_CYCLE_DETECTED` |
389
+ | Swarm | `SWARM_NO_WORKERS`, `SWARM_CONSENSUS_FAILED` |
390
+ | General | `VALIDATION_ERROR`, `CONFIGURATION_ERROR`, `INTERNAL_ERROR`, `NOT_IMPLEMENTED`, `CIRCUIT_OPEN` |
391
+
392
+ ---
393
+
394
+ ## Reflection Types
395
+
396
+ Types for self-analyzing agents that learn from their actions.
397
+
398
+ ```typescript
399
+ import type {
400
+ Reflection,
401
+ ReflectionConfig,
402
+ ReflectionAction,
403
+ Insight,
404
+ InsightStore,
405
+ ReflectionSummary,
406
+ } from '@cogitator-ai/types';
407
+
408
+ // Reflection configuration
409
+ const reflectionConfig: ReflectionConfig = {
410
+ enabled: true,
411
+ reflectAfterToolCall: true,
412
+ reflectAfterError: true,
413
+ reflectAtEnd: true,
414
+ storeInsights: true,
415
+ maxInsightsPerAgent: 100,
416
+ minConfidenceToStore: 0.7,
417
+ useSmallModelForReflection: true,
418
+ reflectionModel: 'gpt-4o-mini',
419
+ };
420
+
421
+ // Insight types
422
+ type InsightType = 'pattern' | 'mistake' | 'success' | 'tip' | 'warning';
423
+
424
+ // Reflection result
425
+ const reflection: Reflection = {
426
+ id: 'ref_123',
427
+ runId: 'run_456',
428
+ agentId: 'agent_789',
429
+ timestamp: new Date(),
430
+ action: {
431
+ type: 'tool_call',
432
+ toolName: 'search',
433
+ input: { query: 'AI news' },
434
+ output: { results: [] },
435
+ duration: 500,
436
+ },
437
+ analysis: {
438
+ wasSuccessful: false,
439
+ confidence: 0.8,
440
+ reasoning: 'Search returned no results, should try broader query',
441
+ whatCouldImprove: 'Use more general search terms',
442
+ },
443
+ insights: [
444
+ {
445
+ id: 'ins_1',
446
+ type: 'tip',
447
+ content: 'Broaden search queries when results are empty',
448
+ context: 'search operations',
449
+ confidence: 0.85,
450
+ /* ... */
451
+ },
452
+ ],
453
+ goal: 'Find recent AI news',
454
+ iterationIndex: 2,
455
+ };
456
+ ```
457
+
458
+ ---
459
+
460
+ ## Reasoning Types
461
+
462
+ Tree-of-Thought (ToT) reasoning types for branching exploration.
463
+
464
+ ```typescript
465
+ import type {
466
+ ToTConfig,
467
+ ThoughtTree,
468
+ ThoughtNode,
469
+ ThoughtBranch,
470
+ ToTResult,
471
+ ExplorationStrategy,
472
+ } from '@cogitator-ai/types';
473
+
474
+ // ToT configuration
475
+ const totConfig: ToTConfig = {
476
+ branchFactor: 3, // Generate 3 candidate thoughts per step
477
+ beamWidth: 2, // Keep top 2 branches
478
+ maxDepth: 5, // Max reasoning depth
479
+ explorationStrategy: 'beam', // 'beam' | 'best-first' | 'dfs'
480
+
481
+ confidenceThreshold: 0.3,
482
+ terminationConfidence: 0.8,
483
+ maxTotalNodes: 50,
484
+ maxIterationsPerBranch: 3,
485
+
486
+ // Callbacks
487
+ onBranchGenerated: (node, branches) => console.log('Generated:', branches.length),
488
+ onBranchEvaluated: (branch, score) => console.log('Score:', score.composite),
489
+ onNodeExplored: (node) => console.log('Explored:', node.id),
490
+ onBacktrack: (from, to) => console.log('Backtracking...'),
491
+ };
492
+
493
+ // Thought branch with proposed action
494
+ const branch: ThoughtBranch = {
495
+ id: 'branch_1',
496
+ parentId: 'node_0',
497
+ thought: 'I should search for the latest information first',
498
+ proposedAction: { type: 'tool_call', toolName: 'search', arguments: { query: 'AI news 2024' } },
499
+ score: { confidence: 0.8, progress: 0.3, novelty: 0.6, composite: 0.57, reasoning: '...' },
500
+ messagesSnapshot: [
501
+ /* ... */
502
+ ],
503
+ };
504
+ ```
505
+
506
+ ---
507
+
508
+ ## Learning Types
509
+
510
+ DSPy-inspired agent optimization types.
12
511
 
13
512
  ```typescript
14
- import type { Agent, Tool, Message, RunResult } from '@cogitator-ai/types';
513
+ import type {
514
+ ExecutionTrace,
515
+ TraceStore,
516
+ Demo,
517
+ OptimizerConfig,
518
+ OptimizationResult,
519
+ LearningConfig,
520
+ } from '@cogitator-ai/types';
521
+
522
+ // Learning configuration
523
+ const learningConfig: LearningConfig = {
524
+ enabled: true,
525
+ captureTraces: true,
526
+ autoOptimize: true,
527
+ optimizeAfterRuns: 10,
528
+ maxDemosPerAgent: 5,
529
+ minScoreForDemo: 0.8,
530
+ defaultMetrics: ['success', 'tool_accuracy', 'efficiency'],
531
+ };
532
+
533
+ // Optimizer configuration
534
+ const optimizerConfig: OptimizerConfig = {
535
+ type: 'full', // 'bootstrap-few-shot' | 'instruction' | 'full'
536
+ maxBootstrappedDemos: 5,
537
+ maxRounds: 3,
538
+ instructionCandidates: 3,
539
+ metricThreshold: 0.7,
540
+ teacherModel: 'gpt-4o',
541
+ };
15
542
 
16
- const agent: Agent = {
17
- name: 'my-agent',
18
- instructions: 'You are a helpful assistant',
19
- model: 'ollama/llama3.2:3b',
543
+ // Execution trace
544
+ const trace: ExecutionTrace = {
545
+ id: 'trace_123',
546
+ runId: 'run_456',
547
+ agentId: 'agent_789',
548
+ input: 'Calculate compound interest',
549
+ output: 'The compound interest is $1,628.89',
550
+ steps: [
551
+ /* execution steps */
552
+ ],
553
+ metrics: {
554
+ success: true,
555
+ toolAccuracy: 0.95,
556
+ efficiency: 0.8,
557
+ completeness: 1.0,
558
+ },
559
+ score: 0.92,
560
+ isDemo: true,
561
+ /* ... */
20
562
  };
21
563
  ```
22
564
 
23
- ## Types
565
+ ---
566
+
567
+ ## Time Travel Types
568
+
569
+ Execution debugging with checkpoints, replay, and forking.
570
+
571
+ ```typescript
572
+ import type {
573
+ ExecutionCheckpoint,
574
+ TimeTravelCheckpointStore,
575
+ ReplayOptions,
576
+ ReplayResult,
577
+ ForkOptions,
578
+ TraceDiff,
579
+ } from '@cogitator-ai/types';
580
+
581
+ // Checkpoint
582
+ const checkpoint: ExecutionCheckpoint = {
583
+ id: 'cp_123',
584
+ traceId: 'trace_456',
585
+ runId: 'run_789',
586
+ agentId: 'agent_abc',
587
+ stepIndex: 5,
588
+ messages: [
589
+ /* conversation at this point */
590
+ ],
591
+ toolResults: { call_1: 42, call_2: 'result' },
592
+ pendingToolCalls: [],
593
+ label: 'before-critical-decision',
594
+ createdAt: new Date(),
595
+ };
596
+
597
+ // Replay options
598
+ const replayOptions: ReplayOptions = {
599
+ fromCheckpoint: 'cp_123',
600
+ mode: 'live', // 'deterministic' | 'live'
601
+ modifiedToolResults: { call_3: 'different_result' },
602
+ skipTools: ['expensive_api'],
603
+ onStep: (step, index) => console.log(`Step ${index}:`, step.type),
604
+ pauseAt: 8,
605
+ };
606
+
607
+ // Fork options (branch execution with modifications)
608
+ const forkOptions: ForkOptions = {
609
+ checkpointId: 'cp_123',
610
+ input: 'Try a different approach',
611
+ additionalContext: 'Focus on efficiency',
612
+ mockToolResults: { api_call: { mocked: true } },
613
+ label: 'efficiency-experiment',
614
+ };
615
+
616
+ // Compare two execution traces
617
+ const diff: TraceDiff = {
618
+ trace1Id: 'trace_a',
619
+ trace2Id: 'trace_b',
620
+ stepDiffs: [
621
+ { index: 0, status: 'identical' },
622
+ { index: 1, status: 'similar', differences: ['different tool args'] },
623
+ {
624
+ index: 2,
625
+ status: 'different',
626
+ step1: {
627
+ /* ... */
628
+ },
629
+ step2: {
630
+ /* ... */
631
+ },
632
+ },
633
+ ],
634
+ divergencePoint: 2,
635
+ metricsDiff: {
636
+ success: { trace1: true, trace2: false },
637
+ score: { trace1: 0.9, trace2: 0.6, delta: -0.3 },
638
+ /* ... */
639
+ },
640
+ };
641
+ ```
642
+
643
+ ---
644
+
645
+ ## Memory Types
646
+
647
+ See [@cogitator-ai/memory](../memory) for detailed memory adapter types.
648
+
649
+ ---
650
+
651
+ ## Knowledge Graph Types
652
+
653
+ Entity-relationship memory with traversal and inference.
654
+
655
+ ```typescript
656
+ import type {
657
+ GraphNode,
658
+ GraphEdge,
659
+ EntityType,
660
+ RelationType,
661
+ GraphAdapter,
662
+ TraversalOptions,
663
+ TraversalResult,
664
+ GraphPath,
665
+ EntityExtractionResult,
666
+ InferredEdge,
667
+ } from '@cogitator-ai/types';
668
+
669
+ // Entity types
670
+ type EntityType = 'person' | 'organization' | 'location' | 'concept' | 'event' | 'object';
671
+
672
+ // Relationship types
673
+ type RelationType =
674
+ | 'knows'
675
+ | 'works_at'
676
+ | 'located_in'
677
+ | 'part_of'
678
+ | 'related_to'
679
+ | 'created_by'
680
+ | 'owns'
681
+ | 'member_of'
682
+ | 'causes'
683
+ | 'depends_on';
684
+
685
+ // Graph node
686
+ const node: GraphNode = {
687
+ id: 'node_123',
688
+ agentId: 'agent-1',
689
+ type: 'person',
690
+ name: 'Alice',
691
+ aliases: ['alice_dev'],
692
+ description: 'Software engineer',
693
+ properties: { role: 'developer', team: 'platform' },
694
+ embedding: [0.1, 0.2, ...],
695
+ confidence: 1.0,
696
+ source: 'extracted',
697
+ createdAt: new Date(),
698
+ };
699
+
700
+ // Graph edge
701
+ const edge: GraphEdge = {
702
+ id: 'edge_456',
703
+ agentId: 'agent-1',
704
+ sourceNodeId: 'node_123',
705
+ targetNodeId: 'node_789',
706
+ type: 'works_at',
707
+ label: 'Senior Developer',
708
+ weight: 1.0,
709
+ bidirectional: false,
710
+ confidence: 0.95,
711
+ source: 'extracted',
712
+ properties: { since: '2020' },
713
+ createdAt: new Date(),
714
+ };
715
+
716
+ // Traversal options
717
+ const traversalOptions: TraversalOptions = {
718
+ startNodeId: 'node_123',
719
+ maxDepth: 3,
720
+ direction: 'outgoing',
721
+ edgeTypes: ['works_at', 'knows'],
722
+ nodeTypes: ['person', 'organization'],
723
+ minConfidence: 0.7,
724
+ maxNodes: 100,
725
+ };
726
+
727
+ // Traversal result
728
+ const result: TraversalResult = {
729
+ visitedNodes: [node1, node2, ...],
730
+ traversedEdges: [edge1, edge2, ...],
731
+ paths: [[node1, edge1, node2], ...],
732
+ totalNodesVisited: 15,
733
+ maxDepthReached: 3,
734
+ };
735
+ ```
736
+
737
+ ---
738
+
739
+ ## Prompt Optimization Types
740
+
741
+ A/B testing, monitoring, and version control for agent instructions.
742
+
743
+ ```typescript
744
+ import type {
745
+ CapturedPrompt,
746
+ PromptStore,
747
+ ABTest,
748
+ ABTestResults,
749
+ ABTestOutcome,
750
+ ABTestStore,
751
+ InstructionVersion,
752
+ InstructionVersionStore,
753
+ PromptPerformanceMetrics,
754
+ DegradationAlert,
755
+ OptimizationRun,
756
+ } from '@cogitator-ai/types';
757
+
758
+ // Captured prompt
759
+ const prompt: CapturedPrompt = {
760
+ id: 'prompt_123',
761
+ runId: 'run_456',
762
+ agentId: 'agent-1',
763
+ model: 'gpt-4o',
764
+ systemPrompt: 'You are a helpful assistant.',
765
+ messages: [{ role: 'user', content: 'Hello' }],
766
+ tools: [{ name: 'calculator', description: '...' }],
767
+ promptTokens: 150,
768
+ response: {
769
+ content: 'Hi there!',
770
+ completionTokens: 10,
771
+ latencyMs: 450,
772
+ },
773
+ createdAt: new Date(),
774
+ };
775
+
776
+ // A/B test
777
+ const abTest: ABTest = {
778
+ id: 'test_123',
779
+ agentId: 'agent-1',
780
+ name: 'Instruction Experiment',
781
+ description: 'Testing concise vs verbose',
782
+ status: 'running',
783
+ controlInstructions: 'You are helpful.',
784
+ treatmentInstructions: 'Be concise and direct.',
785
+ treatmentAllocation: 0.5,
786
+ minSampleSize: 100,
787
+ maxDuration: 7 * 24 * 60 * 60 * 1000,
788
+ confidenceLevel: 0.95,
789
+ metricToOptimize: 'score',
790
+ controlResults: { sampleSize: 50, avgScore: 0.82, ... },
791
+ treatmentResults: { sampleSize: 48, avgScore: 0.87, ... },
792
+ createdAt: new Date(),
793
+ startedAt: new Date(),
794
+ };
795
+
796
+ // A/B test outcome
797
+ const outcome: ABTestOutcome = {
798
+ winner: 'treatment',
799
+ pValue: 0.023,
800
+ confidenceInterval: [0.02, 0.08],
801
+ effectSize: 0.45,
802
+ isSignificant: true,
803
+ recommendation: 'Treatment performs significantly better.',
804
+ };
805
+
806
+ // Instruction version
807
+ const version: InstructionVersion = {
808
+ id: 'ver_123',
809
+ agentId: 'agent-1',
810
+ version: 3,
811
+ instructions: 'Optimized instructions...',
812
+ source: 'optimization',
813
+ sourceId: 'opt-run-456',
814
+ deployedAt: new Date(),
815
+ metrics: { runCount: 100, avgScore: 0.88, successRate: 0.95 },
816
+ };
817
+
818
+ // Degradation alert
819
+ const alert: DegradationAlert = {
820
+ id: 'alert_123',
821
+ agentId: 'agent-1',
822
+ type: 'score_drop',
823
+ severity: 'warning',
824
+ currentValue: 0.72,
825
+ baselineValue: 0.85,
826
+ threshold: 0.15,
827
+ percentChange: 0.153,
828
+ detectedAt: new Date(),
829
+ autoAction: 'rollback',
830
+ actionTaken: false,
831
+ };
832
+ ```
833
+
834
+ ---
835
+
836
+ ## Sandbox Types
837
+
838
+ See [@cogitator-ai/sandbox](../sandbox) for detailed sandbox execution types.
839
+
840
+ ## Workflow Types
841
+
842
+ See [@cogitator-ai/workflows](../workflows) for detailed workflow types.
24
843
 
25
- - **Agent** - Agent configuration
26
- - **Tool** - Tool definition with Zod schemas
27
- - **Message** - Chat messages (user, assistant, tool)
28
- - **RunResult** - Execution results with usage stats
29
- - **Workflow** - DAG workflow definitions
30
- - **Swarm** - Multi-agent swarm configurations
31
- - **Memory** - Memory adapters and context builders
844
+ ## Swarm Types
32
845
 
33
- ## Documentation
846
+ See [@cogitator-ai/swarms](../swarms) for detailed swarm coordination types.
34
847
 
35
- See the [Cogitator documentation](https://github.com/eL1fe/cogitator) for full API reference.
848
+ ---
36
849
 
37
850
  ## License
38
851