agent_core#
transport-independent actions, schema validation, JSON-RPC, MCP and tasks -- crate root lib/agent_core/src/lib.rs
Transport-independent action contracts. New shared implementation; no corresponding module
exists in the frozen assembly reference.
action semantic action dispatch: Dispatcher, ActionSpec, ActionContext, ActionResult /
ActionError, batches, pages
schema statically registered input / output schemas (a JSON Schema subset), validation
rpc versioned newline JSON-RPC (Protocol, RpcSession) with MCP adapters; no I/O
task bounded cooperative tasks for long operations
json, jmap, record!, wire_enum! re-exports of formats::{json, jmap} (they lived here until
0.3.0; new code names formats)
agent_core crate root#
Re-exports: json::Value
Re-exports: formats::json
Re-exports: formats::jmap
Re-exports: formats::{record, wire_enum}
agent_core/src/action.rs#
Source: lib/agent_core/src/action.rs
Shared semantic action dispatch. GUI adapters and all external transports call this core.
New library code, independent of native windows, document types and language models.
enum ErrorCodeStable structured failure categories.Disabled-- External control has not been explicitly activated.NotFound-- The action or resource is unknown.InvalidInput-- Parameters fail their declared schema or bounds.CapabilityUnavailable-- The platform lacks a required capability.Unavailable-- The action is temporarily unavailable (including modal UI states).RevisionConflict-- The caller's expected revision differs from the current revision.Unsupported-- An operation or atomic transaction is unsupported.LimitExceeded-- A bounded collection or response limit was exceeded.Cancelled-- A task was cancelled at a defined interruption point.Internal-- The host violated its action contract or returned an internal failure.Forbidden-- The application or the user does not allow this action for external control.ConfirmationRequired-- The user was asked to confirm the action and has not answered yet; retry later.
impl ErrorCode
fn as_str(self) -> &'static strStable wire spelling.enum AccessWho may run an action through external control (agents, scripts over IPC / MCP).Open-- External calls run after the usual checks.Confirm-- The host asks the user before an external call runs (Host::confirm).Local-- Only trusted in-process GUI calls; external calls fail withforbidden.
impl Access
fn as_str(self) -> &'static strStable wire spelling ("open", "confirm", "local").struct ActionErrorAn actionable failure with structured details; no transport-specific error numbers.code: ErrorCode-- Stable error category.message: String-- Human-readable diagnosis.details: Value-- Structured correction details such as a field pointer or current revision.
impl ActionError
fn new(code: ErrorCode, message: impl Into<String>) -> SelfConstruct a failure without extra details.fn with_details(mut self, details: Value) -> SelfAttach machine-readable context.fn to_json(&self) -> ValueJSON form shared by batch, JSON-RPC and MCP results.struct ActionSpecA static semantic action contract. Register each implementation once in its host.name: &'static str-- Stable, language-independent identifier, e.g.document.text.replace.description: &'static str-- Description for human and automated discovery.input: &'static Schema-- Validated input schema.output: &'static Schema-- Validated completed-result schema.capabilities: u64-- Bit set of platform services required by this action; defined by the platform layer.mutation: bool-- Whether the action can change application or document state.revision_required: bool-- Require an expected revision for external mutation calls.undo: bool-- Whether the operation is integrated with the application's undo history.transaction: Option<&'static str>-- Transaction domain, or None when atomic batches are unsupported.cancellable: bool-- Whether the operation can return a cancellable task.command_id: Option<u32>-- Optional compatible numeric GUI command identifier.access: Access-- Who may run it through external control; hosts may tighten it (Host::access).
impl ActionSpec
const fn read(name: &'static str, description: &'static str) -> SelfParameterless read action with a general structured-object result.const fn confirm(mut self) -> SelfExternal calls need the user's confirmation first.const fn local_only(mut self) -> SelfOnly trusted in-process GUI calls; external control is refused.const fn write(name: &'static str, description: &'static str) -> SelfRevision-checked mutation; the caller can set undo and transaction metadata.const fn schemas(mut self, input: &'static Schema, output: &'static Schema) -> SelfReplace both schemas while preserving other metadata.struct ActionContextRequest metadata passed unchanged to registered handlers.expected_revision: Option<u64>-- Expected revision supplied by the caller and checked by the dispatcher.atomic: bool-- True when executing inside a host transaction.local: bool-- True for trusted in-process GUI commands, which may omit an expected revision.
struct ResourceSmall metadata link to binary/file data, kept out of state snapshots.uri: String-- Opaque application resource identifier.name: String-- Friendly name.mime_type: String-- Content media type.size: Option<u64>-- Exact payload byte count if known.
impl Resource
fn to_json(&self) -> ValueMetadata only; resource bytes are read separately.struct ActionResultAction completion or a deferred host-managed task.value: Value-- Completed structured output (Null for deferred work).revision: u64-- Current host revision after execution.task: Option<u64>-- Task identifier when execution continues asynchronously.resources: Vec<Resource>-- Metadata for optional separately readable payloads.
impl ActionResult
fn completed(value: Value, revision: u64) -> SelfReturn a completed result.fn deferred(task: u64, revision: u64) -> SelfReturn a task whose state can be queried or cancelled.fn to_json(&self) -> ValueShared structured wire response.trait HostApplication adapter; the dispatcher never invents domain semantics from pixels.fn actions(&self) -> &[ActionSpec]All registered action contracts, normally a static slice.fn revision(&self) -> u64Current document/application revision for optimistic concurrency control.fn capabilities(&self) -> u64Services currently available from the native or browser platform.fn availability(&self, _action: &ActionSpec) -> Result<(), ActionError>Check dynamic availability, including modal state, selection and permissions.fn access(&self, action: &ActionSpec) -> AccessWho may run the action externally: itsActionSpec::access, or stricter (the app's permission manifest).fn confirm(&mut self, _action: &ActionSpec, _input: &Value) -> Result<(), ActionError>Ask the user before an external call of anAccess::Confirmaction runs.Oklets it run;forbiddenwhen refused,confirmation_requiredwhile the question is open.fn refused(&mut self, _action: &ActionSpec)An external call of anAccess::Localaction was refused (an audit hook).fn execute( &mut self, action: &ActionSpec, input: &Value, context: &ActionContext, ) -> Result<ActionResult, ActionError>Execute the same handler used by GUI/keyboard command adapters.fn supports_transaction(&self, _domain: &str) -> boolWhether a named transaction domain supports reliable rollback.fn begin_transaction(&mut self, _domain: &str) -> Result<(), ActionError>Begin one undoable transaction. Atomic actions must complete synchronously.fn commit_transaction(&mut self) -> Result<(), ActionError>Commit all changes in the active transaction.fn rollback_transaction(&mut self) -> Result<(), ActionError>Restore state and revision to before begin_transaction.fn inspect(&self, _query: &Value) -> Result<Value, ActionError>Filtered, paginated semantic state; these control methods (inspect, tasks, resources) are not gated byaccess, so the host must apply its own access rules to them and should not hand out guessable task ids; hosts may accept asinceRevisionquery.fn task_status(&self, _id: u64) -> Result<Value, ActionError>Query a host-managed asynchronous task.fn task_cancel(&mut self, _id: u64) -> Result<Value, ActionError>Request cancellation at the task's next defined interruption point.fn resource_info(&self, _uri: &str) -> Result<Resource, ActionError>Metadata for one application-owned resource; arbitrary filesystem paths are not URIs.fn resource_read( &self, _uri: &str, _offset: u64, _limit: usize, ) -> Result<Vec<u8>, ActionError>Read a bounded resource slice. Offsets are bytes; unknown URIs must be rejected.
struct Invocation<'a>Borrowed single invocation.action: &'a str-- Stable action name.input: &'a Value-- Structured parameters.expected_revision: Option<u64>-- Expected revision for mutations.
struct BatchCallOwned invocation for an ordered batch.action: String-- Stable action name.input: Value-- Structured parameters.expected_revision: Option<u64>-- Revision at the moment this call should execute; atomic calls refer to the batch start.
struct BatchResultOrdered batch outcome, retaining the outcome of each attempted call.results: Vec<Result<ActionResult, ActionError>>-- Per-call results in original order.rolled_back: bool-- True if a failed atomic batch was rolled back successfully.revision: u64-- Current revision, including rollback.
impl BatchResult
fn to_json(&self) -> ValueStructured batch result.struct PageOne deterministic page of action discovery.actions: Vec<Value>-- Metadata of matching actions, without full schemas.next_cursor: Option<String>-- Exclusive action-name cursor for the next page.revision: u64-- Current state revision.
impl Page
fn to_json(&self) -> ValueShared discovery response.struct DispatcherActivation gate and deterministic dispatcher. Opening transports remains a host decision.
impl Dispatcher
const fn new() -> SelfConstruct with all external access disabled.fn set_enabled(&mut self, enabled: bool)Explicitly enable/disable control; transports should also close when disabled.fn enabled(&self) -> boolWhether external access was explicitly enabled.fn check_enabled(&self) -> Result<(), ActionError>Reject access before consulting application state.fn execute( &self, host: &mut impl Host, call: Invocation<'_>, ) -> Result<ActionResult, ActionError>Execute an enabled external action after schema, capability and revision checks.fn execute_local( &self, host: &mut impl Host, name: &str, input: &Value, ) -> Result<ActionResult, ActionError>Invoke a trusted GUI/shortcut command through the same schema and handler.fn execute_command( &self, host: &mut impl Host, id: u32, input: &Value, ) -> Result<ActionResult, ActionError>Resolve a legacy numeric GUI command to its registered semantic handler.fn batch( &self, host: &mut impl Host, calls: &[BatchCall], atomic: bool, stop_on_error: bool, ) -> Result<BatchResult, ActionError>Run an ordered batch. Atomic support and every static precondition are checked first.fn discover( &self, host: &impl Host, query: &str, after: Option<&str>, limit: usize, ) -> Result<Page, ActionError>Find actions by name/description, with stable lexical ordering and name cursors.fn describe(&self, host: &impl Host, name: &str) -> Result<Value, ActionError>Return schemas, behavior metadata and a concrete availability reason for one action.fn validate_registry(actions: &[ActionSpec]) -> Result<(), ActionError>Validate stable identifiers and prevent ambiguous name/command registrations.
agent_core/src/rpc.rs#
Source: lib/agent_core/src/rpc.rs
Versioned newline JSON-RPC plus MCP adapters. No I/O: transports supply complete lines.
New shared implementation, kept independent from OS streams and browser MessagePorts.
/// Application protocol revision carried by JSON control responses.
JSON_VERSION: &str = "1"
/// Current MCP revision, selected per request through params._meta.
MCP_VERSION: &str = "2026-07-28"
/// Explicitly supported initialization-based MCP revision.
MCP_LEGACY_VERSION: &str = "2025-11-25"
enum ProtocolOne transport chooses its protocol explicitly; there is no guessing from requests.Json-- jfguiLib JSON-RPC control protocol version 1.Mcp-- MCP with current per-request metadata or the supported legacy handshake.
fn requested_protocol(line: &[u8]) -> Option<Protocol>Select a connection's protocol from its first valid JSON-RPC envelope. An explicit modern MCP version or legacy initialization selects MCP; other requests select JSON v1. Malformed envelopes return None so transports can report them without locking the session.struct RpcSessionPer-connection protocol framing state; application state stays in the Host.
impl RpcSession
fn requires_persistent_session(&self) -> boolWhether initialization-based MCP negotiation must survive between requests. Stateless JSON/current-MCP browser sessions may be evicted when an inactive cache fills.fn new(protocol: Protocol, server_name: &str, server_version: &str) -> SelfCreate a protocol adapter without activating application control.fn handle( &mut self, dispatcher: &Dispatcher, host: &mut impl Host, line: &[u8], ) -> Option<String>Handle one UTF-8 JSON line, returning a newline-terminated response or no notification reply. This method never logs or writes standard streams. Use one session per connection.fn control( dispatcher: &Dispatcher, host: &mut impl Host, method: &str, params: &Value, ) -> Result<Value, ActionError>Execute the version-independent methods used by JSON and the MCP tool catalog.fn base64(bytes: &[u8]) -> StringBase64-encode a separately requested resource payload.
agent_core/src/schema.rs#
Source: lib/agent_core/src/schema.rs
Statically registered input/output schemas and runtime validation. New shared code.
enum SchemaSupported JSON Schema subset, represented without parsing schema text at runtime.Any-- Any bounded JSON value.Null-- Null only.Boolean-- Boolean only.Number-- Any syntactically valid JSON number.Integer { min: i64, max: i64, }-- Signed integer with inclusive bounds.Unsigned { min: u64, max: u64, }-- Unsigned integer with inclusive bounds, retaining all 64 bits.String { min: usize, max: usize, choices: &'static [&'static str], }-- Unicode string, with lengths in Unicode scalar values and optional allowed values.Array { items: &'static Schema, min: usize, max: usize, }-- Array whose items all follow one schema.Object { properties: &'static [Property], additional: bool, }-- Object with named properties and an explicit policy for unknown names.OneOf(&'static [Schema])-- Exactly one member schema must match.
struct PropertyNamed member of an object schema.name: &'static str-- Stable JSON member name.schema: &'static Schema-- Member validation contract.required: bool-- Whether omission is an error.
static EMPTY_OBJECT: SchemaEmpty object accepted by parameterless actions.static OBJECT: SchemaGeneral object, for extensible host results.static ANY: SchemaUnconstrained bounded value.static BOOLEAN: SchemaBoolean value.static U64: SchemaA full-width unsigned integer.static STRING: SchemaTypical short string.struct ViolationValidation error with a JSON Pointer to the invalid field.path: String-- JSON Pointer; empty means the root value.reason: &'static str-- Stable error category suitable for automated correction.
impl Schema
fn validate(&self, value: &Value) -> Result<(), Violation>Validate a value; unknown properties and missing required members are checked.fn to_json(&self) -> ValueEmit a JSON Schema 2020-12 compatible representation for discovery.
agent_core/src/task.rs#
Source: lib/agent_core/src/task.rs
Bounded cooperative tasks for long native/browser operations. New shared implementation.
enum StatusState of a cooperative host operation.Pending-- Queued but not started.Running-- Executing between interruption points.Cancelling-- Cancellation was requested; a host checkpoint still has to acknowledge it.Complete-- Finished successfully.Failed-- Finished with an action error.Cancelled-- Cancellation was acknowledged at an interruption point.
impl Status
fn as_str(self) -> &'static strStable status spelling.fn terminal(self) -> boolWhether no more computation should be performed.struct TaskOne task, isolated inside its app/connection owner.id: u64-- Monotonically allocated identifier; never reused by a table.action: String-- Semantic action that created the task.status: Status-- Current lifecycle state.progress: Option<u16>-- Progress in thousandths, when available.message: String-- Short host-provided progress description.cancellable: bool-- Whether cancellation is supported at host interruption points.result: Option<ActionResult>-- Completed result, available only in the Complete state.error: Option<ActionError>-- Terminal failure or cancellation diagnosis.
impl Task
fn to_json(&self) -> ValueCompact poll response. Binary resources remain links inside action results.struct TaskTableBounded in-memory task owner; a host drives work by calling checkpoint/update/finish.
impl TaskTable
fn new(capacity: usize) -> SelfCreate a table; capacity is clamped to 1..=1024 tasks.fn create(&mut self, action: &str, cancellable: bool) -> Result<u64, ActionError>Allocate a pending task. Completed tasks are retained until explicitly forgotten or, when the table is full, evicted oldest first.fn get(&self, id: u64) -> Result<&Task, ActionError>Inspect one task, without allowing external callers to mutate its state directly.fn request_cancel(&mut self, id: u64) -> Result<&Task, ActionError>Request cancellation; completion is reported only when the host acknowledges it.fn checkpoint(&mut self, id: u64) -> Result<bool, ActionError>Enter a safe interruption point. False means cancelled/finished; do no more work.fn update( &mut self, id: u64, progress: Option<u16>, message: &str, ) -> Result<(), ActionError>Update progress; host work must still call checkpoint before each interruptible chunk.fn finish(&mut self, id: u64, result: ActionResult) -> Result<(), ActionError>Finish a task. A pending cancellation must first be resolved at a checkpoint.fn fail(&mut self, id: u64, error: ActionError) -> Result<(), ActionError>Fail a pending/running task with structured diagnostic details.fn forget(&mut self, id: u64) -> Result<(), ActionError>Remove only a terminal task, retaining monotonic IDs to prevent accidental reuse.fn list(&self, after: u64, limit: usize) -> Result<Value, ActionError>One ID-ordered page of task metadata.