diff --git a/docs/changelog.md b/docs/changelog.md index 221086a116..753d810543 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -3,6 +3,91 @@ > **Purpose:** Living document tracking all changes, decisions, and reasoning during implementation. Updated as work progresses for easy reference and review. +--- + +## 🎚️ feat(hitl): per-endpoint approval friction (2026-08-01) + +**Repo:** EDDI (`feat/operator-write-capability`) + +First of the follow-ups named at the end of [#622](#-featoperator-the-foundation-for-an-agent-that-can-safely-write-2026-07-29). `timeoutPolicy`, `approvalTimeout`, `pauseReason` and `pendingMessage` were single scalars covering every gated tool, so "deploy an agent" and "create an agent" could not differ in how long a reviewer had or what the approval card said. `toolApprovals.rules` is an optional list of per-tool overrides addressed by the same pattern language as `requireApproval`: + +```json +"rules": [ + { "match": "http.post:/agentstore/agents", "timeoutPolicy": "WAIT_INDEFINITELY", + "pauseReason": "Creating a new agent — review the whole config" }, + { "match": "http.post:/administration/{environment}/deploy/{agentId}", + "timeoutPolicy": "AUTO_REJECT", "approvalTimeout": "PT5M" } +] +``` + +**A rule tunes friction; it never gates or ungates.** That stays entirely in `requireApproval`/`exempt`. The gate allows an unmatched call, so it only survives by gating broadly and exempting narrowly — a rule able to ungate would let a config grant capability by adding an entry, which is the enumerate-upward failure the whole design avoids. The invariant is asserted against the gate itself: a config whose rules name an exempt GET and give a required POST `AUTO_APPROVE` changes neither classification. + +**Two resolution decisions worth recording.** + +*Most specific wins, per call.* Fewest wildcards first, then longest pattern — so `http.post:/agentstore/agents` beats `http.post:*` regardless of JSON array order. Order-dependence would mean a designer silently losing their intended friction to a list edit. + +*Strictest wins, per batch.* A model can emit several gated calls in one message and they pause **together**, under one timeout policy, so the matched rules must reduce to one. Ranking them by how much of the human's decision the policy takes on timeout — `WAIT_INDEFINITELY` > `ABORT` > `AUTO_REJECT` > `AUTO_APPROVE` > (no policy) — means bundling a lenient call into a batch can never soften a stricter rule. Taking the *first* match instead would have let a model turn "delete waits for a human" into "delete auto-rejects in five minutes" by pairing a delete with a deploy. Fields fall back to the scalars *individually*, so a rule that sets only `pauseReason` keeps the configured policy. + +**The rule is resolved once, at gate time, and persisted on the batch.** `PendingToolCallBatch` keeps each gated call's name and source but no endpoint, so `http.post:/agentstore/agents` could not be re-matched by the post-pause resolvers in `ConversationService` (timeout) and `Conversation.resolvePendingMessage` (end-user message) — and a rule resolving differently on the two sides of a pause is exactly the bug the persisted field removes. It mirrors the existing `effectiveToolApprovals` field and is nullable for the same backward-compatibility reason. + +**Extracted rather than duplicated.** `ToolApprovalGate.addressesOf` is now public and is the single derivation of the three forms a pattern may address a call by; the gate and `ToolApprovalRules` both call it. A second copy would drift, and since the gate allows an unmatched call, drift there is an ungated write. + +**Metric.** `eddi.hitl.rule.matched{match=""}` — deduplicated per pause, so it counts reviews governed rather than calls the model happened to bundle. The tag is the pattern from the config, never a URL, credential, argument or user id, so cardinality is bounded by the size of the `rules` list. + +**Verification.** 1929 tests pass across the HITL, conversation, orchestrator and lifecycle suites (the 3 errors are the known Docker/Testcontainers and Quarkus-IT environmental failures, unchanged from a clean checkout). Five mutations applied and each confirmed to kill tests: strictest-wins → first-wins (3 dead), specificity sort removed (2), the governing-rule branch in `applyEffectiveToolTimeoutPolicy` disabled (2), the rule's duration ignored (2), the rule's `pendingMessage` ignored (1). The duration test asserts on the *armed deadline* rather than the policy name, because both levels state `AUTO_REJECT` there and only the fire time distinguishes which duration was read. + +Documented in [`docs/hitl.md`](hitl.md). + +### setup-api can now install the gate (2026-08-01) + +**`CreateApiAgentRequest` had no HITL field and `AgentSetupService.createApiAgent` built a bare `AgentConfiguration`, so every agent the wizard has ever created has `hitlConfig == null` and an inert gate.** Nothing could provision a gated agent through setup-api at all — which is the blocker for anything downstream that wants to *offer* write capability, because there was no way to install the thing that makes writes safe. + +`hitlConfig` is now the last-but-one component of the request record (appended, so the positional constructor `McpSetupTools` uses keeps its existing meaning) and is set at step 7, **on v1 of the agent document**. Creating it with the agent rather than `PUT`-ing it afterwards matters: `HistorizedResourceStore.update` writes `version + 1` and leaves the ungated v1 reachable by a redeploy, so a two-step provision would ship an agent that can be returned to an ungated state. + +**Validated before the first resource exists.** `AgentStore.create` validates `hitlConfig` too ([`AgentStore.java:48`](../src/main/java/ai/labs/eddi/configs/agents/mongo/AgentStore.java)) — but that runs at step 7, so an unusable approval pattern surfaced only after the apicalls, parser, behaviour, LLM and workflow had all been created, leaving five orphaned resources behind. The up-front check gives the caller the same actionable message and no debris; the test asserts it by proving no REST store was even requested. + +**Deliberately not on the MCP tool.** `create_api_agent` passes `null` and has no `@ToolArg` for it. That tool already provisions an agent with a caller-chosen endpoint filter; letting the caller also choose the gate would turn it into a complete escape from whatever allow-list governs the agent doing the calling. Gated provisioning goes through `POST /administration/agents/setup-api` (`eddi-admin`). + +**Also on setup-api: `mcpServerUrls`.** An API agent could previously hold only the tools generated from its OpenAPI spec — `createApiAgent` passed `null` for the MCP locations — so "REST endpoints *and* an MCP server" was unreachable through the wizard and had to be assembled by hand. The per-URL creation loop is now shared with `setupAgent` rather than duplicated. + +Mutation-checked: dropping the up-front validation, dropping `setHitlConfig`, and reverting the workflow to `null` MCP locations each kill their test. + +### EDDI's docs are now readable by an EDDI agent (2026-08-01) + +**An MCP resource does not reach an EDDI agent.** A resource is only usable by a client that asks for it, and EDDI's own MCP client never calls `resources/read` — it consumes *tools*. So `eddi://docs/*` made EDDI's documentation readable by a desktop MCP client and not by an agent running on EDDI, which is exactly backwards for an agent whose job is to explain the platform. + +`DocsService` is extracted from `McpDocResources` (filesystem access plus the path-traversal guard) and served over REST at `GET /administration/docs` and `GET /administration/docs/{name}`, both open to the widest read tier (`eddi-admin`, `eddi-editor`, `eddi-user`, `eddi-approver`, `eddi-viewer` — enumerated, because EDDI has no role hierarchy; see the review-pass note below) — the docs are published documentation, so anyone who may look at the deployment may read them. `McpDocResources` becomes a thin delegate, and its pre-existing test class is kept assertion-for-assertion as the evidence that no MCP client sees a different response than before. + +**Runtime doc set ≠ repo doc set,** and this is now written down where a caller will see it. The image copies only top-level `docs/*.md` (non-recursive) and then removes `changelog.md`, `code-review-standards.md`, `incident-response.md` and `SUMMARY.md` — so a caller must read the index rather than assume a page exists. The REST list endpoint is what makes that practical. + +**A redundant guard was found and made non-redundant.** Mutating away the name shape-check (`/`, `\`, `..`) killed nothing: `readDoc` also verifies the resolved path still sits under the docs directory, which subsumes it. The shape check is worth keeping — it is what lets the MCP surface answer "invalid name" rather than "not found" — but `McpDocResources` had *restated the predicate* to pick that message, i.e. two copies of a security check. It is now one shared `DocsService.isValidDocName`, and mutating it kills five tests. The REST surface deliberately returns a bare `404` for both cases instead, so an attacker-supplied traversal string is never echoed back. + +### `updateResourceUri` verified as the gate-immune re-point path (2026-08-01) + +`PUT /agentstore/agents/{id}` and `PUT /llmstore/llms/{id}` are permanently unbound for an approval-gated operator, because the gate lives in those documents and one approved write there removes all subsequent gating. That leaves editing an agent apparently impossible: changing a behaviour rule means rules v2 → workflow re-points at rules v2 → agent re-points at workflow v2, and the last two steps are document writes. The escape hatch is `PUT /{id}/updateResourceUri` on the agent and workflow stores — but it is only safe to bind if it *provably* cannot drop the gate, so this was checked rather than assumed. + +**It holds, for two independent reasons.** The caller cannot *supply* a `hitlConfig`: the request body is `text/plain` and is a single URI. And the implementation *preserves* the stored one — `updateResourceInAgent` reads the current document, mutates only the workflow URI list, and writes the whole document back, so the gate survives by round-trip rather than by the endpoint happening to ignore it. Both variants go through the normal `update` path, so `HistorizedResourceStore` writes `version + 1` as usual. Asserted by capturing the written `AgentConfiguration`: the gate is intact and only the URI list changed. Mutation-checked by nulling `hitlConfig` before the write. + +**One defect found and fixed on that path.** Both variants computed `resourceURIString.substring(0, resourceURIString.lastIndexOf("?"))`, which throws `StringIndexOutOfBoundsException` on a URI carrying no `?version=` — turning malformed caller input into a 500. That matters more here than it usually would: this is the endpoint an approval-gated operator has to walk to finish an edit, so its failure mode is one an LLM will hit and must be able to act on. Now an actionable 400. + +### Review pass over the above (2026-08-01) + +A critical read-back of the whole branch, which found three things worth recording: + +- **`GET /administration/docs` would have 403'd an admin.** It was written as `@RolesAllowed("eddi-viewer")` — the role the plan named and the one the MCP surface uses. But EDDI has **no role hierarchy**: JAX-RS `@RolesAllowed` and the MCP layer's `McpToolUtils.requireRole` are both literal `hasRole` checks, and `eddi-viewer` appears in *no other* REST endpoint. An `eddi-admin` principal — what an operator agent actually runs as — would have been refused by the one endpoint built for it. Now the read tier is enumerated like every other REST resource here. +- **A javadoc was silently reassigned.** The new `recordRuleMatches` was inserted directly above `recordPauseCapGuard`, leaving two consecutive javadoc blocks: the original doc detached from its method and `recordPauseCapGuard` ended up undocumented. Method moved. +- **One more sound validation.** A `rules[].match` string-identical to an `exempt` pattern is provably dead config — an exempt call is never gated, so no rule is ever resolved for it — and is now refused, in the same spirit as the existing "in both requireApproval and exempt" check. Deliberately *only* exact equality: a broader rule may legitimately overlap an exemption while still covering gated calls, and deciding that in general would mean reasoning about globs over an unknown tool set. + +### PR review pass — CodeRabbit + Copilot on #625 (2026-08-01) + +- **`updateResourceUri` could unpin a reference (Major, real).** The versionless-URI guard added above tested only for the presence of a `?`. A URI like `.../workflows/{id}?other=2` satisfied it, matched the stored `?version=1` reference by path prefix, and **replaced it with a versionless one** — silently unpinning the workflow an agent resolves at runtime. The guard now parses the query and requires a `version` that is a non-negative integer, via a shared `RestUtilities.pathWithoutVersionQuery` so both stores ask the same question. Mutation-checked: with the parse removed, `?other=2` returns 200 and the write goes through. +- **A whitespace-only duration degraded a finite policy silently.** `RuntimeUtilities.isNullOrEmpty` is `isEmpty`-only, but `HitlConfigValidation` uses `isBlank` when deciding whether a finite rule may inherit the enclosing `approvalTimeout`. So `" "` saved as "absent" and then resolved as "present", won the chain, threw inside `Duration.parse`, armed no schedule, and left the bookmark reporting a finite policy that could never fire. Both resolution sites are blank-aware now, and the three identical duration ternaries in `applyEffectiveToolTimeoutPolicy` are computed once — the timeout resolves down its own chain regardless of which branch picks the policy, and three copies would drift. +- **MCP server URLs are validated before the first write.** `McpCallsConfiguration.validate()` (write-time validation, new on main) rejects a non-http(s) URL, so a bad *second* URL aborted with the first one's resource already persisted — plus, on the API-agent path, the apicalls, parser, behaviour and LLM resources. Same fix as the `hitlConfig` check: sweep them all up front. +- **Declined, with evidence:** a suggestion to wrap `ToolApprovalPatterns.compile` in a try/catch for "invalid regex syntax". It cannot throw — every non-wildcard segment is `Pattern.quote`d by design. Probed 18 adversarial inputs (`\E`, `\Q`, `[`, `(((`, a lone backslash) and none threw, so the catch would be unreachable code implying a failure mode that does not exist. +- Two doc comments about the docs endpoint's role tier were correct and are fixed. + +Also verified rather than assumed: `PendingToolCallBatch.effectiveRule` round-trips through the snapshot serializer (asserted in `PendingToolCallBatchSnapshotTest`). If it did not, a paused conversation would render the rule's pending message and the resume would recompute the scalar one — leaving the placeholder stranded, since `dropPendingApprovalPlaceholder` removes it by recomputing that exact string. And the null-`callId` branch in `ToolApprovalRules.matchByCallId` is unreachable in production: `AgentOrchestrator.normalizeToolCallIds` assigns a synthetic id to every request whenever the gate is active, so its test documents defensive behaviour rather than a live path. + --- ## 🔎 test(configs): sweep the config JSON the ITs build inline, not just the files (2026-08-01) diff --git a/docs/hitl.md b/docs/hitl.md index f73635fd2b..09cee2e0e8 100644 --- a/docs/hitl.md +++ b/docs/hitl.md @@ -253,9 +253,49 @@ The gate lives in the tool-execution loop (`AgentOrchestrator`), so it is **fail | `pauseReason` | string, ≤ 500 chars | generic | Approver-facing reason; the literal `{toolNames}` placeholder is substituted with the gated tool names. | | `pendingMessage` | string, ≤ 500 chars | `null` | End-user-facing message stored as **public output** at pause commit (so a chat UI shows the user *why* the turn stalled). `{toolNames}` is substituted. | | `inGroupTurns` | `REJECT` | `REJECT` | Behavior when a member agent's tool call is gated inside a group turn. `INBOX` is **reserved** (rejected with a 400 in v1). See [Group members](#group-members). | +| `rules` | list of objects | `null` | Per-tool friction overrides. See [Per-tool approval rules](#per-tool-approval-rules). | All values are validated at **save time** and on ZIP import (`HitlConfigValidation.validateToolApprovals`): bad patterns (with the offending index), a pattern in both `requireApproval` and `exempt`, duplicates, `exempt` without `requireApproval`, out-of-range integers, a reserved `INBOX`, a finite policy without a valid `approvalTimeout`, and overlong reason/message all yield an actionable 400 — the gate never degrades silently at runtime. +### Per-tool approval rules + +The fields above are single scalars for *every* gated tool, so "deploy an agent" and "create an agent" cannot differ in how long a reviewer has or what the approval card says. `rules` fixes that: + +```json +{ + "requireApproval": ["http.post:*", "http.put:*", "http.patch:*", "http.delete:*"], + "exempt": ["http.get:*"], + "rules": [ + { "match": "http.post:/agentstore/agents", + "timeoutPolicy": "WAIT_INDEFINITELY", + "pauseReason": "Creating a new agent — review the whole config" }, + { "match": "http.post:/administration/{environment}/deploy/{agentId}", + "timeoutPolicy": "AUTO_REJECT", "approvalTimeout": "PT5M" }, + { "match": "http.delete:*", "timeoutPolicy": "WAIT_INDEFINITELY" } + ] +} +``` + +| Field | Type | Description | +|-------|------|-------------| +| `match` | pattern | **Required.** Same [pattern language](#pattern-language) as `requireApproval` — bare name, `source:name`, or `source.method:path`. | +| `timeoutPolicy` | `AUTO_APPROVE` \| `AUTO_REJECT` \| `ABORT` \| `WAIT_INDEFINITELY` | Overrides `toolApprovals.timeoutPolicy` for this rule. | +| `approvalTimeout` | ISO-8601 duration | Overrides `toolApprovals.approvalTimeout`. | +| `pauseReason` | string, ≤ 500 chars | Overrides `toolApprovals.pauseReason`. `{toolNames}` is substituted. | +| `pendingMessage` | string, ≤ 500 chars | Overrides `toolApprovals.pendingMessage`. `{toolNames}` is substituted. | + +> **A rule tunes friction; it never gates or ungates.** Whether a call needs approval is decided *only* by `requireApproval`/`exempt`. This is deliberate: the gate allows an unmatched call, so it only survives by gating broadly and exempting narrowly — a rule able to ungate would let a config grant capability by adding an entry. + +Resolution (`ToolApprovalRules`): + +1. **Per call, most specific wins.** Rules are tried fewest-wildcards-first, then longest-pattern-first, so `http.post:/agentstore/agents` beats `http.post:*` **whatever order they are listed in**. +2. **Per batch, strictest wins.** A model can emit several gated calls in one message and they pause *together*, under one policy — so the matched rules are reduced to one: the rule assuming the least human authority on timeout, ordered `WAIT_INDEFINITELY` > `ABORT` > `AUTO_REJECT` > `AUTO_APPROVE` > (no policy stated). Bundling a lenient call into a batch can therefore never soften a stricter rule. Ties break on specificity. +3. **Fields fall back individually** to the `toolApprovals` scalars, so a rule that sets only `pauseReason` keeps the configured timeout policy. + +The governing rule is resolved **at gate time** and persisted on the pending batch (`PendingToolCallBatch.effectiveRule`), because the persisted batch keeps tool names and sources but no endpoints — an endpoint-addressed rule could not be re-matched after the pause. Each gated call also records the rule that tuned it (`matchedRule`), so an approver can tell which call brought the batch's policy. + +Validation mirrors `requireApproval`: `match` goes through the same `ToolApprovalPatterns.validate`, duplicates are refused, `rules` without `requireApproval` is refused, a finite `timeoutPolicy` with no duration at either level is refused, and a `match` string-identical to an `exempt` pattern is refused — an exempt call is never gated, so such a rule could never apply. Only *exact* equality is refused: a broader rule may legitimately overlap an exemption (`http.*:*` alongside an exempt `http.get:*`) while still covering gated calls. The counter `eddi.hitl.rule.matched{match=""}` records which rules actually fire (deduplicated per pause; the tag is the configured pattern, never a URL or argument). + ### Pattern language Patterns are matched by `ToolApprovalPatterns` / `ToolApprovalGate`: @@ -282,9 +322,12 @@ Patterns are matched by `ToolApprovalPatterns` / `ToolApprovalGate`: Tool pauses resolve their effective timeout policy with a deliberate rule (`ConversationService.applyEffectiveToolTimeoutPolicy`): -1. An **explicit** `toolApprovals.timeoutPolicy` wins verbatim — including an explicit `AUTO_APPROVE` (the designer opted in at the tool level). Its `approvalTimeout` is used, falling back to the outer `hitlConfig.approvalTimeout`. -2. Otherwise the outer `hitlConfig.timeoutPolicy`/`approvalTimeout` is inherited, **except** an inherited `AUTO_APPROVE` is **demoted to `WAIT_INDEFINITELY`** — a silent timeout must never auto-execute a gated tool call (that is exactly what the gate exists to prevent). -3. Absent config on both levels leaves the default `WAIT_INDEFINITELY`. +1. The **governing [rule](#per-tool-approval-rules)**'s `timeoutPolicy` wins — the most specific statement in the config, so it is honoured verbatim (`AUTO_APPROVE` included). +2. Otherwise an **explicit** `toolApprovals.timeoutPolicy` wins verbatim — including an explicit `AUTO_APPROVE` (the designer opted in at the tool level). Its `approvalTimeout` is used, falling back to the outer `hitlConfig.approvalTimeout`. +3. Otherwise the outer `hitlConfig.timeoutPolicy`/`approvalTimeout` is inherited, **except** an inherited `AUTO_APPROVE` is **demoted to `WAIT_INDEFINITELY`** — a silent timeout must never auto-execute a gated tool call (that is exactly what the gate exists to prevent). +4. Absent config on every level leaves the default `WAIT_INDEFINITELY`. + +The duration resolves down the same chain independently (rule → `toolApprovals` → `hitlConfig`), so a rule that states only a policy still inherits a clock and actually fires. > **Key rule:** `AUTO_APPROVE` applies to a **tool** pause **only when set explicitly on `toolApprovals`**. Agent-level `AUTO_APPROVE` covers RULE pauses but is demoted for tool pauses. Save-time emits a WARN (not a 400) when an agent sets `AUTO_APPROVE` and a `toolApprovals` block without its own `timeoutPolicy`. diff --git a/docs/mcp-server.md b/docs/mcp-server.md index c3ca7a01e1..6faf5511c4 100644 --- a/docs/mcp-server.md +++ b/docs/mcp-server.md @@ -68,7 +68,9 @@ EDDI uses **Streamable HTTP** transport, served by the Quarkus MCP Server extens | Tool | Description | | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `setup_agent` | Create a fully working agent in one call: creates behavior rules, LangChain config, optional output/greeting, package, agent, and deploys. Supports built-in tools, quick replies, and sentiment analysis. Default: `anthropic`/`claude-sonnet-4-6` | -| `create_api_agent` | Create an agent from an OpenAPI 3.0/3.1 spec. Parses the spec, generates HttpCalls configs (grouped by API tag), creates the full pipeline, and deploys. Supports endpoint filtering, base URL override, and auth header propagation. A generated write tool takes the whole request body as one `requestBody` parameter — see below | +| `create_api_agent` | Create an agent from an OpenAPI 3.0/3.1 spec. Parses the spec, generates HttpCalls configs (grouped by API tag), creates the full pipeline, and deploys. Supports endpoint filtering, base URL override, auth header propagation, and `mcpServerUrls` to add an MCP server's tools alongside the generated ones. A generated write tool takes the whole request body as one `requestBody` parameter — see below | + +> **The approval gate is not settable over MCP.** `POST /administration/agents/setup-api` accepts a `hitlConfig` on the request body, so a caller can provision an agent whose write tools are gated from v1 onward. The MCP `create_api_agent` tool deliberately has **no** such parameter and always passes `null`: it already provisions an agent with a caller-chosen endpoint filter, so letting the caller also choose the gate would make it a complete escape from whatever allow-list governs the agent doing the calling. Provisioning a gated agent goes through REST (`eddi-admin`). ### Schedule Management Tools (6) @@ -164,6 +166,23 @@ EDDI also exposes its documentation as MCP **resources**, allowing AI agents to Configure the docs path with: `eddi.docs.path` (default: `docs/`, in Docker: `/deployments/docs`). +### The same docs over REST + +> **MCP resources do not reach an EDDI agent.** A resource is only usable by a client that asks for it, and EDDI's own MCP client never calls `resources/read` — it consumes *tools*. So `eddi://docs/*` made EDDI's documentation readable by a desktop MCP client and not by an agent running on EDDI, which is precisely backwards for an agent whose job is to explain the platform. + +The same doc set is therefore served read-only over REST, where an agent generated from EDDI's OpenAPI spec picks it up as ordinary tools: + +| Endpoint | Role | Returns | +| -------- | ---- | ------- | +| `GET /administration/docs` | any of `eddi-admin`, `eddi-editor`, `eddi-user`, `eddi-approver`, `eddi-viewer` | JSON array of page names, without the `.md` suffix | +| `GET /administration/docs/{name}` | same | The page's markdown source as `text/plain`; `404` if absent | + +> **Roles are enumerated, not inherited.** EDDI has no role hierarchy — JAX-RS `@RolesAllowed` and the MCP layer's `requireRole` are both literal `hasRole` checks — so `eddi-viewer` alone would refuse an `eddi-admin`. The widest read tier is spelled out because these are published documentation pages. + +Both surfaces delegate to `DocsService`, which owns the filesystem access and the path-traversal guard. + +> **The runtime doc set is smaller than the repository's.** The container image copies only top-level `docs/*.md` (non-recursive, so nothing under `docs/agent-configs/` or `docs/templates/` is reachable) and then removes `changelog.md`, `code-review-standards.md`, `incident-response.md` and `SUMMARY.md`. Call the index and read from it — do not assume a particular page exists. + ## Quick Start ### Client Configuration diff --git a/src/main/java/ai/labs/eddi/configs/agents/rest/RestAgentStore.java b/src/main/java/ai/labs/eddi/configs/agents/rest/RestAgentStore.java index 12822f4e36..75c654ead3 100644 --- a/src/main/java/ai/labs/eddi/configs/agents/rest/RestAgentStore.java +++ b/src/main/java/ai/labs/eddi/configs/agents/rest/RestAgentStore.java @@ -141,8 +141,19 @@ public Response updateAgent(String id, Integer version, AgentConfiguration agent @Override public Response updateResourceInAgent(String id, Integer version, URI resourceURI) { - String resourceURIString = resourceURI.toString(); - String resourceURIWithoutVersion = resourceURIString.substring(0, resourceURIString.lastIndexOf("?")); + // The supplied URI must carry a real version, not merely a '?'. Stored + // references are matched by "everything before the query" and then REPLACED by + // this URI, so '...?other=2' would match a versioned reference and overwrite it + // with a versionless one — silently unpinning the workflow the agent resolves. + // (Testing lastIndexOf('?') alone also made substring(0, -1) throw, turning + // malformed input into a 500 on the re-point cascade an approval-gated agent + // must walk to finish an edit.) + String resourceURIWithoutVersion = RestUtilities.pathWithoutVersionQuery(resourceURI); + if (resourceURIWithoutVersion == null) { + return Response.status(BAD_REQUEST) + .entity("resourceURI must carry a version, e.g. '...?version=2'") + .type(MediaType.TEXT_PLAIN).build(); + } boolean updated = false; AgentConfiguration agentConfig = readAgent(id, version); diff --git a/src/main/java/ai/labs/eddi/configs/hitl/HitlConfigValidation.java b/src/main/java/ai/labs/eddi/configs/hitl/HitlConfigValidation.java index 7296beb93e..bb46f20555 100644 --- a/src/main/java/ai/labs/eddi/configs/hitl/HitlConfigValidation.java +++ b/src/main/java/ai/labs/eddi/configs/hitl/HitlConfigValidation.java @@ -100,6 +100,74 @@ public static void validateToolApprovals(ToolApprovalsConfig cfg, String fieldPa checkReasonLength(cfg.getPauseReason(), fieldPath + ".pauseReason"); checkReasonLength(cfg.getPendingMessage(), fieldPath + ".pendingMessage"); + + validateRules(cfg, fieldPath); + } + + /** + * Validates {@code toolApprovals.rules} — the per-tool friction overrides. + *

