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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .github/workflows/packages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ jobs:
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)
(cd invocation-budget && "$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
Expand Down Expand Up @@ -118,10 +119,15 @@ jobs:
[[bin]]
name = "typed-module"
path = "typed-module/example.rs"

[[bin]]
name = "invocation-budget"
path = "invocation-budget/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)
(cd invocation-budget && cargo run --locked --quiet --manifest-path ../Cargo.toml --bin invocation-budget)
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: core-rust-distribution
Expand Down Expand Up @@ -170,10 +176,11 @@ 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 typed-module/example.ts
quick-start/example.ts governed-stream/example.ts typed-module/example.ts invocation-budget/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)
(cd invocation-budget && node ../compiled/invocation-budget/example.js)
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: core-npm-distribution
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **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.
- **Protocol 2.0.0 draft revision 3.** Add caller-scoped capability summaries and full-schema lookup using silent ACL visibility. Add the read-only `system.manifest.search` module with opaque cursors bound to the original requester.
- **Protocol 2.0.0 draft revision 4.** Add trusted identity delegation, scope-aware ACL grants, root-subject conditions, and authority binding for discovery cursors, policy input, and pending approval resumption.
- **Protocol 2.0.0 draft revision 5.** Define in-process call-tree budgets, progress and elicitation callbacks across the three SDKs. Bound the regex scan length in configured redaction. ([#244](https://github.com/aiperceivable/apcore/issues/244))

### Changed

Expand Down
1 change: 1 addition & 0 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ declared extension. Adapter wire projections are verified in Surfaces.
| `openai_strict_compat.json` | protocol-spec §5.12.5 | OpenAI structured-outputs strict-mode compatibility detection backing `BindingStrictSchemaIncompatibleError` on the `auto_schema: strict` binding path. Pins the supported/unsupported keyword set (`anyOf` supported except at root; `$ref`/`$defs` recursion supported; `oneOf`/`allOf`/`not`/`if`/`then`/`else`/`minLength`/`maxLength`/`patternProperties`/`uniqueItems`/… unsupported; nine supported `format` values) and the sorted, de-duplicated feature-path list all three SDKs must emit byte-identically. Detection never rewrites — an author-written `oneOf` is reported, not downgraded to `anyOf` — see `driver_contract`. |
| `schema_export_envelope.json` | §4.16 / A23 | `Registry.export_schema(module_id, strict)` envelope parity — exactly the four keys `schemas/module-schema-export.schema.json` declares. Descriptor metadata (`name`/`version`/`tags`/`annotations`/`examples`) belongs to `system.manifest.module`, and there is no sibling `definitions` key: `$defs` stay inside `input_schema`. Drivers MUST assert the key set EXACTLY — an extra key is the defect this pins. |
| `config_key_governance.json` | §9.1 / §9.3 / §9.15.3 | Governance of the configuration key surface: an SDK default or constraint table MUST stay inside the key set `apcore-config.schema.json` + `defaults.schema.json` + `sys-modules.schema.json` declare, and MUST reproduce every canonical default exactly. `allowed_keys` / `canonical_defaults` are derived from those schemas by `conformance/generate_config_key_governance.py` — never hand-edit them. |
| `call_budget.json` | Call-budget SDK contract | Governed calls reconcile estimated and actual cost, retain overruns, and stop admitting work after the configured count or cost limit. |
| `config_path_typed_keys.json` | §9.2.1 | The closed set of path-typed configuration keys, declared by `"x-apcore-path": true` in `apcore-config.schema.json`. Asserts the SDK accessor equals the declared set in BOTH directions, and that `bindings.pattern` (a glob, not a path) stays out. Asserts nothing about resolution bases — that is `config_project_root.json`'s subject (§9.2.2). |
| `config_project_root.json` | §9.2.2 / §9.14 | One captured project root across discovery tiers, explicit and symlinked loads, and subsequent working-directory changes. Pins filesystem paths from defaults, mappings, YAML, and environment overrides, including numeric names and trailing directory qualifiers. Drives the ACL and schema loaders against competing directories. |
| `schema_strict_conversion.json` | A23 / §4.16 | `to_strict_schema()` output parity: the exact strict-mode schema all three SDKs must emit. Pins the object-detection rule (`properties` alone identifies an object schema — `type` may be absent, `"object"`, or `["object", "null"]`; `properties` beside a non-object `type` is inert), the single nullable spelling (`{anyOf: [<original>, {type: "null"}]}` for a property with no `type` keyword or with `enum`, `const`, references or applicators — an author-written `oneOf`/`anyOf` is wrapped, never appended to), recursion into `prefixItems`/`items`/combinators/`$defs`, `x-*` + `default` stripping, and the sorted-and-complete `required` list. Drivers MUST call A23 directly — see `driver_contract`. |
Expand Down
12 changes: 12 additions & 0 deletions conformance/check_config_key_consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1387,6 +1387,18 @@ def _sensitive_keys() -> str | None:
return None


@probe("obs.redaction.max_regex_scan_length")
def _max_regex_scan_length() -> str | None:
"""The executor redacts values above the configured UTF-8 byte limit."""
out = _capture_point(
{"sensitive_keys": [], "regex_patterns": ["^secret$"], "max_regex_scan_length": 4},
{"probe_field": "ééé", "other_field": "éé"},
)
if out.get("probe_field") != "***REDACTED***" or out.get("other_field") != "éé":
return "executor did not enforce the configured UTF-8 regex scan limit"
return None


@probe("obs.redaction.regex_patterns")
def _regex_patterns() -> str | None:
"""A VALUE matching the key is redacted at the capture point; one that is not, is not."""
Expand Down
4 changes: 4 additions & 0 deletions conformance/config_key_consumers.json
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@
"reason": "No code path reads it.",
"tracking": "https://github.com/aiperceivable/apcore/issues/118"
},
"obs.redaction.max_regex_scan_length": {
"status": "live",
"probe": "obs.redaction.max_regex_scan_length"
},
"obs.redaction.regex_patterns": {
"status": "live",
"probe": "obs.redaction.regex_patterns"
Expand Down
1 change: 1 addition & 0 deletions conformance/extract_doc_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def main() -> None:
(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}"),
("docs/features/context-object.md", "invocation-budget", args.language, f"invocation-budget/example.{ext}"),
)
try:
files = [(args.destination / target, example(source, label, lang)) for source, label, lang, target in sources]
Expand Down
101 changes: 101 additions & 0 deletions conformance/fixtures/call_budget.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
{
"description": "Shared call-tree accounting through the public governed call entry point.",
"test_cases": [
{
"id": "settle_actual_cost_and_exhaust_call_count",
"module_id": "budget.fixture",
"max_calls": 2,
"max_cost": 5,
"estimated_cost": 2,
"calls": [
{
"actual_cost": 3
},
{
"actual_cost": 1
},
{
"actual_cost": 0
}
],
"expected": [
{
"calls_used": 1,
"calls_reserved": 0,
"cost_used": 3,
"error_code": null
},
{
"calls_used": 2,
"calls_reserved": 0,
"cost_used": 4,
"error_code": null
},
{
"calls_used": 2,
"calls_reserved": 0,
"cost_used": 4,
"error_code": "CALL_BUDGET_EXCEEDED"
}
]
},
{
"id": "keep_the_charge_for_an_actual_overrun",
"module_id": "budget.fixture",
"max_calls": null,
"max_cost": 3,
"estimated_cost": 1,
"calls": [
{
"actual_cost": 4
},
{
"actual_cost": 0
}
],
"expected": [
{
"calls_used": 1,
"calls_reserved": 0,
"cost_used": 4,
"error_code": "CALL_BUDGET_EXCEEDED"
},
{
"calls_used": 1,
"calls_reserved": 0,
"cost_used": 4,
"error_code": "CALL_BUDGET_EXCEEDED"
}
]
},
{
"id": "keep_the_estimate_if_the_module_does_not_report_cost",
"module_id": "budget.fixture",
"max_calls": 3,
"max_cost": 3,
"estimated_cost": 2,
"calls": [
{
"actual_cost": null
},
{
"actual_cost": null
}
],
"expected": [
{
"calls_used": 1,
"calls_reserved": 0,
"cost_used": 2,
"error_code": null
},
{
"calls_used": 1,
"calls_reserved": 0,
"cost_used": 2,
"error_code": "CALL_BUDGET_EXCEEDED"
}
]
}
]
}
1 change: 1 addition & 0 deletions conformance/fixtures/config_key_governance.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"logging.format",
"logging.level",
"middleware.disabled",
"obs.redaction.max_regex_scan_length",
"obs.redaction.regex_patterns",
"obs.redaction.replacement",
"obs.redaction.sensitive_keys",
Expand Down
126 changes: 124 additions & 2 deletions docs/features/context-object.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ For caller-identity semantics see [Identity System](./identity-system.md). For `
| Framework engine dependency | `trace_id`, `caller_id`, `call_chain`, `executor` | Removing any one breaks the framework |
| Almost always needed | `identity` | ACL is first-class; it needs a standardized "who" |
| Logging safety | `redacted_inputs`, `redacted_output` | Payload copies safe to log |
| Optional extensions | `cancel_token`, `services`, `global_deadline` | Cooperative cancellation, DI, call-tree budget |
| Optional extensions | `cancel_token`, `services`, `global_deadline` | Cooperative cancellation, dependency injection, and an absolute deadline |
| Generic bag | `data` | Pipeline state, locale, feature flags |

### Field Constraints
Expand Down Expand Up @@ -152,11 +152,133 @@ For cross-process transfer (distributed execution, task queues) a Context serial
TypeScript's `serialize()` / `deserialize()` remain as deprecated aliases of `toJSON()` / `fromJSON()`.

- Serialized: `_context_version: 1`, `trace_id`, `caller_id`, `call_chain`, `identity`, `data` (keys not starting with `_`), and `redacted_inputs` / `redacted_output` when set.
- Not serialized (runtime-only): `executor`, `cancel_token`, `services`, `global_deadline`.
- Not serialized (runtime-only): `executor`, `cancel_token`, `services`, `global_deadline`, and the invocation attachments described below.
- A `_context_version` greater than 1 logs a warning and deserialization proceeds best-effort.

After deserialization `executor` is null; the receiving Executor binds itself on the first call ([Executor binding to Context](./core-executor.md#contract-executor-binding-to-context)), synthesizes a fresh local `CancelToken`, and recomputes `global_deadline` from its own configuration. `services` is re-injected by the application.

### In-process invocation attachments

A host can derive a context with a shared call budget, a progress reporter,
or an elicitation handler. Child calls inherit the attachments. Reattach them
locally when reconstructing a context from serialized data.

A budget counts invocations that start business execution. Pending approval,
input rejection, and cancellation before dispatch release their reservations.
Each dispatched retry consumes a call. A host can assign a cost estimate in
integer units to each module. During execution, `record_cost` or `recordCost`
replaces the estimate once with the actual total for that attempt. On an
overrun, the method raises `CALL_BUDGET_EXCEEDED` and the actual charge stays
in the budget. Preflight runs independently of the budget.

=== "Python"

<!-- executable-example: invocation-budget -->
```python
from apcore import APCore, CallBudget, Context

client = APCore()
budget = CallBudget(max_calls=8, max_cost=20, estimated_costs={"reports.render": 2})
context = Context.create().with_budget(budget)


@client.module("reports.render", description="Render a report")
def render(context: Context) -> dict[str, bool]:
context.record_cost(3)
return {"rendered": True}


assert client.call("reports.render", {}, context) == {"rendered": True}
assert (budget.snapshot().calls_used, budget.snapshot().cost_used) == (1, 3)
client.close()
```

Use `with_progress_reporter` and `with_elicitation_handler` to attach
callbacks. Modules await `context.report_progress(...)` or
`context.elicit(...)` during execution.

=== "TypeScript"

<!-- executable-example: invocation-budget -->
```typescript
import assert from 'node:assert/strict';
import { APCore, CallBudget, Context } from 'apcore-js';

const client = new APCore();
const budget = new CallBudget({ maxCalls: 8, maxCost: 20, estimatedCosts: { 'reports.render': 2 } });
const context = Context.create().withBudget(budget);
await client.register('reports.render', {
description: 'Render a report',
inputSchema: { type: 'object' },
outputSchema: { type: 'object', properties: { rendered: { type: 'boolean' } } },
execute(_input: unknown, context: Context) {
context.recordCost(3);
return { rendered: true };
},
});
assert.deepEqual(await client.call('reports.render', {}, context), { rendered: true });
assert.deepEqual(budget.snapshot(), { callsUsed: 1, callsReserved: 0, costUsed: 3 });
await client.shutdown();
```

Use `withProgressReporter` and `withElicitationHandler` to attach
callbacks. Modules await `context.reportProgress(...)` or
`context.elicit(...)` during execution.

=== "Rust"

<!-- executable-example: invocation-budget -->
```rust
use apcore::{APCore, CallBudget, Context, ModuleError};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::HashMap, sync::Arc};

