@almadar/agent 1.6.4 → 2.0.1

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 (107) hide show
  1. package/LICENSE +21 -72
  2. package/README.md +25 -0
  3. package/dist/agent/event-budget.d.ts +28 -0
  4. package/dist/agent/experimental/hitl-v2.d.ts +161 -0
  5. package/dist/agent/experimental/hitl-workflow-integration.d.ts +182 -0
  6. package/dist/agent/index.d.ts +14 -13
  7. package/dist/agent/index.js.map +1 -1
  8. package/dist/agent/interrupt-config.d.ts +51 -0
  9. package/dist/agent/session-manager.d.ts +204 -0
  10. package/dist/agent/skill-agent.d.ts +182 -0
  11. package/dist/agent/workflow-middleware.d.ts +63 -0
  12. package/dist/agent/workflow-tool-wrapper.d.ts +87 -0
  13. package/dist/{api-types-CXrq-fts.d.ts → api-types.d.ts} +85 -51
  14. package/dist/context/compaction.d.ts +191 -0
  15. package/dist/context-compaction.d.ts +55 -0
  16. package/dist/evals/online-sampling.d.ts +114 -0
  17. package/dist/evals/utils/compact-orbital.d.ts +100 -0
  18. package/dist/event-transformer/event-transformer.d.ts +120 -0
  19. package/dist/event-transformer/index.d.ts +4 -122
  20. package/dist/events.d.ts +85 -0
  21. package/dist/index.d.ts +58 -1678
  22. package/dist/index.js +39 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/memory/MemoryManager.d.ts +243 -0
  25. package/dist/memory/PreferenceLearner.d.ts +59 -0
  26. package/dist/memory/agentic-search.d.ts +116 -0
  27. package/dist/memory/index.d.ts +14 -0
  28. package/dist/memory/memory-orbital.d.ts +66 -0
  29. package/dist/memory/types.d.ts +143 -0
  30. package/dist/metrics.d.ts +77 -0
  31. package/dist/multi-user.d.ts +155 -0
  32. package/dist/observability/index.d.ts +14 -0
  33. package/dist/observability/langsmith-integration.d.ts +203 -0
  34. package/dist/observability.d.ts +196 -0
  35. package/dist/orbitals/archive/sanitize.d.ts +24 -0
  36. package/dist/orbitals/batch/batch-generator.d.ts +41 -0
  37. package/dist/orbitals/batch/concurrency.d.ts +54 -0
  38. package/dist/orbitals/batch/index.d.ts +14 -0
  39. package/dist/orbitals/batch/prompt-assembler.d.ts +92 -0
  40. package/dist/orbitals/batch/types.d.ts +103 -0
  41. package/dist/orbitals/cache/index.d.ts +11 -0
  42. package/dist/orbitals/cache/orbital-fingerprint.d.ts +37 -0
  43. package/dist/orbitals/cache/prompt-assembler.d.ts +65 -0
  44. package/dist/orbitals/cache/structural-templates.d.ts +33 -0
  45. package/dist/orbitals/combiner/index.d.ts +102 -0
  46. package/dist/orbitals/domain-language/index.d.ts +9 -0
  47. package/dist/orbitals/domain-language/prompts/index.d.ts +11 -0
  48. package/dist/orbitals/domain-language/prompts/odl-examples.d.ts +8 -0
  49. package/dist/orbitals/domain-language/prompts/odl-patterns.d.ts +8 -0
  50. package/dist/orbitals/domain-language/prompts/odl-syntax.d.ts +8 -0
  51. package/dist/orbitals/domain-language/prompts/odl-to-schema.d.ts +8 -0
  52. package/dist/orbitals/generation/index.d.ts +10 -0
  53. package/dist/orbitals/generation/orbital-generator.d.ts +120 -0
  54. package/dist/orbitals/shared/constants.d.ts +65 -0
  55. package/dist/orbitals/shared/index.d.ts +11 -0
  56. package/dist/orbitals/shared/types.d.ts +187 -0
  57. package/dist/orbitals/shared/utils.d.ts +97 -0
  58. package/dist/orchestration/complexity-classifier.d.ts +38 -0
  59. package/dist/orchestration/fixing-orchestrator.d.ts +53 -0
  60. package/dist/orchestration/index.d.ts +31 -0
  61. package/dist/orchestration/provider-router.d.ts +45 -0
  62. package/dist/{firestore-checkpointer-CkNKXoun.d.ts → persistence/firestore-checkpointer.d.ts} +13 -58
  63. package/dist/persistence/firestore-session-store.d.ts +75 -0
  64. package/dist/persistence/firestore-store.d.ts +86 -0
  65. package/dist/persistence/index.d.ts +7 -198
  66. package/dist/persistence/memory-backend.d.ts +33 -0
  67. package/dist/persistence/types.d.ts +40 -0
  68. package/dist/security/audit-log.d.ts +44 -0
  69. package/dist/state-sync.d.ts +171 -0
  70. package/dist/subagents.d.ts +38 -0
  71. package/dist/tools/combine-schemas.d.ts +154 -0
  72. package/dist/tools/composition.d.ts +119 -0
  73. package/dist/{orbital-subagent-BdFuf77p.d.ts → tools/domain-orbital.d.ts} +22 -461
  74. package/dist/tools/execute.d.ts +38 -0
  75. package/dist/tools/finish-task.d.ts +56 -0
  76. package/dist/tools/generate-schema.d.ts +53 -0
  77. package/dist/tools/github.d.ts +297 -0
  78. package/dist/tools/index.d.ts +1318 -8
  79. package/dist/tools/orbital-batch-subagent.d.ts +85 -0
  80. package/dist/tools/orbital-subagent.d.ts +454 -0
  81. package/dist/tools/orchestrated-fixing.d.ts +74 -0
  82. package/dist/tools/orchestrated-generation.d.ts +75 -0
  83. package/dist/tools/sandbox-executor.d.ts +31 -0
  84. package/dist/tools/schema-chunking.d.ts +117 -0
  85. package/dist/tools/trait-subagent.d.ts +179 -0
  86. package/dist/tools/validate-schema.d.ts +17 -0
  87. package/dist/types.d.ts +14 -17
  88. package/dist/utils/safety/capability-token.d.ts +50 -0
  89. package/dist/utils/safety/circuit-breaker.d.ts +71 -0
  90. package/dist/utils/safety/index.d.ts +19 -0
  91. package/dist/utils/safety/rate-limiter.d.ts +39 -0
  92. package/dist/utils/safety/threshold-auth.d.ts +70 -0
  93. package/dist/workspace/git-client.d.ts +51 -0
  94. package/dist/workspace/index.d.ts +29 -346
  95. package/dist/workspace/index.js +39 -0
  96. package/dist/workspace/index.js.map +1 -1
  97. package/dist/workspace/memory-files.d.ts +31 -0
  98. package/dist/workspace/sink-manager.d.ts +26 -0
  99. package/dist/workspace/sinks/firestore-sink.d.ts +41 -0
  100. package/dist/workspace/sinks/git-sink.d.ts +47 -0
  101. package/dist/workspace/sinks/index.d.ts +9 -0
  102. package/dist/workspace/templates.d.ts +32 -0
  103. package/dist/workspace/types.d.ts +86 -0
  104. package/dist/workspace/workspace-manager.d.ts +57 -0
  105. package/package.json +12 -10
  106. package/dist/index-DW3F-Ihx.d.ts +0 -2501
  107. package/dist/index-DZn69no8.d.ts +0 -1014
