@almadar/agent 1.3.2 → 1.6.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.
package/dist/index.d.ts CHANGED
@@ -1,25 +1,25 @@
1
1
  import { SubAgent } from './types.js';
2
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-DVdGNr2M.js';
4
- import { O as OrbitalUnit, a as OrbitalGenerationOptions$1, b as OrbitalGenerationResult$1 } from './index-DFJdTDbo.js';
5
- export { T as TraitCompleteCallback, c as TraitEventCallback, d as TraitSpec, e as TraitSubagentToolOptions, f as createAgentTools, g as createApplyChunkTool, h as createCombineSchemasTool, i as createExecuteTool, j as createExtractChunkTool, k as createFinishTaskTool, l as createGenerateSchemaTool, m as createQuerySchemaStructureTool, n as createSchemaChunkingTools, o as createTraitEventWrapper, p as createTraitSubagentTool, q as createValidateSchemaTool, v as validateCommandPaths } from './index-DFJdTDbo.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-Bj2jeOU7.js';
4
+ import { O as OrbitalUnit, a as OrbitalGenerationOptions$1, b as OrbitalGenerationResult$1, A as AuditLog } from './index-DGdLGf-L.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-DGdLGf-L.js';
6
6
  import { DomainContext, OrbitalSchema, Orbital } from '@almadar/core/types';
7
7
  export { DomainDocument, DomainToSchemaResult, ParseError, SchemaToDomainResult, SectionMapping, applySectionUpdate, convertDomainToSchema, convertSchemaToDomain, deleteSection } from '@almadar/core/domain-language';
8
8
  import { LLMClient } from '@almadar/llm';
9
9
  export { createCompactSystemPrompt, createSystemPrompt } from './prompts/index.js';
10
- import { U as UserPreference, M as MemoryManager, G as GenerationSession } from './interrupt-config-Bib_RCTB.js';
11
- export { C as CheckpointRecord, l as ContextCompactionConfig, D as DEFAULT_COMPACTION_CONFIG, E as EVENT_BUDGETS, I as InterruptRecord, m as MemoryManagerOptions, n as MemoryOrbitalSchema, P as PatternAffinity, o as ProjectContext, S as SessionManager, a as SessionManagerOptions, b as Skill, c as SkillAgentOptions, d as SkillAgentResult, e as SkillLoader, f as SkillMeta, g as SkillRefLoader, T as ToolApprovalPreference, p as UserFeedback, h as createSkillAgent, q as createSummaryPrompt, s as estimateTokens, i as getBudgetWarningMessage, j as getEventBudget, k as getInterruptConfig, t as needsCompaction, r as resumeSkillAgent } from './interrupt-config-Bib_RCTB.js';
10
+ import { U as UserPreference, M as MemoryManager, G as GenerationSession } from './workflow-tool-wrapper-CXD0A7l3.js';
11
+ export { A as ActionGate, C as CRITICAL_COMMAND_PATTERNS, p as CheckpointRecord, q as ContextCompactionConfig, D as DEFAULT_COMPACTION_CONFIG, E as EVENT_BUDGETS, I as InterruptRecord, s as MemoryManagerOptions, t as MemoryOrbitalSchema, P as PatternAffinity, u as ProjectContext, S as SessionManager, a as SessionManagerOptions, b as Skill, d as SkillAgentOptions, e as SkillAgentResult, f as SkillLoader, g as SkillMeta, h as SkillRefLoader, v as TOOL_GATES, w as ToolApprovalPreference, T as ToolTelemetry, x as UserFeedback, W as WorkflowToolWrapper, i as WorkflowToolWrapperOptions, y as classifyCommand, j as createEvalWorkflowWrapper, k as createSkillAgent, z as createSummaryPrompt, l as createWorkflowToolWrapper, B as estimateTokens, m as getBudgetWarningMessage, n as getEventBudget, o as getInterruptConfig, F as needsCompaction, r as resumeSkillAgent } from './workflow-tool-wrapper-CXD0A7l3.js';
12
12
  import { S as SessionMetadata } from './firestore-checkpointer-BkFR-sZM.js';
