diff --git a/CHANGELOG.md b/CHANGELOG.md index 08e32b1..046f9b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## [Unreleased] +## [0.5.0] + +### Added + +- Add typed Forward `ManagedToolConfig.schedule` and `ScheduleToolConfig.accessScope` for Identity- or Template-scoped Schedule management tools. Preserve unknown fields and omitted/null schedule configuration; Template managed-capability updates remain whole-object replacements. +- Add offline contracts and packaged-consumer checks for Schedule tool scope and direct Managed SA Key Bearer authentication, including rejection without PAT fallback. + +### Documentation + +- Document Managed SA Key direct calls separately from optional SAT exchange and Forward authentication, and reconcile Forward coverage to 147 HTTP operations including A2A Agent Card discovery. + ## [0.4.0] ### Added diff --git a/README.md b/README.md index c3893e1..4cd5aad 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ The Qoder Cloud Agents Java SDK provides typed synchronous and asynchronous clients, with shared authentication, timeouts, retries, pagination, streaming and error handling. -Version **0.4.0** supports both the **Forward API** and the **[Managed API](docs/managed.md)** in one package. Use `ForwardClient` / `AsyncForwardClient` for Forward and `ManagedClient` / `AsyncManagedClient` for Managed. +Version **0.5.0** supports both the **Forward API** and the **[Managed API](docs/managed.md)** in one package. Use `ForwardClient` / `AsyncForwardClient` for Forward and `ManagedClient` / `AsyncManagedClient` for Managed. - [Installation](#installation) - [Quick start](#quick-start) @@ -20,13 +20,13 @@ Version **0.4.0** supports both the **Forward API** and the **[Managed API](docs ## Installation -Add the Maven dependency; published versions require no local SDK build or additional repository configuration. +Add the Maven dependency; published versions require no local SDK build or additional repository configuration. Version 0.5.0 is prepared in this checkout but is not yet published; install the local SDK for development, or use a version listed in [Releases](https://github.com/QoderAI/qoder-cloud-agents-sdk-java/releases). ```xml com.qoder.sdk qoder-cloud-agents-sdk - 0.4.0 + 0.5.0 ``` @@ -76,6 +76,7 @@ PAT and SA are parallel authentication modes: | PAT | `.pat(token)` | Managed by your application | | SA Key | `.credential(ServiceAccountCredential)` | SDK exchanges, caches and refreshes the SAT on demand | | Existing SAT | `.authMode(AuthMode.SA).accessToken(token)` | Managed by your application | +| Direct SA Key (Managed only) | `.authMode(AuthMode.SA).accessToken(saKey)` | No SAT exchange or renewal; rotate the Key in your application | With no explicit credentials, PAT mode reads `QODER_ACCESS_TOKEN`, then `QODER_PAT`. An explicit token or credential takes precedence over environment tokens; configure only one explicit source. The SDK does not load `.env` files or enable SA merely because `QODER_SA_KEY` is set. @@ -96,7 +97,9 @@ try (ServiceAccountCredential credential = ServiceAccountCredential.builder() } ``` -Business requests use the SAT; the SA Key is sent only to the exchange service. For CN, use both `Region.CN` and the CN BaseURL. Keep a shared credential open until all clients using it are closed. Failed SA authentication does not fall back to PAT. +With `ServiceAccountCredential`, business requests use the SAT; the SA Key is sent only to the exchange service. For CN, use both `Region.CN` and the CN BaseURL. Keep a shared credential open until all clients using it are closed. Failed SA authentication does not fall back to PAT. + +Managed APIs also accept the full SA Key directly as a Bearer credential through the existing `accessToken(...)` builder. Explicitly read it from your secrets manager or `QODER_SA_KEY`; the SDK does not infer this mode. See [Managed authentication](docs/managed.md#client-and-authentication) for a complete example. Direct SA Key authentication does not apply to Forward business APIs, which require PAT or SAT. Forward also provides explicit administrator/Identity SAT issuance and revocation through `serviceAccountTokens()` and `identities().serviceAccountTokens()`. These methods take a per-call SA Key and do not retry automatically. See [SAT management](docs/usage-sat-drive.md) and [authentication configuration](docs/client-configuration.md). diff --git a/docs/client-configuration.md b/docs/client-configuration.md index 0318319..8c72f25 100644 --- a/docs/client-configuration.md +++ b/docs/client-configuration.md @@ -56,6 +56,8 @@ Forward SAT management uses explicit per-call SA Keys through `serviceAccountTok Close the client after use. A static SAT is not automatically renewed. SA mode does not fall back to `QODER_PAT`. For application-managed rotation, implement `Credential.getToken()` returning a `CompletableFuture`; it is called before each attempt and must be thread-safe and return promptly. Cancelling a request does not cancel a shared credential future. +For Managed-only integrations, the full SA Key can instead be passed directly with `ManagedClient.builder().authMode(AuthMode.SA).accessToken(saKey)`. This sends the Key as Bearer without exchange or SAT renewal; do not use this path for Forward business requests. No `QODER_SA_KEY` lookup is automatic. See [Managed authentication](managed.md#client-and-authentication) and [the official credential rules](https://docs.qoder.com/cloud-agents/api/conventions/authentication). + ## Asynchronous calls and cancellation ```java diff --git a/docs/forward-api-coverage.md b/docs/forward-api-coverage.md index c126280..f46d03b 100644 --- a/docs/forward-api-coverage.md +++ b/docs/forward-api-coverage.md @@ -2,7 +2,7 @@ 开发中契约复核(2026-11-03):补齐 Session budget(省略/null/对象)、config.model、审批 evaluation 和 Environment startup_script;修正顶层 evaluatedPermission 字符串与 Thread 终止后的续订行为。本轮没有新增 HTTP 操作;验证见 `DocumentationAlignmentTest`,真实环境结果单独记录。 -契约核对:2026-10-28。**0.2.0** 覆盖 **146 个 HTTP 操作及 Realtime WebSocket**:首版 123 项、Webhook 8 项、Forward Search / Dream / Pairing / Decision 15 项。同一版本还提供 [107 个 Managed 操作](managed-api-coverage.md)。离线验证与真实环境验收分别记录,不能把操作覆盖数当作线上通过率。 +契约核对:2026-10-28,能力增量核对:2026-11-21,Schedule 工具范围核对:2026-12-03。当前 **0.5.0** 覆盖 **147 个 HTTP 操作及 Realtime WebSocket**:首版 123 项、Webhook 8 项、Forward Search / Dream / Pairing / Decision 15 项、0.4.0 新增 A2A Agent Card 1 项。同一包还提供 [107 个 Managed 操作](managed-api-coverage.md)。离线验证与真实环境验收分别记录,不能把操作覆盖数当作线上通过率。 HTTP BaseURL 为 CN `https://api.qoder.com.cn/api/v1/forward` 或 Global `https://api.qoder.com/api/v1/forward`;表内路径均相对于 BaseURL。 @@ -16,6 +16,8 @@ HTTP BaseURL 为 CN `https://api.qoder.com.cn/api/v1/forward` 或 Global `https: 开发中能力补齐(2026-11-21):新增 `GET /templates/{template_id}/a2a/agent-card.json`,方法 `templates().retrieveAgentCard(...)`,同步/异步及 withResponse 均支持;其余变更补齐 Session 更新多智能体、创建自动标题、A2A 配置和 OSS 模型,不新增这些资源的 HTTP 路由。新增测试见 `CapabilityParityTest`;真实环境未在本轮执行。 +0.5.0 补齐 `managed_tool_config.schedule.access_scope` 的类型化请求/响应和省略/null 表达,不新增 HTTP 路由。Template 配置整体替换与 Identity/template 范围边界见 [Template 指南](templates.md#schedule-management-tool-scope),契约测试见 `TemplatesTest`,独立 JAR 消费测试见 `TemplateConsumerTest`。 + ## 使用指南 - [客户端认证、超时、重试与取消](client-configuration.md) @@ -214,6 +216,12 @@ Webhook 的 8 个操作已实现同步/异步、分页、原始请求体验签 | 145 | `GET` | `/decisions` | `decisions().list(...)` | | 146 | `GET` | `/decisions/{decision_id}` | `decisions().retrieve(...)` | +## 0.4.0 新增的 A2A 操作 + +| # | HTTP | 相对路径 | Java 入口 | +| ---: | --- | --- | --- | +| 147 | `GET` | `/templates/{template_id}/a2a/agent-card.json` | `templates().retrieveAgentCard(...)` | + 最新公开契约及字段迁移说明见 [Forward 补齐指南](forward-parity.md)。固定官方来源为 2026-10-28 文档快照;Go/Python/TS 0.13.0 作为行为对照,不把其扩展字段自动视为官方契约。 本轮独立请求 fixture 位于 `src/test/resources/forward-parity-routes.json`,覆盖 15 个操作的同步/异步及 withResponse 入口。`ForwardParityTest`、`ForwardPaginationParityTest` 验证字段、metadata 冲突、精度、分页、幂等重试与取消。`ForwardCapabilitiesConsumerTest` 通过独立 examples 工程消费实际 JAR。真实环境和 QA 包尚须按 [验收指南](live-testing.md) 执行;目前没有这些新增功能的线上通过声明。 diff --git a/docs/maintaining.md b/docs/maintaining.md index 5a7908c..387d977 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -1,6 +1,6 @@ # Java SDK maintenance -SDK 0.4.0 covers Forward and Managed and targets Java 8. Use JDK 17 or later for maintenance tools; the runtime compatibility matrix remains Java 8, 11, 17, 21 and 25. +SDK 0.5.0 covers Forward and Managed and targets Java 8. Use JDK 17 or later for maintenance tools; the runtime compatibility matrix remains Java 8, 11, 17, 21 and 25. ## Local checks and pull requests @@ -36,10 +36,10 @@ The SDK's embedded version is filtered from `${project.version}`; do not replace ```sh python3 .github/scripts/release_notes.py check # After adding the actual release entry: -python3 .github/scripts/release_notes.py extract --version 0.4.0 +python3 .github/scripts/release_notes.py extract --version 0.5.0 ``` -The release version in this checkout is `0.4.0`. Also update the README dependency and version-specific maintenance examples. Acceptance records must include the resolved version, source SHA and JAR digest. Release versions must not be overwritten; a successful test of an older build is not evidence for a newer one. +The release version in this checkout is `0.5.0`. Also update the README dependency and version-specific maintenance examples. Acceptance records must include the resolved version, source SHA and JAR digest. Release versions must not be overwritten; a successful test of an older build is not evidence for a newer one. ### RC qualification for 0.1.0 diff --git a/docs/managed.md b/docs/managed.md index 4a2e5c4..5b798b5 100644 --- a/docs/managed.md +++ b/docs/managed.md @@ -26,7 +26,28 @@ try (ManagedClient client = ManagedClient.builder() } ``` -The base URL is resolved from `.baseUrl(...)`, then `QODER_BASE_URL`, then Global `https://api.qoder.com/api/v1/cloud`. CN uses `https://api.qoder.com.cn/api/v1/cloud`. PAT and static SAT use the same configuration rules as Forward; `ServiceAccountCredential` exchanges an SA Key for a platform SAT with `qca.access`. The examples' `ManagedExampleClient` handles PAT, SA Key and static SAT selection. Managed does not expose Forward's Identity query selector. +The base URL is resolved from `.baseUrl(...)`, then `QODER_BASE_URL`, then Global `https://api.qoder.com/api/v1/cloud`. CN uses `https://api.qoder.com.cn/api/v1/cloud`. PAT and static SAT use the same configuration rules as Forward. Managed does not expose Forward's Identity query selector. + +Managed APIs accept the **full SA Key directly** as a Bearer credential; no SAT exchange or renewal is required. Use the existing builder explicitly: + +```java +import com.qoder.cloudagents.ManagedClient; +import com.qoder.cloudagents.auth.AuthMode; + +try (ManagedClient client = ManagedClient.builder() + .baseUrl("https://api.qoder.com/api/v1/cloud") + .authMode(AuthMode.SA) + .accessToken(System.getenv("QODER_SA_KEY")) + .build()) { + System.out.println(client.models().list().data().size()); +} +``` + +For an independently owned async client, use the same builder with `.buildAsync()` and close it after requests finish. The SDK does not automatically read `QODER_SA_KEY`, exchange a directly configured Key, validate JWT structure or fall back to PAT on rejection. Keep the Key in a secrets manager, rotate it in your application, and select the credential's region and workspace binding; the service enforces access. + +SAT exchange remains optional: `ServiceAccountCredential` obtains, caches and refreshes a platform SAT with `qca.access`; request both `qca.access` and `forward.access` if that SAT will also call Forward. Forward business APIs accept PAT/SAT, **not direct SA Keys**. `ManagedExampleClient` retains its existing automatic-exchange behavior when `QODER_SA_KEY` is supplied. For direct calls with that helper, set `QODER_AUTH_MODE=sa` and put the Key in `QODER_ACCESS_TOKEN`, leaving `QODER_SA_KEY` unset in the helper's environment. + +Source: [official authentication](https://docs.qoder.com/cloud-agents/api/conventions/authentication), checked on 2026-12-03. `ManagedContractsTest` and `ManagedConsumerTest` validate direct Bearer wire placement without contacting the service; real account access remains a separate opt-in verification. `client.async()` shares the parent's transport; closing that view is a no-op. `ManagedClient.builder().buildAsync()` owns its transport. `withOptions(...)` creates an independently closeable client. Ordinary HTTP methods also offer `withResponse()` for status, headers and request ID. SSE streams expose handshake metadata through `response()` and must be closed. diff --git a/docs/releasing.md b/docs/releasing.md index c4a232e..22ee236 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,6 +1,6 @@ # Java SDK release setup -The release version in this checkout is `com.qoder.sdk:qoder-cloud-agents-sdk:0.4.0`. The manual [Release workflow](../.github/workflows/release.yml) publishes using repository Actions secrets. Dispatching it from `main` authorizes publication after all automated checks pass; there is no separate environment approval. The Central account, namespace, signing key and repository settings below must be configured first. The GitHub repository and internal Maven access do not grant Maven Central publishing access. +The release version in this checkout is `com.qoder.sdk:qoder-cloud-agents-sdk:0.5.0`. The manual [Release workflow](../.github/workflows/release.yml) publishes using repository Actions secrets. Dispatching it from `main` authorizes publication after all automated checks pass; there is no separate environment approval. The Central account, namespace, signing key and repository settings below must be configured first. The GitHub repository and internal Maven access do not grant Maven Central publishing access. `0.1.0-rc.1` was published to Maven Central on 2026-10-21; see its [Release](https://github.com/QoderAI/qoder-cloud-agents-sdk-java/releases/tag/v0.1.0-rc.1) and [successful publication workflow](https://github.com/QoderAI/qoder-cloud-agents-sdk-java/actions/runs/39572349619). A version committed to a POM is not yet a published package: check the workflow's public verification and matching GitHub Release for each version. @@ -70,13 +70,13 @@ The namespace variable is a maintainer's setup confirmation, not an automatic ow Prepare a PR that updates the root POM, the example project's version and SDK dependency, plus the changelog version section. Keep an empty `Unreleased` section. Review any version-specific install examples. Merge only after `quality` and all five Java checks succeed. The workflow does not bump versions or merge the PR. -For the Forward and Managed contract-alignment `0.4.0` release, run internal integration tests and accept a QA package built from the merged version commit. Record both API surfaces, the Java runtime, cleanup warnings and untested scenarios. Earlier development-package results do not replace this check. Use the merged `0.4.0` main SHA and a new batch ID; leave recovery inputs empty for the first publication. +For the Forward and Managed contract-alignment `0.5.0` release, run internal integration tests and accept a QA package built from the merged version commit. Record both API surfaces, the Java runtime, cleanup warnings and untested scenarios. Earlier development-package results do not replace this check. Use the merged `0.5.0` main SHA and a new batch ID; leave recovery inputs empty for the first publication. Open **Actions → Release → Run workflow**, select **main**, and verify the following inputs before dispatch. Successful preflight automatically proceeds to signing and publication; it does not pause for an additional approval. | Input | First publication | | --- | --- | -| `version` | The reviewed version without `v` or `SNAPSHOT`, for example `0.4.0` | +| `version` | The reviewed version without `v` or `SNAPSHOT`, for example `0.5.0` | | `commit_sha` | Full 40-character lowercase SHA of the current GitHub main | | `batch_id` | 1–64 letters/digits/dots/underscores/hyphens, starting with a letter or digit | | `resume_run_id` | Empty | diff --git a/docs/templates.md b/docs/templates.md index 0ec7482..3a6be27 100644 --- a/docs/templates.md +++ b/docs/templates.md @@ -37,7 +37,8 @@ TemplateCreateParams params = TemplateCreateParams.builder() .enabledTools(Arrays.asList("Read", "Bash")) .build())) .managedToolConfig(ManagedToolConfig.builder() - .enabledTools(Collections.singletonList("create_forward_schedule")) + .enabledTools(Collections.singletonList("schedule")) + .schedule(ScheduleToolConfig.builder().accessScope("template").build()) .build()) .environmentVariables(EnvironmentVariables.of( Collections.singletonMap("MODE", "support"))) @@ -50,7 +51,7 @@ Use values supported by the selected environment and model; the SDK does not inf | --- | --- | | `model` | `ModelConfig`: string or object with id, effort, speed, context window | | `tools` | `List`, with `ToolConfig`, `PermissionPolicy` and JSON Schema | -| `managed_tool_config` | `ManagedToolConfig` | +| `managed_tool_config` | `ManagedToolConfig`, with nested `ScheduleToolConfig` | | `mcp_servers` | `List` | | `skills` | `List` | | `multiagent` | `MultiagentConfig`, `MultiagentEntry` (string reference, Agent, Self or Advisor) | @@ -64,6 +65,19 @@ GitHub `authorizationToken(...)` is a write-only request field. The typed respon List summaries can omit detail fields. Optional typed getters return null for missing or null fields; `field("wire_name").isMissing()` and `isNull()` distinguish them. Unknown values are retained instead of rejected as closed enums. +## Schedule management tool scope + +Since 0.5.0, `ManagedToolConfig.schedule(...)` accepts `ScheduleToolConfig.builder().accessScope(...)`. The `schedule` selector enables the six Schedule management capabilities as a bundle; `drive` selects Drive capabilities. Scope does not enable tools by itself: include the intended selectors in `enabledTools(...)`. + +- `identity` is the server default: manage Schedules under the same Identity, including those from other Templates. +- `template` restricts Session management tools to Schedules created by the current Template. Other Templates' Schedules are excluded from listings and access by ID returns `not_found`. +- Omit `schedule` or use `.schedule(null)` for the default scope. A supplied Schedule object requires a nonempty `accessScope`. The SDK retains future strings and fields for compatibility; supported values are validated by the service. +- Identity overrides cannot broaden the Template scope. This setting does not change the console Schedule API or scheduled execution. + +Read configured scope through `template.managedToolConfig().schedule().accessScope()`, checking nullable parent getters first. Missing/null response fields remain distinguishable with `field(...)`. + +Contract sources: [Template creation](https://docs.qoder.com/cloud-agents/api/forward/templates/create#forward-managed-capabilities) and [natural-language Schedule management](https://docs.qoder.com/cloud-agents/natural-language-schedule-management), checked on 2026-12-03. `TemplatesTest` and `TemplateConsumerTest` cover the wire contract and packaged model; these tests do not establish live permission enforcement. + ## Updates: omitted, null and empty ```java @@ -85,6 +99,8 @@ client.templates().update("tmpl_example", update); The SDK preserves these wire distinctions; each field's clearing/merge semantics remain server-defined. In particular, metadata patch semantics are handled by the service. +`managed_tool_config` is a **whole-object replacement**, not a nested merge patch. When changing scope, resend the complete `enabledTools(...)` set you intend to retain. Omitting the top-level field preserves it; top-level null, an empty object or an empty `enabled_tools` list clears enabled capabilities. Omitting/nulling only `schedule` within a supplied replacement selects the default scope and does not retain the previous scope. See [Template updates](https://docs.qoder.com/cloud-agents/api/forward/templates/update#forward-managed-capabilities). + ## Headers and safe retries ```java diff --git a/examples/README.md b/examples/README.md index 298509c..c0bb821 100644 --- a/examples/README.md +++ b/examples/README.md @@ -48,6 +48,8 @@ export QODER_MODEL=auto -Dexec.mainClass=com.qoder.cloudagents.examples.TemplateLifecycleExample ``` +The example keeps managed tools disabled. To build a Schedule-enabled Template configuration, use `ManagedToolConfig.builder().enabledTools(Collections.singletonList("schedule")).schedule(ScheduleToolConfig.builder().accessScope("template").build()).build()`. The scope constrains Session management tools, not the console Schedule API. See [scope and replacement semantics](../docs/templates.md#schedule-management-tool-scope); the packaged `TemplateConsumerTest` exercises this configuration without live execution. + The example uses unique names and a separate idempotency key per write. It archives created Templates even when a later operation fails, and reports failed cleanup IDs. Archive retains the record; the public Template API has no delete endpoint. An ambiguous network failure after creation can still require a manual check by the unique `sdk-java-` name. ## Identity configuration @@ -251,4 +253,4 @@ Forward Webhook listing and receiver verification: see [Webhook guide](../docs/w ## Managed API -`ManagedExampleClient` configures PAT / SA Key / SAT authentication with `QODER_BASE_URL` for `/api/v1/cloud`. `ManagedLiveCheck` provides explicit `read`, `resources`, `session`, `deployment` and `work` integration groups against the resolved JAR. See [Managed usage](../docs/managed.md) and [opt-in live testing](../docs/managed-live-testing.md) for permissions, test resources and cleanup. These examples require SDK 0.2.0 or later. +`ManagedExampleClient` configures PAT / SA Key / SAT authentication with `QODER_BASE_URL` for `/api/v1/cloud`. `ManagedLiveCheck` provides explicit `read`, `resources`, `session`, `deployment` and `work` integration groups against the resolved JAR. See [Managed usage](../docs/managed.md) and [opt-in live testing](../docs/managed-live-testing.md) for permissions, test resources and cleanup. These examples require SDK 0.2.0 or later. The helper exchanges `QODER_SA_KEY` for SAT as before. For direct Managed SA Key calls, set `QODER_AUTH_MODE=sa`, supply the full Key in `QODER_ACCESS_TOKEN`, and leave `QODER_SA_KEY` unset for this helper. Alternatively, explicitly configure `.authMode(AuthMode.SA).accessToken(saKey)` on `ManagedClient` / `AsyncManagedClient`; see [direct authentication](../docs/managed.md#client-and-authentication). Forward examples still require PAT or SAT. diff --git a/examples/pom.xml b/examples/pom.xml index c0b7c5f..70a8808 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -2,11 +2,11 @@ 4.0.0 - com.qoder.examplesqca-forward-examples0.4.0 + com.qoder.examplesqca-forward-examples0.5.0 8UTF-8 - com.qoder.sdkqoder-cloud-agents-sdk0.4.0 + com.qoder.sdkqoder-cloud-agents-sdk0.5.0 org.junit.jupiterjunit-jupiter5.13.4test com.squareup.okhttp3mockwebserver5.5.0test diff --git a/examples/src/test/java/com/qoder/cloudagents/examples/ManagedConsumerTest.java b/examples/src/test/java/com/qoder/cloudagents/examples/ManagedConsumerTest.java index 8d369e8..895b6eb 100644 --- a/examples/src/test/java/com/qoder/cloudagents/examples/ManagedConsumerTest.java +++ b/examples/src/test/java/com/qoder/cloudagents/examples/ManagedConsumerTest.java @@ -2,7 +2,9 @@ import static org.junit.jupiter.api.Assertions.*; +import com.qoder.cloudagents.AsyncManagedClient; import com.qoder.cloudagents.ManagedClient; +import com.qoder.cloudagents.auth.AuthMode; import com.qoder.cloudagents.core.*; import com.qoder.cloudagents.managed.*; import java.io.*; @@ -31,6 +33,44 @@ void packagedManagedSkillsExcludeTheDeprecatedUpdateApi() { () -> Class.forName("com.qoder.cloudagents.managed.SkillUpdateParams")); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void packagedManagedClientsAcceptDirectSaKeys(boolean async) throws Exception { + assertTrue( + ManagedClient.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .toString() + .endsWith(".jar")); + try (MockWebServer server = new MockWebServer()) { + server.start(); + server.enqueue(new MockResponse().setBody("{\"data\":[{\"id\":\"auto\"}]}")); + ManagedClient.Builder builder = + ManagedClient.builder() + .baseUrl(server.url("/api/v1/cloud").toString()) + .authMode(AuthMode.SA) + .accessToken("synthetic-direct-sa-key") + .maxRetries(0); + ModelListResponse models; + if (async) { + try (AsyncManagedClient direct = builder.buildAsync()) { + models = direct.models().list().get(); + } + } else { + try (ManagedClient direct = builder.build()) { + models = direct.models().list(); + } + } + assertEquals("auto", models.data().get(0).id()); + RecordedRequest sent = server.takeRequest(2, TimeUnit.SECONDS); + assertNotNull(sent); + assertEquals("/api/v1/cloud/models", sent.getPath()); + assertEquals("Bearer synthetic-direct-sa-key", sent.getHeader("Authorization")); + assertEquals(1, server.getRequestCount()); + } + } + @Test void compiledConsumerUsesJarAndCreatesBudgetedSession() throws Exception { assertTrue( diff --git a/examples/src/test/java/com/qoder/cloudagents/examples/TemplateConsumerTest.java b/examples/src/test/java/com/qoder/cloudagents/examples/TemplateConsumerTest.java index 638ba27..e58ceab 100644 --- a/examples/src/test/java/com/qoder/cloudagents/examples/TemplateConsumerTest.java +++ b/examples/src/test/java/com/qoder/cloudagents/examples/TemplateConsumerTest.java @@ -3,10 +3,13 @@ import static org.junit.jupiter.api.Assertions.*; import com.qoder.cloudagents.ForwardClient; +import com.qoder.cloudagents.core.JsonValue; import com.qoder.cloudagents.errors.ApiStatusException; +import com.qoder.cloudagents.forward.*; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.*; +import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -63,6 +66,60 @@ void lifecycleUsesPackagedSdkAndArchivesBothTemplates() throws Exception { } } + @Test + void packagedScheduleToolConfigurationSupportsTemplateScopedManagement() throws Exception { + assertTrue( + ScheduleToolConfig.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .getPath() + .endsWith(".jar")); + try (MockWebServer server = new MockWebServer()) { + server.start(); + server.enqueue( + new MockResponse() + .setBody( + "{\"id\":\"tmpl_scoped\",\"managed_tool_config\":{\"enabled_tools\":[\"schedule\"]," + + "\"schedule\":{\"access_scope\":\"template\"}}}")); + try (ForwardClient client = + ForwardClient.builder() + .baseUrl(server.url("/api/v1/forward").toString()) + .pat("test-token") + .build()) { + Template template = + client + .async() + .templates() + .create( + TemplateCreateParams.builder() + .name("scoped") + .modelId("auto") + .environmentId("env_test") + .managedToolConfig( + ManagedToolConfig.builder() + .enabledTools(Collections.singletonList("schedule")) + .schedule( + ScheduleToolConfig.builder().accessScope("template").build()) + .build()) + .build()) + .get(); + assertEquals("template", template.managedToolConfig().schedule().accessScope()); + RecordedRequest sent = server.takeRequest(2, TimeUnit.SECONDS); + assertNotNull(sent); + assertEquals("/api/v1/forward/templates", sent.getPath()); + JsonValue body = JsonValue.parse(sent.getBody().readUtf8()); + assertEquals( + "template", + body.get("managed_tool_config").get("schedule").get("access_scope").asString()); + assertEquals( + "schedule", + body.get("managed_tool_config").get("enabled_tools").asArray().get(0).asString()); + assertTrue(body.get("schedule").isMissing()); + } + } + } + @Test void cleanupFailureIsRetainedAlongsideOriginalFailure() throws Exception { try (MockWebServer server = new MockWebServer()) { diff --git a/pom.xml b/pom.xml index e92e10e..9b73ad6 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.qoder.sdk qoder-cloud-agents-sdk - 0.4.0 + 0.5.0 Qoder Cloud Agents Java SDK Java 8 compatible Qoder Cloud Agents Forward and Managed API clients. https://github.com/QoderAI/qoder-cloud-agents-sdk-java diff --git a/src/main/java/com/qoder/cloudagents/forward/ManagedToolConfig.java b/src/main/java/com/qoder/cloudagents/forward/ManagedToolConfig.java index 7bdaad3..9aa9439 100644 --- a/src/main/java/com/qoder/cloudagents/forward/ManagedToolConfig.java +++ b/src/main/java/com/qoder/cloudagents/forward/ManagedToolConfig.java @@ -19,6 +19,10 @@ public List enabledTools() { return optionalList("enabled_tools", JsonValue::asString); } + public ScheduleToolConfig schedule() { + return optional("schedule", ScheduleToolConfig::fromJson); + } + public static Builder builder() { return new Builder(); } @@ -30,6 +34,10 @@ public Builder enabledTools(List value) { return put("enabled_tools", value); } + public Builder schedule(ScheduleToolConfig value) { + return put("schedule", value); + } + public ManagedToolConfig build() { return new ManagedToolConfig(json()); } diff --git a/src/main/java/com/qoder/cloudagents/forward/ScheduleToolConfig.java b/src/main/java/com/qoder/cloudagents/forward/ScheduleToolConfig.java new file mode 100644 index 0000000..8d55f07 --- /dev/null +++ b/src/main/java/com/qoder/cloudagents/forward/ScheduleToolConfig.java @@ -0,0 +1,37 @@ +package com.qoder.cloudagents.forward; + +import com.qoder.cloudagents.core.JsonObject; +import com.qoder.cloudagents.core.JsonObjectBuilder; +import com.qoder.cloudagents.core.JsonValue; + +/** Schedule management scope for a Template's Forward managed tools. */ +public final class ScheduleToolConfig extends JsonObject { + private ScheduleToolConfig(JsonValue value) { + super(value); + } + + public static ScheduleToolConfig fromJson(JsonValue value) { + return new ScheduleToolConfig(value); + } + + public String accessScope() { + return optionalString("access_scope"); + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder extends JsonObjectBuilder { + private Builder() {} + + public Builder accessScope(String value) { + return put("access_scope", value); + } + + public ScheduleToolConfig build() { + require("access_scope"); + return new ScheduleToolConfig(json()); + } + } +} diff --git a/src/test/java/com/qoder/cloudagents/ManagedContractsTest.java b/src/test/java/com/qoder/cloudagents/ManagedContractsTest.java index a9d8f7b..94934cf 100644 --- a/src/test/java/com/qoder/cloudagents/ManagedContractsTest.java +++ b/src/test/java/com/qoder/cloudagents/ManagedContractsTest.java @@ -606,6 +606,66 @@ void asyncCancellationAndDerivedClientsKeepOwnership() throws Exception { assertEquals("Bearer test-pat", request().getHeader("Authorization")); } + @ParameterizedTest + @ValueSource(ints = {0, 1, 2, 3}) + void directSaKeyAuthenticationDoesNotExchangeOrRewriteTheKey(int style) throws Exception { + respond("{\"data\":[{\"id\":\"auto\"}]}"); + ManagedClient.Builder builder = + ManagedClient.builder() + .baseUrl(server.url("/api/v1/cloud").toString()) + .authMode(AuthMode.SA) + .accessToken("synthetic-sa-key-not-a-jwt") + .maxRetries(0); + ModelListResponse models; + if (style < 2) { + try (ManagedClient direct = builder.build()) { + models = style == 0 ? direct.models().list() : direct.models().withResponse().list().data(); + } + } else { + try (AsyncManagedClient direct = builder.buildAsync()) { + models = + style == 2 + ? direct.models().list().get() + : direct.models().withResponse().list().get().data(); + } + } + assertEquals("auto", models.data().get(0).id()); + RecordedRequest sent = request(); + assertEquals("GET", sent.getMethod()); + assertEquals("/api/v1/cloud/models", sent.getPath()); + assertEquals("Bearer synthetic-sa-key-not-a-jwt", sent.getHeader("Authorization")); + assertEquals(1, server.getRequestCount()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void rejectedDirectSaKeyDoesNotFallBackToPatOrRetry(boolean async) throws Exception { + server.enqueue( + new MockResponse() + .setResponseCode(401) + .setHeader("X-Request-ID", "req_sa_rejected") + .setBody("{\"error\":{\"type\":\"authentication_error\",\"message\":\"rejected\"}}")); + try (ManagedClient direct = + ManagedClient.builder() + .baseUrl(server.url("/api/v1/cloud").toString()) + .authMode(AuthMode.SA) + .accessToken("synthetic-rejected-sa-key") + .maxRetries(2) + .build()) { + ApiStatusException failure; + if (async) { + ExecutionException wrapped = + assertThrows(ExecutionException.class, () -> direct.async().models().list().get()); + assertTrue(wrapped.getCause() instanceof ApiStatusException); + failure = (ApiStatusException) wrapped.getCause(); + } else failure = assertThrows(ApiStatusException.class, () -> direct.models().list()); + assertEquals(401, failure.statusCode()); + assertEquals("req_sa_rejected", failure.requestId()); + assertEquals("Bearer synthetic-rejected-sa-key", request().getHeader("Authorization")); + assertEquals(1, server.getRequestCount()); + } + } + @Test void staticSatAuthenticationAndTypedErrorContextAreRetained() throws Exception { try (AsyncManagedClient sat = diff --git a/src/test/java/com/qoder/cloudagents/TemplatesTest.java b/src/test/java/com/qoder/cloudagents/TemplatesTest.java index a9812ab..e8c5a53 100644 --- a/src/test/java/com/qoder/cloudagents/TemplatesTest.java +++ b/src/test/java/com/qoder/cloudagents/TemplatesTest.java @@ -160,6 +160,165 @@ void allTemplateRoutesExposeResponseMetadataAndRequestOptions(boolean async) thr assertEquals(0, archive.getBodySize()); } + @ParameterizedTest + @ValueSource(ints = {0, 1, 2, 3}) + void scheduleToolScopeUsesTemplateConfigurationInAllCallStyles(int style) throws Exception { + for (String scope : Arrays.asList("identity", "template")) { + String config = + "{\"enabled_tools\":[\"schedule\"],\"schedule\":{\"access_scope\":\"" + scope + "\"}}"; + String response = "{\"id\":\"tmpl_scope\",\"managed_tool_config\":" + config + "}"; + ManagedToolConfig managed = + ManagedToolConfig.builder() + .enabledTools(Collections.singletonList("schedule")) + .schedule(ScheduleToolConfig.builder().accessScope(scope).build()) + .build(); + TemplateCreateParams params = + TemplateCreateParams.builder() + .name("scoped") + .modelId("auto") + .environmentId("env_test") + .managedToolConfig(managed) + .build(); + server.enqueue(json(response)); + Template created; + if (style == 0) created = client.templates().create(params); + else if (style == 1) created = client.templates().withResponse().create(params).data(); + else if (style == 2) created = client.async().templates().create(params).get(); + else created = client.async().templates().withResponse().create(params).get().data(); + assertEquals(scope, created.managedToolConfig().schedule().accessScope()); + RecordedRequest create = request(); + assertEquals("POST", create.getMethod()); + assertEquals("/api/v1/forward/templates", create.getPath()); + assertEquals( + JSON.readTree( + "{\"name\":\"scoped\",\"model\":\"auto\",\"environment_id\":\"env_test\"," + + "\"managed_tool_config\":" + + config + + "}"), + JSON.readTree(create.getBody().readUtf8())); + + server.enqueue(json(response)); + Template retrieved; + if (style == 0) retrieved = client.templates().retrieve("tmpl_scope"); + else if (style == 1) + retrieved = client.templates().withResponse().retrieve("tmpl_scope").data(); + else if (style == 2) retrieved = client.async().templates().retrieve("tmpl_scope").get(); + else + retrieved = client.async().templates().withResponse().retrieve("tmpl_scope").get().data(); + assertEquals(scope, retrieved.managedToolConfig().schedule().accessScope()); + RecordedRequest get = request(); + assertEquals("GET", get.getMethod()); + assertEquals("/api/v1/forward/templates/tmpl_scope", get.getPath()); + + String replacement = "{\"schedule\":{\"access_scope\":\"identity\"}}"; + server.enqueue(json("{\"id\":\"tmpl_scope\",\"managed_tool_config\":" + replacement + "}")); + TemplateUpdateParams update = + TemplateUpdateParams.builder() + .managedToolConfig( + ManagedToolConfig.builder() + .schedule(ScheduleToolConfig.builder().accessScope("identity").build()) + .build()) + .build(); + Template updated; + if (style == 0) updated = client.templates().update("tmpl_scope", update); + else if (style == 1) + updated = client.templates().withResponse().update("tmpl_scope", update).data(); + else if (style == 2) updated = client.async().templates().update("tmpl_scope", update).get(); + else + updated = + client.async().templates().withResponse().update("tmpl_scope", update).get().data(); + assertEquals("identity", updated.managedToolConfig().schedule().accessScope()); + assertTrue(updated.managedToolConfig().field("enabled_tools").isMissing()); + RecordedRequest patch = request(); + assertEquals("POST", patch.getMethod()); + assertEquals(get.getPath(), patch.getPath()); + assertEquals( + JSON.readTree("{\"managed_tool_config\":" + replacement + "}"), + JSON.readTree(patch.getBody().readUtf8())); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void scheduleToolDefaultsPreserveOmissionNullAndEmptyOnTheWire(boolean async) throws Exception { + List updates = + Arrays.asList( + TemplateUpdateParams.builder().build(), + TemplateUpdateParams.builder().managedToolConfig(null).build(), + TemplateUpdateParams.builder() + .managedToolConfig(ManagedToolConfig.builder().build()) + .build(), + TemplateUpdateParams.builder() + .managedToolConfig(ManagedToolConfig.builder().schedule(null).build()) + .build(), + TemplateUpdateParams.builder() + .managedToolConfig( + ManagedToolConfig.builder().enabledTools(Collections.emptyList()).build()) + .build()); + List expected = + Arrays.asList( + "{}", + "{\"managed_tool_config\":null}", + "{\"managed_tool_config\":{}}", + "{\"managed_tool_config\":{\"schedule\":null}}", + "{\"managed_tool_config\":{\"enabled_tools\":[]}}"); + for (int index = 0; index < updates.size(); index++) { + server.enqueue(json(TEMPLATE)); + if (async) client.async().templates().update("tmpl_scope", updates.get(index)).get(); + else client.templates().update("tmpl_scope", updates.get(index)); + assertEquals( + JSON.readTree(expected.get(index)), JSON.readTree(request().getBody().readUtf8())); + } + } + + @Test + void scheduleToolModelsRetainUnknownsAndSnapshotBuilderValues() { + assertThrows(ConfigurationException.class, () -> ScheduleToolConfig.builder().build()); + assertThrows( + ConfigurationException.class, () -> ScheduleToolConfig.builder().accessScope(null).build()); + assertThrows( + ConfigurationException.class, () -> ScheduleToolConfig.builder().accessScope("").build()); + assertThrows( + ConfigurationException.class, + () -> ScheduleToolConfig.builder().accessScope("identity").omit("access_scope").build()); + ScheduleToolConfig.Builder nested = + ScheduleToolConfig.builder() + .accessScope("template") + .additionalField("future_option", JsonValue.of(true)); + List selectors = new ArrayList<>(Collections.singletonList("schedule")); + ManagedToolConfig.Builder builder = + ManagedToolConfig.builder().enabledTools(selectors).schedule(nested.build()); + ManagedToolConfig snapshot = builder.build(); + nested.accessScope("identity"); + selectors.clear(); + builder.schedule(null); + assertEquals("template", snapshot.schedule().accessScope()); + assertTrue(snapshot.schedule().field("future_option").asBoolean()); + assertEquals(Collections.singletonList("schedule"), snapshot.enabledTools()); + assertTrue(builder.build().field("schedule").isNull()); + assertNull(builder.build().schedule()); + assertTrue(builder.omit("schedule").build().field("schedule").isMissing()); + assertNull(builder.build().schedule()); + assertThrows(UnsupportedOperationException.class, () -> snapshot.enabledTools().clear()); + ManagedToolConfig future = + ManagedToolConfig.fromJson( + JsonValue.parse( + "{\"schedule\":{\"access_scope\":\"future_scope\",\"new_field\":7},\"future_tool\":true}")); + assertEquals("future_scope", future.schedule().accessScope()); + assertEquals(7L, future.schedule().field("new_field").asLong()); + assertTrue(future.field("future_tool").asBoolean()); + assertEquals( + "future_scope", + ScheduleToolConfig.builder().accessScope("future_scope").build().accessScope()); + ScheduleToolConfig absent = ScheduleToolConfig.fromJson(JsonValue.parse("{}")); + ScheduleToolConfig nullable = + ScheduleToolConfig.fromJson(JsonValue.parse("{\"access_scope\":null}")); + assertNull(absent.accessScope()); + assertTrue(absent.field("access_scope").isMissing()); + assertNull(nullable.accessScope()); + assertTrue(nullable.field("access_scope").isNull()); + } + @Test void typedConfigurationMatchesIndependentWireFixture() throws Exception { TemplateCreateParams params =