diff --git a/README.md b/README.md index 383a24d..d8cd9eb 100644 --- a/README.md +++ b/README.md @@ -36,5 +36,7 @@ Runnable companion code for the Spring AI articles on [ankurm.com](https://ankur | [`batch-llm/`](batch-llm) | 100,000 synthetic support tickets classified by a `ChatClient` inside a Spring Batch 6 chunk step: a Resilience4j rate limiter and retry around the model call (and where Spring Batch's own retry and skip belong instead), replies that are not valid JSON skipped and recorded, a restart after `kill -9` in a second JVM that ends with a byte-identical result, and a cost ledger row committed with every chunk. **The model is a deterministic simulated `ChatModel`, not a language model; token counts are estimates and prices are configurable placeholders.** Spring Boot 4.1.2, Spring Batch 6.0.6, Spring AI 2.0.2, Resilience4j 2.4.0, Java 25. | [Spring AI + Spring Batch: Classifying 100,000 Support Tickets with an LLM](https://ankurm.com/spring-ai-spring-batch-llm-ticket-classification/) | | [`docker-model-runner/`](docker-model-runner) | The Spring AI OpenAI starter pointed at Docker Model Runner and at Ollama by changing only `base-url` and the model name (no `/v1` is appended: the path is used exactly as given), plus a benchmark runner: time to first token, decode tokens/second, container memory from `docker stats` and tool-call success over 10 runs. Measured with the real `docker/model-runner` v1.2.9 CPU image and Ollama 0.40.13 on one shared 2-vCPU sandbox, Qwen2.5-0.5B Q4_K_M; no GPU, and Docker Desktop's `docker model` path was not used. Spring Boot 4.1.2, Spring AI 2.0.2, Java 25. | [Spring AI with Docker Model Runner vs Ollama: Local LLMs Benchmarked on the Same Laptop](https://ankurm.com/spring-ai-docker-model-runner-vs-ollama/) | | [`chat-ui-htmx/`](chat-ui-htmx) | A streaming chat page with no JavaScript of our own: htmx and its SSE extension (vendored) post the message and append each token from a `Flux>` over `ChatClient` with `MessageChatMemoryAdvisor` keyed by the HTTP session. Measured traps: EventSource strips one leading space per data line, model text must be HTML-escaped, a cancelled stream left the upstream connection open in 7 of 8 runs until an OkHttp interceptor made it `call.cancel()` (closed in 8 of 8 after), and the SDK's push source ignores back-pressure (`limitRate` changes nothing; a bounded buffer does). Checked in headless Chromium. **The model is a stub OpenAI-compatible SSE server I wrote, not a language model; no real provider was run.** Spring Boot 4.1.2, Spring AI 2.0.2, htmx 2.0.11, Java 25. | [Streaming AI Chat UI with Spring AI, SSE and htmx (No React Needed)](https://ankurm.com/spring-ai-streaming-chat-ui-sse-htmx/) | +| [`tool-confirmation/`](tool-confirmation) | Human-in-the-loop tool calls in Spring AI 2.1: `@Tool(requiresConfirmation = true)`, `ToolCallConfirmationPolicy` (by metadata, by name, by argument), the pause and resume with `ToolCallDecisions`, deny messages, and what the application must add itself: a server-side pause store, an approver check, a replay guard (one winner among 16 concurrent approvers), an audit log, and an approver page over SSE and htmx with model-chosen arguments HTML-escaped. Also measured: an open SSE stream holds up Spring Boot's graceful shutdown. **The model is a scripted `ChatModel`, not a language model; the htmx page was not opened in a browser.** Spring Boot 4.1.3, Spring AI 2.1.0, Java 25. | [Human-in-the-Loop Tool Calls in Spring AI 2.1](https://ankurm.com/spring-ai-2-1-human-in-the-loop-tool-call-confirmation/) | + Upgrading from Spring AI 1.x: [migration guide](https://ankurm.com/spring-ai-1-to-2-migration-guide/). diff --git a/tool-confirmation/README.md b/tool-confirmation/README.md new file mode 100644 index 0000000..4435d4a --- /dev/null +++ b/tool-confirmation/README.md @@ -0,0 +1,78 @@ +# tool-confirmation + +Human-in-the-loop tool calls in Spring AI 2.1: `requiresConfirmation`, `ToolCallConfirmationPolicy`, +`ToolCallDecisions`, the pause and the resume, and everything the framework leaves to the +application -- where the paused reply lives, who may approve, a pause that resolves once, an audit +log, and an approver page driven by Server-Sent Events and htmx. **The model is a hand-written +`ScriptedChatModel`, not a language model**: every test queues the tool calls the "model" makes, so +what is asserted is Spring AI's real pause/resume code, not how often a real model asks for a tool. + +Companion code for [Human-in-the-Loop Tool Calls in Spring AI 2.1](https://ankurm.com/spring-ai-2-1-human-in-the-loop-tool-call-confirmation/) +on [ankurm.com](https://ankurm.com). + +## Versions + +| Component | Version | +|---|---| +| Spring Boot | 4.1.3 | +| Spring AI | 2.1.0 (GA; Maven Central lists it under 2026-11-19) | +| Java | 25 (Temurin 25.0.5.1) | +| htmx / SSE extension | 2.0.11 (vendored in `src/main/resources/static/vendor`) | + +## Quickstart + +```bash +export JAVA_HOME=/path/to/jdk-25 +./scripts/run-all.sh +``` + +No API key, no network once Maven has its dependencies, no Docker. Every file in `output/` is +written by the test suite itself (the `Transcript` helper), so each number in the article is an +assertion that fails the build when it stops being true. + +## What is here + +| File | What it does | +|---|---| +| [`tools/FlightTools.java`](src/main/java/com/ankurm/toolconfirmation/tools/FlightTools.java) | One harmless tool and two with `@Tool(requiresConfirmation = true)`. | +| [`tools/TransferTools.java`](src/main/java/com/ankurm/toolconfirmation/tools/TransferTools.java) | A tool with no annotation, paused from the outside (by name, or by its arguments). | +| [`tools/DeleteFileTool.java`](src/main/java/com/ankurm/toolconfirmation/tools/DeleteFileTool.java) | The programmatic way: `ToolMetadata.builder().requiresConfirmation(true)`. | +| [`config/ConfirmationPolicies.java`](src/main/java/com/ankurm/toolconfirmation/config/ConfirmationPolicies.java) | A `ToolCallConfirmationPolicy` bean that pauses transfers over USD 1,000. | +| [`config/ChatClientFactory.java`](src/main/java/com/ankurm/toolconfirmation/config/ChatClientFactory.java) | The one `ChatClient` construction, shared by the app and the tests. | +| [`approval/ApprovalService.java`](src/main/java/com/ankurm/toolconfirmation/approval/ApprovalService.java) | Pause handling, the approver check, resume, audit. | +| [`approval/ApprovalStore.java`](src/main/java/com/ankurm/toolconfirmation/approval/ApprovalStore.java) | Server-side pauses; `take` is atomic so one approver wins. | +| [`approval/AuditLog.java`](src/main/java/com/ankurm/toolconfirmation/approval/AuditLog.java) | PAUSED / APPROVED / DENIED / refusals, with who and what. | +| [`approval/ApprovalEvents.java`](src/main/java/com/ankurm/toolconfirmation/approval/ApprovalEvents.java) | SSE fan-out, completed on stop so graceful shutdown is not held up. | +| [`web/ApiController.java`](src/main/java/com/ankurm/toolconfirmation/web/ApiController.java) | `/api/chat`, `/api/approvals`, `/api/approvals/{id}/decisions`, `/approvals/stream`. | +| [`web/ApproverUiController.java`](src/main/java/com/ankurm/toolconfirmation/web/ApproverUiController.java) | The htmx fragments, with everything the model chose HTML-escaped. | +| [`static/approver.html`](src/main/resources/static/approver.html) | The approver page: one SSE connection, no polling. | + +## Output files + +| File | What it captures | +|---|---| +| `output/01-pause-and-resume.txt` | One gated call: pause, nothing runs, allow, run, second model call. | +| `output/02-whole-reply-pauses.txt` | A harmless call beside a gated one also waits; `awaitingDecision` lists only the gated key but every call needs a decision. | +| `output/03-deny-messages.txt` | What the model receives for a bare deny and for a deny with a message. | +| `output/04-policies.txt` | Ten policy / call combinations: which pause, which run. | +| `output/05-resume-errors.txt` | The three `IllegalArgumentException`s of a refused resume, and an empty ledger. | +| `output/06-replay-is-not-prevented.txt` | The same decisions twice: the tool runs twice. | +| `output/07-multi-round-turn.txt` | A search round before the gated call is missing from the resumed request. | +| `output/08-tools-property.txt` | `spring.ai.tools.confirmation.tools` pausing an unannotated tool. | +| `output/09-confirmation-disabled.txt` | `enabled=false`: the startup warning, the flag ignored, the policy bean still applies. | +| `output/10-http-flow.txt` | The API end to end: 200, 403, 400, 200, 409, 404. | +| `output/11-audit-log.txt` | The audit lines for that exchange. | +| `output/12-concurrent-approvers.txt` | Sixteen simultaneous approvals: one booking. | +| `output/13-approver-ui-and-sse.txt` | SSE events, and an injected tool argument rendered escaped. | +| `output/14-sse-and-graceful-shutdown.txt` | An open SSE stream against Boot's graceful shutdown, with and without closing it first. | +| `output/15-api-surface.txt` | `javap -public` of the confirmation classes in the 2.1.0 jars, and the two properties with their defaults (`scripts/api-surface.sh`). | +| `output/16-position-keys.txt` | Keys when a provider sends no id or the same id twice: `#0`, `#1`. | +| `output/17-custom-manager.txt` | A `ToolCallingManager` wrapper that does not delegate the decision overload: the pause works, the resume throws. | + +## What was NOT run + +- No real model. Whether a particular provider's model asks for the tools you expect is a separate question. +- The htmx page was never opened in a browser; the tests check the server side of it (events, fragments, escaping). +- Streaming (`.stream()`), session memory and chat-memory resumption are described in the article from the reference documentation only. +- The pause store is in memory and does not survive a restart; persisting it is left to you. +- The approver identity is a request header so the check is visible. It is a stand-in for an authenticated principal. diff --git a/tool-confirmation/output/01-pause-and-resume.txt b/tool-confirmation/output/01-pause-and-resume.txt new file mode 100644 index 0000000..dee0d28 --- /dev/null +++ b/tool-confirmation/output/01-pause-and-resume.txt @@ -0,0 +1,23 @@ +# A gated tool pauses the loop; an approval resumes it + +-- first request ---------------------------------------------- +model calls so far: 1 +reply text (content()): '' +reply has tool calls: true +awaitingDecision(reply): [call_1] +isAwaitingDecision(reply): true +tool call shown to the person: bookFlight {"flightNumber":"VX205"} +ledger (real side effects): [] +metadata key holding the keys: spring.ai.tool-calls-awaiting-decision + +-- after allow(call_1) + executeToolCalls --------------------- +ledger (real side effects): [bookFlight VX205] +conversationHistory(): + UserMessage[Book flight VX205 for tomorrow] + AssistantMessage[toolCalls=call_1:bookFlight{"flightNumber":"VX205"}] + ToolResponseMessage[call_1:bookFlight -> "Booked VX205, reference BK-5"] +returnDirect(): false + +-- resumed request -------------------------------------------- +model calls so far: 2 +final answer: Done. VX205 is booked. diff --git a/tool-confirmation/output/02-whole-reply-pauses.txt b/tool-confirmation/output/02-whole-reply-pauses.txt new file mode 100644 index 0000000..48a9680 --- /dev/null +++ b/tool-confirmation/output/02-whole-reply-pauses.txt @@ -0,0 +1,13 @@ +# One gated call pauses the whole reply, including the harmless call beside it + +calls in the reply: [call_1=searchFlights, call_2=bookFlight] +awaitingDecision(reply): [call_2] +ledger after the pause: [] + +decision for call_2 only -> IllegalArgumentException: + Every tool call of the reply needs a decision; missing: [call_1] +ledger after the refused resume: [] + +decisions for both -> ledger: [searchFlights BOS->SFO, bookFlight VX205] +tool results, in the model's order: +ToolResponseMessage[call_1:searchFlights -> "VX205 07:10 USD 240; VX311 18:40 USD 198"][call_2:bookFlight -> "Booked VX205, reference BK-5"] diff --git a/tool-confirmation/output/03-deny-messages.txt b/tool-confirmation/output/03-deny-messages.txt new file mode 100644 index 0000000..818d135 --- /dev/null +++ b/tool-confirmation/output/03-deny-messages.txt @@ -0,0 +1,12 @@ +# What the model receives when a call is denied + +DEFAULT_DENY_MESSAGE: The user did not allow this tool call. + +history the model is sent next: + UserMessage[Rebook me on VX205] + AssistantMessage[toolCalls=call_1:bookFlight{"flightNumber":"VX205"}, call_2:cancelBooking{"reference":"BK-9"}] + ToolResponseMessage[call_1:bookFlight -> The user did not allow this tool call.][call_2:cancelBooking -> The user wants an aisle seat, ask again.] + +ledger (nothing ran): [] +returnDirect(): false +model's next answer: Understood, I will ask which seat you prefer. diff --git a/tool-confirmation/output/04-policies.txt b/tool-confirmation/output/04-policies.txt new file mode 100644 index 0000000..0570cb7 --- /dev/null +++ b/tool-confirmation/output/04-policies.txt @@ -0,0 +1,13 @@ +# Which calls pause under which policy + +policy | call result +default (fromToolMetadata) | bookFlight PAUSES [c1] +default (fromToolMetadata) | transferMoney 500 runs (ledger [transferMoney ACME 500]) +none() | bookFlight runs (ledger [bookFlight VX205]) +forTools("transferMoney") | transferMoney 500 PAUSES [c2] +forTools("transferMoney") | bookFlight runs (ledger [bookFlight VX205]) +over-1000 argument policy | transferMoney 500 runs (ledger [transferMoney ACME 500]) +over-1000 argument policy | transferMoney 5000 PAUSES [c3] +over-1000 argument policy | bookFlight runs (ledger [bookFlight VX205]) +fromToolMetadata().or(over-1000)| bookFlight PAUSES [c1] +fromToolMetadata().or(over-1000)| transferMoney 5000 PAUSES [c3] diff --git a/tool-confirmation/output/05-resume-errors.txt b/tool-confirmation/output/05-resume-errors.txt new file mode 100644 index 0000000..eae7ea0 --- /dev/null +++ b/tool-confirmation/output/05-resume-errors.txt @@ -0,0 +1,10 @@ +# Three refused resumes + +1. no decision for call_1: + IllegalArgumentException: Every tool call of the reply needs a decision; missing: [call_1] +2. a decision for a key that is not in the reply (call_99): + IllegalArgumentException: No tool call has the key 'call_99'; the reply's tool call keys: [call_1] +3. allowed call, but its tool is not on the Prompt: + IllegalArgumentException: The prompt does not carry the tool 'bookFlight' of the allowed call 'call_1'; an allowed call runs only with a tool of the prompt + +ledger after all three: [] diff --git a/tool-confirmation/output/06-replay-is-not-prevented.txt b/tool-confirmation/output/06-replay-is-not-prevented.txt new file mode 100644 index 0000000..95db1d5 --- /dev/null +++ b/tool-confirmation/output/06-replay-is-not-prevented.txt @@ -0,0 +1,5 @@ +# executeToolCalls twice with the same decisions on the same reply + +calls to executeToolCalls: 2 +ledger: [bookFlight VX205, bookFlight VX205] +A customer is booked, and charged, twice. diff --git a/tool-confirmation/output/07-multi-round-turn.txt b/tool-confirmation/output/07-multi-round-turn.txt new file mode 100644 index 0000000..f960cfe --- /dev/null +++ b/tool-confirmation/output/07-multi-round-turn.txt @@ -0,0 +1,19 @@ +# Search (ungated) then book (gated) in one turn: what the model sees on each call + +ledger at the pause: [searchFlights BOS->SFO] +model calls: 3 + +prompt 1 sent to the model: + UserMessage[Find a flight BOS to SFO and book the first one] + +prompt 2 sent to the model: + UserMessage[Find a flight BOS to SFO and book the first one] + AssistantMessage[toolCalls=s1:searchFlights{"from":"BOS","to":"SFO"}] + ToolResponseMessage[s1:searchFlights -> "VX205 07:10 USD 240; VX311 18:40 USD 198"] + +prompt 3 sent to the model: + UserMessage[Find a flight BOS to SFO and book the first one] + AssistantMessage[toolCalls=b1:bookFlight{"flightNumber":"VX205"}] + ToolResponseMessage[b1:bookFlight -> "Booked VX205, reference BK-5"] + +Prompt 2 had the search round; prompt 3 (the resume) does not. diff --git a/tool-confirmation/output/08-tools-property.txt b/tool-confirmation/output/08-tools-property.txt new file mode 100644 index 0000000..1f39de8 --- /dev/null +++ b/tool-confirmation/output/08-tools-property.txt @@ -0,0 +1,5 @@ +# spring.ai.tools.confirmation.tools=transferMoney (a USD 5 transfer, far under the 1000 policy bean) + +status: AWAITING_APPROVAL +calls: [CallView[key=t1, name=transferMoney, arguments={"payee":"ACME","amount":5}]] +ledger: [] diff --git a/tool-confirmation/output/09-confirmation-disabled.txt b/tool-confirmation/output/09-confirmation-disabled.txt new file mode 100644 index 0000000..9ff56bf --- /dev/null +++ b/tool-confirmation/output/09-confirmation-disabled.txt @@ -0,0 +1,6 @@ +# spring.ai.tools.confirmation.enabled=false + +startup warning: WARN ToolCallingAutoConfiguration: Tool call confirmation is disabled (spring.ai.tools.confirmation.enabled=false): tools marked requiresConfirmation run as soon as the model calls them, without a person's confirmation. + +bookFlight (requiresConfirmation = true): status=DONE ledger=[bookFlight VX205] +transferMoney 5000 (policy bean): status=AWAITING_APPROVAL ledger=[bookFlight VX205] diff --git a/tool-confirmation/output/10-http-flow.txt b/tool-confirmation/output/10-http-flow.txt new file mode 100644 index 0000000..623c36e --- /dev/null +++ b/tool-confirmation/output/10-http-flow.txt @@ -0,0 +1,27 @@ +# The approval API over HTTP + +POST /api/chat (carol: Book VX205) + -> 200 {"status":"AWAITING_APPROVAL","answer":null,"approvalId":"4dbe1483","calls":[{"key":"call_1","name":"bookFlight","arguments":"{\"flightNumber\":\"VX205\"}"}]} + ledger: [] + +GET /api/approvals + -> 200 [{"id":"4dbe1483","conversationId":"c1","requestedBy":"carol","calls":[{"key":"call_1","name":"bookFlight","arguments":"{\"flightNumber\":\"VX205\"}"}]}] + +POST /api/approvals/4dbe1483/decisions X-Approver: mallory (allow call_1) + -> 403 {"error":"'mallory' may not approve"} + ledger: [] + +POST /api/approvals/4dbe1483/decisions X-Approver: alice (no decisions) + -> 400 {"error":"Every tool call of the reply needs a decision; missing: [call_1]"} + still pending: true + +POST /api/approvals/4dbe1483/decisions X-Approver: alice (allow call_1) + -> 200 {"status":"DONE","answer":"Booked VX205. Reference BK-5.","approvalId":null,"calls":[]} + ledger: [bookFlight VX205] + +POST /api/approvals/4dbe1483/decisions X-Approver: bob (the same pause again) + -> 409 {"error":"approval 4dbe1483 was already resolved"} + ledger: [bookFlight VX205] + +POST /api/approvals/nope0000/decisions X-Approver: alice + -> 404 {"error":"no such approval nope0000"} diff --git a/tool-confirmation/output/11-audit-log.txt b/tool-confirmation/output/11-audit-log.txt new file mode 100644 index 0000000..d837f6c --- /dev/null +++ b/tool-confirmation/output/11-audit-log.txt @@ -0,0 +1,7 @@ +# What the audit log recorded for that exchange + +PAUSED approval=4dbe1483 actor=carol tool=bookFlight {"flightNumber":"VX205"} +APPROVER_REFUSED approval=4dbe1483 actor=mallory tool=- not in the approver list +DECISION_REJECTED approval=4dbe1483 actor=alice tool=- Every tool call of the reply needs a decision; missing: [call_1] +APPROVED approval=4dbe1483 actor=alice tool=bookFlight {"flightNumber":"VX205"} +REPLAY_REFUSED approval=4dbe1483 actor=bob tool=- pause already resolved diff --git a/tool-confirmation/output/12-concurrent-approvers.txt b/tool-confirmation/output/12-concurrent-approvers.txt new file mode 100644 index 0000000..8f7c81c --- /dev/null +++ b/tool-confirmation/output/12-concurrent-approvers.txt @@ -0,0 +1,5 @@ +# 16 threads approve the same pause at once + + 1 x 200 DONE +15 x 409 approval was already resolved +ledger: [bookFlight VX205] diff --git a/tool-confirmation/output/13-approver-ui-and-sse.txt b/tool-confirmation/output/13-approver-ui-and-sse.txt new file mode 100644 index 0000000..9d5744b --- /dev/null +++ b/tool-confirmation/output/13-approver-ui-and-sse.txt @@ -0,0 +1,23 @@ +# Approver page: SSE events and an escaped fragment (injected tool argument) + +tool argument chosen by the model: + +SSE lines the approver page received: + event:hello + data:connected + event:approval-requested + data:69b1d486 + event:approval-resolved + data:69b1d486 + +GET /ui/approvals (the
 element):
