diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 99a48190..5cbe88ee 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -45,6 +45,7 @@ jobs: "$temporary/venv/bin/python" -c 'from importlib.resources import files; assert files("apcore").joinpath("py.typed").is_file(), "installed wheel is missing apcore/py.typed"' python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" python "$temporary" (cd quick-start && "$temporary/venv/bin/python" -I example.py) + (cd typed-module && "$temporary/venv/bin/python" -I example.py) python -m venv "$temporary/full" "$temporary/full/bin/python" -m pip install "${wheel[0]}[all]" "$temporary/full/bin/python" -m pip check @@ -65,17 +66,26 @@ jobs: - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc with: toolchain: 1.86.0 - - run: cargo package --locked --all-features + - name: Package the macro and its SDK + shell: bash + run: | + cargo package --locked -p apcore-macros + # Cargo resolves the normalized SDK manifest against crates.io. + # Provide the same macro locally while the candidate is unpublished. + cargo --config "patch.crates-io.apcore-macros.path='$PWD/apcore-macros'" \ + package --locked -p apcore --all-features - name: Run downstream examples against the packaged crate shell: bash env: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: fallback run: | - archives=( "$PWD"/target/package/*.crate ) + sdk=( "$PWD"/target/package/apcore-[0-9]*.crate ) + macro=( "$PWD"/target/package/apcore-macros-[0-9]*.crate ) temporary=$(mktemp -d) cd "$temporary" - mkdir sdk - tar -xzf "${archives[0]}" --strip-components=1 -C sdk + mkdir sdk macros + tar -xzf "${sdk[0]}" --strip-components=1 -C sdk + tar -xzf "${macro[0]}" --strip-components=1 -C macros cp sdk/Cargo.lock Cargo.lock python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" rust "$temporary" cat > Cargo.toml <<'EOF' @@ -86,12 +96,17 @@ jobs: rust-version = "1.86" [dependencies] - apcore = { path = "sdk", features = ["config", "events"] } + apcore = { path = "sdk", features = ["config", "events", "macros"] } async-trait = "0.1.92" futures-util = "0.3" + schemars = "0.8" + serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } + [patch.crates-io] + apcore-macros = { path = "macros" } + [[bin]] name = "quick-start" path = "quick-start/example.rs" @@ -99,9 +114,14 @@ jobs: [[bin]] name = "governed-stream" path = "governed-stream/example.rs" + + [[bin]] + name = "typed-module" + path = "typed-module/example.rs" EOF (cd quick-start && cargo run --quiet --manifest-path ../Cargo.toml --bin quick-start) (cd governed-stream && cargo run --locked --quiet --manifest-path ../Cargo.toml --bin governed-stream) + (cd typed-module && cargo run --locked --quiet --manifest-path ../Cargo.toml --bin typed-module) - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: core-rust-distribution @@ -137,7 +157,7 @@ jobs: cd "$temporary" npm init -y npm pkg set type=module - npm install --ignore-scripts "${archive[0]}" typescript@5.5.4 @types/node@20 + npm install --ignore-scripts "${archive[0]}" typescript@5.5.4 @types/node@20 zod@4 node --input-type=module -e 'import {APCore} from "apcore-js"; import "apcore-js/context-keys"; if (!APCore) throw new Error("APCore is missing");' cat > verify-browser.mjs <<'EOF' const url = await import.meta.resolve("apcore-js"); @@ -150,9 +170,10 @@ jobs: node --input-type=module -e 'import {APCore} from "apcore-js/full"; import {Config} from "apcore-js/config"; import {createFilesystemDiscoveryPlugin} from "apcore-js/discovery"; if (!new APCore({config: new Config(), plugins: [createFilesystemDiscoveryPlugin()]}).registry) throw new Error("invalid full assembly");' python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" typescript "$temporary" ./node_modules/.bin/tsc --strict --module NodeNext --target ES2022 --rootDir . --outDir compiled \ - quick-start/example.ts governed-stream/example.ts + quick-start/example.ts governed-stream/example.ts typed-module/example.ts (cd quick-start && node ../compiled/quick-start/example.js) (cd governed-stream && node ../compiled/governed-stream/example.js) + (cd typed-module && node ../compiled/typed-module/example.js) - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: core-npm-distribution diff --git a/.github/workflows/sdk-rust.yml b/.github/workflows/sdk-rust.yml index b17c2415..9c5c84d7 100644 --- a/.github/workflows/sdk-rust.yml +++ b/.github/workflows/sdk-rust.yml @@ -74,7 +74,7 @@ jobs: CONFORMANCE_SPEC_REPO: ${{ github.workspace }} - name: Run tests - run: cargo test --locked --all-features + run: cargo test --locked --workspace --all-features env: CONFORMANCE_SPEC_REPO: ${{ github.workspace }} diff --git a/CHANGELOG.md b/CHANGELOG.md index b481008a..a154314b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Add governed typed Python module handles, TypeScript Standard Schema declarations, and optional Rust module macros and packs. - Provide explicit configuration, discovery, and full runtime assemblies. The default profile supports in-memory execution from installed Python, TypeScript, and Rust packages. - Add the pure TypeScript Prometheus text renderer and host-owned subscriber factories for configured event delivery. - **Protocol 2.0.0 draft revision 2.** Add opt-in policy evaluation after input validation. The enabled pipeline combines approval requirements at one gate, binds approval to the selected module version and effective arguments, and enforces the gate before ordinary and streaming execution. Final-scope pending approvals require an explicitly compatible scoped handler. diff --git a/conformance/extract_doc_examples.py b/conformance/extract_doc_examples.py index 25b5fb21..f8b7b625 100644 --- a/conformance/extract_doc_examples.py +++ b/conformance/extract_doc_examples.py @@ -36,6 +36,7 @@ def main() -> None: (STREAM_GUIDE, "governed-stream", args.language, f"governed-stream/example.{ext}"), (STREAM_GUIDE, "stream-config", "yaml", "governed-stream/apcore.yaml"), (STREAM_GUIDE, "stream-acl", "yaml", "governed-stream/acl/global_acl.yaml"), + ("docs/features/module-interface.md", "typed-module", args.language, f"typed-module/example.{ext}"), ) try: files = [(args.destination / target, example(source, label, lang)) for source, label, lang, target in sources] diff --git a/docs/features/module-interface.md b/docs/features/module-interface.md index 913269b3..8652f6ac 100644 --- a/docs/features/module-interface.md +++ b/docs/features/module-interface.md @@ -486,7 +486,7 @@ The examples below use a stand-in `Mailer` so they run as written; replace it wi === "Rust" ```rust - // Rust has no attribute macro; register a closure with APCore::module(). + // Register a closure when the optional macros feature is disabled. use apcore::errors::ModuleError; use apcore::{APCore, Context}; use serde_json::{json, Value}; @@ -524,6 +524,125 @@ The examples below use a stand-in `Mailer` so they run as written; replace it wi For YAML-based bindings and decorator details, see [Decorator & YAML Bindings](./decorator-bindings.md). +### Typed module declarations + +A typed declaration registers an ordinary APCore module. The typed handle +invokes the registered module through the executor. An MCP adapter can use +that executor to expose the same module and governance policy. + +=== "Python" + + `APCore.module` exposes `invoke`, `invoke_async`, `validate`, and + `preview` with the function's business signature. `with_context` attaches + a caller context. `with_approval_token` carries a resume credential. + Ordinary function calls and `raw` call the underlying function directly. + Use the governed methods for application calls and `raw` for isolated unit + tests. + + A governed call passes native arguments to the registered function's + input validator. With a post-validation evaluator, native values must have + an unambiguous JSON-shaped representation under the input declaration. + + + ```python + from apcore import APCore + from pydantic import BaseModel + + + class Note(BaseModel): + note_id: str + + + client = APCore() + + + @client.module("notes.lookup", description="Look up a note") + def lookup(note_id: str) -> Note: + return Note(note_id=note_id) + + + assert lookup.validate("note-1").valid + assert lookup.invoke("note-1").note_id == "note-1" + client.close() + ``` + +=== "TypeScript" + + `define` accepts validators that implement Standard Schema v1. If the + provider also implements Standard JSON Schema, Core requests Draft 2020-12 + for the submitted inputs and the returned output. With validation-only + providers or conversions that cannot describe a transformation, pass + `inputSchema` and `outputSchema` explicitly on the affected side. The + handler receives normalized inputs and the caller receives the normalized + output. Both use JSON-compatible objects. + + A handle belongs to its registered declaration. After replacing or + re-registering the module, use the handle returned for the new declaration. + + + ```typescript + import assert from 'node:assert/strict'; + import { APCore } from 'apcore-js'; + import { z } from 'zod/v4'; + + const client = new APCore(); + const lookup = await client.define({ + id: 'notes.lookup', + description: 'Look up a note', + readonly: true, + input: z.object({ noteId: z.string().min(1) }), + output: z.object({ noteId: z.string() }), + execute: ({ noteId }) => ({ noteId }), + }); + + assert.equal((await lookup.invoke({ noteId: 'note-1' })).noteId, 'note-1'); + await client.shutdown(); + ``` + +=== "Rust" + + Enable the `macros` feature of `apcore` and derive Serde and + `schemars::JsonSchema` for the input and output. `ModulePack` explicitly + selects the declarations compiled into the host. Pass + `client.executor_arc()` to the Rust MCP builder to expose that pack + with the host's executor configuration. + + + ```rust + use apcore::{APCore, ModuleError, ModulePack}; + use schemars::JsonSchema; + use serde::{Deserialize, Serialize}; + + #[derive(Deserialize, JsonSchema, Serialize)] + struct Note { + note_id: String, + } + + /// Look up a note. + #[apcore::module(id = "notes.lookup", readonly = true)] + async fn lookup(input: Note) -> Result { + Ok(input) + } + + const NOTES: ModulePack = ModulePack::new(&[lookup::DECLARATION]); + + #[tokio::main] + async fn main() -> Result<(), ModuleError> { + let client = APCore::new(); + NOTES.register(&client)?; + let note = lookup::HANDLE + .invoke(&client, Note { note_id: "note-1".into() }, None) + .await?; + assert_eq!(note.note_id, "note-1"); + Ok(()) + } + ``` + +When the executor has a post-validation evaluator, both the evaluator and +final approval receive the validated arguments. The default approval gate +retains its early position in the execution pipeline. See +[Approval System](./approval-system.md) for the two approval timings. + ## Dependencies - [Schema System](./schema-system.md) — input/output schema loading and validation. diff --git a/docs/index.md b/docs/index.md index ffbb26b2..840dd81f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -25,9 +25,9 @@ A schema makes a capability contract machine-readable and validatable. It does n | Component | Package | Stable | In development | |---|---|---|---| | Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft revision 4) | -| Python SDK | `apcore` | `0.33.0` | `1.0.0a5` | -| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.5` | -| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.5` | +| Python SDK | `apcore` | `0.33.0` | `1.0.0a6` | +| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.6` | +| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.6` | The protocol `2.0.0` draft defines the contract for the SDK `1.0.0` release line. The three core SDKs share that release line. Surface adapters (`apcore-mcp`, `apcore-a2a`, `apcore-cli`, `apcore-toolkit`) are versioned independently and declare the core range they support in their package metadata. diff --git a/examples/python/golden-path/README.md b/examples/python/golden-path/README.md index 5553f775..1ff33543 100644 --- a/examples/python/golden-path/README.md +++ b/examples/python/golden-path/README.md @@ -1,6 +1,6 @@ # Python Golden Path -Register an existing application function as an APCore module and call it from Python and through MCP. The two executors use the same notebook, module definitions, and governance policy. Each uses an in-memory approval store. The MCP server binds to a temporary loopback port and uses the local process as its trust boundary. +Register an application function as an APCore module and invoke it through a typed Python handle and through MCP. The two executors use the same notebook, module definitions, and governance policy. Each uses an in-memory approval store. The MCP server binds to a temporary loopback port and uses the local process as its trust boundary. ## Run the example @@ -20,8 +20,15 @@ Set `APCORE_WHEEL` and `APCORE_MCP_WHEEL` to the absolute paths of the Core and 1. `app.py` registers the notebook's archive operation with an input type inferred from the function signature and an output schema inferred from `ArchiveResult`. It marks the operation as destructive and configures `ExecutionPolicy(strict=True, gate_destructive=True)`. 2. `verify.py` checks a normal lookup, an ACL denial, and invalid input through both entry points. An archive request stays pending until the reviewer records a decision. -3. In Python, the verifier resolves the pending result's public `audit_id` in the store. It retries the same arguments through Core with the private `approval_id` in the reserved `_approval_token` field. +3. In Python, the verifier resolves the pending result's public `audit_id` in the store. It passes the private `approval_id` to `archive.with_approval_token(...)` and invokes the handle again with the same business argument. The handle returns an `ArchiveResult` model. 4. Through MCP, the verifier reads `approvalId` and `resumeToken` from the pending tool result's `_meta.apcore.approval`. It polls `__apcore_approval_check` with the public ID, resolves the request, and checks that the status changes to approved. It then retries the original tool arguments with the private token in request `_meta.approvalId`. 5. The verifier checks that each archive executes once and prints the ACL decisions with trace ID, caller ID, and target ID. The approval credential stays out of the audit output. The in-memory stores are for this local example. A deployed application can use an authenticated review service and a persistent scoped approval store. + +## In-process agent tool + +Install `openai-agents` to use `archive_tool(archive)` from `agent_tool.py`. +Pass the returned tool to `Agent(..., tools=[...])`. The tool calls the same +governed handle as the direct example. The host's approval handler still decides +whether an archive may run. [OpenAI Agents SDK function tools](https://openai.github.io/openai-agents-python/tools/#function-tools) diff --git a/examples/python/golden-path/agent_tool.py b/examples/python/golden-path/agent_tool.py new file mode 100644 index 00000000..718e8d17 --- /dev/null +++ b/examples/python/golden-path/agent_tool.py @@ -0,0 +1,15 @@ +"""Expose the same governed archive operation to an in-process Agents SDK agent.""" + +from agents import FunctionTool, function_tool +from apcore import BoundModule +from app import ArchiveResult + + +def archive_tool(archive: BoundModule[[str], ArchiveResult]) -> FunctionTool: + @function_tool + async def archive_note(note_id: str) -> str: + """Archive a note by its ID.""" + result = await archive.invoke_async(note_id) + return result.model_dump_json() + + return archive_note diff --git a/examples/python/golden-path/app.py b/examples/python/golden-path/app.py index 2a281d1f..02ee74f4 100644 --- a/examples/python/golden-path/app.py +++ b/examples/python/golden-path/app.py @@ -2,7 +2,7 @@ from dataclasses import dataclass, field -from apcore import ACL, ACLRule, APCore, ExecutionPolicy +from apcore import ACL, ACLRule, APCore, BoundModule, ExecutionPolicy from apcore.acl import AuditEntry from apcore_mcp import APCoreMCP, InMemoryApprovalStore from pydantic import BaseModel @@ -25,7 +25,7 @@ def archive(self, note_id: str) -> ArchiveResult: return ArchiveResult(archived=note_id) -def build_app(notebook: Notebook, audit: list[AuditEntry]) -> APCore: +def build_app(notebook: Notebook, audit: list[AuditEntry]) -> tuple[APCore, BoundModule[[str], ArchiveResult]]: client = APCore(policy=ExecutionPolicy(strict=True, gate_destructive=True)) client.executor.set_acl( ACL( @@ -35,7 +35,7 @@ def build_app(notebook: Notebook, audit: list[AuditEntry]) -> APCore: ) ) - @client.module(ARCHIVE, description="Archive a note", annotations={"destructive": True}) + @client.module(ARCHIVE, description="Archive a note", destructive=True, requires_approval=True) def archive(note_id: str) -> ArchiveResult: return notebook.archive(note_id) @@ -47,7 +47,7 @@ def lookup(note_id: str) -> dict[str, bool]: def restricted() -> dict[str, bool]: raise AssertionError("The ACL must prevent this function from running") - return client + return client, archive def build_mcp(client: APCore, reviews: InMemoryApprovalStore) -> APCoreMCP: diff --git a/examples/python/golden-path/verify.py b/examples/python/golden-path/verify.py index a904b9d6..bae6f7e1 100644 --- a/examples/python/golden-path/verify.py +++ b/examples/python/golden-path/verify.py @@ -7,17 +7,22 @@ from socket import socket import uvicorn -from apcore import APCore +from apcore import APCore, BoundModule from apcore.acl import AuditEntry from apcore.errors import ACLDeniedError, ApprovalPendingError, SchemaValidationError from apcore_mcp import APCoreMCP, InMemoryApprovalStore, StorageBackedApprovalHandler -from app import ARCHIVE, LOOKUP, RESTRICTED, Notebook, build_app, build_mcp +from app import ARCHIVE, LOOKUP, RESTRICTED, ArchiveResult, Notebook, build_app, build_mcp from mcp import ClientSession from mcp.client.streamable_http import streamable_http_client from mcp.types import CallToolResult, TextContent -async def verify_direct(client: APCore, notebook: Notebook, reviews: InMemoryApprovalStore) -> None: +async def verify_direct( + client: APCore, + archive: BoundModule[[str], ArchiveResult], + notebook: Notebook, + reviews: InMemoryApprovalStore, +) -> None: assert await client.call_async(LOOKUP, {"note_id": "from-code"}) == {"archived": False} try: @@ -34,9 +39,8 @@ async def verify_direct(client: APCore, notebook: Notebook, reviews: InMemoryApp else: raise AssertionError("Expected input validation to fail") - arguments = {"note_id": "from-code"} try: - await client.call_async(ARCHIVE, arguments) + await archive.invoke_async("from-code") except ApprovalPendingError as pending: approval_id = pending.result.audit_id resume_token = pending.approval_id @@ -45,8 +49,8 @@ async def verify_direct(client: APCore, notebook: Notebook, reviews: InMemoryApp raise AssertionError("Expected approval to be pending") assert notebook.archived == [] assert await reviews.resolve(approval_id, approved=True) - resumed = await client.call_async(ARCHIVE, {**arguments, "_approval_token": resume_token}) - assert resumed == {"archived": "from-code"} + resumed = await archive.with_approval_token(resume_token).invoke_async("from-code") + assert isinstance(resumed, ArchiveResult) and resumed.archived == "from-code" assert notebook.archived == ["from-code"] @@ -125,13 +129,13 @@ async def main() -> None: notebook = Notebook() audit: list[AuditEntry] = [] async with AsyncExitStack() as cleanup: - direct = build_app(notebook, audit) + direct, archive = build_app(notebook, audit) cleanup.push_async_callback(direct.shutdown) direct_reviews = InMemoryApprovalStore() direct.executor.set_approval_handler(StorageBackedApprovalHandler(direct_reviews)) - await verify_direct(direct, notebook, direct_reviews) + await verify_direct(direct, archive, notebook, direct_reviews) - mcp_client = build_app(notebook, audit) + mcp_client, _ = build_app(notebook, audit) cleanup.push_async_callback(mcp_client.shutdown) mcp_reviews = InMemoryApprovalStore() await verify_mcp(build_mcp(mcp_client, mcp_reviews), notebook, mcp_reviews) diff --git a/examples/rust/golden-path/README.md b/examples/rust/golden-path/README.md new file mode 100644 index 00000000..d7c52b08 --- /dev/null +++ b/examples/rust/golden-path/README.md @@ -0,0 +1,18 @@ +# Rust Golden Path + +`verify.rs` registers a compiled `ModulePack` and shares its executor with the +Rust MCP adapter. The integration test checks tool discovery, direct and +protocol execution, input validation, and the canonical arguments reviewed +by final approval. + +Use the Surface repository's candidate verifier with both Core crate archives. +It stages the test in the MCP crate, enables the macro feature for that run, +and checks that Cargo resolved the unpacked artifacts. + +```sh +cd "$SURFACES_CHECKOUT" +python3 scripts/verify-rust-core-candidate.py mcp "$APCORE_VERSION" \ + --archive "$APCORE_CRATE" \ + --macro-archive "$APCORE_MACRO_CRATE" \ + --typed-example "$APCORE_CHECKOUT/examples/rust/golden-path/verify.rs" +``` diff --git a/examples/rust/golden-path/verify.rs b/examples/rust/golden-path/verify.rs new file mode 100644 index 00000000..c0579f81 --- /dev/null +++ b/examples/rust/golden-path/verify.rs @@ -0,0 +1,151 @@ +use std::sync::{Arc, Mutex}; + +use apcore::{ + APCore, ApprovalHandler, ApprovalRequest, ApprovalResult, Config, Executor, ModuleError, + ModulePack, PolicyEffect, PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict, Registry, +}; +use apcore_mcp::{async_serve, AsyncServeConfig}; +use async_trait::async_trait; +use axum::body::{to_bytes, Body}; +use axum::http::Request; +use axum::Router; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use tower::ServiceExt; + +#[derive(Debug, Deserialize, JsonSchema, PartialEq, Serialize)] +struct Note { + note_id: String, + #[serde(default)] + archived: bool, +} + +/// Look up a note. +#[apcore::module(id = "notes.lookup", readonly = true)] +async fn lookup(note: Note) -> Result { + Ok(note) +} + +const NOTES: ModulePack = ModulePack::new(&[lookup::DECLARATION]); + +#[derive(Debug, Default)] +struct Review(Mutex>); + +#[async_trait] +impl PolicyEvaluator for Review { + async fn evaluate( + &self, + request: &PolicyEvaluationRequest, + ) -> Result { + let decision = if request.arguments["note_id"] == "private" { + PolicyEffect::Deny + } else { + PolicyEffect::RequireApproval + }; + Ok(PolicyVerdict { + decision, + rule_id: None, + }) + } +} + +#[async_trait] +impl ApprovalHandler for Review { + async fn request_approval( + &self, + request: &ApprovalRequest, + ) -> Result { + self.0.lock().unwrap().push(request.arguments.clone()); + Ok(ApprovalResult::approved("example-reviewer")) + } + + async fn check_approval(&self, _: &str) -> Result { + unreachable!("this example returns approval immediately") + } +} + +async fn request(app: &Router, method: &str, params: Value) -> Value { + let request = Request::post("/mcp") + .header("content-type", "application/json") + .body(Body::from( + json!({ + "jsonrpc": "2.0", "id": 1, "method": method, "params": params + }) + .to_string(), + )) + .unwrap(); + let response = app.clone().oneshot(request).await.unwrap(); + assert!(response.status().is_success()); + serde_json::from_slice(&to_bytes(response.into_body(), 65_536).await.unwrap()).unwrap() +} + +#[tokio::test] +async fn typed_pack_and_mcp_use_the_same_governed_executor() { + let config = Config::in_memory(); + let review = Arc::new(Review::default()); + let mut executor = Executor::new(Registry::new(), config.clone()); + executor.set_policy_evaluator(Some(review.clone())).unwrap(); + executor.set_approval_handler_shared(review.clone()); + let core = APCore::with_options(None, Some(executor), Some(config), None); + NOTES.register(&core).unwrap(); + + let available = Note { + note_id: "public".into(), + archived: false, + }; + let expected = serde_json::to_value(&available).unwrap(); + assert_eq!( + lookup::HANDLE + .invoke(&core, available, None) + .await + .unwrap() + .note_id, + "public" + ); + let private = Note { + note_id: "private".into(), + archived: false, + }; + assert!(lookup::HANDLE.invoke(&core, private, None).await.is_err()); + + let app = async_serve( + core.executor_arc(), + AsyncServeConfig { + require_auth: Some(false), + ..Default::default() + }, + ) + .await + .unwrap(); + let listed = request(&app, "tools/list", json!({})).await; + let tools = listed["result"]["tools"].as_array().unwrap(); + let tool = tools + .iter() + .find(|tool| tool["name"] == "notes.lookup") + .unwrap(); + assert_eq!(tool["inputSchema"]["required"], json!(["note_id"])); + let reply = request( + &app, + "tools/call", + json!({ + "name": "notes.lookup", "arguments": {"note_id": "public"}, + }), + ) + .await; + assert_ne!(reply["result"]["isError"], true, "{reply}"); + let text = reply["result"]["content"][0]["text"].as_str().unwrap(); + assert_eq!(serde_json::from_str::(text).unwrap(), expected); + for arguments in [json!({"note_id": "private"}), json!({})] { + let denied = request( + &app, + "tools/call", + json!({ + "name": "notes.lookup", "arguments": arguments, + }), + ) + .await; + assert_eq!(denied["result"]["isError"], true, "{denied}"); + } + assert_eq!(*review.0.lock().unwrap(), vec![expected.clone(), expected]); +} diff --git a/examples/typescript/golden-path/README.md b/examples/typescript/golden-path/README.md new file mode 100644 index 00000000..2977f267 --- /dev/null +++ b/examples/typescript/golden-path/README.md @@ -0,0 +1,21 @@ +# TypeScript Golden Path + +`verify.ts` registers a typed module with `APCore.define`, then calls it +through its typed handle and through an MCP client connected in-process. +The same executor normalizes the arguments, denies private lookups, and +requires approval for public lookups. The example's approval handler is +a test double that records the arguments and immediately returns approval. + +Run this example in an ES module project with compatible `apcore-js` and +`apcore-mcp` packages, `@modelcontextprotocol/sdk`, `zod`, and TypeScript. + +```sh +npx tsc --strict --module NodeNext --target ES2022 --outDir dist verify.ts +node dist/verify.js +``` + +The optional `agent-tool.ts` example requires the `ai` package and +`@types/json-schema` for strict TypeScript builds. Pass it the +same handle and the input schema from `core.getCallableDefinition(lookup.id)`. +Use the returned tool in the `tools` option of your AI SDK call. It invokes the +same executor as the MCP route. [AI SDK tool reference](https://ai-sdk.dev/docs/reference/ai-sdk-core/tool) diff --git a/examples/typescript/golden-path/agent-tool.ts b/examples/typescript/golden-path/agent-tool.ts new file mode 100644 index 00000000..8f442a97 --- /dev/null +++ b/examples/typescript/golden-path/agent-tool.ts @@ -0,0 +1,12 @@ +import { jsonSchema, tool } from 'ai'; +import type { BoundModule } from 'apcore-js'; + +type Note = { noteId: string }; + +export function lookupTool(lookup: BoundModule, wireInputSchema: Record) { + return tool({ + description: 'Look up a note', + inputSchema: jsonSchema(wireInputSchema), + execute: (args) => lookup.invoke(args), + }); +} diff --git a/examples/typescript/golden-path/verify.ts b/examples/typescript/golden-path/verify.ts new file mode 100644 index 00000000..f286c6f0 --- /dev/null +++ b/examples/typescript/golden-path/verify.ts @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { APCore, createApprovalResult, Executor, Registry } from 'apcore-js'; +import { ExecutionRouter, MCPServerFactory } from 'apcore-mcp'; +import { z } from 'zod/v4'; + +const registry = new Registry(); +const approved: unknown[] = []; +const executor = new Executor({ + registry, + policyEvaluator: { + async evaluate({ arguments: args }) { + return { decision: args['noteId'] === 'private' ? 'deny' : 'require_approval' }; + }, + }, + approvalHandler: { + supportsFinalScope: true, + async requestApproval({ arguments: args }) { + approved.push(args['noteId']); + return createApprovalResult({ status: 'approved' }); + }, + async checkApproval() { return createApprovalResult({ status: 'rejected' }); }, + }, +}); +const core = new APCore({ registry, executor }); +let calls = 0; +const lookup = await core.define({ + id: 'notes.lookup', + description: 'Look up a note', + readonly: true, + input: z.object({ noteId: z.string().trim().min(1) }), + output: z.object({ noteId: z.string() }), + execute: ({ noteId }) => { + calls++; + return { noteId }; + }, +}); +const factory = new MCPServerFactory({ richDescription: false }); +const server = factory.createServer(); +const router = new ExecutionRouter({ + registry, + call: executor.call.bind(executor), + getCallableDescriptor: executor.getCallableDescriptor.bind(executor), +}); +factory.registerHandlers(server, factory.buildTools(registry), router); +const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); +const mcp = new Client({ name: 'typed-module-example', version: '1' }); +try { + assert.deepEqual(await lookup.invoke({ noteId: ' public ' }), { noteId: 'public' }); + await assert.rejects(lookup.invoke({ noteId: ' private ' }), { code: 'POLICY_DENIED' }); + await assert.rejects(lookup.invoke({ noteId: ' ' }), { code: 'SCHEMA_VALIDATION_ERROR' }); + await server.connect(serverTransport); + await mcp.connect(clientTransport); + const listed = (await mcp.listTools()).tools.find(tool => tool.name === lookup.id); + assert.deepEqual(listed?.inputSchema.required, ['noteId']); + const good = await mcp.callTool({ name: lookup.id, arguments: { noteId: ' public ' } }); + assert.ok(!good.isError); + assert.deepEqual(good.structuredContent, { noteId: 'public' }); + assert.ok((await mcp.callTool({ name: lookup.id, arguments: { noteId: ' private ' } })).isError); + assert.ok((await mcp.callTool({ name: lookup.id, arguments: { noteId: ' ' } })).isError); + assert.deepEqual(approved, ['public', 'public']); + assert.equal(calls, 2); +} finally { + await mcp.close(); + await server.close(); + await core.shutdown(); +} diff --git a/planning/overview.md b/planning/overview.md index 17f4f563..c4e7d72f 100644 --- a/planning/overview.md +++ b/planning/overview.md @@ -13,6 +13,7 @@ Record lasting specifications, changes, and decisions in the spec, CHANGELOG, an | [Module lifecycle](module-lifecycle/overview.md) | Owned shutdown, detailed removal, and managed reload in Python, TypeScript, and Rust | [Phases A and B complete](module-lifecycle/state.json) | | [APCore project review remediation](apcore-project-review-2026-11-26/overview.md) | Findings 1–8 and 26 across the runtime, wire contracts, observability, and conformance | [9 of 9 complete](apcore-project-review-2026-11-26/state.json) | | [Post-validation policy](post-validation-policy/overview.md) | Argument-value policy and approval binding across Core SDKs and MCP | [Local implementation and verification complete](post-validation-policy/state.json) | +| [Typed module declarations](typed-module-declarations/overview.md) | Governed typed handles, Standard Schema support, compiled Rust packs, and MCP Golden Paths | [Local implementation and verification complete](typed-module-declarations/state.json) | The review remediation restored the fixture inventory before the eight runtime changes. Its verification record covers the combined SDK, fixture, and documentation checks. diff --git a/planning/typed-module-declarations/overview.md b/planning/typed-module-declarations/overview.md new file mode 100644 index 00000000..b6e45423 --- /dev/null +++ b/planning/typed-module-declarations/overview.md @@ -0,0 +1,7 @@ +# Typed Module Declarations + +This milestone follows the merged identity-delegation candidate. The Core baseline is `22d69599089c9053fd9110c8aab1a2ddef3c76d6` and the Surfaces baseline is `46f659f69396402314d5d5a14af481522fa78bcd`. + +The architecture blueprint's declaration and Golden Path work covers a Python `BoundModule`, TypeScript `client.define`, and an optional Rust declaration macro with `TypedHandle` and `ModulePack`. Each declaration registers an ordinary protocol module so existing Core calls and MCP calls enter the same executor. Protocol wire forms, the Context constructor, and existing registration and invocation behavior remain supported. + +The SDK work can proceed in parallel. Shared documentation and artifact-based acceptance depend on the public APIs agreed in [the plan](plan.md). diff --git a/planning/typed-module-declarations/plan.md b/planning/typed-module-declarations/plan.md new file mode 100644 index 00000000..c5ec3916 --- /dev/null +++ b/planning/typed-module-declarations/plan.md @@ -0,0 +1,15 @@ +# Typed Module Declarations Implementation Plan + +## Shared acceptance + +Every typed handle resolves its registered ID through the public client. Verify normal execution, denial before business execution, required approval, and validation through normal Core calls and an MCP client. Any SDK-owned conversion of arguments that changes the values sent to a module must happen before post-validation policy and final-scope approval. + +## SDK declarations + +- Python returns a `ParamSpec`-preserving `BoundModule` from `APCore.module`, with governed sync and async invocation, validation and preview, and a raw testing accessor. Existing direct decorated calls retain their callable behavior. Declaration shortcuts use the existing annotation representation. Preserve native Pydantic values through the existing typed function adapter and decode the governed result. +- TypeScript adds `APCore.define` for Standard Schema v1. Keep schema library adapters structural. Obtain the protocol's Draft 2020-12 JSON Schema through Standard JSON Schema where available, with explicit schema input for validators that supply validation only. Validate normalized values through the governed runtime and preserve the input/output type distinction. +- Rust adds an optional `macros` feature for a sibling `apcore-macros` crate. Generate existing `Module` implementations from typed functions, Doc comments and Draft 2020-12 schemas. Typed handles call the executor and resolve through the registry. A static pack assembles declarations explicitly without global discovery and can be exercised by MCP and CLI consumers. + +## Integration + +Validate no extra runtime dependency in the minimal Python and TypeScript package profiles. In Rust, verify the default feature set and test the optional macro installation from local candidate archives. Use Core and Surfaces source to exercise declaration-driven tool calls and Rust empty-discovery startup behavior. Publish examples through existing documentation and the established Golden Path workflow. diff --git a/planning/typed-module-declarations/state.json b/planning/typed-module-declarations/state.json new file mode 100644 index 00000000..d141448d --- /dev/null +++ b/planning/typed-module-declarations/state.json @@ -0,0 +1,14 @@ +{ + "feature": "typed-module-declarations", + "created": "2026-11-28", + "updated": "2026-11-28", + "status": "completed", + "execution_order": ["python", "typescript", "rust", "verification"], + "progress": { "total_tasks": 4, "completed": 4, "in_progress": 0, "pending": 0 }, + "tasks": [ + { "id": "python", "file": "tasks/python.md", "title": "Python governed module declarations", "status": "completed" }, + { "id": "typescript", "file": "tasks/typescript.md", "title": "TypeScript Standard Schema declarations", "status": "completed" }, + { "id": "rust", "file": "tasks/rust.md", "title": "Rust declaration macro and module pack", "status": "completed" }, + { "id": "verification", "file": "tasks/verification.md", "title": "Installed SDK and Surface verification", "status": "completed", "dependencies": ["python", "typescript", "rust"] } + ] +} diff --git a/planning/typed-module-declarations/tasks/python.md b/planning/typed-module-declarations/tasks/python.md new file mode 100644 index 00000000..403e2b06 --- /dev/null +++ b/planning/typed-module-declarations/tasks/python.md @@ -0,0 +1,3 @@ +# Python + +Extend `APCore.module` with typed handles and annotation shortcuts. Exercise existing callable behavior, governed sync and async execution, validation, preview, input binding and native Pydantic results. Compare direct and registry calls on the same module. diff --git a/planning/typed-module-declarations/tasks/rust.md b/planning/typed-module-declarations/tasks/rust.md new file mode 100644 index 00000000..f0af4b48 --- /dev/null +++ b/planning/typed-module-declarations/tasks/rust.md @@ -0,0 +1,3 @@ +# Rust + +Add optional typed declarations, a governed handle and a static pack. Cover supported signatures and compile-time diagnostics, required governance and default features. Verify locally packaged proc-macro and runtime distributions without publishing. diff --git a/planning/typed-module-declarations/tasks/typescript.md b/planning/typed-module-declarations/tasks/typescript.md new file mode 100644 index 00000000..0e012848 --- /dev/null +++ b/planning/typed-module-declarations/tasks/typescript.md @@ -0,0 +1,3 @@ +# TypeScript + +Add a typed `APCore.define` entry point and structural schema adapter. Validate type inference, registration, schema export, normalization before governance, async validation and unchanged legacy registration. Exercise native JSON Schema conversion and explicit fallback for validation-only providers. diff --git a/planning/typed-module-declarations/tasks/verification.md b/planning/typed-module-declarations/tasks/verification.md new file mode 100644 index 00000000..2d9c0f90 --- /dev/null +++ b/planning/typed-module-declarations/tasks/verification.md @@ -0,0 +1,27 @@ +# Verification + +Run the three SDK regression suites, documentation checks and installed-package examples. For each supported declaration, exercise the same module by typed call and MCP. Check a compiled pack through MCP and empty directory backends through both Rust binaries. Record tested candidates and any compatibility boundaries. + +Local validation on 2026-11-28 used the Core alpha.6 wheel, npm tarball, and +two Rust crates. Python passed 6,748 SDK tests. TypeScript passed 5,955 SDK +tests with 90.53% branch coverage. Rust 1.86 passed 3,271 full workspace tests +and 522 default-profile tests. Strict MkDocs and the installed typed examples +passed. + +The installed candidate passed the Toolkit, MCP, A2A, and CLI test suites in +all three languages. The Python Golden Path exercised approval resumption and +an ACL denial over a real HTTP MCP session. TypeScript and Rust verified +direct and MCP results, invalid input, policy denial, and final approval +arguments. The Rust binary tests checked stderr diagnostics for an empty +directory backend. The Python Agents SDK and TypeScript AI SDK bridges ran +local tool calls using the governed handles. + +The candidate workflow stages dependency overrides for compatibility tests. +GitHub CI and review follow when the candidate branches are opened. + +PR review added regression coverage for native Python inputs and replaced +TypeScript registrations. Python passed 6,750 tests, including rejection of +ambiguous native argument projections before hosted policy evaluates. +TypeScript passed 5,959 tests, including replacement before lookup, before +dispatch, and during preflight. Ordinary ID-based calls still resolve the +current registration. diff --git a/python/apcore-conformance.yaml b/python/apcore-conformance.yaml index c6cf5bd3..9b613b7b 100644 --- a/python/apcore-conformance.yaml +++ b/python/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-python - version: 1.0.0a5 + version: 1.0.0a6 language: python spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/python/pyproject.toml b/python/pyproject.toml index 8f0d57dd..be5ba33d 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "apcore" -version = "1.0.0a5" +version = "1.0.0a6" description = "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call" readme = "README.md" requires-python = ">=3.11" diff --git a/python/src/apcore/__init__.py b/python/src/apcore/__init__.py index 9f150bf7..58b4a565 100644 --- a/python/src/apcore/__init__.py +++ b/python/src/apcore/__init__.py @@ -52,6 +52,7 @@ ) from apcore.registry.registry import Discoverer, ModuleValidator from apcore.client import APCore +from apcore.bound_module import AsyncBoundModule, BoundModule from apcore.lifecycle import ( DrainAbortedContext, DrainContext, @@ -481,23 +482,9 @@ def module( APCore.module() — it is an intentional escape hatch that lets global-decorator usage target a specific Registry instance rather than the default one. """ - if registry is not None: - from apcore.decorator import module as original_module - - return original_module( - id=id, - description=description, - documentation=documentation, - annotations=annotations, - tags=tags, - version=version, - metadata=metadata, - display=display, - examples=examples, - registry=registry, - resources=resources, - ) - return _get_default_client().module( + from apcore.decorator import module as original_module + + return original_module( id=id, description=description, documentation=documentation, @@ -507,6 +494,7 @@ def module( metadata=metadata, display=display, examples=examples, + registry=_get_default_client().registry if registry is None else registry, resources=resources, ) @@ -597,12 +585,14 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "ACL", "ACLRule", "APCore", + "AsyncBoundModule", "ApprovalDeniedError", "ApprovalHandler", "ApprovalPendingError", "ApprovalRequest", "ApprovalResult", "AutoApproveHandler", + "BoundModule", "CancelToken", "AccessHint", "CallableDefinition", diff --git a/python/src/apcore/_post_validation_policy.py b/python/src/apcore/_post_validation_policy.py index 76252b56..e03a23af 100644 --- a/python/src/apcore/_post_validation_policy.py +++ b/python/src/apcore/_post_validation_policy.py @@ -11,11 +11,17 @@ import time from contextlib import suppress from copy import copy, deepcopy -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Annotated, get_args, get_origin +from uuid import UUID, SafeUUID + +from pydantic import AliasPath, BaseModel, RootModel +from pydantic.fields import FieldInfo from apcore.errors import PolicyEvaluationError from apcore.context import _APPROVAL_TOKEN_KEY +from apcore.decorator import FunctionModule from apcore.policy import PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict +from apcore.utils.module_output import _validation_property_name if TYPE_CHECKING: from apcore.cancel import CancelToken @@ -55,6 +61,61 @@ def _argument_digest(arguments: dict[str, Any]) -> str: return hashlib.sha256(encoded).hexdigest() +def _project_function_model(value: BaseModel) -> Any: + fields = type(value).model_fields + extras = value.model_extra or {} + stored = vars(value) + # A detached JSON object cannot preserve private state or whether a field + # equal to its default was actually supplied. + if ( + value.__pydantic_private__ + or stored.keys() != fields.keys() + or value.model_fields_set != fields.keys() | extras.keys() + ): + raise PolicyEvaluationError() + if isinstance(value, RootModel): + return _project_function_value(stored["root"], fields["root"].annotation) + projected = {key: _project_function_value(item, Any) for key, item in extras.items()} + for name, field in fields.items(): + if isinstance(field.validation_alias, AliasPath): + raise PolicyEvaluationError() + wire_name = _validation_property_name(name, field.validation_alias, name) + if wire_name in projected: + raise PolicyEvaluationError() + projected[wire_name] = _project_function_value(stored[name], field.annotation) + return projected + + +def _project_function_value(value: Any, annotation: Any) -> Any: + """Project native values only at paths where the declaration fixes their type.""" + if get_origin(annotation) is Annotated: + annotation = get_args(annotation)[0] + if annotation is UUID or type(value) is UUID: + if annotation is not UUID or type(value) is not UUID or value.is_safe is not SafeUUID.unknown: + raise PolicyEvaluationError() + return str(value) + model_type = isinstance(annotation, type) and issubclass(annotation, BaseModel) + if model_type or isinstance(value, BaseModel): + if not model_type or type(value) is not annotation: + raise PolicyEvaluationError() + return _project_function_model(value) + parameters = get_args(annotation) + if type(value) is dict: + item_type = parameters[1] if get_origin(annotation) is dict and parameters else Any + return {key: _project_function_value(item, item_type) for key, item in value.items()} + if type(value) is list: + item_type = parameters[0] if get_origin(annotation) is list and parameters else Any + return [_project_function_value(item, item_type) for item in value] + return value + + +def _project_function_arguments(arguments: dict[str, Any], fields: dict[str, FieldInfo]) -> dict[str, Any]: + return { + name: _project_function_value(value, fields[name].annotation if name in fields else Any) + for name, value in arguments.items() + } + + class _PolicyInvocation: """Record the selected invocation before middleware or provider callbacks.""" @@ -70,6 +131,8 @@ def __init__(self, ctx: PipelineContext, version: str | None) -> None: except Exception: raise PolicyEvaluationError() from None self.arguments: dict[str, Any] | None = None + self._native_arguments: dict[str, Any] | None = None + self._function_fields: dict[str, FieldInfo] | None = None self.digest: str | None = None self.authorized = False @@ -77,8 +140,23 @@ def capture(self, ctx: PipelineContext) -> None: arguments = ctx.validated_inputs if arguments is None or _APPROVAL_TOKEN_KEY in arguments: raise PolicyEvaluationError() - self.digest = _argument_digest(arguments) - self.arguments = deepcopy(arguments) + try: + if isinstance(self.module, FunctionModule): + self._function_fields = dict(getattr(self.module.input_schema, "model_fields", {})) + projected = _project_function_arguments(arguments, self._function_fields) + self.digest = _argument_digest(projected) + self._native_arguments = deepcopy(arguments) + if ( + _argument_digest(_project_function_arguments(self._native_arguments, self._function_fields)) + != self.digest + ): + raise PolicyEvaluationError() + self.arguments = projected + else: + self.digest = _argument_digest(arguments) + self.arguments = deepcopy(arguments) + except Exception: + raise PolicyEvaluationError() from None def _check_binding(self, ctx: PipelineContext) -> None: identity = ctx.context.identity @@ -91,17 +169,27 @@ def _check_binding(self, ctx: PipelineContext) -> None: ): raise PolicyEvaluationError() - def checked_arguments(self, ctx: PipelineContext) -> dict[str, Any]: + def checked_arguments(self, ctx: PipelineContext, *, dispatch: bool = False) -> dict[str, Any]: self._check_binding(ctx) capture = deepcopy(self.arguments) + current = ctx.validated_inputs + if self._function_fields is not None: + try: + if current is None or current != self._native_arguments: + raise PolicyEvaluationError() + current = _project_function_arguments(current, self._function_fields) + except Exception: + raise PolicyEvaluationError() from None if ( - ctx.validated_inputs is None + current is None or capture is None or self.digest is None - or _argument_digest(ctx.validated_inputs) != self.digest + or _argument_digest(current) != self.digest or _argument_digest(capture) != self.digest ): raise PolicyEvaluationError() + if dispatch and self._native_arguments is not None: + return self._native_arguments return capture def preflight_snapshot(self, ctx: PipelineContext) -> tuple[dict[str, Any], Context[Any]]: diff --git a/python/src/apcore/bound_module.py b/python/src/apcore/bound_module.py new file mode 100644 index 00000000..1f614fb4 --- /dev/null +++ b/python/src/apcore/bound_module.py @@ -0,0 +1,218 @@ +"""Typed operations on functions registered with :meth:`APCore.module`.""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable, Coroutine +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, Self, TypeVar, get_origin, get_type_hints, overload + +from pydantic import BaseModel, TypeAdapter +from pydantic_core import PydanticSerializationError, to_json + +from apcore.context import Context, _APPROVAL_TOKEN_KEY +from apcore.decorator import FunctionModule, _context_param_name, _forward_function +from apcore.module import PreflightResult, PreviewResult + +if TYPE_CHECKING: + from apcore.client import APCore + +P = ParamSpec("P") +R = TypeVar("R", covariant=True) +T = TypeVar("T") + + +class _GovernedModule(Protocol[P, R]): + @property + def apcore_module(self) -> FunctionModule: + """The registered module, including its introspection metadata.""" + ... + + @property + def __name__(self) -> str: ... + + def invoke(self, *args: P.args, **kwargs: P.kwargs) -> R: + """Execute a call through the client and return its typed result.""" + ... + + async def invoke_async(self, *args: P.args, **kwargs: P.kwargs) -> R: + """Execute a governed call on the current event loop.""" + ... + + def validate(self, *args: P.args, **kwargs: P.kwargs) -> PreflightResult: + """Run the client's preflight checks.""" + ... + + async def validate_async(self, *args: P.args, **kwargs: P.kwargs) -> PreflightResult: ... + + def preview(self, *args: P.args, **kwargs: P.kwargs) -> PreviewResult: + """Return the changes disclosed by the client's preflight checks.""" + ... + + async def preview_async(self, *args: P.args, **kwargs: P.kwargs) -> PreviewResult: ... + + def with_context(self, context: Context[Any]) -> Self: + """Bind a context to governed operations without changing the function's signature.""" + ... + + def with_approval_token(self, token: str) -> Self: + """Pass a resumption token to the governed invocation's approval gate.""" + ... + + +class BoundModule(_GovernedModule[P, R], Protocol[P, R]): + """A registered sync function with typed governed operations and raw access.""" + + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... + + @property + def raw(self) -> Callable[P, R]: + """The original callable for direct execution.""" + ... + + +class AsyncBoundModule(_GovernedModule[P, R], Protocol[P, R]): + """A registered async function whose governed calls return its resolved type.""" + + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Coroutine[Any, Any, R]: ... + + @property + def raw(self) -> Callable[P, Coroutine[Any, Any, R]]: + """The original coroutine function for direct execution.""" + ... + + +class _BoundModuleDecorator(Protocol): + @overload + def __call__(self, func: Callable[P, Coroutine[Any, Any, T]], /) -> AsyncBoundModule[P, T]: ... + + @overload + def __call__(self, func: Callable[P, T], /) -> BoundModule[P, T]: ... + + +@dataclass(frozen=True) +class _Invocation: + client: APCore + module_id: str + context: Context[Any] | None + approval_token: str | None + signature: inspect.Signature + context_parameter: str | None + return_type: Any + return_adapter: TypeAdapter[Any] + + def arguments(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> tuple[dict[str, Any], Context[Any] | None]: + bound = self.bind(args, kwargs) + context = self.context + inputs: dict[str, Any] = {} + extras: dict[str, Any] = {} + for name, value in bound.arguments.items(): + kind = self.signature.parameters[name].kind + if name == self.context_parameter: + if not isinstance(value, Context): + raise TypeError(f"{name!r} must be an apcore Context") + if context is not None and context is not value: + raise TypeError("The function argument and bound invocation provide different contexts") + context = value + elif kind == inspect.Parameter.VAR_POSITIONAL: + raise TypeError("Variadic positional arguments cannot be represented as module inputs") + elif kind == inspect.Parameter.VAR_KEYWORD: + extras = value + else: + inputs[name] = value + if inputs.keys() & extras.keys(): + raise TypeError("A positional argument and a keyword extra cannot use the same module input name") + inputs.update(extras) + if self.approval_token is not None: + if _APPROVAL_TOKEN_KEY in inputs: + raise TypeError("An approval token is already present in the module inputs") + inputs[_APPROVAL_TOKEN_KEY] = self.approval_token + return inputs, context + + def bind(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> inspect.BoundArguments: + if self.context_parameter is None: + return self.signature.bind(*args, **kwargs) + try: + bound = self.signature.bind(*args, **kwargs) + except TypeError: + if self.context_parameter in kwargs: + raise + else: + if self.context_parameter not in bound.arguments or isinstance( + bound.arguments[self.context_parameter], Context + ): + return bound + if self.context_parameter in kwargs: + return bound + parameters = [p for name, p in self.signature.parameters.items() if name != self.context_parameter] + return self.signature.replace(parameters=parameters).bind(*args, **kwargs) + + def result(self, output: dict[str, Any]) -> Any: + if self.return_type is type(None): + return None + object_result = self.return_type is dict or get_origin(self.return_type) is dict + model_result = isinstance(self.return_type, type) and issubclass(self.return_type, BaseModel) + payload = output if object_result or model_result else output["result"] + try: + encoded = to_json(payload) + except PydanticSerializationError: + return self.return_adapter.validate_python(payload) + return self.return_adapter.validate_json(encoded) + + def invoke(self, *args: Any, **kwargs: Any) -> Any: + inputs, context = self.arguments(args, kwargs) + return self.result(self.client.call(self.module_id, inputs, context)) + + async def invoke_async(self, *args: Any, **kwargs: Any) -> Any: + inputs, context = self.arguments(args, kwargs) + return self.result(await self.client.call_async(self.module_id, inputs, context)) + + def validate(self, *args: Any, **kwargs: Any) -> PreflightResult: + inputs, context = self.arguments(args, kwargs) + return self.client.validate(self.module_id, inputs, context) + + async def validate_async(self, *args: Any, **kwargs: Any) -> PreflightResult: + inputs, context = self.arguments(args, kwargs) + return await self.client.validate_async(self.module_id, inputs, context) + + def preview(self, *args: Any, **kwargs: Any) -> PreviewResult: + return PreviewResult(changes=self.validate(*args, **kwargs).predicted_changes) + + async def preview_async(self, *args: Any, **kwargs: Any) -> PreviewResult: + result = await self.validate_async(*args, **kwargs) + return PreviewResult(changes=result.predicted_changes) + + +def _bind_module(client: APCore, func: Callable[..., Any], module: FunctionModule) -> Callable[..., Any]: + signature = inspect.signature(func) + context_parameter = _context_param_name(func) + return_type = get_type_hints(func, include_extras=True)["return"] + return_adapter: TypeAdapter[Any] = TypeAdapter(return_type) + + def bind(context: Context[Any] | None, approval_token: str | None) -> Callable[..., Any]: + invocation = _Invocation( + client, module.module_id, context, approval_token, signature, context_parameter, return_type, return_adapter + ) + + def with_context(context: Context[Any]) -> Callable[..., Any]: + return bind(context, approval_token) + + def with_approval_token(token: str) -> Callable[..., Any]: + return bind(context, token) + + wrapped = _forward_function(func) + wrapped.__dict__.update( + apcore_module=module, + raw=func, + invoke=invocation.invoke, + invoke_async=invocation.invoke_async, + validate=invocation.validate, + validate_async=invocation.validate_async, + preview=invocation.preview, + preview_async=invocation.preview_async, + with_context=with_context, + with_approval_token=with_approval_token, + ) + return wrapped + + return bind(None, None) diff --git a/python/src/apcore/builtin_steps.py b/python/src/apcore/builtin_steps.py index 48a786cd..c89ff6ec 100644 --- a/python/src/apcore/builtin_steps.py +++ b/python/src/apcore/builtin_steps.py @@ -1547,7 +1547,7 @@ async def execute(self, ctx: PipelineContext) -> StepResult: invocation = ctx._policy_invocation if invocation is None or not invocation.authorized: raise PolicyEvaluationError() - inputs = invocation.checked_arguments(ctx) + inputs = invocation.checked_arguments(ctx, dispatch=True) else: inputs = ctx.validated_inputs if ctx.validated_inputs is not None else ctx.inputs diff --git a/python/src/apcore/client.py b/python/src/apcore/client.py index 3b8c40af..a7b497f3 100644 --- a/python/src/apcore/client.py +++ b/python/src/apcore/client.py @@ -15,18 +15,20 @@ from __future__ import annotations import asyncio +import dataclasses import logging import threading from datetime import datetime, timezone -from collections.abc import AsyncGenerator, Callable as CallableABC, Iterable +from collections.abc import AsyncGenerator, Awaitable, Callable as CallableABC, Iterable from contextlib import aclosing -from typing import Any, Callable +from typing import Any, Callable, cast +from apcore.bound_module import _BoundModuleDecorator, _bind_module from apcore.capabilities import CallableDefinition, CapabilityPage, CapabilitySearchProvider from apcore.config import Config from apcore.context import Context from apcore.errors import InvalidInputError, SysModulesDisabledError -from apcore.decorator import module as decorator_module +from apcore.decorator import FunctionModule, _make_auto_id from apcore.events.emitter import ApCoreEvent, EventEmitter, EventSubscriber from apcore.events.factory import SubscriberRegistry from apcore.executor import Executor @@ -40,7 +42,7 @@ _validate_drain_options, _validate_duration, ) -from apcore.module import PreflightResult +from apcore.module import ModuleAnnotations, ModuleExample, PreflightResult, PreviewResult from apcore.policy import ExecutionPolicy from apcore.observability.metrics import MetricsCollector from apcore.registry import Registry @@ -215,18 +217,23 @@ def module( id: str | None = None, # noqa: A002 description: str | None = None, documentation: str | None = None, - annotations: dict[str, Any] | None = None, + annotations: ModuleAnnotations | dict[str, Any] | None = None, tags: list[str] | None = None, version: str = "1.0.0", metadata: dict[str, Any] | None = None, display: dict[str, Any] | None = None, - examples: list[Any] | None = None, + examples: list[ModuleExample] | None = None, *, resources: dict[str, Any] | None = None, - ) -> Callable: + destructive: bool | None = None, + requires_approval: bool | None = None, + preview: Callable[[dict[str, Any], Context[Any]], PreviewResult | Awaitable[PreviewResult]] | None = None, + ) -> _BoundModuleDecorator: """Decorator to register a function as a module in this client's registry. ``resources["timeout"]`` sets the module's execution budget in milliseconds. + Use ``invoke`` for governed execution and ``raw`` for direct execution. + Calling the decorated function directly retains its original behavior. Usage: @client.module(id="math.add") @@ -234,23 +241,38 @@ def add(a: int, b: int) -> int: return a + b """ - def decorator(func: Callable) -> Callable: - inner = decorator_module( - id=id, + def decorator(func: Callable[..., Any], /) -> Callable[..., Any]: + flags = { + key: value + for key, value in (("destructive", destructive), ("requires_approval", requires_approval)) + if value is not None + } + if not flags: + merged_annotations = annotations + elif isinstance(annotations, ModuleAnnotations): + merged_annotations = dataclasses.replace(annotations, **flags) + else: + merged_annotations = {**(annotations or {}), **flags} + module_id = id if id is not None else _make_auto_id(func) + module = FunctionModule( + func=func, + module_id=module_id, description=description, documentation=documentation, - annotations=annotations, + annotations=merged_annotations, tags=tags, version=version, metadata=metadata, display=display, examples=examples, - registry=self.registry, resources=resources, + preview=preview, ) - return inner(func) + bound = _bind_module(self, func, module) + self.registry.register(module_id, module) + return bound - return decorator + return cast(_BoundModuleDecorator, decorator) def register(self, module_id: str, module_obj: Any) -> None: """Register a module object directly. diff --git a/python/src/apcore/decorator.py b/python/src/apcore/decorator.py index 8f7f76a9..a04e430e 100644 --- a/python/src/apcore/decorator.py +++ b/python/src/apcore/decorator.py @@ -8,6 +8,7 @@ import logging import re import typing +from collections.abc import Awaitable from typing import Annotated, Any, Callable, get_args, get_origin from pydantic import BaseModel, ConfigDict, Field, create_model @@ -16,7 +17,7 @@ from apcore._docstrings import parse_docstring from apcore.context import Context from apcore.errors import ErrorCodes, FuncMissingReturnTypeError, FuncMissingTypeHintError, InvalidInputError -from apcore.module import ModuleAnnotations, ModuleExample +from apcore.module import ModuleAnnotations, ModuleExample, PreviewResult from apcore.utils.module_output import normalize_module_output _logger = logging.getLogger(__name__) @@ -80,7 +81,7 @@ def generate_input_model( annotation = hints[param_name] # Skip Context-typed parameters - if annotation is Context: + if annotation is Context or get_origin(annotation) is Context: continue # Inject docstring description if no explicit Field(description=...) exists @@ -148,7 +149,7 @@ def _context_param_name(func: Any) -> str | None: for param_name, hint in hints.items(): if param_name == "return": continue - if hint is Context: + if hint is Context or get_origin(hint) is Context: return param_name return None @@ -180,13 +181,15 @@ def __init__( documentation: str | None = None, tags: list[str] | None = None, version: str = "1.0.0", - annotations: dict[str, Any] | None = None, + annotations: ModuleAnnotations | dict[str, Any] | None = None, metadata: dict[str, Any] | None = None, display: dict[str, Any] | None = None, examples: list[ModuleExample] | None = None, input_schema: type[BaseModel] | None = None, output_schema: type[BaseModel] | None = None, resources: dict[str, Any] | None = None, + *, + preview: Callable[[dict[str, Any], Context[Any]], PreviewResult | Awaitable[PreviewResult]] | None = None, ) -> None: self._func = func self.module_id = module_id @@ -230,6 +233,8 @@ def __init__( # reads ``resources["timeout"]`` in milliseconds and uses it instead of # ``executor.default_timeout`` for this module. self.resources = resources + if preview is not None: + self.preview = preview def call_arguments(inputs: dict[str, Any], context: Context) -> tuple[list[Any], dict[str, Any]]: kwargs = dict(inputs) @@ -284,6 +289,11 @@ def _attribute_host(func: Callable) -> Callable: """ if not inspect.ismethod(func): return func + return _forward_function(func) + + +def _forward_function(func: Callable[..., Any]) -> Callable[..., Any]: + """Create a separate callable while preserving metadata and async behavior.""" if inspect.iscoroutinefunction(func): @functools.wraps(func) diff --git a/python/tests/test_bound_module.py b/python/tests/test_bound_module.py new file mode 100644 index 00000000..7e1b423c --- /dev/null +++ b/python/tests/test_bound_module.py @@ -0,0 +1,264 @@ +"""Public typed declaration tests through the stock client and executor.""" + +from __future__ import annotations + +from inspect import iscoroutinefunction, signature +from typing import Annotated, Any, Literal, assert_type +from uuid import UUID + +import pytest +from pydantic import BaseModel, ConfigDict, Field + +from apcore import ( + ACL, + ACLRule, + APCore, + ApprovalRequest, + ApprovalResult, + AutoApproveHandler, + Context, + Executor, + Identity, + PolicyEvaluationRequest, + PolicyVerdict, + PreflightResult, + PreviewResult, + Registry, +) +from apcore.errors import ( + ACLDeniedError, + ApprovalDeniedError, + ApprovalPendingError, + PolicyDeniedError, + PolicyEvaluationError, + SchemaValidationError, +) +from apcore.module import Change + + +class Order(BaseModel): + model_config = ConfigDict(strict=True) + id: UUID = Field(alias="order_id") + + +class Receipt(BaseModel): + order: Order + quantity: int + + +class NativePayload(BaseModel): + value: Annotated[str | UUID, Field(union_mode="left_to_right")] + + +def test_bound_module_preserves_native_results_and_callable_metadata() -> None: + client = APCore() + + def save(order: Order, /, quantity: int = 1, *, multiplier: int = 2) -> Receipt: + """Save an order.""" + assert isinstance(order, Order) + return Receipt(order=order, quantity=quantity * multiplier) + + bound = client.module("orders.save")(save) + order = Order(order_id=UUID("23416db0-3d95-44b0-8072-578bed43391a")) + expected = Receipt(order=order, quantity=3) + + assert assert_type(bound.invoke(order, multiplier=3), Receipt) == expected + assert assert_type(bound.raw(order, multiplier=3), Receipt) == expected + assert bound(order, multiplier=3) == expected + assert bound.__name__ == save.__name__ + assert bound.__doc__ == save.__doc__ + assert signature(bound) == signature(save) + assert bound.apcore_module is client.registry.get("orders.save") + assert client.call("orders.save", {"order": {"order_id": str(order.id)}, "multiplier": 3}) == { + "order": {"order_id": str(order.id)}, + "quantity": 3, + } + + with pytest.raises(TypeError): + bound.invoke(order=order) # type: ignore[call-arg] + with pytest.raises(SchemaValidationError): + bound.invoke(order, quantity="2") # type: ignore[arg-type] + + +def test_bound_module_keeps_the_native_union_branch() -> None: + client = APCore() + + @client.module("payload.classify") + def classify(payload: NativePayload) -> str: + return type(payload.value).__name__ + + value = UUID("23416db0-3d95-44b0-8072-578bed43391a") + payload = NativePayload(value=value) + assert classify.raw(payload) == "UUID" + assert client.call("payload.classify", {"payload": payload}) == {"result": "UUID"} + assert classify.invoke(payload) == "UUID" + assert classify.invoke(NativePayload(value=str(value))) == "str" + + +def test_final_policy_rejects_a_native_union_branch_with_a_colliding_json_projection() -> None: + calls: list[dict[str, Any]] = [] + + class Evaluator: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + calls.append(request.arguments) + return PolicyVerdict("allow") + + client = APCore(executor=Executor(Registry(), policy_evaluator=Evaluator())) + + @client.module("payload.classify") + def classify(payload: NativePayload) -> str: + return type(payload.value).__name__ + + value = UUID("23416db0-3d95-44b0-8072-578bed43391a") + assert classify.invoke(NativePayload(value=str(value))) == "str" + calls.clear() + payload = NativePayload(value=value) + preflight = classify.validate(payload) + assert [error["code"] for error in preflight.errors] == ["POLICY_EVALUATION_ERROR"] + with pytest.raises(PolicyEvaluationError): + client.call("payload.classify", {"payload": payload}) + with pytest.raises(PolicyEvaluationError): + classify.invoke(payload) + assert calls == [] + + +def test_bound_module_routes_acl_approval_and_preview_through_executor() -> None: + executor = Executor(Registry()) + client = APCore(executor=executor) + executions: list[int] = [] + previews: list[int] = [] + + def preview(inputs: dict[str, Any], context: Context[Any]) -> PreviewResult: + assert context.identity is not None and context.identity.type == "system" + previews.append(inputs["quantity"]) + return PreviewResult(changes=[Change(action="update", target="inventory", summary="Update the quantity")]) + + @client.module("inventory.update", destructive=True, requires_approval=True, preview=preview) + def update(quantity: int) -> int: + executions.append(quantity) + return quantity + + executor.set_acl(ACL([ACLRule(callers=["@system"], targets=["inventory.update"], effect="allow")])) + assert not update.validate(3).valid + assert update.preview(3).changes == [] + with pytest.raises(ACLDeniedError): + update.invoke(3) + assert previews == executions == [] + + context: Context[Any] = Context.create(identity=Identity(id="stock-system", type="system")) + authorized = update.with_context(context) + validation = assert_type(authorized.validate(quantity=3), PreflightResult) + assert validation.valid and validation.requires_approval + assert [change.summary for change in authorized.preview(3).changes] == ["Update the quantity"] + assert previews == [3, 3] + with pytest.raises(ApprovalDeniedError): + authorized.invoke(3) + assert executions == [] + + executor.set_approval_handler(AutoApproveHandler()) + assert authorized.invoke(3) == 3 + assert update.raw(4) == 4 + assert executions == [3, 4] + + +async def test_async_bound_method_preserves_raw_awaitability_and_governed_result() -> None: + client = APCore() + + class Greeter: + prefix = "hello" + + async def greet(self, name: str, **labels: str) -> str: + return f"{self.prefix}, {labels['title']} {name}" + + greet = client.module("greet.person")(Greeter().greet) + + assert iscoroutinefunction(greet) + assert await greet("Ada", title="Dr") == "hello, Dr Ada" + assert await greet.raw("Ada", title="Dr") == "hello, Dr Ada" + assert assert_type(await greet.invoke_async("Ada", title="Dr"), str) == "hello, Dr Ada" + assert (await greet.validate_async("Ada", title="Dr")).valid + assert (await greet.preview_async("Ada", title="Dr")).changes == [] + + +def test_multiple_bindings_of_same_function_keep_independent_clients() -> None: + first = APCore(executor=Executor(Registry(), acl=ACL())) + second = APCore() + + def get() -> int: + return 1 + + blocked = first.module("test.get")(get) + allowed = second.module("test.get")(get) + + with pytest.raises(ACLDeniedError): + blocked.invoke() + assert allowed.invoke() == 1 + assert blocked() == 1 + + +def test_bound_module_injects_typed_context_outside_the_input_schema() -> None: + client = APCore() + + @client.module("test.identify") + def identify(context: Context[Any], /, fallback: str = "anonymous") -> str: + return context.identity.id if context.identity is not None else fallback + + context: Context[Any] = Context.create(identity=Identity(id="operator")) + assert identify.invoke(context) == "operator" + assert identify.invoke(fallback="guest") == "guest" # type: ignore[call-arg] + assert identify.with_context(context).invoke() == "operator" # type: ignore[call-arg] + assert identify.raw(context) == "operator" + assert client.call("test.identify", {}) == {"result": "anonymous"} + + +@pytest.mark.asyncio +async def test_bound_module_reuses_the_final_policy_and_approval_snapshot() -> None: + order = Order(order_id=UUID("23416db0-3d95-44b0-8072-578bed43391a")) + expected = {"order": {"order_id": str(order.id)}, "quantity": 3} + decisions: list[str] = [] + invocations: list[Receipt] = [] + + class Evaluator: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + decision: Literal["require_approval", "deny"] = ( + "require_approval" if request.arguments == expected else "deny" + ) + decisions.append(decision) + return PolicyVerdict(decision) + + class Handler: + supports_final_scope = True + digest: str | None = None + + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: + assert request.arguments == expected + self.digest = request.canonical_args_digest + assert self.digest is not None + return ApprovalResult("pending", approval_id="pending-1") + + async def check_approval(self, approval_id: str) -> ApprovalResult: + raise AssertionError("Final approval requires a scoped check") + + async def check_approval_for_call(self, approval_id: str, request: ApprovalRequest) -> ApprovalResult: + assert request.arguments == expected + assert request.canonical_args_digest == self.digest + return ApprovalResult("approved" if approval_id == "pending-1" else "rejected") + + client = APCore(executor=Executor(Registry(), policy_evaluator=Evaluator(), approval_handler=Handler())) + + @client.module("orders.process", destructive=True) + def process(order: Order, quantity: int) -> Receipt: + result = Receipt(order=order, quantity=quantity) + invocations.append(result) + return result + + assert (await process.validate_async(order, 3)).requires_approval + with pytest.raises(PolicyDeniedError): + await process.invoke_async(order, 4) + with pytest.raises(ApprovalPendingError) as pending: + await process.invoke_async(order, 3) + assert invocations == [] + assert pending.value.approval_id == "pending-1" + receipt = await process.with_approval_token(pending.value.approval_id).invoke_async(order, 3) + assert invocations == [receipt] == [Receipt(order=order, quantity=3)] + assert decisions == ["require_approval", "deny", "require_approval", "require_approval"] diff --git a/python/tests/test_public_api.py b/python/tests/test_public_api.py index f05db9a9..b3bdf7ff 100644 --- a/python/tests/test_public_api.py +++ b/python/tests/test_public_api.py @@ -448,12 +448,14 @@ class TestPublicAPIAll: "ACL", "ACLRule", "APCore", + "AsyncBoundModule", "ApprovalDeniedError", "ApprovalHandler", "ApprovalPendingError", "ApprovalRequest", "ApprovalResult", "AutoApproveHandler", + "BoundModule", "CancelToken", "AccessHint", "CallableDefinition", diff --git a/python/uv.lock b/python/uv.lock index a2dbcb2c..aa69082c 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -199,7 +199,7 @@ wheels = [ [[package]] name = "apcore" -version = "1.0.0a5" +version = "1.0.0a6" source = { editable = "." } dependencies = [ { name = "jsonschema" }, diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 4e08a693..da10e69c 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -42,8 +42,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.5" +version = "1.0.0-alpha.6" dependencies = [ + "apcore-macros", "async-stream", "async-trait", "chrono", @@ -72,6 +73,16 @@ dependencies = [ "uuid", ] +[[package]] +name = "apcore-macros" +version = "1.0.0-alpha.6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "trybuild", +] + [[package]] name = "async-stream" version = "0.3.6" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index accfa234..1cca036c 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore" -version = "1.0.0-alpha.5" +version = "1.0.0-alpha.6" edition = "2021" # Minimum supported Rust version. Verified with `cargo +1.86 check --all-features`. # The binding language constraint is `std::task::Waker::noop()` (used by the @@ -34,6 +34,9 @@ categories = [ all-features = true rustdoc-args = ["--cfg", "docsrs"] +[workspace] +members = ["apcore-macros"] + # The consolidated integration-test binary for all files that don't touch # process-global state (autotests disabled above). [[test]] @@ -45,6 +48,11 @@ required-features = ["config", "discovery", "events-file", "sys-modules"] name = "core_profile" path = "tests/core_profile.rs" +[[test]] +name = "typed_modules" +path = "tests/typed_modules.rs" +required-features = ["macros"] + # Files that register into the process-global Config namespace registry or # mutate env vars are kept as SEPARATE binaries so each runs in its own process # — one binary would cross-pollute their global state and break `cargo test`. @@ -148,6 +156,7 @@ path = "tests/test_otlp_proxy_routing.rs" required-features = ["events"] [dependencies] +apcore-macros = { version = "=1.0.0-alpha.6", path = "apcore-macros", optional = true } tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"] } serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -181,6 +190,7 @@ config = ["dep:serde_yaml_ng"] discovery = ["config", "dep:notify"] events = ["reqwest", "dep:h2", "dep:url"] events-file = ["tokio/fs", "tokio/io-util"] +macros = ["dep:apcore-macros"] sys-modules = ["config"] full = ["config", "discovery", "events", "events-file", "sys-modules"] diff --git a/rust/README.md b/rust/README.md index a653aef4..64407655 100644 --- a/rust/README.md +++ b/rust/README.md @@ -141,7 +141,8 @@ watching, YAML loading, and network delivery are opt-in. | `sys-modules` | Configured system modules and event setup | | `events` | HTTP webhook delivery and OTLP transport | | `events-file` | JSONL event subscribers | -| `full` | All of the above | +| `full` | All runtime integrations above | +| `macros` | Typed module declarations and governed handles | Use `APCore::with_config` or `APCore::try_start` with the required features for configured startup. Calls requiring approval are denied when a handler is @@ -161,6 +162,13 @@ For a prerelease, select its exact version on [crates.io](https://crates.io/crat Enable `full` on the `apcore` dependency when the application uses all of the optional integrations. +Enable `macros` when declaring modules with `#[apcore::module]`. Use +`schemars` 0.8 to derive schemas for the input and output types and Serde to +serialize both types. The input type's serialized representation must include +the values the handler relies on. The registered module uses the normal +executor, including ACL and approval. See the +[typed module declarations](https://apcore.aiperceivable.com/features/module-interface/#typed-module-declarations). + Configured health summaries expose `project.version` when supplied. Explicit `sys_modules.usage.retention_hours` sets the cutoff for hourly usage buckets at collector startup. Without that setting, the collector keeps up to 168 diff --git a/rust/apcore-conformance.yaml b/rust/apcore-conformance.yaml index 716e12f5..909b0346 100644 --- a/rust/apcore-conformance.yaml +++ b/rust/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-rust - version: 1.0.0-alpha.5 + version: 1.0.0-alpha.6 language: rust spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/rust/apcore-macros/Cargo.toml b/rust/apcore-macros/Cargo.toml new file mode 100644 index 00000000..45d94d4f --- /dev/null +++ b/rust/apcore-macros/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "apcore-macros" +version = "1.0.0-alpha.6" +edition = "2021" +rust-version = "1.86" +description = "Typed module declarations for the APCore Rust SDK" +license = "Apache-2.0" +repository = "https://github.com/aiperceivable/apcore" + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1" +quote = "1" +syn = { version = "2", features = ["full", "visit-mut"] } + +[dev-dependencies] +trybuild = "1" diff --git a/rust/apcore-macros/LICENSE b/rust/apcore-macros/LICENSE new file mode 100644 index 00000000..3ff5b1c3 --- /dev/null +++ b/rust/apcore-macros/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by the Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding any notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2024 AI Perceivable + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/rust/apcore-macros/src/lib.rs b/rust/apcore-macros/src/lib.rs new file mode 100644 index 00000000..68b014bc --- /dev/null +++ b/rust/apcore-macros/src/lib.rs @@ -0,0 +1,265 @@ +use proc_macro::TokenStream; +use proc_macro2::TokenStream as TokenStream2; +use quote::quote; +use syn::meta::ParseNestedMeta; +use syn::visit_mut::{self, VisitMut}; +use syn::{ + parse_macro_input, parse_quote, Error, Expr, FnArg, GenericArgument, ItemFn, Lit, LitBool, + LitStr, Meta, Path, PathArguments, ReturnType, Type, Visibility, +}; + +/// Declare an async typed APCore module and its registration and invocation handles. +/// +/// The handler accepts an input and optionally an immutable execution context. +/// It returns `Result`. The input and output use +/// Serde and Schemars 0.8. For inputs, Serde's serialized representation must +/// include the arguments the business code relies on. +/// +/// Supply `id = "group.name"` and either a doc comment or an explicit +/// `description`. The macro creates a sibling module named after the function +/// with `DECLARATION` and `HANDLE` constants. +#[proc_macro_attribute] +pub fn module(args: TokenStream, item: TokenStream) -> TokenStream { + let mut options = Options::default(); + let parser = syn::meta::parser(|meta| options.parse(&meta)); + parse_macro_input!(args with parser); + let function = parse_macro_input!(item as ItemFn); + expand(options, &function) + .unwrap_or_else(|error| error.into_compile_error()) + .into() +} + +#[derive(Default)] +struct Options { + id: Option, + description: Option, + sdk: Option, + readonly: Option, + destructive: Option, + idempotent: Option, + open_world: Option, + requires_approval: Option, + discoverable: Option, +} + +impl Options { + fn parse(&mut self, meta: &ParseNestedMeta<'_>) -> syn::Result<()> { + match meta.path.get_ident().map(ToString::to_string).as_deref() { + Some("id") => parse_option(meta, &mut self.id), + Some("description") => parse_option(meta, &mut self.description), + Some("crate") => parse_option(meta, &mut self.sdk), + Some("readonly") => parse_option(meta, &mut self.readonly), + Some("destructive") => parse_option(meta, &mut self.destructive), + Some("idempotent") => parse_option(meta, &mut self.idempotent), + Some("open_world") => parse_option(meta, &mut self.open_world), + Some("requires_approval") => parse_option(meta, &mut self.requires_approval), + Some("discoverable") => parse_option(meta, &mut self.discoverable), + _ => Err(meta.error("unsupported APCore module option")), + } + } + + fn annotations(&self) -> impl Iterator + '_ { + [ + ("readonly", self.readonly.as_ref()), + ("destructive", self.destructive.as_ref()), + ("idempotent", self.idempotent.as_ref()), + ("open_world", self.open_world.as_ref()), + ("requires_approval", self.requires_approval.as_ref()), + ("discoverable", self.discoverable.as_ref()), + ] + .into_iter() + .filter_map(|(name, value)| { + value.map(|value| { + let field = syn::Ident::new(name, value.span()); + quote!(#field: #value,) + }) + }) + } +} + +fn parse_option( + meta: &ParseNestedMeta<'_>, + target: &mut Option, +) -> syn::Result<()> { + if target.is_some() { + return Err(meta.error("duplicate APCore module option")); + } + *target = Some(meta.value()?.parse()?); + Ok(()) +} + +fn expand(options: Options, function: &ItemFn) -> syn::Result { + let signature = &function.sig; + let name = &signature.ident; + if signature.asyncness.is_none() + || signature.unsafety.is_some() + || signature.abi.is_some() + || !signature.generics.params.is_empty() + || signature.generics.where_clause.is_some() + { + return Err(Error::new_spanned( + signature, + "APCore module handler must be a safe, non-generic async function", + )); + } + let (mut input_type, context_arg) = match signature.inputs.iter().collect::>().as_slice() + { + [FnArg::Typed(input)] => ((*input.ty).clone(), quote!()), + [FnArg::Typed(input), FnArg::Typed(_)] => ((*input.ty).clone(), quote!(, context)), + _ => { + return Err(Error::new_spanned( + signature, + "APCore module handler takes an input and an optional &Context", + )); + } + }; + let mut output_type = result_output(&signature.output)?.clone(); + MoveIntoChild.visit_type_mut(&mut input_type); + MoveIntoChild.visit_type_mut(&mut output_type); + + let id = options + .id + .as_ref() + .filter(|id| !id.value().is_empty()) + .ok_or_else(|| Error::new(name.span(), "APCore module requires id = \"group.name\""))?; + let (description, documentation) = documentation(options.description.as_ref(), function)?; + let annotations = options.annotations(); + let mut sdk: Path = options + .sdk + .clone() + .unwrap_or_else(|| parse_quote!(::apcore)); + MoveIntoChild.visit_path_mut(&mut sdk); + let visibility = &function.vis; + let item_visibility = if matches!(visibility, Visibility::Inherited) { + quote!(pub(super)) + } else { + quote!(pub) + }; + let cfg = function + .attrs + .iter() + .filter(|attr| attr.path().is_ident("cfg")); + + Ok(quote! { + #function + + #(#cfg)* + #[doc = "Typed handle and registration for this APCore module."] + #visibility mod #name { + use super::*; + + #[doc = "Registration for this module."] + #item_visibility const DECLARATION: #sdk::ModuleDeclaration = + #sdk::ModuleDeclaration::new(#id, build_module); + + #[doc = "Governed invocation through the registered module ID."] + #item_visibility const HANDLE: #sdk::TypedHandle<#input_type, #output_type> = + #sdk::TypedHandle::new(#id); + + #[allow(clippy::result_large_err)] + fn build_module() -> ::core::result::Result< + ::std::boxed::Box, + #sdk::ModuleError, + > { + #sdk::__declare_module::<#input_type, #output_type>( + #description, + #documentation, + #sdk::ModuleAnnotations { + #(#annotations)* + ..::core::default::Default::default() + }, + |input, context| ::std::boxed::Box::pin(super::#name(input #context_arg)), + ) + } + } + }) +} + +fn result_output(output: &ReturnType) -> syn::Result<&Type> { + let error = || { + Error::new_spanned( + output, + "APCore module handler must return Result", + ) + }; + let ReturnType::Type(_, output) = output else { + return Err(error()); + }; + let Type::Path(path) = output.as_ref() else { + return Err(error()); + }; + let segment = path + .path + .segments + .last() + .filter(|segment| segment.ident == "Result") + .ok_or_else(error)?; + let PathArguments::AngleBracketed(arguments) = &segment.arguments else { + return Err(error()); + }; + match arguments.args.first() { + Some(GenericArgument::Type(output)) => Ok(output), + _ => Err(error()), + } +} + +fn documentation( + description: Option<&LitStr>, + function: &ItemFn, +) -> syn::Result<(LitStr, TokenStream2)> { + let docs = function.attrs.iter().filter_map(|attr| { + let Meta::NameValue(meta) = &attr.meta else { + return None; + }; + if meta.path.is_ident("doc") { + if let Expr::Lit(expr) = &meta.value { + if let Lit::Str(line) = &expr.lit { + let line = line.value(); + return Some(line.strip_prefix(' ').unwrap_or(&line).to_owned()); + } + } + } + None + }); + let docs = docs.collect::>().join("\n"); + let docs = docs.trim(); + let description = match description { + Some(description) => description.value(), + None => docs + .lines() + .take_while(|line| !line.trim().is_empty()) + .map(str::trim) + .collect::>() + .join(" "), + }; + if description.trim().is_empty() { + return Err(Error::new( + function.sig.ident.span(), + "APCore module requires a doc comment or a nonempty description", + )); + } + let span = function.sig.ident.span(); + let description = LitStr::new(description.trim(), span); + let documentation = if docs.is_empty() { + quote!(::core::option::Option::None) + } else { + let docs = LitStr::new(docs, span); + quote!(::core::option::Option::Some(#docs)) + }; + Ok((description, documentation)) +} + +struct MoveIntoChild; + +impl VisitMut for MoveIntoChild { + fn visit_path_mut(&mut self, path: &mut Path) { + if let Some(first) = path.segments.first_mut() { + if first.ident == "self" { + first.ident = syn::Ident::new("super", first.ident.span()); + } else if first.ident == "super" { + path.segments.insert(0, parse_quote!(super)); + } + } + visit_mut::visit_path_mut(self, path); + } +} diff --git a/rust/apcore-macros/tests/diagnostics.rs b/rust/apcore-macros/tests/diagnostics.rs new file mode 100644 index 00000000..a45a6d39 --- /dev/null +++ b/rust/apcore-macros/tests/diagnostics.rs @@ -0,0 +1,6 @@ +#[test] +fn unsupported_annotation_has_a_compile_time_diagnostic() { + // Use the proc-macro crate directly so the UI test does not depend on + // trybuild recovering the SDK's optional features from Cargo fingerprints. + trybuild::TestCases::new().compile_fail("tests/ui/typed_module_invalid_annotation.rs"); +} diff --git a/rust/apcore-macros/tests/ui/typed_module_invalid_annotation.rs b/rust/apcore-macros/tests/ui/typed_module_invalid_annotation.rs new file mode 100644 index 00000000..076d28c4 --- /dev/null +++ b/rust/apcore-macros/tests/ui/typed_module_invalid_annotation.rs @@ -0,0 +1,6 @@ +#[apcore_macros::module(id = "demo.invalid", read_only = true)] +async fn declaration(input: ()) -> Result<(), ()> { + Ok(input) +} + +fn main() {} diff --git a/rust/apcore-macros/tests/ui/typed_module_invalid_annotation.stderr b/rust/apcore-macros/tests/ui/typed_module_invalid_annotation.stderr new file mode 100644 index 00000000..1c40d286 --- /dev/null +++ b/rust/apcore-macros/tests/ui/typed_module_invalid_annotation.stderr @@ -0,0 +1,5 @@ +error: unsupported APCore module option + --> tests/ui/typed_module_invalid_annotation.rs:1:46 + | +1 | #[apcore_macros::module(id = "demo.invalid", read_only = true)] + | ^^^^^^^^^ diff --git a/rust/src/builtin_steps.rs b/rust/src/builtin_steps.rs index 82bcb932..fe1ee8a7 100644 --- a/rust/src/builtin_steps.rs +++ b/rust/src/builtin_steps.rs @@ -940,6 +940,14 @@ impl Step for BuiltinInputValidation { let input_schema = module.input_schema(); validate_against_schema(&ctx.inputs, &input_schema, "Input")?; + // Keep the legacy approval step in its existing position. Hosted policy + // and its final-scope approval receive the validated Serde representation. + #[cfg(feature = "macros")] + if let Some(inputs) = module.normalize_declared_inputs(&ctx.inputs)? { + validate_against_schema(&inputs, &input_schema, "Input")?; + ctx.inputs = inputs; + } + if ctx.policy_evaluator.is_some() { ctx.policy_sensitive_fields = crate::executor::schema_sensitive_fields(&ctx.inputs, &input_schema); diff --git a/rust/src/decorator.rs b/rust/src/decorator.rs index 836b592a..ee35e406 100644 --- a/rust/src/decorator.rs +++ b/rust/src/decorator.rs @@ -13,6 +13,9 @@ use crate::context::Context; use crate::errors::ModuleError; use crate::module::{Module, ModuleAnnotations, ModuleExample}; +#[cfg(feature = "macros")] +type InputNormalizer = fn(&serde_json::Value) -> Result; + /// Boxed async handler type for `FunctionModule`. type HandlerFn = Box< dyn for<'a> Fn( @@ -40,6 +43,8 @@ pub struct FunctionModule { pub metadata: HashMap, pub examples: Vec, handler: HandlerFn, + #[cfg(feature = "macros")] + input_normalizer: Option, } impl std::fmt::Debug for FunctionModule { @@ -83,6 +88,8 @@ impl FunctionModule { metadata: HashMap::new(), examples: vec![], handler: Box::new(handler), + #[cfg(feature = "macros")] + input_normalizer: None, } } @@ -128,8 +135,15 @@ impl FunctionModule { metadata, examples, handler: Box::new(handler), + #[cfg(feature = "macros")] + input_normalizer: None, } } + + #[cfg(feature = "macros")] + pub(crate) fn set_input_normalizer(&mut self, normalizer: InputNormalizer) { + self.input_normalizer = Some(normalizer); + } } #[async_trait] @@ -142,6 +156,16 @@ impl Module for FunctionModule { self.output_schema.clone() } + #[cfg(feature = "macros")] + fn normalize_declared_inputs( + &self, + inputs: &serde_json::Value, + ) -> Result, ModuleError> { + self.input_normalizer + .map(|normalize| normalize(inputs)) + .transpose() + } + fn description(&self) -> &str { &self.description } diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 8a445a30..bf04684b 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -43,6 +43,8 @@ pub mod schema; pub mod stream_completion; pub mod sys_modules; pub mod trace_context; +#[cfg(feature = "macros")] +mod typed_module; pub mod utils; pub mod version; @@ -52,6 +54,8 @@ pub use acl::{ RuleValidationFinding, ACL, EXTERNAL_CALLER, }; pub use acl_handlers::{ACLConditionHandler, ConditionOutcome}; +#[cfg(feature = "macros")] +pub use apcore_macros::module; pub use approval::{ AlwaysDenyHandler, ApprovalHandler, ApprovalRequest, ApprovalResult, AutoApproveHandler, CallbackApprovalHandler, @@ -211,6 +215,11 @@ pub use sys_modules::{ UsageModule, UsageSummaryModule, }; pub use trace_context::{TraceContext, TraceParent}; +#[doc(hidden)] +#[cfg(feature = "macros")] +pub use typed_module::__declare_module; +#[cfg(feature = "macros")] +pub use typed_module::{ModuleDeclaration, ModulePack, TypedHandle}; pub use utils::{ calculate_specificity, canonicalize_name, guard_call_chain, guard_call_chain_for_context, guard_call_chain_with_repeat, match_pattern, normalize_to_canonical_id, propagate_error, diff --git a/rust/src/module.rs b/rust/src/module.rs index 99b65d04..7a7f9deb 100644 --- a/rust/src/module.rs +++ b/rust/src/module.rs @@ -39,6 +39,15 @@ pub trait Module: Send + Sync { /// Returns the JSON Schema describing this module's output. fn output_schema(&self) -> serde_json::Value; + #[cfg(feature = "macros")] + #[doc(hidden)] + fn normalize_declared_inputs( + &self, + _inputs: &serde_json::Value, + ) -> Result, ModuleError> { + Ok(None) + } + /// Returns a human-readable description of this module. fn description(&self) -> &str; diff --git a/rust/src/typed_module.rs b/rust/src/typed_module.rs new file mode 100644 index 00000000..749893f6 --- /dev/null +++ b/rust/src/typed_module.rs @@ -0,0 +1,235 @@ +use std::collections::HashMap; +use std::future::Future; +use std::marker::PhantomData; +use std::pin::Pin; + +use schemars::{gen::SchemaSettings, JsonSchema}; +use serde::{de::DeserializeOwned, Serialize}; +use serde_json::Value; + +use crate::{APCore, Context, ErrorCode, FunctionModule, Module, ModuleAnnotations, ModuleError}; + +/// A typed reference to a registered module ID. +/// +/// Calling the handle uses the same registry, middleware and governance as +/// [`APCore::call`]. +pub struct TypedHandle { + module_id: &'static str, + types: PhantomData O>, +} + +impl TypedHandle { + #[doc(hidden)] + pub const fn new(module_id: &'static str) -> Self { + Self { + module_id, + types: PhantomData, + } + } + + /// Return the registry ID used by this handle. + pub const fn module_id(&self) -> &'static str { + self.module_id + } +} + +impl TypedHandle { + /// Serialize input, invoke the governed module, and decode its result. + pub async fn invoke( + &self, + client: &APCore, + input: I, + context: Option<&Context>, + ) -> Result { + let input = encode(&input).map_err(ModuleError::invalid_input)?; + let output = client.call(self.module_id, input, context, None).await?; + serde_json::from_value(output).map_err(|_| { + ModuleError::new( + ErrorCode::SchemaValidationError, + "Module output cannot be decoded as the handle's output type", + ) + }) + } +} + +/// A module definition materialized by the attribute macro. +#[derive(Clone, Copy)] +pub struct ModuleDeclaration { + module_id: &'static str, + build: fn() -> Result, ModuleError>, +} + +impl ModuleDeclaration { + #[doc(hidden)] + pub const fn new( + module_id: &'static str, + build: fn() -> Result, ModuleError>, + ) -> Self { + Self { module_id, build } + } + + /// Return the ID that registration assigns to the module. + pub const fn module_id(&self) -> &'static str { + self.module_id + } + + /// Materialize and register the declared module on this client. + pub fn register(&self, client: &APCore) -> Result<(), ModuleError> { + client.register(self.module_id, (self.build)()?) + } +} + +/// A static collection of explicitly selected module declarations. +#[derive(Clone, Copy)] +pub struct ModulePack { + declarations: &'static [ModuleDeclaration], +} + +impl ModulePack { + /// Create a pack in registration order. + pub const fn new(declarations: &'static [ModuleDeclaration]) -> Self { + Self { declarations } + } + + /// Register declarations in order. Earlier registrations remain on error. + pub fn register(&self, client: &APCore) -> Result<(), ModuleError> { + for declaration in self.declarations { + declaration.register(client)?; + } + Ok(()) + } +} + +#[doc(hidden)] +pub fn __declare_module( + description: &str, + documentation: Option<&str>, + annotations: ModuleAnnotations, + handler: impl for<'a> Fn( + I, + &'a Context, + ) -> Pin> + Send + 'a>> + + Send + + Sync + + 'static, +) -> Result, ModuleError> +where + I: JsonSchema + Serialize + DeserializeOwned + Send + 'static, + O: JsonSchema + Serialize + Send + 'static, +{ + let mut module = FunctionModule::with_description( + annotations, + draft2020_12::()?, + draft2020_12::()?, + description, + documentation.map(str::to_owned), + Vec::new(), + crate::registry::registry::DEFAULT_MODULE_VERSION, + HashMap::new(), + Vec::new(), + move |inputs, context| { + let future = decode::(&inputs).and_then(|input| { + if encode_input(&input)? != inputs { + return Err(ModuleError::invalid_input( + "Typed module arguments changed after normalization", + )); + } + Ok(handler(input, context)) + }); + Box::pin(async move { + encode(&future?.await?) + .map_err(|message| ModuleError::new(ErrorCode::GeneralInternalError, message)) + }) + }, + ); + module.set_input_normalizer(|inputs| encode_input(&decode::(inputs)?)); + Ok(Box::new(module)) +} + +fn decode(value: &Value) -> Result { + T::deserialize(value).map_err(|_| { + ModuleError::invalid_input("Arguments cannot be decoded as the declared input") + }) +} + +fn encode(value: &T) -> Result { + serde_json::to_value(value).map_err(|_| "Declared value cannot be encoded as JSON") +} + +fn encode_input(value: &T) -> Result { + let inputs = encode(value).map_err(ModuleError::invalid_input)?; + if !inputs.is_object() || inputs.get(crate::policy::APPROVAL_TOKEN_KEY).is_some() { + return Err(ModuleError::invalid_input( + "Typed module input must encode a JSON object without reserved approval credentials", + )); + } + Ok(inputs) +} + +fn draft2020_12() -> Result { + let settings = SchemaSettings::draft2019_09().with(|settings| { + settings.meta_schema = Some("https://json-schema.org/draft/2020-12/schema".into()); + settings.definitions_path = "#/$defs/".into(); + }); + let mut schema = serde_json::to_value(settings.into_generator().into_root_schema_for::()) + .map_err(|_| { + ModuleError::new( + ErrorCode::SchemaParseError, + "Could not encode the declared JSON Schema", + ) + })?; + if let Some(root) = schema.as_object_mut() { + if let Some(definitions) = root.remove("definitions") { + root.insert("$defs".into(), definitions); + } + } + update_tuple_keywords(&mut schema); + Ok(schema) +} + +// Schemars 0.8 emits the 2019-09 tuple encoding. Walk only schema positions +// so literal values such as a default or enum choice remain untouched. +fn update_tuple_keywords(schema: &mut Value) { + let Some(schema) = schema.as_object_mut() else { + return; + }; + if schema.get("items").is_some_and(Value::is_array) { + if let Some(items) = schema.remove("items") { + schema.insert("prefixItems".into(), items); + } + if let Some(additional) = schema.remove("additionalItems") { + schema.insert("items".into(), additional); + } + } + for keyword in [ + "$defs", + "properties", + "patternProperties", + "dependentSchemas", + ] { + if let Some(children) = schema.get_mut(keyword).and_then(Value::as_object_mut) { + children.values_mut().for_each(update_tuple_keywords); + } + } + for keyword in ["allOf", "anyOf", "oneOf", "prefixItems"] { + if let Some(children) = schema.get_mut(keyword).and_then(Value::as_array_mut) { + children.iter_mut().for_each(update_tuple_keywords); + } + } + for keyword in [ + "additionalProperties", + "contains", + "else", + "if", + "items", + "not", + "propertyNames", + "then", + "unevaluatedItems", + "unevaluatedProperties", + ] { + if let Some(child) = schema.get_mut(keyword) { + update_tuple_keywords(child); + } + } +} diff --git a/rust/tests/typed_modules.rs b/rust/tests/typed_modules.rs new file mode 100644 index 00000000..e57eb38b --- /dev/null +++ b/rust/tests/typed_modules.rs @@ -0,0 +1,270 @@ +#![allow(clippy::result_large_err)] + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use apcore::{ + APCore, ApprovalHandler, ApprovalRequest, ApprovalResult, Config, Context, ErrorCode, Executor, + ModuleError, ModulePack, PolicyEffect, PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict, + Registry, ACL, +}; +use async_trait::async_trait; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +const SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema"; +static STARTS: AtomicUsize = AtomicUsize::new(0); + +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +struct TypedInput { + name: String, + #[serde(default = "default_limit")] + limit: u8, + selection: Selection, +} + +fn default_limit() -> u8 { + 3 +} + +#[derive(Debug, Serialize, Deserialize, JsonSchema)] +struct Selection { + position: (u32, String), +} + +#[derive(Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +struct TypedOutput { + label: String, + limit: u8, +} + +/// Return a typed label +/// and its defaulted limit. +/// +/// The execution context supplies the current module ID. +#[apcore::module(id = "demo.typed", requires_approval = true)] +async fn declared( + input: self::TypedInput, + context: &Context, +) -> Result { + STARTS.fetch_add(1, Ordering::Relaxed); + let current = context.call_chain.last().unwrap(); + Ok(TypedOutput { + label: format!("{}:{current}", input.name), + limit: input.limit, + }) +} + +mod sibling { + #[apcore::module(id = "demo.echo", description = "Echo a typed label", readonly = true)] + pub(super) async fn echo( + input: super::TypedOutput, + ) -> Result { + Ok(input) + } +} + +const PACK: ModulePack = ModulePack::new(&[declared::DECLARATION, sibling::echo::DECLARATION]); + +fn raw_input() -> Value { + json!({"name": "label", "selection": {"position": [2, "here"]}}) +} + +#[derive(Debug, Default)] +struct Gate { + policy: Mutex>, + approvals: Mutex>, +} + +#[async_trait] +impl PolicyEvaluator for Gate { + async fn evaluate( + &self, + request: &PolicyEvaluationRequest, + ) -> Result { + self.policy.lock().unwrap().push(request.arguments.clone()); + Ok(PolicyVerdict { + decision: if request.arguments["name"] == "denied" { + PolicyEffect::Deny + } else { + PolicyEffect::Allow + }, + rule_id: None, + }) + } +} + +#[async_trait] +impl ApprovalHandler for Gate { + async fn request_approval( + &self, + request: &ApprovalRequest, + ) -> Result { + self.approvals.lock().unwrap().push(request.clone()); + Ok(ApprovalResult::approved("reviewer")) + } + + async fn check_approval(&self, _: &str) -> Result { + panic!("an immediate grant must not query a token"); + } +} + +fn client_with_gate(gate: Arc, hosted: bool) -> APCore { + let config = Config::in_memory(); + let mut executor = Executor::with_options(Registry::new(), config.clone(), None, None, None); + if hosted { + executor.set_policy_evaluator(Some(gate.clone())).unwrap(); + } + executor.set_approval_handler_shared(gate); + let client = APCore::with_options(None, Some(executor), Some(config), None); + PACK.register(&client).unwrap(); + client +} + +#[tokio::test] +async fn registration_preserves_descriptor_and_builtin_call_guards() { + let client = APCore::new(); + let typed = || serde_json::from_value::(raw_input()).unwrap(); + assert_eq!(declared::HANDLE.module_id(), "demo.typed"); + assert_eq!(declared::DECLARATION.module_id(), "demo.typed"); + let err = declared::HANDLE + .invoke(&client, typed(), None) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::ModuleNotFound); + + PACK.register(&client).unwrap(); + let descriptor = client + .registry() + .get_definition("demo.typed") + .unwrap() + .unwrap(); + assert_eq!( + descriptor.description, + "Return a typed label and its defaulted limit." + ); + assert!(descriptor + .documentation + .unwrap() + .contains("execution context")); + assert!(descriptor.annotations.unwrap().requires_approval); + assert_eq!(descriptor.input_schema["$schema"], SCHEMA_DIALECT); + assert_eq!(descriptor.output_schema["$schema"], SCHEMA_DIALECT); + assert!(jsonschema::draft202012::meta::is_valid( + &descriptor.input_schema + )); + assert!(jsonschema::draft202012::meta::is_valid( + &descriptor.output_schema + )); + assert_eq!( + descriptor.input_schema["properties"]["selection"]["$ref"], + "#/$defs/Selection" + ); + let tuple = &descriptor.input_schema["$defs"]["Selection"]["properties"]["position"]; + assert_eq!(tuple["prefixItems"][0]["type"], "integer"); + assert_eq!(tuple["prefixItems"][1]["type"], "string"); + assert_eq!(client.list_modules(None, None), ["demo.echo", "demo.typed"]); + + let err = declared::HANDLE + .invoke(&client, typed(), None) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::ApprovalDenied); + let config = Config::in_memory(); + let executor = Executor::with_options( + Registry::new(), + config.clone(), + None, + Some(ACL::try_new(vec![], "deny", None).unwrap()), + None, + ); + let denied = APCore::with_options(None, Some(executor), Some(config), None); + declared::DECLARATION.register(&denied).unwrap(); + let err = declared::HANDLE + .invoke(&denied, typed(), None) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::ACLDenied); +} + +fn malformed_input() -> Value { + let mut invalid = raw_input(); + invalid["selection"]["position"][1] = json!(2); + invalid +} + +#[tokio::test] +async fn legacy_approval_still_runs_before_input_validation() { + let legacy = Arc::new(Gate::default()); + let client = client_with_gate(legacy.clone(), false); + let invalid = malformed_input(); + let err = client + .call("demo.typed", invalid.clone(), None, None) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::SchemaValidationError); + assert_eq!(legacy.approvals.lock().unwrap()[0].arguments, invalid); +} + +#[tokio::test] +async fn normalizes_typed_input_before_hosted_policy_and_final_approval() { + let input = raw_input(); + let typed = || serde_json::from_value::(input.clone()).unwrap(); + let gate = Arc::new(Gate::default()); + let client = client_with_gate(gate.clone(), true); + let err = client + .call("demo.typed", malformed_input(), None, None) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::SchemaValidationError); + assert!(gate.policy.lock().unwrap().is_empty()); + assert!(gate.approvals.lock().unwrap().is_empty()); + + let mut rejected = typed(); + rejected.name = "denied".to_owned(); + let err = declared::HANDLE + .invoke(&client, rejected, None) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::PolicyDenied); + assert!(gate.approvals.lock().unwrap().is_empty()); + assert_eq!(STARTS.load(Ordering::Relaxed), 0); + + assert_eq!( + client + .call("demo.typed", input.clone(), None, None) + .await + .unwrap(), + json!({"label": "label:demo.typed", "limit": 3}) + ); + let output = declared::HANDLE + .invoke(&client, typed(), None) + .await + .unwrap(); + assert_eq!(output.limit, 3); + assert_eq!(output.label, "label:demo.typed"); + assert_eq!(STARTS.load(Ordering::Relaxed), 2); + { + let observations = gate.policy.lock().unwrap(); + let approvals = gate.approvals.lock().unwrap(); + let mut expected = input; + expected["limit"] = json!(3); + assert_eq!(observations.len(), 3); + assert_eq!(approvals.len(), 2); + assert_eq!(observations[1], expected); + assert_eq!(observations[2], expected); + assert_eq!(approvals[0].arguments, expected); + assert_eq!(approvals[1].arguments, expected); + assert!(approvals[0].canonical_args_digest.is_some()); + assert_eq!( + approvals[0].canonical_args_digest, + approvals[1].canonical_args_digest + ); + } + let echoed = sibling::echo::HANDLE + .invoke(&client, output, None) + .await + .unwrap(); + assert_eq!(echoed.label, "label:demo.typed"); +} diff --git a/typescript/apcore-conformance.yaml b/typescript/apcore-conformance.yaml index e24d23e9..50023ba9 100644 --- a/typescript/apcore-conformance.yaml +++ b/typescript/apcore-conformance.yaml @@ -2,7 +2,7 @@ # It does not certify every fixture required by Level 1 or Level 2. implementation: name: apcore-typescript - version: "1.0.0-alpha.5" + version: "1.0.0-alpha.6" language: typescript spec_version: "1.65.0" maintainer: AI Perceivable diff --git a/typescript/package.json b/typescript/package.json index 609da262..b9d6a3d2 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-js", - "version": "1.0.0-alpha.5", + "version": "1.0.0-alpha.6", "description": "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call", "type": "module", "main": "./dist/index.js", diff --git a/typescript/src/browser/index.ts b/typescript/src/browser/index.ts index 8cdf61ad..264cb5bb 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -5,7 +5,8 @@ // ---- Client / runtime core ----------------------------------------------- export { APCore } from '../client.js'; -export type { APCoreOptions, APCorePlugin, ModuleOptions } from '../client.js'; +export type { APCoreOptions, APCorePlugin, BoundModule, DefineModuleOptions, ModuleOptions } from '../client.js'; +export type { StandardSchemaInput, StandardSchemaIssue, StandardSchemaOutput, StandardSchemaV1 } from '../schema/standard.js'; export type { DrainAbortedContext, DrainAbortReason, DrainContext, LifecycleError, LifecycleEventFlush, LifecycleModuleReport, LifecycleOperation, LifecycleReport, LifecycleStatus, ShutdownOptions, UnregisterOptions, WatchOptions } from '../lifecycle.js'; export { Executor, REDACTED_VALUE } from '../executor.js'; diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index 011bd8d6..68323970 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -18,6 +18,7 @@ import type { Config } from './config.js'; import { getDefault } from './config-defaults.js'; import { CancelToken, awaitExecution } from './cancel.js'; import { Context } from './context.js'; +import { assertDeclarationInvocation, recordDeclarationDispatch } from './declaration-invocation.js'; import { authorityKeyOf, hasScopeCeiling } from './identity.js'; import { assertScopedInvocation, isStockScopeAcl, recordScopedGrant, recordScopedLookup } from './scoped-invocation.js'; import { @@ -52,6 +53,7 @@ import { ConfigurationError, ExecutionStrategy, GOVERNANCE_GATE } from './pipeli import { isStreamingModule } from './streaming.js'; import type { Registry } from './registry/registry.js'; import { jsonSchemaToTypeBox } from './schema/loader-pure.js'; +import { declarationJsonObject, declarationOf, takeDeclarationInputs, validateDeclarationInputs } from './schema/standard.js'; import { SchemaValidator } from './schema/validator.js'; import { guardCallChain } from './utils/call-chain.js'; import { normalizeModuleObject } from './utils/module-output.js'; @@ -61,6 +63,8 @@ import { normalizeModuleObject } from './utils/module-output.js'; // --------------------------------------------------------------------------- function resolveSchema(mod: Record, key: string): TSchema | null { + const declaration = declarationOf(mod); + if (declaration) return key === 'inputSchema' ? declaration.inputSchema : declaration.outputSchema; const schema = mod[key] as TSchema | undefined; if (schema == null) return null; if (Kind in schema) return schema; @@ -257,6 +261,7 @@ export class BuiltinModuleLookup implements Step { if (mod === null || (!(invocation?.preflight ?? ctx.dryRun) && this._registry.isDraining(ctx.moduleId))) { throw new ModuleNotFoundError(ctx.moduleId); } + assertDeclarationInvocation(ctx, mod); // Inline toggle check — matches apcore-python builtin_steps.py:231 and // apcore-rust builtin_steps.rs:219 (sync finding A-D-011). @@ -827,22 +832,30 @@ export class BuiltinInputValidation implements Step { readonly provides = ['validated_inputs'] as const; async execute(ctx: PipelineContext): Promise { + assertDeclarationInvocation(ctx); const invocation = policyInvocationOf(ctx); if (invocation) assertPolicyBinding(ctx, invocation); let snapshot = invocation ? copyPolicyInputs(ctx.moduleId, ctx.inputs) : null; const mod = ctx.module as Record; + const declaration = declarationOf(mod); const inputSchema = resolveSchema(mod, 'inputSchema'); + let effectiveInputs = snapshot?.arguments ?? ctx.inputs; + if (declaration && !snapshot) effectiveInputs = declarationJsonObject(effectiveInputs, 'input'); if (inputSchema !== null) { - validateSchema(inputSchema, snapshot?.arguments ?? ctx.inputs, 'Input'); + validateSchema(inputSchema, effectiveInputs, 'Input'); // Native TypeBox validators can change the inputs and retain aliases. // Capture both the values and their encoding from the detached result. - if (snapshot) snapshot = copyPolicyInputs(ctx.moduleId, snapshot.arguments); + if (snapshot && !declaration) snapshot = copyPolicyInputs(ctx.moduleId, effectiveInputs); + } + if (declaration) { + effectiveInputs = await validateDeclarationInputs(ctx, declaration, effectiveInputs); + if (snapshot) snapshot = copyPolicyInputs(ctx.moduleId, effectiveInputs); } const effectiveSchema = inputSchema ?? {}; - const effectiveInputs = snapshot?.arguments ?? ctx.inputs; + effectiveInputs = snapshot?.arguments ?? effectiveInputs; ctx.context.redactedInputs = redactSensitive(effectiveInputs, effectiveSchema, this._redaction); - ctx.validatedInputs = snapshot ? structuredClone(effectiveInputs) : effectiveInputs; + ctx.validatedInputs = snapshot || declaration ? structuredClone(effectiveInputs) : effectiveInputs; if (invocation && snapshot) { snapshot.sensitiveFields = sensitivePolicyFields(effectiveInputs, effectiveSchema); invocation.validated = snapshot; @@ -958,8 +971,10 @@ export class BuiltinExecute implements Step { async execute(ctx: PipelineContext): Promise { assertScopedInvocation(ctx, true); + assertDeclarationInvocation(ctx); const invocation = policyInvocationOf(ctx); - let inputs = ctx.inputs; + const declaration = declarationOf(ctx.module); + let inputs = declaration ? takeDeclarationInputs(ctx) : ctx.inputs; if (invocation) { assertPolicyBinding(ctx, invocation); if (!invocation.approvedForDispatch || !invocation.validated) throw new PolicyEvaluationError(ctx.moduleId); @@ -1035,6 +1050,7 @@ export class BuiltinExecute implements Step { const release = moduleExecutionLeases.get(ctx)?.(); let executionPromise: Promise>; try { + recordDeclarationDispatch(ctx); if (invocation) invocation.dispatched = true; executionPromise = Promise.resolve( ( diff --git a/typescript/src/client.ts b/typescript/src/client.ts index d1e7defb..f031ba22 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -27,11 +27,19 @@ import { import type { StepMiddleware } from './pipeline.js'; import type { ExecutionPolicy } from './policy.js'; import type { Middleware } from './middleware/index.js'; -import type { ModuleAnnotations, ModuleExample, PreflightResult, ResourceLimits } from './module.js'; +import { createAnnotations, type ModuleAnnotations, type ModuleExample, type PreflightResult, type ResourceLimits } from './module.js'; import type { MetricsCollector } from './observability/metrics.js'; import type { StreamExecution } from './stream-completion.js'; import { Registry } from './registry/registry.js'; import type { ModuleDescriptor } from './registry/types.js'; +import { + bindDeclaration, + prepareStandardSchema, + validateStandard, + type StandardSchemaInput, + type StandardSchemaOutput, + type StandardSchemaV1, +} from './schema/standard.js'; import type { RegisterSysModulesOptions, SysModulesContext } from './sys-modules/registration.js'; import { ToggleState } from './sys-modules/toggle.js'; @@ -110,6 +118,30 @@ export interface ModuleOptions { execute: (inputs: Record, context: Context) => Promise> | Record; } +/** Typed module declaration. Explicit schemas take precedence over vendor conversion. */ +export interface DefineModuleOptions + extends Omit { + id: string; + description: string; + input: Input; + output: Output; + /** Draft 2020-12 schema for the raw invocation arguments. */ + inputSchema?: Record; + /** Draft 2020-12 schema for the normalized result. */ + outputSchema?: Record; + readonly?: boolean; + annotations?: Partial; + execute: (inputs: StandardSchemaOutput, context: Context) => + StandardSchemaInput | Promise>; +} + +/** A typed reference to a module registered with this client. */ +export interface BoundModule { + readonly id: string; + invoke(inputs: Input, context?: Context | null, versionHint?: string | null): Promise; + validate(inputs: Input, context?: Context | null): Promise; +} + interface ClientShutdown { readonly operation: LifecycleOperation; readonly completion: Promise; @@ -271,6 +303,36 @@ export class APCore { }); } + /** Register a Standard Schema declaration and return a governed, typed handle. */ + async define( + options: DefineModuleOptions, + ): Promise, StandardSchemaOutput>> { + const { id, input, output, inputSchema, outputSchema, execute, readonly, annotations, ...definition } = options; + if (typeof execute !== 'function') throw new InvalidInputError('Typed module requires an execute function'); + const preparedInput = prepareStandardSchema(input, 'input', inputSchema); + const preparedOutput = prepareStandardSchema(output, 'output', outputSchema); + const module = { + ...definition, + inputSchema: preparedInput.document, + outputSchema: preparedOutput.document, + annotations: createAnnotations({ ...annotations, ...(readonly === undefined ? {} : { readonly }) }), + async execute(inputs: Record, context: Context): Promise> { + return validateStandard(output, await execute(inputs as StandardSchemaOutput, context), 'output'); + }, + }; + bindDeclaration(module, { input, inputSchema: preparedInput.compiled, outputSchema: preparedOutput.compiled }); + await this.register(id, module); + const declaration = { module, isCurrent: this.registry.bindRegistration(id, module) }; + + return Object.freeze({ + id, + invoke: async (inputs: StandardSchemaInput, context?: Context | null, versionHint?: string | null) => + await this.executor.callDeclaration(id, declaration, inputs as Record, context, versionHint) as StandardSchemaOutput, + validate: (inputs: StandardSchemaInput, context?: Context | null) => + this.executor.validateDeclaration(id, declaration, inputs as Record, context), + }); + } + /** * Register a module object directly. * diff --git a/typescript/src/declaration-invocation.ts b/typescript/src/declaration-invocation.ts new file mode 100644 index 00000000..d85cdaf9 --- /dev/null +++ b/typescript/src/declaration-invocation.ts @@ -0,0 +1,47 @@ +import { ModuleNotFoundError } from './errors.js'; +import type { PipelineContext } from './pipeline.js'; + +/** @internal The declaration and registration generation owned by a typed handle. */ +export interface BoundDeclaration { + readonly module: object; + readonly isCurrent: () => boolean; +} + +type BoundInvocation = { + readonly id: string; + readonly declaration: BoundDeclaration; + dispatched: boolean; +}; + +const invocations = new WeakMap(); + +/** @internal Keep the expected registration outside mutable pipeline state. */ +export function beginDeclarationInvocation(ctx: PipelineContext, declaration?: BoundDeclaration): void { + if (declaration) invocations.set(ctx, { id: ctx.moduleId, declaration, dispatched: false }); +} + +/** @internal Check the registration chosen by lookup or recorded for dispatch. */ +export function assertDeclarationInvocation(ctx: PipelineContext, module: unknown = ctx.module): void { + const binding = invocations.get(ctx); + if (binding && (ctx.moduleId !== binding.id || module !== binding.declaration.module || !binding.declaration.isCurrent())) { + throw new ModuleNotFoundError(binding.id); + } +} + +/** @internal Record dispatch after the stock execution lease was acquired. */ +export function recordDeclarationDispatch(ctx: PipelineContext): void { + const binding = invocations.get(ctx); + if (binding) binding.dispatched = true; +} + +/** @internal A typed call cannot return output from a traversal that skipped dispatch. */ +export function assertDeclarationDispatch(ctx: PipelineContext): void { + const binding = invocations.get(ctx); + if (binding && !binding.dispatched) throw new ModuleNotFoundError(binding.id); +} + +/** @internal Reject recovery of unavailable registrations before module execution. */ +export function isDeclarationAdmissionError(ctx: PipelineContext, error: unknown): boolean { + const binding = invocations.get(ctx); + return binding !== undefined && !binding.dispatched && error instanceof ModuleNotFoundError; +} diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index 1a30f7a8..e7cfe482 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -52,6 +52,10 @@ import { type EventEmitter, createEvent } from './events/emitter.js'; import { Context } from './context.js'; import { hasScopeCeiling } from './identity.js'; import { assertScopeGate, assertScopedInvocation, beginScopedInvocation, isScopedAdmissionError, isStockScopeAcl } from './scoped-invocation.js'; +import { + assertDeclarationDispatch, assertDeclarationInvocation, beginDeclarationInvocation, isDeclarationAdmissionError, + type BoundDeclaration, +} from './declaration-invocation.js'; import { governanceUnion } from './schema/annotations.js'; import { sourceSchemaFor } from './schema/loader-pure.js'; import { RedactionConfig } from './observability/context-logger.js'; @@ -60,6 +64,7 @@ import { ErrorCodes, InvalidInputError, ModuleError, + ModuleNotFoundError, ModuleTimeoutError, PolicyEvaluationError, } from './errors.js'; @@ -80,6 +85,7 @@ import type { } from './module.js'; import { createPreflightResult, isModuleIdempotent } from './module.js'; import type { + ExecutionStrategy, GovernanceState, PipelineContext, PipelineTrace, @@ -87,7 +93,6 @@ import type { StrategyInfo, } from './pipeline.js'; import { - ExecutionStrategy, PipelineAbortError, PipelineEngine, PipelineStepError, @@ -1256,12 +1261,25 @@ export class Executor { return output; } + /** @internal Execute a typed handle over the ordinary pipeline using its original registration. */ + async callDeclaration( + moduleId: string, + declaration: BoundDeclaration, + inputs: Record, + context?: Context | null, + versionHint?: string | null, + ): Promise> { + const [output] = await this._callWithTrace(moduleId, inputs, context, this._strategy, versionHint, declaration); + return output; + } + private async _callWithTrace( moduleId: string, inputs: Record | null | undefined, context: Context | null | undefined, strategy: ExecutionStrategy, versionHint: string | null | undefined, + declaration?: BoundDeclaration, ): Promise<[Record, PipelineTrace]> { this._validateModuleId(moduleId); // Per-call strategies use the providers owned by this executor (D-129). @@ -1296,6 +1314,7 @@ export class Executor { try { while (true) { try { + beginDeclarationInvocation(pipeCtx, declaration); beginScopedInvocation(pipeCtx); if (protectedCall) { beginPolicyInvocation(pipeCtx); @@ -1304,6 +1323,7 @@ export class Executor { prepareApprovalInputs(pipeCtx); const [output, trace] = await this._pipelineEngine.run(strategy, pipeCtx); assertScopedInvocation(pipeCtx, true); + assertDeclarationDispatch(pipeCtx); if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw new PolicyEvaluationError(moduleId); return [(output ?? {}) as Record, trace]; } catch (exc) { @@ -1323,7 +1343,9 @@ export class Executor { unwrapped instanceof MiddlewareChainError ? unwrapped.original : (unwrapped as Error); if (underlying instanceof ExecutionCancelledError) throw underlying; const wrapped = propagateError(underlying, moduleId, ctxObj); - if (isScopedAdmissionError(pipeCtx, underlying)) throw wrapped; + if (isScopedAdmissionError(pipeCtx, underlying) || isDeclarationAdmissionError(pipeCtx, underlying)) { + throw wrapped; + } if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; const executedMw = pipeCtx.executedMiddlewares; if (executedMw && executedMw.length > 0) { @@ -1714,6 +1736,25 @@ export class Executor { moduleId: string, inputs?: Record | null, context?: Context | null, + ): Promise { + return this._validate(moduleId, inputs, context); + } + + /** @internal Preflight a typed handle against its original registration. */ + validateDeclaration( + moduleId: string, + declaration: BoundDeclaration, + inputs: Record, + context?: Context | null, + ): Promise { + return this._validate(moduleId, inputs, context, declaration); + } + + private async _validate( + moduleId: string, + inputs: Record | null | undefined, + context: Context | null | undefined, + declaration?: BoundDeclaration, ): Promise { const checks: PreflightCheckResult[] = []; @@ -1777,6 +1818,7 @@ export class Executor { dryRun: true, }; if (protectedCall) beginPolicyInvocation(pipeCtx); + beginDeclarationInvocation(pipeCtx, declaration); beginScopedInvocation(pipeCtx); try { @@ -1830,6 +1872,18 @@ export class Executor { checks.push(...this._traceToChecks(trace)); } + // An async validator can finish after the selected generation has been replaced. + if (declaration && (checks.some(check => check.check === 'module_lookup' && check.passed) || + checks.every(check => check.passed))) { + try { + assertDeclarationInvocation(pipeCtx); + } catch (error) { + if (!(error instanceof ModuleNotFoundError)) throw error; + checks.push({ check: 'module_lookup', passed: false, error: error.toJSON() }); + return createPreflightResult(checks); + } + } + // Detect requires_approval let requiresApproval = false; if (pipeCtx.module != null) { diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts index e1ceff88..72bd8100 100644 --- a/typescript/src/node-api.ts +++ b/typescript/src/node-api.ts @@ -1,6 +1,7 @@ // Client export { APCore } from './client.js'; -export type { APCoreOptions, APCorePlugin, ModuleOptions } from './client.js'; +export type { APCoreOptions, APCorePlugin, BoundModule, DefineModuleOptions, ModuleOptions } from './client.js'; +export type { StandardSchemaInput, StandardSchemaIssue, StandardSchemaOutput, StandardSchemaV1 } from './schema/standard.js'; export type { DrainAbortedContext, DrainAbortReason, DrainContext, LifecycleError, LifecycleEventFlush, LifecycleModuleReport, LifecycleOperation, LifecycleReport, LifecycleStatus, ShutdownOptions, UnregisterOptions, WatchOptions } from './lifecycle.js'; // Core diff --git a/typescript/src/pipeline.ts b/typescript/src/pipeline.ts index 83f60d8e..e1fa2f50 100644 --- a/typescript/src/pipeline.ts +++ b/typescript/src/pipeline.ts @@ -4,11 +4,13 @@ import type { GovernanceProjection } from './acl-handlers.js'; import type { Context } from './context.js'; +import { isDeclarationAdmissionError } from './declaration-invocation.js'; import { ModuleError, ModuleTimeoutError } from './errors.js'; import type { ErrorOptions } from './errors.js'; import { MiddlewareChainError } from './middleware/manager.js'; import { matchPattern } from './utils/pattern.js'; import { policyInvocationOf } from './policy-evaluation.js'; +import { StandardValidationError } from './schema/standard.js'; import { isScopedAdmissionError } from './scoped-invocation.js'; // --------------------------------------------------------------------------- @@ -1244,7 +1246,12 @@ export class PipelineEngine { trace.steps.push({ name: step.name, durationMs, result: { action: 'abort', explanation: cause.message }, skipped: false, decisionPoint: false, - error: { code: cause instanceof ModuleError ? cause.code : 'GENERAL_INTERNAL_ERROR', message: cause.message } }); + error: { + code: cause instanceof ModuleError ? cause.code : 'GENERAL_INTERNAL_ERROR', + message: cause.message, + ...(cause instanceof StandardValidationError ? { details: cause.details } : {}), + }, + }); for (const key of step.provides ?? []) failedProvides.add(key); idx += 1; continue; @@ -1253,6 +1260,7 @@ export class PipelineEngine { // 3 b onStepError hooks: reverse registration order (onion model), // first non-null recovery wins and short-circuits the rest (§2.2). const isGovernanceGate = governanceGateOf(step) !== null || isScopedAdmissionError(ctx, cause) || + isDeclarationAdmissionError(ctx, cause) || (policyInvocation !== undefined && !policyInvocation.dispatched); const observedCancellation = observeStep !== undefined && cause instanceof ModuleError && cause.code === 'EXECUTION_CANCELLED'; diff --git a/typescript/src/policy-evaluation.ts b/typescript/src/policy-evaluation.ts index 99838ec1..ad678402 100644 --- a/typescript/src/policy-evaluation.ts +++ b/typescript/src/policy-evaluation.ts @@ -166,15 +166,24 @@ function copyObject(value: object, parts: string[], active: Set): Record return Object.fromEntries(keys.map((key) => [key, copies.get(key)])); } +/** @internal Detach a wire object using the invocation's canonical JSON constraints. */ +export function snapshotJsonObject(value: unknown): ValidationSnapshot { + const parts: string[] = []; + const args = copyArgument(value, parts, new Set()); + if (args === null || typeof args !== 'object' || Array.isArray(args)) { + throw new Error('Expected a JSON object.'); + } + return { arguments: args as Record, canonical: parts, sensitiveFields: [] }; +} + /** @internal Detach the inputs and capture their canonical encoding. */ export function copyPolicyInputs(moduleId: string, inputs: Record): ValidationSnapshot { try { - const parts: string[] = []; - const args = copyArgument(inputs, parts, new Set()); - if (args === null || typeof args !== 'object' || Array.isArray(args) || Object.hasOwn(args, '_approval_token')) { + const snapshot = snapshotJsonObject(inputs); + if (Object.hasOwn(snapshot.arguments, '_approval_token')) { throw new Error('Policy requires an object of business arguments.'); } - return { arguments: args as Record, canonical: parts, sensitiveFields: [] }; + return snapshot; } catch { throw new PolicyEvaluationError(moduleId); } diff --git a/typescript/src/registry/registry.ts b/typescript/src/registry/registry.ts index b3a410b4..d07c6e53 100644 --- a/typescript/src/registry/registry.ts +++ b/typescript/src/registry/registry.ts @@ -2287,11 +2287,18 @@ export class Registry { }; } + /** @internal Check that a captured registration still refers to the same generation. */ + bindRegistration(moduleId: string, expectedModule: unknown): () => boolean { + const expectedGeneration = this._executionGenerations.get(moduleId); + return () => expectedGeneration !== undefined && this._modules.get(moduleId) === expectedModule && + this._executionGenerations.get(moduleId) === expectedGeneration; + } + /** @internal Capture the registration now and acquire its execution reference later. */ bindExecution(moduleId: string, expectedModule: unknown, token?: CancelToken | null): () => () => void { - const expectedGeneration = this._executionGenerations.get(moduleId); + const isCurrent = this.bindRegistration(moduleId, expectedModule); return () => { - if (this._executionGenerations.get(moduleId) !== expectedGeneration) { + if (!isCurrent()) { throw new ModuleNotFoundError(moduleId); } return this.acquireExecution(moduleId, expectedModule, token); diff --git a/typescript/src/schema/standard.ts b/typescript/src/schema/standard.ts new file mode 100644 index 00000000..ab9d4df2 --- /dev/null +++ b/typescript/src/schema/standard.ts @@ -0,0 +1,154 @@ +import type { TSchema } from '@sinclair/typebox'; +import { awaitExecution } from '../cancel.js'; +import type { Context } from '../context.js'; +import { InvalidInputError, ModuleTimeoutError, SchemaValidationError } from '../errors.js'; +import { snapshotJsonObject } from '../policy-evaluation.js'; +import type { PipelineContext } from '../pipeline.js'; +import { jsonSchemaToTypeBox } from './loader-pure.js'; + +type Awaitable = T | Promise; +type Direction = 'input' | 'output'; + +export interface StandardSchemaIssue { + readonly message: string; + readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[]; +} + +type StandardResult = + | { readonly value: Output; readonly issues?: undefined } + | { readonly issues: readonly StandardSchemaIssue[] }; + +/** The structural Standard Schema v1 contract with optional Standard JSON Schema support. */ +export interface StandardSchemaV1 { + readonly '~standard': { + readonly version: 1; + readonly vendor: string; + readonly validate: (value: unknown) => Awaitable>; + readonly types?: { readonly input: Input; readonly output: Output } | undefined; + readonly jsonSchema?: { + readonly input: (options: { readonly target: 'draft-2020-12' }) => Record; + readonly output: (options: { readonly target: 'draft-2020-12' }) => Record; + }; + }; +} + +export type StandardSchemaInput = NonNullable['input']; +export type StandardSchemaOutput = NonNullable['output']; + +/** @internal Preserves Standard Schema issue details in the preflight result. */ +export class StandardValidationError extends SchemaValidationError {} + +const DRAFT_2020_12 = 'https://json-schema.org/draft/2020-12/schema'; + +/** @internal Prepare a stable public schema and compile its runtime equivalent once. */ +export function prepareStandardSchema( + schema: StandardSchemaV1, + direction: Direction, + explicit: Record | undefined, +): { readonly document: Record; readonly compiled: TSchema } { + const standard = schema?.['~standard']; + if (standard?.version !== 1 || typeof standard.vendor !== 'string' || typeof standard.validate !== 'function') { + throw new InvalidInputError(`Typed ${direction} must implement Standard Schema v1`); + } + + let document: Record; + try { + const source = explicit ?? standard.jsonSchema?.[direction]({ target: 'draft-2020-12' }); + // Providers such as Zod attach non-enumerable adapter metadata to the + // returned document. Export only JSON data, without retaining the provider. + document = snapshotJsonObject(structuredClone(source)).arguments; + } catch { + throw new InvalidInputError(`Typed ${direction} requires a Draft 2020-12 JSON Schema. Supply ${direction}Schema explicitly if conversion is unavailable.`); + } + const draft = document['$schema']; + if (draft !== undefined && draft !== DRAFT_2020_12) { + throw new InvalidInputError(`Typed ${direction} JSON Schema must use Draft 2020-12`); + } + return { document, compiled: jsonSchemaToTypeBox(document) }; +} + +function standardIssue(issue: StandardSchemaIssue): Record { + const path = (issue.path ?? []).map(segment => { + const key = typeof segment === 'object' ? segment.key : segment; + return '/' + String(key).replaceAll('~', '~0').replaceAll('/', '~1'); + }).join(''); + return { path, message: issue.message, keyword: 'standardSchema' }; +} + +function validationFailure(direction: Direction, errors: Array>): StandardValidationError { + const label = direction === 'input' ? 'Input' : 'Output'; + return new StandardValidationError(`${label} validation failed`, errors); +} + +/** @internal Validate JSON data passing between a typed module and the runtime. */ +export function declarationJsonObject(value: unknown, direction: Direction): Record { + try { + const record = snapshotJsonObject(value).arguments; + if (direction === 'input' && Object.hasOwn(record, '_approval_token')) throw new Error('Reserved property'); + return record; + } catch { + throw validationFailure(direction, [{ path: '', message: 'Expected a plain JSON object', keyword: 'type' }]); + } +} + +/** @internal Validate or normalize data using the vendor's structural contract. */ +export async function validateStandard( + schema: StandardSchemaV1, + value: unknown, + direction: Direction, +): Promise> { + let result: StandardResult; + try { + result = await schema['~standard'].validate(value); + } catch { + throw validationFailure(direction, [{ path: '', message: 'Standard Schema validator failed', keyword: 'standardSchema' }]); + } + if (result.issues !== undefined) throw validationFailure(direction, result.issues.map(standardIssue)); + return declarationJsonObject(result.value, direction); +} + +interface DeclarationValidation { + readonly inputSchema: TSchema; + readonly outputSchema: TSchema; + readonly input: StandardSchemaV1; +} + +const declarations = new WeakMap(); +const validated = new WeakMap }>(); + +/** @internal Bind validation to the exact registry instance. */ +export function bindDeclaration(module: object, validation: DeclarationValidation): void { + declarations.set(module, validation); +} + +/** @internal Retrieve the internal adapter without reading user-supplied module properties. */ +export function declarationOf(module: unknown): DeclarationValidation | undefined { + return declarations.get(module as object); +} + +/** @internal Normalize the invocation's detached inputs before final policy. */ +export async function validateDeclarationInputs( + ctx: PipelineContext, + declaration: DeclarationValidation, + inputs: Record, +): Promise> { + const module = ctx.module; + const context: Context = ctx.context; + const timeout = context.globalDeadline === null ? 0 : Math.ceil(context.globalDeadline * 1000 - Date.now()); + context.cancelToken?.check(); + if (context.globalDeadline !== null && timeout <= 0) throw new ModuleTimeoutError(ctx.moduleId, 0); + const parsed = await awaitExecution(validateStandard(declaration.input, inputs, 'input'), + context.cancelToken, ctx.moduleId, timeout, false); + validated.set(ctx, { module, inputs: parsed }); + return parsed; +} + +/** @internal Consume the invocation-owned inputs instead of using mutable pipeline fields. */ +export function takeDeclarationInputs(ctx: PipelineContext): Record { + const binding = validated.get(ctx); + validated.delete(ctx); + if (!binding || binding.module !== ctx.module) { + throw new InvalidInputError('Typed module execution requires built-in input validation'); + } + return binding.inputs; +} diff --git a/typescript/tests/test-typed-module.test.ts b/typescript/tests/test-typed-module.test.ts new file mode 100644 index 00000000..b246277c --- /dev/null +++ b/typescript/tests/test-typed-module.test.ts @@ -0,0 +1,319 @@ +import { describe, expect, expectTypeOf, it, vi } from 'vitest'; +import { + APCore, + CallbackApprovalHandler, + Executor, + Registry, + createApprovalResult, + type BoundModule, + type StandardSchemaV1, +} from '../src/index.js'; +import { Type } from '@sinclair/typebox'; + +const id = 'orders.quote'; +const draft = 'https://json-schema.org/draft/2020-12/schema'; +const wireInput = { + $schema: draft, + type: 'object', + properties: { units: { type: 'string' } }, + required: ['units'], + additionalProperties: false, +}; +const wireOutput = { + $schema: draft, + type: 'object', + properties: { total: { type: 'number' } }, + required: ['total'], +}; + +interface RawInput { units: string } +interface ParsedInput { units: number } +interface RawOutput { total: string } +interface ParsedOutput { total: number } + +function deferred() { + let release!: () => void; + const promise = new Promise(resolve => { release = resolve; }); + return { promise, release }; +} + +function schemas() { + const nativeInput = vi.fn(() => Object.defineProperty({ ...wireInput }, '~standard', { + value: { validate: () => ({ issues: [] }) }, + })); + const nativeOutput = vi.fn(() => wireOutput); + const input: StandardSchemaV1 = { + '~standard': { + version: 1, + vendor: 'test-validator', + async validate(value) { + const units = Number((value as RawInput).units); + return units > 0 ? { value: { units } } : { issues: [ + { message: 'Units must be positive', path: [{ key: 'units' }] }, + { message: 'Invalid allocation', path: ['options/~names', 0] }, + ] }; + }, + jsonSchema: { + input: nativeInput, + output: () => { throw new Error('An input declaration must use the input schema'); }, + }, + }, + }; + const output: StandardSchemaV1 = { + '~standard': { + version: 1, + vendor: 'test-validator', + async validate(value) { + const total = Number((value as RawOutput).total); + return total >= 0 ? { value: { total } } : { issues: [{ message: 'Total must be nonnegative', path: ['total'] }] }; + }, + jsonSchema: { + input: () => { throw new Error('An output declaration must use the output schema'); }, + output: nativeOutput, + }, + }, + }; + return { input, output, nativeInput, nativeOutput }; +} + +describe('APCore.define', () => { + it('infers the types on both sides of validation and registers canonical schemas for both entry points', async () => { + const client = new APCore(); + const { input, output, nativeInput, nativeOutput } = schemas(); + const module = await client.define({ id, description: 'Quote an order', readonly: true, input, output, execute(args) { + expectTypeOf(args).toEqualTypeOf(); + return { total: String(args.units * 2) }; + } }); + expectTypeOf(module).toEqualTypeOf>(); + expectTypeOf(module.invoke).parameter(0).not.toEqualTypeOf(); + expect(module.id).toBe(id); + expect(nativeInput).toHaveBeenCalledExactlyOnceWith({ target: 'draft-2020-12' }); + expect(nativeOutput).toHaveBeenCalledExactlyOnceWith({ target: 'draft-2020-12' }); + await expect(module.invoke({ units: '2.5' })).resolves.toEqual({ total: 5 }); + await expect(client.call(id, { units: '2.5' })).resolves.toEqual({ total: 5 }); + await expect(client.stream(id, { units: '2.5' }).next()).resolves.toMatchObject({ value: { total: 5 } }); + expect(client.getCallableDefinition(id)).toMatchObject({ inputSchema: wireInput, outputSchema: wireOutput }); + expect(client.registry.getDefinition(id)).toMatchObject({ annotations: { readonly: true } }); + }); + + it('awaits registration and uses an explicit schema in place of native conversion', async () => { + const client = new APCore(); + const { input, output, nativeInput, nativeOutput } = schemas(); + let finish!: (errors: string[]) => void; + client.registry.setValidator({ validate: () => new Promise(resolve => { finish = resolve; }) }); + const typedInput = { '~standard': { ...input['~standard'], jsonSchema: undefined } }; + const handle = client.define({ + id, description: 'Quote an order', input: typedInput, output, inputSchema: wireInput, outputSchema: wireOutput, + execute: ({ units }) => ({ total: String(units) }), + }); + expect(client.registry.get(id)).toBeNull(); + finish([]); + await expect(handle).resolves.toMatchObject({ id }); + expect(client.registry.get(id)).not.toBeNull(); + expect(nativeInput).not.toHaveBeenCalled(); + expect(nativeOutput).not.toHaveBeenCalled(); + }); + + it('rejects a stale handle while leaving ordinary calls and preflight on the replacement', async () => { + const client = new APCore(); + const { input, output } = schemas(); + const original = await client.define({ id, description: 'Quote an order', input, output, + execute: ({ units }) => ({ total: String(units) }) }); + expect(client.registry.unregister(id)).toBe(true); + const replacement = vi.fn(() => ({ total: 'different result type' })); + const preflight = vi.fn(() => []); + await client.register(id, { + description: 'Replacement quote', inputSchema: wireInput, + outputSchema: Type.Object({ total: Type.String() }), execute: replacement, preflight, + }); + + await expect(original.invoke({ units: '2' })).rejects.toMatchObject({ code: 'MODULE_NOT_FOUND' }); + expect(await original.validate({ units: '2' })).toMatchObject({ + valid: false, errors: [expect.objectContaining({ code: 'MODULE_NOT_FOUND' })], + }); + expect(replacement).not.toHaveBeenCalled(); + expect(preflight).not.toHaveBeenCalled(); + await expect(client.call(id, { units: '2' })).resolves.toEqual({ total: 'different result type' }); + expect((await client.validate(id, { units: '2' })).valid).toBe(true); + expect(preflight).toHaveBeenCalledOnce(); + }); + + it.each(['module_lookup', 'execute'])('rejects replacement while the old invocation waits at %s', async step => { + const client = new APCore(); + const { input, output } = schemas(); + const execute = vi.fn(({ units }: ParsedInput) => ({ total: String(units) })); + const original = await client.define({ id, description: 'Quote an order', input, output, execute }); + const replacement = vi.fn(() => ({ total: 'different result type' })); + const hookEntered = deferred(); + const hookReleased = deferred(); + const recover = vi.fn(() => ({ total: 'middleware recovery' })); + client.executor.addStepMiddleware({ + async beforeStep(name) { + if (name !== step) return; + hookEntered.release(); + await hookReleased.promise; + }, + onStepError: recover, + }); + + const obsolete = original.invoke({ units: '2' }); + try { + await hookEntered.promise; + expect(client.registry.unregister(id)).toBe(true); + await client.register(id, { + description: 'Replacement quote', inputSchema: wireInput, + outputSchema: Type.Object({ total: Type.String() }), execute: replacement, + }); + } finally { + hookReleased.release(); + } + await expect(obsolete).rejects.toMatchObject({ code: 'MODULE_NOT_FOUND' }); + expect(recover).toHaveBeenCalledOnce(); + expect(execute).not.toHaveBeenCalled(); + expect(replacement).not.toHaveBeenCalled(); + await expect(client.call(id, { units: '2' })).resolves.toEqual({ total: 'different result type' }); + }); + + it('keeps a completed validation from certifying an unregistered generation', async () => { + const client = new APCore(); + const { input, output } = schemas(); + const schema = input['~standard']; + const validationStarted = deferred(); + const validationReleased = deferred(); + const slowInput = { '~standard': { ...schema, async validate(value: unknown) { + validationStarted.release(); + await validationReleased.promise; + return schema.validate(value); + } } }; + const execute = vi.fn(({ units }: ParsedInput) => ({ total: String(units) })); + const original = await client.define({ id, description: 'Quote an order', input: slowInput, output, execute }); + const originalRegistration = client.registry.get(id); + + const preflight = original.validate({ units: '2' }); + try { + await validationStarted.promise; + expect(client.registry.unregister(id)).toBe(true); + await client.register(id, originalRegistration); + } finally { + validationReleased.release(); + } + + await expect(preflight).resolves.toMatchObject({ valid: false, errors: [expect.objectContaining({ code: 'MODULE_NOT_FOUND' })] }); + await expect(original.invoke({ units: '2' })).rejects.toMatchObject({ code: 'MODULE_NOT_FOUND' }); + expect(execute).not.toHaveBeenCalled(); + await expect(client.call(id, { units: '2' })).resolves.toEqual({ total: 2 }); + }); + + it('rejects declarations without compatible validation and export contracts', async () => { + const client = new APCore(); + const { input, output } = schemas(); + const options = { id, description: 'Quote an order', input, output, execute: () => ({ total: '0' }) }; + const validationOnly = { '~standard': { ...input['~standard'], jsonSchema: undefined } }; + await expect(client.define({ ...options, input: validationOnly })).rejects.toThrow('Supply inputSchema explicitly'); + await expect(client.define({ ...options, inputSchema: { $schema: 'http://json-schema.org/draft-07/schema#' } })) + .rejects.toThrow('must use Draft 2020-12'); + const wrongVersion = { '~standard': { ...input['~standard'], version: 2 } } as unknown as typeof input; + await expect(client.define({ ...options, input: wrongVersion })).rejects.toThrow('must implement Standard Schema v1'); + await expect(client.define({ ...options, execute: null as unknown as typeof options.execute })) + .rejects.toThrow('requires an execute function'); + expect(client.registry.get(id)).toBeNull(); + }); + + it('preserves detailed Standard Schema issues in preflight and runtime failures', async () => { + const client = new APCore(); + const { input, output } = schemas(); + const execute = vi.fn(() => ({ total: '-1' })); + const module = await client.define({ id, description: 'Quote an order', input, output, execute }); + const errors = [ + { path: '/units', message: 'Units must be positive', keyword: 'standardSchema' }, + { path: '/options~1~0names/0', message: 'Invalid allocation', keyword: 'standardSchema' }, + ]; + const preflight = await module.validate({ units: '0' }); + expect(preflight.valid).toBe(false); + expect(preflight.errors).toContainEqual(expect.objectContaining({ code: 'SCHEMA_VALIDATION_ERROR', details: { errors } })); + await expect(module.invoke({ units: '0' })).rejects.toMatchObject({ code: 'SCHEMA_VALIDATION_ERROR', details: { errors } }); + await expect(client.call(id, { units: 1 })).rejects.toMatchObject({ code: 'SCHEMA_VALIDATION_ERROR' }); + expect(execute).not.toHaveBeenCalled(); + await expect(module.invoke({ units: '1' })).rejects.toMatchObject({ + code: 'SCHEMA_VALIDATION_ERROR', details: { errors: [{ path: '/total', message: 'Total must be nonnegative' }] }, + }); + }); + + it('uses detached normalized input for final evaluation, approval and execution', async () => { + const registry = new Registry(); + const approved: unknown[] = []; + const evaluate = vi.fn(async ({ arguments: args }: { arguments: Readonly> }) => { + const units = args['units']; + Reflect.set(args, 'units', 100); + return { decision: units === 6 ? 'require_approval' : 'deny' } as const; + }); + const executor = new Executor({ registry, policyEvaluator: { evaluate }, approvalHandler: { + supportsFinalScope: true, + async requestApproval(request) { + approved.push(request.arguments['units']); + Reflect.set(request.arguments, 'units', 200); + return createApprovalResult({ status: 'approved' }); + }, + async checkApproval() { return createApprovalResult({ status: 'rejected' }); }, + } }); + executor.useBefore((_name, args) => ({ units: String(Number(args['units']) * 2) })); + executor.addStepMiddleware({ beforeStep(name, state) { + if (name === 'execute') state.context.inputs = { units: 300 }; + } }); + const client = new APCore({ registry, executor }); + const { input, output } = schemas(); + const execute = vi.fn(({ units }: ParsedInput) => ({ total: String(units) })); + const module = await client.define({ id, description: 'Quote an order', input, output, execute }); + await expect(module.invoke({ units: '3' })).resolves.toEqual({ total: 6 }); + expect(evaluate).toHaveBeenCalledOnce(); + expect(approved).toEqual([6]); + expect(execute).toHaveBeenCalledExactlyOnceWith({ units: 6 }, expect.anything()); + await expect(module.invoke({ units: '4' })).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + expect(approved).toHaveLength(1); + expect(execute).toHaveBeenCalledOnce(); + }); + + it('keeps default approval before middleware and checks Standard Schema before dispatch', async () => { + const registry = new Registry(); + const observations: unknown[] = []; + const approvalHandler = new CallbackApprovalHandler(async request => { + observations.push(['approval', request.arguments['units']]); + return createApprovalResult({ status: 'approved' }); + }); + const executor = new Executor({ registry, approvalHandler }); + executor.useBefore((_name, args) => { + observations.push(['middleware', args['units']]); + return { units: '4' }; + }); + const client = new APCore({ registry, executor }); + const { input, output } = schemas(); + const module = await client.define({ + id, description: 'Quote an order', input, output, annotations: { requiresApproval: true }, + execute: ({ units }) => { + observations.push(['execute', units]); + return { total: String(units) }; + }, + }); + await expect(module.invoke({ units: '2' })).resolves.toEqual({ total: 4 }); + expect(observations).toEqual([['approval', '2'], ['middleware', '2'], ['execute', 4]]); + }); + + it('rejects non-wire results and skips execution when the validation step is unavailable', async () => { + const registry = new Registry(); + const client = new APCore({ registry, executor: new Executor({ registry, strategy: 'minimal' }) }); + const { input, output } = schemas(); + const execute = vi.fn(() => ({ total: '1' })); + const module = await client.define({ id, description: 'Quote an order', input, output, execute }); + await expect(module.invoke({ units: '1' })).rejects.toThrow('requires built-in input validation'); + expect(execute).not.toHaveBeenCalled(); + + const normalClient = new APCore(); + const invalidOutput: StandardSchemaV1 = { + '~standard': { version: 1, vendor: 'test-validator', validate: () => ({ value: { time: new Date() } }) }, + }; + const nonWire = await normalClient.define({ + id, description: 'Quote an order', input, output: invalidOutput, outputSchema: wireOutput, execute, + }); + await expect(nonWire.invoke({ units: '1' })).rejects.toMatchObject({ code: 'SCHEMA_VALIDATION_ERROR' }); + }); +});