#[derive(Deserialize, JsonSchema, Serialize)]
struct RenderInput {}

#[derive(Deserialize, JsonSchema, Serialize)]
struct RenderOutput {
rendered: bool,
}

/// Render a report.
#[apcore::module(id = "reports.render")]
async fn render(_input: RenderInput, context: &Context<Value>) -> Result<RenderOutput, ModuleError> {
context.record_cost(3)?;
Ok(RenderOutput { rendered: true })
}

#[tokio::main]
async fn main() -> Result<(), ModuleError> {
let client = APCore::new();
render::DECLARATION.register(&client)?;
let budget = Arc::new(CallBudget::new(
Some(8),
Some(20),
HashMap::from([("reports.render".into(), 2)]),
)?);
let context = Context::<Value>::anonymous().with_budget(Some(Arc::clone(&budget)));
let result = render::HANDLE.invoke(&client, RenderInput {}, Some(&context)).await?;
assert!(result.rendered);
assert_eq!((budget.snapshot().calls_used, budget.snapshot().cost_used), (1, 3));
Ok(())
}
```

Use `with_progress_reporter` and `with_elicitation_handler` to attach
callbacks. Modules await `context.report_progress(...)` or
`context.elicit(...)` during execution.

Progress reporting has no effect when the host supplies no reporter.
Elicitation without a handler returns an empty optional result. With a
handler, the response indicates acceptance, decline, or cancellation.
Execution cancellation and the invocation deadline also apply to the callbacks.

Rust code that constructs a `Context { ... }` struct literal can migrate to
`Context::create(...)` or `Context::anonymous()` and apply the derivation methods.

## Edge Cases

| Scenario | Behavior | Level |
Expand Down
3 changes: 2 additions & 1 deletion docs/features/error-system.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,9 @@ Class names are the Python / TypeScript names; where the two differ, both are gi
| `CALL_DEPTH_EXCEEDED` | `CallDepthExceededError` | Exceeds max nesting depth (`details`: `depth`, `max_depth`, `call_chain`) |
| `CIRCULAR_CALL` | `CircularCallError` | Circular call detected (`details`: `module_id`, `call_chain`) |
| `CALL_FREQUENCY_EXCEEDED` | `CallFrequencyExceededError` | Module called too many times (`details`: `module_id`, `count`, `max_repeat`, `call_chain`) |
| `CALL_BUDGET_EXCEEDED` | `CallBudgetExceededError` (Python and TypeScript), `ErrorCode::CallBudgetExceeded` (Rust) | The call tree exceeded its call or cost limit. The nonretryable error reports the `dimension` as `calls` or `cost`. |

See [Call Chain Guard](./call-chain-guard.md) for when each is raised.
See [Call Chain Guard](./call-chain-guard.md) and [Call-tree budgets](./context-object.md#in-process-invocation-attachments) for the execution boundaries.

#### Binding Errors

Expand Down
Loading
Loading