@almadar/agent 1.0.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.
@@ -0,0 +1,742 @@
1
+ import { SubAgent } from './types.js';
2
+ export { AgentDependencies, CombineOrbitalsFn, CombinerOptions, CombinerResult, ConvertDomainToSchemaFn, DomainConversionResult, GenerateFullOrbitalFn, GenerationLog, OrbitalGenerationOptions, OrbitalGenerationResult } from './types.js';
3
+ export { C as CompleteEvent, b as ContinueRequest, c as ContinueRequestSchema, E as ErrorEvent, d as ExtractedRequirementsInput, e as ExtractedRequirementsSchema, G as GenerateRequest, f as GenerateRequestSchema, g as GenerationLogEvent, I as InterruptEvent, M as MessageEvent, R as ResumeRequest, h as ResumeRequestSchema, a as SSEEvent, S as SSEEventType, i as StartEvent, j as SubagentEvent, T as TodoUpdateEvent, k as ToolCallEvent, l as ToolResultEvent, m as createSSEEvent, n as formatSSEEvent, o as isSSECompleteEvent, p as isSSEErrorEvent, q as isSSEGenerationLogEvent, r as isSSEInterruptEvent, s as isSSEMessageEvent, t as isSSEStartEvent, u as isSSESubagentEvent, v as isSSETodoDetailEvent, w as isSSETodoUpdateEvent, x as isSSEToolCallEvent, y as parseSSEEvent } from './api-types-BW_58thJ.js';
4
+ export { TraitCompleteCallback, TraitEventCallback, TraitSpec, TraitSubagentToolOptions, createAgentTools, createApplyChunkTool, createCombineSchemasTool, createExecuteTool, createExtractChunkTool, createFinishTaskTool, createGenerateSchemaTool, createQuerySchemaStructureTool, createSchemaChunkingTools, createTraitEventWrapper, createTraitSubagentTool, createValidateSchemaTool, validateCommandPaths } from './tools/index.js';
5
+ import { DomainContext, OrbitalSchema, Orbital, OrbitalDefinition, FullOrbitalUnit as FullOrbitalUnit$1 } from '@almadar/core/types';
6
+ import { LLMClient } from '@almadar/llm';
7
+ export { createCompactSystemPrompt, createSystemPrompt } from './prompts/index.js';
8
+ import { BaseMessage } from '@langchain/core/messages';
9
+ export { EVENT_BUDGETS, SessionManager, SessionManagerOptions, Skill, SkillAgentOptions, SkillAgentResult, SkillLoader, SkillMeta, SkillRefLoader, createSkillAgent, getBudgetWarningMessage, getEventBudget, getInterruptConfig, resumeSkillAgent } from './agent/index.js';
10
+ export { F as FirestoreCheckpointer, a as FirestoreCheckpointerOptions, b as FirestoreDb, c as FirestoreTimestamp, P as PersistenceMode, S as Session, d as SessionMetadata, e as SessionRecord } from './firestore-checkpointer-DxbQ10ve.js';
11
+ export { FirestoreSessionStore, FirestoreSessionStoreOptions, FirestoreStore, FirestoreStoreOptions, MemorySessionBackend } from './persistence/index.js';
12
+ export { RawAgentEvent, extractFileOperation, extractInterruptData, hasInterrupt, isFileOperation, isTodoUpdate, transformAgentEvent, transformAgentEventMulti } from './event-transformer/index.js';
13
+ export { Command } from '@langchain/langgraph';
14
+ export { D as DomainOrbitalCompleteCallback, a as DomainOrbitalEventCallback, b as DomainOrbitalSpec, c as DomainOrbitalToolOptions, O as OrbitalCompleteCallback, d as OrbitalRequirements, e as OrbitalSubagentToolOptions, S as SubagentEventCallback, f as createConstructCombinedDomainTool, g as createDomainOrbitalTools, h as createGenerateOrbitalDomainTool, i as createOrbitalSubagentTool, j as createSubagentEventWrapper } from './orbital-subagent-BsQBhKzi.js';
15
+ import 'zod';
16
+ import '@langchain/core/tools';
17
+ import '@langchain/langgraph-checkpoint';
18
+ import '@langchain/core/runnables';
19
+
20
+ /**
21
+ * Orbital Combiner
22
+ *
23
+ * Deterministically combines multiple Orbitals into a single OrbitalSchema.
24
+ * This removes the need for LLM involvement in the combining step.
25
+ *
26
+ * All UI is rendered via render_ui effects from traits (no static sections).
27
+ *
28
+ * NOTE: Validation is handled externally via `orbital validate` CLI.
29
+ * The combiner only assembles schemas - it does not validate them.
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+
34
+ interface OrbitalSchemaValidationResult {
35
+ valid: boolean;
36
+ errors: Array<{
37
+ code: string;
38
+ message: string;
39
+ path?: string;
40
+ }>;
41
+ warnings: Array<{
42
+ code: string;
43
+ message: string;
44
+ path?: string;
45
+ }>;
46
+ }
47
+ type FullOrbitalUnit = Orbital;
48
+ interface CombinerOptions {
49
+ /** Application name */
50
+ name: string;
51
+ /** Optional description */
52
+ description?: string;
53
+ /** Schema version */
54
+ version?: string;
55
+ /** Domain context */
56
+ domain?: DomainContext;
57
+ /** Whether to run validation (default: true) */
58
+ validate?: boolean;
59
+ /** Global theme */
60
+ theme?: string;
61
+ /** Default route (first page if not specified) */
62
+ defaultRoute?: string;
63
+ }
64
+ interface CombinerResult {
65
+ /** Whether combining succeeded */
66
+ success: boolean;
67
+ /** The combined OrbitalSchema (if successful) */
68
+ schema?: OrbitalSchema;
69
+ /** Validation result (if validation was run) */
70
+ validation?: OrbitalSchemaValidationResult;
71
+ /** Error message (if failed) */
72
+ error?: string;
73
+ /** Statistics about the combining */
74
+ stats: {
75
+ totalOrbitals: number;
76
+ totalEntities: number;
77
+ totalPages: number;
78
+ totalTraits: number;
79
+ };
80
+ }
81
+ /**
82
+ * Combine multiple Orbitals into a single OrbitalSchema.
83
+ *
84
+ * This function performs deterministic merging:
85
+ * 1. Builds an OrbitalSchema from the Orbitals
86
+ * 2. Optionally runs validation
87
+ *
88
+ * Note: All UI is rendered via render_ui effects from traits.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const result = combineOrbitals([taskOrbital, userOrbital], {
93
+ * name: 'My App',
94
+ * validate: true,
95
+ * });
96
+ *
97
+ * if (result.success) {
98
+ * // Write schema to file
99
+ * await fs.writeFile('schema.json', JSON.stringify(result.schema, null, 2));
100
+ * } else {
101
+ * console.error(result.error);
102
+ * console.error(result.validation?.errors);
103
+ * }
104
+ * ```
105
+ */
106
+ declare function combineOrbitals(orbitals: FullOrbitalUnit[], options: CombinerOptions): CombinerResult;
107
+ /**
108
+ * Combine orbitals and return only the schema (throws on error).
109
+ * Use this when you want a simple API and will handle errors upstream.
110
+ */
111
+ declare function combineOrbitalsToSchema(orbitals: FullOrbitalUnit[], options: CombinerOptions): OrbitalSchema;
112
+ /**
113
+ * Estimate the combination complexity (for progress indication).
114
+ */
115
+ declare function estimateCombineComplexity(orbitals: FullOrbitalUnit[]): {
116
+ entities: number;
117
+ pages: number;
118
+ traits: number;
119
+ totalSections: number;
120
+ };
121
+
122
+ /**
123
+ * Effect operator mapping: Both systems use the same operator names
124
+ */
125
+ declare const EFFECT_OPERATORS: readonly ["set", "emit", "navigate", "render-ui", "persist", "call-service", "spawn", "despawn", "do", "notify"];
126
+ /**
127
+ * Effect operator names (S-expression first element)
128
+ * These are the operators used in S-expression effects like ['emit', ...]
129
+ */
130
+ type EffectType = (typeof EFFECT_OPERATORS)[number];
131
+ interface SourceLocation {
132
+ line: number;
133
+ column: number;
134
+ offset: number;
135
+ }
136
+ interface SourceRange {
137
+ start: SourceLocation;
138
+ end: SourceLocation;
139
+ }
140
+ interface ASTNode {
141
+ type: string;
142
+ range?: SourceRange;
143
+ }
144
+ /**
145
+ * Domain Language field types
146
+ *
147
+ * Note: These map to OrbitalSchema types via DOMAIN_TO_SCHEMA_FIELD_TYPE
148
+ */
149
+ type DomainFieldType = 'text' | 'long text' | 'number' | 'currency' | 'date' | 'timestamp' | 'datetime' | 'yes/no' | 'enum' | 'list' | 'object' | 'relation';
150
+ interface DomainField extends ASTNode {
151
+ type: 'field';
152
+ name: string;
153
+ fieldType: DomainFieldType;
154
+ required: boolean;
155
+ unique: boolean;
156
+ auto: boolean;
157
+ default?: unknown;
158
+ enumValues?: string[];
159
+ }
160
+ type RelationshipType = 'belongs_to' | 'has_many' | 'has_one';
161
+ interface DomainRelationship extends ASTNode {
162
+ type: 'relationship';
163
+ relationshipType: RelationshipType;
164
+ targetEntity: string;
165
+ alias?: string;
166
+ }
167
+ interface DomainEntity extends ASTNode {
168
+ type: 'entity';
169
+ name: string;
170
+ description: string;
171
+ fields: DomainField[];
172
+ relationships: DomainRelationship[];
173
+ states?: string[];
174
+ initialState?: string;
175
+ }
176
+ interface DomainPageSection extends ASTNode {
177
+ type: 'page_section';
178
+ description: string;
179
+ }
180
+ interface DomainPageAction extends ASTNode {
181
+ type: 'page_action';
182
+ trigger: string;
183
+ action: string;
184
+ }
185
+ interface DomainPage extends ASTNode {
186
+ type: 'page';
187
+ name: string;
188
+ description: string;
189
+ purpose: string;
190
+ url: string;
191
+ primaryEntity?: string;
192
+ traitName?: string;
193
+ sections: DomainPageSection[];
194
+ actions: DomainPageAction[];
195
+ onAccess?: string;
196
+ }
197
+ type ComparisonOperator = '==' | '!=' | '>' | '<' | '>=' | '<=';
198
+ type LogicalOperator = 'AND' | 'OR';
199
+ interface FieldReference extends ASTNode {
200
+ type: 'field_reference';
201
+ entityName: string;
202
+ fieldName: string;
203
+ }
204
+ interface FieldCheckCondition extends ASTNode {
205
+ type: 'field_check';
206
+ field: FieldReference;
207
+ check: 'provided' | 'empty' | 'equals';
208
+ value?: string | number | boolean;
209
+ }
210
+ interface ComparisonCondition extends ASTNode {
211
+ type: 'comparison';
212
+ field: FieldReference;
213
+ operator: ComparisonOperator;
214
+ value: string | number | boolean;
215
+ }
216
+ interface UserCheckCondition extends ASTNode {
217
+ type: 'user_check';
218
+ check: 'is_role' | 'owns_this';
219
+ role?: string;
220
+ ownerField?: string;
221
+ }
222
+ interface LogicalCondition extends ASTNode {
223
+ type: 'logical';
224
+ operator: LogicalOperator;
225
+ left: GuardCondition;
226
+ right: GuardCondition;
227
+ }
228
+ type GuardCondition = FieldCheckCondition | ComparisonCondition | UserCheckCondition | LogicalCondition;
229
+ interface DomainGuard extends ASTNode {
230
+ type: 'guard';
231
+ condition: GuardCondition;
232
+ raw: string;
233
+ }
234
+ interface DomainEffect extends ASTNode {
235
+ type: 'effect';
236
+ effectType: EffectType;
237
+ description: string;
238
+ config: Record<string, unknown>;
239
+ }
240
+ interface DomainTransition extends ASTNode {
241
+ type: 'transition';
242
+ fromState: string;
243
+ toState: string;
244
+ event: string;
245
+ guards: DomainGuard[];
246
+ effects: DomainEffect[];
247
+ }
248
+ interface DomainTick extends ASTNode {
249
+ type: 'tick';
250
+ name: string;
251
+ interval: string;
252
+ intervalMs?: number;
253
+ guard?: DomainGuard;
254
+ effects: DomainEffect[];
255
+ }
256
+ interface DomainBehavior extends ASTNode {
257
+ type: 'behavior';
258
+ name: string;
259
+ entityName: string;
260
+ states: string[];
261
+ initialState: string;
262
+ transitions: DomainTransition[];
263
+ ticks: DomainTick[];
264
+ rules: string[];
265
+ }
266
+ interface DomainDocument extends ASTNode {
267
+ type: 'document';
268
+ entities: DomainEntity[];
269
+ pages: DomainPage[];
270
+ behaviors: DomainBehavior[];
271
+ }
272
+ interface SectionMapping {
273
+ sectionId: string;
274
+ sectionType: 'entity' | 'page' | 'behavior' | 'tick';
275
+ schemaPath: string;
276
+ domainText: string;
277
+ aiDescription?: string;
278
+ range?: SourceRange;
279
+ lastModified?: number;
280
+ }
281
+ interface ParseError {
282
+ message: string;
283
+ range?: SourceRange;
284
+ suggestion?: string;
285
+ }
286
+
287
+ /**
288
+ * Schema to Domain Converter
289
+ *
290
+ * Converts a complete OrbitalSchema to domain language text.
291
+ * Generates three sections: Entities, Pages, and Behaviors.
292
+ *
293
+ * Updated to read from OrbitalSchema where entities, pages, and traits
294
+ * are grouped into Orbital units. Also supports legacy KFlowSchema format
295
+ * for backward compatibility.
296
+ */
297
+
298
+ interface SchemaToDomainResult {
299
+ /** The complete domain text document */
300
+ domainText: string;
301
+ /** Parsed AST representation */
302
+ document: DomainDocument;
303
+ /** Mapping of sections to schema paths */
304
+ mappings: SectionMapping[];
305
+ /** Separate section texts for individual editing */
306
+ sections: {
307
+ entities: string[];
308
+ pages: string[];
309
+ behaviors: string[];
310
+ };
311
+ }
312
+ /**
313
+ * Legacy KFlowSchema format (for backward compatibility)
314
+ */
315
+ interface LegacyKFlowSchema {
316
+ name?: string;
317
+ dataEntities?: Array<Record<string, unknown>>;
318
+ ui?: {
319
+ pages?: Array<Record<string, unknown>>;
320
+ };
321
+ traits?: Array<Record<string, unknown>>;
322
+ ticks?: Array<Record<string, unknown>>;
323
+ }
324
+ /**
325
+ * Combined input type for the converter
326
+ */
327
+ type SchemaInput = OrbitalSchema | LegacyKFlowSchema;
328
+ /**
329
+ * Convert a complete OrbitalSchema or legacy KFlowSchema to domain language
330
+ */
331
+ declare function convertSchemaToDomain(schema: SchemaInput): SchemaToDomainResult;
332
+
333
+ /**
334
+ * Domain to Schema Converter
335
+ *
336
+ * Applies domain language text changes to an OrbitalSchema.
337
+ * Supports incremental updates (single section) and full replacement.
338
+ *
339
+ * Updated to use OrbitalSchema where entities, pages, and traits
340
+ * are grouped into Orbital units instead of flat arrays.
341
+ */
342
+
343
+ interface DomainToSchemaResult {
344
+ /** Whether the conversion was successful */
345
+ success: boolean;
346
+ /** The updated schema */
347
+ schema: OrbitalSchema;
348
+ /** Any parse errors encountered */
349
+ errors: ParseError[];
350
+ /** Warnings (non-fatal issues) */
351
+ warnings: ParseError[];
352
+ /** Updated section mappings */
353
+ mappings: SectionMapping[];
354
+ }
355
+ /**
356
+ * Parse a complete domain document and convert to OrbitalSchema
357
+ */
358
+ declare function convertDomainToSchema(domainText: string, baseSchema?: OrbitalSchema): DomainToSchemaResult;
359
+ /**
360
+ * Apply a single section update to an OrbitalSchema
361
+ */
362
+ declare function applySectionUpdate(schema: OrbitalSchema, sectionType: 'entity' | 'page' | 'behavior' | 'tick', sectionId: string, newDomainText: string): DomainToSchemaResult;
363
+ /**
364
+ * Delete a section from the schema
365
+ */
366
+ declare function deleteSection(schema: OrbitalSchema, sectionType: 'entity' | 'page' | 'behavior' | 'tick', sectionId: string): OrbitalSchema;
367
+
368
+ /**
369
+ * Orbital Generator
370
+ *
371
+ * Provides utilities for generating FullOrbitalUnit definitions from
372
+ * lightweight OrbitalUnit inputs. Designed for SUBAGENT use where each
373
+ * orbital is generated separately for better caching.
374
+ *
375
+ * ## Subagent Caching Pattern
376
+ *
377
+ * When generating multiple orbitals in a subagent pattern:
378
+ * 1. Main agent decomposes request → OrbitalUnit[]
379
+ * 2. For each orbital, subagent calls generateFullOrbital()
380
+ * 3. Each subagent call uses the SAME cached system prompt blocks
381
+ * 4. Anthropic caches at request level → subsequent calls get 90% discount
382
+ *
383
+ * This is MORE efficient than batch generation because:
384
+ * - System prompt is cached and reused across subagent calls
385
+ * - Template guidance is cached per fingerprint
386
+ * - Only the orbital-specific content varies
387
+ *
388
+ * @packageDocumentation
389
+ */
390
+
391
+ /**
392
+ * Extracted requirements from the analysis phase.
393
+ * Matches ExtractedRequirements from agents/orchestrator/shared/requirements.ts
394
+ */
395
+ interface ExtractedRequirements {
396
+ /** Entity names to create */
397
+ entities: string[];
398
+ /** State names that should exist */
399
+ states: string[];
400
+ /** Event/action names */
401
+ events: string[];
402
+ /** Business rules (become guards) */
403
+ guards: string[];
404
+ /** Page types needed */
405
+ pages: string[];
406
+ /** Notifications/side-effects */
407
+ effects: string[];
408
+ /** Raw requirement statements */
409
+ rawRequirements: string[];
410
+ }
411
+ type OrbitalUnit = OrbitalDefinition;
412
+ /**
413
+ * A structured log entry from the generation process.
414
+ * Used for debugging and observability of subagent reasoning.
415
+ */
416
+ interface GenerationLog {
417
+ /** Timestamp of the log entry */
418
+ timestamp: number;
419
+ /** Log level */
420
+ level: 'info' | 'warn' | 'error' | 'debug';
421
+ /** Log message */
422
+ message: string;
423
+ /** Optional structured data */
424
+ data?: Record<string, unknown>;
425
+ }
426
+ interface OrbitalGenerationOptions {
427
+ /** Maximum tokens for generation */
428
+ maxTokens?: number;
429
+ /** Enable validation after generation */
430
+ validate?: boolean;
431
+ /** Callback for real-time log streaming (SSE integration) */
432
+ onLog?: (log: GenerationLog, orbitalName?: string) => void;
433
+ /** Optional requirements relevant to this orbital (from analysis) */
434
+ requirements?: Partial<ExtractedRequirements>;
435
+ }
436
+ interface OrbitalGenerationResult {
437
+ /** Generated full orbital unit */
438
+ orbital: FullOrbitalUnit$1;
439
+ /** Fingerprint used for caching */
440
+ fingerprint: string;
441
+ /** Whether template guidance was used */
442
+ usedTemplate: boolean;
443
+ /** Token usage */
444
+ usage?: {
445
+ promptTokens: number;
446
+ completionTokens: number;
447
+ totalTokens: number;
448
+ };
449
+ /** Validation result */
450
+ validation?: {
451
+ valid: boolean;
452
+ errorCount: number;
453
+ warningCount: number;
454
+ };
455
+ /** Structured logs from the generation process */
456
+ logs: GenerationLog[];
457
+ }
458
+ /**
459
+ * Generate a full orbital unit from a lightweight orbital input.
460
+ *
461
+ * DESIGNED FOR SUBAGENT USE: Call this once per orbital in separate
462
+ * subagent invocations. Caching works across calls because:
463
+ * - System prompt blocks are marked as cacheable
464
+ * - Anthropic caches at the request level
465
+ * - Subsequent calls with same system prompt get cache hits
466
+ *
467
+ * @example
468
+ * ```typescript
469
+ * // In subagent for each orbital:
470
+ * const result = await generateFullOrbital(client, orbitalUnit, { validate: true });
471
+ * // First call: Cache WRITE: 3500 tokens
472
+ * // Second call: Cache HIT: 3500 tokens (90% discount!)
473
+ * ```
474
+ */
475
+ declare function generateFullOrbital(client: LLMClient, orbital: OrbitalUnit, options?: OrbitalGenerationOptions): Promise<OrbitalGenerationResult>;
476
+ /**
477
+ * Estimate cache savings for a set of orbitals.
478
+ *
479
+ * Use this to predict how much caching will help for a decomposition.
480
+ */
481
+ declare function estimateCacheSavings(orbitals: OrbitalUnit[]): {
482
+ totalOrbitals: number;
483
+ uniqueFingerprints: number;
484
+ estimatedCacheHits: number;
485
+ estimatedSavingsPercent: number;
486
+ };
487
+
488
+ /**
489
+ * KFlow DeepAgent Subagents
490
+ *
491
+ * Specialized subagents for complex schema generation tasks.
492
+ * These are spawned via the `task()` built-in tool.
493
+ *
494
+ * Uses @almadar/skills for schema reference documentation.
495
+ *
496
+ * @packageDocumentation
497
+ */
498
+
499
+ /**
500
+ * Create the Schema Generator Subagent configuration.
501
+ *
502
+ * Focused agent for generating KFlow schemas from requirements.
503
+ * Writes schema to file and verifies it exists.
504
+ */
505
+ declare function createSchemaGeneratorSubagent(): SubAgent;
506
+ /**
507
+ * Create the Error Fixer Subagent configuration.
508
+ *
509
+ * Focused agent for fixing validation and compilation errors.
510
+ */
511
+ declare function createErrorFixerSubagent(): SubAgent;
512
+ /**
513
+ * Create the Test Analyzer Subagent configuration.
514
+ *
515
+ * Focused agent for analyzing test failures and suggesting fixes.
516
+ */
517
+ declare function createTestAnalyzerSubagent(): SubAgent;
518
+ /**
519
+ * Create all subagent configurations.
520
+ */
521
+ declare function createSubagents(): SubAgent[];
522
+ /**
523
+ * Create subagent configs as a record for easy lookup.
524
+ */
525
+ declare function createSubagentConfigs(): Record<string, SubAgent>;
526
+
527
+ /**
528
+ * DeepAgent SSE Event Types
529
+ *
530
+ * Type definitions for Server-Sent Events from the DeepAgent streaming endpoint.
531
+ * Use these types for client-side consumption of /deepagent/generate-stream.
532
+ *
533
+ * @packageDocumentation
534
+ */
535
+ /**
536
+ * Initial event sent when streaming begins.
537
+ */
538
+ interface DeepAgentStartEvent {
539
+ type: 'start';
540
+ sessionId: string;
541
+ }
542
+ /**
543
+ * Agent execution event (tool calls, messages, etc.).
544
+ */
545
+ interface DeepAgentExecutionEvent {
546
+ type: 'event';
547
+ node?: string;
548
+ toolCall?: {
549
+ name: string;
550
+ args: Record<string, unknown>;
551
+ };
552
+ toolResult?: {
553
+ name: string;
554
+ result: unknown;
555
+ };
556
+ message?: {
557
+ role: 'assistant' | 'user' | 'system';
558
+ content: string;
559
+ };
560
+ [key: string]: unknown;
561
+ }
562
+ /**
563
+ * Schema generated event.
564
+ */
565
+ interface DeepAgentSchemaEvent {
566
+ type: 'schema';
567
+ schema: Record<string, unknown>;
568
+ }
569
+ /**
570
+ * Completion event sent when generation finishes successfully.
571
+ */
572
+ interface DeepAgentCompleteEvent {
573
+ type: 'complete';
574
+ sessionId: string;
575
+ appCompiled: boolean;
576
+ }
577
+ /**
578
+ * Error event sent when generation fails.
579
+ */
580
+ interface DeepAgentErrorEvent {
581
+ type: 'error';
582
+ error: string;
583
+ }
584
+ /**
585
+ * Union of all possible DeepAgent SSE events.
586
+ */
587
+ type DeepAgentEvent = DeepAgentStartEvent | DeepAgentExecutionEvent | DeepAgentSchemaEvent | DeepAgentCompleteEvent | DeepAgentErrorEvent;
588
+ /**
589
+ * Parse an SSE data line into a DeepAgentEvent.
590
+ */
591
+ declare function parseDeepAgentEvent(data: string): DeepAgentEvent;
592
+ /**
593
+ * Type guard for start events.
594
+ */
595
+ declare function isStartEvent(event: DeepAgentEvent): event is DeepAgentStartEvent;
596
+ /**
597
+ * Type guard for execution events.
598
+ */
599
+ declare function isExecutionEvent(event: DeepAgentEvent): event is DeepAgentExecutionEvent;
600
+ /**
601
+ * Type guard for schema events.
602
+ */
603
+ declare function isSchemaEvent(event: DeepAgentEvent): event is DeepAgentSchemaEvent;
604
+ /**
605
+ * Type guard for complete events.
606
+ */
607
+ declare function isCompleteEvent(event: DeepAgentEvent): event is DeepAgentCompleteEvent;
608
+ /**
609
+ * Type guard for error events.
610
+ */
611
+ declare function isErrorEvent(event: DeepAgentEvent): event is DeepAgentErrorEvent;
612
+
613
+ /**
614
+ * Context Compaction for DeepAgent
615
+ *
616
+ * Provides middleware to manage context length in long-running agent sessions.
617
+ * Uses @langchain/core's trimMessages to keep context within token limits.
618
+ *
619
+ * @packageDocumentation
620
+ */
621
+
622
+ /**
623
+ * Configuration for context compaction.
624
+ */
625
+ interface ContextCompactionConfig {
626
+ /**
627
+ * Maximum number of tokens before triggering compaction.
628
+ * Default: 150000 (leaves headroom for Claude's 200K context)
629
+ */
630
+ maxTokens?: number;
631
+ /**
632
+ * Number of recent messages to always keep.
633
+ * Default: 10
634
+ */
635
+ keepRecentMessages?: number;
636
+ /**
637
+ * Whether to include the system message in trimming.
638
+ * Default: false (system message is always kept)
639
+ */
640
+ includeSystem?: boolean;
641
+ /**
642
+ * Strategy for trimming: 'first' keeps first messages, 'last' keeps last messages.
643
+ * Default: 'last'
644
+ */
645
+ strategy?: 'first' | 'last';
646
+ }
647
+ /**
648
+ * Default configuration for context compaction.
649
+ */
650
+ declare const DEFAULT_COMPACTION_CONFIG: Required<ContextCompactionConfig>;
651
+ /**
652
+ * Check if messages need compaction based on estimated token count.
653
+ */
654
+ declare function needsCompaction(messages: BaseMessage[], threshold?: number): boolean;
655
+ /**
656
+ * Create a message summarizer prompt for compacting old context.
657
+ */
658
+ declare function createSummaryPrompt(messages: BaseMessage[]): string;
659
+ /**
660
+ * Estimate token count for messages using character-based heuristic.
661
+ */
662
+ declare function estimateTokens(messages: BaseMessage[]): number;
663
+
664
+ /**
665
+ * Metrics Collection for DeepAgent Evaluation
666
+ *
667
+ * Tracks success rates, iteration counts, token usage, and timing
668
+ * for agent generation tests.
669
+ *
670
+ * @packageDocumentation
671
+ */
672
+ /**
673
+ * Metrics for a single generation attempt.
674
+ */
675
+ interface GenerationMetrics {
676
+ testName: string;
677
+ complexity: 'simple' | 'medium' | 'complex';
678
+ success: boolean;
679
+ iterations: number;
680
+ timeMs: number;
681
+ tokenUsage?: {
682
+ input: number;
683
+ output: number;
684
+ total: number;
685
+ };
686
+ error?: string;
687
+ timestamp?: number;
688
+ }
689
+ /**
690
+ * Aggregated metrics summary.
691
+ */
692
+ interface MetricsSummary {
693
+ total: number;
694
+ passed: number;
695
+ failed: number;
696
+ successRate: number;
697
+ avgIterations: number;
698
+ avgTimeMs: number;
699
+ avgTokens: number;
700
+ byComplexity: {
701
+ simple: {
702
+ total: number;
703
+ passed: number;
704
+ successRate: number;
705
+ };
706
+ medium: {
707
+ total: number;
708
+ passed: number;
709
+ successRate: number;
710
+ };
711
+ complex: {
712
+ total: number;
713
+ passed: number;
714
+ successRate: number;
715
+ };
716
+ };
717
+ }
718
+ /**
719
+ * Collects and aggregates generation metrics.
720
+ */
721
+ declare class MetricsCollector {
722
+ private metrics;
723
+ record(metrics: GenerationMetrics): void;
724
+ getAll(): GenerationMetrics[];
725
+ getSummary(): MetricsSummary;
726
+ private getComplexitySummary;
727
+ getFailures(): GenerationMetrics[];
728
+ getMultiIterationTests(): GenerationMetrics[];
729
+ clear(): void;
730
+ saveToFile(filePath: string): Promise<void>;
731
+ loadFromFile(filePath: string): Promise<void>;
732
+ }
733
+ /**
734
+ * Format metrics summary as a readable string.
735
+ */
736
+ declare function formatSummary(summary: MetricsSummary): string;
737
+ /**
738
+ * Analyze failure patterns to suggest prompt improvements.
739
+ */
740
+ declare function analyzeFailures(failures: GenerationMetrics[]): string[];
741
+
742
+ export { type ContextCompactionConfig, DEFAULT_COMPACTION_CONFIG, type DeepAgentCompleteEvent, type DeepAgentErrorEvent, type DeepAgentEvent, type DeepAgentExecutionEvent, type DeepAgentSchemaEvent, type DeepAgentStartEvent, type DomainDocument, type DomainToSchemaResult, type GenerationMetrics, MetricsCollector, type MetricsSummary, type CombinerOptions as OrbitalCombinerOptions, type CombinerResult as OrbitalCombinerResult, type OrbitalSchemaValidationResult, type ParseError, type SchemaToDomainResult, type SectionMapping, SubAgent, analyzeFailures, applySectionUpdate, combineOrbitals, combineOrbitalsToSchema, convertDomainToSchema, convertSchemaToDomain, createErrorFixerSubagent, createSchemaGeneratorSubagent, createSubagentConfigs, createSubagents, createSummaryPrompt, createTestAnalyzerSubagent, deleteSection, estimateCacheSavings, estimateCombineComplexity, estimateTokens, formatSummary, generateFullOrbital, isCompleteEvent, isErrorEvent, isExecutionEvent, isSchemaEvent, isStartEvent, needsCompaction, parseDeepAgentEvent };