+ * {@code match} goes through the same {@link ToolApprovalPatterns#validate} as + * a gating pattern, so a rule that could never match is refused rather than + * saved. That matters less here than for {@code requireApproval} (an + * unmatchable rule costs the designer their intended friction, not the gate + * itself), but the failure looks identical from the outside — a config that + * reads as if it were protecting something — so it is refused the same way. + */ + private static void validateRules(ToolApprovalsConfig cfg, String fieldPath) { + List rules = cfg.getRules(); + if (rules == null || rules.isEmpty()) { + return; + } + if (cfg.getRequireApproval() == null || cfg.getRequireApproval().isEmpty()) { + throw new IllegalArgumentException(fieldPath + + ".rules has no effect without requireApproval patterns — rules tune the friction on a gated" + + " call, they never gate one"); + } + Set seen = new HashSet<>(); + for (int i = 0; i < rules.size(); i++) { + String rulePath = fieldPath + ".rules[" + i + "]"; + ToolApprovalsConfig.ApprovalRule rule = rules.get(i); + if (rule == null) { + throw new IllegalArgumentException(rulePath + " must not be null"); + } + Optional error = ToolApprovalPatterns.validate(rule.getMatch()); + if (error.isPresent()) { + throw new IllegalArgumentException(rulePath + ".match: " + error.get()); + } + if (!seen.add(rule.getMatch())) { + throw new IllegalArgumentException("duplicate rule match '" + rule.getMatch() + "' in " + fieldPath + + ".rules — only one would ever apply; merge them"); + } + // A rule whose pattern is string-identical to an exempt pattern is provably + // dead: any call it could match is exempt, so it is never gated, so no rule + // is ever resolved for it. Only the exact-equality case is checked — a rule + // may legitimately OVERLAP an exempt pattern while still covering gated + // calls (e.g. 'http.*:*' alongside an exempt 'http.get:*'), and deciding + // that in general would mean reasoning about globs over an unknown tool + // set. Exact equality needs no such reasoning. + if (cfg.getExempt() != null && cfg.getExempt().contains(rule.getMatch())) { + throw new IllegalArgumentException(rulePath + ".match '" + rule.getMatch() + + "' is also an exempt pattern, so it can never apply — an exempt call is never gated, and a" + + " rule only tunes a gated call. Remove the rule or the exemption"); + } + // Format only — the "a finite policy needs a duration" check is rule-scoped + // below, because a rule may legitimately inherit the enclosing timeout. + validateApprovalTimeout(rule.getApprovalTimeout(), false); + boolean finitePolicy = rule.getTimeoutPolicy() != null + && rule.getTimeoutPolicy() != HitlTimeoutPolicy.WAIT_INDEFINITELY; + if (finitePolicy && isNullOrBlank(rule.getApprovalTimeout()) && isNullOrBlank(cfg.getApprovalTimeout())) { + throw new IllegalArgumentException(rulePath + ".timeoutPolicy is " + rule.getTimeoutPolicy() + + ", which never fires without a duration — set " + rulePath + ".approvalTimeout (ISO-8601," + + " e.g. \"PT5M\") or " + fieldPath + ".approvalTimeout for the rule to inherit"); + } + checkReasonLength(rule.getPauseReason(), rulePath + ".pauseReason"); + checkReasonLength(rule.getPendingMessage(), rulePath + ".pendingMessage"); + } + } + + private static boolean isNullOrBlank(String value) { + return value == null || value.isBlank(); } private static Set validatePatternList(List patterns, String fieldPath) { diff --git a/src/main/java/ai/labs/eddi/configs/hitl/model/ToolApprovalsConfig.java b/src/main/java/ai/labs/eddi/configs/hitl/model/ToolApprovalsConfig.java index b40606bb63..2f29f820f2 100644 --- a/src/main/java/ai/labs/eddi/configs/hitl/model/ToolApprovalsConfig.java +++ b/src/main/java/ai/labs/eddi/configs/hitl/model/ToolApprovalsConfig.java @@ -54,6 +54,90 @@ public class ToolApprovalsConfig { * REJECT (default) | INBOX (reserved, 400 in v1) — behavior inside group turns. */ private String inGroupTurns; + /** + * Optional per-tool friction, most-specific-first. See {@link ApprovalRule} — + * rules tune HOW a gated call is reviewed, never WHETHER it is gated. + */ + private List rules; + + /** + * Per-tool override of the approval scalars above, addressed by the same + * pattern language as {@code requireApproval} (see + * {@code ToolApprovalPatterns}): a bare tool name, {@code source:name}, or — + * for httpcall tools — {@code source.method:path}, e.g. + * {@code http.post:/agentstore/agents}. + *

+ * A rule tunes friction; it never gates or ungates. Whether a call needs + * approval is decided solely by {@code requireApproval}/{@code exempt}. A rule + * able to ungate would mean a config could grant capability by adding an entry, + * i.e. enumerating upward — the opposite of the gate's design, which allows an + * unmatched call and therefore only ever survives by gating broadly and + * exempting narrowly. + *

+ * Every field is optional and falls back individually to the enclosing + * {@link ToolApprovalsConfig} scalar, so a rule that sets only + * {@code pauseReason} still inherits the configured timeout policy. + */ + public static class ApprovalRule { + /** Pattern selecting the tool calls this rule applies to. Required. */ + private String match; + /** Overrides {@link ToolApprovalsConfig#getTimeoutPolicy()} for this rule. */ + private HitlTimeoutPolicy timeoutPolicy; + /** Overrides {@link ToolApprovalsConfig#getApprovalTimeout()}. */ + private String approvalTimeout; + /** Overrides {@link ToolApprovalsConfig#getPauseReason()}. ≤500 chars. */ + private String pauseReason; + /** Overrides {@link ToolApprovalsConfig#getPendingMessage()}. ≤500 chars. */ + private String pendingMessage; + + public String getMatch() { + return match; + } + + public void setMatch(String match) { + this.match = match; + } + + public HitlTimeoutPolicy getTimeoutPolicy() { + return timeoutPolicy; + } + + public void setTimeoutPolicy(HitlTimeoutPolicy timeoutPolicy) { + this.timeoutPolicy = timeoutPolicy; + } + + public String getApprovalTimeout() { + return approvalTimeout; + } + + public void setApprovalTimeout(String approvalTimeout) { + this.approvalTimeout = approvalTimeout; + } + + public String getPauseReason() { + return pauseReason; + } + + public void setPauseReason(String pauseReason) { + this.pauseReason = pauseReason; + } + + public String getPendingMessage() { + return pendingMessage; + } + + public void setPendingMessage(String pendingMessage) { + this.pendingMessage = pendingMessage; + } + } + + public List getRules() { + return rules; + } + + public void setRules(List rules) { + this.rules = rules; + } public List getRequireApproval() { return requireApproval; diff --git a/src/main/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStore.java b/src/main/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStore.java index 3cb8168eee..32716dbe96 100644 --- a/src/main/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStore.java +++ b/src/main/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStore.java @@ -95,8 +95,16 @@ public Response updateWorkflow(String id, Integer version, WorkflowConfiguration @Override public Response updateResourceInWorkflow(String id, Integer version, URI resourceURI) { - String resourceURIString = resourceURI.toString(); - String resourceURIWithoutVersion = resourceURIString.substring(0, resourceURIString.lastIndexOf("?")); + // Must carry a real version, not merely a '?' — same guard and same reason as + // the agent-store variant: a stored reference is matched by everything before + // the query and then replaced by this URI, so '...?other=2' would overwrite a + // versioned reference with a versionless one. + String resourceURIWithoutVersion = RestUtilities.pathWithoutVersionQuery(resourceURI); + if (resourceURIWithoutVersion == null) { + return Response.status(BAD_REQUEST) + .entity("resourceURI must carry a version, e.g. '...?version=2'") + .type(MediaType.TEXT_PLAIN).build(); + } boolean updated = false; WorkflowConfiguration workflowConfig = readWorkflow(id, version); diff --git a/src/main/java/ai/labs/eddi/engine/api/IRestDocs.java b/src/main/java/ai/labs/eddi/engine/api/IRestDocs.java new file mode 100644 index 0000000000..83e45d06ec --- /dev/null +++ b/src/main/java/ai/labs/eddi/engine/api/IRestDocs.java @@ -0,0 +1,67 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.engine.api; + +import jakarta.annotation.security.RolesAllowed; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.eclipse.microprofile.openapi.annotations.Operation; +import org.eclipse.microprofile.openapi.annotations.parameters.Parameter; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; +import org.eclipse.microprofile.openapi.annotations.tags.Tag; + +import java.util.List; + +/** + * Read-only access to EDDI's own documentation. + *

+ * The same doc set that MCP serves at {@code eddi://docs/*}. It needs a REST + * surface too because MCP resources only reach a client that asks for + * them and EDDI's own MCP client never calls {@code resources/read} — so an + * agent built on EDDI could not read EDDI's documentation, which is exactly + * what an agent meant to explain the platform needs. Over REST these become + * ordinary generated tools. + *

+ * Roles are enumerated, not inherited. EDDI has no role hierarchy — + * neither JAX-RS {@code @RolesAllowed} nor the MCP layer's + * {@code McpToolUtils.requireRole} (a literal {@code identity.hasRole}) grants + * one role by virtue of holding a more privileged one. So the read tier is + * spelled out. In particular this must NOT be {@code eddi-viewer} alone: that + * role appears only on the MCP surface, and an {@code eddi-admin} principal — + * which is what an operator agent actually runs as — would be refused by the + * one endpoint built for it. + *

+ * The set is deliberately the widest read tier in the codebase: these are the + * project's published documentation pages, so anyone permitted to use the + * deployment at all may read them. + * + * @since 6.2.0 + */ +@Path("/administration/docs") +@Tag(name = "Operations / Docs", description = "Read EDDI's own documentation") +@RolesAllowed({"eddi-admin", "eddi-editor", "eddi-user", "eddi-approver", "eddi-viewer"}) +public interface IRestDocs { + + @GET + @Produces(MediaType.APPLICATION_JSON) + @Operation(summary = "List available documentation pages", description = "Returns the names of the documentation pages this deployment " + + "serves, without the .md suffix. The runtime set is smaller than the repository's — the container image ships only the " + + "top-level docs and omits a few — so read this list rather than assuming a page exists.") + @APIResponse(responseCode = "200", description = "Available documentation page names.") + List listDocs(); + + @GET + @Path("/{name}") + @Produces(MediaType.TEXT_PLAIN) + @Operation(summary = "Read a documentation page", description = "Returns the markdown source of one documentation page.") + @APIResponse(responseCode = "200", description = "The page's markdown source.") + @APIResponse(responseCode = "404", description = "No such documentation page in this deployment.") + Response readDoc(@Parameter(description = "Page name without the .md suffix, e.g. 'architecture'.") + @PathParam("name") String name); +} diff --git a/src/main/java/ai/labs/eddi/engine/docs/DocsService.java b/src/main/java/ai/labs/eddi/engine/docs/DocsService.java new file mode 100644 index 0000000000..f536d7ac0c --- /dev/null +++ b/src/main/java/ai/labs/eddi/engine/docs/DocsService.java @@ -0,0 +1,127 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.engine.docs; + +import jakarta.enterprise.context.ApplicationScoped; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.TreeSet; + +/** + * Reads EDDI's own markdown documentation off the filesystem. + *

+ * Extracted from {@code McpDocResources} so the same doc set is reachable from + * more than one surface. MCP resources are only usable by a client + * that asks for them — EDDI's own MCP client never calls {@code resources/read} + * — so as long as this logic lived only behind {@code eddi://docs/*}, a desktop + * MCP client could read EDDI's documentation and an EDDI agent could not. The + * REST surface ({@code /administration/docs}) closes that gap: an agent + * generated from EDDI's OpenAPI spec gets doc access as ordinary tools. + * + *

Runtime doc set is smaller than the repo's

The Docker image copies + * only top-level {@code docs/*.md} (non-recursive) and then deletes + * {@code changelog.md}, {@code code-review-standards.md}, + * {@code incident-response.md} and {@code SUMMARY.md}. So callers must treat + * "not found" as normal and read {@link #listDocs()} rather than assuming any + * particular page exists — nothing here should hard-code a doc name. + */ +@ApplicationScoped +public class DocsService { + + private static final Logger LOGGER = Logger.getLogger(DocsService.class); + private static final String MD_SUFFIX = ".md"; + + @ConfigProperty(name = "eddi.docs.path", defaultValue = "docs") + String docsPath; + + /** + * The configured docs directory, for diagnostics. Callers surface this when + * {@link #isAvailable()} is false — "0 documents" reads as success, whereas a + * mis-set {@code eddi.docs.path} is the realistic misconfiguration and should + * say so. + */ + public String docsDirectory() { + return docsPath; + } + + /** Whether the configured docs directory exists and is a directory. */ + public boolean isAvailable() { + return Files.isDirectory(Path.of(docsPath)); + } + + /** Sorted names of the available docs, without the {@code .md} suffix. */ + public List listDocs() { + Path docsDir = Path.of(docsPath); + if (!Files.isDirectory(docsDir)) { + LOGGER.warnf("Docs directory not found: %s", docsPath); + return List.of(); + } + var docs = new TreeSet(); + try (DirectoryStream stream = Files.newDirectoryStream(docsDir, "*" + MD_SUFFIX)) { + for (Path entry : stream) { + String filename = entry.getFileName().toString(); + docs.add(filename.substring(0, filename.length() - MD_SUFFIX.length())); + } + } catch (IOException e) { + LOGGER.error("Failed to list docs", e); + return List.of(); + } + return List.copyOf(docs); + } + + /** + * Whether a doc name is usable at all: non-empty and free of path separators + * and parent references. + *

+ * Public and shared so a caller that wants to tell "you asked for something + * illegal" apart from "there is no such page" does not have to restate the + * predicate — {@code McpDocResources} did exactly that, and two copies of a + * security check drift. + *

+ * Note this is not the only guard: {@link #readDoc} also verifies the + * resolved path still sits under the docs directory, which catches everything + * this does and more. The shape check is kept for the clearer rejection it + * allows, not because the normalisation check needs help. + */ + public static boolean isValidDocName(String name) { + return name != null && !name.isEmpty() && !name.contains("/") && !name.contains("\\") && !name.contains(".."); + } + + /** + * Reads one doc by name (with or without the {@code .md} suffix), or null if + * the name is unusable or no such doc exists. + */ + public String readDoc(String name) { + if (!isValidDocName(name)) { + LOGGER.warnf("Rejected doc name: %s", name); + return null; + } + Path docsDir = Path.of(docsPath).toAbsolutePath().normalize(); + Path docFile = docsDir.resolve(name + MD_SUFFIX).normalize(); + if (!docFile.startsWith(docsDir)) { + LOGGER.warnf("Path traversal attempt blocked: %s", name); + return null; + } + if (!Files.isRegularFile(docFile)) { + // The name may already carry the .md suffix. + docFile = docsDir.resolve(name).normalize(); + if (!docFile.startsWith(docsDir) || !Files.isRegularFile(docFile)) { + return null; + } + } + try { + return Files.readString(docFile); + } catch (IOException e) { + LOGGER.error("Failed to read doc: " + name, e); + return null; + } + } +} diff --git a/src/main/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalGate.java b/src/main/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalGate.java index 6263804863..da9499f7bf 100644 --- a/src/main/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalGate.java +++ b/src/main/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalGate.java @@ -19,9 +19,11 @@ * allowed calls. *

* Precedence: (P1) exempt always beats requireApproval; (P2) any pattern match - * suffices; (P3) empty/absent requireApproval = gate fully inactive. Patterns - * are tested against {@code "source:name"} first, then the bare dispatch name — - * fail-safe: a tool with unknown source still matches bare-name patterns. + * suffices; (P3) empty/absent requireApproval = gate fully inactive. Each call + * is tested against the forms in {@link #addressesOf} — + * {@code source.method:path}, then {@code source:name}, then the bare dispatch + * name — fail-safe: a tool with an unknown source still matches bare-name + * patterns. */ public class ToolApprovalGate { @@ -75,16 +77,12 @@ public GateResult classify(List batch, Map allowed.add(request); continue; } - String source = toolSources.get(request.name()); - String qualified = source != null ? source + ":" + request.name() : null; - // e.g. "http" + "." + "post:/agentstore/agents" - String endpoint = toolEndpoints.get(request.name()); - String endpointQualified = source != null && endpoint != null ? source + "." + endpoint : null; - if (firstMatch(exempt, qualified, endpointQualified, request.name()) != null) { + List addresses = addressesOf(request.name(), toolSources, toolEndpoints); + if (firstMatch(exempt, addresses) != null) { allowed.add(request); continue; } - CompiledPattern match = firstMatch(require, qualified, endpointQualified, request.name()); + CompiledPattern match = firstMatch(require, addresses); if (match != null) { gated.add(request); if (request.id() != null) { @@ -97,6 +95,39 @@ public GateResult classify(List batch, Map return new GateResult(gated, allowed, reasons); } + /** + * The forms a pattern may address one tool call by, in the order they are + * tried: {@code source.method:path} (httpcall tools only), {@code source:name}, + * and the bare {@code name}. + *

+ * Extracted and public so that everything matching a configured + * pattern against a tool call — the gate itself and {@link ToolApprovalRules}, + * which picks the per-tool friction rule — asks the identical question. A + * second, independent copy of this derivation would drift silently, and since + * the gate allows an unmatched call, drift here is an ungated write. + *

+ * Entries that cannot be derived are omitted, so the result is empty for a null + * name (a malformed provider tool call) and matches nothing. + */ + public static List addressesOf(String name, Map toolSources, + Map toolEndpoints) { + if (name == null) { + return List.of(); + } + String source = toolSources.get(name); + // e.g. "http" + "." + "post:/agentstore/agents" + String endpoint = toolEndpoints.get(name); + List addresses = new ArrayList<>(3); + if (source != null && endpoint != null) { + addresses.add(source + "." + endpoint); + } + if (source != null) { + addresses.add(source + ":" + name); + } + addresses.add(name); + return addresses; + } + private record CompiledPattern(String raw, Pattern pattern) { } @@ -107,20 +138,23 @@ private static List compileAll(List globs) { return globs.stream().map(g -> new CompiledPattern(g, ToolApprovalPatterns.compile(g))).toList(); } - private static CompiledPattern firstMatch(List patterns, String qualified, String endpointQualified, String bare) { + /** + * Pattern order dominates address order: the first configured pattern matching + * any address wins. + *

+ * {@code addresses} is empty for a null tool name (langchain4j's + * {@code ToolExecutionRequest} does not guarantee one — some providers emit + * malformed tool calls), so such a call matches nothing and flows to + * {@code allowed}; the gate stays inert for it and the downstream dispatch + * degrades gracefully to "tool not found", as it did pre-HITL, instead of + * failing the whole turn. + */ + private static CompiledPattern firstMatch(List patterns, List addresses) { for (CompiledPattern cp : patterns) { - if (endpointQualified != null && cp.pattern().matcher(endpointQualified).matches()) { - return cp; - } - // bare (= request.name()) can be null: langchain4j's ToolExecutionRequest - // does not guarantee a non-null name (some providers emit malformed tool - // calls). Guard both matchers so a null name matches nothing and the call - // flows to `allowed` — the gate stays inert for it and the downstream tool - // dispatch degrades gracefully to "tool not found", as it did pre-HITL, - // instead of NPEing and failing the whole turn. - if ((qualified != null && cp.pattern().matcher(qualified).matches()) - || (bare != null && cp.pattern().matcher(bare).matches())) { - return cp; + for (String address : addresses) { + if (cp.pattern().matcher(address).matches()) { + return cp; + } } } return null; diff --git a/src/main/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalRules.java b/src/main/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalRules.java new file mode 100644 index 0000000000..2a8e8ca138 --- /dev/null +++ b/src/main/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalRules.java @@ -0,0 +1,176 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.engine.hitl.tools; + +import ai.labs.eddi.configs.hitl.HitlTimeoutPolicy; +import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig; +import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig.ApprovalRule; +import dev.langchain4j.agent.tool.ToolExecutionRequest; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * Resolves the per-tool friction rule ({@code toolApprovals.rules}) governing a + * gated tool-call batch. + *

+ * Rules answer "how carefully is this reviewed?" — timeout policy, timeout, + * approver-facing reason, end-user pending message. They deliberately cannot + * answer "is this reviewed at all?": that stays with + * {@code requireApproval}/{@code exempt} in {@link ToolApprovalGate}, which + * this class never consults and never overrides. + * + *

Per call: most specific wins

A rule is matched against a call using + * {@link ToolApprovalGate#addressesOf} — the same three addressing forms the + * gate itself uses, from the same method, so a rule can never address a call + * differently than the pattern that gated it. Rules are tried most-specific + * first: fewer wildcards beats more, then the longer pattern beats the shorter. + * So {@code http.post:/agentstore/agents} takes precedence over + * {@code http.post:*}, whatever order the designer listed them in. + * + *

Per batch: strictest wins

A model can emit several gated calls in + * one message and they pause together, under one timeout policy — so + * the calls' rules must be reduced to one. The batch is governed by the matched + * rule that assumes the least human authority on timeout: + *
    + *
  1. {@code WAIT_INDEFINITELY} — assumes none; the pause outlives any + * clock
  2. + *
  3. {@code ABORT} — decides nothing, but abandons the turn
  4. + *
  5. {@code AUTO_REJECT} — decides "no" on the human's behalf
  6. + *
  7. {@code AUTO_APPROVE} — decides "yes", executing the write unreviewed
  8. + *
+ * A rule with no {@code timeoutPolicy} expresses no opinion and yields to any + * rule that does; ties break on specificity. The practical guarantee: mixing a + * lenient rule into a batch can never soften a stricter one, so + * {@code http.delete:*} at {@code WAIT_INDEFINITELY} still holds when the model + * bundles a delete with an auto-approved read-ish write. + */ +public final class ToolApprovalRules { + + private ToolApprovalRules() { + } + + /** + * The rule governing each gated call, keyed by call id. Calls with no id or + * matching no rule are absent; an empty map means "no rules apply, use the + * scalars". + */ + public static Map matchByCallId(List gated, + Map toolSources, + Map toolEndpoints, + ToolApprovalsConfig cfg) { + Map result = new LinkedHashMap<>(); + List compiled = compile(cfg); + if (compiled.isEmpty() || gated == null) { + return result; + } + for (ToolExecutionRequest request : gated) { + if (request.id() == null) { + continue; + } + ApprovalRule rule = firstMatch(compiled, ToolApprovalGate.addressesOf(request.name(), toolSources, toolEndpoints)); + if (rule != null) { + result.put(request.id(), rule); + } + } + return result; + } + + /** + * Reduces the rules matched across a batch to the single one that governs its + * pause — see the strictness ordering in the class javadoc. Returns null when + * nothing matched, in which case every field falls back to the + * {@link ToolApprovalsConfig} scalars. + */ + public static ApprovalRule governing(Collection matched) { + if (matched == null || matched.isEmpty()) { + return null; + } + return matched.stream().filter(Objects::nonNull) + .max(Comparator.comparingInt((ApprovalRule r) -> strictness(r.getTimeoutPolicy())) + .thenComparing(Comparator.comparingInt(ToolApprovalRules::specificity))) + .orElse(null); + } + + /** + * Convenience for the common path: match, then reduce. Returns null when the + * config has no rules or none matched. + */ + public static ApprovalRule governing(List gated, Map toolSources, + Map toolEndpoints, ToolApprovalsConfig cfg) { + return governing(matchByCallId(gated, toolSources, toolEndpoints, cfg).values()); + } + + /** + * How much of the human's decision the policy takes on timeout, ascending. Only + * {@code AUTO_APPROVE} can produce an unreviewed side effect, so it must lose + * every tie-break; {@code WAIT_INDEFINITELY} takes no decision at all, so it + * wins them. A null policy has no opinion and loses to every stated one. + */ + private static int strictness(HitlTimeoutPolicy policy) { + if (policy == null) { + return 0; + } + return switch (policy) { + case AUTO_APPROVE -> 1; + case AUTO_REJECT -> 2; + case ABORT -> 3; + case WAIT_INDEFINITELY -> 4; + }; + } + + /** + * Higher is more specific: a pattern with fewer wildcards beats one with more, + * and among equals the longer literal wins. Scored so the two criteria cannot + * trade off against each other — a single {@code *} costs more than any + * realistic pattern length ({@code ToolApprovalPatterns} caps patterns at 256 + * characters). + */ + private static int specificity(ApprovalRule rule) { + String match = rule.getMatch(); + if (match == null) { + return Integer.MIN_VALUE; + } + int wildcards = (int) match.chars().filter(c -> c == '*').count(); + return -wildcards * 1024 + match.length(); + } + + private record CompiledRule(ApprovalRule rule, Pattern pattern) { + } + + /** Rules compiled and sorted most-specific-first; invalid entries dropped. */ + private static List compile(ToolApprovalsConfig cfg) { + if (cfg == null || cfg.getRules() == null || cfg.getRules().isEmpty()) { + return List.of(); + } + List sorted = new ArrayList<>(); + for (ApprovalRule rule : cfg.getRules()) { + // A blank match is refused at save time (HitlConfigValidation); skipping it + // here keeps a hand-edited or legacy document from failing a live turn. + if (rule != null && rule.getMatch() != null && !rule.getMatch().isBlank()) { + sorted.add(rule); + } + } + sorted.sort(Comparator.comparingInt(ToolApprovalRules::specificity).reversed()); + return sorted.stream().map(r -> new CompiledRule(r, ToolApprovalPatterns.compile(r.getMatch()))).toList(); + } + + private static ApprovalRule firstMatch(List compiled, List addresses) { + for (CompiledRule cr : compiled) { + for (String address : addresses) { + if (cr.pattern().matcher(address).matches()) { + return cr.rule(); + } + } + } + return null; + } +} diff --git a/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java b/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java index 54aa6710a5..1be22ac354 100644 --- a/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java +++ b/src/main/java/ai/labs/eddi/engine/internal/ConversationService.java @@ -21,6 +21,7 @@ import ai.labs.eddi.engine.hitl.HitlSchedules; import ai.labs.eddi.engine.lifecycle.model.HitlDecision; import ai.labs.eddi.engine.lifecycle.model.ToolCallDecision; +import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig; import ai.labs.eddi.engine.memory.model.PendingToolCallBatch; import ai.labs.eddi.engine.tenancy.QuotaExceededException; import ai.labs.eddi.engine.tenancy.TenantQuotaService; @@ -2051,7 +2052,7 @@ private NoProgressOutcome evaluateAndApplyNoProgressGuard(String conversationId, // Fix #1: resolve max-auto-approvals + onNoProgress from the config that gated // the RE-PAUSE batch (task-scoped override when present), falling back to the // agent-level default for a legacy/null-field batch. - ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig noProgressCfg = newBatch.getEffectiveToolApprovals() != null + ToolApprovalsConfig noProgressCfg = newBatch.getEffectiveToolApprovals() != null ? newBatch.getEffectiveToolApprovals() : memory.getAgentToolApprovalsConfig(); int maxAutoApprovals = resolveMaxAutoApprovals(noProgressCfg); @@ -2103,7 +2104,7 @@ private NoProgressOutcome evaluateAndApplyNoProgressGuard(String conversationId, * Effective max consecutive system auto-approvals per turn (default 2, clamped * 0..10). */ - private static int resolveMaxAutoApprovals(ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig cfg) { + private static int resolveMaxAutoApprovals(ToolApprovalsConfig cfg) { if (cfg == null || cfg.getMaxAutoApprovalsPerTurn() == null) { return DEFAULT_MAX_AUTO_APPROVALS_PER_TURN; } @@ -2111,7 +2112,7 @@ private static int resolveMaxAutoApprovals(ai.labs.eddi.configs.hitl.model.ToolA } /** Effective onNoProgress policy (WAIT_FOR_HUMAN default). */ - private static String resolveOnNoProgress(ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig cfg) { + private static String resolveOnNoProgress(ToolApprovalsConfig cfg) { if (cfg == null || isNullOrEmpty(cfg.getOnNoProgress())) { return "WAIT_FOR_HUMAN"; } @@ -2484,6 +2485,9 @@ private void populateHitlTimeoutBookmark(IConversationMemory memory) { * Task 10 — resolves the EFFECTIVE tool-pause timeout policy and writes it into * the memory bookmark. Precedence: *
    + *
  1. the governing {@code toolApprovals.rules} entry's {@code timeoutPolicy} — + * the most specific statement there is, resolved at gate time and carried on + * the batch (iteration 1);
  2. *
  3. an explicit {@code toolApprovals.timeoutPolicy} (with its own * {@code approvalTimeout}) wins verbatim — an explicit AUTO_APPROVE is * honored;
  4. @@ -2492,7 +2496,10 @@ private void populateHitlTimeoutBookmark(IConversationMemory memory) { * {@code WAIT_INDEFINITELY} so a silent timeout never auto-executes a gated * tool call. *
- * Absent config on both levels leaves the default WAIT_INDEFINITELY already set + * The timeout resolves down the same chain independently, so a rule that states + * only a policy still inherits a duration. + *

+ * Absent config on every level leaves the default WAIT_INDEFINITELY already set * by the caller. */ private void applyEffectiveToolTimeoutPolicy(IConversationMemory memory, AgentConfiguration.HitlConfig hitlConfig) { @@ -2502,26 +2509,42 @@ private void applyEffectiveToolTimeoutPolicy(IConversationMemory memory, AgentCo // agent-level hitlConfig.toolApprovals for a legacy batch (null field) or a // null batch. The inherit-from-outer fallback and the AUTO_APPROVE-demotion // below still read the OUTER hitlConfig — Task 10 semantics unchanged. - ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig toolApprovals = effectiveToolApprovals(memory, hitlConfig); + ToolApprovalsConfig toolApprovals = effectiveToolApprovals(memory, hitlConfig); + PendingToolCallBatch pendingBatch = memory.getHitlPendingToolCalls(); + ToolApprovalsConfig.ApprovalRule rule = pendingBatch != null ? pendingBatch.getEffectiveRule() : null; + // The duration resolves down its own chain, independently of which branch + // decides the policy: rule → toolApprovals → outer hitlConfig. Computed once + // rather than repeated per branch — three identical copies would drift, and a + // rule stating only "AUTO_REJECT" must still inherit a duration or the policy + // never fires. + // + // Blank-aware on purpose: HitlConfigValidation treats a whitespace-only + // approvalTimeout as ABSENT (isBlank) when deciding whether a finite rule may + // inherit the enclosing duration, so it saves cleanly. If resolution here + // treated it as PRESENT (isEmpty), it would win the chain, Duration.parse + // would throw inside scheduleHitlTimeout, no schedule would be armed, and the + // finite policy would silently degrade to wait-forever while the bookmark + // still reported the finite policy name. + String effectiveTimeout = firstNonBlank( + rule != null ? rule.getApprovalTimeout() : null, + toolApprovals != null ? toolApprovals.getApprovalTimeout() : null, + hitlConfig.getApprovalTimeout()); + HitlTimeoutPolicy effectivePolicy; - String effectiveTimeout; - if (toolApprovals != null && toolApprovals.getTimeoutPolicy() != null) { + if (rule != null && rule.getTimeoutPolicy() != null) { + // Most specific statement in the config — honored verbatim, AUTO_APPROVE + // included: naming one endpoint and giving it a policy is as explicit as a + // designer can be. + effectivePolicy = rule.getTimeoutPolicy(); + } else if (toolApprovals != null && toolApprovals.getTimeoutPolicy() != null) { // Explicit tool-level override — honored verbatim (AUTO_APPROVE included). effectivePolicy = toolApprovals.getTimeoutPolicy(); - effectiveTimeout = !isNullOrEmpty(toolApprovals.getApprovalTimeout()) - ? toolApprovals.getApprovalTimeout() - : hitlConfig.getApprovalTimeout(); } else { // Inherit the outer policy, demoting AUTO_APPROVE to WAIT_INDEFINITELY. effectivePolicy = hitlConfig.getTimeoutPolicy(); if (effectivePolicy == HitlTimeoutPolicy.AUTO_APPROVE) { effectivePolicy = HitlTimeoutPolicy.WAIT_INDEFINITELY; } - // A tool-level approvalTimeout may still be set even without a tool-level - // policy — prefer it, else inherit the outer timeout. - effectiveTimeout = toolApprovals != null && !isNullOrEmpty(toolApprovals.getApprovalTimeout()) - ? toolApprovals.getApprovalTimeout() - : hitlConfig.getApprovalTimeout(); } if (effectivePolicy == null) { effectivePolicy = HitlTimeoutPolicy.WAIT_INDEFINITELY; @@ -2530,6 +2553,20 @@ private void applyEffectiveToolTimeoutPolicy(IConversationMemory memory, AgentCo memory.setHitlApprovalTimeout(effectiveTimeout); } + /** + * First value that is neither null nor blank, or null. Blank-aware because + * {@code RuntimeUtilities.isNullOrEmpty} is not: a whitespace-only duration + * saves as "absent" and must resolve as absent too. + */ + private static String firstNonBlank(String... candidates) { + for (String candidate : candidates) { + if (candidate != null && !candidate.isBlank()) { + return candidate; + } + } + return null; + } + /** * Fix #1: resolves the TASK-SCOPED effective tool-approval config for a paused * batch. Returns the config the batch carries (persisted at gate time — the @@ -2538,9 +2575,9 @@ private void applyEffectiveToolTimeoutPolicy(IConversationMemory memory, AgentCo * the batch is null (never populated) or carries a null effective config (a * legacy pre-fix batch) — so those paths resolve EXACTLY as before the fix. */ - private static ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig effectiveToolApprovals( - IConversationMemory memory, - AgentConfiguration.HitlConfig hitlConfig) { + private static ToolApprovalsConfig effectiveToolApprovals( + IConversationMemory memory, + AgentConfiguration.HitlConfig hitlConfig) { PendingToolCallBatch batch = memory.getHitlPendingToolCalls(); if (batch != null && batch.getEffectiveToolApprovals() != null) { return batch.getEffectiveToolApprovals(); diff --git a/src/main/java/ai/labs/eddi/engine/mcp/McpDocResources.java b/src/main/java/ai/labs/eddi/engine/mcp/McpDocResources.java index 7f2af79fcc..f12942933d 100644 --- a/src/main/java/ai/labs/eddi/engine/mcp/McpDocResources.java +++ b/src/main/java/ai/labs/eddi/engine/mcp/McpDocResources.java @@ -4,18 +4,14 @@ */ package ai.labs.eddi.engine.mcp; +import ai.labs.eddi.engine.docs.DocsService; import io.quarkiverse.mcp.server.Resource; import io.quarkiverse.mcp.server.ResourceTemplate; import io.quarkiverse.mcp.server.ResourceTemplateArg; import jakarta.enterprise.context.ApplicationScoped; -import org.eclipse.microprofile.config.inject.ConfigProperty; -import org.jboss.logging.Logger; +import jakarta.inject.Inject; -import java.io.IOException; -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.*; +import java.util.List; /** * Expose EDDI documentation as MCP resources. @@ -23,19 +19,23 @@ * AI agents can browse and read the 40+ markdown docs via MCP resources/list * and resources/read. *

- * Docs are loaded from the filesystem at a configurable path (default: - * {@code docs/} relative to working directory). In Docker, docs must be copied - * into the container. + * Thin delegate over {@link DocsService}, which owns the filesystem access and + * the path-traversal guard. The same doc set is served over REST at + * {@code /administration/docs} — MCP resources only reach clients that + * ask for them, and EDDI's own MCP client never does, so this surface alone + * left EDDI's docs readable by a desktop client and not by an EDDI agent. * * @author ginccc */ @ApplicationScoped public class McpDocResources { - private static final Logger LOGGER = Logger.getLogger(McpDocResources.class); + private final DocsService docsService; - @ConfigProperty(name = "eddi.docs.path", defaultValue = "docs") - String docsPath; + @Inject + public McpDocResources(DocsService docsService) { + this.docsService = docsService; + } /** * Read a specific doc by name. Example URI: eddi://docs/getting-started @@ -47,34 +47,20 @@ public class McpDocResources { @ResourceTemplate(uriTemplate = "eddi://docs/{name}", name = "eddi-doc", description = "Read an EDDI documentation page by name. " + "Pass the doc name without .md extension, " + "e.g. 'getting-started', 'architecture', 'langchain'") public String readDoc(@ResourceTemplateArg(name = "name") String name) { - // Path traversal protection: reject names with directory separators or parent - // refs - if (name == null || name.isEmpty() || name.contains("/") || name.contains("\\") || name.contains("..")) { - return "Invalid document name: " + name; + String content = docsService.readDoc(name); + if (content != null) { + return content; } - - Path docsDir = Path.of(docsPath).toAbsolutePath().normalize(); - Path docFile = docsDir.resolve(name + ".md").normalize(); - - // Defense-in-depth: verify resolved path is within docs directory - if (!docFile.startsWith(docsDir)) { - LOGGER.warnf("Path traversal attempt blocked: %s", name); + // MCP resources have no error channel here, so the two failure modes stay + // distinguishable in the returned text, exactly as before the extraction: + // a rejected name reads as invalid, an accepted-but-absent one as not found. + // The predicate comes from DocsService rather than being restated here — two + // copies of a security check drift, and this one decides which message a + // traversal attempt gets. + if (!DocsService.isValidDocName(name)) { return "Invalid document name: " + name; } - - if (!Files.isRegularFile(docFile)) { - // Try without adding .md in case the name already has it - docFile = docsDir.resolve(name).normalize(); - if (!docFile.startsWith(docsDir) || !Files.isRegularFile(docFile)) { - return "Document not found: " + name; - } - } - try { - return Files.readString(docFile); - } catch (IOException e) { - LOGGER.error("Failed to read doc: " + name, e); - return "Error reading document: " + e.getMessage(); - } + return "Document not found: " + name; } /** @@ -83,22 +69,10 @@ public String readDoc(@ResourceTemplateArg(name = "name") String name) { */ @Resource(uri = "eddi://docs/index", name = "eddi-docs-index", description = "List of all available EDDI documentation pages") public String listDocs() { - Path docsDir = Path.of(docsPath); - if (!Files.isDirectory(docsDir)) { - return "Docs directory not found: " + docsPath; + if (!docsService.isAvailable()) { + return "Docs directory not found: " + docsService.docsDirectory(); } - - var docs = new TreeSet(); - try (DirectoryStream stream = Files.newDirectoryStream(docsDir, "*.md")) { - for (Path entry : stream) { - String filename = entry.getFileName().toString(); - docs.add(filename.substring(0, filename.length() - 3)); // remove .md - } - } catch (IOException e) { - LOGGER.error("Failed to list docs", e); - return "Error listing documents: " + e.getMessage(); - } - + List docs = docsService.listDocs(); var sb = new StringBuilder(); sb.append("# EDDI Documentation Index\n\n"); sb.append("Available documents (").append(docs.size()).append("):\n\n"); diff --git a/src/main/java/ai/labs/eddi/engine/mcp/McpSetupTools.java b/src/main/java/ai/labs/eddi/engine/mcp/McpSetupTools.java index f7ae7d209b..ac8dab3d11 100644 --- a/src/main/java/ai/labs/eddi/engine/mcp/McpSetupTools.java +++ b/src/main/java/ai/labs/eddi/engine/mcp/McpSetupTools.java @@ -120,11 +120,18 @@ public String createApIAgent(@ToolArg(description = "Agent name (required)") Str @ToolArg(description = "Deploy after creation? (default: true)") Boolean deploy, @ToolArg(description = "Environment: 'production' (default) or 'test'") String environment, @ToolArg(description = "Base URL of the LLM provider itself, for local models " - + "(e.g. 'http://localhost:11434' for Ollama). Not the API's base URL — that is apiBaseUrl.") String llmBaseUrl) { + + "(e.g. 'http://localhost:11434' for Ollama). Not the API's base URL — that is apiBaseUrl.") String llmBaseUrl, + @ToolArg(description = "Comma-separated MCP server URLs whose tools the agent should also get, " + + "alongside the ones generated from the OpenAPI spec (optional).") String mcpServerUrls) { requireRole(identity, authEnabled, "eddi-editor"); try { + // hitlConfig is deliberately null and has no @ToolArg: this tool already + // provisions an agent with a caller-chosen endpoint filter, so also letting + // the caller choose the approval gate would turn it into a complete escape + // from whatever allow-list governs the agent doing the calling. Provisioning + // a gated agent goes through the REST setup-api endpoint. var request = new CreateApiAgentRequest(agentName, systemPrompt, openApiSpec, provider, model, apiKey, apiBaseUrl, apiAuth, endpoints, - enableQuickReplies, enableSentimentAnalysis, deploy, environment, llmBaseUrl); + enableQuickReplies, enableSentimentAnalysis, deploy, environment, llmBaseUrl, null, mcpServerUrls); var result = agentSetupService.createApiAgent(request); return jsonSerialization.serialize(result); } catch (AgentSetupException e) { diff --git a/src/main/java/ai/labs/eddi/engine/memory/model/PendingToolCallBatch.java b/src/main/java/ai/labs/eddi/engine/memory/model/PendingToolCallBatch.java index e170ff7301..e881554308 100644 --- a/src/main/java/ai/labs/eddi/engine/memory/model/PendingToolCallBatch.java +++ b/src/main/java/ai/labs/eddi/engine/memory/model/PendingToolCallBatch.java @@ -36,6 +36,7 @@ public static class PendingToolCall { private boolean argsTruncated; // true => call may NOT be executed on resume (auto-error result) private String argumentsRedacted; // SecretRedactionFilter'd, capped — the ONLY field approver surfaces read private String gateReason; // the matched pattern, e.g. "mcp:*" + private String matchedRule; // toolApprovals.rules[].match that tuned this call, or null public String getCallId() { return callId; @@ -92,6 +93,14 @@ public String getGateReason() { public void setGateReason(String gateReason) { this.gateReason = gateReason; } + + public String getMatchedRule() { + return matchedRule; + } + + public void setMatchedRule(String matchedRule) { + this.matchedRule = matchedRule; + } } private String pauseEpoch; // UUID per pause — journal key component @@ -123,6 +132,24 @@ public void setGateReason(String gateReason) { * it is config, not user data, and the generic read path does not need it. */ private ToolApprovalsConfig effectiveToolApprovals; + /** + * The single {@code toolApprovals.rules} entry governing THIS pause — resolved + * at gate time by {@code ToolApprovalRules}, where the gated calls' names, + * sources and endpoints are all still in hand. + *

+ * Resolved once and persisted rather than re-derived downstream: after the + * pause, {@code ConversationService} (timeout policy) and + * {@code Conversation.resolvePendingMessage} see only this batch, whose + * {@link PendingToolCall}s carry a name and source but no endpoint — so + * {@code http.post:/agentstore/agents} could not be re-matched there, and a + * silently different answer on the two sides of a pause is exactly the class of + * bug this field removes. + *

+ * Null when the config has no rules or none matched; readers then fall back to + * the {@link #effectiveToolApprovals} scalars, which is also what every batch + * persisted before this field existed does. + */ + private ToolApprovalsConfig.ApprovalRule effectiveRule; public String getPauseEpoch() { return pauseEpoch; @@ -243,4 +270,12 @@ public ToolApprovalsConfig getEffectiveToolApprovals() { public void setEffectiveToolApprovals(ToolApprovalsConfig effectiveToolApprovals) { this.effectiveToolApprovals = effectiveToolApprovals; } + + public ToolApprovalsConfig.ApprovalRule getEffectiveRule() { + return effectiveRule; + } + + public void setEffectiveRule(ToolApprovalsConfig.ApprovalRule effectiveRule) { + this.effectiveRule = effectiveRule; + } } diff --git a/src/main/java/ai/labs/eddi/engine/rest/RestDocs.java b/src/main/java/ai/labs/eddi/engine/rest/RestDocs.java new file mode 100644 index 0000000000..7b8606b1a0 --- /dev/null +++ b/src/main/java/ai/labs/eddi/engine/rest/RestDocs.java @@ -0,0 +1,47 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.engine.rest; + +import ai.labs.eddi.engine.api.IRestDocs; +import ai.labs.eddi.engine.docs.DocsService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.List; + +/** + * REST implementation of {@link IRestDocs}. Thin adapter over + * {@link DocsService}, which owns the filesystem access and the path-traversal + * guard. + */ +@ApplicationScoped +public class RestDocs implements IRestDocs { + + private final DocsService docsService; + + @Inject + public RestDocs(DocsService docsService) { + this.docsService = docsService; + } + + @Override + public List listDocs() { + return docsService.listDocs(); + } + + @Override + public Response readDoc(String name) { + String content = docsService.readDoc(name); + if (content == null) { + // A rejected name and an absent page are both 404 here, deliberately: the + // caller can do nothing different about either, and distinguishing them + // would echo an attacker-supplied traversal string back in the response. + return Response.status(Response.Status.NOT_FOUND).build(); + } + return Response.ok(content, MediaType.TEXT_PLAIN_TYPE).build(); + } +} diff --git a/src/main/java/ai/labs/eddi/engine/runtime/internal/Conversation.java b/src/main/java/ai/labs/eddi/engine/runtime/internal/Conversation.java index 3fac10df94..702281eb95 100644 --- a/src/main/java/ai/labs/eddi/engine/runtime/internal/Conversation.java +++ b/src/main/java/ai/labs/eddi/engine/runtime/internal/Conversation.java @@ -796,9 +796,16 @@ private void pauseConversation(ConversationPauseException e) { + "You will receive the result once a reviewer decides."; /** - * Resolves the end-user-facing pending message for a tool pause: - * {@code toolApprovals.pendingMessage} with {@code {toolNames}} substituted - * from the pending batch's gated call names, falling back to a generic default. + * Resolves the end-user-facing pending message for a tool pause: the governing + * {@code toolApprovals.rules} entry's {@code pendingMessage} if it set one, + * else {@code toolApprovals.pendingMessage}, with {@code {toolNames}} + * substituted from the pending batch's gated call names, falling back to a + * generic default. + *

+ * Must stay deterministic from the persisted batch alone — + * {@code dropPendingApprovalPlaceholder} recomputes this exact string on resume + * to remove it, so a value that varied between the two calls would leave the + * placeholder stranded in the resolved turn's output. */ private String resolvePendingMessage(IConversationMemory memory) { String template = null; @@ -810,7 +817,13 @@ private String resolvePendingMessage(IConversationMemory memory) { var cfg = batch != null && batch.getEffectiveToolApprovals() != null ? batch.getEffectiveToolApprovals() : memory.getAgentToolApprovalsConfig(); - if (cfg != null && !isNullOrEmpty(cfg.getPendingMessage())) { + var rule = batch != null ? batch.getEffectiveRule() : null; + // isBlank, not isNullOrEmpty (which is isEmpty-only): a whitespace-only + // pendingMessage would otherwise be used verbatim and render as an empty + // bubble instead of falling back to the scalar or the default. + if (rule != null && rule.getPendingMessage() != null && !rule.getPendingMessage().isBlank()) { + template = rule.getPendingMessage(); + } else if (cfg != null && !isNullOrEmpty(cfg.getPendingMessage())) { template = cfg.getPendingMessage(); } if (template == null) { diff --git a/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java b/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java index 5d5df829f6..a864b8737e 100644 --- a/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java +++ b/src/main/java/ai/labs/eddi/engine/setup/AgentSetupService.java @@ -18,6 +18,7 @@ import ai.labs.eddi.configs.agents.IRestAgentStore; import ai.labs.eddi.configs.agents.model.AgentConfiguration; import ai.labs.eddi.configs.descriptors.IRestDocumentDescriptorStore; +import ai.labs.eddi.configs.hitl.HitlConfigValidation; import ai.labs.eddi.configs.descriptors.model.DocumentDescriptor; import ai.labs.eddi.configs.apicalls.IRestApiCallsStore; import ai.labs.eddi.configs.mcpcalls.IRestMcpCallsStore; @@ -123,6 +124,7 @@ public SetupResult setupAgent(SetupAgentRequest request) throws AgentSetupExcept if (!isLocalLLM && (request.apiKey() == null || request.apiKey().isBlank())) { throw new AgentSetupException("API key is required for cloud LLM providers (anthropic, openai, gemini)"); } + validateMcpServerUrls(request.mcpServerUrls()); var params = resolveParamsValidated(request.provider(), request.model(), request.deploy(), request.environment()); boolean toolsEnabled = request.enableBuiltInTools() != null && request.enableBuiltInTools(); @@ -165,23 +167,7 @@ public SetupResult setupAgent(SetupAgentRequest request) throws AgentSetupExcept patchDescriptor(langchainId, langchainVersion, request.agentName()); // --- Step 4: Create MCP Calls Configurations (if MCP server URLs provided) --- - List mcpCallsLocations = null; - if (request.mcpServerUrls() != null && !request.mcpServerUrls().isBlank()) { - mcpCallsLocations = new ArrayList<>(); - for (String url : request.mcpServerUrls().split(",")) { - String trimmed = url.trim(); - if (trimmed.isEmpty()) - continue; - var mcpConfig = createMcpCallsConfig(trimmed); - Response mcpResponse = getRestStore(IRestMcpCallsStore.class).createMcpCalls(mcpConfig); - String mcpLocation = mcpResponse.getHeaderString("Location"); - String mcpId = extractIdFromLocation(mcpLocation); - int mcpVersion = extractVersionFromLocation(mcpLocation); - mcpCallsLocations.add(mcpLocation); - createdResources.put("mcpCallsLocation_" + mcpCallsLocations.size(), mcpLocation); - patchDescriptor(mcpId, mcpVersion, request.agentName()); - } - } + List mcpCallsLocations = createMcpCallsResources(request.mcpServerUrls(), request.agentName(), createdResources); // --- Step 5: Create Output Set (if intro message provided) --- String outputLocation = null; @@ -269,6 +255,18 @@ public SetupResult createApiAgent(CreateApiAgentRequest request) throws AgentSet if (request.llmBaseUrl() != null && !request.llmBaseUrl().isBlank() && !UrlValidationUtils.isValidHttpUrl(request.llmBaseUrl())) { throw new AgentSetupException("llmBaseUrl must be a valid http(s) URL"); } + // Validate the HITL config HERE, before a single resource exists. + // AgentStore.create validates it too, but only at step 7 — so an unusable + // approval pattern would surface after the apicalls, parser, behaviour, LLM + // and workflow had all been created, leaving every one of them orphaned. + // The caller gets the same actionable message either way; only the debris + // differs. + try { + HitlConfigValidation.validate(request.hitlConfig()); + } catch (IllegalArgumentException e) { + throw new AgentSetupException("Invalid hitlConfig: " + e.getMessage(), e); + } + validateMcpServerUrls(request.mcpServerUrls()); var params = resolveParamsValidated(request.provider(), request.model(), request.deploy(), request.environment()); var createdResources = new LinkedHashMap(); @@ -332,8 +330,12 @@ public SetupResult createApiAgent(CreateApiAgentRequest request) throws AgentSet createdResources.put("langchainLocation", langchainLocation); patchDescriptor(extractIdFromLocation(langchainLocation), extractVersionFromLocation(langchainLocation), request.agentName()); + // --- Step 5b: Create MCP Calls Configurations (if MCP URLs provided) --- + List mcpCallsLocations = createMcpCallsResources(request.mcpServerUrls(), request.agentName(), createdResources); + // --- Step 6: Create Workflow (with httpcalls in pipeline) --- - var workflowConfig = createWorkflowConfig(parserLocation, behaviorLocation, httpCallsLocations, null, langchainLocation, null); + var workflowConfig = createWorkflowConfig(parserLocation, behaviorLocation, httpCallsLocations, mcpCallsLocations, langchainLocation, + null); Response workflowResponse = getRestStore(IRestWorkflowStore.class).createWorkflow(workflowConfig); String workflowLocation = workflowResponse.getHeaderString("Location"); createdResources.put("packageLocation", workflowLocation); @@ -342,6 +344,11 @@ public SetupResult createApiAgent(CreateApiAgentRequest request) throws AgentSet // --- Step 7: Create Agent --- var agentConfig = new AgentConfiguration(); agentConfig.setWorkflows(List.of(URI.create(workflowLocation))); + // The gate is installed on v1 of the agent document. It has to be created + // WITH the agent rather than PUT afterwards: an update writes version + 1 and + // leaves the ungated v1 reachable by a redeploy, so a two-step provision would + // ship an agent that can be returned to an ungated state. + agentConfig.setHitlConfig(request.hitlConfig()); Response agentResponse = getRestStore(IRestAgentStore.class).createAgent(agentConfig); String agentLocation = agentResponse.getHeaderString("Location"); String agentId = extractIdFromLocation(agentLocation); @@ -371,6 +378,63 @@ public SetupResult createApiAgent(CreateApiAgentRequest request) throws AgentSet } } + /** + * Creates one McpCalls resource per comma-separated server URL, recording each + * location in {@code createdResources}. Returns null when no URLs were given, + * which is what {@code createWorkflowConfig} expects for "no MCP step". + *

+ * Shared by {@code setupAgent} and {@code createApiAgent} so an API agent can + * hold both the tools generated from its OpenAPI spec and an MCP server's — + * previously only the former, which made "REST plus MCP" unreachable through + * the wizard. + */ + /** + * Validates every MCP server URL before any of them is written. + *

+ * {@code McpCallsConfiguration.validate()} rejects a non-http(s) URL at save + * time, so without this the second bad URL in a list would abort the run with + * the first one's resource already persisted — and in {@code createApiAgent} + * with the apicalls, parser, behaviour and LLM resources persisted too. Same + * reasoning as the up-front {@code hitlConfig} check: a config error is cheap + * to detect before the first write, and the caller gets the same message with + * no debris. + */ + private void validateMcpServerUrls(String mcpServerUrls) throws AgentSetupException { + if (mcpServerUrls == null || mcpServerUrls.isBlank()) { + return; + } + for (String url : mcpServerUrls.split(",")) { + String trimmed = url.trim(); + if (trimmed.isEmpty()) + continue; + try { + createMcpCallsConfig(trimmed).validate(); + } catch (IllegalArgumentException e) { + throw new AgentSetupException("Invalid mcpServerUrls entry '" + trimmed + "': " + e.getMessage(), e); + } + } + } + + private List createMcpCallsResources(String mcpServerUrls, String agentName, Map createdResources) + throws Exception { + if (mcpServerUrls == null || mcpServerUrls.isBlank()) { + return null; + } + var locations = new ArrayList(); + for (String url : mcpServerUrls.split(",")) { + String trimmed = url.trim(); + if (trimmed.isEmpty()) + continue; + var mcpConfig = createMcpCallsConfig(trimmed); + Response mcpResponse = getRestStore(IRestMcpCallsStore.class).createMcpCalls(mcpConfig); + String mcpLocation = mcpResponse.getHeaderString("Location"); + locations.add(mcpLocation); + createdResources.put("mcpCallsLocation_" + locations.size(), mcpLocation); + patchDescriptor(extractIdFromLocation(mcpLocation), extractVersionFromLocation(mcpLocation), agentName); + } + return locations; + } + // ==================== Config Builders ==================== /** diff --git a/src/main/java/ai/labs/eddi/engine/setup/CreateApiAgentRequest.java b/src/main/java/ai/labs/eddi/engine/setup/CreateApiAgentRequest.java index 1ea917123e..63c1bbcade 100644 --- a/src/main/java/ai/labs/eddi/engine/setup/CreateApiAgentRequest.java +++ b/src/main/java/ai/labs/eddi/engine/setup/CreateApiAgentRequest.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.engine.setup; +import ai.labs.eddi.configs.agents.model.AgentConfiguration; import com.fasterxml.jackson.annotation.JsonProperty; /** @@ -23,5 +24,27 @@ public record CreateApiAgentRequest(@JsonProperty(required = true) String agentN * Appended last so the positional constructor used by McpSetupTools stays * unambiguous. */ - String llmBaseUrl) { + String llmBaseUrl, + /* + * HITL configuration for the created agent, including the tool-approval gate + * (hitlConfig.toolApprovals). Without this the wizard could only ever build a + * bare AgentConfiguration, so EVERY agent it created had hitlConfig == null and + * an inert gate — no caller could provision a gated agent through setup-api at + * all. + * + * Deliberately NOT exposed on the MCP create_api_agent tool: that tool + * provisions an agent with an arbitrary endpoint filter, so letting a model + * also choose the gate would make it a complete escape from any allow-list. + * McpSetupTools passes null. + * + * Appended last for the same positional-constructor reason as llmBaseUrl. + */ + AgentConfiguration.HitlConfig hitlConfig, + /* + * Comma-separated MCP server URLs, as on the setup_agent path. An API agent + * could previously only hold tools generated from the OpenAPI spec, so an agent + * needing both — REST endpoints the spec describes AND an MCP server's tools — + * was unreachable through this wizard and had to be assembled by hand. + */ + String mcpServerUrls) { } diff --git a/src/main/java/ai/labs/eddi/modules/llm/impl/AgentOrchestrator.java b/src/main/java/ai/labs/eddi/modules/llm/impl/AgentOrchestrator.java index a27f0cda4e..e08b860d8b 100644 --- a/src/main/java/ai/labs/eddi/modules/llm/impl/AgentOrchestrator.java +++ b/src/main/java/ai/labs/eddi/modules/llm/impl/AgentOrchestrator.java @@ -18,6 +18,7 @@ import ai.labs.eddi.engine.hitl.tools.IHitlToolJournalStore; import ai.labs.eddi.engine.hitl.tools.ToolApprovalGate; import ai.labs.eddi.engine.hitl.tools.ToolApprovalRequiredException; +import ai.labs.eddi.engine.hitl.tools.ToolApprovalRules; import ai.labs.eddi.engine.lifecycle.model.ToolCallDecision; import ai.labs.eddi.engine.memory.model.Data; import ai.labs.eddi.engine.memory.model.PendingToolCallBatch; @@ -1279,13 +1280,22 @@ private String runToolCallLoop(ChatModel chatModel, List initialMes throw new LifecycleException.LifecycleInterruptedException( "Tool-approval pause abandoned: executing thread was interrupted before commit"); } - // 2) snapshot + persist the pending batch, then abort the loop + // 2) resolve the per-tool friction rule (iteration 1). Done HERE, + // once, because this is the last place the gated calls' endpoints + // exist — the persisted batch keeps names and sources only, so an + // endpoint-addressed rule could never be re-matched downstream. + var ruleByCallId = ToolApprovalRules.matchByCallId(gateResult.gated(), toolSources, + setup.toolEndpoints(), effectiveToolApprovals); + var governingRule = ToolApprovalRules.governing(ruleByCallId.values()); + recordRuleMatches(ruleByCallId.values()); + // 3) snapshot + persist the pending batch, then abort the loop PendingToolCallBatch batch = buildPendingBatch(currentMessages, gateResult, task, memory, i, activatedToolNames(isLazy, activeSpecs), trace, pausesSoFar + 1, llmTaskIndex, - toolSources, effectiveToolApprovals, transcriptMaxBytes); + toolSources, effectiveToolApprovals, transcriptMaxBytes, ruleByCallId, governingRule); memory.setHitlPendingToolCalls(batch); incrementToolPauseCount(memory, pausesSoFar); - throw new ToolApprovalRequiredException(buildPauseReason(effectiveToolApprovals, gateResult), batch); + throw new ToolApprovalRequiredException( + buildPauseReason(effectiveToolApprovals, gateResult, governingRule), batch); } } @@ -1776,6 +1786,25 @@ private static int maxPausesPerTurn(ToolApprovalsConfig cfg) { return Math.max(1, Math.min(10, cfg.getMaxPausesPerTurn())); } + /** + * Counts which friction rules actually fire, tagged by the CONFIGURED pattern — + * never a URL, credential, tool argument or user id, so cardinality is bounded + * by the size of the agent's {@code rules} list. Deduplicated per pause: a + * batch where three calls match {@code http.delete:*} increments once, so the + * counter reads "how often did this rule govern a review", not "how many calls + * did the model happen to bundle". Best-effort, like the other guard metrics: a + * failure here must never break the LLM loop. + */ + private void recordRuleMatches(Collection matched) { + try { + matched.stream().filter(Objects::nonNull).map(ToolApprovalsConfig.ApprovalRule::getMatch) + .filter(Objects::nonNull).distinct() + .forEach(match -> Metrics.globalRegistry.counter("eddi.hitl.rule.matched", "match", match).increment()); + } catch (Exception e) { + LOGGER.debugf("hitl rule metric emit failed: %s", e.getMessage()); + } + } + /** Names activated in LAZY mode (for resume reactivation); empty otherwise. */ private static List activatedToolNames(boolean isLazy, List activeSpecs) { if (!isLazy) { @@ -1784,17 +1813,29 @@ private static List activatedToolNames(boolean isLazy, List a + ", " + b).orElse(""); - String template = cfg != null && cfg.getPauseReason() != null && !cfg.getPauseReason().isBlank() - ? cfg.getPauseReason() - : "Tool call requires approval: {toolNames}"; + String template = firstNonBlank(rule != null ? rule.getPauseReason() : null, + cfg != null ? cfg.getPauseReason() : null); + if (template == null) { + template = "Tool call requires approval: {toolNames}"; + } String reason = template.replace("{toolNames}", names); reason = SecretRedactionFilter.redact(reason); if (reason.length() > PAUSE_REASON_MAX_CHARS) { @@ -1816,6 +1857,21 @@ PendingToolCallBatch buildPendingBatch(List currentMessages, ToolAp pauseCountThisTurn, llmTaskIndex, toolSources, effectiveToolApprovals, DEFAULT_TRANSCRIPT_MAX_BYTES); } + /** + * Backward-compatible overload: no per-tool friction rules resolved (the batch + * falls back to the {@code toolApprovals} scalars, exactly as before iteration + * 1). + */ + PendingToolCallBatch buildPendingBatch(List currentMessages, ToolApprovalGate.GateResult gateResult, + LlmConfiguration.Task task, IConversationMemory memory, int iterationIndex, + List activatedToolNames, List> trace, + int pauseCountThisTurn, int llmTaskIndex, + Map toolSources, ToolApprovalsConfig effectiveToolApprovals, + int transcriptMaxBytes) { + return buildPendingBatch(currentMessages, gateResult, task, memory, iterationIndex, activatedToolNames, trace, + pauseCountThisTurn, llmTaskIndex, toolSources, effectiveToolApprovals, transcriptMaxBytes, Map.of(), null); + } + /** * Snapshots the interrupted tool-call batch into a durable * {@link PendingToolCallBatch}. All approver-facing strings are secret-redacted @@ -1826,13 +1882,22 @@ PendingToolCallBatch buildPendingBatch(List currentMessages, ToolAp * — resolved by {@code LlmTask} from * {@code eddi.hitl.tool.transcript-max-bytes} (default * {@link PendingToolCallBatch#TRANSCRIPT_MAX_BYTES_DEFAULT}). + * @param ruleByCallId + * per gated call, the {@code toolApprovals.rules} entry tuning it — + * recorded for approver visibility only + * @param governingRule + * the single rule governing this pause (strictest of the above), or + * null; persisted so the post-pause resolvers read the same answer + * this gate computed */ PendingToolCallBatch buildPendingBatch(List currentMessages, ToolApprovalGate.GateResult gateResult, LlmConfiguration.Task task, IConversationMemory memory, int iterationIndex, List activatedToolNames, List> trace, int pauseCountThisTurn, int llmTaskIndex, Map toolSources, ToolApprovalsConfig effectiveToolApprovals, - int transcriptMaxBytes) { + int transcriptMaxBytes, + Map ruleByCallId, + ToolApprovalsConfig.ApprovalRule governingRule) { PendingToolCallBatch batch = new PendingToolCallBatch(); batch.setPauseEpoch(UUID.randomUUID().toString()); batch.setLlmTaskId(task.getId()); @@ -1843,6 +1908,7 @@ PendingToolCallBatch buildPendingBatch(List currentMessages, ToolAp // Conversation.resolvePendingMessage read the task-scoped config that produced // the pause instead of re-deriving from the agent level only. batch.setEffectiveToolApprovals(effectiveToolApprovals); + batch.setEffectiveRule(governingRule); // workflowId is informational; the authoritative pause bookmark carries the // paused workflow id (set by the LifecycleManager → Conversation pause commit). batch.setIterationIndex(iterationIndex); @@ -1881,6 +1947,11 @@ PendingToolCallBatch buildPendingBatch(List currentMessages, ToolAp // gateReason: the matched pattern (by call id), fall back to bare name. String reason = req.id() != null ? gateResult.gateReasonByCallId().get(req.id()) : null; call.setGateReason(reason); + // matchedRule: which friction rule tuned THIS call, which is not necessarily + // the one governing the pause — an approver seeing a five-minute auto-reject + // on a batch should be able to tell which call brought it. + var callRule = req.id() != null ? ruleByCallId.get(req.id()) : null; + call.setMatchedRule(callRule != null ? callRule.getMatch() : null); calls.add(call); } batch.setCalls(calls); diff --git a/src/main/java/ai/labs/eddi/utils/RestUtilities.java b/src/main/java/ai/labs/eddi/utils/RestUtilities.java index 2f1e0fdc8c..f08bfd6866 100644 --- a/src/main/java/ai/labs/eddi/utils/RestUtilities.java +++ b/src/main/java/ai/labs/eddi/utils/RestUtilities.java @@ -152,6 +152,43 @@ private static boolean isValidId(String s) { return true; } + /** + * The URI with its query string removed — but only when that query actually + * carries a usable {@code version}. Returns {@code null} when the URI has no + * query, no {@code version} parameter, or a {@code version} that is not a + * non-negative integer. + *

+ * Exists for the {@code updateResourceUri} endpoints on the agent and workflow + * stores, which match stored references by "everything before the query" and + * then replace them with the supplied URI. Testing only for the presence of a + * {@code ?} is not enough there: {@code .../workflows/{id}?other=2} would match + * the stored {@code .../workflows/{id}?version=1} and replace it with a + * versionless reference, quietly corrupting the pinned version an + * agent resolves at runtime. + */ + public static String pathWithoutVersionQuery(URI uri) { + if (uri == null) { + return null; + } + String uriString = uri.toString(); + int queryStart = uriString.lastIndexOf('?'); + if (queryStart < 0) { + return null; + } + String version = getQueryMap(uriString.substring(queryStart + 1)).get("version"); + if (version == null || version.isBlank()) { + return null; + } + try { + if (Integer.parseInt(version.trim()) < 0) { + return null; + } + } catch (NumberFormatException e) { + return null; + } + return uriString.substring(0, queryStart); + } + private static Map getQueryMap(String query) { String[] params = query.split("&"); Map map = new HashMap<>(); diff --git a/src/test/java/ai/labs/eddi/configs/agents/rest/RestAgentStoreExpandedTest.java b/src/test/java/ai/labs/eddi/configs/agents/rest/RestAgentStoreExpandedTest.java index 308881eea2..5817a14cfa 100644 --- a/src/test/java/ai/labs/eddi/configs/agents/rest/RestAgentStoreExpandedTest.java +++ b/src/test/java/ai/labs/eddi/configs/agents/rest/RestAgentStoreExpandedTest.java @@ -256,6 +256,84 @@ void noMatch() throws Exception { assertEquals(400, response.getStatus()); } + + @Test + @DisplayName("preserves hitlConfig — the approval gate survives a re-point") + void preservesHitlConfig() throws Exception { + // This endpoint is the ONLY way an approval-gated agent can be re-pointed at + // a new workflow version, because the full PUT /agentstore/agents/{id} is + // permanently unbound (the gate lives in that document, so one approved write + // there would remove all subsequent gating). It is safe to bind only if it + // provably cannot drop the gate: the caller cannot SUPPLY a hitlConfig — the + // body is a text/plain URI — and the implementation must PRESERVE the stored + // one. The signature guarantees the first; this asserts the second. + var config = new AgentConfiguration(); + config.setWorkflows(new ArrayList<>(List.of( + URI.create("eddi://ai.labs.workflow/workflowstore/workflows/" + PKG_ID + "?version=1")))); + var hitl = new AgentConfiguration.HitlConfig(); + var toolApprovals = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig(); + toolApprovals.setRequireApproval(List.of("http.post:*", "http.put:*", "http.delete:*")); + toolApprovals.setExempt(List.of("http.get:*")); + hitl.setToolApprovals(toolApprovals); + config.setHitlConfig(hitl); + + when(agentStore.read(AGENT_ID, 1)).thenReturn(config); + when(agentStore.update(eq(AGENT_ID), eq(1), any())).thenReturn(2); + + URI newUri = URI.create("eddi://ai.labs.workflow/workflowstore/workflows/" + PKG_ID + "?version=2"); + assertEquals(200, sut.updateResourceInAgent(AGENT_ID, 1, newUri).getStatus()); + + var captor = org.mockito.ArgumentCaptor.forClass(AgentConfiguration.class); + verify(agentStore).update(eq(AGENT_ID), eq(1), captor.capture()); + var written = captor.getValue(); + assertNotNull(written.getHitlConfig(), "the gate must survive a re-point"); + assertEquals(List.of("http.post:*", "http.put:*", "http.delete:*"), + written.getHitlConfig().getToolApprovals().getRequireApproval()); + assertEquals(List.of("http.get:*"), written.getHitlConfig().getToolApprovals().getExempt()); + // ...and ONLY the URI list changed. + assertEquals(List.of(newUri), written.getWorkflows()); + } + + @Test + @DisplayName("a URI without ?version is a 400, not a 500") + void uriWithoutVersionIsRejected() throws Exception { + // resourceURI.toString().substring(0, lastIndexOf("?")) throws + // StringIndexOutOfBoundsException when there is no '?', turning a caller's + // malformed input into a 500. That matters here more than usual: this + // endpoint is on the re-point cascade an approval-gated operator has to walk + // to finish editing an agent, so its failure mode is one an LLM will hit and + // has to be able to act on. + var config = new AgentConfiguration(); + config.setWorkflows(new ArrayList<>(List.of( + URI.create("eddi://ai.labs.workflow/workflowstore/workflows/" + PKG_ID + "?version=1")))); + lenient().when(agentStore.read(AGENT_ID, 1)).thenReturn(config); + + URI noVersion = URI.create("eddi://ai.labs.workflow/workflowstore/workflows/" + PKG_ID); + Response response = sut.updateResourceInAgent(AGENT_ID, 1, noVersion); + + assertEquals(400, response.getStatus()); + verify(agentStore, never()).update(eq(AGENT_ID), eq(1), any()); + } + + @Test + @DisplayName("a query without a version parameter cannot unpin the stored reference") + void queryWithoutVersionParameterIsRejected() throws Exception { + // Guarding on the presence of a '?' alone is not enough: the stored reference + // is matched by everything BEFORE the query and then replaced by the supplied + // URI, so '?other=2' would match the versioned reference and overwrite it + // with a versionless one — silently unpinning the workflow the agent resolves + // at runtime. + var config = new AgentConfiguration(); + config.setWorkflows(new ArrayList<>(List.of( + URI.create("eddi://ai.labs.workflow/workflowstore/workflows/" + PKG_ID + "?version=1")))); + lenient().when(agentStore.read(AGENT_ID, 1)).thenReturn(config); + + for (String query : List.of("?other=2", "?version=", "?version=abc", "?versionx=2", "?")) { + URI bad = URI.create("eddi://ai.labs.workflow/workflowstore/workflows/" + PKG_ID + query); + assertEquals(400, sut.updateResourceInAgent(AGENT_ID, 1, bad).getStatus(), "must refuse: " + query); + } + verify(agentStore, never()).update(eq(AGENT_ID), eq(1), any()); + } } // ─── duplicateAgent ──────────────────────────────────────────────────────── diff --git a/src/test/java/ai/labs/eddi/configs/hitl/ToolApprovalRulesValidationTest.java b/src/test/java/ai/labs/eddi/configs/hitl/ToolApprovalRulesValidationTest.java new file mode 100644 index 0000000000..2963245314 --- /dev/null +++ b/src/test/java/ai/labs/eddi/configs/hitl/ToolApprovalRulesValidationTest.java @@ -0,0 +1,180 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.configs.hitl; + +import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig; +import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig.ApprovalRule; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Save-time validation of {@code toolApprovals.rules}. A rule that cannot match + * costs the designer the friction they thought they configured, and — like an + * unmatchable {@code requireApproval} pattern — the failure is invisible from + * the config, so it is refused rather than saved. + */ +@DisplayName("toolApprovals.rules validation") +class ToolApprovalRulesValidationTest { + + private static ToolApprovalsConfig withRules(ApprovalRule... rules) { + var cfg = new ToolApprovalsConfig(); + cfg.setRequireApproval(List.of("http.post:*")); + cfg.setRules(Arrays.asList(rules)); + return cfg; + } + + private static ApprovalRule rule(String match) { + var r = new ApprovalRule(); + r.setMatch(match); + return r; + } + + private static String messageOf(Executable body) { + return assertThrows(IllegalArgumentException.class, body).getMessage(); + } + + @Test + @DisplayName("a valid endpoint-addressed rule saves") + void validRuleSaves() { + var r = rule("http.post:/agentstore/agents"); + r.setTimeoutPolicy(HitlTimeoutPolicy.WAIT_INDEFINITELY); + r.setPauseReason("Creating a new agent — review the whole config"); + assertDoesNotThrow(() -> HitlConfigValidation.validateToolApprovals(withRules(r), "hitlConfig.toolApprovals")); + } + + @Test + @DisplayName("a rule whose prefix can never match an endpoint is refused") + void unmatchableRuleIsRefused() { + // 'mcp' tools carry no endpoint, so 'mcp:/agentstore/agents' matches nothing — + // the same defect ToolApprovalPatterns already refuses in requireApproval. + String message = messageOf( + () -> HitlConfigValidation.validateToolApprovals(withRules(rule("mcp:/agentstore/agents")), "cfg.toolApprovals")); + assertTrue(message.startsWith("cfg.toolApprovals.rules[0].match:"), message); + assertTrue(message.contains("matches nothing"), message); + } + + @Test + @DisplayName("a blank match is refused") + void blankMatchIsRefused() { + assertTrue(messageOf(() -> HitlConfigValidation.validateToolApprovals(withRules(rule(" ")), "cfg.toolApprovals")) + .contains("must not be blank")); + } + + @Test + @DisplayName("two rules with the same match are refused — only one could ever apply") + void duplicateMatchIsRefused() { + assertTrue(messageOf(() -> HitlConfigValidation.validateToolApprovals( + withRules(rule("http.post:*"), rule("http.post:*")), "cfg.toolApprovals")).contains("duplicate rule match")); + } + + @Test + @DisplayName("a rule whose match is also an exempt pattern is refused — it could never apply") + void ruleMatchingAnExemptPatternIsRefused() { + // An exempt call is never gated, and a rule only tunes a gated call — so this + // rule is dead config that reads as if it were doing something. + var cfg = new ToolApprovalsConfig(); + cfg.setRequireApproval(List.of("http.post:*")); + cfg.setExempt(List.of("http.get:*")); + cfg.setRules(List.of(rule("http.get:*"))); + + assertTrue(messageOf(() -> HitlConfigValidation.validateToolApprovals(cfg, "cfg.toolApprovals")) + .contains("can never apply")); + } + + @Test + @DisplayName("a rule merely OVERLAPPING an exempt pattern still saves") + void ruleOverlappingAnExemptPatternSaves() { + // Only exact equality is provably dead. A broader rule can still cover gated + // calls, and refusing it would be a false positive. + var cfg = new ToolApprovalsConfig(); + cfg.setRequireApproval(List.of("http.post:*")); + cfg.setExempt(List.of("http.get:*")); + cfg.setRules(List.of(rule("http.*:*"))); + + assertDoesNotThrow(() -> HitlConfigValidation.validateToolApprovals(cfg, "cfg.toolApprovals")); + } + + @Test + @DisplayName("rules without requireApproval are refused — a rule never gates") + void rulesWithoutRequireApprovalAreRefused() { + var cfg = new ToolApprovalsConfig(); + cfg.setRules(List.of(rule("http.post:*"))); + assertTrue(messageOf(() -> HitlConfigValidation.validateToolApprovals(cfg, "cfg.toolApprovals")) + .contains("they never gate one")); + } + + @Test + @DisplayName("a finite rule policy with no duration anywhere is refused — it would never fire") + void finitePolicyWithoutAnyDurationIsRefused() { + var r = rule("http.post:*"); + r.setTimeoutPolicy(HitlTimeoutPolicy.AUTO_REJECT); + String message = messageOf(() -> HitlConfigValidation.validateToolApprovals(withRules(r), "cfg.toolApprovals")); + assertTrue(message.contains("cfg.toolApprovals.rules[0].approvalTimeout"), message); + } + + @Test + @DisplayName("a finite rule policy may inherit the enclosing approvalTimeout") + void finitePolicyInheritsEnclosingDuration() { + var r = rule("http.post:*"); + r.setTimeoutPolicy(HitlTimeoutPolicy.AUTO_REJECT); + var cfg = withRules(r); + cfg.setApprovalTimeout("PT30M"); + assertDoesNotThrow(() -> HitlConfigValidation.validateToolApprovals(cfg, "cfg.toolApprovals")); + } + + @Test + @DisplayName("a malformed rule duration is refused") + void malformedRuleDurationIsRefused() { + var r = rule("http.post:*"); + r.setApprovalTimeout("5 minutes"); + assertTrue(messageOf(() -> HitlConfigValidation.validateToolApprovals(withRules(r), "cfg.toolApprovals")) + .contains("not a valid ISO-8601 duration")); + } + + @Test + @DisplayName("over-long rule messages are refused, with the rule index named") + void overLongRuleMessagesAreRefused() { + var r = rule("http.post:*"); + r.setPauseReason("x".repeat(HitlConfigValidation.MAX_PAUSE_REASON_LENGTH + 1)); + assertTrue(messageOf(() -> HitlConfigValidation.validateToolApprovals(withRules(r), "cfg.toolApprovals")) + .contains("cfg.toolApprovals.rules[0].pauseReason")); + + var r2 = rule("http.post:*"); + r2.setPendingMessage("x".repeat(HitlConfigValidation.MAX_PAUSE_REASON_LENGTH + 1)); + assertTrue(messageOf(() -> HitlConfigValidation.validateToolApprovals(withRules(r2), "cfg.toolApprovals")) + .contains("cfg.toolApprovals.rules[0].pendingMessage")); + } + + @Test + @DisplayName("a null rule entry is refused rather than NPEing at runtime") + void nullRuleEntryIsRefused() { + var cfg = new ToolApprovalsConfig(); + cfg.setRequireApproval(List.of("http.post:*")); + var rules = new ArrayList(); + rules.add(null); + cfg.setRules(rules); + assertTrue(messageOf(() -> HitlConfigValidation.validateToolApprovals(cfg, "cfg.toolApprovals")) + .contains("must not be null")); + } + + @Test + @DisplayName("absent rules leave every existing config validating exactly as before") + void absentRulesAreANoOp() { + var cfg = new ToolApprovalsConfig(); + cfg.setRequireApproval(List.of("http.post:*")); + assertDoesNotThrow(() -> HitlConfigValidation.validateToolApprovals(cfg, "cfg.toolApprovals")); + cfg.setRules(List.of()); + assertDoesNotThrow(() -> HitlConfigValidation.validateToolApprovals(cfg, "cfg.toolApprovals")); + } +} diff --git a/src/test/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStoreCrudTest.java b/src/test/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStoreCrudTest.java index 31ac3f73e2..b7d703bf63 100644 --- a/src/test/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStoreCrudTest.java +++ b/src/test/java/ai/labs/eddi/configs/workflows/rest/RestWorkflowStoreCrudTest.java @@ -205,6 +205,46 @@ void updatesStepConfigUri() throws Exception { assertEquals(200, response.getStatus()); } + @Test + @DisplayName("a URI without ?version is a 400, not a 500") + void uriWithoutVersionIsRejected() throws Exception { + // Same defect as the agent-store variant: substring(0, lastIndexOf('?')) + // throws when there is no '?'. Both sit on the re-point cascade an + // approval-gated agent must walk, so a caller has to get an actionable 400. + var config = new WorkflowConfiguration(); + var step = new WorkflowStep(); + step.setType(URI.create("eddi://ai.labs.rules")); + step.setConfig(new HashMap<>(Map.of("uri", "eddi://ai.labs.rules/rulestore/rulesets/111111111111111111111111?version=1"))); + config.getWorkflowSteps().add(step); + lenient().when(workflowStore.read(WORKFLOW_ID, 1)).thenReturn(config); + + URI noVersion = URI.create("eddi://ai.labs.rules/rulestore/rulesets/111111111111111111111111"); + Response response = sut.updateResourceInWorkflow(WORKFLOW_ID, 1, noVersion); + + assertEquals(400, response.getStatus()); + verify(workflowStore, never()).update(eq(WORKFLOW_ID), eq(1), any()); + } + + @Test + @DisplayName("a query without a version parameter cannot unpin the stored reference") + void queryWithoutVersionParameterIsRejected() throws Exception { + // Same defect as the agent-store variant: '?other=2' satisfies a bare + // '?'-presence check, matches the stored versioned reference, and replaces it + // with a versionless one. + var config = new WorkflowConfiguration(); + var step = new WorkflowStep(); + step.setType(URI.create("eddi://ai.labs.rules")); + step.setConfig(new HashMap<>(Map.of("uri", "eddi://ai.labs.rules/rulestore/rulesets/111111111111111111111111?version=1"))); + config.getWorkflowSteps().add(step); + lenient().when(workflowStore.read(WORKFLOW_ID, 1)).thenReturn(config); + + for (String query : List.of("?other=2", "?version=", "?version=abc", "?versionx=2", "?")) { + URI bad = URI.create("eddi://ai.labs.rules/rulestore/rulesets/111111111111111111111111" + query); + assertEquals(400, sut.updateResourceInWorkflow(WORKFLOW_ID, 1, bad).getStatus(), "must refuse: " + query); + } + verify(workflowStore, never()).update(eq(WORKFLOW_ID), eq(1), any()); + } + @Test @DisplayName("should update resource URI in extension element config") void updatesExtensionConfigUri() throws Exception { diff --git a/src/test/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalRulesTest.java b/src/test/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalRulesTest.java new file mode 100644 index 0000000000..0126f67f95 --- /dev/null +++ b/src/test/java/ai/labs/eddi/engine/hitl/tools/ToolApprovalRulesTest.java @@ -0,0 +1,214 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.engine.hitl.tools; + +import ai.labs.eddi.configs.hitl.HitlTimeoutPolicy; +import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig; +import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig.ApprovalRule; +import dev.langchain4j.agent.tool.ToolExecutionRequest; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Per-endpoint approval friction: {@code toolApprovals.rules}. The properties + * under test are that a rule reaches the call the designer aimed it at, that + * the most specific one wins regardless of list order, that a batch is governed + * by its strictest rule, and — the load-bearing one — that a rule can never + * change whether a call is gated. + */ +class ToolApprovalRulesTest { + + private static final Map SOURCES = Map.of( + "listAgents", "http", "createAgent", "http", "deployAgent", "http", "deleteAgent", "http", "readMemory", "memory"); + private static final Map ENDPOINTS = Map.of( + "listAgents", "get:/agentstore/agents/descriptors", + "createAgent", "post:/agentstore/agents", + "deployAgent", "post:/administration/{environment}/deploy/{agentId}", + "deleteAgent", "delete:/agentstore/agents/{id}"); + + private static ToolExecutionRequest req(String id, String name) { + return ToolExecutionRequest.builder().id(id).name(name).arguments("{}").build(); + } + + private static ApprovalRule rule(String match, HitlTimeoutPolicy policy, String timeout) { + var r = new ApprovalRule(); + r.setMatch(match); + r.setTimeoutPolicy(policy); + r.setApprovalTimeout(timeout); + return r; + } + + private static ToolApprovalsConfig cfg(ApprovalRule... rules) { + var c = new ToolApprovalsConfig(); + c.setRequireApproval(List.of("http.post:*", "http.put:*", "http.patch:*", "http.delete:*")); + c.setExempt(List.of("http.get:*")); + c.setRules(List.of(rules)); + return c; + } + + // ==================== matching ==================== + + @Test + void endpointAddressedRule_reachesTheGeneratedToolItNames() { + // The whole point of the feature: "creating an agent" and "deploying one" + // must be able to differ, and the tool names (operationId-derived) say + // nothing, so the rule has to address the endpoint. + var create = rule("http.post:/agentstore/agents", HitlTimeoutPolicy.WAIT_INDEFINITELY, null); + var deploy = rule("http.post:/administration/{environment}/deploy/{agentId}", HitlTimeoutPolicy.AUTO_REJECT, "PT5M"); + + var matched = ToolApprovalRules.matchByCallId(List.of(req("1", "createAgent")), SOURCES, ENDPOINTS, cfg(create, deploy)); + + assertEquals(1, matched.size()); + assertEquals("http.post:/agentstore/agents", matched.get("1").getMatch()); + } + + @Test + void ruleAddressesBareNameAndSourceQualifiedName_notOnlyEndpoints() { + var byName = rule("readMemory", HitlTimeoutPolicy.AUTO_REJECT, "PT1M"); + var bySource = rule("memory:*", HitlTimeoutPolicy.ABORT, "PT1M"); + + assertEquals("readMemory", + ToolApprovalRules.matchByCallId(List.of(req("1", "readMemory")), SOURCES, ENDPOINTS, cfg(byName)).get("1").getMatch()); + assertEquals("memory:*", + ToolApprovalRules.matchByCallId(List.of(req("1", "readMemory")), SOURCES, ENDPOINTS, cfg(bySource)).get("1").getMatch()); + } + + @Test + void mostSpecificRuleWins_regardlessOfListOrder() { + var broad = rule("http.post:*", HitlTimeoutPolicy.AUTO_REJECT, "PT5M"); + var narrow = rule("http.post:/agentstore/agents", HitlTimeoutPolicy.WAIT_INDEFINITELY, null); + var call = List.of(req("1", "createAgent")); + + // Listed broad-first and narrow-first: the narrow rule governs either way, so + // a designer cannot lose their intended friction to JSON array order. + assertEquals("http.post:/agentstore/agents", + ToolApprovalRules.matchByCallId(call, SOURCES, ENDPOINTS, cfg(broad, narrow)).get("1").getMatch()); + assertEquals("http.post:/agentstore/agents", + ToolApprovalRules.matchByCallId(call, SOURCES, ENDPOINTS, cfg(narrow, broad)).get("1").getMatch()); + } + + @Test + void aCallMatchingNoRule_isAbsentAndFallsBackToTheScalars() { + var matched = ToolApprovalRules.matchByCallId(List.of(req("1", "createAgent")), SOURCES, ENDPOINTS, + cfg(rule("http.delete:*", HitlTimeoutPolicy.WAIT_INDEFINITELY, null))); + + assertTrue(matched.isEmpty()); + assertNull(ToolApprovalRules.governing(matched.values())); + } + + @Test + void absentRulesList_resolvesToNothing() { + var noRules = new ToolApprovalsConfig(); + noRules.setRequireApproval(List.of("http.post:*")); + + assertTrue(ToolApprovalRules.matchByCallId(List.of(req("1", "createAgent")), SOURCES, ENDPOINTS, noRules).isEmpty()); + assertNull(ToolApprovalRules.governing(List.of(req("1", "createAgent")), SOURCES, ENDPOINTS, noRules)); + assertNull(ToolApprovalRules.governing(List.of(req("1", "createAgent")), SOURCES, ENDPOINTS, null)); + } + + // ==================== batch reduction ==================== + + @Test + void strictestRuleGovernsTheBatch_soALenientCallCannotSoftenAStrictOne() { + // A model can bundle a delete with a deploy; they pause together under ONE + // policy. If the lenient one won, "delete waits for a human" would silently + // become "delete auto-rejects in five minutes" — or worse, auto-approves. + var deploy = rule("http.post:/administration/{environment}/deploy/{agentId}", HitlTimeoutPolicy.AUTO_REJECT, "PT5M"); + var delete = rule("http.delete:*", HitlTimeoutPolicy.WAIT_INDEFINITELY, null); + var batch = List.of(req("1", "deployAgent"), req("2", "deleteAgent")); + + var governing = ToolApprovalRules.governing(batch, SOURCES, ENDPOINTS, cfg(deploy, delete)); + + assertNotNull(governing); + assertEquals("http.delete:*", governing.getMatch()); + assertEquals(HitlTimeoutPolicy.WAIT_INDEFINITELY, governing.getTimeoutPolicy()); + } + + @Test + void autoApproveNeverWinsABatch_evenWhenItIsTheMoreSpecificRule() { + // Specificity decides between equals; it must not promote the one policy that + // can execute a write with nobody watching. + var autoApprove = rule("http.post:/agentstore/agents", HitlTimeoutPolicy.AUTO_APPROVE, "PT1M"); + var broadWait = rule("http.post:*", HitlTimeoutPolicy.WAIT_INDEFINITELY, null); + var batch = List.of(req("1", "createAgent"), req("2", "deployAgent")); + + var governing = ToolApprovalRules.governing(batch, SOURCES, ENDPOINTS, cfg(autoApprove, broadWait)); + + assertEquals(HitlTimeoutPolicy.WAIT_INDEFINITELY, governing.getTimeoutPolicy()); + } + + @Test + void aRuleStatingNoPolicy_yieldsToOneThatDoes() { + var messageOnly = new ApprovalRule(); + messageOnly.setMatch("http.post:/agentstore/agents"); + messageOnly.setPauseReason("Creating a new agent — review the whole config"); + var deploy = rule("http.post:/administration/{environment}/deploy/{agentId}", HitlTimeoutPolicy.AUTO_REJECT, "PT5M"); + + var governing = ToolApprovalRules.governing(List.of(req("1", "createAgent"), req("2", "deployAgent")), + SOURCES, ENDPOINTS, cfg(messageOnly, deploy)); + + assertEquals(HitlTimeoutPolicy.AUTO_REJECT, governing.getTimeoutPolicy()); + } + + @Test + void withNoPolicyAnywhere_theMostSpecificRuleStillSuppliesTheMessages() { + var narrow = new ApprovalRule(); + narrow.setMatch("http.post:/agentstore/agents"); + narrow.setPauseReason("narrow"); + var broad = new ApprovalRule(); + broad.setMatch("http.post:*"); + broad.setPauseReason("broad"); + + var governing = ToolApprovalRules.governing(List.of(req("1", "createAgent")), SOURCES, ENDPOINTS, cfg(broad, narrow)); + + assertEquals("narrow", governing.getPauseReason()); + } + + // ==================== the invariant ==================== + + @Test + void rulesNeverGateAnUngatedCall_norUngateAGatedOne() { + // Rules tune friction only. If a rule could gate, a config would grant + // capability by adding an entry; if it could ungate, one entry would remove + // the review the whole design rests on. Assert against the gate itself. + var config = cfg( + rule("http.get:/agentstore/agents/descriptors", HitlTimeoutPolicy.WAIT_INDEFINITELY, null), + rule("http.post:/agentstore/agents", HitlTimeoutPolicy.AUTO_APPROVE, "PT1M")); + var batch = List.of(req("1", "listAgents"), req("2", "createAgent")); + + var result = new ToolApprovalGate().classify(batch, SOURCES, ENDPOINTS, config, Set.of()); + + // The exempt GET stays allowed although a rule names it; the required POST + // stays gated although its rule is the most permissive policy there is. + assertEquals(List.of("listAgents"), result.allowed().stream().map(ToolExecutionRequest::name).toList()); + assertEquals(List.of("createAgent"), result.gated().stream().map(ToolExecutionRequest::name).toList()); + } + + @Test + void aCallWithNoId_isSkippedRatherThanCollidingInTheMap() { + var matched = ToolApprovalRules.matchByCallId( + List.of(ToolExecutionRequest.builder().name("createAgent").arguments("{}").build()), + SOURCES, ENDPOINTS, cfg(rule("http.post:*", HitlTimeoutPolicy.WAIT_INDEFINITELY, null))); + + assertTrue(matched.isEmpty()); + } + + @Test + void aMalformedCallWithNoName_matchesNothing() { + var matched = ToolApprovalRules.matchByCallId( + List.of(ToolExecutionRequest.builder().id("1").arguments("{}").build()), + SOURCES, ENDPOINTS, cfg(rule("*", HitlTimeoutPolicy.WAIT_INDEFINITELY, null))); + + assertTrue(matched.isEmpty()); + } +} diff --git a/src/test/java/ai/labs/eddi/engine/internal/ConversationServiceToolTimeoutTest.java b/src/test/java/ai/labs/eddi/engine/internal/ConversationServiceToolTimeoutTest.java index 80816d6eda..3ad3be79da 100644 --- a/src/test/java/ai/labs/eddi/engine/internal/ConversationServiceToolTimeoutTest.java +++ b/src/test/java/ai/labs/eddi/engine/internal/ConversationServiceToolTimeoutTest.java @@ -48,6 +48,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Date; @@ -119,7 +120,15 @@ class ConversationServiceToolTimeoutTest { * resolvers read the batch config instead of the agent-level default. Null * exercises the legacy/backward-compat path (agent-level resolution). */ - private ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig batchEffectiveToolApprovals; + private ToolApprovalsConfig batchEffectiveToolApprovals; + + /** + * When set, the helper stamps this governing per-tool friction rule onto both + * batches — the shape {@code AgentOrchestrator} persists after resolving + * {@code toolApprovals.rules} at gate time. Null exercises the + * no-rules/legacy-batch path. + */ + private ToolApprovalsConfig.ApprovalRule batchEffectiveRule; @BeforeEach @SuppressWarnings("unchecked") @@ -494,6 +503,113 @@ void batchEffectiveMaxAutoApprovalsHonored() throws Exception { // which owns that resolution). } + // ========================================================================= + // Iteration 1 — the governing toolApprovals.rules entry outranks the scalars + // ========================================================================= + + @Nested + @DisplayName("per-tool friction rule drives the tool-pause timeout policy") + class GoverningRule { + + @Test + @DisplayName("the rule's policy + duration beat the toolApprovals scalars") + void ruleOverridesToolApprovalsScalars() throws Exception { + // "Deploying an agent" wants a short fuse even though the agent's blanket + // tool policy is wait-forever — the whole reason rules exist. + var hitl = new AgentConfiguration.HitlConfig(); + var toolApprovals = new ToolApprovalsConfig(); + toolApprovals.setTimeoutPolicy(HitlTimeoutPolicy.WAIT_INDEFINITELY); + hitl.setToolApprovals(toolApprovals); + batchEffectiveToolApprovals = toolApprovals; + + var rule = new ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("http.post:/administration/{environment}/deploy/{agentId}"); + rule.setTimeoutPolicy(HitlTimeoutPolicy.AUTO_REJECT); + rule.setApprovalTimeout("PT5M"); + batchEffectiveRule = rule; + + resumeWithToolRePause(hitl, FINGERPRINT, null); + + ArgumentCaptor cap = ArgumentCaptor.forClass(ScheduleConfiguration.class); + verify(scheduleStore).createSchedule(cap.capture()); + assertEquals("AUTO_REJECT", cap.getValue().getMetadata().get("policy"), + "the governing rule must outrank the toolApprovals scalar policy"); + } + + @Test + @DisplayName("a rule stating only a policy inherits the enclosing duration") + void ruleWithoutDurationInheritsEnclosingTimeout() throws Exception { + // Otherwise a rule that omits approvalTimeout would arm a policy with no + // clock, i.e. silently behave as wait-forever. + var hitl = new AgentConfiguration.HitlConfig(); + var toolApprovals = new ToolApprovalsConfig(); + toolApprovals.setApprovalTimeout("PT30S"); + hitl.setToolApprovals(toolApprovals); + batchEffectiveToolApprovals = toolApprovals; + + var rule = new ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("http.delete:*"); + rule.setTimeoutPolicy(HitlTimeoutPolicy.ABORT); + batchEffectiveRule = rule; + + resumeWithToolRePause(hitl, FINGERPRINT, null); + + ArgumentCaptor cap = ArgumentCaptor.forClass(ScheduleConfiguration.class); + verify(scheduleStore).createSchedule(cap.capture()); + assertEquals("ABORT", cap.getValue().getMetadata().get("policy")); + } + + @Test + @DisplayName("the rule's duration beats an enclosing one — the deadline is the rule's, not the agent's") + void ruleDurationBeatsTheEnclosingDuration() throws Exception { + // Asserted on the armed deadline rather than the policy name, because both + // levels here agree on AUTO_REJECT: only the fire time distinguishes "the + // rule's PT5M was read" from "the agent's PT10H was". + var hitl = new AgentConfiguration.HitlConfig(); + var toolApprovals = new ToolApprovalsConfig(); + toolApprovals.setTimeoutPolicy(HitlTimeoutPolicy.AUTO_REJECT); + toolApprovals.setApprovalTimeout("PT10H"); + hitl.setToolApprovals(toolApprovals); + batchEffectiveToolApprovals = toolApprovals; + + var rule = new ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("http.post:/administration/{environment}/deploy/{agentId}"); + rule.setTimeoutPolicy(HitlTimeoutPolicy.AUTO_REJECT); + rule.setApprovalTimeout("PT5M"); + batchEffectiveRule = rule; + + Instant before = Instant.now(); + resumeWithToolRePause(hitl, FINGERPRINT, null); + + ArgumentCaptor cap = ArgumentCaptor.forClass(ScheduleConfiguration.class); + verify(scheduleStore).createSchedule(cap.capture()); + Instant fireAt = cap.getValue().getNextFire(); + assertTrue(fireAt.isBefore(before.plus(Duration.ofMinutes(30))), + "the rule's PT5M must arm the deadline, not the enclosing PT10H — armed at " + fireAt); + assertTrue(fireAt.isAfter(before), "a fresh pause must arm a future deadline, armed at " + fireAt); + } + + @Test + @DisplayName("a rule stating only a duration leaves the policy resolution alone") + void ruleWithOnlyDurationDoesNotChangeThePolicy() throws Exception { + // A messages-and-timing rule must not accidentally promote the inherited + // AUTO_APPROVE that Task 10 demotes. + var hitl = new AgentConfiguration.HitlConfig(); + hitl.setApprovalTimeout("PT30S"); + hitl.setTimeoutPolicy(HitlTimeoutPolicy.AUTO_APPROVE); + hitl.setToolApprovals(new ToolApprovalsConfig()); + + var rule = new ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("http.post:*"); + rule.setApprovalTimeout("PT2M"); + batchEffectiveRule = rule; + + resumeWithToolRePause(hitl, FINGERPRINT, null); + + verify(scheduleStore, never()).createSchedule(any()); + } + } + // ========================================================================= // Fix #1 — backward compatibility: a legacy batch (null effective config), // a RULE pause, or a null batch must behave EXACTLY as before. @@ -649,6 +765,7 @@ private void resumeWithToolRePause(AgentConfiguration.HitlConfig hitlConfig, Str newBatch.setAutoApproveCount(0); newBatch.setCalls(List.of(pendingCall("call-xyz", false))); newBatch.setEffectiveToolApprovals(batchEffectiveToolApprovals); + newBatch.setEffectiveRule(batchEffectiveRule); memory.setHitlPendingToolCalls(newBatch); if (newBatchCapture != null) { newBatchCapture.set(newBatch); @@ -724,6 +841,7 @@ private ConversationMemorySnapshot toolCallPauseSnapshot(String fingerprint, int batch.setFingerprint(fingerprint); batch.setAutoApproveCount(autoApproveCount); batch.setEffectiveToolApprovals(batchEffectiveToolApprovals); + batch.setEffectiveRule(batchEffectiveRule); List calls = new ArrayList<>(); calls.add(pendingCall("call-abc", false)); batch.setCalls(calls); diff --git a/src/test/java/ai/labs/eddi/engine/mcp/McpDocResourcesTest.java b/src/test/java/ai/labs/eddi/engine/mcp/McpDocResourcesTest.java index 8e0aca1f21..fbeecbbe01 100644 --- a/src/test/java/ai/labs/eddi/engine/mcp/McpDocResourcesTest.java +++ b/src/test/java/ai/labs/eddi/engine/mcp/McpDocResourcesTest.java @@ -4,6 +4,7 @@ */ package ai.labs.eddi.engine.mcp; +import ai.labs.eddi.engine.docs.DocsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -16,27 +17,37 @@ /** * Tests for McpDocResources, focusing on path traversal prevention. + *

+ * Every assertion here predates the extraction of {@link DocsService} and is + * kept verbatim: this class is the evidence that moving the filesystem access + * out did not change a single response an MCP client sees. */ class McpDocResourcesTest { private McpDocResources resources; + private DocsService docsService; @TempDir Path tempDir; @BeforeEach void setUp() throws Exception { - resources = new McpDocResources(); - - // Set docsPath via reflection (normally injected by CDI) - Field docsPathField = McpDocResources.class.getDeclaredField("docsPath"); - docsPathField.setAccessible(true); - docsPathField.set(resources, tempDir.toString()); + docsService = docsServiceFor(tempDir.toString()); + resources = new McpDocResources(docsService); // Create a test doc Files.writeString(tempDir.resolve("getting-started.md"), "# Getting Started\nHello!"); } + /** DocsService with docsPath set directly (normally injected by CDI). */ + private static DocsService docsServiceFor(String path) throws Exception { + var service = new DocsService(); + Field docsPathField = DocsService.class.getDeclaredField("docsPath"); + docsPathField.setAccessible(true); + docsPathField.set(service, path); + return service; + } + @Test void readDoc_validName_returnsContent() { String result = resources.readDoc("getting-started"); @@ -104,11 +115,11 @@ void listDocs_returnsIndex() { @Test void listDocs_invalidDir_returnsError() throws Exception { - Field docsPathField = McpDocResources.class.getDeclaredField("docsPath"); - docsPathField.setAccessible(true); - docsPathField.set(resources, "/nonexistent/path"); + // A mis-set eddi.docs.path must still read as a misconfiguration, not as an + // index of zero documents — which would look like success. + var broken = new McpDocResources(docsServiceFor("/nonexistent/path")); - String result = resources.listDocs(); + String result = broken.listDocs(); assertTrue(result.contains("Docs directory not found")); } } diff --git a/src/test/java/ai/labs/eddi/engine/mcp/McpSetupToolsTest.java b/src/test/java/ai/labs/eddi/engine/mcp/McpSetupToolsTest.java index 2ac1939d05..6f33e82fcc 100644 --- a/src/test/java/ai/labs/eddi/engine/mcp/McpSetupToolsTest.java +++ b/src/test/java/ai/labs/eddi/engine/mcp/McpSetupToolsTest.java @@ -6,6 +6,9 @@ import ai.labs.eddi.configs.rules.IRestRuleSetStore; import ai.labs.eddi.configs.agents.IRestAgentStore; +import ai.labs.eddi.configs.agents.model.AgentConfiguration; +import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig; +import ai.labs.eddi.engine.setup.CreateApiAgentRequest; import ai.labs.eddi.configs.descriptors.IRestDocumentDescriptorStore; import ai.labs.eddi.configs.apicalls.IRestApiCallsStore; import ai.labs.eddi.configs.mcpcalls.IRestMcpCallsStore; @@ -783,7 +786,7 @@ void createApiAgent_fullWorkflow_createsAllResources() throws Exception { when(agentAdmin.deployAgent(any(), any(), anyInt(), anyBoolean(), anyBoolean())).thenReturn(Response.ok().build()); String result = tools.createApIAgent("API Agent", "You are an API assistant", SIMPLE_SPEC, "anthropic", "claude-sonnet-4-6", "sk-test", null, - "Bearer api-key", null, null, null, true, null, null); + "Bearer api-key", null, null, null, true, null, null, null); assertNotNull(result); @@ -806,14 +809,14 @@ void createApiAgent_fullWorkflow_createsAllResources() throws Exception { @Test void createApiAgent_missingSpec_returnsError() { - String result = tools.createApIAgent("Agent", "prompt", null, null, null, "key", null, null, null, null, null, null, null, null); + String result = tools.createApIAgent("Agent", "prompt", null, null, null, "key", null, null, null, null, null, null, null, null, null); assertTrue(result.contains("error")); assertTrue(result.contains("OpenAPI spec is required")); } @Test void createApiAgent_missingApiKey_returnsError() { - String result = tools.createApIAgent("Agent", "prompt", SIMPLE_SPEC, null, null, null, null, null, null, null, null, null, null, null); + String result = tools.createApIAgent("Agent", "prompt", SIMPLE_SPEC, null, null, null, null, null, null, null, null, null, null, null, null); assertTrue(result.contains("error")); assertTrue(result.contains("API key is required")); } @@ -827,7 +830,7 @@ void createApiAgent_packageContainsApiCallsExtensions() throws Exception { when(WorkflowStore.createWorkflow(any())).thenReturn(Response.created(URI.create("/workflowstore/workflows/pkg-1?version=1")).build()); when(AgentStore.createAgent(any())).thenReturn(Response.created(URI.create("/agentstore/agents/agent-1?version=1")).build()); - tools.createApIAgent("Agent", "prompt", SIMPLE_SPEC, null, null, "key", null, null, null, null, null, false, null, null); + tools.createApIAgent("Agent", "prompt", SIMPLE_SPEC, null, null, "key", null, null, null, null, null, false, null, null, null); var packageCaptor = ArgumentCaptor.forClass(WorkflowConfiguration.class); verify(WorkflowStore).createWorkflow(packageCaptor.capture()); @@ -841,4 +844,71 @@ void createApiAgent_packageContainsApiCallsExtensions() throws Exception { assertEquals(URI.create("eddi://ai.labs.httpcalls"), pkgConfig.getWorkflowSteps().get(3).getType()); assertEquals(URI.create("eddi://ai.labs.llm"), pkgConfig.getWorkflowSteps().get(4).getType()); } + + // --- setup-api can now provision the approval gate (iteration 2) --- + + @Test + void createApiAgent_installsTheHitlGateOnV1OfTheAgentDocument() throws Exception { + // Before this, createApiAgent built a bare AgentConfiguration, so EVERY agent + // the wizard produced had hitlConfig == null and an inert gate — no caller + // could provision a gated agent through setup-api at all. It must land on v1: + // a later PUT would write version + 1 and leave the ungated v1 redeployable. + stubApiAgentStores(); + + var hitl = new AgentConfiguration.HitlConfig(); + var toolApprovals = new ToolApprovalsConfig(); + toolApprovals.setRequireApproval(List.of("http.post:*", "http.put:*", "http.patch:*", "http.delete:*")); + toolApprovals.setExempt(List.of("http.get:*")); + hitl.setToolApprovals(toolApprovals); + + service.createApiAgent(new CreateApiAgentRequest("Agent", "prompt", SIMPLE_SPEC, null, null, "key", + null, null, null, null, null, false, null, null, hitl, null)); + + var agentCaptor = ArgumentCaptor.forClass(AgentConfiguration.class); + verify(AgentStore).createAgent(agentCaptor.capture()); + var created = agentCaptor.getValue().getHitlConfig(); + assertNotNull(created, "the gate must be created WITH the agent, not added afterwards"); + assertEquals(List.of("http.post:*", "http.put:*", "http.patch:*", "http.delete:*"), + created.getToolApprovals().getRequireApproval()); + assertEquals(List.of("http.get:*"), created.getToolApprovals().getExempt()); + } + + @Test + void createApiAgent_withoutHitlConfig_leavesTheAgentExactlyAsBefore() throws Exception { + stubApiAgentStores(); + + service.createApiAgent(new CreateApiAgentRequest("Agent", "prompt", SIMPLE_SPEC, null, null, "key", + null, null, null, null, null, false, null, null, null, null)); + + var agentCaptor = ArgumentCaptor.forClass(AgentConfiguration.class); + verify(AgentStore).createAgent(agentCaptor.capture()); + assertNull(agentCaptor.getValue().getHitlConfig()); + } + + @Test + void createApiAgent_withMcpServerUrls_addsAnMcpStepAlongsideTheGeneratedHttpcalls() throws Exception { + // "REST plus MCP" was unreachable through this wizard: createApiAgent passed + // null for the MCP locations, so an agent needing both had to be hand-built. + stubApiAgentStores(); + when(mcpCallsStore.createMcpCalls(any())) + .thenReturn(Response.created(URI.create("/mcpcallstore/mcpcalls/mcp-1?version=1")).build()); + + service.createApiAgent(new CreateApiAgentRequest("Agent", "prompt", SIMPLE_SPEC, null, null, "key", + null, null, null, null, null, false, null, null, null, "https://mcp.example.com/sse")); + + var packageCaptor = ArgumentCaptor.forClass(WorkflowConfiguration.class); + verify(WorkflowStore).createWorkflow(packageCaptor.capture()); + var stepTypes = packageCaptor.getValue().getWorkflowSteps().stream().map(s -> s.getType().toString()).toList(); + assertTrue(stepTypes.contains("eddi://ai.labs.mcpcalls"), "expected an MCP step, got: " + stepTypes); + assertTrue(stepTypes.contains("eddi://ai.labs.httpcalls"), "the generated httpcalls must survive: " + stepTypes); + } + + private void stubApiAgentStores() { + when(httpCallsStore.createApiCalls(any())).thenReturn(Response.created(URI.create("/apicallstore/apicalls/hc-1?version=1")).build()) + .thenReturn(Response.created(URI.create("/apicallstore/apicalls/hc-2?version=1")).build()); + when(behaviorStore.createRuleSet(any())).thenReturn(Response.created(URI.create("/rulestore/rulesets/beh-1?version=1")).build()); + when(langchainStore.createLlm(any())).thenReturn(Response.created(URI.create("/llmstore/llms/lc-1?version=1")).build()); + when(WorkflowStore.createWorkflow(any())).thenReturn(Response.created(URI.create("/workflowstore/workflows/pkg-1?version=1")).build()); + when(AgentStore.createAgent(any())).thenReturn(Response.created(URI.create("/agentstore/agents/agent-1?version=1")).build()); + } } diff --git a/src/test/java/ai/labs/eddi/engine/memory/model/PendingToolCallBatchSnapshotTest.java b/src/test/java/ai/labs/eddi/engine/memory/model/PendingToolCallBatchSnapshotTest.java index 7a634b394d..55467136a2 100644 --- a/src/test/java/ai/labs/eddi/engine/memory/model/PendingToolCallBatchSnapshotTest.java +++ b/src/test/java/ai/labs/eddi/engine/memory/model/PendingToolCallBatchSnapshotTest.java @@ -52,6 +52,7 @@ private static PendingToolCallBatch fullBatch() { call2.setArgsTruncated(true); call2.setArgumentsRedacted(""); call2.setGateReason("mcp:*"); + call2.setMatchedRule("mcp:delete_*"); var batch = new PendingToolCallBatch(); batch.setPauseEpoch("epoch-1"); @@ -76,6 +77,13 @@ private static PendingToolCallBatch fullBatch() { effective.setOnNoProgress("AUTO_REJECT"); effective.setPendingMessage("Awaiting review for {toolNames}"); batch.setEffectiveToolApprovals(effective); + + var rule = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("mcp:delete_*"); + rule.setTimeoutPolicy(ai.labs.eddi.configs.hitl.HitlTimeoutPolicy.WAIT_INDEFINITELY); + rule.setPauseReason("Deleting a record — check the id"); + rule.setPendingMessage("Waiting on a reviewer for {toolNames}"); + batch.setEffectiveRule(rule); return batch; } @@ -113,6 +121,21 @@ void snapshot_roundTrips_toolPauseFields() throws Exception { assertEquals("PT1H", batch.getEffectiveToolApprovals().getApprovalTimeout()); assertEquals("AUTO_REJECT", batch.getEffectiveToolApprovals().getOnNoProgress()); assertEquals("Awaiting review for {toolNames}", batch.getEffectiveToolApprovals().getPendingMessage()); + + // The governing per-tool friction rule must round-trip too. It is resolved + // ONCE at gate time and read back after the pause by ConversationService (the + // timeout policy) and Conversation.resolvePendingMessage (the end-user text). + // If it did not survive persistence, a paused conversation would show the + // rule's message and the resume would recompute the scalar one — leaving the + // pending-approval placeholder stranded in the resolved turn's output, because + // dropPendingApprovalPlaceholder removes it by recomputing that exact string. + assertNotNull(batch.getEffectiveRule()); + assertEquals("mcp:delete_*", batch.getEffectiveRule().getMatch()); + assertEquals(ai.labs.eddi.configs.hitl.HitlTimeoutPolicy.WAIT_INDEFINITELY, + batch.getEffectiveRule().getTimeoutPolicy()); + assertEquals("Deleting a record — check the id", batch.getEffectiveRule().getPauseReason()); + assertEquals("Waiting on a reviewer for {toolNames}", batch.getEffectiveRule().getPendingMessage()); + assertEquals("mcp:delete_*", batch.getCalls().get(1).getMatchedRule()); } @Test diff --git a/src/test/java/ai/labs/eddi/engine/rest/RestDocsTest.java b/src/test/java/ai/labs/eddi/engine/rest/RestDocsTest.java new file mode 100644 index 0000000000..bcfa7a8a56 --- /dev/null +++ b/src/test/java/ai/labs/eddi/engine/rest/RestDocsTest.java @@ -0,0 +1,100 @@ +/* + * Copyright EDDI contributors + * SPDX-License-Identifier: Apache-2.0 + */ +package ai.labs.eddi.engine.rest; + +import ai.labs.eddi.engine.docs.DocsService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The REST doc surface an EDDI agent actually reaches — MCP resources do not + * reach one, because EDDI's own MCP client never calls {@code resources/read}. + *

+ * The traversal guard is asserted here as well as on the MCP surface: the two + * share {@link DocsService}, but a REST path parameter is the more exposed of + * the two inputs and a regression that only reintroduced it on one surface + * would otherwise pass. + */ +@DisplayName("RestDocs") +class RestDocsTest { + + private RestDocs restDocs; + + @TempDir + Path tempDir; + + @BeforeEach + void setUp() throws Exception { + var service = new DocsService(); + Field docsPathField = DocsService.class.getDeclaredField("docsPath"); + docsPathField.setAccessible(true); + docsPathField.set(service, tempDir.toString()); + restDocs = new RestDocs(service); + + Files.writeString(tempDir.resolve("architecture.md"), "# Architecture\nPipeline."); + Files.writeString(tempDir.resolve("hitl.md"), "# HITL\nGate."); + Files.writeString(tempDir.resolve("not-markdown.txt"), "ignored"); + } + + @Test + @DisplayName("lists the markdown pages, sorted and suffix-stripped") + void listsMarkdownPages() { + assertEquals(List.of("architecture", "hitl"), restDocs.listDocs()); + } + + @Test + @DisplayName("reads a page as text/plain") + void readsAPage() { + var response = restDocs.readDoc("architecture"); + assertEquals(200, response.getStatus()); + assertTrue(response.getEntity().toString().contains("# Architecture")); + } + + @Test + @DisplayName("an absent page is a 404, not an empty 200") + void absentPageIs404() { + assertEquals(404, restDocs.readDoc("no-such-page").getStatus()); + } + + @Test + @DisplayName("traversal attempts are 404 and never echo the supplied name back") + void traversalAttemptsAre404() throws Exception { + // The name is attacker-supplied, so it must not be reflected in the response — + // hence a bare 404 rather than a "invalid name: ..." message. + Files.writeString(tempDir.getParent().resolve("secret.md"), "top secret"); + + for (String attempt : List.of("../secret", "../../etc/passwd", "sub/doc", "sub\\doc", "..", "")) { + var response = restDocs.readDoc(attempt); + assertEquals(404, response.getStatus(), "must refuse: " + attempt); + assertNull(response.getEntity(), "must not echo the supplied name back: " + attempt); + } + assertEquals(404, restDocs.readDoc(null).getStatus()); + } + + @Test + @DisplayName("a missing docs directory lists nothing rather than failing") + void missingDirectoryListsNothing() throws Exception { + var service = new DocsService(); + Field docsPathField = DocsService.class.getDeclaredField("docsPath"); + docsPathField.setAccessible(true); + docsPathField.set(service, tempDir.resolve("does-not-exist").toString()); + + var docs = new RestDocs(service); + assertTrue(docs.listDocs().isEmpty()); + assertFalse(service.isAvailable()); + } +} diff --git a/src/test/java/ai/labs/eddi/engine/runtime/internal/ConversationHitlTest.java b/src/test/java/ai/labs/eddi/engine/runtime/internal/ConversationHitlTest.java index 25a11954ec..ee78c84060 100644 --- a/src/test/java/ai/labs/eddi/engine/runtime/internal/ConversationHitlTest.java +++ b/src/test/java/ai/labs/eddi/engine/runtime/internal/ConversationHitlTest.java @@ -207,6 +207,83 @@ void toolPauseLegacyBatchFallsBackToAgentLevel() throws Exception { "a legacy batch must fall back to the agent-level pendingMessage; got: " + rendered); } + @Test + @DisplayName("TOOL_CALL pause uses the governing rule's pendingMessage over both scalar levels") + void toolPauseUsesGoverningRulePendingMessage() throws Exception { + // "You are about to create an agent" reads very differently from a blanket + // "an action needs approval" — per-endpoint friction is only worth having if + // the end user actually sees the endpoint-specific wording. + memory.setConversationState(ConversationState.READY); + + var agentLevel = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig(); + agentLevel.setPendingMessage("AGENT default for {toolNames}"); + memory.setAgentToolApprovalsConfig(agentLevel); + + var taskOverride = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig(); + taskOverride.setPendingMessage("TASK review pending for {toolNames}"); + + var rule = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("http.post:/agentstore/agents"); + rule.setPendingMessage("RULE creating an agent via {toolNames}"); + + doAnswer(inv -> { + var call = new ai.labs.eddi.engine.memory.model.PendingToolCallBatch.PendingToolCall(); + call.setToolName("createAgent"); + var batch = new ai.labs.eddi.engine.memory.model.PendingToolCallBatch(); + batch.setCalls(List.of(call)); + batch.setEffectiveToolApprovals(taskOverride); + batch.setEffectiveRule(rule); + memory.setHitlPendingToolCalls(batch); + throw new ConversationPauseException("wf1", 2, "gated tool call", + ConversationPauseException.PauseOrigin.TOOL_CALL); + }).when(lifecycleManager).executeLifecycle(any(), any()); + + var conv = createConversation(); + conv.say("create an agent", Map.of()); + + var output = memory.getCurrentStep().getConversationOutput(); + String rendered = output.get(ai.labs.eddi.engine.memory.MemoryKeys.OUTPUT_PREFIX).toString(); + assertTrue(rendered.contains("RULE creating an agent via createAgent"), + "the governing rule's pendingMessage must win over both scalar levels; got: " + rendered); + assertFalse(rendered.contains("TASK review pending"), + "the toolApprovals scalar must NOT be used when the governing rule states a message"); + } + + @Test + @DisplayName("a governing rule stating no pendingMessage still falls back to the toolApprovals scalar") + void toolPauseRuleWithoutMessageFallsBackToScalar() throws Exception { + // Fields fall back individually: a rule that only tightens the timeout must + // not blank out the message the designer wrote at the level above. + memory.setConversationState(ConversationState.READY); + + var taskOverride = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig(); + taskOverride.setPendingMessage("TASK review pending for {toolNames}"); + + var rule = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("http.delete:*"); + rule.setTimeoutPolicy(ai.labs.eddi.configs.hitl.HitlTimeoutPolicy.WAIT_INDEFINITELY); + + doAnswer(inv -> { + var call = new ai.labs.eddi.engine.memory.model.PendingToolCallBatch.PendingToolCall(); + call.setToolName("deleteAgent"); + var batch = new ai.labs.eddi.engine.memory.model.PendingToolCallBatch(); + batch.setCalls(List.of(call)); + batch.setEffectiveToolApprovals(taskOverride); + batch.setEffectiveRule(rule); + memory.setHitlPendingToolCalls(batch); + throw new ConversationPauseException("wf1", 2, "gated tool call", + ConversationPauseException.PauseOrigin.TOOL_CALL); + }).when(lifecycleManager).executeLifecycle(any(), any()); + + var conv = createConversation(); + conv.say("delete it", Map.of()); + + var output = memory.getCurrentStep().getConversationOutput(); + String rendered = output.get(ai.labs.eddi.engine.memory.MemoryKeys.OUTPUT_PREFIX).toString(); + assertTrue(rendered.contains("TASK review pending for deleteAgent"), + "a rule silent on pendingMessage must inherit the scalar; got: " + rendered); + } + @Test @DisplayName("normal (non-pause) turn DOES purge step-scoped properties — companion to Invariant 9") void normalTurnPurgesStepProperties() throws Exception { diff --git a/src/test/java/ai/labs/eddi/engine/setup/AgentSetupServiceTest.java b/src/test/java/ai/labs/eddi/engine/setup/AgentSetupServiceTest.java index 1368d9f95e..5324a723ff 100644 --- a/src/test/java/ai/labs/eddi/engine/setup/AgentSetupServiceTest.java +++ b/src/test/java/ai/labs/eddi/engine/setup/AgentSetupServiceTest.java @@ -618,7 +618,7 @@ class CreateApiAgentValidationTests { void nullAgentName() { var request = new CreateApiAgentRequest( null, "prompt", "openapi: 3.0", "openai", "gpt-4", - "sk-key", null, null, null, null, null, null, null, null); + "sk-key", null, null, null, null, null, null, null, null, null, null); var ex = assertThrows(AgentSetupService.AgentSetupException.class, () -> service.createApiAgent(request)); assertTrue(ex.getMessage().contains("Agent name is required")); @@ -629,7 +629,7 @@ void nullAgentName() { void blankSystemPrompt() { var request = new CreateApiAgentRequest( "My Agent", " ", "openapi: 3.0", "openai", "gpt-4", - "sk-key", null, null, null, null, null, null, null, null); + "sk-key", null, null, null, null, null, null, null, null, null, null); var ex = assertThrows(AgentSetupService.AgentSetupException.class, () -> service.createApiAgent(request)); assertTrue(ex.getMessage().contains("System prompt is required")); @@ -640,7 +640,7 @@ void blankSystemPrompt() { void blankOpenApiSpec() { var request = new CreateApiAgentRequest( "My Agent", "You are helpful", "", "openai", "gpt-4", - "sk-key", null, null, null, null, null, null, null, null); + "sk-key", null, null, null, null, null, null, null, null, null, null); var ex = assertThrows(AgentSetupService.AgentSetupException.class, () -> service.createApiAgent(request)); assertTrue(ex.getMessage().contains("OpenAPI spec is required")); @@ -651,11 +651,106 @@ void blankOpenApiSpec() { void cloudProviderNoApiKey() { var request = new CreateApiAgentRequest( "My Agent", "You are helpful", "openapi: 3.0", "openai", "gpt-4", - null, null, null, null, null, null, null, null, null); + null, null, null, null, null, null, null, null, null, null, null); var ex = assertThrows(AgentSetupService.AgentSetupException.class, () -> service.createApiAgent(request)); assertTrue(ex.getMessage().contains("API key is required")); } + + @Test + @DisplayName("an unusable approval pattern is refused BEFORE any resource is created") + void invalidHitlConfigRefusedBeforeAnyResourceIsCreated() throws Exception { + // AgentStore.create validates hitlConfig too — but that runs at step 7, so + // without the up-front check a bad pattern would surface only after the + // apicalls, parser, behaviour, LLM and workflow had been created, leaving + // all five orphaned. Asserted by proving no store was even asked for. + var restInterfaceFactory = mock(IRestInterfaceFactory.class); + var guardedService = new AgentSetupService(restInterfaceFactory, + mock(IRestAgentAdministration.class), mock(ISecretProvider.class), "http://localhost:11434"); + + var hitl = new ai.labs.eddi.configs.agents.model.AgentConfiguration.HitlConfig(); + var toolApprovals = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig(); + // 'mcp' tools carry no endpoint, so this pattern can never match — it would + // save as a gate that gates nothing. + toolApprovals.setRequireApproval(List.of("mcp:/agentstore/agents")); + hitl.setToolApprovals(toolApprovals); + + var request = new CreateApiAgentRequest( + "My Agent", "You are helpful", "openapi: 3.0", "openai", "gpt-4", + "sk-key", null, null, null, null, null, null, null, null, hitl, null); + + var ex = assertThrows(AgentSetupService.AgentSetupException.class, + () -> guardedService.createApiAgent(request)); + assertTrue(ex.getMessage().startsWith("Invalid hitlConfig:"), ex.getMessage()); + org.mockito.Mockito.verify(restInterfaceFactory, org.mockito.Mockito.never()).get(any()); + } + + @Test + @DisplayName("an invalid MCP server URL is refused BEFORE any resource is created") + void invalidMcpUrlRefusedBeforeAnyResourceIsCreated() throws Exception { + // McpCallsConfiguration.validate() rejects a non-http(s) URL at save time, so + // without the up-front sweep the SECOND bad URL would abort with the first + // one's resource already persisted — plus, on this path, the apicalls, + // parser, behaviour and LLM resources. + var restInterfaceFactory = mock(IRestInterfaceFactory.class); + var guardedService = new AgentSetupService(restInterfaceFactory, + mock(IRestAgentAdministration.class), mock(ISecretProvider.class), "http://localhost:11434"); + + var request = new CreateApiAgentRequest( + "My Agent", "You are helpful", "openapi: 3.0", "openai", "gpt-4", + "sk-key", null, null, null, null, null, null, null, null, null, + "https://good.example.com/mcp,ftp://bad.example.com/mcp"); + + var ex = assertThrows(AgentSetupService.AgentSetupException.class, + () -> guardedService.createApiAgent(request)); + assertTrue(ex.getMessage().startsWith("Invalid mcpServerUrls entry"), ex.getMessage()); + assertTrue(ex.getMessage().contains("ftp://bad.example.com/mcp"), ex.getMessage()); + org.mockito.Mockito.verify(restInterfaceFactory, org.mockito.Mockito.never()).get(any()); + } + + @Test + @DisplayName("valid MCP server URLs pass the up-front check") + void validMcpUrlsPassTheUpFrontCheck() throws Exception { + var restInterfaceFactory = mock(IRestInterfaceFactory.class); + var guardedService = new AgentSetupService(restInterfaceFactory, + mock(IRestAgentAdministration.class), mock(ISecretProvider.class), "http://localhost:11434"); + + var request = new CreateApiAgentRequest( + "My Agent", "You are helpful", "openapi: 3.0", "openai", "gpt-4", + "sk-key", null, null, null, null, null, null, null, null, null, + "https://a.example.com/mcp, https://b.example.com/mcp"); + + var ex = assertThrows(AgentSetupService.AgentSetupException.class, + () -> guardedService.createApiAgent(request)); + assertFalse(ex.getMessage().startsWith("Invalid mcpServerUrls entry"), + "valid URLs must not be refused; got: " + ex.getMessage()); + } + + @Test + @DisplayName("a valid hitlConfig passes the up-front check and reaches resource creation") + void validHitlConfigPassesTheUpFrontCheck() throws Exception { + // Mutation guard for the test above: the guard must reject only what is + // actually invalid. A valid gate proceeds past validation into the REST + // calls (which fail here for want of a store — a different failure). + var restInterfaceFactory = mock(IRestInterfaceFactory.class); + var guardedService = new AgentSetupService(restInterfaceFactory, + mock(IRestAgentAdministration.class), mock(ISecretProvider.class), "http://localhost:11434"); + + var hitl = new ai.labs.eddi.configs.agents.model.AgentConfiguration.HitlConfig(); + var toolApprovals = new ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig(); + toolApprovals.setRequireApproval(List.of("http.post:*", "http.put:*", "http.delete:*")); + toolApprovals.setExempt(List.of("http.get:*")); + hitl.setToolApprovals(toolApprovals); + + var request = new CreateApiAgentRequest( + "My Agent", "You are helpful", "openapi: 3.0", "openai", "gpt-4", + "sk-key", null, null, null, null, null, null, null, null, hitl, null); + + var ex = assertThrows(AgentSetupService.AgentSetupException.class, + () -> guardedService.createApiAgent(request)); + assertFalse(ex.getMessage().startsWith("Invalid hitlConfig:"), + "a valid gate must not be refused by the up-front check; got: " + ex.getMessage()); + } } // ==================== deployAndWait ==================== diff --git a/src/test/java/ai/labs/eddi/modules/llm/impl/AgentOrchestratorCoverageTest.java b/src/test/java/ai/labs/eddi/modules/llm/impl/AgentOrchestratorCoverageTest.java index 5a37d7e025..481bb7dbcd 100644 --- a/src/test/java/ai/labs/eddi/modules/llm/impl/AgentOrchestratorCoverageTest.java +++ b/src/test/java/ai/labs/eddi/modules/llm/impl/AgentOrchestratorCoverageTest.java @@ -5,6 +5,7 @@ package ai.labs.eddi.modules.llm.impl; import ai.labs.eddi.configs.agents.IRestAgentStore; +import ai.labs.eddi.configs.hitl.HitlTimeoutPolicy; import ai.labs.eddi.configs.hitl.model.ToolApprovalsConfig; import ai.labs.eddi.configs.properties.IUserMemoryStore; import ai.labs.eddi.configs.workflows.IRestWorkflowStore; @@ -1046,10 +1047,44 @@ void normalizeToolCallIds_gateConfigEmptyRequireApproval_inert() throws Exceptio // ═══════════════════════════════════════════════════════════════════ private String buildPauseReason(ToolApprovalsConfig cfg, ToolApprovalGate.GateResult gr) throws Exception { + return buildPauseReason(cfg, gr, null); + } + + private String buildPauseReason(ToolApprovalsConfig cfg, ToolApprovalGate.GateResult gr, + ToolApprovalsConfig.ApprovalRule rule) + throws Exception { Method m = AgentOrchestrator.class.getDeclaredMethod("buildPauseReason", - ToolApprovalsConfig.class, ToolApprovalGate.GateResult.class); + ToolApprovalsConfig.class, ToolApprovalGate.GateResult.class, ToolApprovalsConfig.ApprovalRule.class); m.setAccessible(true); - return (String) m.invoke(null, cfg, gr); + return (String) m.invoke(null, cfg, gr, rule); + } + + @Test + void buildPauseReason_governingRuleBeatsTheScalar() throws Exception { + // The approval card is where per-endpoint friction is actually felt: the + // approver must read why THIS write is different, not the blanket text. + var cfg = new ToolApprovalsConfig(); + cfg.setPauseReason("Generic: {toolNames}"); + var rule = new ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("http.post:/agentstore/agents"); + rule.setPauseReason("Creating a new agent — review the whole config ({toolNames})"); + var gr = gateResult(ToolExecutionRequest.builder().id("c1").name("createAgent").arguments("{}").build()); + + String reason = buildPauseReason(cfg, gr, rule); + + assertEquals("Creating a new agent — review the whole config (createAgent)", reason); + } + + @Test + void buildPauseReason_ruleSilentOnReason_fallsBackToTheScalar() throws Exception { + var cfg = new ToolApprovalsConfig(); + cfg.setPauseReason("Generic: {toolNames}"); + var rule = new ToolApprovalsConfig.ApprovalRule(); + rule.setMatch("http.post:*"); + rule.setTimeoutPolicy(HitlTimeoutPolicy.WAIT_INDEFINITELY); + var gr = gateResult(ToolExecutionRequest.builder().id("c1").name("createAgent").arguments("{}").build()); + + assertEquals("Generic: createAgent", buildPauseReason(cfg, gr, rule)); } private ToolApprovalGate.GateResult gateResult(ToolExecutionRequest... gated) { @@ -1136,6 +1171,49 @@ void buildPendingBatch_overloadDelegates_usesDefaultCap() { assertFalse(batch.isTranscriptOmitted()); } + @Test + void buildPendingBatch_persistsTheGoverningRuleAndThePerCallMatch() { + // The rule is resolved at gate time and must SURVIVE the pause: the persisted + // batch keeps names and sources but no endpoints, so an endpoint-addressed + // rule could never be re-derived by the post-pause resolvers. + var deploy = ToolExecutionRequest.builder().id("c1").name("deployAgent").arguments("{}").build(); + var delete = ToolExecutionRequest.builder().id("c2").name("deleteAgent").arguments("{}").build(); + var gr = new ToolApprovalGate.GateResult(List.of(deploy, delete), List.of(), + Map.of("c1", "http.post:*", "c2", "http.delete:*")); + List msgs = List.of(UserMessage.from("hi"), AiMessage.from(List.of(deploy, delete))); + + var deployRule = new ToolApprovalsConfig.ApprovalRule(); + deployRule.setMatch("http.post:/administration/{environment}/deploy/{agentId}"); + var deleteRule = new ToolApprovalsConfig.ApprovalRule(); + deleteRule.setMatch("http.delete:*"); + deleteRule.setTimeoutPolicy(HitlTimeoutPolicy.WAIT_INDEFINITELY); + + var batch = orchestrator.buildPendingBatch(msgs, gr, twoToolTask(), memory, 0, + List.of(), new ArrayList<>(), 1, 0, Map.of("deployAgent", "http", "deleteAgent", "http"), + gateCalculate(), PendingToolCallBatch.TRANSCRIPT_MAX_BYTES_DEFAULT, + Map.of("c1", deployRule, "c2", deleteRule), deleteRule); + + assertNotNull(batch.getEffectiveRule()); + assertEquals("http.delete:*", batch.getEffectiveRule().getMatch()); + // Per call: which rule tuned THIS call, so an approver can tell which one + // brought the batch's policy. + assertEquals("http.post:/administration/{environment}/deploy/{agentId}", batch.getCalls().get(0).getMatchedRule()); + assertEquals("http.delete:*", batch.getCalls().get(1).getMatchedRule()); + } + + @Test + void buildPendingBatch_withoutRules_leavesTheBatchExactlyAsBefore() { + var gated = ToolExecutionRequest.builder().id("c1").name("calculate").arguments("{\"x\":1}").build(); + var gr = new ToolApprovalGate.GateResult(List.of(gated), List.of(), Map.of("c1", "calculate")); + List msgs = List.of(UserMessage.from("hi"), AiMessage.from(List.of(gated))); + + var batch = orchestrator.buildPendingBatch(msgs, gr, twoToolTask(), memory, 0, + List.of(), new ArrayList<>(), 1, 0, Map.of("calculate", "builtin"), gateCalculate()); + + assertNull(batch.getEffectiveRule(), "no rules configured must persist no rule"); + assertNull(batch.getCalls().get(0).getMatchedRule()); + } + @Test void buildPendingBatch_nullIdGeneratesSyntheticCallId() { // Request has null id -> "gen-" callId path.