Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ All notable changes to the AxonFlow Java SDK will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Fixed

- `AxonFlowTry.register()` no longer attempts anonymous Hosted tenant creation; it directs new buyers to the verified Portal. Custom self-hosted Community registration and explicitly configured credentials/endpoints remain available.
- Answered Hosted `402 hosted_payment_required` preserves HTTP 402 and its error code as a terminal SDK error. Answered Hosted `429 hosted_monthly_limit_reached` remains a terminal `RateLimitException` after one request, including a truncated body with the Agent's monthly-tier header. Ordinary 429 capacity responses retain retry behavior.

## [9.5.0] - 2026-10-21: Decision API approval retry fields

### Added
Expand Down
17 changes: 6 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,22 +77,17 @@ Concurrent executions applies to MAP and WCP executions per tenant. Pending exec

[Get a free Evaluation license](https://getaxonflow.com/evaluation-license?utm_source=readme_sdk_java_eval) · [Run a paid production program](https://getaxonflow.com/design-partner?utm_source=readme_sdk_java_eval) · [Full feature matrix](https://docs.getaxonflow.com/docs/features/community-vs-enterprise?utm_source=readme_sdk_java_eval)

## Try Without Installing
## Hosted without installing the platform

Skip local setup entirely — try AxonFlow instantly at [**try.getaxonflow.com**](https://docs.getaxonflow.com/docs/deployment/community-saas):
Start at the [AxonFlow website](https://getaxonflow.com/) and follow Hosted signup to the [verified Portal](https://portal.try.getaxonflow.com/hosted/start). Verify your email and activate a plan, then download the Hosted API link command from the Portal. Run it locally and approve its device code from your signed-in owner session. It writes a separate revocable API credential to the protected `~/.config/axonflow/hosted-api.json` file. Use the file's `endpoint`, `clientId`, and `clientSecret` values for SDK configuration; keep the secret out of source control and prompts. A newly registered unpaid Basic account cannot obtain a linked credential through the Portal.

```bash
# 1. Register (30 seconds)
curl -X POST https://try.getaxonflow.com/api/v1/register \
-H "Content-Type: application/json" -d '{"label":"my-trial"}'

# 2. Set credentials and auto-connect
export AXONFLOW_TRY=1
export AXONFLOW_CLIENT_ID=cs_your-tenant-id
export AXONFLOW_CLIENT_SECRET=your-secret
export AXONFLOW_CLIENT_ID='<linked-client-id>'
export AXONFLOW_CLIENT_SECRET='<linked-client-secret>'
```

No Docker, no license, no installation. Rate-limited to 20 req/min. [Learn more](https://docs.getaxonflow.com/docs/deployment/community-saas).
Use `AxonFlow.create(AxonFlowConfig.fromEnvironment())` or pass the linked file's `clientId` and `clientSecret` to `AxonFlowConfig.builder()` with its `endpoint` (normally `https://try.getaxonflow.com`). An explicitly configured endpoint takes precedence over `AXONFLOW_TRY=1`, so an existing self-hosted Community client stays on its own Agent. The legacy `AxonFlowTry.register()` overloads now point new Hosted buyers to the Portal; `register(label, endpoint)` remains available for a custom self-hosted Community server. An answered Hosted 402 payment refusal or 429 allowance refusal remains an error, so resolve the plan or allowance before retrying. [Learn more](https://docs.getaxonflow.com/docs/deployment/community-saas).

## Quick Start

Expand Down Expand Up @@ -548,7 +543,7 @@ try {

The SDK includes automatic retry with exponential backoff. The retry policy
itself is not configurable per HTTP status — retries fire on connect/timeout
errors, `5xx` server errors, and `429 Too Many Requests`. Authentication
errors, `5xx` server errors, and ordinary `429 Too Many Requests` capacity responses. An answered Hosted monthly-governance-cap 429 is terminal, including when the Agent's tier-limit header survives a truncated body. Authentication
failures (`401`/`403`), policy violations, and other `4xx` client errors are
always terminal and never retried (see `RetryExecutor.isRetryable`). This
contract is locked in as a regression test for
Expand Down
24 changes: 24 additions & 0 deletions src/main/java/com/getaxonflow/sdk/AxonFlow.java
Original file line number Diff line number Diff line change
Expand Up @@ -4977,6 +4977,18 @@ private void handleErrorResponse(Response response) throws IOException {
// Try to extract error message from JSON body
String errorMessage = extractErrorMessage(body, message);

// An answered Hosted cap is a governance refusal, even if the body was
// truncated after the Agent wrote its monthly-tier header. Ordinary 429s
// still use the retryable rate-limit path below.
if (code == 429
&& ("monthly_governed_events".equals(response.header("X-Axonflow-Tier-Limit"))
|| hasErrorCode(body, "hosted_monthly_limit_reached"))) {
throw RateLimitException.hostedMonthlyLimit(errorMessage);
}
if (code == 402 && hasErrorCode(body, "hosted_payment_required")) {
throw new AxonFlowException(errorMessage, 402, "hosted_payment_required");
}

// v11.0.0: a legacy policy write is refused with its own code, which is not a version conflict.
if (code == 409) {
String frozen = legacyPolicyWriteFrozenMessage(body);
Expand Down Expand Up @@ -5059,6 +5071,18 @@ private String legacyPolicyWriteFrozenMessage(String body) {
}
}

private boolean hasErrorCode(String body, String expected) {
if (body == null || body.isEmpty()) {
return false;
}
try {
JsonNode error = objectMapper.readTree(body).path("error");
return expected.equals(error.asText(null));
} catch (JsonProcessingException e) {
return false;
}
}

private String extractErrorMessage(String body, String defaultMessage) {
if (body == null || body.isEmpty()) {
return defaultMessage;
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/getaxonflow/sdk/AxonFlowConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ private static String detectSdkVersion() {
private final PEPHandshake pepHandshake;

private AxonFlowConfig(Builder builder) {
this.tryMode = "1".equals(System.getenv("AXONFLOW_TRY"));
// An explicit endpoint always wins over the legacy convenience switch.
// This keeps a configured self-hosted Community client on its own Agent.
this.tryMode = "1".equals(System.getenv("AXONFLOW_TRY")) && builder.endpoint == null;
this.endpoint =
this.tryMode
? normalizeUrl(TRY_ENDPOINT)
Expand Down
27 changes: 22 additions & 5 deletions src/main/java/com/getaxonflow/sdk/AxonFlowTry.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,45 @@
import java.net.http.HttpResponse;
import java.time.Duration;

/** Registration helper for try.getaxonflow.com shared evaluation server. */
/** Legacy registration helper for self-hosted Community servers. */
public class AxonFlowTry {

public static final String TRY_ENDPOINT = "https://try.getaxonflow.com";
public static final String HOSTED_START_URL = "https://portal.try.getaxonflow.com/hosted/start";

private static final ObjectMapper MAPPER = new ObjectMapper();
private static final HttpClient CLIENT =
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();

/** Register for a free evaluation tenant. Store the secret securely — it is shown only once. */
/**
* Direct new Hosted buyers to the verified Portal journey. Existing linked credentials can be
* supplied through {@link AxonFlowConfig.Builder#clientId(String)} and {@link
* AxonFlowConfig.Builder#clientSecret(String)}.
*/
public static TryRegistration register() throws IOException, InterruptedException {
return register("", TRY_ENDPOINT);
}

/** Register with an optional label. */
/** Legacy overload: directs new Hosted buyers to verified Portal signup. */
public static TryRegistration register(String label) throws IOException, InterruptedException {
return register(label, TRY_ENDPOINT);
}

/** Register with a custom endpoint (for local testing). */
/** Register with a custom self-hosted Community endpoint. */
public static TryRegistration register(String label, String endpoint)
throws IOException, InterruptedException {
URI origin = URI.create(endpoint);
String host = origin.getHost();
if (host != null) {
host = host.replaceFirst("\\.+$", "");
}
if ("try.getaxonflow.com".equalsIgnoreCase(host)
|| "try-staging.getaxonflow.com".equalsIgnoreCase(host)) {
throw new IOException(
"New Hosted accounts start at "
+ HOSTED_START_URL
+ ": verify your email, complete account and plan setup, then link an API client in the Portal. Configure the linked client ID and secret explicitly in AxonFlowConfig.");
}
String body =
label != null && !label.isEmpty() ? String.format("{\"label\":\"%s\"}", label) : "{}";

Expand All @@ -53,7 +70,7 @@ public static TryRegistration register(String label, String endpoint)
return MAPPER.readValue(response.body(), TryRegistration.class);
}

/** Registration response from try.getaxonflow.com. */
/** Registration response from a custom self-hosted Community server. */
public static class TryRegistration {
private String tenant_id;
private String secret;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ public RateLimitException(String message) {
this.upgrade = null;
}

/** An answered Hosted monthly governance cap. Unlike an ordinary 429, it is terminal. */
public static RateLimitException hostedMonthlyLimit(String message) {
return new RateLimitException(message, "hosted_monthly_limit_reached");
}

private RateLimitException(String message, String errorCode) {
super(message, 429, errorCode);
this.limit = 0;
this.remaining = 0;
this.resetAt = null;
this.limitType = "monthly_governed_events";
this.tier = null;
this.upgrade = null;
}

/**
* Creates a new RateLimitException with rate limit details.
*
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/getaxonflow/sdk/util/RetryExecutor.java
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ private boolean isRetryable(Exception e) {

// Retry rate limit errors
if (e instanceof RateLimitException) {
return true;
return !"hosted_monthly_limit_reached".equals(((RateLimitException) e).getErrorCode());
}

// Retry server errors (5xx)
Expand Down
199 changes: 199 additions & 0 deletions src/test/java/com/getaxonflow/sdk/HostedFirstRunTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
// Copyright 2026 AxonFlow
// SPDX-License-Identifier: MIT
package com.getaxonflow.sdk;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.assertj.core.api.Assertions.*;

import com.getaxonflow.sdk.exceptions.AxonFlowException;
import com.getaxonflow.sdk.exceptions.PolicyViolationException;
import com.getaxonflow.sdk.exceptions.RateLimitException;
import com.getaxonflow.sdk.types.ClientRequest;
import com.getaxonflow.sdk.types.ClientResponse;
import com.getaxonflow.sdk.util.CacheConfig;
import com.getaxonflow.sdk.util.RetryConfig;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.SetEnvironmentVariable;

@WireMockTest
class HostedFirstRunTest {
private static final String PAYMENT =
"{\"error\":\"hosted_payment_required\",\"message\":\"Hosted governance requires an active paid plan.\",\"checkout_method\":\"POST\",\"checkout_url\":\"https://try-staging.getaxonflow.com/api/v1/billing/checkout\"}";
private static final String MONTHLY =
"{\"error\":\"hosted_monthly_limit_reached\",\"message\":\"Monthly hosted governance allowance reached.\",\"limit_type\":\"monthly_governed_events\",\"higher_usage_path\":\"paid_enterprise_poc\"}";

private AxonFlow client(String endpoint, String clientId, String secret) {
return AxonFlow.create(
AxonFlowConfig.builder()
.endpoint(endpoint)
.clientId(clientId)
.clientSecret(secret)
.retryConfig(
RetryConfig.builder().maxAttempts(3).initialDelay(Duration.ofMillis(1)).build())
.cacheConfig(CacheConfig.disabled())
.build());
}

private ClientRequest request() {
return ClientRequest.builder().query("harmless governed probe").build();
}

@Test
void defaultHostedRegistrationRequiresVerifiedPortal() {
assertThatThrownBy(AxonFlowTry::register)
.isInstanceOf(IOException.class)
.hasMessageContaining(AxonFlowTry.HOSTED_START_URL)
.hasMessageContaining("link an API client");
assertThatThrownBy(() -> AxonFlowTry.register("trial", AxonFlowTry.TRY_ENDPOINT + "/"))
.isInstanceOf(IOException.class)
.hasMessageContaining(AxonFlowTry.HOSTED_START_URL);
assertThatThrownBy(() -> AxonFlowTry.register("trial", "https://try.getaxonflow.com."))
.isInstanceOf(IOException.class)
.hasMessageContaining(AxonFlowTry.HOSTED_START_URL);
assertThatThrownBy(
() -> AxonFlowTry.register("trial", "https://try-staging.getaxonflow.com.:443"))
.isInstanceOf(IOException.class)
.hasMessageContaining(AxonFlowTry.HOSTED_START_URL);
}

@Test
void explicitCommunityRegistrationStillWorks(WireMockRuntimeInfo server) throws Exception {
stubFor(
post(urlEqualTo("/api/v1/register"))
.withRequestBody(containing("\"label\":\"local\""))
.willReturn(
aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody("{\"tenant_id\":\"cs_local\",\"secret\":\"local-secret\"}")));
AxonFlowTry.TryRegistration registration =
AxonFlowTry.register("local", server.getHttpBaseUrl());
assertThat(registration.getTenantId()).isEqualTo("cs_local");
assertThat(registration.getSecret()).isEqualTo("local-secret");
verify(1, postRequestedFor(urlEqualTo("/api/v1/register")));
}

@Test
@SetEnvironmentVariable(key = "AXONFLOW_TRY", value = "1")
void explicitEndpointAndCredentialsWinOverLegacyTrySwitch(WireMockRuntimeInfo server) {
AxonFlowConfig config =
AxonFlowConfig.builder()
.endpoint(server.getHttpBaseUrl())
.clientId("self-hosted")
.clientSecret("configured-secret")
.build();
assertThat(config.getEndpoint()).isEqualTo(server.getHttpBaseUrl());
assertThat(config.getClientId()).isEqualTo("self-hosted");
assertThat(config.getClientSecret()).isEqualTo("configured-secret");
}

@Test
void linkedCredentialAndOrdinary200StillWork(WireMockRuntimeInfo server) throws Exception {
stubFor(
post(urlEqualTo("/api/request"))
.willReturn(
aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"success\":true,\"result\":\"governed\"}")));
try (AxonFlow sdk = client(server.getHttpBaseUrl(), "cs_linked", "linked-secret")) {
ClientResponse response = sdk.proxyLLMCall(request());
assertThat(response.isSuccess()).isTrue();
assertThat(response.getResult()).isEqualTo("governed");
}
String basic =
Base64.getEncoder()
.encodeToString("cs_linked:linked-secret".getBytes(StandardCharsets.UTF_8));
verify(
1,
postRequestedFor(urlEqualTo("/api/request"))
.withHeader("Authorization", equalTo("Basic " + basic)));
}

@Test
void answeredHosted402IsTerminal(WireMockRuntimeInfo server) throws Exception {
stubFor(
post(urlEqualTo("/api/request")).willReturn(aResponse().withStatus(402).withBody(PAYMENT)));
try (AxonFlow sdk = client(server.getHttpBaseUrl(), "cs_linked", "linked-secret")) {
AxonFlowException refusal =
catchThrowableOfType(() -> sdk.proxyLLMCall(request()), AxonFlowException.class);
assertThat(refusal).isNotNull();
assertThat(refusal.getStatusCode()).isEqualTo(402);
assertThat(refusal.getErrorCode()).isEqualTo("hosted_payment_required");
}
verify(1, postRequestedFor(urlEqualTo("/api/request")));
}

@Test
void answeredHosted429IsTerminalWithBodyOrHeader(WireMockRuntimeInfo server) throws Exception {
for (String body : new String[] {MONTHLY, "{\"error\":\"hosted_monthly_limit_reached\""}) {
resetAllRequests();
stubFor(
post(urlEqualTo("/api/request"))
.willReturn(
aResponse()
.withStatus(429)
.withHeader("X-Axonflow-Tier-Limit", "monthly_governed_events")
.withBody(body)));
try (AxonFlow sdk = client(server.getHttpBaseUrl(), "cs_linked", "linked-secret")) {
RateLimitException refusal =
catchThrowableOfType(() -> sdk.proxyLLMCall(request()), RateLimitException.class);
assertThat(refusal).isNotNull();
assertThat(refusal.getStatusCode()).isEqualTo(429);
assertThat(refusal.getErrorCode()).isEqualTo("hosted_monthly_limit_reached");
assertThat(refusal.getLimitType()).isEqualTo("monthly_governed_events");
}
verify(1, postRequestedFor(urlEqualTo("/api/request")));
}
}

@Test
void answeredHosted429BodyCodeIsTerminalWithoutHeader(WireMockRuntimeInfo server)
throws Exception {
stubFor(
post(urlEqualTo("/api/request")).willReturn(aResponse().withStatus(429).withBody(MONTHLY)));
try (AxonFlow sdk = client(server.getHttpBaseUrl(), "cs_linked", "linked-secret")) {
RateLimitException refusal =
catchThrowableOfType(() -> sdk.proxyLLMCall(request()), RateLimitException.class);
assertThat(refusal).isNotNull();
assertThat(refusal.getErrorCode()).isEqualTo("hosted_monthly_limit_reached");
}
verify(1, postRequestedFor(urlEqualTo("/api/request")));
}

@Test
void ordinary429StillRetries(WireMockRuntimeInfo server) throws Exception {
stubFor(
post(urlEqualTo("/api/request"))
.willReturn(aResponse().withStatus(429).withBody("{\"error\":\"rate_limited\"}")));
try (AxonFlow sdk = client(server.getHttpBaseUrl(), "self-hosted", "secret")) {
RateLimitException refusal =
catchThrowableOfType(() -> sdk.proxyLLMCall(request()), RateLimitException.class);
assertThat(refusal).isNotNull();
assertThat(refusal.getErrorCode()).isEqualTo("RATE_LIMIT_EXCEEDED");
}
verify(3, postRequestedFor(urlEqualTo("/api/request")));
}

@Test
void legacySelfHostedBlocked402StillBlocks(WireMockRuntimeInfo server) throws Exception {
stubFor(
post(urlEqualTo("/api/request"))
.willReturn(
aResponse()
.withStatus(402)
.withBody(
"{\"success\":false,\"blocked\":true,\"block_reason\":\"budget exceeded\"}")));
try (AxonFlow sdk = client(server.getHttpBaseUrl(), "self-hosted", "secret")) {
assertThatThrownBy(() -> sdk.proxyLLMCall(request()))
.isInstanceOf(PolicyViolationException.class);
}
verify(1, postRequestedFor(urlEqualTo("/api/request")));
}
}
Loading