+  
{"flightNumber":"<img src=x onerror=alert(1)>"}
+ +POST /ui/approvals/69b1d486 (approver=alice, deny) -> +

Decision recorded.

+ledger: [] + +approver.html wiring: + + +
diff --git a/tool-confirmation/output/14-sse-and-graceful-shutdown.txt b/tool-confirmation/output/14-sse-and-graceful-shutdown.txt new file mode 100644 index 0000000..476c258 --- /dev/null +++ b/tool-confirmation/output/14-sse-and-graceful-shutdown.txt @@ -0,0 +1,5 @@ +# ctx.close() with one approver page connected (grace period 5000 ms) + +streams left open: over 4000 ms +streams completed by the lifecycle: under 2000 ms +(the exact figures vary per run; the 5 s wall is the configured grace period) diff --git a/tool-confirmation/output/15-api-surface.txt b/tool-confirmation/output/15-api-surface.txt new file mode 100644 index 0000000..4650247 --- /dev/null +++ b/tool-confirmation/output/15-api-surface.txt @@ -0,0 +1,63 @@ +# Public API of the confirmation classes, from spring-ai-model-2.1.0.jar (javap -public) + +public interface org.springframework.ai.model.tool.ToolCallConfirmationPolicy { + public abstract boolean requiresConfirmation(org.springframework.ai.chat.messages.AssistantMessage$ToolCall, org.springframework.ai.tool.metadata.ToolMetadata); + public default org.springframework.ai.model.tool.ToolCallConfirmationPolicy or(org.springframework.ai.model.tool.ToolCallConfirmationPolicy); + public static org.springframework.ai.model.tool.ToolCallConfirmationPolicy none(); + public static org.springframework.ai.model.tool.ToolCallConfirmationPolicy fromToolMetadata(); + public static org.springframework.ai.model.tool.ToolCallConfirmationPolicy forTools(java.lang.String...); +} + +public class org.springframework.ai.model.tool.ToolCallConfirmationRequiredException extends java.lang.RuntimeException { + public org.springframework.ai.model.tool.ToolCallConfirmationRequiredException(java.util.List); + public java.util.List getToolCallIds(); +} + +public final class org.springframework.ai.model.tool.ToolCallDecision extends java.lang.Record { + public static final java.lang.String DEFAULT_DENY_MESSAGE; + public org.springframework.ai.model.tool.ToolCallDecision(java.lang.String, boolean, java.lang.String); + public static org.springframework.ai.model.tool.ToolCallDecision allow(java.lang.String); + public static org.springframework.ai.model.tool.ToolCallDecision deny(java.lang.String); + public static org.springframework.ai.model.tool.ToolCallDecision deny(java.lang.String, java.lang.String); + public java.lang.String denyMessage(); + public final java.lang.String toString(); + public final int hashCode(); + public final boolean equals(java.lang.Object); + public java.lang.String toolCallId(); + public boolean allowed(); + public java.lang.String message(); +} + +public final class org.springframework.ai.model.tool.ToolCallDecisions extends java.lang.Record { + public static final java.lang.String POSITION_KEY_PREFIX; + public static final java.lang.String AWAITING_DECISION_METADATA_KEY; + public org.springframework.ai.model.tool.ToolCallDecisions(java.util.List); + public static org.springframework.ai.model.tool.ToolCallDecisions of(org.springframework.ai.model.tool.ToolCallDecision...); + public org.springframework.ai.model.tool.ToolCallDecision decisionOn(java.lang.String); + public static java.util.List toolCallKeys(org.springframework.ai.chat.messages.AssistantMessage); + public static java.util.List awaitingDecision(org.springframework.ai.chat.model.ChatResponse); + public static boolean isAwaitingDecision(org.springframework.ai.chat.model.ChatResponse); + public final java.lang.String toString(); + public final int hashCode(); + public final boolean equals(java.lang.Object); + public java.util.List decisions(); +} + +public interface org.springframework.ai.tool.metadata.ToolMetadata { + public default boolean returnDirect(); + public default boolean requiresConfirmation(); + public static org.springframework.ai.tool.metadata.DefaultToolMetadata$Builder builder(); + public static org.springframework.ai.tool.metadata.ToolMetadata from(java.lang.reflect.Method); +} + +# ToolCallingManager (the overload resumption uses is a default method) +public interface org.springframework.ai.model.tool.ToolCallingManager { + public abstract java.util.List resolveToolDefinitions(org.springframework.ai.model.tool.ToolCallingChatOptions); + public abstract org.springframework.ai.model.tool.ToolExecutionResult executeToolCalls(org.springframework.ai.chat.prompt.Prompt, org.springframework.ai.chat.model.ChatResponse); + public default org.springframework.ai.model.tool.ToolExecutionResult executeToolCalls(org.springframework.ai.chat.prompt.Prompt, org.springframework.ai.chat.model.ChatResponse, org.springframework.ai.model.tool.ToolCallDecisions); + public static org.springframework.ai.model.tool.DefaultToolCallingManager$Builder builder(); +} + +# Configuration properties, from spring-ai-autoconfigure-model-tool-2.1.0.jar +spring.ai.tools.confirmation.enabled | default: True +spring.ai.tools.confirmation.tools | default: None diff --git a/tool-confirmation/output/16-position-keys.txt b/tool-confirmation/output/16-position-keys.txt new file mode 100644 index 0000000..cc4d555 --- /dev/null +++ b/tool-confirmation/output/16-position-keys.txt @@ -0,0 +1,7 @@ +# Tool call keys when ids are missing or repeated + +POSITION_KEY_PREFIX: # +two calls that both have id 'dup' -> keys: [#0, #1] +awaitingDecision for that reply: [#0, #1] +one call with an empty id -> keys: [#0] +allow('#0') + deny('#1') -> ledger: [bookFlight VX205] diff --git a/tool-confirmation/output/17-custom-manager.txt b/tool-confirmation/output/17-custom-manager.txt new file mode 100644 index 0000000..bd9760c --- /dev/null +++ b/tool-confirmation/output/17-custom-manager.txt @@ -0,0 +1,5 @@ +# A ToolCallingManager that wraps the default and forgets the decision overload + +pause through the wrapping manager: awaitingDecision = [call_1] +resume through the wrapping manager: UnsupportedOperationException: com.ankurm.toolconfirmation.CustomManagerTest$ForgetfulManager does not support tool call decisions +ledger: [] diff --git a/tool-confirmation/pom.xml b/tool-confirmation/pom.xml new file mode 100644 index 0000000..0a4fc3a --- /dev/null +++ b/tool-confirmation/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.3 + + + + com.ankurm + tool-confirmation + 1.0.0 + tool-confirmation + Human-in-the-loop tool calls in Spring AI 2.1: requiresConfirmation, ToolCallConfirmationPolicy, ToolCallDecisions, pause and resume, an approval API with SSE and htmx, and an audit log. + + + 25 + + 2.1.0 + + + + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + + org.springframework.ai + spring-ai-starter-model-openai + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + -Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8 + + + + + diff --git a/tool-confirmation/scripts/api-surface.sh b/tool-confirmation/scripts/api-surface.sh new file mode 100755 index 0000000..28cd0fc --- /dev/null +++ b/tool-confirmation/scripts/api-surface.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Writes output/15-api-surface.txt: the public API of the confirmation classes as the 2.1.0 jars +# declare it (javap), and the two configuration properties from the autoconfigure metadata. +# Requires the jars in ~/.m2 (run ./scripts/run-all.sh or any build once) and JDK 25 on PATH. +set -euo pipefail +cd "$(dirname "$0")/.." +M="${HOME}/.m2/repository/org/springframework/ai" +MODEL="$M/spring-ai-model/2.1.0/spring-ai-model-2.1.0.jar" +AUTO="$M/spring-ai-autoconfigure-model-tool/2.1.0/spring-ai-autoconfigure-model-tool-2.1.0.jar" +OUT=output/15-api-surface.txt +{ + echo "# Public API of the confirmation classes, from spring-ai-model-2.1.0.jar (javap -public)" + echo + for c in ToolCallConfirmationPolicy ToolCallConfirmationRequiredException ToolCallDecision ToolCallDecisions; do + javap -cp "$MODEL" -public "org.springframework.ai.model.tool.$c" 2>/dev/null | grep -v '^Compiled from' + echo + done + javap -cp "$MODEL" -public org.springframework.ai.tool.metadata.ToolMetadata 2>/dev/null | grep -v '^Compiled from' + echo + echo "# ToolCallingManager (the overload resumption uses is a default method)" + javap -cp "$MODEL" -public org.springframework.ai.model.tool.ToolCallingManager 2>/dev/null | grep -v '^Compiled from' + echo + echo "# Configuration properties, from spring-ai-autoconfigure-model-tool-2.1.0.jar" + unzip -p "$AUTO" META-INF/spring-configuration-metadata.json | python3 -c " +import json, sys +for p in json.load(sys.stdin)['properties']: + if 'confirmation' in p['name']: + print(p['name'], '| default:', p.get('defaultValue'))" +} > "$OUT" +cat "$OUT" diff --git a/tool-confirmation/scripts/run-all.sh b/tool-confirmation/scripts/run-all.sh new file mode 100755 index 0000000..4d044eb --- /dev/null +++ b/tool-confirmation/scripts/run-all.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Regenerates every file under output/ -- the test suite writes each one itself through the +# Transcript helper, overwriting it in place. No file in output/ is hand-captured. +# Needs JDK 25 on PATH (JAVA_HOME) and Maven; no API key, no Docker, no network once the +# dependencies are in the local repository. +set -euo pipefail +cd "$(dirname "$0")/.." +rm -rf target +mvn -q test +./scripts/api-surface.sh > /dev/null diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/ToolConfirmationApplication.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/ToolConfirmationApplication.java new file mode 100644 index 0000000..d7e9823 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/ToolConfirmationApplication.java @@ -0,0 +1,14 @@ +package com.ankurm.toolconfirmation; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class ToolConfirmationApplication { + + public static void main(String[] args) { + SpringApplication.run(ToolConfirmationApplication.class, args); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalEvents.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalEvents.java new file mode 100644 index 0000000..9985adc --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalEvents.java @@ -0,0 +1,84 @@ +package com.ankurm.toolconfirmation.approval; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.SmartLifecycle; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +/** Fan-out of "something changed" to every open approver page over Server-Sent Events. */ +@Component +public class ApprovalEvents implements SmartLifecycle { + + private final List emitters = new CopyOnWriteArrayList<>(); + private volatile boolean running; + private final boolean closeStreamsOnStop; + + /** The flag exists only so output/14 can measure the cost of leaving it off. Keep it true. */ + public ApprovalEvents(@Value("${app.approval.close-streams-on-stop:true}") boolean closeStreamsOnStop) { + this.closeStreamsOnStop = closeStreamsOnStop; + } + + public SseEmitter subscribe() { + SseEmitter emitter = new SseEmitter(0L); + this.emitters.add(emitter); + emitter.onCompletion(() -> this.emitters.remove(emitter)); + emitter.onTimeout(() -> this.emitters.remove(emitter)); + emitter.onError(e -> this.emitters.remove(emitter)); + try { + emitter.send(SseEmitter.event().name("hello").data("connected")); + } + catch (IOException e) { + this.emitters.remove(emitter); + } + return emitter; + } + + public void publish(String eventName, String data) { + for (SseEmitter emitter : this.emitters) { + try { + emitter.send(SseEmitter.event().name(eventName).data(data)); + } + catch (IOException | IllegalStateException e) { + this.emitters.remove(emitter); + } + } + } + + /** + * Graceful shutdown waits for in-flight requests, and an open SSE stream is one that never + * finishes: with Spring Boot's default 30 s grace period an open approver page delays every + * stop by 30 s. {@code @PreDestroy} is too late (it runs after the web server has already + * waited), so this stops first: the highest phase is stopped before the web server's. + */ + @Override + public void start() { + this.running = true; + } + + @Override + public void stop() { + if (this.closeStreamsOnStop) { + this.emitters.forEach(SseEmitter::complete); + this.emitters.clear(); + } + this.running = false; + } + + @Override + public boolean isRunning() { + return this.running; + } + + @Override + public int getPhase() { + return Integer.MAX_VALUE; + } + + public int subscribers() { + return this.emitters.size(); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalException.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalException.java new file mode 100644 index 0000000..56ec896 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalException.java @@ -0,0 +1,18 @@ +package com.ankurm.toolconfirmation.approval; + +import org.springframework.http.HttpStatus; + +/** A refusal that maps to an HTTP status. */ +public class ApprovalException extends RuntimeException { + + private final HttpStatus status; + + public ApprovalException(HttpStatus status, String message) { + super(message); + this.status = status; + } + + public HttpStatus status() { + return this.status; + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalProperties.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalProperties.java new file mode 100644 index 0000000..2565f58 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalProperties.java @@ -0,0 +1,23 @@ +package com.ankurm.toolconfirmation.approval; + +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Who may approve. Spring AI does not authenticate the approver: the framework hands your + * application a paused reply and takes decisions back. Deciding WHO may decide is yours. This + * module uses a plain name list so the check is visible; a real service would read the + * authenticated principal and its authorities instead of a request parameter. + */ +@ConfigurationProperties(prefix = "app.approval") +public record ApprovalProperties(List approvers) { + + public ApprovalProperties { + approvers = approvers == null ? List.of() : List.copyOf(approvers); + } + + public boolean mayApprove(String name) { + return name != null && this.approvers.contains(name); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalService.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalService.java new file mode 100644 index 0000000..e137d0f --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalService.java @@ -0,0 +1,132 @@ +package com.ankurm.toolconfirmation.approval; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import com.ankurm.toolconfirmation.tools.ToolRegistry; + +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.messages.UserMessage; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.ai.model.tool.ToolCallDecision; +import org.springframework.ai.model.tool.ToolCallDecisions; +import org.springframework.ai.model.tool.ToolCallingChatOptions; +import org.springframework.ai.model.tool.ToolCallingManager; +import org.springframework.ai.model.tool.ToolExecutionResult; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +/** + * The application half of human-in-the-loop. Spring AI supplies the pause and the resume; this + * class supplies everything around them: where the paused reply lives, who may decide, that a pause + * is resolved once, and a record of what happened. + */ +@Service +public class ApprovalService { + + public record Verdict(String key, boolean allow, String message) { + } + + private final ChatClient chatClient; + private final ToolCallingManager toolCallingManager; + private final ToolRegistry tools; + private final ConversationStore conversations; + private final ApprovalStore store; + private final ApprovalProperties properties; + private final AuditLog audit; + private final ApprovalEvents events; + + public ApprovalService(ChatClient chatClient, ToolCallingManager toolCallingManager, ToolRegistry tools, + ConversationStore conversations, ApprovalStore store, ApprovalProperties properties, AuditLog audit, + ApprovalEvents events) { + this.chatClient = chatClient; + this.toolCallingManager = toolCallingManager; + this.tools = tools; + this.conversations = conversations; + this.store = store; + this.properties = properties; + this.audit = audit; + this.events = events; + } + + /** A new user turn. Returns the answer, or a pause when a gated tool was requested. */ + public ChatResult chat(String conversationId, String user, String text) { + List conversation = this.conversations.get(conversationId); + conversation.add(new UserMessage(text)); + ChatResponse reply = this.chatClient.prompt().messages(conversation).call().chatResponse(); + return handle(conversationId, user, conversation, reply); + } + + /** An approver's verdicts for one paused turn. */ + public ChatResult decide(String approvalId, String approver, List verdicts) { + PendingApproval pending = this.store.find(approvalId).orElse(null); + if (pending == null) { + if (this.store.wasResolved(approvalId)) { + this.audit.record("REPLAY_REFUSED", approvalId, approver, "-", "pause already resolved"); + throw new ApprovalException(HttpStatus.CONFLICT, "approval " + approvalId + " was already resolved"); + } + throw new ApprovalException(HttpStatus.NOT_FOUND, "no such approval " + approvalId); + } + if (!this.properties.mayApprove(approver)) { + this.audit.record("APPROVER_REFUSED", approvalId, String.valueOf(approver), "-", "not in the approver list"); + throw new ApprovalException(HttpStatus.FORBIDDEN, "'" + approver + "' may not approve"); + } + pending = this.store.take(approvalId).orElseThrow( + () -> new ApprovalException(HttpStatus.CONFLICT, "approval " + approvalId + " was already resolved")); + + ToolCallDecisions decisions = ToolCallDecisions.of(verdicts.stream() + .map(v -> v.allow() ? ToolCallDecision.allow(v.key()) + : (v.message() == null || v.message().isBlank() ? ToolCallDecision.deny(v.key()) + : ToolCallDecision.deny(v.key(), v.message()))) + .toArray(ToolCallDecision[]::new)); + + ToolExecutionResult result; + try { + Prompt prompt = new Prompt(pending.conversation(), + ToolCallingChatOptions.builder().toolCallbacks(this.tools.callbacks()).build()); + for (CallView call : pending.calls()) { + ToolCallDecision decision = decisions.decisionOn(call.key()); + if (decision != null) { + this.audit.record(decision.allowed() ? "APPROVED" : "DENIED", approvalId, approver, call.name(), + call.arguments()); + } + } + result = this.toolCallingManager.executeToolCalls(prompt, pending.reply(), decisions); + } + catch (IllegalArgumentException e) { + // Nothing ran: the manager validates the whole decision list before executing any call. + this.store.restore(pending); + this.audit.record("DECISION_REJECTED", approvalId, approver, "-", e.getMessage()); + throw new ApprovalException(HttpStatus.BAD_REQUEST, e.getMessage()); + } + + List history = new ArrayList<>(result.conversationHistory()); + ChatResponse next = this.chatClient.prompt().messages(history).call().chatResponse(); + this.events.publish("approval-resolved", approvalId); + return handle(pending.conversationId(), pending.requestedBy(), history, next); + } + + private ChatResult handle(String conversationId, String user, List conversation, ChatResponse reply) { + List awaiting = ToolCallDecisions.awaitingDecision(reply); + if (!awaiting.isEmpty()) { + PendingApproval pending = new PendingApproval(UUID.randomUUID().toString().substring(0, 8), + conversationId, user, Instant.now(), List.copyOf(conversation), reply, awaiting); + this.store.add(pending); + this.conversations.save(conversationId, conversation); + for (CallView call : pending.calls()) { + this.audit.record("PAUSED", pending.id(), user, call.name(), call.arguments()); + } + this.events.publish("approval-requested", pending.id()); + return ChatResult.awaiting(pending); + } + AssistantMessage output = reply.getResult().getOutput(); + conversation.add(output); + this.conversations.save(conversationId, conversation); + return ChatResult.done(output.getText()); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalStore.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalStore.java new file mode 100644 index 0000000..a8c6fac --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ApprovalStore.java @@ -0,0 +1,53 @@ +package com.ankurm.toolconfirmation.approval; + +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.stereotype.Component; + +/** + * In-memory store of paused turns. {@link #take} removes and returns in one atomic step, so when + * two approvers click at the same moment exactly one of them gets the pause, which is the replay + * guard the framework does not provide. It does not survive a restart: a paused reply is ordinary + * data, so a real service would persist it (and the conversation) in a database. + */ +@Component +public class ApprovalStore { + + private final Map pending = new ConcurrentHashMap<>(); + private final Set issued = ConcurrentHashMap.newKeySet(); + + public void add(PendingApproval approval) { + this.issued.add(approval.id()); + this.pending.put(approval.id(), approval); + } + + public Optional find(String id) { + return Optional.ofNullable(this.pending.get(id)); + } + + /** Atomic: the first caller gets the pause, every later caller gets empty. */ + public Optional take(String id) { + return Optional.ofNullable(this.pending.remove(id)); + } + + /** Put a pause back when resuming failed before anything ran (a bad decision list). */ + public void restore(PendingApproval approval) { + this.pending.put(approval.id(), approval); + } + + /** Known to this store once, and not pending now. Derived, so there is no window between the two. */ + public boolean wasResolved(String id) { + return this.issued.contains(id) && !this.pending.containsKey(id); + } + + public List pending() { + Collection all = this.pending.values(); + return all.stream().sorted(Comparator.comparing(PendingApproval::createdAt)).toList(); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/AuditLog.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/AuditLog.java new file mode 100644 index 0000000..419544d --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/AuditLog.java @@ -0,0 +1,44 @@ +package com.ankurm.toolconfirmation.approval; + +import java.time.Instant; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +/** + * One line per decision point. The framework logs nothing about WHO approved WHAT, because it does + * not know who anyone is; this is the record an auditor will ask for. Kept in memory here so tests + * can read it back; in production write it to an append-only table. + */ +@Component +public class AuditLog { + + private static final Logger log = LoggerFactory.getLogger("audit"); + + public record Event(Instant at, String type, String approvalId, String actor, String tool, String detail) { + + public String line() { + return "%s approval=%s actor=%s tool=%s %s".formatted(this.type, this.approvalId, this.actor, + this.tool, this.detail); + } + } + + private final List events = new CopyOnWriteArrayList<>(); + + public void record(String type, String approvalId, String actor, String tool, String detail) { + Event event = new Event(Instant.now(), type, approvalId, actor, tool, detail); + this.events.add(event); + log.info(event.line()); + } + + public List events() { + return List.copyOf(this.events); + } + + public void clear() { + this.events.clear(); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/CallView.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/CallView.java new file mode 100644 index 0000000..3fc206a --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/CallView.java @@ -0,0 +1,5 @@ +package com.ankurm.toolconfirmation.approval; + +/** What an approver is shown for one call: the key to answer with, the tool, and its arguments. */ +public record CallView(String key, String name, String arguments) { +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ChatResult.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ChatResult.java new file mode 100644 index 0000000..e96ce7a --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ChatResult.java @@ -0,0 +1,15 @@ +package com.ankurm.toolconfirmation.approval; + +import java.util.List; + +/** Either a final answer, or a pause the caller must route to an approver. */ +public record ChatResult(String status, String answer, String approvalId, List calls) { + + public static ChatResult done(String answer) { + return new ChatResult("DONE", answer, null, List.of()); + } + + public static ChatResult awaiting(PendingApproval approval) { + return new ChatResult("AWAITING_APPROVAL", null, approval.id(), approval.calls()); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ConversationStore.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ConversationStore.java new file mode 100644 index 0000000..ca2c021 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/ConversationStore.java @@ -0,0 +1,24 @@ +package com.ankurm.toolconfirmation.approval; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.ai.chat.messages.Message; +import org.springframework.stereotype.Component; + +/** The conversation the application keeps. Spring AI keeps no state while a call is paused. */ +@Component +public class ConversationStore { + + private final Map> conversations = new ConcurrentHashMap<>(); + + public List get(String conversationId) { + return new ArrayList<>(this.conversations.getOrDefault(conversationId, List.of())); + } + + public void save(String conversationId, List messages) { + this.conversations.put(conversationId, List.copyOf(messages)); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/PendingApproval.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/PendingApproval.java new file mode 100644 index 0000000..78b6a53 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/approval/PendingApproval.java @@ -0,0 +1,29 @@ +package com.ankurm.toolconfirmation.approval; + +import java.time.Instant; +import java.util.List; + +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.model.tool.ToolCallDecisions; + +/** + * A paused turn, kept SERVER-SIDE. The reply held here is the one the model actually produced; + * the approver only ever sends keys and verdicts. If a client could replace the reply, it could run + * any tool with any arguments and approve its own call. + */ +public record PendingApproval(String id, String conversationId, String requestedBy, Instant createdAt, + List conversation, ChatResponse reply, List awaiting) { + + public List calls() { + AssistantMessage message = this.reply.getResult().getOutput(); + List keys = ToolCallDecisions.toolCallKeys(message); + List views = new java.util.ArrayList<>(); + for (int i = 0; i < keys.size(); i++) { + AssistantMessage.ToolCall call = message.getToolCalls().get(i); + views.add(new CallView(keys.get(i), call.name(), call.arguments())); + } + return views; + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ChatClientConfig.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ChatClientConfig.java new file mode 100644 index 0000000..b472599 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ChatClientConfig.java @@ -0,0 +1,22 @@ +package com.ankurm.toolconfirmation.config; + +import com.ankurm.toolconfirmation.tools.ToolRegistry; + +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.model.tool.ToolCallingManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration(proxyBeanMethods = false) +public class ChatClientConfig { + + /** + * {@code manager} is the auto-configured {@code ToolCallingManager}: it already carries the + * policy built from the flag, the property and every policy bean. + */ + @Bean + ChatClient chatClient(ChatModel chatModel, ToolCallingManager manager, ToolRegistry tools) { + return ChatClientFactory.create(chatModel, manager, tools.callbacks()); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ChatClientFactory.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ChatClientFactory.java new file mode 100644 index 0000000..eb9e68a --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ChatClientFactory.java @@ -0,0 +1,41 @@ +package com.ankurm.toolconfirmation.config; + +import java.util.List; + +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.client.advisor.ToolCallingAdvisor; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.model.tool.ToolCallingChatOptions; +import org.springframework.ai.model.tool.ToolCallingManager; +import org.springframework.ai.tool.ToolCallback; + +/** + * The one place a {@link ChatClient} is built, shared by the Spring configuration and by the + * plain unit tests, so the wiring under test is the wiring that ships. + * + *

