import "std/schema"
/** The callback result is retained as a VM value; event payloads are JSON. */
pub type AgentEventCapture<T> = {result: T, events: list<unknown>}
pub type AgentEvent = {type: string, ...dict}
pub type AgentValidatedEventCapture = {result?: unknown, events: list<AgentEvent>, ...dict}
pub type AgentMutationStatus = "applied" | "unchanged" | "not_applied" | "unknown"
pub type AgentToolExecutor = "harn" | "host_bridge" | "mcp_server" | "provider_native"
type AgentToolEventFields = {
tool_call_id: string,
tool_name: string,
raw_input?: unknown,
raw_output?: unknown,
error?: unknown,
duration_ms?: int | float,
execution_duration_ms?: int | float,
error_category?: string,
executor?: unknown,
}
pub type AgentToolPendingEvent = {
type: "tool_call",
status: "pending",
...AgentToolEventFields,
...dict,
}
pub type AgentToolUpdateEvent = {
type: "tool_call_update",
status: "pending" | "in_progress" | "completed" | "failed",
mutation_status: AgentMutationStatus,
changed_paths?: list<string>,
data?: unknown,
...AgentToolEventFields,
...dict,
}
pub type AgentToolLifecycleEvent = AgentToolPendingEvent | AgentToolUpdateEvent
pub type AgentToolCallReceipt = {
schema_version: 1,
session_id: string,
run_id: string?,
tool_call_id: string,
tool_name: string,
iteration: int,
turn_index: int?,
emit_order: int,
reason: string?,
kind: string?,
executor: AgentToolExecutor?,
status: "ok" | "schema_violation" | "consent_denied" | "timeout" | "error",
error_category: string?,
duration_ms: int,
args_hash: string,
result_hash: string?,
audit: unknown,
emitted_at: string,
model: string?,
provider: string?,
}
pub type AgentToolAuditEvent = {
type: "tool_call_audit",
tool_call_id: string,
tool_name: string,
audit?: dict<string, unknown>,
receipt?: AgentToolCallReceipt,
...dict,
}
pub type AgentToolBatchPhase = "observation" \
| "mutation" \
| "process_verification" \
| "terminal" \
| "provider_native"
pub type AgentToolBatchDispositionReceipt = {
schema: "harn.agent_tool_batch_disposition.v1",
batch_id: string,
source_batch_id: string?,
call_index: int,
tool_call_id: string,
tool_name: string,
phase: AgentToolBatchPhase,
selected_phase: AgentToolBatchPhase,
disposition: "executed" | "deferred" | "skipped_after_blocking_result" | "resolved",
proposal_status: "new" | "re_proposed" | "confirmed",
retained_proposal_id?: string?,
source_tool_call_id?: string?,
reason: string,
planned_at_ms: int | float,
started_at_ms: int | float | nil,
finished_at_ms: int | float | nil,
duration_ms: int | float | nil,
blocking_tool_call_id: string?,
blocking_tool_name: string?,
blocking_mutation_status: string?,
}
pub type AgentToolBatchDispositionEvent = {
type: "tool_batch_disposition",
receipt: AgentToolBatchDispositionReceipt,
...dict,
}
pub type AgentToolBatchProposalResolution = {
proposal_id: string,
source_batch_id: string,
source_tool_call_id: string,
tool_name: string,
resolution: "confirmed" | "discarded" | "invalidated" | "superseded",
reason: string,
confirmation_call_id: string?,
pending_count: int,
}
pub type AgentToolBatchProposalResolutionEvent = {
type: "tool_batch_proposal_resolution",
resolution: AgentToolBatchProposalResolution,
...dict,
}
pub type AgentTypedCheckpoint = {
kind: string,
phase?: string,
iteration?: int,
attempt?: int,
context_overflow_recovery_attempt?: int,
provider?: string,
model?: string,
tool_format?: string,
final_wrapup?: bool,
...dict,
}
pub type AgentTypedCheckpointEvent = {
type: "typed_checkpoint",
checkpoint: AgentTypedCheckpoint,
...dict,
}
pub type AgentFeedbackInjectedEvent = {
type: "feedback_injected",
kind: string,
content: string,
streak?: int,
...dict,
}
pub type AgentNextToolClaimReceipt = {
iteration: int,
kind: "next_tool_claim_applied",
receipt_kind: "next_tool_claim_applied",
schema: "harn.agent_next_tool_claim_receipt.v1",
source: string,
status: "applied",
tool_name: string,
}
/**
* A shape owns presence and field types. Refinements retain the stricter
* value constraints, including optional fields that reject explicit nil.
*/
fn __agent_event_fields<T>(shape: Schema<T>, constraints: dict) -> Schema<T> {
return schema_refine(
shape,
schema_object(
constraints.map_values({ rule -> schema_field(rule, false) }),
{additional_properties: schema_any()},
),
)
}
fn __agent_closed_event_schema<T>(shape: Schema<T>) -> Schema<T> {
return schema_refine(shape, schema_extend(shape, {additional_properties: false}))
}
fn __agent_event_number_schema() {
return schema_union([schema_int(), schema_float()])
}
fn __agent_event_nonnegative_int_schema() {
return schema_int() + {min: 0}
}
fn __agent_event_digest_schema() {
return schema_string() + {pattern: "^[a-f0-9]{64}$"}
}
/**
* Generic schema for agent events captured by `agent_capture_events`.
*
* The runtime event stream is intentionally extensible: event-specific payload
* fields live beside the required `type` discriminator. Use the narrower
* schemas below when a consumer relies on a specific event family.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_event_schema() -> Schema<AgentEvent> {
return schema_of(AgentEvent)
}
/**
* Schema for captured event envelopes returned by `agent_capture_events`.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_event_capture_schema() -> Schema<AgentValidatedEventCapture> {
return schema_of(AgentValidatedEventCapture)
}
/**
* Schema for tool lifecycle events emitted by the agent loop.
*
* Covers `tool_call` and `tool_call_update` events that drive TUI/ACP tool
* progress, transcript integrity audits, and replay/debug tooling.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_tool_lifecycle_event_schema() -> Schema<AgentToolLifecycleEvent> {
return schema_refine(
__agent_event_fields(
schema_of(AgentToolLifecycleEvent),
{
duration_ms: __agent_event_number_schema(),
execution_duration_ms: __agent_event_number_schema(),
error_category: schema_string(),
},
),
schema_union(
[
schema_of(AgentToolPendingEvent),
__agent_event_fields(
schema_of(AgentToolUpdateEvent),
{changed_paths: schema_list(schema_string())},
),
],
),
)
}
/**
* Schema for typed tool-call receipts attached to `tool_call_audit` events.
*
* Matches the runtime's `ToolCallReceipt` wire shape: arguments/results are
* represented by hashes and nullable metadata fields serialize as explicit
* `nil` values.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_tool_call_receipt_schema() -> Schema<AgentToolCallReceipt> {
return __agent_event_fields(
__agent_closed_event_schema(schema_of(AgentToolCallReceipt)),
{
session_id: schema_string() + {min_length: 1},
tool_call_id: schema_string() + {min_length: 1},
tool_name: schema_string() + {min_length: 1},
iteration: __agent_event_nonnegative_int_schema(),
turn_index: schema_nullable(__agent_event_nonnegative_int_schema()),
emit_order: __agent_event_nonnegative_int_schema(),
duration_ms: __agent_event_nonnegative_int_schema(),
args_hash: __agent_event_digest_schema(),
result_hash: schema_nullable(__agent_event_digest_schema()),
},
)
}
/**
* Schema for tool-call audit events emitted by agent tooling and subagents.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_tool_audit_event_schema() -> Schema<AgentToolAuditEvent> {
return __agent_event_fields(
schema_of(AgentToolAuditEvent),
{audit: schema_dict(schema_any()), receipt: agent_tool_call_receipt_schema()},
)
}
/**
* Typed disposition/timing receipt for one call proposed in a model tool batch.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_tool_batch_disposition_receipt_schema() -> Schema<AgentToolBatchDispositionReceipt> {
return __agent_event_fields(
__agent_closed_event_schema(schema_of(AgentToolBatchDispositionReceipt)),
{
batch_id: __agent_event_digest_schema(),
source_batch_id: schema_nullable(__agent_event_digest_schema()),
call_index: __agent_event_nonnegative_int_schema(),
tool_name: schema_string() + {min_length: 1},
reason: schema_string() + {min_length: 1},
},
)
}
/**
* Agent event carrying a tool-batch disposition receipt.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_tool_batch_disposition_event_schema() -> Schema<AgentToolBatchDispositionEvent> {
return __agent_event_fields(
schema_of(AgentToolBatchDispositionEvent),
{receipt: agent_tool_batch_disposition_receipt_schema()},
)
}
/**
* A retained proposal changed authority without creating another tool attempt.
* @effects: []
* @errors: []
*/
pub fn agent_tool_batch_proposal_resolution_event_schema() -> Schema<
AgentToolBatchProposalResolutionEvent
> {
return __agent_event_fields(
schema_of(AgentToolBatchProposalResolutionEvent),
{
resolution: __agent_event_fields(
__agent_closed_event_schema(schema_of(AgentToolBatchProposalResolution)),
{
proposal_id: schema_string() + {min_length: 1},
source_batch_id: __agent_event_digest_schema(),
pending_count: __agent_event_nonnegative_int_schema(),
},
),
},
)
}
/**
* Schema for typed checkpoint events used by control, replay, and eval
* diagnostics.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_typed_checkpoint_event_schema() -> Schema<AgentTypedCheckpointEvent> {
return __agent_event_fields(
schema_of(AgentTypedCheckpointEvent),
{
checkpoint: __agent_event_fields(
schema_of(AgentTypedCheckpoint),
{
phase: schema_string(),
iteration: schema_int(),
attempt: schema_int(),
context_overflow_recovery_attempt: schema_int(),
provider: schema_string(),
model: schema_string(),
tool_format: schema_string(),
final_wrapup: schema_bool(),
},
),
},
)
}
/**
* Schema for runtime feedback injected into an agent session.
*
* The `kind` field is the semantic identity consumers should route on; the
* human-facing `content` may change without invalidating the event contract.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_feedback_injected_event_schema() -> Schema<AgentFeedbackInjectedEvent> {
return __agent_event_fields(
schema_of(AgentFeedbackInjectedEvent),
{kind: schema_string() + {min_length: 1}, streak: __agent_event_nonnegative_int_schema()},
)
}
/**
* Schema for a one-turn exact-tool contract applied to a model request. This
* receipt proves request actuation, not successful provider completion or tool
* execution; those have their own lifecycle events.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_next_tool_claim_receipt_schema() -> Schema<AgentNextToolClaimReceipt> {
return __agent_event_fields(
__agent_closed_event_schema(schema_of(AgentNextToolClaimReceipt)),
{
iteration: __agent_event_nonnegative_int_schema(),
source: schema_string() + {min_length: 1},
tool_name: schema_string() + {min_length: 1},
},
)
}
type AgentEventContractFailure = SchemaReport<never> & {ok: bool}
fn __agent_event_contract_report(value: unknown) -> AgentEventContractFailure? {
if type_of(value) != "dict" {
return nil
}
const event_type = to_string(value?.type ?? "")
if event_type == "tool_call" && to_string(value?.status ?? "") != "pending" {
const message = "tool_call lifecycle events must have status 'pending'"
return {ok: false, message: message, errors: [message], issues: []}
}
if event_type != "tool_call_update" {
return nil
}
if value?.mutation_status == nil {
const message = "missing required key 'mutation_status'"
return {ok: false, message: message, errors: [message], issues: []}
}
const mutation_status = to_string(value.mutation_status)
if !contains(["applied", "unchanged", "not_applied", "unknown"], mutation_status) {
const message = "mutation_status must be one of applied, unchanged, not_applied, unknown"
return {ok: false, message: message, errors: [message], issues: []}
}
return nil
}
/**
* Validate one captured agent event and return a structured schema report.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_event_report<T>(
value: unknown,
schema: dict | Schema<T> | nil = nil,
apply_defaults: bool = false,
) -> SchemaReport<T> {
const contract_report = __agent_event_contract_report(value)
if contract_report != nil {
return contract_report
}
return get_typed_report(value, schema ?? agent_event_schema(), apply_defaults)
}
/**
* Validate one captured agent event and return the typed value, throwing on
* validation failure.
*
* @effects: []
* @errors: [runtime]
* @api_stability: experimental
*/
pub fn agent_event_value<T>(
value: unknown,
schema: dict | Schema<T> | nil = nil,
apply_defaults: bool = false,
) -> T {
const contract_report = __agent_event_contract_report(value)
if contract_report != nil {
throw contract_report.message
}
return get_typed_value(value, schema ?? agent_event_schema(), apply_defaults)
}
/**
* Validate an `agent_capture_events` result and return a structured report.
*
* @effects: []
* @errors: []
* @api_stability: experimental
*/
pub fn agent_event_capture_report(
value: unknown,
apply_defaults: bool = false,
) -> SchemaReport<AgentValidatedEventCapture> {
return get_typed_report(value, agent_event_capture_schema(), apply_defaults)
}
/**
* Validate an `agent_capture_events` result and return the typed value,
* throwing on validation failure.
*
* @effects: []
* @errors: [runtime]
* @api_stability: experimental
*/
pub fn agent_event_capture_value(
value: unknown,
apply_defaults: bool = false,
) -> AgentValidatedEventCapture {
return get_typed_value(value, agent_event_capture_schema(), apply_defaults)
}
/**
* Capture agent events for session_id while body runs.
*
* @effects: [host]
* @errors: []
* @api_stability: experimental
*/
pub fn agent_capture_events<T>(
agent: HarnessAgent,
session_id: string,
body: fn() -> T,
) -> AgentEventCapture<T> {
const captured = agent.capture_events(session_id, body)
return {result: captured.result, events: captured.events}
}