Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion .github/workflows/case-pinning.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ jobs:

- name: Install SDKs
run: |
python3 -m pip install --quiet -e "./python[dev]"
python3 -m pip install --quiet -e "./python[all,dev]"
pnpm --dir typescript install --frozen-lockfile
cargo build --manifest-path rust/Cargo.toml --tests --all-features

Expand Down
18 changes: 12 additions & 6 deletions .github/workflows/packages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,15 @@ jobs:
cd "$temporary"
"$temporary/venv/bin/python" -m pip install "${wheel[0]}"
"$temporary/venv/bin/python" -m pip check
"$temporary/venv/bin/python" -c 'from apcore import APCore, Registry'
"$temporary/venv/bin/python" -c 'from apcore import APCore, Registry; from importlib.util import find_spec; assert all(find_spec(name) is None for name in ("yaml", "watchdog", "aiohttp", "opentelemetry"))'
"$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 governed-stream && "$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
"$temporary/full/bin/python" -c 'from apcore.full import APCore, Config; from apcore.events import SubscriberRegistry; assert APCore(config=Config.from_defaults()).registry is not None'
(cd governed-stream && "$temporary/full/bin/python" -I example.py)
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: core-python-distributions
Expand Down Expand Up @@ -82,7 +86,7 @@ jobs:
rust-version = "1.86"

[dependencies]
apcore = { path = "sdk", features = ["events"] }
apcore = { path = "sdk", features = ["config", "events"] }
async-trait = "0.1.92"
futures-util = "0.3"
serde_json = "1"
Expand Down Expand Up @@ -137,11 +141,13 @@ jobs:
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");
if (!url.endsWith("/dist/browser/index.js")) throw new Error("browser entry did not resolve");
await import("apcore-js");
if (!url.endsWith("/dist/index.js")) throw new Error("browser entry did not resolve to the portable root");
const core = await import("apcore-js");
if (!core.APCore || "Config" in core) throw new Error("invalid Core Profile exports");
EOF
node --conditions=browser --experimental-import-meta-resolve verify-browser.mjs
node --input-type=module -e 'import {accessSync} from "node:fs"; for (const entry of ["index", "browser/index", "context-keys"]) accessSync(`node_modules/apcore-js/dist/${entry}.d.ts`);'
node --input-type=module -e 'import {accessSync} from "node:fs"; for (const entry of ["index", "core", "full", "config-entry", "discovery", "events/entry", "context-keys"]) accessSync(`node_modules/apcore-js/dist/${entry}.d.ts`);'
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
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/sdk-python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ jobs:
python -m pip install --upgrade pip
# If a constraints.txt file is present, use it to pin critical dependency versions.
if [ -f constraints.txt ]; then
pip install -e ".[dev]" -c constraints.txt
pip install -e ".[all,dev]" -c constraints.txt
else
pip install -e ".[dev]"
pip install -e ".[all,dev]"
fi

- name: Verify canonical conformance fixture checkout
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/sdk-rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ jobs:
- name: Build
run: cargo build --locked --all-features

- name: Test the in-memory Core Profile
run: cargo test --locked --no-default-features --lib --test core_profile
env:
CONFORMANCE_SPEC_REPO: ${{ github.workspace }}

- name: Run tests
run: cargo test --locked --all-features
env:
Expand Down
21 changes: 20 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- 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.

### Changed

- **Protocol 2.0.0 draft for SDK 1.0.0.** The default Core Profile supports in-memory execution, with file-backed capabilities and host integrations supplied by explicit extension profiles. The built-in approval gate rejects calls that require approval when no handler is configured and requires approval for destructive modules by default. An explicit policy with `strict = false` and `gate_destructive = false` retains the earlier behavior during migration.
- Report the configured project version in the health summary and use the configured usage retention period.

### Fixed

- Reuse one Python synchronous event loop per calling thread. Bound nested workers and retain in-flight execution until its worker completes after timeouts.

### Removed

- Move Prometheus HTTP listening, A2A delivery, and provider-specific tool projections to Surfaces. Core retains text rendering, generic schema export, and strict schema conversion.
- Remove the deprecated `reload_dependents` input. Use `path_filter` to select dependent modules.

## [1.0.0-alpha.1]

This prerelease delivers the cross-repository governance and streaming fixes ahead of the microkernel package split. SDK installations use `1.0.0a1` for Python and `1.0.0-alpha.1` for TypeScript and Rust. The full package and configuration entry points remain available for adapter migration.

### Added

- **Protocol 2.1.0 draft, §6.7, §9.16.2, and §12.7.9.** Add managed drain and recovery hooks, async lifecycle adapters, host-directed cancellation before forced removal, opt-in reload reports, and lifecycle events across the three SDKs.
- **Managed lifecycle, §6.7, §9.16.2, and §12.7.9.** Add managed drain and recovery hooks, async lifecycle adapters, host-directed cancellation before forced removal, opt-in reload reports, and lifecycle events across the three SDKs.
- Add owned shutdown and ordered removal handles with independent wait budgets and lifecycle reports in Python, TypeScript, and Rust.
- Expose Prometheus text rendering without starting an HTTP listener in Python and Rust. TypeScript uses the existing exporter render method.
- Expose a single-invocation stream completion handle in Python, TypeScript, and Rust. The handle reports the output-validation snapshot, post-processing outcomes, and a distinct terminal reason.
Expand Down
9 changes: 7 additions & 2 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ All fixture files use **JSON** format (`.json`), with one intentional exception:

SDK conformance runners **must** load `.json` files with a JSON parser. The `.yaml` file is consumed directly by binding-loader tests, not by the generic conformance runner.

The `profile` field identifies the runtime profile exercised by a fixture.
`core` fixtures can run against a default in-memory SDK installation.
Configuration, Discovery, Events, and System Modules fixtures use their
declared extension. Adapter wire projections are verified in Surfaces.

> **Note for tooling authors:** Some ecosystem skill docs describe conformance fixtures as YAML; this is incorrect. The canonical format for all conformance test cases is JSON. The README is the authoritative format reference.

## Fixtures
Expand Down Expand Up @@ -62,7 +67,8 @@ SDK conformance runners **must** load `.json` files with a JSON parser. The `.ya
| `stream_aggregation.json` | — | Stream chunk deep-merge aggregation algorithm |
| `stream_post_processing.json` | D-20 | Native streams propagate cancellation from after-middleware and report ordinary post-processing failures as events |
| `stream_completion.json` | SDK streaming completion | One invocation reports its canonical output, individual post-processing outcomes, and termination through the opt-in stream handle |
| `approval_gate.json` | A05 | Approval gate Step 5: skip/fire conditions, result-status outcomes, and scoped resumption |
| `approval_gate.json` | A05 | Approval gate Step 5: explicit compatibility policy, result-status outcomes, and scoped resumption |
| `core_profile_governance.json` | §7.4, §7.9 | Core Profile defaults and explicit overrides through public preflight and execution, including an injected Executor |
| `approval_request_fields.json` | D-03 | `ApprovalRequest` carries `caller_id` (null for a top-level call) and `action` (= `module_id`) — fields the Contract text already required and no SDK's `ApprovalRequest` carried |
| `preflight_disclosure.json` | §12.8.5.1 | `Executor.validate()` withholds module-level introspection from a caller the ACL denied: no `module_preflight` / `module_preview` check, empty `predicted_changes`, and the hooks themselves not invoked. Module lookup is Step 3 and the ACL check is Step 4, so all three SDKs gated these hooks on "lookup succeeded" alone and ran module-authored code for a denied caller. Scoped to AUTHORIZATION: a failed `schema` check does **not** suppress introspection. Drivers MUST run the real `validate()` against a real Registry and ACL, and MUST observe hook invocation from inside the hook bodies — see `driver_contract` |
| `middleware_on_error_recovery.json` | A11 | After-middleware error recovery: first-dict-wins, null passthrough, success non-override |
Expand Down Expand Up @@ -112,7 +118,6 @@ SDK conformance runners **must** load `.json` files with a JSON parser. The `.ya
| `preflight_check_reporting.json` | §12.8, D-134, D-141 | `validate()` reports every check: a failure does not stop later checks and passed checks are never dropped; no module-dependent check when the module is unknown; `preview()` returning null adds no check; `predicted_changes` always present |
| `json_input_native_types.json` | type-mapping §17.3, D-136 | A module declared from native date-time / UUID / enum types accepts the JSON strings its schema accepts and still rejects what it rejects (a number for a date-time, a string outside the enum) |
| `binding_file_validation.json` | §5.12.2, §5.12.5, D-139 | Binding files fail loudly: unknown top-level / entry keys, a one-sided schema pair and an invalid `auto_schema` are `BINDING_FILE_INVALID`; an uninferable schema is `BINDING_SCHEMA_INFERENCE_FAILED` in every mode, implicit included; a complete entry with free-form `metadata` still loads |
| `export_profiles.json` | §4.17, Appendix D.1, D-140 | `anthropic` strips every `x-*` keyword but keeps a property NAMED `x-…`; `mcp` carries `requiresApproval` / `streaming` in `_meta` only when true, never in `annotations`, and keeps `x-*` |
| `env_prefix_dispatch.json` | §9.8.2, D-146 | `APCORE` is reserved for the `apcore` namespace (`CONFIG_NAMESPACE_RESERVED`), `APCORE_<X>` prefixes are legal, a variable is dispatched to exactly one namespace by longest prefix, an unmatched `APCORE_` variable belongs to `apcore` |
| `ephemeral_modules.json` | §2.5.1, D-148 | Exactly one registry audit event per ephemeral register / unregister under the standard bootstrap with `caller_id`, `identity` (or null) and `namespace_class`; the bare ID `ephemeral`; `INVALID_MODULE_ID` rejections from `register_internal` and discovery |
| `error_details_shape.json` | §8.1, D-149 | `SCHEMA_VALIDATION_ERROR` `details.errors` items are exactly `{path, keyword, message}`, `path` an RFC 6901 pointer (`""` for the root); serialized `details` keys are snake_case |
Expand Down
65 changes: 65 additions & 0 deletions conformance/check_config_key_consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,54 @@ def _usage_enabled() -> str | None:
return _group_probe("usage", {"system.usage.summary", "system.usage.module"})


