-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAxonFlow.java
More file actions
7665 lines (6938 loc) · 280 KB
/
Copy pathAxonFlow.java
File metadata and controls
7665 lines (6938 loc) · 280 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.HeartbeatState;
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.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ThreadFactory;
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");
// Single-threaded daemon executor for async heartbeat dispatch from the
// request hot path. Bounded to one worker so concurrent gate calls land
// serially on the gate's mutex (the gate itself coalesces them via
// in-flight + 1-hour cache). Daemon thread never blocks JVM exit.
// Static so 10k req/s creates 0 extra threads — the alternative
// (`new Thread()` per request) costs ~1ms per spawn at scale.
private static final ExecutorService HEARTBEAT_EXECUTOR =
Executors.newSingleThreadExecutor(
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "axonflow-heartbeat");
t.setDaemon(true);
return t;
}
});
private final AxonFlowConfig config;
private final OkHttpClient httpClient;
// Telemetry heartbeat is process-global — see HeartbeatState.shared().
// No instance field here on purpose: concurrent AxonFlow constructions
// on the same JVM must coalesce onto a single ping per
// heartbeatInterval, which requires a shared singleton, not a per-
// instance gate. Access via {@link #invokeHeartbeat()}.
/**
* Clone of {@link #httpClient} with {@code callTimeout} overridden to {@code
* config.getMapTimeout()}. Used for every plan-lifecycle call (generate, execute, get, update,
* cancel, resume, rollback) where a single call may outlive the default request timeout. MAP
* plans chain multiple LLM calls end-to-end and commonly take 60-120s; the global timeout
* (default 60s) would cut them off. Shares the connection pool, interceptors, and dispatcher with
* {@link #httpClient} — only the call-timeout attribute differs.
*/
private final OkHttpClient planHttpClient;
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.planHttpClient =
this.httpClient
.newBuilder()
.callTimeout(
config.getMapTimeout().toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS)
.readTimeout(
config.getMapTimeout().toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS)
.writeTimeout(
config.getMapTimeout().toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS)
.build();
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());
// Heartbeat gate — at most one anonymous ping per machine per 7 days,
// gated by SDK activity. The constructor runs the gate synchronously
// so a fresh install on a short-lived JVM (CLI binaries, AWS Lambda
// cold-starts, quickstart scripts) still delivers the first ping
// before main() returns. Subsequent gate runs (from executeHttp) are
// dispatched ASYNCHRONOUSLY through a shared single-threaded daemon
// executor so a 3-second telemetry POST never delays a user request.
// See HeartbeatState for the full algorithm.
invokeHeartbeat();
}
/**
* Run the heartbeat gate against the process-global singleton. Constructs the gating decision
* from this client's mode/config, then asks {@link HeartbeatState#shared()} to decide whether to
* send (and to write the stamp on success).
*
* <p>This call is synchronous and bounded by the per-call HTTP timeout (3s) WHEN the gate decides
* to fire. When the gate decides not to fire (typical hot-path case after the first cold-start
* ping), the cost is a single mutex acquire and a {@code System.currentTimeMillis()} comparison.
*
* <p>For the request hot path, see {@link #invokeHeartbeatAsync()}, which delegates to a daemon
* thread so a 3-second firing-block never delays a user API call.
*/
private void invokeHeartbeat() {
String modeStr = config.getMode() != null ? config.getMode().getValue() : "production";
String envOptOut = System.getenv("AXONFLOW_TELEMETRY");
// v8: AXONFLOW_TELEMETRY=off is the SOLE opt-out path. The v7.x mode-based suppression
// and the AxonFlowConfig.telemetry(Boolean) override were both removed. Sandbox-mode
// pings now fire and are tagged stream="sandbox" in the payload.
boolean isEnabled = TelemetryReporter.isEnabled(envOptOut);
HeartbeatState.shared()
.maybeSendHeartbeat(
isEnabled,
() ->
TelemetryReporter.sendPingNow(
modeStr,
config.getEndpoint(),
config.isDebug(),
System.getenv("AXONFLOW_CHECKPOINT_URL")));
}
/**
* Async variant of {@link #invokeHeartbeat()} — dispatches the gate onto {@link
* #HEARTBEAT_EXECUTOR} so a user-facing API call is never delayed by the 3-second telemetry POST
* when the gate decides to fire.
*
* <p>The executor is a single-threaded daemon — concurrent dispatches queue rather than spawning
* threads (10k req/s would otherwise create 10k threads/s pre-fix). The gate's in-flight + 1-hour
* cache means queued runs immediately fast-path past the work, so queue depth is bounded in
* practice.
*
* <p>Daemon thread choice: long-running services have stable JVMs so the executor completes the
* POST normally. Short-lived processes (Lambda cold start, CLI binaries) deliver the boot ping
* via the synchronous {@link #invokeHeartbeat} call from the constructor, so the async
* request-path heartbeat is "extra" — its loss to JVM exit is acceptable and only matters across
* the 7-day boundary.
*/
private void invokeHeartbeatAsync() {
try {
HEARTBEAT_EXECUTOR.execute(this::invokeHeartbeat);
} catch (RuntimeException e) {
// Executor rejected (e.g. shutdown during JVM teardown) — telemetry
// is best-effort; the user request continues unaffected.
logger.debug("heartbeat dispatch rejected", e);
}
}
/**
* Single HTTP wrapper used by every public-API request path. Invokes the heartbeat gate as a side
* effect, ASYNCHRONOUSLY so the user's API call is never delayed by telemetry.
*
* <p>IMPORTANT: This wrapper must NOT be called from telemetry code itself ({@link
* TelemetryReporter#sendPingNow} or its private helpers). Those build their own throw-away {@code
* OkHttpClient} instances to avoid any recursive heartbeat triggering.
*/
private Response executeHttp(OkHttpClient client, Request request) throws java.io.IOException {
invokeHeartbeatAsync();
return client.newCall(request).execute();
}
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 = executeHttp(httpClient, request)) {
return parseResponse(response, HealthStatus.class);
}
},
"healthCheck");
String minJavaVersion =
status.getSdkCompatibility() != null
? status.getSdkCompatibility().getMinSdkVersionFor("java")
: null;
if (minJavaVersion != null
&& !"unknown".equals(AxonFlowConfig.SDK_VERSION)
&& compareSemver(AxonFlowConfig.SDK_VERSION, minJavaVersion) < 0) {
logger.warn(
"SDK version {} is below minimum supported version {}. Please upgrade.",
AxonFlowConfig.SDK_VERSION,
minJavaVersion);
}
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 = executeHttp(httpClient, httpRequest)) {
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 = executeHttp(httpClient, httpRequest)) {
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 = executeHttp(httpClient, httpRequest)) {
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 = executeHttp(httpClient, httpRequest)) {
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);
}
/**
* Fetches the full explanation for a previously-made policy decision.
*
* <p>Implements ADR-043 (Explainability Data Contract). Calls {@code GET
* /api/v1/decisions/:id/explain} and returns a {@link DecisionExplanation} including matched
* policies, risk level, reason, override availability, existing override ID (if any), and a
* rolling-24h session hit count for the matched rule.
*
* <p>The caller must either own the decision (user_email match) or belong to the same tenant as
* the decision's originator.
*
* <p>Example usage:
*
* <pre>{@code
* DecisionExplanation exp = axonflow.explainDecision("dec_wf123_step4");
* if (exp.isOverrideAvailable()) {
* // offer the user a governed override action
* }
* }</pre>
*
* @param decisionId the global decision identifier returned in the original step gate or policy
* evaluation response
* @return the decision explanation (frozen shape per ADR-043)
* @throws IllegalArgumentException if decisionId is null or empty
* @throws AxonFlowException if the request fails or the decision is past retention
*/
public DecisionExplanation explainDecision(String decisionId) {
if (decisionId == null || decisionId.isEmpty()) {
throw new IllegalArgumentException("decisionId is required");
}
return retryExecutor.execute(
() -> {
// Path-segment encoding: URLEncoder is application/x-www-form-urlencoded
// (space -> '+'), which is wrong for path segments. Replacing '+' with
// '%20' converts the form-encoded output into a valid percent-encoded
// path segment, matching how Go / Python / TypeScript escape the
// decision_id in this path.
String encoded =
java.net.URLEncoder.encode(decisionId, java.nio.charset.StandardCharsets.UTF_8)
.replace("+", "%20");
String path = "/api/v1/decisions/" + encoded + "/explain";
Request httpRequest = buildOrchestratorRequest("GET", path, null);
try (Response response = executeHttp(httpClient, httpRequest)) {
JsonNode node = parseResponseNode(response);
return objectMapper.treeToValue(node, DecisionExplanation.class);
}
},
"explainDecision");
}
/**
* Asynchronously fetches a decision explanation.
*
* @param decisionId the global decision identifier
* @return a future containing the decision explanation
*/
public CompletableFuture<DecisionExplanation> explainDecisionAsync(String decisionId) {
return CompletableFuture.supplyAsync(() -> explainDecision(decisionId), asyncExecutor);
}
// ============================================================================
// listDecisions — Session γ (#1982)
// ============================================================================
/**
* Lists recent policy decisions for the caller's tenant (Session γ / #1982).
*
* <p>Returns the slim 5-field {@link DecisionSummary} page; the platform applies a tier-gated cap
* (5/24h Free + Community, 100/30d Pro + Evaluation, 1000/full retention Enterprise). Over-cap
* requests yield a 429 with the V1 upgrade envelope, surfaced as {@link RateLimitException}
* carrying {@code limitType}, {@code tier}, and {@code upgrade.{tier,compareUrl,buyUrl}}.
*
* <p>Filters compose; null fields are omitted from the URL so the platform applies tier defaults.
*
* <p>Example:
*
* <pre>{@code
* try {
* List<DecisionSummary> decisions = axonflow.listDecisions(
* ListDecisionsOptions.builder().decision("blocked").limit(10).build());
* for (DecisionSummary d : decisions) {
* System.out.println(d.getDecisionId() + " " + d.getDecision());
* }
* } catch (RateLimitException rle) {
* if (rle.getUpgrade() != null) {
* System.out.println("Upgrade at: " + rle.getUpgrade().getBuyUrl());
* }
* }
* }</pre>
*
* @param opts filter and page-size options; null returns the tier-default page
* @return list of {@code DecisionSummary} rows ordered newest-first
* @throws RateLimitException 429 tier-cap; {@code rle.getUpgrade()} exposes
* tier/compareUrl/buyUrl
* @throws AxonFlowException other HTTP errors (401, 5xx, etc.)
*/
public List<DecisionSummary> listDecisions(ListDecisionsOptions opts) {
return retryExecutor.execute(
() -> {
String path = "/api/v1/decisions" + buildListDecisionsQuery(opts);
Request httpRequest = buildOrchestratorRequest("GET", path, null);
try (Response response = executeHttp(httpClient, httpRequest)) {
if (response.code() == 429) {
// Try to parse the V1 upgrade envelope. If the body changed
// shape we still surface the 429 — never silently succeed.
String body = response.body() != null ? response.body().string() : "";
try {
JsonNode envelope = objectMapper.readTree(body);
JsonNode limitTypeNode = envelope.get("limit_type");
if (limitTypeNode != null && !limitTypeNode.isNull()) {
RateLimitException.UpgradeInfo upgrade = null;
JsonNode upgradeNode = envelope.get("upgrade");
if (upgradeNode != null && upgradeNode.isObject()) {
upgrade =
new RateLimitException.UpgradeInfo(
optString(upgradeNode, "tier"),
optString(upgradeNode, "wording"),
optString(upgradeNode, "compare_url"),
optString(upgradeNode, "buy_url"));
}
throw new RateLimitException(
optString(envelope, "error"),
envelope.has("limit") ? envelope.get("limit").asInt() : 0,
envelope.has("remaining") ? envelope.get("remaining").asInt() : 0,
null,
limitTypeNode.asText(),
optString(envelope, "tier"),
upgrade);
}
} catch (com.fasterxml.jackson.core.JsonProcessingException ignored) {
// fall through — never silently succeed on 429
}
throw new AxonFlowException("Too Many Requests: " + body, 429, null);
}
JsonNode node = parseResponseNode(response);
JsonNode decisionsNode = node.get("decisions");
java.util.List<DecisionSummary> result = new java.util.ArrayList<>();
if (decisionsNode != null && decisionsNode.isArray()) {
for (JsonNode row : decisionsNode) {
result.add(objectMapper.treeToValue(row, DecisionSummary.class));
}
}
return result;
}
},
"listDecisions");
}
/**
* Asynchronously lists recent decisions for the caller's tenant.
*
* @param opts filter + page-size options (may be null)
* @return a future resolving to the list of summaries
*/
public CompletableFuture<List<DecisionSummary>> listDecisionsAsync(ListDecisionsOptions opts) {
return CompletableFuture.supplyAsync(() -> listDecisions(opts), asyncExecutor);
}
/** Reads a string field, returning null when absent or not textual. */
private static String optString(JsonNode node, String field) {
JsonNode v = node.get(field);
return (v == null || v.isNull()) ? null : v.asText();
}
/**
* Serialize {@link ListDecisionsOptions} into a "?k=v&k=v" query string. Empty when opts or all
* fields are null. Stable field order so test mocks can match the URL exactly.
*/
static String buildListDecisionsQuery(ListDecisionsOptions opts) {
if (opts == null) {
return "";
}
java.util.List<String> pairs = new java.util.ArrayList<>(5);
if (opts.getSince() != null) {
// Instant.toString() already emits RFC 3339 with the "Z" UTC marker.
pairs.add("since=" + urlEncode(opts.getSince().toString()));
}
if (opts.getDecision() != null) {
pairs.add("decision=" + urlEncode(opts.getDecision()));
}
if (opts.getPolicyId() != null) {
pairs.add("policy_id=" + urlEncode(opts.getPolicyId()));
}
if (opts.getToolSignature() != null) {
pairs.add("tool_signature=" + urlEncode(opts.getToolSignature()));
}
if (opts.getLimit() != null) {
pairs.add("limit=" + opts.getLimit());
}
if (pairs.isEmpty()) {
return "";
}
return "?" + String.join("&", pairs);
}
private static String urlEncode(String s) {
return java.net.URLEncoder.encode(s, java.nio.charset.StandardCharsets.UTF_8);
}
/**
* 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 = executeHttp(httpClient, httpRequest)) {
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 = executeHttp(httpClient, httpRequest)) {
return parseResponse(response, AuditToolCallResponse.class);
}
},