diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7587e53..4e67fd2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,48 @@ permissions: contents: read jobs: + java: + runs-on: ubuntu-latest + strategy: + matrix: + java: [11, 17] + # The external session storage contract tests run against these services. + services: + redis: + image: redis:7-alpine + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s + --health-timeout 3s + --health-retries 10 + postgres: + image: postgres:17-alpine + env: + POSTGRES_USER: qoder + POSTGRES_PASSWORD: qoder + POSTGRES_DB: qoder_session_store + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U qoder -d qoder_session_store" + --health-interval 5s + --health-timeout 3s + --health-retries 10 + env: + QODER_SAMPLE_TEST_REDIS_URL: redis://127.0.0.1:6379 + QODER_SAMPLE_TEST_POSTGRES_URL: postgresql://qoder:qoder@127.0.0.1:5432/qoder_session_store + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java }} + - name: Build and test Java samples from Central + run: mvn -B -ntp -Dmaven.repo.local="${{ runner.temp }}/java-maven-cache" clean verify + working-directory: java + typescript: runs-on: ubuntu-latest steps: diff --git a/.gitignore b/.gitignore index 295ff73..2192694 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ __pycache__/ # Editors .idea/ .vscode/ + +# Java / Maven +target/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 68cc8f4..a5ddbd0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,6 +25,8 @@ this repository. environment (see the sample README). Maintainer checks use [`uv`](https://docs.astral.sh/uv/); contributors do not need `uv` to run a sample. +- Java: JDK 11 or later (17 recommended) and Maven 3.6.3 or later. Run + `mvn clean verify` from `java/`, or build a sample from its own directory. ## Sample requirements @@ -42,6 +44,12 @@ Every sample must: - Avoid shared source modules that hide the SDK calls being demonstrated. - Keep generated files and expected model output out of the sample directory. +Java coverage is incremental. Keep Java ports behaviorally equivalent and mark +missing Java entries with an em dash in both indexes. +Document differences required by the released Java API and verify them with the +actual SDK/CLI pair. Adding a Java port of an existing concept does not require +porting unrelated concepts. + ## Adding a new sample Use an existing sample (for example, `quickstart`) as a template, then register @@ -61,6 +69,29 @@ kebab-case sample name. 5. **List it in both READMEs:** add a row to the sample table in `README.md` and in `README.zh-CN.md`. +For a Java port, create `java//` with a standalone `pom.xml`, a README, +and sources under `src/main/java`. Register it in `java/pom.xml` and both sample +indexes. The Java CI job builds every registered module. Pin a released Central +SDK version, compile with `--release 8`, and keep the sample independent of +the aggregator and any SDK source checkout. Tests must run without credentials +or a real CLI; document real queries as opt-in checks. + +When updating the Java SDK, update every sample's `qoder.sdk.version` and any +explicit dependency versions, both root README compatibility lists, the Java +overview coordinate, and affected sample requirements. Validate the published +artifact using an empty Maven local repository: + +```bash +cd java +mvn -B -ntp -Dmaven.repo.local=/path/to/empty/maven-cache clean verify +``` + +Use Central or a verified Central mirror, and build each changed sample from +its own directory as well. For real queries, use the SDK's managed CLI; record +the SDK/CLI versions and platform actually exercised. Keep historical +verification records accurate. A newer version in registry metadata or a green +compile is not a real-runtime compatibility result. + Keep the TypeScript and Python versions behaviorally equivalent so readers can switch between languages. When one concept has multiple independently copyable variants, keep them in one sample directory and list every entry in its README. @@ -80,6 +111,7 @@ cd ../python && uv sync && uv run ruff check . && uv run ruff format --check . for sample in quickstart multi-turn-conversation streaming-chat code-review tool-permissions ask-user-question model-selection hooks custom-tools subagents external-session-storage; do uv run mypy "$sample" done +cd ../java && mvn -B -ntp clean verify ``` If `ruff format --check` reports changes, run `uv run ruff format .` to apply diff --git a/README.md b/README.md index 22d27ac..233401c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Qoder Agent SDK Samples Runnable, focused examples for building applications with the Qoder Agent SDK. -Every sample is available in TypeScript and Python. +Samples are available in TypeScript, Python, and Java, with coverage listed below. ## Application templates @@ -11,19 +11,19 @@ Every sample is available in TypeScript and Python. ## Samples -| Sample | What it demonstrates | TypeScript | Python | -| --- | --- | --- | --- | -| Quickstart | Run one repository-aware query and handle the result | [Open](typescript/quickstart) | [Open](python/quickstart) | -| Multi-turn conversation | Control the query lifecycle and resume context after closing | [Open](typescript/multi-turn-conversation) | [Open](python/multi-turn-conversation) | -| Streaming chat | Stream output while keeping one live session open | [Open](typescript/streaming-chat) | [Open](python/streaming-chat) | -| Code review | Review a Git diff with read-only repository tools | [Open](typescript/code-review) | [Open](python/code-review) | -| Tool permissions | Separate tool visibility, pre-approval, and runtime authorization | [Open](typescript/tool-permissions) | [Open](python/tool-permissions) | -| Ask user question | Render structured questions and return user answers | [Open](typescript/ask-user-question) | [Open](python/ask-user-question) | -| Model selection | List models and select context-window and reasoning parameters | [Open](typescript/model-selection) | [Open](python/model-selection) | -| Hooks | Add lifecycle observation, context injection, and tool policy | [Open](typescript/hooks) | [Open](python/hooks) | -| Custom tools | Expose application functions as in-process MCP tools | [Open](typescript/custom-tools) | [Open](python/custom-tools) | -| Subagents | Delegate a task to specialized SDK-defined agents | [Open](typescript/subagents) | [Open](python/subagents) | -| External session storage | Resume a session on another runtime through Redis or PostgreSQL | [Open](typescript/external-session-storage) | [Open](python/external-session-storage) | +| Sample | What it demonstrates | TypeScript | Python | Java | +| --- | --- | --- | --- | --- | +| Quickstart | Run one repository-aware query and handle the result | [Open](typescript/quickstart) | [Open](python/quickstart) | [Open](java/quickstart) | +| Multi-turn conversation | Control the query lifecycle and resume context after closing | [Open](typescript/multi-turn-conversation) | [Open](python/multi-turn-conversation) | [Open](java/multi-turn-conversation) | +| Streaming chat | Stream output while keeping one live session open | [Open](typescript/streaming-chat) | [Open](python/streaming-chat) | [Open](java/streaming-chat) | +| Code review | Review a Git diff with read-only repository tools | [Open](typescript/code-review) | [Open](python/code-review) | [Open](java/code-review) | +| Tool permissions | Separate tool visibility, pre-approval, and runtime authorization | [Open](typescript/tool-permissions) | [Open](python/tool-permissions) | [Open](java/tool-permissions) | +| Ask user question | Render structured questions and return user answers | [Open](typescript/ask-user-question) | [Open](python/ask-user-question) | [Open](java/ask-user-question) | +| Model selection | List models and select context-window and reasoning parameters | [Open](typescript/model-selection) | [Open](python/model-selection) | [Open](java/model-selection) | +| Hooks | Add lifecycle observation, context injection, and tool policy | [Open](typescript/hooks) | [Open](python/hooks) | [Open](java/hooks) | +| Custom tools | Expose application functions as in-process MCP tools | [Open](typescript/custom-tools) | [Open](python/custom-tools) | [Open](java/custom-tools) | +| Subagents | Delegate a task to specialized SDK-defined agents | [Open](typescript/subagents) | [Open](python/subagents) | [Open](java/subagents) | +| External session storage | Resume a session on another runtime through Redis or PostgreSQL | [Open](typescript/external-session-storage) | [Open](python/external-session-storage) | [Open](java/external-session-storage) | ## Setup @@ -43,6 +43,7 @@ For the complete API guide, see the - TypeScript samples: Node.js 18 or later - Python samples: Python 3.10 or later +- Java samples: JDK 11 or later (17 recommended), Maven 3.6.3 or later; see [Java setup](java) - Qoder authentication configured as described above Each sample is self-contained. Open its README for installation and run @@ -50,13 +51,15 @@ commands. ## Compatibility -The sample manifests declare compatible SDK version ranges, while the -repository lockfiles record the exact versions used by CI. +TypeScript and Python manifests declare compatible SDK version ranges; their +lockfiles record the exact versions used by CI. Java POMs pin SDK 0.2.5 from +Maven Central and compile with `--release 8`. -Last verified on July 29, 2026: +Dependency versions (build and runtime checks are reported separately): - TypeScript SDK 1.0.16 - Python SDK 1.0.10 +- Java SDK 0.2.5 ## License and terms diff --git a/README.zh-CN.md b/README.zh-CN.md index badb7c5..241b073 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,7 +1,7 @@ # Qoder Agent SDK Samples -本仓库提供面向实际开发者的 Qoder Agent SDK 示例。每个场景同时提供 -TypeScript 和 Python 实现。 +本仓库提供面向实际开发者的 Qoder Agent SDK 示例,包含 TypeScript、Python 和 Java 实现; +各语言的覆盖范围见下表。 ## 应用样板 @@ -11,19 +11,19 @@ TypeScript 和 Python 实现。 ## 示例列表 -| 示例 | 展示内容 | TypeScript | Python | -| --- | --- | --- | --- | -| Quickstart | 发起一次理解代码仓库的查询并处理结果 | [查看](typescript/quickstart) | [查看](python/quickstart) | -| Multi-turn conversation | 控制 query 生命周期并在关闭后恢复上下文 | [查看](typescript/multi-turn-conversation) | [查看](python/multi-turn-conversation) | -| Streaming chat | 在一个持续连接的会话中进行流式输出 | [查看](typescript/streaming-chat) | [查看](python/streaming-chat) | -| Code review | 使用只读仓库工具审查 Git diff | [查看](typescript/code-review) | [查看](python/code-review) | -| Tool permissions | 区分工具可见性、预授权和运行时授权 | [查看](typescript/tool-permissions) | [查看](python/tool-permissions) | -| Ask user question | 渲染结构化问题并将用户回答返回给 Agent | [查看](typescript/ask-user-question) | [查看](python/ask-user-question) | -| Model selection | 列出模型并选择上下文窗口和推理参数 | [查看](typescript/model-selection) | [查看](python/model-selection) | -| Hooks | 添加生命周期观测、上下文注入和工具策略 | [查看](typescript/hooks) | [查看](python/hooks) | -| Custom tools | 将应用函数注册为进程内 MCP 工具 | [查看](typescript/custom-tools) | [查看](python/custom-tools) | -| Subagents | 将任务委派给 SDK 定义的专业子 Agent | [查看](typescript/subagents) | [查看](python/subagents) | -| External session storage | 通过 Redis 或 PostgreSQL 在另一个运行实例上恢复会话 | [查看](typescript/external-session-storage) | [查看](python/external-session-storage) | +| 示例 | 展示内容 | TypeScript | Python | Java | +| --- | --- | --- | --- | --- | +| Quickstart | 发起一次理解代码仓库的查询并处理结果 | [查看](typescript/quickstart) | [查看](python/quickstart) | [查看](java/quickstart) | +| Multi-turn conversation | 控制 query 生命周期并在关闭后恢复上下文 | [查看](typescript/multi-turn-conversation) | [查看](python/multi-turn-conversation) | [查看](java/multi-turn-conversation) | +| Streaming chat | 在一个持续连接的会话中进行流式输出 | [查看](typescript/streaming-chat) | [查看](python/streaming-chat) | [查看](java/streaming-chat) | +| Code review | 使用只读仓库工具审查 Git diff | [查看](typescript/code-review) | [查看](python/code-review) | [查看](java/code-review) | +| Tool permissions | 区分工具可见性、预授权和运行时授权 | [查看](typescript/tool-permissions) | [查看](python/tool-permissions) | [查看](java/tool-permissions) | +| Ask user question | 渲染结构化问题并将用户回答返回给 Agent | [查看](typescript/ask-user-question) | [查看](python/ask-user-question) | [查看](java/ask-user-question) | +| Model selection | 列出模型并选择上下文窗口和推理参数 | [查看](typescript/model-selection) | [查看](python/model-selection) | [查看](java/model-selection) | +| Hooks | 添加生命周期观测、上下文注入和工具策略 | [查看](typescript/hooks) | [查看](python/hooks) | [查看](java/hooks) | +| Custom tools | 将应用函数注册为进程内 MCP 工具 | [查看](typescript/custom-tools) | [查看](python/custom-tools) | [查看](java/custom-tools) | +| Subagents | 将任务委派给 SDK 定义的专业子 Agent | [查看](typescript/subagents) | [查看](python/subagents) | [查看](java/subagents) | +| External session storage | 通过 Redis 或 PostgreSQL 在另一个运行实例上恢复会话 | [查看](typescript/external-session-storage) | [查看](python/external-session-storage) | [查看](java/external-session-storage) | ## 准备工作 @@ -37,17 +37,20 @@ export QODER_PERSONAL_ACCESS_TOKEN="" 完整 API 指南见 [Qoder Agent SDK 文档](https://docs.qoder.com/en/cli/sdk)。 TypeScript 需要 Node.js 18 或更高版本,Python 需要 Python 3.10 或更高版本。 +Java 构建需要 JDK 11 或更高版本(推荐 17)和 Maven 3.6.3 或更高版本,见 [Java 说明](java)。 每个示例都是独立项目,具体安装和运行方式见对应目录的 README。 ## 兼容性 -各示例的依赖清单声明了兼容的 SDK 版本范围,仓库锁文件则记录了 CI 使用的确切版本。 +TypeScript/Python 依赖清单声明兼容的版本范围,锁文件记录 CI 使用的确切版本。 +Java POM 固定使用 Maven Central 的 SDK 0.2.5,并以 `--release 8` 编译。 -最近一次验证时间:2026 年 7 月 29 日: +依赖版本(构建与真实运行验证分别记录): - TypeScript SDK 1.0.16 - Python SDK 1.0.10 +- Java SDK 0.2.5 ## 许可与条款 diff --git a/java/README.md b/java/README.md new file mode 100644 index 0000000..4048b21 --- /dev/null +++ b/java/README.md @@ -0,0 +1,170 @@ +# Java samples + +Start with [Quickstart](quickstart), a repository-aware query using the published +Global SDK `com.qoder.sdk:qoder-agent-sdk:0.2.5` from Maven Central. + +| Sample | Focus | +| --- | --- | +| [Quickstart](quickstart) | One repository-aware query | +| [Multi-turn conversation](multi-turn-conversation) | Turn completion, interruption, close, and resume | +| [Streaming chat](streaming-chat) | Text deltas and multiple turns on one cursor | +| [Tool permissions](tool-permissions) | Visibility, preapproval, and runtime authorization | +| [Ask user question](ask-user-question) | Structured questions answered from a terminal | +| [Hooks](hooks) | Lifecycle events, context injection, and tool policy | +| [Code review](code-review) | Bounded Git diffs and read-only review | +| [Model selection](model-selection) | Runtime catalog, parameter selection, and model policy | +| [Custom tools](custom-tools) | Application functions served as in-process MCP tools | +| [Subagents](subagents) | Delegation to agents declared in session options | +| [External session storage](external-session-storage) | Session handoff through Redis, PostgreSQL, or the reference store | + +## Requirements + +- JDK 11 or later for building (JDK 17 recommended) and Maven 3.6.3 or later. +- Sources compile with `--release 8`; the SDK supports JRE 8 or later. +- Runtime queries require `QODER_PERSONAL_ACCESS_TOKEN` and network access to + Qoder. Building and running unit tests require no token or CLI. + +Each sample has a standalone POM. You can copy a sample directory outside this +repository and build it without the aggregator or SDK source checkout. + +## Build and test + +From this directory: + +```bash +mvn -B -ntp clean verify +``` + +The root POM aggregates samples; it is not their parent. CI builds on JDK 11 and +17. Each sample POM pins its SDK version. +Use a fresh Maven local repository when verifying published SDK compatibility: + +```bash +mvn -B -ntp -Dmaven.repo.local=/path/to/empty/maven-cache clean verify +``` + +Use Maven's default Central repository or a verified Central mirror. Do not +install a local SDK build under the published version before this check. + +## Runtime + +The SDK downloads and verifies its pinned CLI on first use and reuses the cache +on later runs. Leave `QODERCLI_PATH` unset to use this managed runtime. SDK 0.2.5 +uses a separate CLI process per query and pins CLI 1.1.80; it has no daemon API. +Do not override it with CLI 1.1.81 or later, which removes that process mode. + +The default samples use Global credentials and artifacts. The CN core is a +separate artifact (`cn.qoder.sdk:qodercn-agent-sdk:0.2.5`) using +`QODERCN_PERSONAL_ACCESS_TOKEN`; never put both brands on one classpath. + +### Moving from 0.2.4 to 0.2.5 + +- `tools(Collections.emptyList())` now disables built-in tools. Omit `tools(...)` + to keep the defaults. MCP servers are configured separately: use + `strictMcpConfig(true)` to expose only the servers supplied by the application. +- `session.send(...)` now defaults to `NEXT`: a follow-up waits rather than + interrupting the active turn. The conversation samples read each turn's result + before sending another; use `interrupt()` for an intentional interruption. +- The SDK no longer loads the CLI's built-in skills. This does not disable + user, project, or plugin skills. None of the samples requires a built-in skill. + +## Verification record + +**SDK 0.2.5 (December 1, 2026).** On macOS arm64 with JDK 11 and Maven 3.9.16, +`mvn clean verify` passed for all eleven samples: 119 tests, no failures, errors, +or skips. The 46 external session storage tests ran with local Redis 8.10.3 and +PostgreSQL 17.11 enabled and also passed as a standalone Maven build. These +builds reused a cache populated from Maven Central; the Global core JAR matched +its published checksum. + +In an earlier runtime check of 0.2.5, all eleven Java entry points ran with Global +authentication and the SDK's managed CLI 1.1.80 on macOS arm64 / JDK 11. +`QODERCLI_PATH` was unset. All 13 runs on the synthetic repository exited +successfully (three backends for external session storage). + +| Sample | Observed on 0.2.5 | +| --- | --- | +| Quickstart | Read the release marker from the repository README. | +| Multi-turn conversation | After `/close` and `/resume`, the second turn returned the first turn's marker. Active interruption was not exercised. | +| Streaming chat | One session completed two turns, emitted two text deltas, and returned the remembered marker without duplicate output. | +| Code review | Identified the inverted comparison in `colors.py:2` and suggested restoring `==`. | +| Tool permissions | One host callback approved the read-only Git status command; the reply identified the modified file. | +| Ask user question | The CLI waited for two answers and summarized Production, Unit tests, and Security scan. | +| Model selection | `--defaults` selected `auto`; the policy callback ran and the query returned `MODEL_OK`. | +| Hooks | All five registered event types fired, including `PreToolUse` and `PostToolUse`. | +| Custom tools | The transcript showed one call to each in-process tool; the reply cited both the build revision and the incident ID from the fixture. | +| Subagents | Both declared agents started, and the transcript showed a separate `Agent` call for each. | +| External session storage | Redis, PostgreSQL, and the in-memory store each held 19 entries. A new CLI process returned the random marker for each backend, and each run deleted the external transcript. | + +**Local history:** If the JVM and CLI resolve different home directories, the SDK +can report that there is no local transcript even when the CLI wrote one. Set +`QODER_CONFIG_DIR` to the same absolute directory for both. With a temporary +configuration directory, the Redis and PostgreSQL entry points each stored 12 +entries, deleted the local JSONL, and resumed the same session ID with the +original marker. After cleanup each backend retained only a deletion seal. A +separate control run could not resume the session from an empty Redis namespace. + +The following records are from earlier SDK releases. + +On November 3, 2026, all seven samples passed the aggregate build and standalone +builds on macOS arm64 with JDK 11 and Global SDK 0.2.3. All 33 credential-free +tests passed (no failures, errors, or skips). Main and test classes have Java 8 +bytecode (version 52). The SDK and its parent POM were resolved from Maven Central +into a fresh local cache; the JAR matched a separate Central download. Subsequent +builds reused that verified cache, without installing the SDK from source. + +On November 6, 2026, the model selection sample changed how it disables tools +and how the policy callback validates parameters (see its +[README](model-selection#catalog-and-callback)). The aggregate build and the +standalone build passed on the same macOS arm64, JDK 11, and SDK 0.2.3 setup +with the verified cache; all 35 credential-free tests passed. The real query +below was not repeated after that change. + +On November 9, 2026, the ask user question and external session storage samples +were added. On the same macOS arm64, JDK 11, and SDK 0.2.3 setup, the aggregate +build of all nine samples passed from an empty Maven cache with empty Maven +settings: all 83 tests passed with no failures, errors, or skips. The SDK, +Jedis 8.0.2, and PostgreSQL JDBC 42.7.14 jars matched the SHA-1 values published +on Central, and the new classes have Java 8 bytecode. That run had the test URLs +of the session store contract suite set, so its 30 cases covered the SDK's +`InMemorySessionStore`, `RedisSessionStore` on a local Redis 8.10.3, and +`PostgresSessionStore` on a local PostgreSQL 17.11, including writers on three +connections racing for one transcript. Without the test URLs the same build +passed with the 20 Redis and PostgreSQL cases skipped. The service containers +that the CI job configures (`redis:7-alpine` and `postgres:17-alpine`) were not +exercised locally. + +On November 11, 2026, every sample moved to SDK 0.2.4, and the custom tools and +subagents samples were added on its new `InProcessMcpServer` and +`SessionOptions.agents` APIs. The 0.2.4 public API only adds to 0.2.3; no +existing sample code changed. On the same macOS arm64 and JDK 11 setup, the +aggregate build of all eleven samples passed from an empty Maven cache with +empty Maven settings: all 97 tests passed with no failures, errors, or skips +with the session store test URLs set (local Redis 8.10.3 and PostgreSQL 17.11), +and with the 20 Redis and PostgreSQL cases skipped without them. The SDK jar +matched the SHA-1 published on Central, its managed CLI is still 1.1.80, and +the new classes have Java 8 bytecode. Every sample was then run with real +authentication on 0.2.4; the table below records those runs. The interruption +scenario of the multi-turn conversation sample was not repeated. The CI service +containers were still not exercised locally. + +Real queries used managed CLI 1.1.80 and synthetic repositories: + +| Sample | Observed behavior | +| --- | --- | +| Quickstart | Read-only query through the documented Maven entry point summarized the synthetic README | +| Multi-turn conversation | Close/resume preserved a remembered word on 0.2.4. On November 3, active interruption returned an error, automatic close/resume recovered, and the next turn succeeded | +| Streaming chat | Two successful turns using one cursor, eight text deltas, no duplicated response | +| Tool permissions | One host callback allowed the Git status command | +| Ask user question | The agent asked both default questions; piped answers `2` and `1,3` were returned and the summary named Production, Unit tests, and Security scan. With input ending after the first answer, the request was denied and the run exited nonzero without counting an answer | +| Hooks | All five registered event types fired; a separate denied-command run had a pre-tool event and no post-tool event | +| Code review | Maven entry point reviewed a synthetic diff and found the introduced empty-array bug | +| Model selection | Runtime catalog supplied model/context choices; the policy callback ran and the queries succeeded with the interactive defaults and with `--defaults`, which returned `MODEL_OK` | +| Custom tools | For `payments-api` the recommendation cited revision `8f2a1c4` and incident `INC-1042`. For `search-api` both tools returned `Unknown service` error results, and the agent reported that it could not assess the release | +| Subagents | The CLI-local transcript shows one `Agent` call to `architecture-explorer` and one to `test-strategist`, and the plan reflected the empty synthetic workspace. With only `Agent` exposed at session level, the run failed because both agents' tool sets resolved empty; see the sample README | +| External session storage | `redis`, `postgres`, and `memory` backends: each store held 18 or 19 entries after host A, host B resumed in a second CLI process and returned the marker, and deletion left only the session's seal in Redis and PostgreSQL. On November 9, resuming a session against an empty store failed with `requested SessionStore transcript is absent or empty` while host A's local transcript still existed | + +The [conversation notes](multi-turn-conversation#lifecycle) explain the observed +interrupt race and recovery behavior. Other platforms and the CN artifact were +not exercised; the CI matrix configures JDK 11 and 17 builds, but a local JDK 11 +pass does not establish a JDK 17 CI result. diff --git a/java/ask-user-question/README.md b/java/ask-user-question/README.md new file mode 100644 index 0000000..f254b40 --- /dev/null +++ b/java/ask-user-question/README.md @@ -0,0 +1,98 @@ +# Ask user question + +Respond to the built-in `AskUserQuestion` tool from an application-owned +terminal interface. + +```text +Agent -- questions --> canUseTool handler --> terminal UI --> user + ^ | + +------------ updatedInput { questions, answers } ------+ +``` + +The sample renders question headers, option labels, and descriptions. It +supports single-select questions, comma-separated multi-select answers, and +free-text answers. + +## Requirements + +Use JDK 11 or later (17 recommended), Maven 3.6.3 or later, and +`QODER_PERSONAL_ACCESS_TOKEN` from your environment. The standalone POM resolves +`com.qoder.sdk:qoder-agent-sdk:0.2.5` from Maven Central and compiles for Java 8. +Leave `QODERCLI_PATH` unset to use the SDK's managed CLI 1.1.80. +See [Java runtime notes](../README.md#runtime); CLI 1.1.81+ is incompatible +with this SDK's separate-process mode. + +Runtime queries use your account and may consume credits. Your answers are sent +to Qoder as tool input. Do not put credentials in prompts, answers, or command +arguments. + +## Run + +From this directory: + +```bash +mvn compile exec:java +``` + +Press Enter to accept the first option, enter an option number such as `2`, or +enter comma-separated numbers such as `1,3` for a multi-select question. Text +that starts exactly one option label selects that option; any other text is +returned as a custom answer. An out-of-range number is rejected and asked again. + +An optional prompt replaces the default one, which asks for an environment and a +set of validation checks: + +```bash +mvn compile exec:java -Dexec.args='"Ask me which database to use, then recommend one."' +``` + +## Behavior + +- `tools` exposes only `AskUserQuestion`. The sample skips local settings sources + and configured MCP servers, and does not preapprove the tool, so the runtime + sends each call to `canUseTool`. +- The handler validates the question objects, reads one answer per question, + and returns `PermissionResult.allow(updatedInput)`. The updated input keeps + every original field and adds an `answers` object keyed by the exact question + text. +- Every tool other than `AskUserQuestion` is denied so the interaction stays + focused. Malformed input, cancellation, and end of terminal input are denied + with a reason instead of an answer. +- The model is `auto`, with a three-turn limit. The final result is printed once. + Answers are counted only when the whole request is allowed; a run in which + no answer reached the agent exits nonzero. + +The handler blocks while it waits for the terminal. The SDK invokes it on its +callback lane, not on the thread that reads CLI output, so the stream keeps +flowing. In SDK 0.2.5 the pending `canUseTool` callback still shares +`controlRequestTimeoutMs` (60 seconds by default) with other control operations. +The sample raises the timeout to ten minutes. This sets the SDK's wait limit; +it does not prevent earlier cancellation or unblock a terminal read. An answer +typed after cancellation is discarded and reported as a denial by the handler. + +Failures exit nonzero. Conditions the sample detects itself are printed as a +message; SDK failures report only the exception type, avoiding raw exception +details or credential logging. The cursor and client close on all paths. + +## Verify + +```bash +mvn -B -ntp clean verify +``` + +Tests use JUnit 4 and the published SDK's public API. They require no token or +CLI. This directory builds independently when copied out of the repository. + +Tests cover question parsing and malformed input, numeric, prefix, and custom +answers, invalid selections, preservation of the original input, denial of +other tools, cancellation, end of input, the session options, and result +handling. + +For a real check, answers can be piped instead of typed: + +```bash +printf '2\n1,3\n' | mvn -q compile exec:java +``` + +Look for both rendered questions, a summary that reflects the selected options, +and `Answered 2 question(s).` The exact model wording is not an assertion. diff --git a/java/ask-user-question/pom.xml b/java/ask-user-question/pom.xml new file mode 100644 index 0000000..4358edb --- /dev/null +++ b/java/ask-user-question/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + com.qoder.samples + java-ask-user-question + 1.0-SNAPSHOT + + UTF-8 + 8 + 0.2.5 + + + + com.qoder.sdk + qoder-agent-sdk + ${qoder.sdk.version} + + + junit + junit + 4.13.2 + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + + org.codehaus.mojo + exec-maven-plugin + 3.5.0 + + com.qoder.samples.questions.AskUserQuestion + + false + + + + + diff --git a/java/ask-user-question/src/main/java/com/qoder/samples/questions/AskUserQuestion.java b/java/ask-user-question/src/main/java/com/qoder/samples/questions/AskUserQuestion.java new file mode 100644 index 0000000..0ffd646 --- /dev/null +++ b/java/ask-user-question/src/main/java/com/qoder/samples/questions/AskUserQuestion.java @@ -0,0 +1,275 @@ +package com.qoder.samples.questions; + +import com.qoder.sdk.MessageCursor; +import com.qoder.sdk.OneShotQueryRequest; +import com.qoder.sdk.QoderClient; +import com.qoder.sdk.QoderQuery; +import com.qoder.sdk.SessionOptions; +import com.qoder.sdk.auth.Auth; +import com.qoder.sdk.json.JsonObject; +import com.qoder.sdk.json.JsonString; +import com.qoder.sdk.json.JsonValue; +import com.qoder.sdk.message.ResultMessage; +import com.qoder.sdk.message.ResultOutcome; +import com.qoder.sdk.message.SdkMessage; +import com.qoder.sdk.model.ModelId; +import com.qoder.sdk.model.ModelSelection; +import com.qoder.sdk.permission.CancellationToken; +import com.qoder.sdk.permission.PermissionMode; +import com.qoder.sdk.permission.PermissionResult; +import com.qoder.sdk.permission.ToolPermissionHandler; +import com.qoder.sdk.permission.ToolPermissionRequest; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicInteger; + +public final class AskUserQuestion { + static final String DEFAULT_PROMPT = "Use AskUserQuestion exactly once before making a recommendation. " + + "Ask these two questions:\n" + + "1. Header \"Environment\": \"Which deployment environment should we use?\" with options " + + "\"Staging\" and \"Production\"; single-select.\n" + + "2. Header \"Checks\": \"Which validation checks should run?\" with options \"Unit tests\", " + + "\"Integration tests\", and \"Security scan\"; multi-select.\n" + + "After receiving the answers, summarize the choices in one sentence. Do not use other tools."; + + // Allow up to ten minutes for the permission handler to answer, rather than the SDK's 60-second default. + static final long ANSWER_TIMEOUT_MS = 10 * 60 * 1000L; + + /** A failure this sample detected itself; its message contains no SDK or model output. */ + static final class SampleFailure extends RuntimeException { + SampleFailure(String message) { + super(message); + } + } + + static final class Option { + final String label; + final String description; + + Option(String label, String description) { + this.label = label; + this.description = description; + } + } + + static final class Question { + final String question; + final String header; + final List