@probe("sys_modules.usage.retention_hours")
def _usage_retention() -> str | None:
from datetime import datetime, timedelta, timezone

from apcore import Executor
from apcore.config import Config
from apcore.registry import Registry
from apcore.sys_modules.registration import register_sys_modules

def call_count(retention_hours: int) -> int:
config = Config.from_defaults()
config.set("sys_modules.enabled", True)
config.set("sys_modules.usage.retention_hours", retention_hours)
registry = Registry()
executor = Executor(registry, config=config)
context = register_sys_modules(registry, executor, config)
collector = context["usage_collector"]
now = datetime.now(timezone.utc)
for age in (5, 0):
collector.record("usage.sample", "probe", 1.0, True, (now - timedelta(hours=age)).isoformat())
return executor.call("system.usage.summary", {"period": "24h"})["total_calls"]

short, long = call_count(2), call_count(12)
if (short, long) != (1, 2):
return f"usage retention of 2h and 12h produced {(short, long)!r} calls, expected (1, 2)"
return None


@probe("sys_modules.usage.bucketing_strategy")
def _usage_bucketing() -> str | None:
from apcore.config import Config
from apcore.errors import ConfigError
from apcore.full import APCore

config = Config.from_defaults()
config.set("sys_modules.enabled", True)
config.set("sys_modules.usage.bucketing_strategy", "hourly")
APCore(config=config, fail_on_error=True).call("system.usage.summary", {})

config.set("sys_modules.usage.bucketing_strategy", "invalid")
try:
APCore(config=config, fail_on_error=True)
except ConfigError as exc:
if "bucketing_strategy" in str(exc):
return None
return "the system-module startup path accepted an invalid usage bucketing strategy"


@probe("sys_modules.control.enabled")
def _control_enabled() -> str | None:
"""The Level 2 write plane (6.7). The one an operator turns off deliberately."""
Expand Down Expand Up @@ -1214,6 +1262,23 @@ def manifest(name: str) -> object:
return None


@probe("project.version")
def _project_version() -> str | None:
from apcore.config import Config
from apcore.full import APCore

for version in ("1.2.3", "2.3.4"):
config = Config.from_defaults()
config.set("sys_modules.enabled", True)
config.set("project.name", "fixture")
config.set("project.version", version)
client = APCore(config=config, fail_on_error=True)
project = client.call("system.health.summary", {})["project"]
if project != {"name": "fixture", "version": version}:
return f"project.version={version!r} produced {project!r}"
return None


@probe("version")
def _config_version() -> str | None:
"""§9.3 requiredness: a document without it is rejected, one with it loads.
Expand Down
29 changes: 23 additions & 6 deletions conformance/check_doc_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,16 @@ def python_surface(sdk: Path) -> dict[str, set[str]]:
if all_m:
names |= set(re.findall(r'"(\w+)"', all_m.group(1)))
surface[dotted] = names

# The root's __getattr__ preserves explicit imports of extension symbols.
# Resolve those routes against their destinations as well as the root.
root = pkg / "__init__.py"
if root.is_file():
extensions = re.search(r"^_EXTENSION_EXPORTS\s*=\s*\{(.*?)^\}", root.read_text(), re.M | re.S)
if extensions:
for name, module in re.findall(r'"(\w+)":\s*"([\w.]+)"', extensions.group(1)):
if name in surface.get(module, ()):
surface["apcore"].add(name)
return surface


Expand Down Expand Up @@ -119,8 +129,15 @@ def sources(target):
}


def _typescript_file_exports(source: Path) -> set[str]:
"""Collect top-level declarations and explicit re-exports from source."""
def _typescript_file_exports(source: Path, visited: set[Path] | None = None) -> set[str]:
"""Collect top-level declarations and follow relative barrel re-exports."""
source = source.resolve()
if visited is None:
visited = set()
if source in visited:
return set()
visited.add(source)

src = source.read_text()
declaration = (r"export\s+(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?"
r"(?:class|function|const|let|var|interface|type|enum)\s+([\w$]+)")
Expand All @@ -135,10 +152,10 @@ def _typescript_file_exports(source: Path) -> set[str]:
)
if m:
names.add(m.group(1))
for star in re.findall(r"export\s+\*\s+from\s+['\"]\./([^'\"]+)['\"]", src):
p = source.parent / star.replace(".js", ".ts")
if p.is_file():
names.update(re.findall(declaration, p.read_text()))
for target in re.findall(r"export\s+\*\s+from\s+['\"](\.{1,2}/[^'\"]+)['\"]", src):
reexport = source.parent / (target.removesuffix(".js") + ".ts")
if reexport.is_file():
names.update(_typescript_file_exports(reexport, visited))
return names


Expand Down
Loading
Loading