13
13
  export { b as FirestoreCheckpointer, c as FirestoreCheckpointerOptions, F as FirestoreDb, d as FirestoreTimestamp, P as PersistenceMode, e as Session, a as SessionRecord } from './firestore-checkpointer-BkFR-sZM.js';
14
14
  export { FirestoreSessionStore, FirestoreSessionStoreOptions, FirestoreStore, FirestoreStoreOptions, MemorySessionBackend } from './persistence/index.js';
15
15
  export { RawAgentEvent, extractFileOperation, extractInterruptData, hasInterrupt, isFileOperation, isTodoUpdate, transformAgentEvent, transformAgentEventMulti } from './event-transformer/index.js';
16
16
  import { EventEmitter } from 'events';
17
17
  import { Checkpoint } from '@langchain/langgraph-checkpoint';
18
+ import { OrbitalDefinition } from '@almadar/core';
18
19
  export { Command } from '@langchain/langgraph';
19
- 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-CCo-ONJY.js';
20
+ 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-CHEeQQr_.js';
20
21
  import 'zod';
21
22
  import '@langchain/core/tools';
22
- import '@almadar/core';
23
23
  import '@langchain/core/messages';
24
24
  import '@langchain/core/runnables';
25
25
 
@@ -1854,4 +1854,353 @@ declare class WorkflowBuilder {
1854
1854
  declare function createSchemaGenerationWorkflow(engine: WorkflowEngine): WorkflowDefinition;
1855
1855
  declare function createWorkflowEngine(executor: ToolExecutor): WorkflowEngine;
1856
1856
 
1857
- export { type AccessCheckResult, AgenticSearchEngine, type AgenticSearchParams, type AgenticSearchResponse, type ConflictResolution, type DeepAgentCompleteEvent, type DeepAgentErrorEvent, type DeepAgentEvent, type DeepAgentExecutionEvent, type DeepAgentSchemaEvent, type DeepAgentStartEvent, type ErrorAlert, type EvalSample, type GenerationMetrics, GenerationSession, type HealthCheckResult, type InferredPreference, type LLMProvider, MCPClient, type MCPClientConfig, MCPClientManager, type MCPDiscoveryRequest, type MCPDiscoveryResponse, MCPResourceRegistry, MCPServer, type MCPServerConfig, MCPToolRegistry, MemoryManager, MetricsCollector, type MetricsSummary, ModelRouter, type ModelRouterConfig, MultiUserManager, ObservabilityCollector, type ObservableEvent, type ObservableEventType, OnlineEvalSampler, type CombinerOptions as OrbitalCombinerOptions, type CombinerResult as OrbitalCombinerResult, type OrbitalEstimation, type OrbitalSchemaValidationResult, type ParallelExecutionResult, type PerformanceSnapshot, type PreferenceAnalysis, PreferenceLearner, type PreferenceLearnerOptions, type ProviderConfig, QwenCircuitBreaker, type RegisteredMCPServer, type ResourceDefinition, type ResourceRequest, type ResourceResponse, type ReviewOptions, type RoutingDecision, type RoutingStrategy, type SamplingConfig, type SamplingStats, type ScopedSessionMetadata, type SearchResult, type SearchStrategy, SessionMetadata, type SessionTelemetry, type StateChangeEvent, type StateChangeType, type StateSyncConfig, StateSyncManager, type StateSyncSnapshot, SubAgent, type ToolCallRequest, type ToolCallResponse, type ToolDefinition, type ToolExecutor, type ToolStep, type ToolStepStatus, type UserContext, UserPreference, type UserSessionStats, type VersionVector, WorkflowBuilder, type WorkflowContext, type WorkflowDefinition, WorkflowEngine, type WorkflowExecutionResult, analyzeFailures, applyConservativeBias, combineOrbitals, combineOrbitalsToSchema, createAgenticSearchEngine, createAlmadarMCPServer, createDefaultMCPClientManager, createErrorFixerSubagent, createMCPClient, createMCPClientManager, createMCPServer, createModelRouter, createOnlineEvalSampler, createPreferenceLearner, createSchemaGenerationWorkflow, createSchemaGeneratorSubagent, createSubagentConfigs, createSubagents, createTestAnalyzerSubagent, createUserContext, createWorkflowEngine, debounceSync, endObservabilitySession, estimateCacheSavings, estimateCombineComplexity, estimateOrbitalCount, estimateOrbitalCountBatch, estimateOrbitalCountHeuristic, estimateOrbitalCountLLM, formatSummary, generateFullOrbital, getCircuitBreaker, getModelRouter, getMultiUserManager, getObservabilityCollector, getPerformanceSnapshot, getStateSyncManager, hasDefiniteComplexIndicators, isAdmin, isCompleteEvent, isErrorEvent, isExecutionEvent, isSchemaEvent, isStartEvent, makeSafeRoutingDecision, parseDeepAgentEvent, quickEstimate, recordEvent, requireOwnership, resetMultiUserManager, resetObservabilityCollector, resetStateSyncManager, reviewSamples, safeEstimate, startObservabilitySession, withSync };
1857
+ /**
1858
+ * Complexity Classifier
1859
+ *
1860
+ * Determines the complexity of an orbital generation request
1861
+ * based on the number of orbitals identified during decomposition.
1862
+ */
1863
+ type ComplexityLevel = 'simple' | 'medium' | 'complex';
1864
+ interface ComplexityResult {
1865
+ level: ComplexityLevel;
1866
+ orbitalCount: number;
1867
+ recommendedProvider: 'qwen' | 'multi-provider';
1868
+ reasoning: string;
1869
+ }
1870
+ /**
1871
+ * Classify complexity based on orbital count
1872
+ *
1873
+ * Simple: 1 orbital
1874
+ * Medium: 2-3 orbitals
1875
+ * Complex: 4+ orbitals
1876
+ */
1877
+ declare function classifyComplexity(orbitalCount: number): ComplexityResult;
1878
+ /**
1879
+ * Quick complexity check without full decomposition
1880
+ * Based on keywords and request length heuristics
1881
+ */
1882
+ declare function estimateComplexity(prompt: string): {
1883
+ estimatedLevel: ComplexityLevel;
1884
+ confidence: 'high' | 'medium' | 'low';
1885
+ };
1886
+ /**
1887
+ * Get execution strategy based on complexity
1888
+ */
1889
+ declare function getExecutionStrategy(complexity: ComplexityResult): {
1890
+ type: 'single' | 'multi-provider';
1891
+ provider: string;
1892
+ model: string;
1893
+ parallelization: number;
1894
+ };
1895
+
1896
+ /**
1897
+ * Provider Router
1898
+ *
1899
+ * Routes generation and fixing requests to the appropriate provider(s)
1900
+ * based on complexity analysis.
1901
+ */
1902
+
1903
+ interface RouteConfig {
1904
+ /** Optional: Override default verbosity */
1905
+ verbose?: boolean;
1906
+ }
1907
+ interface GenerationResult {
1908
+ orbitals: OrbitalDefinition[];
1909
+ complexity: ComplexityResult;
1910
+ timing: {
1911
+ decomposeMs: number;
1912
+ generateMs: number;
1913
+ totalMs: number;
1914
+ };
1915
+ provider: string;
1916
+ }
1917
+ interface DecomposedUnit {
1918
+ name: string;
1919
+ entity: string;
1920
+ traits: string[];
1921
+ }
1922
+ /**
1923
+ * Main routing function for generation
1924
+ *
1925
+ * 1. Decomposes the request
1926
+ * 2. Classifies complexity
1927
+ * 3. Routes to appropriate provider(s)
1928
+ * 4. Returns combined results
1929
+ */
1930
+ declare function routeGeneration(prompt: string, skillContent: string, config?: RouteConfig): Promise<GenerationResult>;
1931
+ /**
1932
+ * Quick check if a request is likely complex
1933
+ * Useful for UI feedback before full decomposition
1934
+ */
1935
+ declare function quickComplexityCheck(prompt: string): {
1936
+ likelyComplex: boolean;
1937
+ confidence: 'high' | 'medium' | 'low';
1938
+ estimatedOrbitals: number;
1939
+ };
1940
+
1941
+ /**
1942
+ * CapabilityToken — HMAC-SHA256 signed scoped token with budget + TTL.
1943
+ *
1944
+ * TypeScript port of saezbaldo/ic-agi `ic_agi/control_plane.py`.
1945
+ * See: https://github.com/saezbaldo/ic-agi
1946
+ *
1947
+ * TLA+ properties verified in CapabilityTokens.tla:
1948
+ * P5 AntiReplay: uses <= budget (invariant)
1949
+ * P6 TTLEnforcement: expired tokens produce no log entries
1950
+ * P7 RevocationFinality: revoked = true => uses frozen forever
1951
+ * P8 BudgetMonotonicity: uses never decreases
1952
+ * P9 ForgeryResistance: invalid signature => uses never incremented
1953
+ */
1954
+ interface CapabilityToken {
1955
+ tokenId: string;
1956
+ issuedTo: string;
1957
+ /** Sorted alphabetically for determinism. */
1958
+ scope: string[];
1959
+ /** Unix epoch seconds. */
1960
+ issuedAt: number;
1961
+ /** Unix epoch seconds. */
1962
+ expiresAt: number;
1963
+ budget: number;
1964
+ uses: number;
1965
+ revoked: boolean;
1966
+ metadata: Record<string, unknown>;
1967
+ /** HMAC-SHA256 hex digest over the immutable fields. */
1968
+ signature: string;
1969
+ }
1970
+ interface TokenParams {
1971
+ issuedTo: string;
1972
+ scope: string[];
1973
+ ttlSeconds?: number;
1974
+ budget?: number;
1975
+ criticality?: 'low' | 'medium' | 'high' | 'critical';
1976
+ metadata?: Record<string, unknown>;
1977
+ }
1978
+ /** Issue a new signed capability token. TTL and budget are policy-capped. */
1979
+ declare function issueToken(params: TokenParams, signingKey: Buffer): CapabilityToken;
1980
+ /** Verify the token's HMAC signature. Uses constant-time comparison (P9). */
1981
+ declare function verifyToken(token: CapabilityToken, signingKey: Buffer): boolean;
1982
+ /** Check if the token can be used (not revoked, not expired, has remaining budget). */
1983
+ declare function isTokenValid(token: CapabilityToken): boolean;
1984
+ /**
1985
+ * Consume one use from the token.
1986
+ * Returns false without mutating if the token is invalid (P5, P8).
1987
+ */
1988
+ declare function consumeToken(token: CapabilityToken): boolean;
1989
+ /** Permanently revoke a token. Immutable once set (P7). */
1990
+ declare function revokeToken(token: CapabilityToken): void;
1991
+
1992
+ /**
1993
+ * ThresholdAuthorizer — K-of-N approval voting for critical agent actions.
1994
+ *
1995
+ * TypeScript port of saezbaldo/ic-agi `ic_agi/threshold_auth.py`.
1996
+ * See: https://github.com/saezbaldo/ic-agi
1997
+ *
1998
+ * TLA+ properties verified in ThresholdAuth.tla:
1999
+ * P1 ThresholdSafety: executed => approvals >= K
2000
+ * P2 NoUnilateralAuthority: K >= 2 enforced in constructor
2001
+ * P3 DenialFinality: once denied, resolution immutable
2002
+ * P4 ResolutionImmutability: resolved => resolution never changes
2003
+ *
2004
+ * Early-denial formula: deny_count > (N - K)
2005
+ * Once enough denials make threshold mathematically unreachable,
2006
+ * the request is immediately resolved as denied.
2007
+ */
2008
+
2009
+ interface ApprovalRequest {
2010
+ requestId: string;
2011
+ actionDescription: string;
2012
+ criticality: string;
2013
+ requester: string;
2014
+ /** Unix epoch seconds. */
2015
+ createdAt: number;
2016
+ ttlSeconds: number;
2017
+ /** Map of approverId → vote (true = approve, false = deny). */
2018
+ approvals: Map<string, boolean>;
2019
+ resolved: boolean;
2020
+ resolution: 'approved' | 'denied' | 'expired' | null;
2021
+ }
2022
+ interface VoteResult {
2023
+ status: 'approved' | 'denied' | 'pending';
2024
+ approvals: number;
2025
+ denials: number;
2026
+ threshold: number;
2027
+ /** Remaining approvals needed to reach threshold. */
2028
+ remaining: number;
2029
+ }
2030
+ declare class ThresholdAuthorizer {
2031
+ private requests;
2032
+ private readonly k;
2033
+ private readonly n;
2034
+ private readonly approverIds;
2035
+ private readonly auditLog?;
2036
+ /**
2037
+ * @param k Minimum approvals required (must be >= 2, P2)
2038
+ * @param approverIds List of registered approver IDs (length >= k)
2039
+ * @param auditLog Optional audit chain for all voting events
2040
+ */
2041
+ constructor(k: number, approverIds: string[], auditLog?: AuditLog);
2042
+ /**
2043
+ * Create a new approval request for a critical action.
2044
+ * The request window is 5 minutes (300s).
2045
+ */
2046
+ createRequest(actionDescription: string, requester: string, criticality?: string): ApprovalRequest;
2047
+ /**
2048
+ * Submit a vote for a pending request.
2049
+ * Auto-resolves the request when threshold is reached (approve)
2050
+ * or when threshold becomes mathematically unreachable (deny).
2051
+ *
2052
+ * @throws if request not found, already resolved, expired, approver not registered, or double-vote
2053
+ */
2054
+ submitVote(requestId: string, approverId: string, vote: boolean): VoteResult;
2055
+ /** Returns true iff the request is resolved and approved (P1). */
2056
+ isApproved(requestId: string): boolean;
2057
+ /** Returns true iff the request is resolved and denied (P3). */
2058
+ isDenied(requestId: string): boolean;
2059
+ isExpired(requestId: string): boolean;
2060
+ getRequest(requestId: string): ApprovalRequest | undefined;
2061
+ }
2062
+
2063
+ /**
2064
+ * RateLimiter — Sliding window per-entity rate limiting.
2065
+ *
2066
+ * TypeScript port of saezbaldo/ic-agi `ic_agi/rate_limiter.py`.
2067
+ * See: https://github.com/saezbaldo/ic-agi
2068
+ *
2069
+ * Two-layer design:
2070
+ * 1. Global counter (10x per-entity limit) — system-wide protection
2071
+ * 2. Per-(entity, scope) counter — fine-grained per-caller limits
2072
+ *
2073
+ * Cooldown note: when a per-entity counter is exceeded, a cooldown
2074
+ * period is applied. The global counter does not apply cooldown.
2075
+ */
2076
+
2077
+ interface RateLimitConfig {
2078
+ /** Maximum requests per window. Default: 20 */
2079
+ maxRequests?: number;
2080
+ /** Sliding window duration in seconds. Default: 60 */
2081
+ windowSeconds?: number;
2082
+ /** Cooldown duration in seconds after limit exceeded. Default: 30 */
2083
+ cooldownSeconds?: number;
2084
+ }
2085
+ declare class RateLimiter {
2086
+ private readonly counters;
2087
+ private readonly global;
2088
+ private readonly config;
2089
+ private readonly auditLog?;
2090
+ constructor(config?: RateLimitConfig, auditLog?: AuditLog);
2091
+ /**
2092
+ * Check whether the (entity, scope) pair is allowed to proceed.
2093
+ * Checks the global counter first, then the per-entity counter.
2094
+ */
2095
+ allow(entity: string, scope?: string): boolean;
2096
+ remaining(entity: string, scope?: string): number;
2097
+ inCooldown(entity: string, scope?: string): boolean;
2098
+ reset(entity: string, scope?: string): void;
2099
+ /** Reset all counters including global (test utility). */
2100
+ resetAll(): void;
2101
+ }
2102
+
2103
+ /**
2104
+ * CircuitBreaker — Fault isolation state machine per worker/session.
2105
+ *
2106
+ * TypeScript port of saezbaldo/ic-agi `ic_agi/circuit_breaker.py`.
2107
+ * See: https://github.com/saezbaldo/ic-agi
2108
+ *
2109
+ * State machine:
2110
+ * CLOSED → OPEN when consecutive failures >= threshold OR error rate >= 50%
2111
+ * OPEN → HALF_OPEN after recovery timeout (probe request allowed through)
2112
+ * HALF_OPEN → CLOSED when consecutive successes >= success threshold
2113
+ * HALF_OPEN → OPEN on any failure (immediate trip)
2114
+ *
2115
+ * Error rate guard only fires when totalRequests >= 5 to prevent
2116
+ * tripping on a single noisy startup failure.
2117
+ */
2118
+
2119
+ declare enum CircuitState {
2120
+ CLOSED = "CLOSED",
2121
+ OPEN = "OPEN",
2122
+ HALF_OPEN = "HALF_OPEN"
2123
+ }
2124
+ interface CircuitBreakerConfig {
2125
+ /** Consecutive failures before tripping. Default: 3 */
2126
+ failureThreshold?: number;
2127
+ /** Consecutive successes in HALF_OPEN before closing. Default: 2 */
2128
+ successThreshold?: number;
2129
+ /** Seconds in OPEN before allowing a probe request. Default: 30 */
2130
+ recoveryTimeoutSeconds?: number;
2131
+ /** Window in seconds for error-rate calculation. Default: 120 */
2132
+ errorRateWindow?: number;
2133
+ /** Error rate threshold (0–1) to trigger OPEN. Default: 0.5 */
2134
+ errorRateThreshold?: number;
2135
+ }
2136
+ interface WorkerCircuit {
2137
+ workerId: string;
2138
+ state: CircuitState;
2139
+ consecutiveFailures: number;
2140
+ consecutiveSuccesses: number;
2141
+ totalRequests: number;
2142
+ totalFailures: number;
2143
+ lastFailureTime: number;
2144
+ openedAt: number;
2145
+ lastTransitionTime: number;
2146
+ /** Sliding window of (timestamp, success) pairs. */
2147
+ recent: Array<{
2148
+ timestamp: number;
2149
+ success: boolean;
2150
+ }>;
2151
+ }
2152
+ declare class CircuitBreaker {
2153
+ private readonly circuits;
2154
+ private readonly config;
2155
+ private readonly auditLog?;
2156
+ constructor(config?: CircuitBreakerConfig, auditLog?: AuditLog);
2157
+ private getOrCreate;
2158
+ /** Compute error rate for the worker within the configured window. Prunes stale entries. */
2159
+ private errorRate;
2160
+ private transition;
2161
+ /**
2162
+ * Check whether the worker is allowed to proceed.
2163
+ * - CLOSED: always allowed
2164
+ * - OPEN: blocked until recovery timeout, then transitions to HALF_OPEN
2165
+ * - HALF_OPEN: probe allowed through
2166
+ */
2167
+ allow(workerId: string): boolean;
2168
+ recordSuccess(workerId: string): void;
2169
+ recordFailure(workerId: string): void;
2170
+ getState(workerId: string): CircuitState;
2171
+ getStats(workerId: string): Pick<WorkerCircuit, 'state' | 'consecutiveFailures' | 'totalRequests' | 'totalFailures'>;
2172
+ }
2173
+
2174
+ /**
2175
+ * SandboxExecutor — V8 isolate-based sandboxed code execution.
2176
+ *
2177
+ * Uses `isolated-vm` to run untrusted code in a separate V8 context
2178
+ * with configurable memory and time limits. Stronger isolation than
2179
+ * Node.js `vm` module (separate heap, no shared references).
2180
+ *
2181
+ * This is an Almadar-specific addition to the IC-AGI security layer.
2182
+ * It will be contributed to almadar-io/ic-agi as an optional module.
2183
+ */
2184
+ interface SandboxOptions {
2185
+ /** Execution timeout in milliseconds. Default: 5000 */
2186
+ timeoutMs?: number;
2187
+ /** Memory limit for the isolate in MB. Default: 32 */
2188
+ memoryLimitMb?: number;
2189
+ }
2190
+ interface SandboxResult {
2191
+ success: boolean;
2192
+ value?: unknown;
2193
+ error?: string;
2194
+ timedOut?: boolean;
2195
+ }
2196
+ /**
2197
+ * Execute a JavaScript code string inside a V8 isolate.
2198
+ *
2199
+ * The `inputs` object is copied into the isolate as a global `inputs` variable.
2200
+ * The code should return a value or assign to a global `result` variable.
2201
+ *
2202
+ * Falls back gracefully if `isolated-vm` is not available in the environment.
2203
+ */
2204
+ declare function executeSandboxed(code: string, inputs?: Record<string, unknown>, options?: SandboxOptions): Promise<SandboxResult>;
2205
+
2206
+ 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, type LLMProvider, MCPClient, type MCPClientConfig, MCPClientManager, type MCPDiscoveryRequest, type MCPDiscoveryResponse, MCPResourceRegistry, MCPServer, type MCPServerConfig, MCPToolRegistry, MemoryManager, MetricsCollector, type MetricsSummary, ModelRouter, type ModelRouterConfig, MultiUserManager, ObservabilityCollector, type ObservableEvent, type ObservableEventType, OnlineEvalSampler, type CombinerOptions as OrbitalCombinerOptions, type CombinerResult as OrbitalCombinerResult, type OrbitalEstimation, type OrbitalSchemaValidationResult, type ParallelExecutionResult, type PerformanceSnapshot, type PreferenceAnalysis, PreferenceLearner, type PreferenceLearnerOptions, type ProviderConfig, QwenCircuitBreaker, type RateLimitConfig, RateLimiter, type RegisteredMCPServer, type ResourceDefinition, type ResourceRequest, type ResourceResponse, type ReviewOptions, type RouteConfig, type RoutingDecision, type RoutingStrategy, 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 ToolCallRequest, type ToolCallResponse, type ToolDefinition, type ToolExecutor, type ToolStep, type ToolStepStatus, type UserContext, UserPreference, type UserSessionStats, type VersionVector, type VoteResult, WorkflowBuilder, type WorkflowContext, type WorkflowDefinition, WorkflowEngine, type WorkflowExecutionResult, analyzeFailures, applyConservativeBias, classifyComplexity, combineOrbitals, combineOrbitalsToSchema, consumeToken, createAgenticSearchEngine, createAlmadarMCPServer, createDefaultMCPClientManager, createErrorFixerSubagent, createMCPClient, createMCPClientManager, createMCPServer, createModelRouter, createOnlineEvalSampler, createPreferenceLearner, createSchemaGenerationWorkflow, createSchemaGeneratorSubagent, createSubagentConfigs, createSubagents, createTestAnalyzerSubagent, createUserContext, createWorkflowEngine, debounceSync, endObservabilitySession, estimateCacheSavings, estimateCombineComplexity, estimateComplexity, estimateOrbitalCount, estimateOrbitalCountBatch, estimateOrbitalCountHeuristic, estimateOrbitalCountLLM, executeSandboxed, formatSummary, generateFullOrbital, getCircuitBreaker, getExecutionStrategy, getModelRouter, getMultiUserManager, getObservabilityCollector, getPerformanceSnapshot, getStateSyncManager, hasDefiniteComplexIndicators, isAdmin, isCompleteEvent, isErrorEvent, isExecutionEvent, isSchemaEvent, isStartEvent, isTokenValid, issueToken, makeSafeRoutingDecision, parseDeepAgentEvent, quickComplexityCheck, quickEstimate, recordEvent, requireOwnership, resetMultiUserManager, resetObservabilityCollector, resetStateSyncManager, reviewSamples, revokeToken, routeGeneration, safeEstimate, startObservabilitySession, verifyToken, withSync };