-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAxonFlow.java
More file actions
6534 lines (5873 loc) · 232 KB
/
AxonFlow.java
File metadata and controls
6534 lines (5873 loc) · 232 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2025 AxonFlow
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.getaxonflow.sdk;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.getaxonflow.sdk.exceptions.*;
import com.getaxonflow.sdk.masfeat.MASFEATTypes.*;
import com.getaxonflow.sdk.simulation.*;
import com.getaxonflow.sdk.telemetry.TelemetryReporter;
import com.getaxonflow.sdk.types.*;
import com.getaxonflow.sdk.types.codegovernance.*;
import com.getaxonflow.sdk.types.costcontrols.CostControlTypes.*;
import com.getaxonflow.sdk.types.executionreplay.ExecutionReplayTypes.*;
import com.getaxonflow.sdk.types.hitl.HITLTypes.*;
import com.getaxonflow.sdk.types.policies.PolicyTypes.*;
import com.getaxonflow.sdk.types.webhook.WebhookTypes.*;
import com.getaxonflow.sdk.util.*;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.function.Consumer;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main client for interacting with the AxonFlow API.
*
* <p>The AxonFlow client provides methods for:
*
* <ul>
* <li><strong>Gateway Mode:</strong> Pre-check and audit for your own LLM calls
* <li><strong>Proxy Mode:</strong> Let AxonFlow handle policy and LLM routing
* <li><strong>Planning:</strong> Multi-agent planning (MAP) operations
* <li><strong>Connectors:</strong> MCP connector discovery and queries
* </ul>
*
* <h2>Gateway Mode Example</h2>
*
* <pre>{@code
* AxonFlow axonflow = AxonFlow.builder()
* .agentUrl("http://localhost:8080")
* .clientId("my-client")
* .clientSecret("my-secret")
* .build();
*
* // Step 1: Pre-check
* PolicyApprovalResult approval = axonflow.getPolicyApprovedContext(
* PolicyApprovalRequest.builder()
* .userToken("user-123")
* .query("What is the weather?")
* .build());
*
* if (approval.isApproved()) {
* // Step 2: Make your LLM call
* // ... call OpenAI/Anthropic directly ...
*
* // Step 3: Audit
* axonflow.auditLLMCall(AuditOptions.builder()
* .contextId(approval.getContextId())
* .provider("openai")
* .model("gpt-4")
* .tokenUsage(TokenUsage.of(100, 150))
* .latencyMs(1234)
* .build());
* }
* }</pre>
*
* <h2>Proxy Mode Example</h2>
*
* <pre>{@code
* ClientResponse response = axonflow.proxyLLMCall(
* ClientRequest.builder()
* .query("What is the weather?")
* .userToken("user-123")
* .llmProvider("openai")
* .model("gpt-4")
* .build());
*
* if (response.isSuccess() && !response.isBlocked()) {
* System.out.println(response.getData());
* }
* }</pre>
*
* @see AxonFlowConfig
* @see PolicyApprovalRequest
* @see ClientRequest
*/
public final class AxonFlow implements Closeable {
private static final Logger logger = LoggerFactory.getLogger(AxonFlow.class);
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private final AxonFlowConfig config;
private final OkHttpClient httpClient;
private final ObjectMapper objectMapper;
private final RetryExecutor retryExecutor;
private final ResponseCache cache;
private final Executor asyncExecutor;
private volatile String sessionCookie; // Session cookie for Customer Portal authentication
private final MASFEATNamespace masfeatNamespace;
private AxonFlow(AxonFlowConfig config) {
this.config = Objects.requireNonNull(config, "config cannot be null");
// Reject clientSecret without clientId — licensed mode must specify tenant
if (config.getClientSecret() != null
&& !config.getClientSecret().isEmpty()
&& (config.getClientId() == null || config.getClientId().isEmpty())) {
throw new ConfigurationException(
"clientId is required when clientSecret is set. "
+ "Set clientId to your tenant identity to avoid data being stored under the wrong tenant.",
"clientId");
}
this.httpClient = HttpClientFactory.create(config);
this.objectMapper = createObjectMapper();
this.retryExecutor = new RetryExecutor(config.getRetryConfig());
this.cache = new ResponseCache(config.getCacheConfig());
this.asyncExecutor = ForkJoinPool.commonPool();
this.masfeatNamespace = new MASFEATNamespace();
logger.info("AxonFlow client initialized for {}", config.getEndpoint());
// Send telemetry ping (fire-and-forget).
boolean hasCredentials =
config.getClientId() != null
&& !config.getClientId().isEmpty()
&& config.getClientSecret() != null
&& !config.getClientSecret().isEmpty();
TelemetryReporter.sendPing(
config.getMode() != null ? config.getMode().getValue() : "production",
config.getEndpoint(),
config.getTelemetry(),
config.isDebug(),
hasCredentials);
}
private static ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
return mapper;
}
/**
* Compares two semantic version strings numerically (major.minor.patch). Returns negative if a <
* b, zero if equal, positive if a > b.
*/
private static int compareSemver(String a, String b) {
String[] partsA = a.split("\\.");
String[] partsB = b.split("\\.");
int length = Math.max(partsA.length, partsB.length);
for (int i = 0; i < length; i++) {
int numA = 0;
int numB = 0;
if (i < partsA.length) {
try {
String cleanA =
partsA[i].contains("-") ? partsA[i].substring(0, partsA[i].indexOf("-")) : partsA[i];
numA = Integer.parseInt(cleanA);
} catch (NumberFormatException ignored) {
// default to 0
}
}
if (i < partsB.length) {
try {
String cleanB =
partsB[i].contains("-") ? partsB[i].substring(0, partsB[i].indexOf("-")) : partsB[i];
numB = Integer.parseInt(cleanB);
} catch (NumberFormatException ignored) {
// default to 0
}
}
if (numA != numB) {
return Integer.compare(numA, numB);
}
}
return 0;
}
// ========================================================================
// Factory Methods
// ========================================================================
/**
* Creates a new builder for AxonFlow configuration.
*
* @return a new builder
*/
public static AxonFlowConfig.Builder builder() {
return AxonFlowConfig.builder();
}
/**
* Creates an AxonFlow client with the given configuration.
*
* @param config the configuration
* @return a new AxonFlow client
*/
public static AxonFlow create(AxonFlowConfig config) {
return new AxonFlow(config);
}
/**
* Creates an AxonFlow client from environment variables.
*
* @return a new AxonFlow client
* @see AxonFlowConfig#fromEnvironment()
*/
public static AxonFlow fromEnvironment() {
return new AxonFlow(AxonFlowConfig.fromEnvironment());
}
/**
* Creates an AxonFlow client in sandbox mode.
*
* @param agentUrl the Agent URL
* @return a new AxonFlow client in sandbox mode
*/
public static AxonFlow sandbox(String agentUrl) {
return new AxonFlow(AxonFlowConfig.builder().agentUrl(agentUrl).mode(Mode.SANDBOX).build());
}
// ========================================================================
// Health Check
// ========================================================================
/**
* Checks if the AxonFlow Agent is healthy.
*
* @return the health status
* @throws ConnectionException if the Agent cannot be reached
*/
public HealthStatus healthCheck() {
HealthStatus status =
retryExecutor.execute(
() -> {
Request request = buildRequest("GET", "/health", null);
try (Response response = httpClient.newCall(request).execute()) {
return parseResponse(response, HealthStatus.class);
}
},
"healthCheck");
if (status.getSdkCompatibility() != null
&& status.getSdkCompatibility().getMinSdkVersion() != null
&& !"unknown".equals(AxonFlowConfig.SDK_VERSION)
&& compareSemver(
AxonFlowConfig.SDK_VERSION, status.getSdkCompatibility().getMinSdkVersion())
< 0) {
logger.warn(
"SDK version {} is below minimum supported version {}. Please upgrade.",
AxonFlowConfig.SDK_VERSION,
status.getSdkCompatibility().getMinSdkVersion());
}
return status;
}
/**
* Asynchronously checks if the AxonFlow Agent is healthy.
*
* @return a future containing the health status
*/
public CompletableFuture<HealthStatus> healthCheckAsync() {
return CompletableFuture.supplyAsync(this::healthCheck, asyncExecutor);
}
// ========================================================================
// MAS FEAT Namespace Accessor
// ========================================================================
/**
* Returns the MAS FEAT (Monetary Authority of Singapore - Fairness, Ethics, Accountability,
* Transparency) compliance namespace.
*
* <p><b>Enterprise Feature:</b> Requires AxonFlow Enterprise license.
*
* <p>Example usage:
*
* <pre>{@code
* AISystemRegistry system = client.masfeat().registerSystem(
* RegisterSystemRequest.builder()
* .systemId("credit-scoring-ai")
* .systemName("Credit Scoring AI")
* .useCase(AISystemUseCase.CREDIT_SCORING)
* .ownerTeam("Risk Management")
* .customerImpact(4)
* .modelComplexity(3)
* .humanReliance(5)
* .build()
* );
* }</pre>
*
* @return the MAS FEAT compliance namespace
*/
public MASFEATNamespace masfeat() {
return masfeatNamespace;
}
/**
* Checks if the AxonFlow Orchestrator is healthy.
*
* @return the health status
* @throws ConnectionException if the Orchestrator cannot be reached
*/
public HealthStatus orchestratorHealthCheck() {
return retryExecutor.execute(
() -> {
Request httpRequest = buildOrchestratorRequest("GET", "/health", null);
try (Response response = httpClient.newCall(httpRequest).execute()) {
if (!response.isSuccessful()) {
return new HealthStatus("unhealthy", null, null, null, null, null);
}
return parseResponse(response, HealthStatus.class);
}
},
"orchestratorHealthCheck");
}
/**
* Asynchronously checks if the AxonFlow Orchestrator is healthy.
*
* @return a future containing the health status
*/
public CompletableFuture<HealthStatus> orchestratorHealthCheckAsync() {
return CompletableFuture.supplyAsync(this::orchestratorHealthCheck, asyncExecutor);
}
// ========================================================================
// Gateway Mode - Policy Pre-check and Audit
// ========================================================================
/**
* Pre-checks a request against policies (Gateway Mode - Step 1).
*
* <p>This is the first step in Gateway Mode. If approved, make your LLM call directly, then call
* {@link #auditLLMCall(AuditOptions)} to complete the flow.
*
* @param request the policy approval request
* @return the approval result with context ID for auditing
* @throws PolicyViolationException if the request is blocked by policy
* @throws AuthenticationException if authentication fails
*/
public PolicyApprovalResult getPolicyApprovedContext(PolicyApprovalRequest request) {
Objects.requireNonNull(request, "request cannot be null");
// Use smart default for clientId - enables zero-config community mode
String effectiveClientId =
(request.getClientId() != null && !request.getClientId().isEmpty())
? request.getClientId()
: getEffectiveClientId();
Map<String, Object> ctx = request.getContext();
PolicyApprovalRequest effectiveRequest =
PolicyApprovalRequest.builder()
.userToken(request.getUserToken())
.query(request.getQuery())
.dataSources(request.getDataSources())
.context(ctx == null || ctx.isEmpty() ? null : ctx)
.clientId(effectiveClientId)
.build();
final PolicyApprovalRequest finalRequest = effectiveRequest;
return retryExecutor.execute(
() -> {
Request httpRequest = buildRequest("POST", "/api/policy/pre-check", finalRequest);
try (Response response = httpClient.newCall(httpRequest).execute()) {
PolicyApprovalResult result = parseResponse(response, PolicyApprovalResult.class);
if (!result.isApproved()) {
throw new PolicyViolationException(
result.getBlockReason(), result.getBlockingPolicyName(), result.getPolicies());
}
return result;
}
},
"getPolicyApprovedContext");
}
/**
* Alias for {@link #getPolicyApprovedContext(PolicyApprovalRequest)}.
*
* @param request the policy approval request
* @return the approval result
*/
public PolicyApprovalResult preCheck(PolicyApprovalRequest request) {
return getPolicyApprovedContext(request);
}
/**
* Asynchronously pre-checks a request against policies.
*
* @param request the policy approval request
* @return a future containing the approval result
*/
public CompletableFuture<PolicyApprovalResult> getPolicyApprovedContextAsync(
PolicyApprovalRequest request) {
return CompletableFuture.supplyAsync(() -> getPolicyApprovedContext(request), asyncExecutor);
}
/**
* Audits an LLM call for compliance tracking (Gateway Mode - Step 3).
*
* <p>Call this after making your direct LLM call to record it for compliance and observability.
*
* @param options the audit options including context ID from pre-check
* @return the audit result
* @throws AxonFlowException if the audit fails
*/
public AuditResult auditLLMCall(AuditOptions options) {
Objects.requireNonNull(options, "options cannot be null");
// Use smart default for clientId - enables zero-config community mode
String effectiveClientId =
(options.getClientId() != null && !options.getClientId().isEmpty())
? options.getClientId()
: getEffectiveClientId();
// Create effective options with the smart default clientId
AuditOptions.Builder builder =
AuditOptions.builder()
.contextId(options.getContextId())
.clientId(effectiveClientId)
.responseSummary(options.getResponseSummary())
.provider(options.getProvider())
.model(options.getModel())
.tokenUsage(options.getTokenUsage())
.metadata(options.getMetadata())
.success(options.getSuccess())
.errorMessage(options.getErrorMessage());
// Handle null latencyMs (builder takes primitive long)
if (options.getLatencyMs() != null) {
builder.latencyMs(options.getLatencyMs());
}
AuditOptions effectiveOptions = builder.build();
return retryExecutor.execute(
() -> {
Request httpRequest = buildRequest("POST", "/api/audit/llm-call", effectiveOptions);
try (Response response = httpClient.newCall(httpRequest).execute()) {
return parseResponse(response, AuditResult.class);
}
},
"auditLLMCall");
}
/**
* Asynchronously audits an LLM call.
*
* @param options the audit options
* @return a future containing the audit result
*/
public CompletableFuture<AuditResult> auditLLMCallAsync(AuditOptions options) {
return CompletableFuture.supplyAsync(() -> auditLLMCall(options), asyncExecutor);
}
// ========================================================================
// Audit Log Read Methods
// ========================================================================
/**
* Searches audit logs with flexible filtering options.
*
* <p>Example usage:
*
* <pre>{@code
* AuditSearchResponse response = axonflow.searchAuditLogs(
* AuditSearchRequest.builder()
* .userEmail("analyst@company.com")
* .startTime(Instant.now().minus(Duration.ofDays(7)))
* .requestType("llm_chat")
* .limit(100)
* .build());
*
* for (AuditLogEntry entry : response.getEntries()) {
* System.out.println(entry.getId() + ": " + entry.getQuerySummary());
* }
* }</pre>
*
* @param request the search request with optional filters
* @return the search response containing matching audit log entries
* @throws AxonFlowException if the search fails
*/
public AuditSearchResponse searchAuditLogs(AuditSearchRequest request) {
return retryExecutor.execute(
() -> {
AuditSearchRequest req = request != null ? request : AuditSearchRequest.builder().build();
Request httpRequest = buildOrchestratorRequest("POST", "/api/v1/audit/search", req);
try (Response response = httpClient.newCall(httpRequest).execute()) {
JsonNode node = parseResponseNode(response);
// Handle both array and wrapped response formats
if (node.isArray()) {
List<AuditLogEntry> entries =
objectMapper.convertValue(node, new TypeReference<List<AuditLogEntry>>() {});
return AuditSearchResponse.fromArray(
entries,
req.getLimit() != null ? req.getLimit() : 100,
req.getOffset() != null ? req.getOffset() : 0);
}
return objectMapper.treeToValue(node, AuditSearchResponse.class);
}
},
"searchAuditLogs");
}
/**
* Searches audit logs with default options (last 100 entries).
*
* @return the search response
*/
public AuditSearchResponse searchAuditLogs() {
return searchAuditLogs(null);
}
/**
* Asynchronously searches audit logs.
*
* @param request the search request
* @return a future containing the search response
*/
public CompletableFuture<AuditSearchResponse> searchAuditLogsAsync(AuditSearchRequest request) {
return CompletableFuture.supplyAsync(() -> searchAuditLogs(request), asyncExecutor);
}
/**
* Gets audit logs for a specific tenant.
*
* <p>Example usage:
*
* <pre>{@code
* AuditSearchResponse response = axonflow.getAuditLogsByTenant("tenant-abc",
* AuditQueryOptions.builder()
* .limit(100)
* .offset(50)
* .build());
*
* System.out.println("Total entries: " + response.getTotal());
* System.out.println("Has more: " + response.hasMore());
* }</pre>
*
* @param tenantId the tenant ID to query
* @param options optional pagination options
* @return the search response containing audit log entries for the tenant
* @throws IllegalArgumentException if tenantId is null or empty
* @throws AxonFlowException if the query fails
*/
public AuditSearchResponse getAuditLogsByTenant(String tenantId, AuditQueryOptions options) {
if (tenantId == null || tenantId.isEmpty()) {
throw new IllegalArgumentException("tenantId is required");
}
return retryExecutor.execute(
() -> {
AuditQueryOptions opts = options != null ? options : AuditQueryOptions.defaults();
String encodedTenantId = java.net.URLEncoder.encode(tenantId, "UTF-8");
String path =
"/api/v1/audit/tenant/"
+ encodedTenantId
+ "?limit="
+ opts.getLimit()
+ "&offset="
+ opts.getOffset();
Request httpRequest = buildOrchestratorRequest("GET", path, null);
try (Response response = httpClient.newCall(httpRequest).execute()) {
JsonNode node = parseResponseNode(response);
// Handle both array and wrapped response formats
if (node.isArray()) {
List<AuditLogEntry> entries =
objectMapper.convertValue(node, new TypeReference<List<AuditLogEntry>>() {});
return AuditSearchResponse.fromArray(entries, opts.getLimit(), opts.getOffset());
}
return objectMapper.treeToValue(node, AuditSearchResponse.class);
}
},
"getAuditLogsByTenant");
}
/**
* Gets audit logs for a specific tenant with default options.
*
* @param tenantId the tenant ID to query
* @return the search response
*/
public AuditSearchResponse getAuditLogsByTenant(String tenantId) {
return getAuditLogsByTenant(tenantId, null);
}
/**
* Asynchronously gets audit logs for a specific tenant.
*
* @param tenantId the tenant ID to query
* @param options optional pagination options
* @return a future containing the search response
*/
public CompletableFuture<AuditSearchResponse> getAuditLogsByTenantAsync(
String tenantId, AuditQueryOptions options) {
return CompletableFuture.supplyAsync(
() -> getAuditLogsByTenant(tenantId, options), asyncExecutor);
}
// ========================================================================
// Audit Tool Call
// ========================================================================
/**
* Audits a non-LLM tool call for compliance and observability.
*
* <p>Records tool invocations such as function calls, MCP operations, or API calls to the audit
* log.
*
* <p>Example usage:
*
* <pre>{@code
* AuditToolCallResponse response = axonflow.auditToolCall(
* AuditToolCallRequest.builder()
* .toolName("web_search")
* .toolType("function")
* .input(Map.of("query", "latest news"))
* .output(Map.of("results", 5))
* .workflowId("wf_123")
* .durationMs(450L)
* .success(true)
* .build());
* }</pre>
*
* @param request the audit tool call request
* @return the audit tool call response with audit ID
* @throws NullPointerException if request is null
* @throws IllegalArgumentException if tool_name is null or empty
* @throws AxonFlowException if the audit fails
*/
public AuditToolCallResponse auditToolCall(AuditToolCallRequest request) {
Objects.requireNonNull(request, "request cannot be null");
return retryExecutor.execute(
() -> {
Request httpRequest =
buildOrchestratorRequest("POST", "/api/v1/audit/tool-call", request);
try (Response response = httpClient.newCall(httpRequest).execute()) {
return parseResponse(response, AuditToolCallResponse.class);
}
},
"auditToolCall");
}
/**
* Asynchronously audits a non-LLM tool call.
*
* @param request the audit tool call request
* @return a future containing the audit tool call response
*/
public CompletableFuture<AuditToolCallResponse> auditToolCallAsync(AuditToolCallRequest request) {
return CompletableFuture.supplyAsync(() -> auditToolCall(request), asyncExecutor);
}
// ========================================================================
// Circuit Breaker Observability
// ========================================================================
/**
* Gets the current circuit breaker status, including all active (tripped) circuits.
*
* <p>Example usage:
*
* <pre>{@code
* CircuitBreakerStatusResponse status = axonflow.getCircuitBreakerStatus();
* System.out.println("Active circuits: " + status.getCount());
* System.out.println("Emergency stop: " + status.isEmergencyStopActive());
* }</pre>
*
* @return the circuit breaker status
* @throws AxonFlowException if the request fails
*/
public CircuitBreakerStatusResponse getCircuitBreakerStatus() {
return retryExecutor.execute(
() -> {
Request httpRequest =
buildOrchestratorRequest("GET", "/api/v1/circuit-breaker/status", null);
try (Response response = httpClient.newCall(httpRequest).execute()) {
JsonNode node = parseResponseNode(response);
if (node.has("data") && node.get("data").isObject()) {
return objectMapper.treeToValue(node.get("data"), CircuitBreakerStatusResponse.class);
}
return objectMapper.treeToValue(node, CircuitBreakerStatusResponse.class);
}
},
"getCircuitBreakerStatus");
}
/**
* Asynchronously gets the current circuit breaker status.
*
* @return a future containing the circuit breaker status
*/
public CompletableFuture<CircuitBreakerStatusResponse> getCircuitBreakerStatusAsync() {
return CompletableFuture.supplyAsync(this::getCircuitBreakerStatus, asyncExecutor);
}
/**
* Gets the circuit breaker history, including past trips and resets.
*
* <p>Example usage:
*
* <pre>{@code
* CircuitBreakerHistoryResponse history = axonflow.getCircuitBreakerHistory(50);
* for (CircuitBreakerHistoryEntry entry : history.getHistory()) {
* System.out.println(entry.getScope() + "/" + entry.getScopeId() + " - " + entry.getState());
* }
* }</pre>
*
* @param limit the maximum number of history entries to return
* @return the circuit breaker history
* @throws IllegalArgumentException if limit is less than 1
* @throws AxonFlowException if the request fails
*/
public CircuitBreakerHistoryResponse getCircuitBreakerHistory(int limit) {
if (limit < 1) {
throw new IllegalArgumentException("limit must be at least 1");
}
return retryExecutor.execute(
() -> {
String path = "/api/v1/circuit-breaker/history?limit=" + limit;
Request httpRequest = buildOrchestratorRequest("GET", path, null);
try (Response response = httpClient.newCall(httpRequest).execute()) {
JsonNode node = parseResponseNode(response);
if (node.has("data") && node.get("data").isObject()) {
return objectMapper.treeToValue(
node.get("data"), CircuitBreakerHistoryResponse.class);
}
return objectMapper.treeToValue(node, CircuitBreakerHistoryResponse.class);
}
},
"getCircuitBreakerHistory");
}
/**
* Asynchronously gets the circuit breaker history.
*
* @param limit the maximum number of history entries to return
* @return a future containing the circuit breaker history
*/
public CompletableFuture<CircuitBreakerHistoryResponse> getCircuitBreakerHistoryAsync(int limit) {
return CompletableFuture.supplyAsync(() -> getCircuitBreakerHistory(limit), asyncExecutor);
}
/**
* Gets the circuit breaker configuration for a specific tenant.
*
* <p>Example usage:
*
* <pre>{@code
* CircuitBreakerConfig config = axonflow.getCircuitBreakerConfig("tenant_123");
* System.out.println("Error threshold: " + config.getErrorThreshold());
* System.out.println("Auto recovery: " + config.isEnableAutoRecovery());
* }</pre>
*
* @param tenantId the tenant ID to get configuration for
* @return the circuit breaker configuration
* @throws NullPointerException if tenantId is null
* @throws IllegalArgumentException if tenantId is empty
* @throws AxonFlowException if the request fails
*/
public CircuitBreakerConfig getCircuitBreakerConfig(String tenantId) {
Objects.requireNonNull(tenantId, "tenantId cannot be null");
if (tenantId.isEmpty()) {
throw new IllegalArgumentException("tenantId cannot be empty");
}
return retryExecutor.execute(
() -> {
String path =
"/api/v1/circuit-breaker/config?tenant_id="
+ java.net.URLEncoder.encode(tenantId, java.nio.charset.StandardCharsets.UTF_8);
Request httpRequest = buildOrchestratorRequest("GET", path, null);
try (Response response = httpClient.newCall(httpRequest).execute()) {
JsonNode node = parseResponseNode(response);
if (node.has("data") && node.get("data").isObject()) {
return objectMapper.treeToValue(node.get("data"), CircuitBreakerConfig.class);
}
return objectMapper.treeToValue(node, CircuitBreakerConfig.class);
}
},
"getCircuitBreakerConfig");
}
/**
* Asynchronously gets the circuit breaker configuration for a specific tenant.
*
* @param tenantId the tenant ID to get configuration for
* @return a future containing the circuit breaker configuration
*/
public CompletableFuture<CircuitBreakerConfig> getCircuitBreakerConfigAsync(String tenantId) {
return CompletableFuture.supplyAsync(() -> getCircuitBreakerConfig(tenantId), asyncExecutor);
}
/**
* Updates the circuit breaker configuration for a tenant.
*
* <p>Example usage:
*
* <pre>{@code
* CircuitBreakerConfig updated = axonflow.updateCircuitBreakerConfig(
* CircuitBreakerConfigUpdate.builder()
* .tenantId("tenant_123")
* .errorThreshold(10)
* .violationThreshold(5)
* .enableAutoRecovery(true)
* .build());
* }</pre>
*
* @param config the configuration update
* @return confirmation with tenant_id and message
* @throws NullPointerException if config is null
* @throws AxonFlowException if the request fails
*/
public CircuitBreakerConfigUpdateResponse updateCircuitBreakerConfig(
CircuitBreakerConfigUpdate config) {
Objects.requireNonNull(config, "config cannot be null");
return retryExecutor.execute(
() -> {
Request httpRequest =
buildOrchestratorRequest("PUT", "/api/v1/circuit-breaker/config", config);
try (Response response = httpClient.newCall(httpRequest).execute()) {
JsonNode node = parseResponseNode(response);
if (node.has("data") && node.get("data").isObject()) {
return objectMapper.treeToValue(
node.get("data"), CircuitBreakerConfigUpdateResponse.class);
}
return objectMapper.treeToValue(node, CircuitBreakerConfigUpdateResponse.class);
}
},
"updateCircuitBreakerConfig");
}
/**
* Asynchronously updates the circuit breaker configuration for a tenant.
*
* @param config the configuration update
* @return a future containing the update confirmation
*/
public CompletableFuture<CircuitBreakerConfigUpdateResponse> updateCircuitBreakerConfigAsync(
CircuitBreakerConfigUpdate config) {
return CompletableFuture.supplyAsync(() -> updateCircuitBreakerConfig(config), asyncExecutor);
}
// ========================================================================
// Policy Simulation
// ========================================================================
/**
* Simulates policy evaluation against a query without actually enforcing policies.
*
* <p>This is a dry-run mode that shows which policies would match and what actions would be
* taken, without blocking the request.
*
* <p>Example usage:
*
* <pre>{@code
* SimulatePoliciesResponse result = axonflow.simulatePolicies(
* SimulatePoliciesRequest.builder()
* .query("Transfer $50,000 to external account")
* .requestType("execute")
* .build());
* System.out.println("Allowed: " + result.isAllowed());
* System.out.println("Applied policies: " + result.getAppliedPolicies());
* System.out.println("Risk score: " + result.getRiskScore());
* }</pre>
*
* <p><b>Evaluation+ Feature:</b> Requires AxonFlow Evaluation tier or higher.
*
* @param request the simulation request
* @return the simulation result
* @throws NullPointerException if request is null
* @throws AxonFlowException if the request fails
*/
public SimulatePoliciesResponse simulatePolicies(SimulatePoliciesRequest request) {
Objects.requireNonNull(request, "request cannot be null");
return retryExecutor.execute(
() -> {
Request httpRequest =
buildOrchestratorRequest("POST", "/api/v1/policies/simulate", request);
try (Response response = httpClient.newCall(httpRequest).execute()) {
JsonNode node = parseResponseNode(response);
if (node.has("data") && node.get("data").isObject()) {
return objectMapper.treeToValue(node.get("data"), SimulatePoliciesResponse.class);
}
return objectMapper.treeToValue(node, SimulatePoliciesResponse.class);
}
},
"simulatePolicies");
}
/**
* Asynchronously simulates policy evaluation against a query.
*
* @param request the simulation request
* @return a future containing the simulation result
*/
public CompletableFuture<SimulatePoliciesResponse> simulatePoliciesAsync(
SimulatePoliciesRequest request) {
return CompletableFuture.supplyAsync(() -> simulatePolicies(request), asyncExecutor);
}
/**
* Generates a policy impact report by testing a set of inputs against a specific policy.
*
* <p>This helps you understand how a policy would affect real traffic before deploying it.
*
* <p>Example usage:
*
* <pre>{@code
* ImpactReportResponse report = axonflow.getPolicyImpactReport(
* ImpactReportRequest.builder()
* .policyId("policy_block_pii")
* .inputs(List.of(
* ImpactReportInput.builder().query("My SSN is 123-45-6789").build(),
* ImpactReportInput.builder().query("What is the weather?").build()))
* .build());
* System.out.println("Match rate: " + report.getMatchRate());
* System.out.println("Block rate: " + report.getBlockRate());
* }</pre>
*
* <p><b>Evaluation+ Feature:</b> Requires AxonFlow Evaluation tier or higher.
*
* @param request the impact report request
* @return the impact report
* @throws NullPointerException if request is null
* @throws AxonFlowException if the request fails
*/
public ImpactReportResponse getPolicyImpactReport(ImpactReportRequest request) {
Objects.requireNonNull(request, "request cannot be null");
return retryExecutor.execute(
() -> {
Request httpRequest =
buildOrchestratorRequest("POST", "/api/v1/policies/impact-report", request);
try (Response response = httpClient.newCall(httpRequest).execute()) {
JsonNode node = parseResponseNode(response);
if (node.has("data") && node.get("data").isObject()) {
return objectMapper.treeToValue(node.get("data"), ImpactReportResponse.class);
}
return objectMapper.treeToValue(node, ImpactReportResponse.class);
}
},
"getPolicyImpactReport");
}
/**
* Asynchronously generates a policy impact report.
*
* @param request the impact report request
* @return a future containing the impact report
*/
public CompletableFuture<ImpactReportResponse> getPolicyImpactReportAsync(