package/dist/index.d.ts CHANGED
@@ -1,1679 +1,59 @@
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-CXrq-fts.js';
4
- import { O as OrbitalUnit, a as OrbitalGenerationOptions$1, b as OrbitalGenerationResult$1, A as AuditLog } from './index-DW3F-Ihx.js';
5
- export { c as AuditEntry, T as TraitCompleteCallback, d as TraitEventCallback, e as TraitSpec, f as TraitSubagentToolOptions, g as createAgentTools, h as createApplyChunkTool, i as createCombineSchemasTool, j as createExecuteTool, k as createExtractChunkTool, l as createFinishTaskTool, m as createGenerateSchemaTool, n as createQuerySchemaStructureTool, o as createSchemaChunkingTools, p as createTraitEventWrapper, q as createTraitSubagentTool, r as createValidateSchemaTool, v as validateCommandPaths } from './index-DW3F-Ihx.js';
6
- import { DomainContext, OrbitalSchema, Orbital } from '@almadar/core/types';
7
- export { DomainDocument, DomainToSchemaResult, ParseError, SchemaToDomainResult, SectionMapping, applySectionUpdate, convertDomainToSchema, convertSchemaToDomain, deleteSection } from '@almadar/core/domain-language';
8
- import { LLMClient } from '@almadar/llm';
9
- import { U as UserPreference, M as MemoryManager, G as GenerationSession } from './index-DZn69no8.js';
10
- export { A as ActionGate, C as CRITICAL_COMMAND_PATTERNS, a as CheckpointRecord, b as ContextCompactionConfig, D as DEFAULT_COMPACTION_CONFIG, E as EVENT_BUDGETS, I as InterruptRecord, c as MemoryManagerOptions, d as MemoryOrbitalSchema, P as PatternAffinity, e as ProjectContext, S as SessionManager, f as SessionManagerOptions, g as Skill, h as SkillAgentOptions, i as SkillAgentResult, j as SkillLoader, k as SkillMeta, l as SkillRefLoader, T as TOOL_GATES, m as ToolApprovalPreference, n as ToolTelemetry, o as UserFeedback, W as WorkflowToolWrapper, p as WorkflowToolWrapperOptions, q as classifyCommand, r as createEvalWorkflowWrapper, s as createSkillAgent, t as createSummaryPrompt, u as createWorkflowToolWrapper, v as estimateTokens, w as getBudgetWarningMessage, x as getEventBudget, y as getInterruptConfig, z as needsCompaction, B as resumeSkillAgent } from './index-DZn69no8.js';
11
- import { S as SessionMetadata } from './firestore-checkpointer-CkNKXoun.js';
12
- export { F as FirestoreCheckpointer, a as FirestoreCheckpointerOptions, b as FirestoreDb, c as FirestoreTimestamp, P as PersistenceMode, d as Session, e as SessionRecord } from './firestore-checkpointer-CkNKXoun.js';
13
- export { FirestoreSessionStore, FirestoreSessionStoreOptions, FirestoreStore, FirestoreStoreOptions, MemorySessionBackend } from './persistence/index.js';
14
- export { RawAgentEvent, extractFileOperation, extractInterruptData, hasInterrupt, isFileOperation, isTodoUpdate, transformAgentEvent, transformAgentEventMulti } from './event-transformer/index.js';
15
- import { EventEmitter } from 'events';
16
- import { Checkpoint } from '@langchain/langgraph-checkpoint';
17
- import { OrbitalDefinition } from '@almadar/core';
18
- export { FileMeta, FirestoreSink, FirestoreSinkConfig, GitClient, GitLogEntry, GitSink, GitStatus, MemorySnapshot, SinkManager, SinkResult, WORKSPACE_LAYOUT, WorkspaceConfig, WorkspaceManager, WorkspaceSink, createProjectOrbTemplate, createSchemaOrbTemplate, createUserOrbTemplate, parseOrb, readOrb, readOrbInstances, serializeOrb, writeOrb, writeOrbInstances } from './workspace/index.js';
19
- export { Command } from '@langchain/langgraph';
20
- export { a as DomainOrbitalCompleteCallback, D 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-BdFuf77p.js';
21
- import 'zod';
22
- import '@langchain/core/tools';
23
- import '@langchain/core/messages';
24
- import '@langchain/core/runnables';
25
-
26
1
  /**
27
- * Orbital Combiner
28
- *
29
- * Deterministically combines multiple Orbitals into a single OrbitalSchema.
30
- * This removes the need for LLM involvement in the combining step.
31
- *
32
- * All UI is rendered via render_ui effects from traits (no static sections).
33
- *
34
- * NOTE: Validation is handled externally via `orbital validate` CLI.
35
- * The combiner only assembles schemas - it does not validate them.
36
- *
37
- * @packageDocumentation
38
- */
39
-
40
- interface OrbitalSchemaValidationResult {
41
- valid: boolean;
42
- errors: Array<{
43
- code: string;
44
- message: string;
45
- path?: string;
46
- }>;
47
- warnings: Array<{
48
- code: string;
49
- message: string;
50
- path?: string;
51
- }>;
52
- }
53
- type FullOrbitalUnit = Orbital;
54
- interface CombinerOptions {
55
- /** Application name */
56
- name: string;
57
- /** Optional description */
58
- description?: string;
59
- /** Schema version */
60
- version?: string;
61
- /** Domain context */
62
- domain?: DomainContext;
63
- /** Whether to run validation (default: true) */
64
- validate?: boolean;
65
- /** Global theme */
66
- theme?: string;
67
- /** Default route (first page if not specified) */
68
- defaultRoute?: string;
69
- }
70
- interface CombinerResult {
71
- /** Whether combining succeeded */
72
- success: boolean;
73
- /** The combined OrbitalSchema (if successful) */
74
- schema?: OrbitalSchema;
75
- /** Validation result (if validation was run) */
76
- validation?: OrbitalSchemaValidationResult;
77
- /** Error message (if failed) */
78
- error?: string;
79
- /** Statistics about the combining */
80
- stats: {
81
- totalOrbitals: number;
82
- totalEntities: number;
83
- totalPages: number;
84
- totalTraits: number;
85
- };
86
- }
87
- /**
88
- * Combine multiple Orbitals into a single OrbitalSchema.
89
- *
90
- * This function performs deterministic merging:
91
- * 1. Builds an OrbitalSchema from the Orbitals
92
- * 2. Optionally runs validation
93
- *
94
- * Note: All UI is rendered via render_ui effects from traits.
95
- *
96
- * @example
97
- * ```typescript
98
- * const result = combineOrbitals([taskOrbital, userOrbital], {
99
- * name: 'My App',
100
- * validate: true,
101
- * });
102
- *
103
- * if (result.success) {
104
- * // Write schema to file
105
- * await fs.writeFile('schema.json', JSON.stringify(result.schema, null, 2));
106
- * } else {
107
- * console.error(result.error);
108
- * console.error(result.validation?.errors);
109
- * }
110
- * ```
111
- */
112
- declare function combineOrbitals(orbitals: FullOrbitalUnit[], options: CombinerOptions): CombinerResult;
113
- /**
114
- * Combine orbitals and return only the schema (throws on error).
115
- * Use this when you want a simple API and will handle errors upstream.
116
- */
117
- declare function combineOrbitalsToSchema(orbitals: FullOrbitalUnit[], options: CombinerOptions): OrbitalSchema;
118
- /**
119
- * Estimate the combination complexity (for progress indication).
120
- */
121
- declare function estimateCombineComplexity(orbitals: FullOrbitalUnit[]): {
122
- entities: number;
123
- pages: number;
124
- traits: number;
125
- totalSections: number;
126
- };
127
-
128
- /**
129
- * Orbital Generator
130
- *
131
- * Provides utilities for generating FullOrbitalUnit definitions from
132
- * lightweight OrbitalUnit inputs. Designed for SUBAGENT use where each
133
- * orbital is generated separately for better caching.
134
- *
135
- * ## Subagent Caching Pattern
136
- *
137
- * When generating multiple orbitals in a subagent pattern:
138
- * 1. Main agent decomposes request → OrbitalUnit[]
139
- * 2. For each orbital, subagent calls generateFullOrbital()
140
- * 3. Each subagent call uses the SAME cached system prompt blocks
141
- * 4. Anthropic caches at request level → subsequent calls get 90% discount
142
- *
143
- * This is MORE efficient than batch generation because:
144
- * - System prompt is cached and reused across subagent calls
145
- * - Template guidance is cached per fingerprint
146
- * - Only the orbital-specific content varies
147
- *
148
- * @packageDocumentation
149
- */
150
-
151
- /**
152
- * Extended options for single orbital generation.
153
- * @deprecated Use shared OrbitalGenerationOptions instead
154
- */
155
- interface OrbitalGenerationOptions extends OrbitalGenerationOptions$1 {
156
- }
157
- /**
158
- * Extended result for single orbital generation.
159
- * @deprecated Use shared OrbitalGenerationResult instead
160
- */
161
- interface OrbitalGenerationResult extends OrbitalGenerationResult$1 {
162
- }
163
- /**
164
- * Generate a full orbital unit from a lightweight orbital input.
165
- *
166
- * DESIGNED FOR SUBAGENT USE: Call this once per orbital in separate
167
- * subagent invocations. Caching works across calls because:
168
- * - System prompt blocks are marked as cacheable
169
- * - Anthropic caches at the request level
170
- * - Subsequent calls with same system prompt get cache hits
171
- *
172
- * @example
173
- * ```typescript
174
- * // In subagent for each orbital:
175
- * const result = await generateFullOrbital(client, orbitalUnit, { validate: true });
176
- * // First call: Cache WRITE: 3500 tokens
177
- * // Second call: Cache HIT: 3500 tokens (90% discount!)
178
- * ```
179
- */
180
- declare function generateFullOrbital(client: LLMClient, orbital: OrbitalUnit, options?: OrbitalGenerationOptions): Promise<OrbitalGenerationResult>;
181
- /**
182
- * Estimate cache savings for a set of orbitals.
183
- *
184
- * Use this to predict how much caching will help for a decomposition.
185
- */
186
- declare function estimateCacheSavings(orbitals: OrbitalUnit[]): {
187
- totalOrbitals: number;
188
- uniqueFingerprints: number;
189
- estimatedCacheHits: number;
190
- estimatedSavingsPercent: number;
191
- };
192
-
193
- /**
194
- * KFlow DeepAgent Subagents
195
- *
196
- * Specialized subagents for complex schema generation tasks.
197
- * These are spawned via the `task()` built-in tool.
198
- *
199
- * Uses @almadar/skills for schema reference documentation.
200
- *
201
- * @packageDocumentation
202
- */
203
-
204
- /**
205
- * Create the Schema Generator Subagent configuration.
206
- *
207
- * Focused agent for generating KFlow schemas from requirements.
208
- * Writes schema to file and verifies it exists.
209
- */
210
- declare function createSchemaGeneratorSubagent(): SubAgent;
211
- /**
212
- * Create the Error Fixer Subagent configuration.
213
- *
214
- * Focused agent for fixing validation and compilation errors.
215
- */
216
- declare function createErrorFixerSubagent(): SubAgent;
217
- /**
218
- * Create the Test Analyzer Subagent configuration.
219
- *
220
- * Focused agent for analyzing test failures and suggesting fixes.
221
- */
222
- declare function createTestAnalyzerSubagent(): SubAgent;
223
- /**
224
- * Create all subagent configurations.
225
- */
226
- declare function createSubagents(): SubAgent[];
227
- /**
228
- * Create subagent configs as a record for easy lookup.
229
- */
230
- declare function createSubagentConfigs(): Record<string, SubAgent>;
231
-
232
- /**
233
- * DeepAgent SSE Event Types
234
- *
235
- * Type definitions for Server-Sent Events from the DeepAgent streaming endpoint.
236
- * Use these types for client-side consumption of /deepagent/generate-stream.
237
- *
238
- * @packageDocumentation
239
- */
240
- /**
241
- * Initial event sent when streaming begins.
242
- */
243
- interface DeepAgentStartEvent {
244
- type: 'start';
245
- sessionId: string;
246
- }
247
- /**
248
- * Agent execution event (tool calls, messages, etc.).
249
- */
250
- interface DeepAgentExecutionEvent {
251
- type: 'event';
252
- node?: string;
253
- toolCall?: {
254
- name: string;
255
- args: Record<string, unknown>;
256
- };
257
- toolResult?: {
258
- name: string;
259
- result: unknown;
260
- };
261
- message?: {
262
- role: 'assistant' | 'user' | 'system';
263
- content: string;
264
- };
265
- [key: string]: unknown;
266
- }
267
- /**
268
- * Schema generated event.
269
- */
270
- interface DeepAgentSchemaEvent {
271
- type: 'schema';
272
- schema: Record<string, unknown>;
273
- }
274
- /**
275
- * Completion event sent when generation finishes successfully.
276
- */
277
- interface DeepAgentCompleteEvent {
278
- type: 'complete';
279
- sessionId: string;
280
- appCompiled: boolean;
281
- }
282
- /**
283
- * Error event sent when generation fails.
284
- */
285
- interface DeepAgentErrorEvent {
286
- type: 'error';
287
- error: string;
288
- }
289
- /**
290
- * Union of all possible DeepAgent SSE events.
291
- */
292
- type DeepAgentEvent = DeepAgentStartEvent | DeepAgentExecutionEvent | DeepAgentSchemaEvent | DeepAgentCompleteEvent | DeepAgentErrorEvent;
293
- /**
294
- * Parse an SSE data line into a DeepAgentEvent.
295
- */
296
- declare function parseDeepAgentEvent(data: string): DeepAgentEvent;
297
- /**
298
- * Type guard for start events.
299
- */
300
- declare function isStartEvent(event: DeepAgentEvent): event is DeepAgentStartEvent;
301
- /**
302
- * Type guard for execution events.
303
- */
304
- declare function isExecutionEvent(event: DeepAgentEvent): event is DeepAgentExecutionEvent;
305
- /**
306
- * Type guard for schema events.
307
- */
308
- declare function isSchemaEvent(event: DeepAgentEvent): event is DeepAgentSchemaEvent;
309
- /**
310
- * Type guard for complete events.
311
- */
312
- declare function isCompleteEvent(event: DeepAgentEvent): event is DeepAgentCompleteEvent;
313
- /**
314
- * Type guard for error events.
315
- */
316
- declare function isErrorEvent(event: DeepAgentEvent): event is DeepAgentErrorEvent;
317
-
318
- /**
319
- * Metrics Collection for DeepAgent Evaluation
320
- *
321
- * Tracks success rates, iteration counts, token usage, and timing
322
- * for agent generation tests.
323
- *
324
- * @packageDocumentation
325
- */
326
- /**
327
- * Metrics for a single generation attempt.
328
- */
329
- interface GenerationMetrics {
330
- testName: string;
331
- complexity: 'simple' | 'medium' | 'complex';
332
- success: boolean;
333
- iterations: number;
334
- timeMs: number;
335
- tokenUsage?: {
336
- input: number;
337
- output: number;
338
- total: number;
339
- };
340
- error?: string;
341
- timestamp?: number;
342
- }
343
- /**
344
- * Aggregated metrics summary.
345
- */
346
- interface MetricsSummary {
347
- total: number;
348
- passed: number;
349
- failed: number;
350
- successRate: number;
351
- avgIterations: number;
352
- avgTimeMs: number;
353
- avgTokens: number;
354
- byComplexity: {
355
- simple: {
356
- total: number;
357
- passed: number;
358
- successRate: number;
359
- };
360
- medium: {
361
- total: number;
362
- passed: number;
363
- successRate: number;
364
- };
365
- complex: {
366
- total: number;
367
- passed: number;
368
- successRate: number;
369
- };
370
- };
371
- }
372
- /**
373
- * Collects and aggregates generation metrics.
374
- */
375
- declare class MetricsCollector {
376
- private metrics;
377
- record(metrics: GenerationMetrics): void;
378
- getAll(): GenerationMetrics[];
379
- getSummary(): MetricsSummary;
380
- private getComplexitySummary;
381
- getFailures(): GenerationMetrics[];
382
- getMultiIterationTests(): GenerationMetrics[];
383
- clear(): void;
384
- saveToFile(filePath: string): Promise<void>;
385
- loadFromFile(filePath: string): Promise<void>;
386
- }
387
- /**
388
- * Format metrics summary as a readable string.
389
- */
390
- declare function formatSummary(summary: MetricsSummary): string;
391
- /**
392
- * Analyze failure patterns to suggest prompt improvements.
393
- */
394
- declare function analyzeFailures(failures: GenerationMetrics[]): string[];
395
-
396
- /**
397
- * Preference Learner
398
- *
399
- * Uses LLM to infer user preferences from generation sessions.
400
- * Leverages @almadar/llm for structured output.
401
- *
402
- * @packageDocumentation
403
- */
404
-
405
- interface PreferenceLearnerOptions {
406
- /** LLM client for inference */
407
- llmClient?: LLMClient;
408
- /** Memory manager for persistence */
409
- memoryManager: MemoryManager;
410
- /** Confidence threshold for auto-accepting preferences */
411
- confidenceThreshold?: number;
412
- }
413
- interface InferredPreference {
414
- /** The preference field being inferred */
415
- field: keyof Omit<UserPreference, 'id' | 'userId' | 'learnedAt'>;
416
- /** The inferred value */
417
- value: unknown;
418
- /** Confidence level (0-1) */
419
- confidence: number;
420
- /** Explanation of why this was inferred */
421
- reasoning: string;
422
- }
423
- interface PreferenceAnalysis {
424
- /** List of inferred preferences */
425
- inferences: InferredPreference[];
426
- /** Whether the inference is high confidence */
427
- isHighConfidence: boolean;
428
- }
429
- declare class PreferenceLearner {
430
- private llmClient;
431
- private memoryManager;
432
- private confidenceThreshold;
433
- constructor(options: PreferenceLearnerOptions);
434
- /**
435
- * Analyze a session and infer user preferences
436
- */
437
- analyzeSession(session: GenerationSession): Promise<PreferenceAnalysis>;
438
- /**
439
- * Learn from a session and update preferences if confidence is high
440
- */
441
- learnFromSession(session: GenerationSession): Promise<UserPreference | null>;
442
- /**
443
- * Batch learn from multiple sessions
444
- */
445
- batchLearn(sessions: GenerationSession[]): Promise<UserPreference | null>;
446
- private buildAnalysisPrompt;
447
- private buildAggregatePrompt;
448
- private parseAnalysisResponse;
449
- private isValidNamingConvention;
450
- private isValidValidationStyle;
451
- }
452
- declare function createPreferenceLearner(options: PreferenceLearnerOptions): PreferenceLearner;
453
-
454
- /**
455
- * Agentic Search - GAP-006
456
- *
457
- * Reasoning-based search through memory orbitals.
458
- * Unlike RAG (vector similarity), this uses agent traversal with understanding
459
- * of state transitions, patterns, and temporal relationships.
460
- *
461
- * @packageDocumentation
462
- */
463
-
464
- /**
465
- * Search strategy for agentic search
466
- */
467
- type SearchStrategy = 'temporal' | 'semantic' | 'pattern' | 'hybrid';
468
- /**
469
- * Search parameters
470
- */
471
- interface AgenticSearchParams {
472
- /** User to search memory for */
473
- userId: string;
474
- /** Natural language query */
475
- query: string;
476
- /** Search strategy */
477
- strategy?: SearchStrategy;
478
- /** Maximum search depth (levels of traversal) */
479
- depth?: number;
480
- /** App/project context to filter by */
481
- appId?: string;
482
- /** Maximum results to return */
483
- limit?: number;
484
- }
485
- /**
486
- * Search result with relevance score
487
- */
488
- interface SearchResult {
489
- /** Type of memory found */
490
- type: 'preference' | 'session' | 'project' | 'interrupt' | 'checkpoint' | 'pattern';
491
- /** The actual data */
492
- data: unknown;
493
- /** Relevance score (0-1) */
494
- relevance: number;
495
- /** Why this result matched */
496
- reasoning: string;
497
- /** Source collection */
498
- source: string;
499
- /** Timestamp for temporal sorting */
500
- timestamp?: Date;
501
- }
502
- /**
503
- * Search result with aggregated insights
504
- */
505
- interface AgenticSearchResponse {
506
- /** Individual search results */
507
- results: SearchResult[];
508
- /** Aggregated insights from results */
509
- insights: {
510
- /** Summary of what was found */
511
- summary: string;
512
- /** Common patterns identified */
513
- patterns: string[];
514
- /** Temporal trends */
515
- trends: string[];
516
- /** Suggested next actions */
517
- suggestions: string[];
518
- };
519
- /** Search metadata */
520
- metadata: {
521
- strategy: SearchStrategy;
522
- depth: number;
523
- duration: number;
524
- totalResults: number;
525
- };
526
- }
527
- declare class AgenticSearchEngine {
528
- private memoryManager;
529
- constructor(memoryManager: MemoryManager);
530
- /**
531
- * Perform agentic search through memory
532
- */
533
- search(params: AgenticSearchParams): Promise<AgenticSearchResponse>;
534
- /**
535
- * Temporal search - "What did I do last week?"
536
- * Navigates memory by time relationships
537
- */
538
- private temporalSearch;
539
- /**
540
- * Semantic search - "How did I handle user roles?"
541
- * Reasoning-based understanding of structure
542
- */
543
- private semanticSearch;
544
- /**
545
- * Pattern search - "Show me all list views I've built"
546
- * Searches for specific patterns and effects
547
- */
548
- private patternSearch;
549
- /**
550
- * Hybrid search - combines all strategies
551
- */
552
- private hybridSearch;
553
- /**
554
- * Extract semantic concepts from query
555
- */
556
- private extractConcepts;
557
- /**
558
- * Extract potential entity names from query
559
- */
560
- private extractEntityNames;
561
- /**
562
- * Generate insights from search results
563
- */
564
- private generateInsights;
565
- }
566
- /**
567
- * Create an agentic search engine
568
- */
569
- declare function createAgenticSearchEngine(memoryManager: MemoryManager): AgenticSearchEngine;
570
-
571
- /**
572
- * Observability - GAP-008
573
- *
574
- * Comprehensive observability layer for DeepAgent including:
575
- * - Event tracking
576
- * - Session metrics
577
- * - Performance monitoring
578
- * - Health checks
579
- *
580
- * @packageDocumentation
581
- */
582
- /**
583
- * Observable event types
584
- */
585
- type ObservableEventType = 'session_start' | 'session_end' | 'tool_call' | 'tool_result' | 'interrupt' | 'checkpoint_save' | 'checkpoint_restore' | 'error' | 'llm_call' | 'memory_sync';
586
- /**
587
- * Observable event
588
- */
589
- interface ObservableEvent {
590
- /** Event type */
591
- type: ObservableEventType;
592
- /** Timestamp */
593
- timestamp: number;
594
- /** Session/thread ID */
595
- sessionId: string;
596
- /** User ID */
597
- userId?: string;
598
- /** Event payload */
599
- payload: Record<string, unknown>;
600
- /** Duration in ms (if applicable) */
601
- duration?: number;
602
- /** Error information */
603
- error?: {
604
- message: string;
605
- code?: string;
606
- stack?: string;
607
- };
608
- }
609
- /**
610
- * Session telemetry
611
- */
612
- interface SessionTelemetry {
613
- /** Session ID */
614
- sessionId: string;
615
- /** User ID */
616
- userId?: string;
617
- /** Session start time */
618
- startedAt: number;
619
- /** Session end time */
620
- endedAt?: number;
621
- /** Number of tool calls */
622
- toolCallCount: number;
623
- /** Number of LLM calls */
624
- llmCallCount: number;
625
- /** Number of interrupts */
626
- interruptCount: number;
627
- /** Number of checkpoints */
628
- checkpointCount: number;
629
- /** Total tokens used */
630
- totalTokens: number;
631
- /** Errors encountered */
632
- errors: Array<{
633
- timestamp: number;
634
- message: string;
635
- type: string;
636
- }>;
637
- /** Final status */
638
- status: 'running' | 'completed' | 'failed' | 'interrupted';
639
- }
640
- /**
641
- * Performance snapshot
642
- */
643
- interface PerformanceSnapshot {
644
- /** Timestamp */
645
- timestamp: number;
646
- /** Active sessions */
647
- activeSessions: number;
648
- /** Total sessions (all time) */
649
- totalSessions: number;
650
- /** Average session duration */
651
- avgSessionDuration: number;
652
- /** Success rate (last 24h) */
653
- successRate24h: number;
654
- /** Error rate (last 24h) */
655
- errorRate24h: number;
656
- /** Average tokens per session */
657
- avgTokensPerSession: number;
658
- }
659
- /**
660
- * Health check result
661
- */
662
- interface HealthCheckResult {
663
- /** Component name */
664
- component: string;
665
- /** Health status */
666
- status: 'healthy' | 'degraded' | 'unhealthy';
667
- /** Response time in ms */
668
- responseTime: number;
669
- /** Last checked timestamp */
670
- checkedAt: number;
671
- /** Error message if unhealthy */
672
- error?: string;
673
- }
674
- declare class ObservabilityCollector {
675
- private events;
676
- private sessions;
677
- private maxEvents;
678
- constructor(options?: {
679
- maxEvents?: number;
680
- });
681
- /**
682
- * Record an observable event
683
- */
684
- recordEvent(event: Omit<ObservableEvent, 'timestamp'>): void;
685
- /**
686
- * Start session tracking
687
- */
688
- startSession(sessionId: string, userId?: string): void;
689
- /**
690
- * End session tracking
691
- */
692
- endSession(sessionId: string, status?: SessionTelemetry['status']): void;
693
- /**
694
- * Record tool call
695
- */
696
- recordToolCall(sessionId: string, toolName: string, args: Record<string, unknown>, duration?: number): void;
697
- /**
698
- * Record LLM call
699
- */
700
- recordLLMCall(sessionId: string, model: string, tokens: {
701
- input: number;
702
- output: number;
703
- }, duration?: number): void;
704
- /**
705
- * Record error
706
- */
707
- recordError(sessionId: string, error: Error, context?: Record<string, unknown>): void;
708
- /**
709
- * Get events by type
710
- */
711
- getEvents(type?: ObservableEventType, sessionId?: string): ObservableEvent[];
712
- /**
713
- * Get session telemetry
714
- */
715
- getSessionTelemetry(sessionId: string): SessionTelemetry | undefined;
716
- /**
717
- * Get all active sessions
718
- */
719
- getActiveSessions(): SessionTelemetry[];
720
- /**
721
- * Get performance snapshot
722
- */
723
- getPerformanceSnapshot(): PerformanceSnapshot;
724
- /**
725
- * Perform health check
726
- */
727
- healthCheck(): Promise<HealthCheckResult[]>;
728
- /**
729
- * Export metrics for external systems
730
- */
731
- exportMetrics(): {
732
- events: ObservableEvent[];
733
- sessions: SessionTelemetry[];
734
- snapshot: PerformanceSnapshot;
735
- health: HealthCheckResult[];
736
- };
737
- /**
738
- * Clear all data
739
- */
740
- clear(): void;
741
- private updateSessionTelemetry;
742
- }
743
- /**
744
- * Get or create global observability collector
745
- */
746
- declare function getObservabilityCollector(): ObservabilityCollector;
747
- /**
748
- * Reset global observability collector
749
- */
750
- declare function resetObservabilityCollector(): void;
751
- /**
752
- * Record event to global collector
753
- */
754
- declare function recordEvent(event: Omit<ObservableEvent, 'timestamp'>): void;
755
- /**
756
- * Start session in global collector
757
- */
758
- declare function startObservabilitySession(sessionId: string, userId?: string): void;
759
- /**
760
- * End session in global collector
761
- */
762
- declare function endObservabilitySession(sessionId: string, status?: SessionTelemetry['status']): void;
763
- /**
764
- * Get performance snapshot from global collector
765
- */
766
- declare function getPerformanceSnapshot(): PerformanceSnapshot;
767
-
768
- /**
769
- * Multi-User Support - GAP-009
770
- *
771
- * Provides proper user isolation and session scoping for multi-user environments.
772
- * Ensures users can only access their own sessions, memory, and data.
773
- *
774
- * @packageDocumentation
775
- */
776
-
777
- /**
778
- * User context for multi-user operations
779
- */
780
- interface UserContext {
781
- /** User ID */
782
- userId: string;
783
- /** Organization/tenant ID (for multi-tenant) */
784
- orgId?: string;
785
- /** User roles/permissions */
786
- roles?: string[];
787
- /** Session ID scope (optional) */
788
- sessionScope?: string[];
789
- }
790
- /**
791
- * Scoped session metadata with user ownership
792
- */
793
- interface ScopedSessionMetadata extends SessionMetadata {
794
- /** Owning user ID */
795
- userId: string;
796
- /** Organization ID */
797
- orgId?: string;
798
- /** Created by (for audit) */
799
- createdBy: string;
800
- /** Last accessed by */
801
- lastAccessedBy?: string;
802
- /** Access control list */
803
- acl?: {
804
- /** Users who can read this session */
805
- readers?: string[];
806
- /** Users who can write/modify */
807
- writers?: string[];
808
- /** Publicly accessible */
809
- isPublic?: boolean;
810
- };
811
- }
812
- /**
813
- * Access check result
814
- */
815
- interface AccessCheckResult {
816
- /** Whether access is granted */
817
- allowed: boolean;
818
- /** Reason if denied */
819
- reason?: string;
820
- /** Required permission level */
821
- requiredRole?: string;
822
- }
823
- /**
824
- * User session stats
825
- */
826
- interface UserSessionStats {
827
- /** User ID */
828
- userId: string;
829
- /** Total sessions */
830
- totalSessions: number;
831
- /** Active sessions */
832
- activeSessions: number;
833
- /** Completed sessions */
834
- completedSessions: number;
835
- /** Sessions by skill */
836
- sessionsBySkill: Record<string, number>;
837
- /** Last activity timestamp */
838
- lastActivityAt?: number;
839
- }
840
- declare class MultiUserManager {
841
- private sessionOwnership;
842
- private userSessions;
843
- /**
844
- * Check if a user owns a session
845
- */
846
- isSessionOwner(threadId: string, userId: string): boolean;
847
- /**
848
- * Check if a user can access a session
849
- */
850
- canAccessSession(threadId: string, userContext: UserContext): AccessCheckResult;
851
- /**
852
- * Assign session ownership
853
- */
854
- assignSessionOwnership(threadId: string, userId: string): void;
855
- /**
856
- * Get all sessions for a user
857
- */
858
- getUserSessions(userId: string): string[];
859
- /**
860
- * Get session owner
861
- */
862
- getSessionOwner(threadId: string): string | undefined;
863
- /**
864
- * Remove session ownership
865
- */
866
- removeSession(threadId: string): void;
867
- /**
868
- * Check if user has any sessions
869
- */
870
- hasSessions(userId: string): boolean;
871
- /**
872
- * Get user session count
873
- */
874
- getSessionCount(userId: string): number;
875
- /**
876
- * Transfer session ownership
877
- */
878
- transferOwnership(threadId: string, fromUserId: string, toUserId: string): AccessCheckResult;
879
- /**
880
- * Share session with another user
881
- */
882
- shareSession(threadId: string, ownerId: string, targetUserId: string, permission?: 'read' | 'write'): AccessCheckResult;
883
- /**
884
- * Get all user IDs with sessions
885
- */
886
- getAllUsers(): string[];
887
- /**
888
- * Clear all data (for testing)
889
- */
890
- clear(): void;
891
- /**
892
- * Create scoped session metadata
893
- */
894
- createScopedMetadata(metadata: SessionMetadata, userContext: UserContext): ScopedSessionMetadata;
895
- /**
896
- * Validate user context
897
- */
898
- validateUserContext(userContext: unknown): userContext is UserContext;
899
- }
900
- /**
901
- * Get or create global multi-user manager
902
- */
903
- declare function getMultiUserManager(): MultiUserManager;
904
- /**
905
- * Reset global multi-user manager
906
- */
907
- declare function resetMultiUserManager(): void;
908
- /**
909
- * Create user context from request
910
- */
911
- declare function createUserContext(userId: string, options?: {
912
- orgId?: string;
913
- roles?: string[];
914
- }): UserContext;
915
- /**
916
- * Check if user is admin
917
- */
918
- declare function isAdmin(userContext: UserContext): boolean;
919
- /**
920
- * Require ownership or throw
921
- */
922
- declare function requireOwnership(threadId: string, userContext: UserContext, manager?: MultiUserManager): void;
923
-
924
- /**
925
- * State Synchronization Support - GAP-010
926
- *
927
- * Provides agent-side support for real-time state synchronization.
928
- * The actual transport (WebSocket/SSE) is handled by @almadar/server.
929
- *
930
- * This module provides:
931
- * - State change notifications
932
- * - Conflict resolution utilities
933
- * - State serialization for sync
934
- * - Event emitters for server integration
935
- *
936
- * @packageDocumentation
937
- */
938
-
939
- /**
940
- * State change event types
941
- */
942
- type StateChangeType = 'checkpoint_created' | 'checkpoint_updated' | 'session_started' | 'session_ended' | 'tool_executed' | 'memory_updated' | 'interrupt_triggered' | 'interrupt_resolved';
943
- /**
944
- * State change event
945
- */
946
- interface StateChangeEvent {
947
- /** Change type */
948
- type: StateChangeType;
949
- /** Thread/session ID */
950
- threadId: string;
951
- /** User ID */
952
- userId?: string;
953
- /** Timestamp */
954
- timestamp: number;
955
- /** Change payload */
956
- payload: Record<string, unknown>;
957
- /** Version vector for conflict resolution */
958
- version: VersionVector;
959
- /** Source client ID */
960
- sourceClientId?: string;
961
- }
962
- /**
963
- * Version vector for conflict resolution
964
- */
965
- interface VersionVector {
966
- /** Logical timestamp */
967
- timestamp: number;
968
- /** Sequence number */
969
- sequence: number;
970
- /** Node/client ID */
971
- nodeId: string;
972
- }
973
- /**
974
- * Sync state snapshot
975
- */
976
- interface StateSyncSnapshot {
977
- /** Thread ID */
978
- threadId: string;
979
- /** Current checkpoint */
980
- checkpoint?: Checkpoint;
981
- /** Session metadata */
982
- sessionMetadata?: Record<string, unknown>;
983
- /** Memory state */
984
- memoryState?: Record<string, unknown>;
985
- /** Version vector */
986
- version: VersionVector;
987
- /** Last updated */
988
- lastUpdated: number;
989
- }
990
- /**
991
- * Conflict resolution result
992
- */
993
- interface ConflictResolution {
994
- /** Whether conflict was resolved */
995
- resolved: boolean;
996
- /** Winning state if resolved */
997
- winningState?: StateSyncSnapshot;
998
- /** Conflicting changes if not resolved */
999
- conflicts?: Array<{
1000
- clientA: StateChangeEvent;
1001
- clientB: StateChangeEvent;
1002
- }>;
1003
- /** Resolution strategy used */
1004
- strategy: 'last_write_wins' | 'merge' | 'manual';
1005
- }
1006
- /**
1007
- * Sync configuration
1008
- */
1009
- interface StateSyncConfig {
1010
- /** Enable sync */
1011
- enabled: boolean;
1012
- /** Conflict resolution strategy */
1013
- conflictStrategy: 'last_write_wins' | 'merge' | 'manual';
1014
- /** Throttle interval (ms) */
1015
- throttleInterval: number;
1016
- /** Max retry attempts */
1017
- maxRetries: number;
1018
- /** Client ID */
1019
- clientId: string;
1020
- }
1021
- declare class StateSyncManager extends EventEmitter {
1022
- private config;
1023
- private sequenceNumber;
1024
- private pendingChanges;
1025
- private throttleTimer;
1026
- constructor(config?: Partial<StateSyncConfig>);
1027
- /**
1028
- * Notify that state has changed (called by agent internals)
1029
- */
1030
- notifyStateChange(type: StateChangeType, threadId: string, payload: Record<string, unknown>, userId?: string): void;
1031
- /**
1032
- * Receive state change from server (called by server transport)
1033
- */
1034
- receiveRemoteChange(event: StateChangeEvent): void;
1035
- /**
1036
- * Create sync snapshot for current state
1037
- */
1038
- createSnapshot(threadId: string, state: {
1039
- checkpoint?: Checkpoint;
1040
- sessionMetadata?: Record<string, unknown>;
1041
- memoryState?: Record<string, unknown>;
1042
- }): StateSyncSnapshot;
1043
- /**
1044
- * Compare two version vectors
1045
- * Returns: -1 if a < b, 0 if concurrent/equal, 1 if a > b
1046
- */
1047
- compareVersions(a: VersionVector, b: VersionVector): number;
1048
- /**
1049
- * Check if there are pending changes to sync
1050
- */
1051
- hasPendingChanges(): boolean;
1052
- /**
1053
- * Get and clear pending changes
1054
- */
1055
- flushPendingChanges(): StateChangeEvent[];
1056
- /**
1057
- * Get sync configuration
1058
- */
1059
- getConfig(): StateSyncConfig;
1060
- /**
1061
- * Update sync configuration
1062
- */
1063
- updateConfig(config: Partial<StateSyncConfig>): void;
1064
- /**
1065
- * Dispose resources
1066
- */
1067
- dispose(): void;
1068
- private generateClientId;
1069
- private createVersionVector;
1070
- private scheduleSync;
1071
- private findConflicts;
1072
- private resolveConflicts;
1073
- }
1074
- /**
1075
- * Get or create global state sync manager
1076
- */
1077
- declare function getStateSyncManager(config?: Partial<StateSyncConfig>): StateSyncManager;
1078
- /**
1079
- * Reset global state sync manager
1080
- */
1081
- declare function resetStateSyncManager(): void;
1082
- /**
1083
- * Create a synchronized wrapper for session operations
1084
- */
1085
- declare function withSync<T extends (...args: unknown[]) => unknown>(fn: T, syncManager: StateSyncManager, options: {
1086
- threadId: string;
1087
- type: StateChangeType;
1088
- getPayload: (...args: unknown[]) => Record<string, unknown>;
1089
- }): T;
1090
- /**
1091
- * Debounce sync notifications
1092
- */
1093
- declare function debounceSync(syncManager: StateSyncManager, delay?: number): (type: StateChangeType, threadId: string, payload: Record<string, unknown>) => void;
1094
-
1095
- /**
1096
- * Online Evaluations - Phase 3.2a: Simple Sampling
1097
- *
1098
- * 10% traffic sampling with async validation and basic alerting.
1099
- * Non-blocking - runs in background without affecting user response.
1100
- *
1101
- * @packageDocumentation
1102
- */
1103
-
1104
- interface SamplingConfig {
1105
- /** Sampling rate (0.0 - 1.0) */
1106
- sampleRate: number;
1107
- /** Async queue size */
1108
- maxQueueSize: number;
1109
- /** Validation timeout */
1110
- validationTimeoutMs: number;
1111
- /** Alert threshold for error rate */
1112
- errorRateThreshold: number;
1113
- /** Alert window in ms */
1114
- alertWindowMs: number;
1115
- }
1116
- interface EvalSample {
1117
- sampleId: string;
1118
- timestamp: number;
1119
- request: {
1120
- prompt: string;
1121
- provider: string;
1122
- model: string;
1123
- };
1124
- result: {
1125
- success: boolean;
1126
- schema?: unknown;
1127
- error?: string;
1128
- latencyMs: number;
1129
- };
1130
- validation?: {
1131
- automatedScore: number;
1132
- syntaxErrors: number;
1133
- structureWarnings: number;
1134
- timestamp: number;
1135
- };
1136
- }
1137
- interface ErrorAlert {
1138
- alertId: string;
1139
- timestamp: number;
1140
- errorRate: number;
1141
- threshold: number;
1142
- windowStart: number;
1143
- sampleCount: number;
1144
- errorCount: number;
1145
- }
1146
- interface SamplingStats {
1147
- totalSampled: number;
1148
- totalValidated: number;
1149
- averageScore: number;
1150
- currentErrorRate: number;
1151
- queueSize: number;
1152
- isHealthy: boolean;
1153
- }
1154
- declare class OnlineEvalSampler extends EventEmitter {
1155
- private config;
1156
- private queue;
1157
- private samples;
1158
- private errorWindow;
1159
- private isProcessing;
1160
- constructor(config?: Partial<SamplingConfig>);
1161
- /**
1162
- * Check if a request should be sampled
1163
- * Uses hash-based sampling for consistency
1164
- */
1165
- shouldSample(requestId: string): boolean;
1166
- /**
1167
- * Add a sample to the queue for async validation
1168
- */
1169
- sample(requestId: string, request: {
1170
- prompt: string;
1171
- provider: string;
1172
- model: string;
1173
- }, result: {
1174
- success: boolean;
1175
- schema?: unknown;
1176
- error?: string;
1177
- latencyMs: number;
1178
- }): Promise<void>;
1179
- /**
1180
- * Pull samples for manual review
1181
- */
1182
- pullSamples(options?: {
1183
- date?: Date;
1184
- limit?: number;
1185
- minScore?: number;
1186
- }): Promise<EvalSample[]>;
1187
- /**
1188
- * Get current stats
1189
- */
1190
- getStats(): SamplingStats;
1191
- /**
1192
- * Stop the processor
1193
- */
1194
- stop(): void;
1195
- private startProcessor;
1196
- private validateSample;
1197
- private runAutomatedValidation;
1198
- private trackError;
1199
- private calculateErrorRate;
1200
- }
1201
- interface ReviewOptions {
1202
- date?: string;
1203
- limit?: number;
1204
- minScore?: number;
1205
- format?: 'json' | 'table';
1206
- }
1207
- declare function reviewSamples(sampler: OnlineEvalSampler, options?: ReviewOptions): Promise<void>;
1208
- declare function createOnlineEvalSampler(config?: Partial<SamplingConfig>): OnlineEvalSampler;
1209
-
1210
- /**
1211
- * Tool Composition & Chaining - Phase 3.3
1212
- *
1213
- * Composable tool workflows with parallel execution, error handling,
1214
- * and conditional branching.
1215
- *
1216
- * @packageDocumentation
1217
- */
1218
- type ToolStepStatus = 'pending' | 'running' | 'success' | 'error' | 'skipped';
1219
- interface ToolStep {
1220
- id: string;
1221
- name: string;
1222
- tool: string;
1223
- input: Record<string, unknown> | ((context: WorkflowContext) => Record<string, unknown>);
1224
- condition?: (context: WorkflowContext) => boolean;
1225
- dependsOn?: string[];
1226
- status: ToolStepStatus;
1227
- output?: unknown;
1228
- error?: string;
1229
- startTime?: number;
1230
- endTime?: number;
1231
- }
1232
- interface WorkflowContext {
1233
- workflowId: string;
1234
- inputs: Record<string, unknown>;
1235
- outputs: Record<string, unknown>;
1236
- stepResults: Map<string, {
1237
- success: boolean;
1238
- output?: unknown;
1239
- error?: string;
1240
- }>;
1241
- metadata: {
1242
- startTime: number;
1243
- stepsCompleted: number;
1244
- stepsFailed: number;
1245
- };
1246
- }
1247
- interface WorkflowDefinition {
1248
- name: string;
1249
- description: string;
1250
- inputs: Record<string, {
1251
- type: string;
1252
- required: boolean;
1253
- default?: unknown;
1254
- }>;
1255
- steps: ToolStep[];
1256
- onError?: 'stop' | 'continue' | 'retry';
1257
- maxRetries?: number;
1258
- }
1259
- interface WorkflowExecutionResult {
1260
- success: boolean;
1261
- workflowId: string;
1262
- context: WorkflowContext;
1263
- steps: ToolStep[];
1264
- durationMs: number;
1265
- error?: string;
1266
- }
1267
- interface ParallelExecutionResult {
1268
- stepId: string;
1269
- success: boolean;
1270
- output?: unknown;
1271
- error?: string;
1272
- durationMs: number;
1273
- }
1274
- interface ToolExecutor {
1275
- execute(tool: string, input: Record<string, unknown>): Promise<unknown>;
1276
- }
1277
- declare class WorkflowEngine {
1278
- private executor;
1279
- private workflows;
1280
- constructor(executor: ToolExecutor);
1281
- /**
1282
- * Register a workflow definition
1283
- */
1284
- registerWorkflow(definition: WorkflowDefinition): void;
1285
- /**
1286
- * Execute a workflow by name
1287
- */
1288
- executeWorkflow(workflowName: string, inputs: Record<string, unknown>): Promise<WorkflowExecutionResult>;
1289
- /**
1290
- * Execute a workflow definition directly
1291
- */
1292
- runWorkflow(definition: WorkflowDefinition, inputs: Record<string, unknown>): Promise<WorkflowExecutionResult>;
1293
- /**
1294
- * Execute independent steps in parallel
1295
- */
1296
- executeParallel(steps: Array<{
1297
- id: string;
1298
- tool: string;
1299
- input: Record<string, unknown>;
1300
- }>, context: WorkflowContext): Promise<ParallelExecutionResult[]>;
1301
- /**
1302
- * Create a workflow builder for fluent API
1303
- */
1304
- createWorkflow(name: string, description: string): WorkflowBuilder;
1305
- private executeStep;
1306
- private resolveDependencies;
1307
- }
1308
- declare class WorkflowBuilder {
1309
- private engine;
1310
- private definition;
1311
- constructor(engine: WorkflowEngine, name: string, description: string);
1312
- input(name: string, type: string, required?: boolean, defaultValue?: unknown): this;
1313
- step(id: string, tool: string, input: Record<string, unknown> | ((context: WorkflowContext) => Record<string, unknown>), options?: {
1314
- dependsOn?: string[];
1315
- condition?: (context: WorkflowContext) => boolean;
1316
- }): this;
1317
- parallel(steps: Array<{
1318
- id: string;
1319
- tool: string;
1320
- input: Record<string, unknown>;
1321
- }>): this;
1322
- onError(policy: 'stop' | 'continue' | 'retry'): this;
1323
- retry(maxRetries: number): this;
1324
- build(): WorkflowDefinition;
1325
- execute(inputs: Record<string, unknown>): Promise<WorkflowExecutionResult>;
1326
- }
1327
- declare function createSchemaGenerationWorkflow(engine: WorkflowEngine): WorkflowDefinition;
1328
- declare function createWorkflowEngine(executor: ToolExecutor): WorkflowEngine;
1329
-
1330
- /**
1331
- * Complexity Classifier
1332
- *
1333
- * Determines the complexity of an orbital generation request
1334
- * based on the number of orbitals identified during decomposition.
1335
- */
1336
- type ComplexityLevel = 'simple' | 'medium' | 'complex';
1337
- interface ComplexityResult {
1338
- level: ComplexityLevel;
1339
- orbitalCount: number;
1340
- recommendedProvider: 'qwen' | 'multi-provider';
1341
- reasoning: string;
1342
- }
1343
- /**
1344
- * Classify complexity based on orbital count
1345
- *
1346
- * Simple: 1 orbital
1347
- * Medium: 2-3 orbitals
1348
- * Complex: 4+ orbitals
1349
- */
1350
- declare function classifyComplexity(orbitalCount: number): ComplexityResult;
1351
- /**
1352
- * Quick complexity check without full decomposition
1353
- * Based on keywords and request length heuristics
1354
- */
1355
- declare function estimateComplexity(prompt: string): {
1356
- estimatedLevel: ComplexityLevel;
1357
- confidence: 'high' | 'medium' | 'low';
1358
- };
1359
- /**
1360
- * Get execution strategy based on complexity
1361
- */
1362
- declare function getExecutionStrategy(complexity: ComplexityResult): {
1363
- type: 'single' | 'multi-provider';
1364
- provider: string;
1365
- model: string;
1366
- parallelization: number;
1367
- };
1368
-
1369
- /**
1370
- * Provider Router
1371
- *
1372
- * Routes generation and fixing requests to the appropriate provider(s)
1373
- * based on complexity analysis.
1374
- */
1375
-
1376
- interface RouteConfig {
1377
- /** Optional: Override default verbosity */
1378
- verbose?: boolean;
1379
- }
1380
- interface GenerationResult {
1381
- orbitals: OrbitalDefinition[];
1382
- complexity: ComplexityResult;
1383
- timing: {
1384
- decomposeMs: number;
1385
- generateMs: number;
1386
- totalMs: number;
1387
- };
1388
- provider: string;
1389
- }
1390
- interface DecomposedUnit {
1391
- name: string;
1392
- entity: string;
1393
- traits: string[];
1394
- }
1395
- /**
1396
- * Main routing function for generation
1397
- *
1398
- * 1. Decomposes the request
1399
- * 2. Classifies complexity
1400
- * 3. Routes to appropriate provider(s)
1401
- * 4. Returns combined results
1402
- */
1403
- declare function routeGeneration(prompt: string, skillContent: string, config?: RouteConfig): Promise<GenerationResult>;
1404
- /**
1405
- * Quick check if a request is likely complex
1406
- * Useful for UI feedback before full decomposition
1407
- */
1408
- declare function quickComplexityCheck(prompt: string): {
1409
- likelyComplex: boolean;
1410
- confidence: 'high' | 'medium' | 'low';
1411
- estimatedOrbitals: number;
1412
- };
1413
-
1414
- /**
1415
- * CapabilityToken — HMAC-SHA256 signed scoped token with budget + TTL.
1416
- *
1417
- * TypeScript port of saezbaldo/ic-agi `ic_agi/control_plane.py`.
1418
- * See: https://github.com/saezbaldo/ic-agi
1419
- *
1420
- * TLA+ properties verified in CapabilityTokens.tla:
1421
- * P5 AntiReplay: uses <= budget (invariant)
1422
- * P6 TTLEnforcement: expired tokens produce no log entries
1423
- * P7 RevocationFinality: revoked = true => uses frozen forever
1424
- * P8 BudgetMonotonicity: uses never decreases
1425
- * P9 ForgeryResistance: invalid signature => uses never incremented
1426
- */
1427
- interface CapabilityToken {
1428
- tokenId: string;
1429
- issuedTo: string;
1430
- /** Sorted alphabetically for determinism. */
1431
- scope: string[];
1432
- /** Unix epoch seconds. */
1433
- issuedAt: number;
1434
- /** Unix epoch seconds. */
1435
- expiresAt: number;
1436
- budget: number;
1437
- uses: number;
1438
- revoked: boolean;
1439
- metadata: Record<string, unknown>;
1440
- /** HMAC-SHA256 hex digest over the immutable fields. */
1441
- signature: string;
1442
- }
1443
- interface TokenParams {
1444
- issuedTo: string;
1445
- scope: string[];
1446
- ttlSeconds?: number;
1447
- budget?: number;
1448
- criticality?: 'low' | 'medium' | 'high' | 'critical';
1449
- metadata?: Record<string, unknown>;
1450
- }
1451
- /** Issue a new signed capability token. TTL and budget are policy-capped. */
1452
- declare function issueToken(params: TokenParams, signingKey: Buffer): CapabilityToken;
1453
- /** Verify the token's HMAC signature. Uses constant-time comparison (P9). */
1454
- declare function verifyToken(token: CapabilityToken, signingKey: Buffer): boolean;
1455
- /** Check if the token can be used (not revoked, not expired, has remaining budget). */
1456
- declare function isTokenValid(token: CapabilityToken): boolean;
1457
- /**
1458
- * Consume one use from the token.
1459
- * Returns false without mutating if the token is invalid (P5, P8).
1460
- */
1461
- declare function consumeToken(token: CapabilityToken): boolean;
1462
- /** Permanently revoke a token. Immutable once set (P7). */
1463
- declare function revokeToken(token: CapabilityToken): void;
1464
-
1465
- /**
1466
- * ThresholdAuthorizer — K-of-N approval voting for critical agent actions.
1467
- *
1468
- * TypeScript port of saezbaldo/ic-agi `ic_agi/threshold_auth.py`.
1469
- * See: https://github.com/saezbaldo/ic-agi
1470
- *
1471
- * TLA+ properties verified in ThresholdAuth.tla:
1472
- * P1 ThresholdSafety: executed => approvals >= K
1473
- * P2 NoUnilateralAuthority: K >= 2 enforced in constructor
1474
- * P3 DenialFinality: once denied, resolution immutable
1475
- * P4 ResolutionImmutability: resolved => resolution never changes
1476
- *
1477
- * Early-denial formula: deny_count > (N - K)
1478
- * Once enough denials make threshold mathematically unreachable,
1479
- * the request is immediately resolved as denied.
1480
- */
1481
-
1482
- interface ApprovalRequest {
1483
- requestId: string;
1484
- actionDescription: string;
1485
- criticality: string;
1486
- requester: string;
1487
- /** Unix epoch seconds. */
1488
- createdAt: number;
1489
- ttlSeconds: number;
1490
- /** Map of approverId → vote (true = approve, false = deny). */
1491
- approvals: Map<string, boolean>;
1492
- resolved: boolean;
1493
- resolution: 'approved' | 'denied' | 'expired' | null;
1494
- }
1495
- interface VoteResult {
1496
- status: 'approved' | 'denied' | 'pending';
1497
- approvals: number;
1498
- denials: number;
1499
- threshold: number;
1500
- /** Remaining approvals needed to reach threshold. */
1501
- remaining: number;
1502
- }
1503
- declare class ThresholdAuthorizer {
1504
- private requests;
1505
- private readonly k;
1506
- private readonly n;
1507
- private readonly approverIds;
1508
- private readonly auditLog?;
1509
- /**
1510
- * @param k Minimum approvals required (must be >= 2, P2)
1511
- * @param approverIds List of registered approver IDs (length >= k)
1512
- * @param auditLog Optional audit chain for all voting events
1513
- */
1514
- constructor(k: number, approverIds: string[], auditLog?: AuditLog);
1515
- /**
1516
- * Create a new approval request for a critical action.
1517
- * The request window is 5 minutes (300s).
1518
- */
1519
- createRequest(actionDescription: string, requester: string, criticality?: string): ApprovalRequest;
1520
- /**
1521
- * Submit a vote for a pending request.
1522
- * Auto-resolves the request when threshold is reached (approve)
1523
- * or when threshold becomes mathematically unreachable (deny).
1524
- *
1525
- * @throws if request not found, already resolved, expired, approver not registered, or double-vote
1526
- */
1527
- submitVote(requestId: string, approverId: string, vote: boolean): VoteResult;
1528
- /** Returns true iff the request is resolved and approved (P1). */
1529
- isApproved(requestId: string): boolean;
1530
- /** Returns true iff the request is resolved and denied (P3). */
1531
- isDenied(requestId: string): boolean;
1532
- isExpired(requestId: string): boolean;
1533
- getRequest(requestId: string): ApprovalRequest | undefined;
1534
- }
1535
-
1536
- /**
1537
- * RateLimiter — Sliding window per-entity rate limiting.
1538
- *
1539
- * TypeScript port of saezbaldo/ic-agi `ic_agi/rate_limiter.py`.
1540
- * See: https://github.com/saezbaldo/ic-agi
1541
- *
1542
- * Two-layer design:
1543
- * 1. Global counter (10x per-entity limit) — system-wide protection
1544
- * 2. Per-(entity, scope) counter — fine-grained per-caller limits
1545
- *
1546
- * Cooldown note: when a per-entity counter is exceeded, a cooldown
1547
- * period is applied. The global counter does not apply cooldown.
1548
- */
1549
-
1550
- interface RateLimitConfig {
1551
- /** Maximum requests per window. Default: 20 */
1552
- maxRequests?: number;
1553
- /** Sliding window duration in seconds. Default: 60 */
1554
- windowSeconds?: number;
1555
- /** Cooldown duration in seconds after limit exceeded. Default: 30 */
1556
- cooldownSeconds?: number;
1557
- }
1558
- declare class RateLimiter {
1559
- private readonly counters;
1560
- private readonly global;
1561
- private readonly config;
1562
- private readonly auditLog?;
1563
- constructor(config?: RateLimitConfig, auditLog?: AuditLog);
1564
- /**
1565
- * Check whether the (entity, scope) pair is allowed to proceed.
1566
- * Checks the global counter first, then the per-entity counter.
1567
- */
1568
- allow(entity: string, scope?: string): boolean;
1569
- remaining(entity: string, scope?: string): number;
1570
- inCooldown(entity: string, scope?: string): boolean;
1571
- reset(entity: string, scope?: string): void;
1572
- /** Reset all counters including global (test utility). */
1573
- resetAll(): void;
1574
- }
1575
-
1576
- /**
1577
- * CircuitBreaker — Fault isolation state machine per worker/session.
1578
- *
1579
- * TypeScript port of saezbaldo/ic-agi `ic_agi/circuit_breaker.py`.
1580
- * See: https://github.com/saezbaldo/ic-agi
1581
- *
1582
- * State machine:
1583
- * CLOSED → OPEN when consecutive failures >= threshold OR error rate >= 50%
1584
- * OPEN → HALF_OPEN after recovery timeout (probe request allowed through)
1585
- * HALF_OPEN → CLOSED when consecutive successes >= success threshold
1586
- * HALF_OPEN → OPEN on any failure (immediate trip)
1587
- *
1588
- * Error rate guard only fires when totalRequests >= 5 to prevent
1589
- * tripping on a single noisy startup failure.
1590
- */
1591
-
1592
- declare enum CircuitState {
1593
- CLOSED = "CLOSED",
1594
- OPEN = "OPEN",
1595
- HALF_OPEN = "HALF_OPEN"
1596
- }
1597
- interface CircuitBreakerConfig {
1598
- /** Consecutive failures before tripping. Default: 3 */
1599
- failureThreshold?: number;
1600
- /** Consecutive successes in HALF_OPEN before closing. Default: 2 */
1601
- successThreshold?: number;
1602
- /** Seconds in OPEN before allowing a probe request. Default: 30 */
1603
- recoveryTimeoutSeconds?: number;
1604
- /** Window in seconds for error-rate calculation. Default: 120 */
1605
- errorRateWindow?: number;
1606
- /** Error rate threshold (0–1) to trigger OPEN. Default: 0.5 */
1607
- errorRateThreshold?: number;
1608
- }
1609
- interface WorkerCircuit {
1610
- workerId: string;
1611
- state: CircuitState;
1612
- consecutiveFailures: number;
1613
- consecutiveSuccesses: number;
1614
- totalRequests: number;
1615
- totalFailures: number;
1616
- lastFailureTime: number;
1617
- openedAt: number;
1618
- lastTransitionTime: number;
1619
- /** Sliding window of (timestamp, success) pairs. */
1620
- recent: Array<{
1621
- timestamp: number;
1622
- success: boolean;
1623
- }>;
1624
- }
1625
- declare class CircuitBreaker {
1626
- private readonly circuits;
1627
- private readonly config;
1628
- private readonly auditLog?;
1629
- constructor(config?: CircuitBreakerConfig, auditLog?: AuditLog);
1630
- private getOrCreate;
1631
- /** Compute error rate for the worker within the configured window. Prunes stale entries. */
1632
- private errorRate;
1633
- private transition;
1634
- /**
1635
- * Check whether the worker is allowed to proceed.
1636
- * - CLOSED: always allowed
1637
- * - OPEN: blocked until recovery timeout, then transitions to HALF_OPEN
1638
- * - HALF_OPEN: probe allowed through
1639
- */
1640
- allow(workerId: string): boolean;
1641
- recordSuccess(workerId: string): void;
1642
- recordFailure(workerId: string): void;
1643
- getState(workerId: string): CircuitState;
1644
- getStats(workerId: string): Pick<WorkerCircuit, 'state' | 'consecutiveFailures' | 'totalRequests' | 'totalFailures'>;
1645
- }
1646
-
1647
- /**
1648
- * SandboxExecutor — V8 isolate-based sandboxed code execution.
1649
- *
1650
- * Uses `isolated-vm` to run untrusted code in a separate V8 context
1651
- * with configurable memory and time limits. Stronger isolation than
1652
- * Node.js `vm` module (separate heap, no shared references).
1653
- *
1654
- * This is an Almadar-specific addition to the IC-AGI security layer.
1655
- * It will be contributed to almadar-io/ic-agi as an optional module.
1656
- */
1657
- interface SandboxOptions {
1658
- /** Execution timeout in milliseconds. Default: 5000 */
1659
- timeoutMs?: number;
1660
- /** Memory limit for the isolate in MB. Default: 32 */
1661
- memoryLimitMb?: number;
1662
- }
1663
- interface SandboxResult {
1664
- success: boolean;
1665
- value?: unknown;
1666
- error?: string;
1667
- timedOut?: boolean;
1668
- }
1669
- /**
1670
- * Execute a JavaScript code string inside a V8 isolate.
1671
- *
1672
- * The `inputs` object is copied into the isolate as a global `inputs` variable.
1673
- * The code should return a value or assign to a global `result` variable.
1674
- *
1675
- * Falls back gracefully if `isolated-vm` is not available in the environment.
1676
- */
1677
- declare function executeSandboxed(code: string, inputs?: Record<string, unknown>, options?: SandboxOptions): Promise<SandboxResult>;
1678
-
1679
- export { type AccessCheckResult, AgenticSearchEngine, type AgenticSearchParams, type AgenticSearchResponse, type ApprovalRequest, AuditLog, type CapabilityToken, CircuitBreaker, type CircuitBreakerConfig, CircuitState, type ComplexityLevel, type ComplexityResult, type ConflictResolution, type DecomposedUnit, type DeepAgentCompleteEvent, type DeepAgentErrorEvent, type DeepAgentEvent, type DeepAgentExecutionEvent, type DeepAgentSchemaEvent, type DeepAgentStartEvent, type ErrorAlert, type EvalSample, type GenerationMetrics, type GenerationResult, GenerationSession, type HealthCheckResult, type InferredPreference, MemoryManager, MetricsCollector, type MetricsSummary, MultiUserManager, ObservabilityCollector, type ObservableEvent, type ObservableEventType, OnlineEvalSampler, type CombinerOptions as OrbitalCombinerOptions, type CombinerResult as OrbitalCombinerResult, type OrbitalSchemaValidationResult, type ParallelExecutionResult, type PerformanceSnapshot, type PreferenceAnalysis, PreferenceLearner, type PreferenceLearnerOptions, type RateLimitConfig, RateLimiter, type ReviewOptions, type RouteConfig, type SamplingConfig, type SamplingStats, type SandboxOptions, type SandboxResult, type ScopedSessionMetadata, type SearchResult, type SearchStrategy, SessionMetadata, type SessionTelemetry, type StateChangeEvent, type StateChangeType, type StateSyncConfig, StateSyncManager, type StateSyncSnapshot, SubAgent, ThresholdAuthorizer, type TokenParams, type ToolExecutor, type ToolStep, type ToolStepStatus, type UserContext, UserPreference, type UserSessionStats, type VersionVector, type VoteResult, WorkflowBuilder, type WorkflowContext, type WorkflowDefinition, WorkflowEngine, type WorkflowExecutionResult, analyzeFailures, classifyComplexity, combineOrbitals, combineOrbitalsToSchema, consumeToken, createAgenticSearchEngine, createErrorFixerSubagent, createOnlineEvalSampler, createPreferenceLearner, createSchemaGenerationWorkflow, createSchemaGeneratorSubagent, createSubagentConfigs, createSubagents, createTestAnalyzerSubagent, createUserContext, createWorkflowEngine, debounceSync, endObservabilitySession, estimateCacheSavings, estimateCombineComplexity, estimateComplexity, executeSandboxed, formatSummary, generateFullOrbital, getExecutionStrategy, getMultiUserManager, getObservabilityCollector, getPerformanceSnapshot, getStateSyncManager, isAdmin, isCompleteEvent, isErrorEvent, isExecutionEvent, isSchemaEvent, isStartEvent, isTokenValid, issueToken, parseDeepAgentEvent, quickComplexityCheck, recordEvent, requireOwnership, resetMultiUserManager, resetObservabilityCollector, resetStateSyncManager, reviewSamples, revokeToken, routeGeneration, startObservabilitySession, verifyToken, withSync };
2
+ * @almadar/agent
3
+ *
4
+ * AI agent infrastructure for Almadar orbital schema generation.
5
+ *
6
+ * Provides everything needed to create, run, checkpoint, and resume
7
+ * skill-based agents. Uses @almadar/llm for LLM access and
8
+ * @almadar/skills for prompt sections.
9
+ *
10
+ * Key modules:
11
+ * - Agent factory: createSkillAgent(), resumeSkillAgent()
12
+ * - Session management: SessionManager with pluggable backends
13
+ * - Persistence: Memory + Firestore backends for checkpoints & sessions
14
+ * - Event transformer: Raw LangGraph events → typed SSE events
15
+ * - Tools: execute, validate, orbital subagent, domain, chunking
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ export type { AgentDependencies, SubAgent, CombineOrbitalsFn, CombinerOptions, CombinerResult, ConvertDomainToSchemaFn, DomainConversionResult, GenerateFullOrbitalFn, OrbitalGenerationResult, OrbitalGenerationOptions, GenerationLog, } from './types.js';
20
+ export { createSSEEvent, formatSSEEvent, parseSSEEvent, isSSEStartEvent, isSSEMessageEvent, isSSEInterruptEvent, isSSECompleteEvent, isSSEErrorEvent, isSSEToolCallEvent, isSSETodoUpdateEvent, isSSETodoDetailEvent, isSSESubagentEvent, isSSEGenerationLogEvent, ExtractedRequirementsSchema, GenerateRequestSchema, ResumeRequestSchema, ContinueRequestSchema, } from './api-types.js';
21
+ export type { SSEEvent, SSEEventType, GenerateRequest, ResumeRequest, ContinueRequest, ExtractedRequirementsInput, StartEvent, MessageEvent, ToolCallEvent, ToolResultEvent, TodoUpdateEvent, ErrorEvent, CompleteEvent, SubagentEvent, GenerationLogEvent, InterruptEvent, } from './api-types.js';
22
+ export { createAgentTools, createExecuteTool, validateCommandPaths, createValidateSchemaTool, createGenerateSchemaTool, createFinishTaskTool, createCombineSchemasTool, createOrbitalSubagentTool, createSubagentEventWrapper, createTraitSubagentTool, createTraitEventWrapper, createGenerateOrbitalDomainTool, createConstructCombinedDomainTool, createDomainOrbitalTools, createQuerySchemaStructureTool, createExtractChunkTool, createApplyChunkTool, createSchemaChunkingTools, } from './tools/index.js';
23
+ export type { SubagentEventCallback, OrbitalCompleteCallback, OrbitalRequirements, OrbitalSubagentToolOptions, TraitEventCallback, TraitCompleteCallback, TraitSubagentToolOptions, TraitSpec, DomainOrbitalEventCallback, DomainOrbitalCompleteCallback, DomainOrbitalToolOptions, DomainOrbitalSpec, } from './tools/index.js';
24
+ export { combineOrbitals, combineOrbitalsToSchema, estimateCombineComplexity, } from './orbitals/combiner/index.js';
25
+ export type { CombinerOptions as OrbitalCombinerOptions, CombinerResult as OrbitalCombinerResult, OrbitalSchemaValidationResult, } from './orbitals/combiner/index.js';
26
+ export { convertDomainToSchema, applySectionUpdate, deleteSection, convertSchemaToDomain, } from './orbitals/domain-language/index.js';
27
+ export type { DomainToSchemaResult, SchemaToDomainResult, DomainDocument, ParseError, SectionMapping, } from './orbitals/domain-language/index.js';
28
+ export { generateFullOrbital, estimateCacheSavings, } from './orbitals/generation/index.js';
29
+ export { createSubagents, createSubagentConfigs, createSchemaGeneratorSubagent, createErrorFixerSubagent, createTestAnalyzerSubagent, } from './subagents.js';
30
+ export { parseDeepAgentEvent, isStartEvent, isExecutionEvent, isSchemaEvent, isCompleteEvent, isErrorEvent, } from './events.js';
31
+ export type { DeepAgentEvent, DeepAgentStartEvent, DeepAgentExecutionEvent, DeepAgentSchemaEvent, DeepAgentCompleteEvent, DeepAgentErrorEvent, } from './events.js';
32
+ export { needsCompaction, createSummaryPrompt, estimateTokens, DEFAULT_COMPACTION_CONFIG, } from './context-compaction.js';
33
+ export type { ContextCompactionConfig, } from './context-compaction.js';
34
+ export { MetricsCollector, formatSummary, analyzeFailures, } from './metrics.js';
35
+ export type { GenerationMetrics, MetricsSummary, } from './metrics.js';
36
+ export { createSkillAgent, resumeSkillAgent, Command, SessionManager, EVENT_BUDGETS, getEventBudget, getBudgetWarningMessage, getInterruptConfig, } from './agent/index.js';
37
+ export type { Skill, SkillLoader, SkillRefLoader, SkillAgentOptions, SkillAgentResult, SessionMetadata, SessionRecord, PersistenceMode, SessionManagerOptions, SkillMeta, } from './agent/index.js';
38
+ export { MemorySessionBackend, FirestoreCheckpointer, FirestoreSessionStore, FirestoreStore, } from './persistence/index.js';
39
+ export type { FirestoreCheckpointerOptions, FirestoreDb, FirestoreTimestamp, FirestoreSessionStoreOptions, FirestoreStoreOptions, Session, } from './persistence/index.js';
40
+ export { transformAgentEvent, transformAgentEventMulti, hasInterrupt, extractInterruptData, isTodoUpdate, isFileOperation, extractFileOperation, } from './event-transformer/index.js';
41
+ export type { RawAgentEvent, } from './event-transformer/index.js';
42
+ export { MemoryOrbitalSchema, MemoryManager, PreferenceLearner, createPreferenceLearner, AgenticSearchEngine, createAgenticSearchEngine, ObservabilityCollector, getObservabilityCollector, resetObservabilityCollector, recordEvent, startObservabilitySession, endObservabilitySession, getPerformanceSnapshot, MultiUserManager, getMultiUserManager, resetMultiUserManager, createUserContext, isAdmin, requireOwnership, StateSyncManager, getStateSyncManager, resetStateSyncManager, withSync, debounceSync, } from './memory/index.js';
43
+ export type { UserPreference, GenerationSession, ProjectContext, UserFeedback, PatternAffinity, InterruptRecord, ToolApprovalPreference, CheckpointRecord, MemoryManagerOptions, PreferenceLearnerOptions, InferredPreference, PreferenceAnalysis, SearchStrategy, AgenticSearchParams, SearchResult, AgenticSearchResponse, ObservableEventType, ObservableEvent, SessionTelemetry, PerformanceSnapshot, HealthCheckResult, UserContext, ScopedSessionMetadata, AccessCheckResult, UserSessionStats, StateChangeType, StateChangeEvent, VersionVector, StateSyncSnapshot, ConflictResolution, StateSyncConfig, } from './memory/index.js';
44
+ export { OnlineEvalSampler, createOnlineEvalSampler, reviewSamples, } from './evals/online-sampling.js';
45
+ export type { SamplingConfig, EvalSample, ErrorAlert, SamplingStats, ReviewOptions, } from './evals/online-sampling.js';
46
+ export { WorkflowEngine, WorkflowBuilder, createWorkflowEngine, createSchemaGenerationWorkflow, } from './tools/composition.js';
47
+ export type { ToolStep, ToolStepStatus, WorkflowContext, WorkflowDefinition, WorkflowExecutionResult, ParallelExecutionResult, ToolExecutor, } from './tools/composition.js';
48
+ export { createWorkflowToolWrapper, createEvalWorkflowWrapper, } from './agent/workflow-tool-wrapper.js';
49
+ export type { WorkflowToolWrapperOptions, ToolTelemetry, WorkflowToolWrapper, } from './agent/workflow-tool-wrapper.js';
50
+ export { classifyComplexity, estimateComplexity, getExecutionStrategy, routeGeneration, quickComplexityCheck, } from './orchestration/index.js';
51
+ export type { ComplexityLevel, ComplexityResult, RouteConfig, GenerationResult, DecomposedUnit, } from './orchestration/index.js';
52
+ export { AuditLog, issueToken, verifyToken, isTokenValid, consumeToken, revokeToken, ThresholdAuthorizer, RateLimiter, CircuitBreaker, CircuitState, } from './utils/safety/index.js';
53
+ export type { AuditEntry, CapabilityToken, TokenParams, ApprovalRequest, VoteResult, RateLimitConfig, CircuitBreakerConfig, } from './utils/safety/index.js';
54
+ export { WorkspaceManager, SinkManager, GitClient, GitSink, FirestoreSink, WORKSPACE_LAYOUT, createUserOrbTemplate, createProjectOrbTemplate, createSchemaOrbTemplate, serializeOrb, parseOrb, readOrbInstances, readOrb, writeOrbInstances, writeOrb, } from './workspace/index.js';
55
+ export type { WorkspaceSink, WorkspaceConfig, FileMeta, SinkResult, MemorySnapshot, FirestoreSinkConfig, GitLogEntry, GitStatus, } from './workspace/index.js';
56
+ export { executeSandboxed } from './tools/sandbox-executor.js';
57
+ export type { SandboxOptions, SandboxResult } from './tools/sandbox-executor.js';
58
+ export { classifyCommand, TOOL_GATES, CRITICAL_COMMAND_PATTERNS } from './agent/interrupt-config.js';
59
+ export type { ActionGate } from './agent/interrupt-config.js';