The {@link ToolCallingManager} is passed to the advisor and reused to resume a + * paused call. The confirmation check lives in the manager, not in the advisor, so a different + * manager at resume time would apply a different policy. + */ +public final class ChatClientFactory { + + private ChatClientFactory() { + } + + public static ChatClient create(ChatModel chatModel, ToolCallingManager manager, List tools) { + ToolCallingAdvisor advisor = ToolCallingAdvisor.builder().toolCallingManager(manager).build(); + return ChatClient.builder(chatModel) + .defaultOptions(baseOptions(chatModel)) + .defaultToolCallbacks(tools) + .defaultAdvisors(advisor) + .build(); + } + + /** ToolCallingAdvisor only engages when the request options are ToolCallingChatOptions. */ + private static ToolCallingChatOptions.Builder baseOptions(ChatModel chatModel) { + if (chatModel.getOptions() instanceof ToolCallingChatOptions existing) { + return existing.mutate(); + } + return ToolCallingChatOptions.builder(); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ConfirmationPolicies.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ConfirmationPolicies.java new file mode 100644 index 0000000..6ff42e8 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/config/ConfirmationPolicies.java @@ -0,0 +1,37 @@ +package com.ankurm.toolconfirmation.config; + +import org.springframework.ai.model.tool.ToolCallConfirmationPolicy; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * A policy bean. Spring AI's auto-configuration ORs every {@link ToolCallConfirmationPolicy} + * bean with the {@code requiresConfirmation} flag and the {@code spring.ai.tools.confirmation.tools} + * property: a bean can only add calls that need confirmation, never remove any. + */ +@Configuration(proxyBeanMethods = false) +public class ConfirmationPolicies { + + static final int TRANSFER_LIMIT = 1_000; + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Bean + ToolCallConfirmationPolicy largeTransfers() { + return (toolCall, toolMetadata) -> toolCall.name().equals("transferMoney") + && amountOf(toolCall.arguments()) > TRANSFER_LIMIT; + } + + /** Model-supplied JSON is untrusted: an unreadable amount is treated as "needs a person". */ + static int amountOf(String argumentsJson) { + try { + JsonNode amount = JSON.readTree(argumentsJson).path("amount"); + return amount.isNumber() ? amount.asInt() : Integer.MAX_VALUE; + } + catch (RuntimeException e) { + return Integer.MAX_VALUE; + } + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/BookingLedger.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/BookingLedger.java new file mode 100644 index 0000000..b2ec961 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/BookingLedger.java @@ -0,0 +1,29 @@ +package com.ankurm.toolconfirmation.tools; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.springframework.stereotype.Component; + +/** + * The record of real side effects. Every tool in this module writes one line here when it + * actually runs, so a test can assert "nothing happened" while a call is paused, which is the + * whole point of the feature. + */ +@Component +public class BookingLedger { + + private final List entries = new CopyOnWriteArrayList<>(); + + public void record(String entry) { + this.entries.add(entry); + } + + public List entries() { + return List.copyOf(this.entries); + } + + public void clear() { + this.entries.clear(); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/DeleteFileTool.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/DeleteFileTool.java new file mode 100644 index 0000000..0acfe30 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/DeleteFileTool.java @@ -0,0 +1,31 @@ +package com.ankurm.toolconfirmation.tools; + +import org.springframework.ai.tool.ToolCallback; +import org.springframework.ai.tool.annotation.ToolParam; +import org.springframework.ai.tool.function.FunctionToolCallback; +import org.springframework.ai.tool.metadata.ToolMetadata; + +/** + * The programmatic way to set the flag: a {@link FunctionToolCallback} whose + * {@link ToolMetadata} carries {@code requiresConfirmation(true)}. Same effect as the annotation, + * for tools that are not methods on a bean. + */ +public final class DeleteFileTool { + + public record DeleteRequest(@ToolParam(description = "Path of the file to delete") String path) { + } + + private DeleteFileTool() { + } + + public static ToolCallback create(BookingLedger ledger) { + return FunctionToolCallback.builder("deleteFile", (DeleteRequest request) -> { + ledger.record("deleteFile " + request.path()); + return "Deleted " + request.path(); + }) + .description("Delete a file by path. Irreversible.") + .inputType(DeleteRequest.class) + .toolMetadata(ToolMetadata.builder().requiresConfirmation(true).build()) + .build(); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/FlightTools.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/FlightTools.java new file mode 100644 index 0000000..ef8a190 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/FlightTools.java @@ -0,0 +1,37 @@ +package com.ankurm.toolconfirmation.tools; + +import org.springframework.ai.tool.annotation.Tool; +import org.springframework.stereotype.Component; + +/** + * One harmless tool and two that change the world. {@code requiresConfirmation = true} on the + * annotation is the whole opt-in: it sets the flag on the {@code ToolMetadata} that Spring AI + * builds for the method, and the default policy reads it. + */ +@Component +public class FlightTools { + + private final BookingLedger ledger; + + public FlightTools(BookingLedger ledger) { + this.ledger = ledger; + } + + @Tool(description = "Search flights between two cities. Read-only.") + public String searchFlights(String from, String to) { + this.ledger.record("searchFlights " + from + "->" + to); + return "VX205 07:10 USD 240; VX311 18:40 USD 198"; + } + + @Tool(description = "Book a flight by flight number. Charges the customer.", requiresConfirmation = true) + public String bookFlight(String flightNumber) { + this.ledger.record("bookFlight " + flightNumber); + return "Booked " + flightNumber + ", reference BK-" + Math.abs(flightNumber.hashCode() % 1000); + } + + @Tool(description = "Cancel a booking by its reference.", requiresConfirmation = true) + public String cancelBooking(String reference) { + this.ledger.record("cancelBooking " + reference); + return "Cancelled " + reference; + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/ToolRegistry.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/ToolRegistry.java new file mode 100644 index 0000000..7f04fe6 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/ToolRegistry.java @@ -0,0 +1,32 @@ +package com.ankurm.toolconfirmation.tools; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.ai.support.ToolCallbacks; +import org.springframework.ai.tool.ToolCallback; +import org.springframework.stereotype.Component; + +/** + * One list of tool callbacks, used twice: registered on the {@code ChatClient} for the first + * request, and handed to {@code Prompt} options again when a paused call is resumed. Resumption + * never looks tools up by name on its own, so an allowed call whose tool is missing from the + * prompt is an error (see output/05). + */ +@Component +public class ToolRegistry { + + private final List callbacks; + + public ToolRegistry(FlightTools flightTools, TransferTools transferTools, BookingLedger ledger) { + List all = new ArrayList<>(); + all.addAll(List.of(ToolCallbacks.from(flightTools))); + all.addAll(List.of(ToolCallbacks.from(transferTools))); + all.add(DeleteFileTool.create(ledger)); + this.callbacks = List.copyOf(all); + } + + public List callbacks() { + return this.callbacks; + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/TransferTools.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/TransferTools.java new file mode 100644 index 0000000..560f9a4 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/tools/TransferTools.java @@ -0,0 +1,26 @@ +package com.ankurm.toolconfirmation.tools; + +import org.springframework.ai.tool.annotation.Tool; +import org.springframework.stereotype.Component; + +/** + * A tool that is NOT annotated {@code requiresConfirmation}. It models a tool you cannot or will + * not touch (a library, an MCP server): the policy has to name it from the outside, either by + * name ({@code forTools}) or by inspecting the arguments (the policy bean in + * {@code config.ConfirmationPolicies}). + */ +@Component +public class TransferTools { + + private final BookingLedger ledger; + + public TransferTools(BookingLedger ledger) { + this.ledger = ledger; + } + + @Tool(description = "Transfer money to a payee. Amount is in whole US dollars.") + public String transferMoney(String payee, int amount) { + this.ledger.record("transferMoney " + payee + " " + amount); + return "Transferred USD " + amount + " to " + payee; + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/web/ApiController.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/web/ApiController.java new file mode 100644 index 0000000..c1bc15f --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/web/ApiController.java @@ -0,0 +1,74 @@ +package com.ankurm.toolconfirmation.web; + +import java.util.List; +import java.util.Map; + +import com.ankurm.toolconfirmation.approval.ApprovalEvents; +import com.ankurm.toolconfirmation.approval.ApprovalException; +import com.ankurm.toolconfirmation.approval.ApprovalService; +import com.ankurm.toolconfirmation.approval.ApprovalStore; +import com.ankurm.toolconfirmation.approval.CallView; +import com.ankurm.toolconfirmation.approval.ChatResult; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +@RestController +public class ApiController { + + public record ChatRequest(String conversationId, String user, String message) { + } + + public record DecisionRequest(List decisions) { + } + + public record PendingView(String id, String conversationId, String requestedBy, List calls) { + } + + private final ApprovalService service; + private final ApprovalStore store; + private final ApprovalEvents events; + + public ApiController(ApprovalService service, ApprovalStore store, ApprovalEvents events) { + this.service = service; + this.store = store; + this.events = events; + } + + @PostMapping("/api/chat") + public ChatResult chat(@RequestBody ChatRequest request) { + return this.service.chat(request.conversationId(), request.user(), request.message()); + } + + @GetMapping("/api/approvals") + public List pending() { + return this.store.pending() + .stream() + .map(p -> new PendingView(p.id(), p.conversationId(), p.requestedBy(), p.calls())) + .toList(); + } + + /** The approver's identity comes from a header here ONLY so the check is visible. */ + @PostMapping("/api/approvals/{id}/decisions") + public ChatResult decide(@PathVariable String id, @RequestHeader("X-Approver") String approver, + @RequestBody DecisionRequest request) { + return this.service.decide(id, approver, request.decisions()); + } + + @GetMapping("/approvals/stream") + public SseEmitter stream() { + return this.events.subscribe(); + } + + @ExceptionHandler(ApprovalException.class) + ResponseEntity> refused(ApprovalException e) { + return ResponseEntity.status(e.status()).body(Map.of("error", e.getMessage())); + } +} diff --git a/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/web/ApproverUiController.java b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/web/ApproverUiController.java new file mode 100644 index 0000000..bb9b9d8 --- /dev/null +++ b/tool-confirmation/src/main/java/com/ankurm/toolconfirmation/web/ApproverUiController.java @@ -0,0 +1,91 @@ +package com.ankurm.toolconfirmation.web; + +import java.util.List; + +import com.ankurm.toolconfirmation.approval.ApprovalException; +import com.ankurm.toolconfirmation.approval.ApprovalService; +import com.ankurm.toolconfirmation.approval.ApprovalStore; +import com.ankurm.toolconfirmation.approval.CallView; +import com.ankurm.toolconfirmation.approval.PendingApproval; + +import org.springframework.http.MediaType; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.util.HtmlUtils; + +/** + * Server-rendered HTML fragments for the htmx approver page (static/approver.html). Everything + * that came from the model -- tool names and, above all, arguments -- is HTML-escaped, because the + * model chose those strings and a prompt-injected model can choose markup. + */ +@RestController +public class ApproverUiController { + + private final ApprovalStore store; + private final ApprovalService service; + + public ApproverUiController(ApprovalStore store, ApprovalService service) { + this.store = store; + this.service = service; + } + + @GetMapping(path = "/ui/approvals", produces = MediaType.TEXT_HTML_VALUE) + public String list() { + List pending = this.store.pending(); + if (pending.isEmpty()) { + return "

Nothing is waiting for approval.

"; + } + StringBuilder html = new StringBuilder(); + for (PendingApproval p : pending) { + html.append(card(p)); + } + return html.toString(); + } + + @PostMapping(path = "/ui/approvals/{id}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, + produces = MediaType.TEXT_HTML_VALUE) + public String decide(@PathVariable String id, @RequestBody MultiValueMap form) { + PendingApproval pending = this.store.find(id).orElse(null); + if (pending == null) { + return "

That approval is no longer pending.

" + list(); + } + List verdicts = pending.calls() + .stream() + .map(c -> new ApprovalService.Verdict(c.key(), "allow".equals(form.getFirst("decision-" + c.key())), + form.getFirst("message-" + c.key()))) + .toList(); + try { + this.service.decide(id, form.getFirst("approver"), verdicts); + return "

Decision recorded.

" + list(); + } + catch (ApprovalException e) { + return "

" + HtmlUtils.htmlEscape(e.getMessage()) + "

" + list(); + } + } + + static String card(PendingApproval p) { + StringBuilder html = new StringBuilder(); + html.append("
"); + html.append("

Approval ").append(HtmlUtils.htmlEscape(p.id())).append(" — requested by ") + .append(HtmlUtils.htmlEscape(String.valueOf(p.requestedBy()))).append("

"); + for (CallView call : p.calls()) { + String key = HtmlUtils.htmlEscape(call.key()); + html.append("
").append(HtmlUtils.htmlEscape(call.name())).append(" ") + .append("
").append(HtmlUtils.htmlEscape(call.arguments())).append("
") + .append(" ") + .append(" ") + .append("
"); + } + html.append(" "); + html.append("
"); + return html.toString(); + } +} diff --git a/tool-confirmation/src/main/resources/application.yml b/tool-confirmation/src/main/resources/application.yml new file mode 100644 index 0000000..6a0591e --- /dev/null +++ b/tool-confirmation/src/main/resources/application.yml @@ -0,0 +1,12 @@ +spring: + application: + name: tool-confirmation + ai: + openai: + # No real key is needed to run this module's tests: they replace the ChatModel with a scripted + # one. The placeholder only lets the context start standalone with a real key in OPENAI_API_KEY. + api-key: ${OPENAI_API_KEY:demo-key-not-used-by-tests} + +app: + approval: + approvers: alice,bob diff --git a/tool-confirmation/src/main/resources/static/approver.html b/tool-confirmation/src/main/resources/static/approver.html new file mode 100644 index 0000000..f7a5209 --- /dev/null +++ b/tool-confirmation/src/main/resources/static/approver.html @@ -0,0 +1,20 @@ + + + + + Pending tool approvals + + + + + + +

Pending tool approvals

+
+ + diff --git a/tool-confirmation/src/main/resources/static/vendor/SHA256SUMS b/tool-confirmation/src/main/resources/static/vendor/SHA256SUMS new file mode 100644 index 0000000..3ae79dc --- /dev/null +++ b/tool-confirmation/src/main/resources/static/vendor/SHA256SUMS @@ -0,0 +1,2 @@ +d6fdc75f204e6bdefa99b69bf1e6d4ac69b8a364f77929f45c13476b4000f717 htmx.min.js +3b5992a541619babefc4c169505af474df5c3039da51e59b96ccf9241ecd61d2 htmx-ext-sse.js diff --git a/tool-confirmation/src/main/resources/static/vendor/htmx-ext-sse.js b/tool-confirmation/src/main/resources/static/vendor/htmx-ext-sse.js new file mode 100644 index 0000000..886e3f9 --- /dev/null +++ b/tool-confirmation/src/main/resources/static/vendor/htmx-ext-sse.js @@ -0,0 +1,290 @@ +/* +Server Sent Events Extension +============================ +This extension adds support for Server Sent Events to htmx. See /www/extensions/sse.md for usage instructions. + +*/ + +(function() { + /** @type {import("../htmx").HtmxInternalApi} */ + var api + + htmx.defineExtension('sse', { + + /** + * Init saves the provided reference to the internal HTMX API. + * + * @param {import("../htmx").HtmxInternalApi} api + * @returns void + */ + init: function(apiRef) { + // store a reference to the internal API. + api = apiRef + + // set a function in the public API for creating new EventSource objects + if (htmx.createEventSource == undefined) { + htmx.createEventSource = createEventSource + } + }, + + getSelectors: function() { + return ['[sse-connect]', '[data-sse-connect]', '[sse-swap]', '[data-sse-swap]'] + }, + + /** + * onEvent handles all events passed to this extension. + * + * @param {string} name + * @param {Event} evt + * @returns void + */ + onEvent: function(name, evt) { + var parent = evt.target || evt.detail.elt + switch (name) { + case 'htmx:beforeCleanupElement': + var internalData = api.getInternalData(parent) + // Try to remove remove an EventSource when elements are removed + var source = internalData.sseEventSource + if (source) { + api.triggerEvent(parent, 'htmx:sseClose', { + source, + type: 'nodeReplaced', + }) + internalData.sseEventSource.close() + } + + return + + // Try to create EventSources when elements are processed + case 'htmx:afterProcessNode': + ensureEventSourceOnElement(parent) + } + } + }) + + /// //////////////////////////////////////////// + // HELPER FUNCTIONS + /// //////////////////////////////////////////// + + /** + * createEventSource is the default method for creating new EventSource objects. + * it is hoisted into htmx.config.createEventSource to be overridden by the user, if needed. + * + * @param {string} url + * @returns EventSource + */ + function createEventSource(url) { + return new EventSource(url, { withCredentials: true }) + } + + /** + * registerSSE looks for attributes that can contain sse events, right + * now hx-trigger and sse-swap and adds listeners based on these attributes too + * the closest event source + * + * @param {HTMLElement} elt + */ + function registerSSE(elt) { + // Add message handlers for every `sse-swap` attribute + if (api.getAttributeValue(elt, 'sse-swap')) { + // Find closest existing event source + var sourceElement = api.getClosestMatch(elt, hasEventSource) + if (sourceElement == null) { + // api.triggerErrorEvent(elt, "htmx:noSSESourceError") + return null // no eventsource in parentage, orphaned element + } + + // Set internalData and source + var internalData = api.getInternalData(sourceElement) + var source = internalData.sseEventSource + + var sseSwapAttr = api.getAttributeValue(elt, 'sse-swap') + var sseEventNames = sseSwapAttr.split(',') + + for (var i = 0; i < sseEventNames.length; i++) { + const sseEventName = sseEventNames[i].trim() + const listener = function(event) { + // If the source is missing then close SSE + if (maybeCloseSSESource(sourceElement)) { + return + } + + // If the body no longer contains the element, remove the listener + if (!api.bodyContains(elt)) { + source.removeEventListener(sseEventName, listener) + return + } + + // swap the response into the DOM and trigger a notification + if (!api.triggerEvent(elt, 'htmx:sseBeforeMessage', event)) { + return + } + swap(elt, event.data) + api.triggerEvent(elt, 'htmx:sseMessage', event) + } + + // Register the new listener + api.getInternalData(elt).sseEventListener = listener + source.addEventListener(sseEventName, listener) + } + } + + // Add message handlers for every `hx-trigger="sse:*"` attribute + if (api.getAttributeValue(elt, 'hx-trigger')) { + // Find closest existing event source + var sourceElement = api.getClosestMatch(elt, hasEventSource) + if (sourceElement == null) { + // api.triggerErrorEvent(elt, "htmx:noSSESourceError") + return null // no eventsource in parentage, orphaned element + } + + // Set internalData and source + var internalData = api.getInternalData(sourceElement) + var source = internalData.sseEventSource + + var triggerSpecs = api.getTriggerSpecs(elt) + triggerSpecs.forEach(function(ts) { + if (ts.trigger.slice(0, 4) !== 'sse:') { + return + } + + var listener = function (event) { + if (maybeCloseSSESource(sourceElement)) { + return + } + if (!api.bodyContains(elt)) { + source.removeEventListener(ts.trigger.slice(4), listener) + } + // Trigger events to be handled by the rest of htmx + htmx.trigger(elt, ts.trigger, event) + htmx.trigger(elt, 'htmx:sseMessage', event) + } + + // Register the new listener + api.getInternalData(elt).sseEventListener = listener + source.addEventListener(ts.trigger.slice(4), listener) + }) + } + } + + /** + * ensureEventSourceOnElement creates a new EventSource connection on the provided element. + * If a usable EventSource already exists, then it is returned. If not, then a new EventSource + * is created and stored in the element's internalData. + * @param {HTMLElement} elt + * @param {number} retryCount + * @returns {EventSource | null} + */ + function ensureEventSourceOnElement(elt, retryCount) { + if (elt == null) { + return null + } + + // handle extension source creation attribute + if (api.getAttributeValue(elt, 'sse-connect')) { + var sseURL = api.getAttributeValue(elt, 'sse-connect') + if (sseURL == null) { + return + } + + ensureEventSource(elt, sseURL, retryCount) + } + + registerSSE(elt) + } + + function ensureEventSource(elt, url, retryCount) { + var source = htmx.createEventSource(url) + + source.onerror = function(err) { + // Log an error event + api.triggerErrorEvent(elt, 'htmx:sseError', { error: err, source }) + + // If parent no longer exists in the document, then clean up this EventSource + if (maybeCloseSSESource(elt)) { + return + } + + // Otherwise, try to reconnect the EventSource + if (source.readyState === EventSource.CLOSED) { + retryCount = retryCount || 0 + retryCount = Math.max(Math.min(retryCount * 2, 128), 1) + var timeout = retryCount * 500 + window.setTimeout(function() { + ensureEventSourceOnElement(elt, retryCount) + }, timeout) + } + } + + source.onopen = function(evt) { + api.triggerEvent(elt, 'htmx:sseOpen', { source }) + + if (retryCount && retryCount > 0) { + const childrenToFix = elt.querySelectorAll("[sse-swap], [data-sse-swap], [hx-trigger], [data-hx-trigger]") + for (let i = 0; i < childrenToFix.length; i++) { + registerSSE(childrenToFix[i]) + } + // We want to increase the reconnection delay for consecutive failed attempts only + retryCount = 0 + } + } + + api.getInternalData(elt).sseEventSource = source + + + var closeAttribute = api.getAttributeValue(elt, "sse-close"); + if (closeAttribute) { + // close eventsource when this message is received + source.addEventListener(closeAttribute, function() { + api.triggerEvent(elt, 'htmx:sseClose', { + source, + type: 'message', + }) + source.close() + }); + } + } + + /** + * maybeCloseSSESource confirms that the parent element still exists. + * If not, then any associated SSE source is closed and the function returns true. + * + * @param {HTMLElement} elt + * @returns boolean + */ + function maybeCloseSSESource(elt) { + if (!api.bodyContains(elt)) { + var source = api.getInternalData(elt).sseEventSource + if (source != undefined) { + api.triggerEvent(elt, 'htmx:sseClose', { + source, + type: 'nodeMissing', + }) + source.close() + // source = null + return true + } + } + return false + } + + + /** + * @param {HTMLElement} elt + * @param {string} content + */ + function swap(elt, content) { + api.withExtensions(elt, function(extension) { + content = extension.transformResponse(content, null, elt) + }) + + var swapSpec = api.getSwapSpecification(elt) + var target = api.getTarget(elt) + api.swap(target, content, swapSpec, { contextElement: elt }) + } + + + function hasEventSource(node) { + return api.getInternalData(node).sseEventSource != null + } +})() diff --git a/tool-confirmation/src/main/resources/static/vendor/htmx.min.js b/tool-confirmation/src/main/resources/static/vendor/htmx.min.js new file mode 100644 index 0000000..e6b8394 --- /dev/null +++ b/tool-confirmation/src/main/resources/static/vendor/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Y={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=pn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.11"};Y.onLoad=V;Y.process=Bt;Y.on=ye;Y.off=xe;Y.trigger=ae;Y.ajax=In;Y.find=a;Y.findAll=x;Y.closest=g;Y.remove=z;Y.addClass=w;Y.removeClass=S;Y.toggleClass=G;Y.takeClass=W;Y.swap=C;Y.defineExtension=zn;Y.removeExtension=Jn;Y.logAll=$;Y.logNone=_;Y.parseInterval=d;Y._=e;const n={addTriggerHandler:Et,bodyContains:ie,canAccessLocalStorage:U,findThisElement:we,filterValues:xn,swap:C,hasAttribute:s,getAttributeValue:f,getClosestAttributeValue:te,getClosestMatch:A,getExpressionVars:qn,getHeaders:yn,getInputValues:pn,getInternalData:re,getSwapSpecification:vn,getTriggerSpecs:lt,getTarget:Se,makeFragment:D,mergeObjects:se,makeSettleInfo:En,oobSwap:Te,querySelectorExt:ce,settleImmediately:Qt,shouldCancel:dt,triggerEvent:ae,triggerErrorEvent:ue,withExtensions:Vt};const he=["get","post","put","delete","patch"];const R=he.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function Q(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function f(e,t){return Q(e,t)||Q(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ee(){return document}function q(e,t){return e.getRootNode?e.getRootNode({composed:t}):ee()}function A(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=f(t,n);const o=f(t,"hx-disinherit");var i=f(t,"hx-inherit");if(e!==t){if(Y.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function te(t,n){let r=null;A(t,function(e){return!!(r=o(t,le(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function N(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function I(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=ee().createElement("script");oe(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Y.config.inlineScriptNonce){t.nonce=Y.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function k(e){if(!Y.config.allowScriptTags){e.querySelectorAll("script").forEach(e=>e.remove());return}Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){T(e)}finally{e.remove()}}})}function D(e){e=e.replace(/]*)?)>/gi,'");const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=N(t);let r;if(n==="html"){r=new DocumentFragment;const i=I(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=I(t);L(r,i.body);r.title=i.title}else{const i=I('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){k(r)}return r}function ne(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function P(e){return typeof e==="function"}function M(e){return t(e,"Object")}function re(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function F(t){const n=[];if(t){for(let e=0;e=0}function ie(e){return e.getRootNode({composed:true})===document}function X(e){return e.trim().split(/\s+/)}function se(e,t){return Object.assign({},e,t)}function v(e){try{return JSON.parse(e)}catch(e){T(e);return null}}function U(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function j(e){try{const t=new URL(e,window.location.href);e=t.pathname+t.search}catch(e){}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return Tn(ee().body,function(){return eval(e)})}function V(t){const e=Y.on("htmx:load",function(e){t(e.detail.elt)});return e}function $(){Y.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Y.logger=null}function a(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return a(ee(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ee(),e)}}function b(){return window}function z(e,t){e=E(e);if(t){b().setTimeout(function(){z(e);e=null},t)}else{u(e).removeChild(e)}}function le(e){return e instanceof Element?e:null}function J(e){return e instanceof HTMLElement?e:null}function K(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function w(e,t,n){e=le(E(e));if(!e){return}if(n){b().setTimeout(function(){w(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function S(e,t,n){let r=le(E(e));if(!r){return}if(n){b().setTimeout(function(){S(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function G(e,t){e=E(e);e.classList.toggle(t)}function W(e,t){e=E(e);oe(e.parentElement.children,function(e){S(e,t)});w(le(e),t)}function g(e,t){e=le(E(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Z(e,t){return e.substring(e.length-t.length)===t}function de(e){const t=e.trim();if(l(t,"<")&&Z(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=E(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=de(o.shift());let e;if(r.indexOf("closest ")===0){e=g(le(t),de(r.slice(8)))}else if(r.indexOf("find ")===0){e=a(p(t),de(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=le(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,de(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=le(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=ge(t,de(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=q(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=p(q(t,!!n));i.push(...F(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=p(q(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ce(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(ee().body,e)[0]}}function E(e,t){if(typeof e==="string"){return a(p(t)||document,e)}else{return e}}function me(e,t,n,r){if(P(t)){return{target:ee().body,event:K(e),listener:t,options:n}}else{return{target:E(e),event:K(t),listener:n,options:r}}}function ye(t,n,r,o){Wn(function(){const e=me(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=P(n);return e?n:r}function xe(t,n,r){Wn(function(){const e=me(t,n,r);e.target.removeEventListener(e.event,e.listener)});return P(n)?n:r}const be=ee().createElement("output");function ve(t,n){const e=te(t,n);if(e){if(e==="this"){return[we(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=le(A(t,function(e){return e!==t&&s(le(e),n)}));if(i){r.push(...ve(i,n))}}if(r.length===0){T('The selector "'+e+'" on '+n+" returned no matches!");return[be]}else{return r}}}}function we(e,t){return le(A(e,function(e){return f(le(e),t)!=null}))}function Se(e){const t=te(e,"hx-target");if(t){if(t==="this"){return we(e,"hx-target")}else{return ce(e,t)}}else{const n=re(e);if(n.boosted){return ee().body}else{return e}}}function Ee(e){return Y.config.attributesToSettle.includes(e)}function Ce(t,n){oe(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ee(e.name)){t.removeAttribute(e.name)}});oe(n.attributes,function(e){if(Ee(e.name)){t.setAttribute(e.name,e.value)}})}function Oe(t,e){const n=Kn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){oe(r,function(e){let t;const n=o.cloneNode(true);t=ee().createDocumentFragment();t.appendChild(n);if(!Oe(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){Re(t);Ve(s,e,e,t,i);He()}oe(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);ue(ee().body,"htmx:oobErrorNoTarget",{content:o,target:n})}return e}function He(){const e=a("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=a("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function Re(e){oe(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=f(e,"id");const n=ee().getElementById(t);if(n!=null){if(e.moveBefore){let e=a("#--htmx-preserve-pantry--");if(e==null){ee().body.insertAdjacentHTML("afterend","
");e=a("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function qe(i,e,s){oe(e.querySelectorAll("[id]"),function(t){const n=Q(t,"id");if(n&&n.length>0){const e=p(i);const r=e&&e.querySelector(CSS.escape(t.tagName)+"#"+CSS.escape(n));if(r&&r!==e){const o=t.cloneNode();Ce(t,r);s.tasks.push(function(){Ce(t,o)})}}})}function Ae(e){return function(){S(e,Y.config.addedClass);Bt(le(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=J(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){qe(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;w(le(o),Y.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function _e(e,n,r){var t=x(e,"[hx-swap-oob], [data-hx-swap-oob]");oe(t,function(e){if(Y.config.allowNestedOobSwaps||e.parentElement===null){const t=f(e,"hx-swap-oob");if(t!=null){Te(t,e,n,r)}}else{e.removeAttribute("hx-swap-oob");e.removeAttribute("data-hx-swap-oob")}});return t.length>0}function C(d,p,g,m){if(!m){m={}}let y=null;let n=null;let e=function(){ne(m.beforeSwapCallback);d=E(d);const r=m.contextElement&&m.contextElement.isConnected?q(m.contextElement,false):ee();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=En(d);if(g.swapStyle==="textContent"){d.textContent=p}else{let n=typeof p==="string"?D(p):p;o.title=m.title||n.title;if(m.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(m.selectOOB){const s=m.selectOOB.split(",");for(let t=0;t0){b().setTimeout(n,g.settleDelay)}else{n()}};let t=Y.config.globalViewTransitions;if(g.hasOwnProperty("transition")){t=g.transition}const r=m.contextElement||ee();if(t&&ae(r,"htmx:beforeTransition",m.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){y=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(g?.swapDelay&&g.swapDelay>0){b().setTimeout(e,g.swapDelay)}else{e()}}catch(e){ue(r,"htmx:swapError",m.eventInfo);ne(n);throw e}}function ze(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r)||{};for(const i of Object.keys(o)){let e=o[i];if(M(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=Tn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){ue(ee().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(nt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function ot(e){let t;if(e.length>0&&Qe.test(e[0])){e.shift();t=O(e,et).trim();e.shift()}else{t=O(e,Ke)}return t}const it="input, textarea, select";function st(e,t,n){const r=[];const o=tt(t);do{O(o,Ye);const l=o.length;const c=O(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};O(o,Ye);u.pollInterval=d(O(o,/[,\[\s]/));O(o,Ye);var i=rt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=rt(e,o,"event");if(i){a.eventFilter=i}O(o,Ye);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(O(o,Ke))}else if(f==="from"&&o[0]===":"){o.shift();if(Qe.test(o[0])){var s=ot(o)}else{var s=O(o,Ke);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=ot(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=ot(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(O(o,Ke))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=O(o,Ke)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=ot(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=O(o,Ke)}else{ue(e,"htmx:syntax:error",{token:o.shift()})}O(o,Ye)}r.push(a)}}if(o.length===l){ue(e,"htmx:syntax:error",{token:o.shift()})}O(o,Ye)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function lt(e){const t=f(e,"hx-trigger");let n=[];if(t){const r=Y.config.triggerSpecsCache;n=r&&r[t]||st(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,it)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function ct(e){re(e).cancelled=true}function ut(e,t,n){const r=re(e);r.timeout=b().setTimeout(function(){if(ie(e)&&r.cancelled!==true){if(!gt(n,e,Ut("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ut(e,t,n)}},n.pollInterval)}function at(e){return location.hostname===e.hostname&&Q(e,"href")&&Q(e,"href").indexOf("#")!==0}function ft(e){return g(e,Y.config.disableSelector)}function ht(t,n,e){if(t instanceof HTMLAnchorElement&&at(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(Q(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=Q(t,"href")}else{const i=Q(t,"method");r=i?i.toLowerCase():"get";o=Q(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){mt(t,function(e,t){const n=le(e);if(ft(n)){y(n);return}fe(r,o,n,t)},n,e,true)})}}function dt(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function pt(e,t){return re(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;ue(ee().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function mt(l,c,e,u,a){const f=re(l);let t;if(u.from){t=m(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}oe(t,function(i){const s=function(e){if(!ie(l)){i.removeEventListener(u.trigger,s);return}if(pt(l,e)){return}if(a||dt(e,i)){e.preventDefault()}if(gt(u,l,e)){return}const t=re(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(le(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=e.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){ae(l,"htmx:trigger");c(l,e);f.throttle=b().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=b().setTimeout(function(){ae(l,"htmx:trigger");c(l,e)},u.delay)}else{ae(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let yt=false;let xt=null;function bt(){if(!xt){xt=function(){yt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(yt){yt=false;oe(ee().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){vt(e)})}},200)}}function vt(e){if(!s(e,"data-hx-revealed")&&B(e)){e.setAttribute("data-hx-revealed","true");const t=re(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function wt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){b().setTimeout(o,r)}else{o()}}function St(t,n,e){let i=false;oe(he,function(r){if(s(t,"hx-"+r)){const o=f(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){Et(t,e,n,function(e,t){const n=le(e);if(ft(n)){y(n);return}fe(r,o,n,t)})})}});return i}function Et(r,e,t,n){if(e.trigger==="revealed"){bt();mt(r,n,t,e);vt(le(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ce(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ut(le(r),n,e)}else{mt(r,n,t,e)}}function Ct(e){const t=le(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function qt(e){const t=Nt(e.target);const n=Lt(e);if(n){n.lastButtonClicked=t}}function At(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Nt(e){return g(le(e),"button, input[type='submit']")}function It(e){return e.form||g(e,"form")}function Lt(e){const t=Nt(e.target);if(!t){return}const n=It(t);if(!n){return}return re(n)}function kt(e){e.addEventListener("click",qt);e.addEventListener("focusin",qt);e.addEventListener("focusout",At)}function Dt(t,e,n){const r=re(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){Tn(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){ke(t);for(let e=0;eY.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){ue(ee().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Kt(t){if(!U()){return null}t=j(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(ee().body,"htmx:historyCacheMissLoad",r);C(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});_t(r.path);ae(ee().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{ue(ee().body,"htmx:historyCacheMissLoadError",r)}};if(ae(ee().body,"htmx:historyCacheMiss",r)){t.send()}}function tn(e){Wt();e=e||location.pathname+location.search;const t=Kt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:zt(),swapSpec:n};if(ae(ee().body,"htmx:historyCacheHit",r)){C(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});_t(r.path);ae(ee().body,"htmx:historyRestore",r)}}else{if(Y.config.refreshOnHistoryMiss){Y.location.reload(true)}else{en(e)}}}function nn(e){let t=ve(e,"hx-indicator");if(t==null){t=[e]}oe(t,function(e){const t=re(e);t.requestCount=(t.requestCount||0)+1;w(e,Y.config.requestClass)});return t}function rn(e){let t=ve(e,"hx-disabled-elt");if(t==null){t=[]}oe(t,function(e){const t=re(e);t.requestCount=(t.requestCount||0)+1;if(!e.hasAttribute("disabled")){e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")}});return t}function on(e,t){oe(e.concat(t),function(e){const t=re(e);t.requestCount=(t.requestCount||1)-1});oe(e,function(e){const t=re(e);if(t.requestCount===0){S(e,Y.config.requestClass)}});oe(t,function(e){const t=re(e);if(t.requestCount===0&&e.hasAttribute("data-disabled-by-htmx")){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function sn(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);oe(e,e=>r.append(t,e))}}function an(e){if(e instanceof HTMLSelectElement&&e.multiple){return F(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return F(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||sn(t,e)){return}else{t.push(e)}if(ln(e)){const i=Q(e,"name");cn(i,an(e),n);if(o){hn(e,r)}}if(e instanceof HTMLFormElement){oe(e.elements,function(e){if(t.indexOf(e)>=0){un(e.name,an(e),n)}else{t.push(e)}if(o){hn(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}cn(t,e,n)})}}function hn(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Y.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function dn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function pn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=re(e);if(s.lastButtonClicked&&!ie(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||f(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,It(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&Q(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=Q(u,"name");cn(a,u.value,o)}const c=ve(e,"hx-include");oe(c,function(e){fn(n,r,i,le(e),l);if(!h(e,"form")){oe(p(e).querySelectorAll(it),function(e){fn(n,r,i,e,l)})}});dn(r,o);return{errors:i,formData:r,values:Mn(r)}}function gn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function mn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=gn(n,t,e)});return n}function yn(e,t,n){const r={"HX-Request":"true","HX-Trigger":Q(e,"id"),"HX-Trigger-Name":Q(e,"name"),"HX-Target":f(t,"id"),"HX-Current-URL":location.href};On(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(re(e).boosted){r["HX-Boosted"]="true"}return r}function xn(n,e){const t=te(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){oe(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;oe(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function bn(e){return!!Q(e,"href")&&Q(e,"href").indexOf("#")>=0}function vn(e,t){const n=t||te(e,"hx-swap");const r={swapStyle:re(e).boosted?"innerHTML":Y.config.defaultSwapStyle,swapDelay:Y.config.defaultSwapDelay,settleDelay:Y.config.defaultSettleDelay};if(Y.config.scrollIntoViewOnBoost&&re(e).boosted&&!bn(e)){r.show="top"}if(n){const s=X(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{T("Unknown modifier in hx-swap: "+l)}}}}return r}function wn(e){return te(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&Q(e,"enctype")==="multipart/form-data"}function Sn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(wn(n)){return dn(new FormData,Dn(r))}else{return mn(r)}}}function En(e){return{tasks:[],elts:[e]}}function Cn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=le(ce(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){b().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=le(ce(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Y.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Y.config.scrollBehavior})}}}function On(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=f(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=Tn(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const c of Object.keys(n)){if(i[c]==null){i[c]=n[c]}}}return On(le(u(r)),e,o,i,s)}function Tn(e,t,n){if(Y.config.allowEval){return t()}else{ue(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return On(e,"hx-vars",true,n,t)}function Rn(e,t,n){return On(e,"hx-vals",false,n,t)}function qn(e,t){return se(Hn(e,t),Rn(e,t))}function An(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function Nn(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){ue(ee().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function H(e,t){return e.getResponseHeader(t)!==null}function In(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return fe(t,n,null,null,{targetOverride:E(r)||be,returnPromise:true})}else{let e=E(r.target);if(r.target&&!e||r.source&&!e&&!E(r.source)){e=be}return fe(t,n,E(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return fe(t,n,null,null,{returnPromise:true})}}function Ln(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function kn(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Y.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",se({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n of Object.keys(e)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function Mn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function fe(t,n,r,o,i,P){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ee().body}const M=i.handler||Vn;const F=i.select||null;if(!ie(r)){ne(s);return e}const c=i.targetOverride||le(Se(r));if(c==null||c==be){ue(r,"htmx:targetError",{target:te(r,"hx-target")});ne(l);return e}let u=re(r);const a=u.lastButtonClicked;if(a){const A=Q(a,"formaction");if(A!=null){n=A}const N=Q(a,"formmethod");if(N!=null){if(he.includes(N.toLowerCase())){t=N}else{ne(s);return e}}}const f=te(r,"hx-confirm");if(P===undefined){const K=function(e){return fe(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(ae(r,"htmx:confirm",G)===false){ne(s);return e}}let h=r;let d=te(r,"hx-sync");let p=null;let B=false;if(d){const I=d.split(":");const L=I[0].trim();if(L==="this"){h=we(r,"hx-sync")}else{h=le(ce(r,L))}d=(I[1]||"drop").trim();u=re(h);if(d==="drop"&&u.xhr&&u.abortable!==true){ne(s);return e}else if(d==="abort"){if(u.xhr){ne(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const k=re(o);if(k&&k.triggerSpec&&k.triggerSpec.queue){p=k.triggerSpec.queue}}if(p==null){p="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(p==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){fe(t,n,r,o,i)})}else if(p==="all"){u.queuedRequests.push(function(){fe(t,n,r,o,i)})}else if(p==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){fe(t,n,r,o,i)})}ne(s);return e}}const g=new XMLHttpRequest;u.xhr=g;u.abortable=B;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const X=te(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:c})){ne(s);m();return e}}if(f&&!P){if(!confirm(f)){ne(s);m();return e}}let x=yn(r,c,y);if(t!=="get"&&!wn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=se(x,i.headers)}const U=pn(r,t);let b=U.errors;const j=U.formData;if(i.values){dn(j,Dn(i.values))}const V=Dn(qn(r,o));const v=dn(j,V);let w=xn(v,r);if(Y.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",Q(c,"id")||"true")}if(n==null||n===""){n=location.href}const S=On(r,"hx-request");const $=re(r).boosted;let E=Y.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:Mn(w),unfilteredFormData:v,unfilteredParameters:Mn(v),headers:x,elt:r,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Y.config.withCredentials,timeout:i.timeout||S.timeout||Y.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){ne(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);ne(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let T=n;if(E){T=z;const Z=!w.keys().next().done;if(Z){if(T.indexOf("?")<0){T+="?"}else{T+="&"}T+=mn(w);if(O){T+="#"+O}}}if(!kn(r,T,C)){ue(r,"htmx:invalidPath",C);ne(l);m();return e}g.open(t.toUpperCase(),T,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const D of Object.keys(x)){An(g,D,x[D])}}const H={xhr:g,target:c,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:T,responsePath:null,anchor:O}};g.onload=function(){try{const t=Ln(r);H.pathInfo.responsePath=Nn(g);M(r,H);if(H.keepIndicators!==true){on(R,q)}ae(r,"htmx:afterRequest",H);ae(r,"htmx:afterOnLoad",H);if(!ie(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(ie(n)){e=n}}if(e){ae(e,"htmx:afterRequest",H);ae(e,"htmx:afterOnLoad",H)}}ne(s)}catch(e){ue(r,"htmx:onLoadError",se({error:e},H));throw e}finally{m()}};g.onerror=function(){on(R,q);ue(r,"htmx:afterRequest",H);ue(r,"htmx:sendError",H);ne(l);m()};g.onabort=function(){on(R,q);ue(r,"htmx:afterRequest",H);ue(r,"htmx:sendAbort",H);ne(l);m()};g.ontimeout=function(){on(R,q);ue(r,"htmx:afterRequest",H);ue(r,"htmx:timeout",H);ne(l);m()};if(!ae(r,"htmx:beforeRequest",H)){ne(s);m();return e}var R=nn(r);var q=rn(r);oe(["loadstart","loadend","progress","abort"],function(t){oe([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",H);const J=E?null:Sn(g,r,w);g.send(J);return e}function Fn(e,t){const n=t.xhr;let r=null;let o=null;if(H(n,"HX-Push")){r=n.getResponseHeader("HX-Push");o="push"}else if(H(n,"HX-Push-Url")){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(H(n,"HX-Replace-Url")){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=t.etc.push||te(e,"hx-push-url");let c=t.etc.replace||te(e,"hx-replace-url");if(c==="false")c=null;const u=re(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function Bn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Xn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Yn(){const e=ee().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Qn(){const e=Yn();if(e){Y.config=se(Y.config,e)}}Wn(function(){Qn();Zn();let e=ee().body;Bt(e);const t=ee().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=re(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){tn();oe(t,function(e){ae(e,"htmx:restored",{document:ee(),triggerEvent:ae})})}else{if(n){n(e)}}};b().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Y}(); \ No newline at end of file diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ApprovalApiTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ApprovalApiTest.java new file mode 100644 index 0000000..b61bdc5 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ApprovalApiTest.java @@ -0,0 +1,109 @@ +package com.ankurm.toolconfirmation; + +import com.ankurm.toolconfirmation.approval.AuditLog; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.TestModelConfig; +import com.ankurm.toolconfirmation.support.Transcript; +import com.ankurm.toolconfirmation.tools.BookingLedger; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; + +/** + * The approval API end to end over MockMvc: a request that pauses, a stranger refused, a bad + * decision list refused with the pause kept, the real approval, and a replay refused. + */ +@SpringBootTest(properties = "spring.ai.model.chat=none") +@AutoConfigureMockMvc +@Import(TestModelConfig.class) +class ApprovalApiTest { + + @Autowired MockMvc mvc; + @Autowired ScriptedChatModel model; + @Autowired BookingLedger ledger; + @Autowired AuditLog audit; + + private String send(Transcript t, MockHttpServletRequestBuilder request, String shown) throws Exception { + MvcResult r = mvc.perform(request).andReturn(); + String body = r.getResponse().getContentAsString(); + t.line("%s", shown); + t.line(" -> %d %s", r.getResponse().getStatus(), body); + return body; + } + + @Test + void fullFlowOverHttp() throws Exception { + model.reset(); + ledger.clear(); + audit.clear(); + model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}")) + .respond("Booked VX205. Reference BK-5."); + + String chatBody; + String approvalId; + try (Transcript t = new Transcript("10-http-flow.txt", "The approval API over HTTP")) { + chatBody = send(t, post("/api/chat").contentType(MediaType.APPLICATION_JSON) + .content("{\"conversationId\":\"c1\",\"user\":\"carol\",\"message\":\"Book VX205\"}"), + "POST /api/chat (carol: Book VX205)"); + approvalId = chatBody.replaceAll(".*\"approvalId\":\"([^\"]+)\".*", "$1"); + t.line(" ledger: %s", ledger.entries()); + assertThat(chatBody).contains("AWAITING_APPROVAL"); + assertThat(ledger.entries()).isEmpty(); + + t.blank(); + send(t, get("/api/approvals"), "GET /api/approvals"); + + String allow = "{\"decisions\":[{\"key\":\"call_1\",\"allow\":true,\"message\":null}]}"; + t.blank(); + send(t, post("/api/approvals/" + approvalId + "/decisions").header("X-Approver", "mallory") + .contentType(MediaType.APPLICATION_JSON).content(allow), + "POST /api/approvals/" + approvalId + "/decisions X-Approver: mallory (allow call_1)"); + t.line(" ledger: %s", ledger.entries()); + assertThat(ledger.entries()).isEmpty(); + + t.blank(); + send(t, post("/api/approvals/" + approvalId + "/decisions").header("X-Approver", "alice") + .contentType(MediaType.APPLICATION_JSON).content("{\"decisions\":[]}"), + "POST /api/approvals/" + approvalId + "/decisions X-Approver: alice (no decisions)"); + t.line(" still pending: %s", mvc.perform(get("/api/approvals")).andReturn().getResponse() + .getContentAsString().contains(approvalId)); + + t.blank(); + String done = send(t, post("/api/approvals/" + approvalId + "/decisions").header("X-Approver", "alice") + .contentType(MediaType.APPLICATION_JSON).content(allow), + "POST /api/approvals/" + approvalId + "/decisions X-Approver: alice (allow call_1)"); + t.line(" ledger: %s", ledger.entries()); + assertThat(done).contains("DONE").contains("Booked VX205"); + assertThat(ledger.entries()).containsExactly("bookFlight VX205"); + + t.blank(); + send(t, post("/api/approvals/" + approvalId + "/decisions").header("X-Approver", "bob") + .contentType(MediaType.APPLICATION_JSON).content(allow), + "POST /api/approvals/" + approvalId + "/decisions X-Approver: bob (the same pause again)"); + t.line(" ledger: %s", ledger.entries()); + assertThat(ledger.entries()).hasSize(1); + + t.blank(); + send(t, post("/api/approvals/nope0000/decisions").header("X-Approver", "alice") + .contentType(MediaType.APPLICATION_JSON).content(allow), + "POST /api/approvals/nope0000/decisions X-Approver: alice"); + } + + try (Transcript t = new Transcript("11-audit-log.txt", "What the audit log recorded for that exchange")) { + audit.events().forEach(e -> t.line("%s", e.line())); + } + assertThat(audit.events()).extracting(AuditLog.Event::type) + .containsExactly("PAUSED", "APPROVER_REFUSED", "DECISION_REJECTED", "APPROVED", "REPLAY_REFUSED"); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ApproverUiTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ApproverUiTest.java new file mode 100644 index 0000000..ac3d7c7 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ApproverUiTest.java @@ -0,0 +1,121 @@ +package com.ankurm.toolconfirmation; + +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.TestModelConfig; +import com.ankurm.toolconfirmation.support.Transcript; +import com.ankurm.toolconfirmation.tools.BookingLedger; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.context.annotation.Import; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The approver page's server side, on a real embedded server: the SSE stream carries events, the + * HTML fragment escapes what the MODEL chose (an injected tool argument), and a form post resolves + * the pause. The htmx page itself was not driven in a browser by this test. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = "spring.ai.model.chat=none") +@Import(TestModelConfig.class) +class ApproverUiTest { + + @LocalServerPort int port; + @Autowired ScriptedChatModel model; + @Autowired BookingLedger ledger; + + private static final String HOSTILE = ""; + + private final HttpClient http = HttpClient.newHttpClient(); + + private String send(HttpRequest request) throws Exception { + return http.send(request, HttpResponse.BodyHandlers.ofString()).body(); + } + + private static void await(List lines, String needle) throws InterruptedException { + for (int i = 0; i < 100 && lines.stream().noneMatch(l -> l.contains(needle)); i++) { + Thread.sleep(50); + } + assertThat(lines).anyMatch(l -> l.contains(needle)); + } + + @Test + void fragmentsAreEscapedAndTheStreamCarriesEvents() throws Exception { + model.reset(); + ledger.clear(); + model.callTools(ScriptedChatModel.call("call_1", "bookFlight", + "{\"flightNumber\":\"" + HOSTILE + "\"}")).respond("ok"); + + String base = "http://localhost:" + port; + List sse = new CopyOnWriteArrayList<>(); + var stream = http.sendAsync(HttpRequest.newBuilder(URI.create(base + "/approvals/stream")) + .header("Accept", "text/event-stream").build(), HttpResponse.BodyHandlers.ofLines()) + .thenAccept(r -> r.body().forEach(sse::add)); + try { + run(base, sse); + } + finally { + stream.cancel(true); + http.shutdownNow(); + } + } + + private void run(String base, List sse) throws Exception { + String hostile = HOSTILE; + await(sse, "event:hello"); + + String chat = send(HttpRequest.newBuilder(URI.create(base + "/api/chat")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString( + "{\"conversationId\":\"ui\",\"user\":\"carol\",\"message\":\"Book it\"}")) + .build()); + String id = chat.replaceAll(".*\"approvalId\":\"([^\"]+)\".*", "$1"); + await(sse, "event:approval-requested"); + + String fragment = send(HttpRequest.newBuilder(URI.create(base + "/ui/approvals")).build()); + String form = "approver=alice&decision-call_1=deny&message-call_1=" + + URLEncoder.encode("Not that one", StandardCharsets.UTF_8); + String after = send(HttpRequest.newBuilder(URI.create(base + "/ui/approvals/" + id)) + .header("Content-Type", "application/x-www-form-urlencoded") + .timeout(Duration.ofSeconds(20)) + .POST(HttpRequest.BodyPublishers.ofString(form)).build()); + await(sse, "event:approval-resolved"); + String page = send(HttpRequest.newBuilder(URI.create(base + "/approver.html")).build()); + + try (Transcript t = new Transcript("13-approver-ui-and-sse.txt", + "Approver page: SSE events and an escaped fragment (injected tool argument)")) { + t.line("tool argument chosen by the model: %s", hostile); + t.blank(); + t.line("SSE lines the approver page received:"); + sse.stream().filter(l -> !l.isBlank()).forEach(l -> t.line(" %s", l)); + t.blank(); + t.line("GET /ui/approvals (the
 element):");
+            t.line("  %s", fragment.replaceAll("(?s).*(
.*?
).*", "$1")); + t.blank(); + t.line("POST /ui/approvals/%s (approver=alice, deny) ->", id); + t.line(" %s", after.replaceAll("(?s)^(]*>.*?

).*", "$1")); + t.line("ledger: %s", ledger.entries()); + t.blank(); + t.line("approver.html wiring:"); + page.lines().filter(l -> l.contains("sse-connect") || l.contains("hx-get")).map(String::strip) + .forEach(l -> t.line(" %s", l)); + } + + assertThat(fragment).contains("<img src=x onerror=alert(1)>").doesNotContain("> results = new ArrayList<>(); + for (int i = 0; i < approvers; i++) { + results.add(pool.submit(() -> { + go.await(); + try { + service.decide(paused.approvalId(), "alice", + List.of(new ApprovalService.Verdict("call_1", true, null))); + return "200 DONE"; + } + catch (ApprovalException e) { + return e.status().value() + " " + e.getMessage().replace(paused.approvalId(), ""); + } + })); + } + go.countDown(); + List outcomes = new ArrayList<>(); + for (Future f : results) { + outcomes.add(f.get(30, TimeUnit.SECONDS)); + } + pool.shutdown(); + pool.awaitTermination(10, TimeUnit.SECONDS); + + try (Transcript t = new Transcript("12-concurrent-approvers.txt", + "16 threads approve the same pause at once")) { + outcomes.stream().distinct().sorted().forEach(o -> t.line("%2d x %s", + outcomes.stream().filter(o::equals).count(), o)); + t.line("ledger: %s", ledger.entries()); + } + + assertThat(ledger.entries()).containsExactly("bookFlight VX205"); + assertThat(outcomes.stream().filter("200 DONE"::equals).count()).isEqualTo(1); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ConfirmationDisabledTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ConfirmationDisabledTest.java new file mode 100644 index 0000000..0d78372 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ConfirmationDisabledTest.java @@ -0,0 +1,58 @@ +package com.ankurm.toolconfirmation; + +import com.ankurm.toolconfirmation.approval.ApprovalService; +import com.ankurm.toolconfirmation.approval.ChatResult; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.TestModelConfig; +import com.ankurm.toolconfirmation.support.Transcript; +import com.ankurm.toolconfirmation.tools.BookingLedger; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +import org.springframework.context.annotation.Import; + +import static org.assertj.core.api.Assertions.assertThat; + +/** spring.ai.tools.confirmation.enabled=false: the flag is ignored, the policy bean is not. */ +@ExtendWith(OutputCaptureExtension.class) +@SpringBootTest(properties = { "spring.ai.model.chat=none", "spring.ai.tools.confirmation.enabled=false" }) +@Import(TestModelConfig.class) +class ConfirmationDisabledTest { + + @Autowired ScriptedChatModel model; + @Autowired ApprovalService service; + @Autowired BookingLedger ledger; + + @Test + void theFlagStopsCountingButThePolicyBeanStillApplies(CapturedOutput output) { + String warning = output.getAll().lines().filter(l -> l.contains("WARN") && l.contains("onfirmation")) + .map(String::strip).findFirst().orElse("(no warning found)"); + + model.reset(); + ledger.clear(); + model.callTools(ScriptedChatModel.call("b1", "bookFlight", "{\"flightNumber\":\"VX205\"}")).respond("Booked."); + ChatResult flagged = service.chat("off-1", "carol", "Book VX205"); + String afterFlagged = ledger.entries().toString(); + + model.reset(); + model.callTools(ScriptedChatModel.call("t1", "transferMoney", "{\"payee\":\"ACME\",\"amount\":5000}")); + ChatResult large = service.chat("off-2", "carol", "Send ACME 5000"); + + try (Transcript t = new Transcript("09-confirmation-disabled.txt", + "spring.ai.tools.confirmation.enabled=false")) { + t.line("startup warning: %s", warning.replaceAll("^.*?(ToolCallingAutoConfiguration)\\s*:\\s*", "WARN $1: ")); + t.blank(); + t.line("bookFlight (requiresConfirmation = true): status=%s ledger=%s", flagged.status(), afterFlagged); + t.line("transferMoney 5000 (policy bean): status=%s ledger=%s", large.status(), + ledger.entries()); + } + + assertThat(flagged.status()).isEqualTo("DONE"); + assertThat(afterFlagged).contains("bookFlight VX205"); + assertThat(large.status()).isEqualTo("AWAITING_APPROVAL"); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/CustomManagerTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/CustomManagerTest.java new file mode 100644 index 0000000..88f8be7 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/CustomManagerTest.java @@ -0,0 +1,75 @@ +package com.ankurm.toolconfirmation; + +import java.util.List; + +import com.ankurm.toolconfirmation.config.ChatClientFactory; +import com.ankurm.toolconfirmation.support.Env; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.Transcript; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.ai.model.tool.ToolCallDecision; +import org.springframework.ai.model.tool.ToolCallDecisions; +import org.springframework.ai.model.tool.ToolCallingChatOptions; +import org.springframework.ai.model.tool.ToolCallingManager; +import org.springframework.ai.model.tool.ToolExecutionResult; +import org.springframework.ai.tool.definition.ToolDefinition; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * A manager that wraps the default one for logging or metrics implements the two abstract methods + * and, if it forgets the third, resumption fails. The pause itself still works, which is what makes + * the omission easy to ship. + */ +class CustomManagerTest { + + /** Wraps the default manager and delegates ONLY the two abstract methods. */ + static final class ForgetfulManager implements ToolCallingManager { + + private final ToolCallingManager delegate = ToolCallingManager.builder().build(); + + @Override + public List resolveToolDefinitions(ToolCallingChatOptions options) { + return delegate.resolveToolDefinitions(options); + } + + @Override + public ToolExecutionResult executeToolCalls(Prompt prompt, ChatResponse chatResponse) { + return delegate.executeToolCalls(prompt, chatResponse); + } + } + + @Test + void aWrappingManagerThatDoesNotDelegateTheDecisionOverloadFailsOnResume() { + Env env = new Env(); + ForgetfulManager forgetful = new ForgetfulManager(); + var client = ChatClientFactory.create(env.model, forgetful, env.tools.callbacks()); + env.model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}")); + + ChatResponse reply = client.prompt().messages(Env.user("Book VX205")).call().chatResponse(); + List awaiting = ToolCallDecisions.awaitingDecision(reply); + + String error; + try { + forgetful.executeToolCalls(env.promptFor(Env.user("Book VX205")), reply, + ToolCallDecisions.of(ToolCallDecision.allow("call_1"))); + error = "(no exception)"; + } + catch (RuntimeException e) { + error = e.getClass().getSimpleName() + ": " + e.getMessage(); + } + + try (Transcript t = new Transcript("17-custom-manager.txt", + "A ToolCallingManager that wraps the default and forgets the decision overload")) { + t.line("pause through the wrapping manager: awaitingDecision = %s", awaiting); + t.line("resume through the wrapping manager: %s", error); + t.line("ledger: %s", env.ledger.entries()); + } + assertThat(awaiting).containsExactly("call_1"); + assertThat(error).startsWith("UnsupportedOperationException"); + assertThat(env.ledger.entries()).isEmpty(); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/DenyTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/DenyTest.java new file mode 100644 index 0000000..3dcc66f --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/DenyTest.java @@ -0,0 +1,53 @@ +package com.ankurm.toolconfirmation; + +import com.ankurm.toolconfirmation.support.Describe; +import com.ankurm.toolconfirmation.support.Env; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.Transcript; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.model.tool.ToolCallDecision; +import org.springframework.ai.model.tool.ToolCallDecisions; +import org.springframework.ai.model.tool.ToolExecutionResult; + +import static org.assertj.core.api.Assertions.assertThat; + +/** What the model is told when a person says no, with and without a message. */ +class DenyTest { + + @Test + void aDenialIsAToolResultTheModelCanReadAndReactTo() { + Env env = new Env(); + env.model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}"), + ScriptedChatModel.call("call_2", "cancelBooking", "{\"reference\":\"BK-9\"}")) + .respond("Understood, I will ask which seat you prefer."); + + ChatResponse reply = env.ask("Rebook me on VX205"); + + try (Transcript t = new Transcript("03-deny-messages.txt", "What the model receives when a call is denied")) { + ToolCallDecisions decisions = ToolCallDecisions.of( + ToolCallDecision.deny("call_1"), + ToolCallDecision.deny("call_2", "The user wants an aisle seat, ask again.")); + ToolExecutionResult result = env.resume(Env.user("Rebook me on VX205"), reply, decisions); + Message last = result.conversationHistory().get(result.conversationHistory().size() - 1); + + t.line("DEFAULT_DENY_MESSAGE: %s", ToolCallDecision.DEFAULT_DENY_MESSAGE); + t.blank(); + t.line("history the model is sent next:"); + t.line("%s", Describe.messages(result.conversationHistory())); + t.blank(); + t.line("ledger (nothing ran): %s", env.ledger.entries()); + t.line("returnDirect(): %s", result.returnDirect()); + + String answer = env.client.prompt().messages(result.conversationHistory()).call().content(); + t.line("model's next answer: %s", answer); + + assertThat(env.ledger.entries()).isEmpty(); + assertThat(last.toString()).contains(ToolCallDecision.DEFAULT_DENY_MESSAGE) + .contains("The user wants an aisle seat, ask again."); + assertThat(result.returnDirect()).isFalse(); + } + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/MultiRoundTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/MultiRoundTest.java new file mode 100644 index 0000000..b6f8010 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/MultiRoundTest.java @@ -0,0 +1,68 @@ +package com.ankurm.toolconfirmation; + +import java.util.List; + +import com.ankurm.toolconfirmation.approval.ApprovalService; +import com.ankurm.toolconfirmation.approval.ChatResult; +import com.ankurm.toolconfirmation.support.Describe; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.TestModelConfig; +import com.ankurm.toolconfirmation.support.Transcript; +import com.ankurm.toolconfirmation.tools.BookingLedger; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * A turn that runs an ungated tool BEFORE reaching a gated one. The paused response holds only the + * paused reply, so the application's copy of the conversation lacks the earlier round. + */ +@SpringBootTest(properties = "spring.ai.model.chat=none") +@Import(TestModelConfig.class) +class MultiRoundTest { + + @Autowired ScriptedChatModel model; + @Autowired ApprovalService service; + @Autowired BookingLedger ledger; + + @BeforeEach + void reset() { + model.reset(); + ledger.clear(); + } + + @Test + void theEarlierRoundIsMissingFromTheResumedRequest() { + model.callTools(ScriptedChatModel.call("s1", "searchFlights", "{\"from\":\"BOS\",\"to\":\"SFO\"}")) + .callTools(ScriptedChatModel.call("b1", "bookFlight", "{\"flightNumber\":\"VX205\"}")) + .respond("Booked VX205."); + + ChatResult paused = service.chat("multi", "carol", "Find a flight BOS to SFO and book the first one"); + assertThat(paused.status()).isEqualTo("AWAITING_APPROVAL"); + List ledgerAtPause = ledger.entries(); + service.decide(paused.approvalId(), "alice", + List.of(new ApprovalService.Verdict("b1", true, null))); + + try (Transcript t = new Transcript("07-multi-round-turn.txt", + "Search (ungated) then book (gated) in one turn: what the model sees on each call")) { + t.line("ledger at the pause: %s", ledgerAtPause); + t.line("model calls: %d", model.callCount()); + for (int i = 0; i < model.prompts().size(); i++) { + t.line(""); + t.line("prompt %d sent to the model:", i + 1); + t.line("%s", Describe.messages(model.prompts().get(i).getInstructions())); + } + t.blank(); + t.line("Prompt 2 had the search round; prompt 3 (the resume) does not."); + } + + assertThat(model.callCount()).isEqualTo(3); + assertThat(model.prompts().get(1).getInstructions()).hasSize(3); + assertThat(model.prompts().get(2).getInstructions().toString()).doesNotContain("searchFlights"); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PauseAndResumeTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PauseAndResumeTest.java new file mode 100644 index 0000000..524862f --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PauseAndResumeTest.java @@ -0,0 +1,92 @@ +package com.ankurm.toolconfirmation; + +import java.util.List; + +import com.ankurm.toolconfirmation.config.ChatClientFactory; +import com.ankurm.toolconfirmation.support.Describe; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.Transcript; +import com.ankurm.toolconfirmation.tools.BookingLedger; +import com.ankurm.toolconfirmation.tools.FlightTools; +import com.ankurm.toolconfirmation.tools.TransferTools; +import com.ankurm.toolconfirmation.tools.ToolRegistry; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.messages.UserMessage; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.ai.model.tool.ToolCallDecision; +import org.springframework.ai.model.tool.ToolCallDecisions; +import org.springframework.ai.model.tool.ToolCallingChatOptions; +import org.springframework.ai.model.tool.ToolCallingManager; +import org.springframework.ai.model.tool.ToolExecutionResult; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The whole feature in one test: a gated tool pauses the loop, nothing runs, the application + * answers, the call runs, and the model is called again with the result. + * Code under test: {@link com.ankurm.toolconfirmation.tools.FlightTools#bookFlight}. + */ +class PauseAndResumeTest { + + @Test + void gatedToolPausesThenRunsAfterApproval() { + BookingLedger ledger = new BookingLedger(); + ToolRegistry tools = new ToolRegistry(new FlightTools(ledger), new TransferTools(ledger), ledger); + ScriptedChatModel model = new ScriptedChatModel() + .callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}")) + .respond("Done. VX205 is booked."); + ToolCallingManager manager = ToolCallingManager.builder().build(); + ChatClient client = ChatClientFactory.create(model, manager, tools.callbacks()); + + List conversation = List.of(new UserMessage("Book flight VX205 for tomorrow")); + ChatResponse reply = client.prompt().messages(conversation).call().chatResponse(); + + List awaiting = ToolCallDecisions.awaitingDecision(reply); + AssistantMessage paused = reply.getResult().getOutput(); + + try (Transcript t = new Transcript("01-pause-and-resume.txt", + "A gated tool pauses the loop; an approval resumes it")) { + t.line("-- first request ----------------------------------------------"); + t.line("model calls so far: %d", model.callCount()); + t.line("reply text (content()): '%s'", paused.getText()); + t.line("reply has tool calls: %s", paused.hasToolCalls()); + t.line("awaitingDecision(reply): %s", awaiting); + t.line("isAwaitingDecision(reply): %s", ToolCallDecisions.isAwaitingDecision(reply)); + t.line("tool call shown to the person: %s %s", paused.getToolCalls().get(0).name(), + paused.getToolCalls().get(0).arguments()); + t.line("ledger (real side effects): %s", ledger.entries()); + t.line("metadata key holding the keys: %s", ToolCallDecisions.AWAITING_DECISION_METADATA_KEY); + + assertThat(model.callCount()).isEqualTo(1); + assertThat(awaiting).containsExactly("call_1"); + assertThat(ledger.entries()).isEmpty(); + + ToolCallDecisions decisions = ToolCallDecisions.of(ToolCallDecision.allow("call_1")); + Prompt prompt = new Prompt(conversation, + ToolCallingChatOptions.builder().toolCallbacks(tools.callbacks()).build()); + ToolExecutionResult result = manager.executeToolCalls(prompt, reply, decisions); + + t.blank(); + t.line("-- after allow(call_1) + executeToolCalls ---------------------"); + t.line("ledger (real side effects): %s", ledger.entries()); + t.line("conversationHistory():"); + t.line("%s", Describe.messages(result.conversationHistory())); + t.line("returnDirect(): %s", result.returnDirect()); + + String answer = client.prompt().messages(result.conversationHistory()).call().content(); + t.blank(); + t.line("-- resumed request --------------------------------------------"); + t.line("model calls so far: %d", model.callCount()); + t.line("final answer: %s", answer); + + assertThat(ledger.entries()).containsExactly("bookFlight VX205"); + assertThat(model.callCount()).isEqualTo(2); + assertThat(answer).isEqualTo("Done. VX205 is booked."); + } + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PolicyTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PolicyTest.java new file mode 100644 index 0000000..dc40449 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PolicyTest.java @@ -0,0 +1,71 @@ +package com.ankurm.toolconfirmation; + +import java.util.LinkedHashMap; +import java.util.Map; + +import com.ankurm.toolconfirmation.support.Env; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.Transcript; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.model.tool.ToolCallConfirmationPolicy; +import org.springframework.ai.model.tool.ToolCallDecisions; +import tools.jackson.databind.json.JsonMapper; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Which calls pause, under each policy. Every row asks the same two questions of a scripted model + * (book a flight; transfer money) and reports what was left waiting for a person. + */ +class PolicyTest { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + /** The same shape as config.ConfirmationPolicies.largeTransfers, written inline for the table. */ + private static final ToolCallConfirmationPolicy OVER_1000 = (call, metadata) -> call.name().equals("transferMoney") + && JSON.readTree(call.arguments()).path("amount").asInt() > 1_000; + + private static String pausedFor(ToolCallConfirmationPolicy policy, AssistantMessage.ToolCall call) { + Env env = policy == null ? new Env() : new Env(policy); + env.model.callTools(call).respond("ok"); + var awaiting = ToolCallDecisions.awaitingDecision(env.ask("go")); + return awaiting.isEmpty() ? "runs (ledger " + env.ledger.entries() + ")" : "PAUSES " + awaiting; + } + + @Test + void policiesDecideWhichCallsPause() { + var book = ScriptedChatModel.call("c1", "bookFlight", "{\"flightNumber\":\"VX205\"}"); + var small = ScriptedChatModel.call("c2", "transferMoney", "{\"payee\":\"ACME\",\"amount\":500}"); + var large = ScriptedChatModel.call("c3", "transferMoney", "{\"payee\":\"ACME\",\"amount\":5000}"); + + Map rows = new LinkedHashMap<>(); + rows.put("default (fromToolMetadata) | bookFlight ", pausedFor(null, book)); + rows.put("default (fromToolMetadata) | transferMoney 500 ", pausedFor(null, small)); + rows.put("none() | bookFlight ", pausedFor(ToolCallConfirmationPolicy.none(), book)); + rows.put("forTools(\"transferMoney\") | transferMoney 500 ", + pausedFor(ToolCallConfirmationPolicy.forTools("transferMoney"), small)); + rows.put("forTools(\"transferMoney\") | bookFlight ", + pausedFor(ToolCallConfirmationPolicy.forTools("transferMoney"), book)); + rows.put("over-1000 argument policy | transferMoney 500 ", pausedFor(OVER_1000, small)); + rows.put("over-1000 argument policy | transferMoney 5000 ", pausedFor(OVER_1000, large)); + rows.put("over-1000 argument policy | bookFlight ", pausedFor(OVER_1000, book)); + rows.put("fromToolMetadata().or(over-1000)| bookFlight ", + pausedFor(ToolCallConfirmationPolicy.fromToolMetadata().or(OVER_1000), book)); + rows.put("fromToolMetadata().or(over-1000)| transferMoney 5000 ", + pausedFor(ToolCallConfirmationPolicy.fromToolMetadata().or(OVER_1000), large)); + + try (Transcript t = new Transcript("04-policies.txt", "Which calls pause under which policy")) { + t.line("%-32s| %-21s %s", "policy", "call", "result"); + rows.forEach((k, v) -> t.line("%s %s", k, v)); + } + + assertThat(rows.get("default (fromToolMetadata) | bookFlight ")).startsWith("PAUSES"); + assertThat(rows.get("default (fromToolMetadata) | transferMoney 500 ")).startsWith("runs"); + assertThat(rows.get("none() | bookFlight ")).startsWith("runs"); + assertThat(rows.get("over-1000 argument policy | bookFlight ")) + .as("a policy that names only transfers does not cover the annotated tool") + .startsWith("runs"); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PositionKeysTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PositionKeysTest.java new file mode 100644 index 0000000..0dcd345 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/PositionKeysTest.java @@ -0,0 +1,49 @@ +package com.ankurm.toolconfirmation; + +import java.util.List; + +import com.ankurm.toolconfirmation.support.Env; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.Transcript; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.model.tool.ToolCallDecision; +import org.springframework.ai.model.tool.ToolCallDecisions; + +import static org.assertj.core.api.Assertions.assertThat; + +/** A tool call key is the call's id, unless the provider sent none or sent the same id twice. */ +class PositionKeysTest { + + @Test + void missingOrDuplicateIdsFallBackToPositions() { + Env env = new Env(); + env.model.callTools( + ScriptedChatModel.call("dup", "bookFlight", "{\"flightNumber\":\"VX205\"}"), + ScriptedChatModel.call("dup", "bookFlight", "{\"flightNumber\":\"VX311\"}")); + ChatResponse reply = env.ask("Book both"); + AssistantMessage message = reply.getResult().getOutput(); + List keys = ToolCallDecisions.toolCallKeys(message); + + Env env2 = new Env(); + env2.model.callTools(ScriptedChatModel.call("", "bookFlight", "{\"flightNumber\":\"VX205\"}")); + ChatResponse noId = env2.ask("Book it"); + + try (Transcript t = new Transcript("16-position-keys.txt", "Tool call keys when ids are missing or repeated")) { + t.line("POSITION_KEY_PREFIX: %s", ToolCallDecisions.POSITION_KEY_PREFIX); + t.line("two calls that both have id 'dup' -> keys: %s", keys); + t.line("awaitingDecision for that reply: %s", ToolCallDecisions.awaitingDecision(reply)); + t.line("one call with an empty id -> keys: %s", + ToolCallDecisions.toolCallKeys(noId.getResult().getOutput())); + + // The keys work as decision keys. + env.resume(Env.user("Book both"), reply, + ToolCallDecisions.of(ToolCallDecision.allow("#0"), ToolCallDecision.deny("#1"))); + t.line("allow('#0') + deny('#1') -> ledger: %s", env.ledger.entries()); + } + assertThat(keys).containsExactly("#0", "#1"); + assertThat(env.ledger.entries()).containsExactly("bookFlight VX205"); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ReplayTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ReplayTest.java new file mode 100644 index 0000000..9b2bf86 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ReplayTest.java @@ -0,0 +1,42 @@ +package com.ankurm.toolconfirmation; + +import java.util.List; + +import com.ankurm.toolconfirmation.support.Env; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.Transcript; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.model.tool.ToolCallDecision; +import org.springframework.ai.model.tool.ToolCallDecisions; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The framework does not prevent replays: the same decisions on the same reply run the tool again. + * The guard is the application's (see approval.ApprovalStore#take and output/10). + */ +class ReplayTest { + + @Test + void theSameDecisionsRunTheToolTwice() { + Env env = new Env(); + env.model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}")); + List conversation = Env.user("Book VX205"); + ChatResponse reply = env.ask("Book VX205"); + ToolCallDecisions decisions = ToolCallDecisions.of(ToolCallDecision.allow("call_1")); + + env.resume(conversation, reply, decisions); + env.resume(conversation, reply, decisions); + + try (Transcript t = new Transcript("06-replay-is-not-prevented.txt", + "executeToolCalls twice with the same decisions on the same reply")) { + t.line("calls to executeToolCalls: 2"); + t.line("ledger: %s", env.ledger.entries()); + t.line("A customer is booked, and charged, twice."); + } + assertThat(env.ledger.entries()).containsExactly("bookFlight VX205", "bookFlight VX205"); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ResumeErrorsTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ResumeErrorsTest.java new file mode 100644 index 0000000..f894ccc --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ResumeErrorsTest.java @@ -0,0 +1,63 @@ +package com.ankurm.toolconfirmation; + +import java.util.List; + +import com.ankurm.toolconfirmation.support.Env; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.Transcript; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.ai.model.tool.ToolCallDecision; +import org.springframework.ai.model.tool.ToolCallDecisions; +import org.springframework.ai.model.tool.ToolCallingChatOptions; + +import static org.assertj.core.api.Assertions.assertThat; + +/** The three ways a resume is refused, with the real messages, and proof that nothing ran. */ +class ResumeErrorsTest { + + private static String message(Runnable r) { + try { + r.run(); + return "(no exception)"; + } + catch (RuntimeException e) { + return e.getClass().getSimpleName() + ": " + e.getMessage(); + } + } + + @Test + void badDecisionListsAreRefusedBeforeAnythingRuns() { + Env env = new Env(); + env.model.callTools(ScriptedChatModel.call("call_1", "bookFlight", "{\"flightNumber\":\"VX205\"}")); + List conversation = Env.user("Book VX205"); + ChatResponse reply = env.ask("Book VX205"); + + String missing = message(() -> env.resume(conversation, reply, ToolCallDecisions.of())); + String unknown = message(() -> env.resume(conversation, reply, ToolCallDecisions.of( + ToolCallDecision.allow("call_1"), ToolCallDecision.allow("call_99")))); + // Same reply, but the Prompt carries no tools: resumption does not look tools up by name. + Prompt noTools = new Prompt(conversation, ToolCallingChatOptions.builder().build()); + String notInPrompt = message(() -> env.manager.executeToolCalls(noTools, reply, + ToolCallDecisions.of(ToolCallDecision.allow("call_1")))); + + try (Transcript t = new Transcript("05-resume-errors.txt", "Three refused resumes")) { + t.line("1. no decision for call_1:"); + t.line(" %s", missing); + t.line("2. a decision for a key that is not in the reply (call_99):"); + t.line(" %s", unknown); + t.line("3. allowed call, but its tool is not on the Prompt:"); + t.line(" %s", notInPrompt); + t.blank(); + t.line("ledger after all three: %s", env.ledger.entries()); + } + + assertThat(missing).startsWith("IllegalArgumentException"); + assertThat(unknown).startsWith("IllegalArgumentException"); + assertThat(notInPrompt).startsWith("IllegalArgumentException"); + assertThat(env.ledger.entries()).isEmpty(); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ShutdownTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ShutdownTest.java new file mode 100644 index 0000000..b44ab24 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ShutdownTest.java @@ -0,0 +1,65 @@ +package com.ankurm.toolconfirmation; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import com.ankurm.toolconfirmation.support.TestModelConfig; +import com.ankurm.toolconfirmation.support.Transcript; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * How long does stopping the application take while one approver page is open? Spring Boot's web + * server shuts down gracefully by default: it waits for in-flight requests, and an SSE stream never + * finishes. The grace period is set to 5 s here so the test is quick; the default is 30 s. + * Code: {@link com.ankurm.toolconfirmation.approval.ApprovalEvents} (a SmartLifecycle). + */ +class ShutdownTest { + + private static long closeWithOneOpenStream(boolean closeStreamsOnStop) throws Exception { + ConfigurableApplicationContext ctx = new SpringApplicationBuilder(ToolConfirmationApplication.class, + TestModelConfig.class) + .properties("server.port=0", "spring.ai.model.chat=none", "server.shutdown=graceful", + "spring.lifecycle.timeout-per-shutdown-phase=5s", "spring.main.banner-mode=off", + "logging.level.root=WARN", "app.approval.close-streams-on-stop=" + closeStreamsOnStop) + .run(); + String port = ctx.getEnvironment().getProperty("local.server.port"); + HttpClient http = HttpClient.newHttpClient(); + List lines = new CopyOnWriteArrayList<>(); + http.sendAsync(HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/approvals/stream")).build(), + HttpResponse.BodyHandlers.ofLines()).thenAccept(r -> r.body().forEach(lines::add)); + for (int i = 0; i < 100 && lines.isEmpty(); i++) { + Thread.sleep(50); + } + assertThat(lines).as("stream is open").isNotEmpty(); + long start = System.nanoTime(); + ctx.close(); + long millis = (System.nanoTime() - start) / 1_000_000; + http.shutdownNow(); + return millis; + } + + @Test + void anOpenStreamDelaysGracefulShutdownUnlessItIsClosedFirst() throws Exception { + long left = closeWithOneOpenStream(false); + long closed = closeWithOneOpenStream(true); + + try (Transcript t = new Transcript("14-sse-and-graceful-shutdown.txt", + "ctx.close() with one approver page connected (grace period 5000 ms)")) { + t.line("streams left open: %s ms", left >= 4000 ? "over 4000" : String.valueOf(left)); + t.line("streams completed by the lifecycle: %s ms", closed < 2000 ? "under 2000" : String.valueOf(closed)); + t.line("(the exact figures vary per run; the 5 s wall is the configured grace period)"); + } + + assertThat(left).isGreaterThan(4000); + assertThat(closed).isLessThan(2000); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ToolsPropertyTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ToolsPropertyTest.java new file mode 100644 index 0000000..cfc56ea --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/ToolsPropertyTest.java @@ -0,0 +1,43 @@ +package com.ankurm.toolconfirmation; + +import com.ankurm.toolconfirmation.approval.ApprovalService; +import com.ankurm.toolconfirmation.approval.ChatResult; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.TestModelConfig; +import com.ankurm.toolconfirmation.support.Transcript; +import com.ankurm.toolconfirmation.tools.BookingLedger; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; + +import static org.assertj.core.api.Assertions.assertThat; + +/** spring.ai.tools.confirmation.tools=transferMoney: pause a tool that carries no annotation. */ +@SpringBootTest(properties = { "spring.ai.model.chat=none", "spring.ai.tools.confirmation.tools=transferMoney" }) +@Import(TestModelConfig.class) +class ToolsPropertyTest { + + @Autowired ScriptedChatModel model; + @Autowired ApprovalService service; + @Autowired BookingLedger ledger; + + @Test + void aListedToolPausesWhateverItsMetadataSays() { + model.reset(); + ledger.clear(); + model.callTools(ScriptedChatModel.call("t1", "transferMoney", "{\"payee\":\"ACME\",\"amount\":5}")); + + ChatResult result = service.chat("prop", "carol", "Send ACME five dollars"); + + try (Transcript t = new Transcript("08-tools-property.txt", + "spring.ai.tools.confirmation.tools=transferMoney (a USD 5 transfer, far under the 1000 policy bean)")) { + t.line("status: %s", result.status()); + t.line("calls: %s", result.calls()); + t.line("ledger: %s", ledger.entries()); + } + assertThat(result.status()).isEqualTo("AWAITING_APPROVAL"); + assertThat(ledger.entries()).isEmpty(); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/WholeReplyPausesTest.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/WholeReplyPausesTest.java new file mode 100644 index 0000000..c18dbdc --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/WholeReplyPausesTest.java @@ -0,0 +1,71 @@ +package com.ankurm.toolconfirmation; + +import java.util.List; + +import com.ankurm.toolconfirmation.support.Describe; +import com.ankurm.toolconfirmation.support.Env; +import com.ankurm.toolconfirmation.support.ScriptedChatModel; +import com.ankurm.toolconfirmation.support.Transcript; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.model.tool.ToolCallDecision; +import org.springframework.ai.model.tool.ToolCallDecisions; +import org.springframework.ai.model.tool.ToolExecutionResult; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * One reply, two tool calls: a harmless search and a gated booking. The documented rule is that + * the whole reply pauses. This test shows what that means for the harmless call. + */ +class WholeReplyPausesTest { + + @Test + void anUngatedCallInTheSameReplyWaitsToo() { + Env env = new Env(); + env.model.callTools( + ScriptedChatModel.call("call_1", "searchFlights", "{\"from\":\"BOS\",\"to\":\"SFO\"}"), + ScriptedChatModel.call("call_2", "bookFlight", "{\"flightNumber\":\"VX205\"}")) + .respond("Booked."); + + ChatResponse reply = env.ask("Find me a flight and book the first one"); + List conversation = Env.user("Find me a flight and book the first one"); + + try (Transcript t = new Transcript("02-whole-reply-pauses.txt", + "One gated call pauses the whole reply, including the harmless call beside it")) { + t.line("calls in the reply: %s", reply.getResult().getOutput().getToolCalls().stream() + .map(c -> c.id() + "=" + c.name()).toList()); + t.line("awaitingDecision(reply): %s", ToolCallDecisions.awaitingDecision(reply)); + t.line("ledger after the pause: %s", env.ledger.entries()); + + assertThat(env.ledger.entries()).as("searchFlights is ungated but did not run").isEmpty(); + + // A decision is required for EVERY call, including the one the policy did not flag. + ToolCallDecisions onlyGated = ToolCallDecisions.of(ToolCallDecision.allow("call_2")); + String error = null; + try { + env.resume(conversation, reply, onlyGated); + } + catch (IllegalArgumentException e) { + error = e.getMessage(); + } + t.blank(); + t.line("decision for call_2 only -> IllegalArgumentException:"); + t.line(" %s", error); + t.line("ledger after the refused resume: %s", env.ledger.entries()); + assertThat(error).isNotNull(); + assertThat(env.ledger.entries()).isEmpty(); + + ToolCallDecisions both = ToolCallDecisions.of(ToolCallDecision.allow("call_1"), + ToolCallDecision.allow("call_2")); + ToolExecutionResult result = env.resume(conversation, reply, both); + t.blank(); + t.line("decisions for both -> ledger: %s", env.ledger.entries()); + t.line("tool results, in the model's order:"); + t.line("%s", Describe.message(result.conversationHistory().get(result.conversationHistory().size() - 1))); + assertThat(env.ledger.entries()).containsExactly("searchFlights BOS->SFO", "bookFlight VX205"); + } + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Describe.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Describe.java new file mode 100644 index 0000000..3ec4789 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Describe.java @@ -0,0 +1,33 @@ +package com.ankurm.toolconfirmation.support; + +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.messages.ToolResponseMessage; + +/** Compact one-line renderings of messages for the transcripts. */ +public final class Describe { + + private Describe() { + } + + public static String message(Message m) { + if (m instanceof AssistantMessage a && a.hasToolCalls()) { + return "AssistantMessage[toolCalls=" + a.getToolCalls().stream() + .map(c -> c.id() + ":" + c.name() + c.arguments()) + .collect(Collectors.joining(", ")) + "]"; + } + if (m instanceof ToolResponseMessage t) { + return "ToolResponseMessage" + t.getResponses().stream() + .map(r -> "[" + r.id() + ":" + r.name() + " -> " + r.responseData() + "]") + .collect(Collectors.joining()); + } + return m.getClass().getSimpleName() + "[" + m.getText() + "]"; + } + + public static String messages(List ms) { + return ms.stream().map(Describe::message).collect(Collectors.joining("\n ", " ", "")); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Env.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Env.java new file mode 100644 index 0000000..196db74 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Env.java @@ -0,0 +1,60 @@ +package com.ankurm.toolconfirmation.support; + +import com.ankurm.toolconfirmation.config.ChatClientFactory; +import com.ankurm.toolconfirmation.tools.BookingLedger; +import com.ankurm.toolconfirmation.tools.FlightTools; +import com.ankurm.toolconfirmation.tools.ToolRegistry; +import com.ankurm.toolconfirmation.tools.TransferTools; + +import java.util.List; + +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.messages.UserMessage; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.ai.model.tool.ToolCallConfirmationPolicy; +import org.springframework.ai.model.tool.ToolCallDecisions; +import org.springframework.ai.model.tool.ToolCallingChatOptions; +import org.springframework.ai.model.tool.ToolCallingManager; +import org.springframework.ai.model.tool.ToolExecutionResult; + +/** A plain-JVM fixture: real tools, real manager, scripted model, no Spring context. */ +public final class Env { + + public final BookingLedger ledger = new BookingLedger(); + public final ToolRegistry tools = new ToolRegistry(new FlightTools(ledger), new TransferTools(ledger), ledger); + public final ScriptedChatModel model = new ScriptedChatModel(); + public final ToolCallingManager manager; + public final ChatClient client; + + public Env() { + this(null); + } + + /** @param policy {@code null} keeps the manager's default, {@code fromToolMetadata()} */ + public Env(ToolCallConfirmationPolicy policy) { + var builder = ToolCallingManager.builder(); + if (policy != null) { + builder.toolCallConfirmationPolicy(policy); + } + this.manager = builder.build(); + this.client = ChatClientFactory.create(model, manager, tools.callbacks()); + } + + public static List user(String text) { + return List.of(new UserMessage(text)); + } + + public ChatResponse ask(String text) { + return client.prompt().messages(user(text)).call().chatResponse(); + } + + public Prompt promptFor(List conversation) { + return new Prompt(conversation, ToolCallingChatOptions.builder().toolCallbacks(tools.callbacks()).build()); + } + + public ToolExecutionResult resume(List conversation, ChatResponse reply, ToolCallDecisions decisions) { + return manager.executeToolCalls(promptFor(conversation), reply, decisions); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/ScriptedChatModel.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/ScriptedChatModel.java new file mode 100644 index 0000000..6994d78 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/ScriptedChatModel.java @@ -0,0 +1,74 @@ +package com.ankurm.toolconfirmation.support; + +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.model.Generation; +import org.springframework.ai.chat.prompt.ChatOptions; +import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.ai.model.tool.ToolCallingChatOptions; + +/** + * A hand-written {@link ChatModel} that returns queued responses instead of calling a provider. + * {@code ChatModel} has one abstract method, {@code call(Prompt)}. Every prompt the advisor sends is + * recorded, so a test can assert what the model was shown on a resumed request. The queue can be + * refilled and cleared, so one instance can sit in a Spring context across tests. + * + *

{@code getOptions()} must return {@link ToolCallingChatOptions}: ToolCallingAdvisor does + * nothing at all otherwise (see tool-calling/ in this repository for how that was found). + */ +public class ScriptedChatModel implements ChatModel { + + private final Queue script = new ConcurrentLinkedQueue<>(); + private final List prompts = new CopyOnWriteArrayList<>(); + + public ScriptedChatModel callTools(AssistantMessage.ToolCall... toolCalls) { + AssistantMessage message = AssistantMessage.builder().content("").toolCalls(List.of(toolCalls)).build(); + this.script.add(new ChatResponse(List.of(new Generation(message)))); + return this; + } + + public ScriptedChatModel respond(String text) { + this.script.add(new ChatResponse(List.of(new Generation(new AssistantMessage(text))))); + return this; + } + + public ScriptedChatModel reset() { + this.script.clear(); + this.prompts.clear(); + return this; + } + + @Override + public ChatResponse call(Prompt prompt) { + this.prompts.add(prompt); + ChatResponse next = this.script.poll(); + if (next == null) { + throw new IllegalStateException("ScriptedChatModel ran out of responses after " + this.prompts.size() + + " calls"); + } + return next; + } + + public List prompts() { + return List.copyOf(this.prompts); + } + + public int callCount() { + return this.prompts.size(); + } + + @Override + public ChatOptions getOptions() { + return ToolCallingChatOptions.builder().build(); + } + + public static AssistantMessage.ToolCall call(String id, String name, String json) { + return new AssistantMessage.ToolCall(id, "function", name, json); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/TestModelConfig.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/TestModelConfig.java new file mode 100644 index 0000000..654725a --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/TestModelConfig.java @@ -0,0 +1,17 @@ +package com.ankurm.toolconfirmation.support; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; + +/** + * Puts a {@link ScriptedChatModel} in the Spring context in place of the OpenAI model. Tests set + * {@code spring.ai.model.chat=none} so the provider starter creates no model of its own. + */ +@TestConfiguration(proxyBeanMethods = false) +public class TestModelConfig { + + @Bean + ScriptedChatModel scriptedChatModel() { + return new ScriptedChatModel(); + } +} diff --git a/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Transcript.java b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Transcript.java new file mode 100644 index 0000000..2ed9767 --- /dev/null +++ b/tool-confirmation/src/test/java/com/ankurm/toolconfirmation/support/Transcript.java @@ -0,0 +1,47 @@ +package com.ankurm.toolconfirmation.support; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Writes a numbered transcript under {@code output/} and echoes it to the console. Every console + * block quoted in the article comes out of one of these files verbatim. + */ +public final class Transcript implements AutoCloseable { + + private final Path path; + private final StringWriter buffer = new StringWriter(); + private final PrintWriter out = new PrintWriter(buffer); + + public Transcript(String fileName, String title) { + this.path = Path.of("output", fileName); + out.println("# " + title); + out.println(); + } + + public Transcript line(String format, Object... args) { + out.println(args.length == 0 ? format : String.format(format, args)); + return this; + } + + public Transcript blank() { + out.println(); + return this; + } + + @Override + public void close() { + out.flush(); + try { + Files.createDirectories(path.getParent()); + Files.writeString(path, buffer.toString()); + } + catch (IOException e) { + throw new IllegalStateException("could not write " + path, e); + } + System.out.print(buffer); + } +}