콘텐츠로 이동

spakky-agent

spakky-agent는 Agent workflow를 Spakky 컴포넌트로 모델링하기 위한 계약, 도구, 상태, signal, evidence 타입을 제공합니다.

Agentic Hexagonal Architecture의 core 계약입니다.

설치

pip install spakky-agent

Structured output과 AgentSteeringUpdate의 검증에 사용하는 Pydantic은 런타임 의존성으로 함께 설치됩니다. 이 public API를 import하기 위해 개발 의존성을 따로 설치할 필요가 없습니다.

spakky-agent는 @Agent, AgentExecutionSpec, RunAgentInput, AgentRunner, AgentEvent, AgentYield, multimodal content, retrieval/memory, offline evaluation, pricing/telemetry, tool dispatch, context compaction, state/signal/evidence repository port, task store, safety/recovery/delegation 타입 같은 public contract를 소유합니다. 이 패키지는 의도적으로 LLM provider SDK, SQLAlchemy, FastAPI, Typer, AG-UI, A2A, MCP를 import하지 않습니다. 운영에서 durable execution을 사용하려면 provider contribution의 repository 구현이 필요하며, 운영용 in-memory fallback은 제공하지 않습니다.

Bounded iterative runner

execute()를 생략한 @Agent에는 framework-owned iterative loop가 합성됩니다. 각 model step은 terminal response와 whole tool batch를 모은 뒤 catalog/ID/signature/authority를 전부 검증합니다. Gate가 열리면 tool을 순차 dispatch하고 assistant tool-call message와 TOOL result message를 history에 추가해 다음 model step을 호출합니다. Tool call이 없는 valid terminal step에서 FINAL 또는 RUN_FINISHED를 정확히 한 번 방출합니다.

AgentExecutionSpec.limits의 타입은 AgentExecutionLimits이며 default는 다음과 같습니다.

필드 기본값 집행 시점
max_steps None 다음 model request 직전
max_tool_calls None candidate batch 전체 dispatch 직전
max_tokens None terminal usage 누적 직후와 다음 request preflight
max_cost None terminal step cost 누적 직후와 다음 request preflight
timeout_seconds None model과 async tool await의 invocation deadline

AgentExecutionSpec.timeout_seconds alias는 없습니다. max_tokens가 설정됐지만 provider가 ModelUsage.total_tokens를 주지 않으면 agent_usage_unavailable로 fail closed합니다. max_cost는 positive Decimal만 허용하며 operator ModelPricingCatalog가 없으면 첫 model request 전에 agent_cost_unavailable입니다. Streaming path와 NO_STREAM_UNTIL_FINAL_GUARDED의 complete() path는 같은 batch, authority, history, limit, terminal uniqueness 의미를 사용합니다.

Deadline이 있는 batch에 in-process sync tool이 포함되면 timeout을 실행 중 강제할 수 없으므로 runner가 전체 batch를 호출 전에 agent_sync_tool_timeout_unenforceable로 거부합니다. Async tool만 actual timeout 경계 안에서 실행됩니다.

Approval checkpoint는 call ID만 저장하지 않고 approval:{state_id}:{call_id}:{digest} fingerprint를 저장합니다. digest는 canonical JSON argument에 대한 full SHA-256이므로 persisted argument가 바뀌면 기존 승인을 재사용하지 않습니다. MODIFY 성공 시 pending call과 assistant tool_calls history 모두 최종 approved arguments로 교체됩니다.

Candidate-only provider stream은 run_events()가 missing tool START/END frame만 합성합니다. Signal hook의 Progress yield는 event surface에서 ArtifactEvent(name="signal_progress")가 되며 다른 yield shape는 agent_signal_projection_unsupported로 fail closed합니다.

Compaction은 assistant tool-call과 모든 correlated TOOL results를 하나의 group으로 보존합니다. Runner는 입력과 각 custom strategy 출력 직후 correlation을 검증하며 orphan 또는 incomplete group은 provider 호출 전에 agent_model_execution_failed로 종료합니다.

Protocol-neutral event step은 model-N, 실제 tool dispatch는 tool-N입니다. Message/reasoning ID와 missing tool-call ID도 model step과 batch index를 포함합니다. Step metadata와 durable model evidence는 누적 model/tool/token counter, provider usage, 제공된 actual route model_ref/profile/provider/model을 보존합니다. Protocol projector가 이 metadata 전체를 wire에 보존한다는 의미는 아닙니다.

Token budget failure도 현재 step의 route/usage/counters를 terminal metadata에 보존하고, durable path에서는 동일 snapshot과 typed error를 model-decision evidence로 남깁니다.

Revisioned steering

from spakky.agent import AgentSteeringUpdate로 공개 입력 계약을 가져옵니다. AgentSignal(kind=AgentSignalKind.STEERING_INSTRUCTION)의 payload에 update.model_dump(mode="json")을 넣습니다. Agent가 해당 signal kind를 허용하고 state·signal·evidence repository를 사용해야 적용됩니다.

AgentSteeringUpdate 필드 타입 기본값
input_id str 필수, 최소 길이 1
revision int 필수, 0 이상
content str 필수
final bool 필수
withdrawn bool False
retain bool False

계약은 frozen·strict이며 unknown field를 거부합니다. 같은 입력의 새 revision은 history를 교체하고, 낮은 revision과 동일 중복은 다시 적용하지 않습니다. 동일 revision의 상충 update는 AgentDefinitionError입니다. 철회는 입력 원문을 제거하되 revision tombstone을 보존합니다.

Runner는 모델 응답 대기 중 실행별 메일박스의 control 차선을 함께 기다립니다. CANCEL이나 AgentSignal(priority=AgentSignalPriority.URGENT) 변경은 진행 중 작업을 취소·cleanup한 뒤 다음 단계로 넘어가고, 일반 변경은 응답이 끝난 안전 지점에서 주입합니다. 실시간 전달 포트는 아래 Signal 절의 spakky.agent.mailbox와 ADR-0023을 참조하세요. final=False 입력이나 복원이 필요한 입력이 남아 있으면 도구와 final을 보류합니다. 미실행 pending call은 input_revised 결과로 닫고 이미 실행한 효과와 counter는 보존합니다. Progress(current_step="steering")의 invalidate_output=True는 이전 출력 무효화 알림이며, event surface에서는 signal_progress artifact입니다.

Steering-enabled 모델 요청과 provider event의 metadata["input_revision"]은 해당 iteration 시작 시 고정합니다. 초기값은 0이고, queue에 남은 옛 delta나 합성된 candidate-only tool START/END frame도 원래 값을 유지합니다. Tool-call metadata의 동명 key는 runner가 고정한 revision보다 우선하지 않습니다.

Checkpoint 원문은 final=True, retain=True인 입력에만 보존합니다. 나머지는 revision/hash로 식별하고 fresh resume에서 동일 update 재전달 또는 새 final revision·철회를 요구합니다. Revisioned 경로는 legacy hook과 raw SIGNAL evidence 기록을 거치지 않지만 signal 저장소와 파생 결과의 보존 정책은 애플리케이션이 소유합니다.

RunAgentInput.steering_input_required: bool = False를 True로 설정하면 최초 확정 입력 전 도구·final을 허용하지 않습니다. 관찰한 모든 입력이 철회되면 Cancel(reason="input_withdrawn"), metadata의 control_outcome="input_withdrawn"과 code="agent_input_withdrawn", state reason AgentStateReason.INPUT_WITHDRAWN을 사용합니다. Event surface는 RunFinishedEvent.error.code="cancelled"로 투영합니다. Resume에서는 이 flag를 유지해야 합니다. 상세 예제와 저장·프로토콜 경계는 실행 중 지시 수정에 있습니다.

Model selection과 capability

Core의 run-scoped 선택 계약은 logical ref 하나뿐입니다.

from spakky.agent import ModelSelection, RunAgentInput


run_input = RunAgentInput(
    state_id="run-42",
    instruction="요청을 분류해 주세요.",
    model_selection=ModelSelection(model_ref="support/primary"),
)

ModelSelection은 frozen dataclass이며 필수 model_ref: str 외에 provider, profile, physical model, metadata field를 두지 않습니다. Blank ref는 AgentDefinitionError입니다. Runner는 selection을 ModelRequest와 IAgentModel.capability_for()에 전달합니다. 고정 model adapter는 같은 capability를 반환할 수 있고, spakky-llm 같은 catalog-aware adapter는 opaque ref를 operator catalog에서 해석합니다.

ModelCapability은 reasoning, context window, token counting, input/output ModelModality, tools, structured output 지원 여부를 표현합니다. 기본값은 text input과 text output만 지원하고 나머지 optional capability는 꺼진 상태입니다. Logical route 구성과 protocol별 wire shape는 LLM 모델 라우팅을 확인하세요.

AgentModelStepRestartError는 model adapter가 stream()이나 complete()에서 raise해 진행 중인 model step의 출력을 버리고 같은 단계를 다시 하게 하는 공개 error입니다. Runner는 그 단계의 text를 transcript에 넣지 않고 tool call을 실행하지 않으며, Progress(metadata={"code": "agent_model_step_restarted", "invalidate_output": True})로 이미 내보낸 출력의 무효화를 알립니다. 버린 단계도 max_steps와 timeout에 들어갑니다.

AbstractAgentModelError는 provider가 이미 성공해 billable usage가 생긴 뒤 cache store 같은 framework 단계가 실패했을 때 ModelUsage와 privacy-safe routing receipt를 붙일 수 있는 model-error base입니다. Runner는 이 receipt를 token/cost counter와 MODEL evidence에 먼저 반영한 뒤 terminal error로 끝냅니다.

Multimodal content

ModelMessage.content는 legacy str 또는 ordered TextPart/ImagePart/AudioPart/ VideoPart/DocumentPart sequence입니다. Text-only DX는 ModelMessage.user("text")이고, runner inbound는 RunAgentInput(..., attachments=(image,))를 사용합니다. Attachment field는 기존 positional order 뒤에 추가됐으며 기본값은 empty tuple입니다.

Media part는 from_bytes()와 from_uri() 중 하나로 만들고 explicit MIME type을 요구합니다. MediaSafetyLimits 기본값은 HTTPS URI, aggregate media 16개, inline bytes 합계 20 MiB입니다. URI construction은 network I/O를 하지 않고 local literal/host/scheme shape만 검증합니다. Provider I/O 전 DNS authority는 spakky-llm의 replaceable media policy가 소유합니다.

ModelRequest.__post_init__()은 outer messages/context sequence를 tuple로 고정하고 request metadata를 defensive snapshot하며 aggregate media budget을 검증합니다. Async adapter 경계의 ModelRequest.snapshot()이 nested message/context/manifest/digest/tool/schema/metadata 전체를 defensive deep snapshot합니다. Request는 실제 content에서 required input modality를 계산하고, IAgentModel.validate_request()는 unsupported modality를 provider I/O 전에 거부합니다. 현재 ModelResponse.content는 text이며 generated non-text output의 공통 contract는 없습니다. 사용 예는 AI Agent 개발을 확인하세요.

Typed structured output

AgentExecutionSpec.output_type은 Pydantic BaseModel, 표준 dataclass, TypedDict class를 지원합니다. Declaration 단계에서 JSON Schema를 만들 수 없는 class, external/missing reference, non-finite JSON은 AgentDefinitionError로 거부됩니다. Pydantic이 만드는 JSON Schema 2020-12 keyword(minLength, pattern, minimum, format 등)는 그대로 두고, 재귀 model은 $defs/$ref로 표현합니다(ADR-0026). 내부 schema builder는 공개 API가 아니며 사용자는 output_type만 선언합니다.

Runner는 selected model의 supports_structured_output을 provider 호출 전에 확인합니다. Final structured payload는 strict type/no-extra/no-coercion으로 materialize되며 text JSON fallback은 없습니다. run()은 typed object를, run_events()는 JSON-safe output과 output_type metadata를 반환합니다. AG-UI는 JSON result, A2A는 output type 이름의 final data artifact로 투영합니다.

terminal code 의미
agent_structured_output_unsupported 선택 model capability가 structured output을 지원하지 않음
agent_structured_output_missing Tool call 없는 final step에 structured payload가 없음
agent_structured_output_ambiguous Payload가 여러 개이거나 한 step에 tool batch와 함께 존재
agent_structured_output_invalid Type/schema/extra/missing/serialization shape 검증 실패

output_type=None이면 기존 AgentRunResult가 유지됩니다. Event metadata에는 output을 추가하지 않으므로 AG-UI result는 None, A2A final output artifact는 없음이 정본입니다.

Static/dynamic typed context

RunAgentInput.context는 AgentContext(packs, manifest, digest) static envelope입니다. ContextPack은 ID/content/source/role, sensitivity, freshness/relevance와 ContextTokenBudget을 가집니다. Runner는 pack을 ModelRequest.context에 넣고 raw prompt concatenation 대신 ModelRequest.assemble_messages() 경계에서 guarded evidence message로 조립합니다.

Dynamic context는 constructor-injected IAgentContextProvider 하나가 provide(run_input, model_step) async port로 제공합니다. refresh_context_each_step=False는 한 invocation에서 첫 결과를 cache하고, True는 1-based model step마다 다시 호출합니다. Fresh resume은 raw provider context cache를 checkpoint하지 않고 provider를 다시 호출합니다.

Durable checkpoint는 raw static context 대신 prepared static context fingerprint만 저장합니다. Static context를 사용하던 run의 resume caller는 동일 RunAgentInput.context를 다시 제공해야 하며 model-bound prepared fingerprint가 다른 missing/different/additive context는 agent_checkpoint_invalid로 pending replay 전에 거부됩니다. Dynamic provider context는 resume에서 다시 취득합니다.

Static/dynamic pack ID는 전체에서 unique해야 합니다. Manifest는 모든 pack을 같은 순서·ID/source/role로 정확히 덮고 digest는 manifest와 전체 pack ID 순서를 덮어야 합니다. Dynamic provider return 또는 model-step combination의 partial digest/incomplete/conflicting provenance는 provider request 전에 agent_model_execution_failed; provider deadline 초과는 agent_timeout입니다. Runner는 digest linkage/coverage만 검증하며 declared digest value를 content에서 재계산하지 않습니다.

Model-safe preparation은 REDACTED content, sensitive-field guard, deterministic token-budget truncation을 적용하고 arbitrary metadata/descriptors 및 digest summary를 제거합니다. 유일한 예외는 exact key/type allowlist를 통과한 framework retrieval block이며 unknown key나 malformed value가 있으면 block 전체를 제거합니다. Durable context evidence도 raw content를 저장하지 않고 pack/provenance/budget/digest와 검증된 retrieval reference만 남깁니다. Evidence의 combined context fingerprint는 같은 model step의 동일 context를 deduplicate하고 변경된 context를 별개로 구분합니다.

RAG retrieval contracts

RAG는 IRetriever 결과를 model 호출 전에 RetrievalContext로 넣는 경로이고, agentic RAG는 같은 port를 RetrievalTool로 model-callable tool에 넣는 경로입니다. 기본 retrieval API는 IRetriever, RetrievalHit, RetrievalContext, RetrievalTool입니다.

RetrievalContext는 limit=5, max_context_tokens=2048, allow_empty=False가 기본입니다. RunAgentInput.instruction을 query로 사용하고 ordered hit를 JSON source frame이 앞선 budgeted evidence pack과 manifest로 변환합니다. 빈 결과는 direct 경계에서 AgentRetrievalError, runner에서는 provider request 전 agent_model_execution_failed입니다. allow_empty=True만 empty context로 계속 진행합니다.

RetrievalTool은 name="search", limit=5가 기본인 injected IAgentToolProvider입니다. Model-facing schema에는 query 하나만 있고 tenant/namespace/filter는 adapter 생성 시 고정됩니다. Result는 ordinary TOOL history로 다음 model step에 들어가며 tool 실행의 typed failure는 agent_tool_execution_failed입니다. 이 경로의 raw hit content는 normal tool history/evidence/checkpoint 의미를 따르며 classic context budget/redaction을 자동 적용하지 않습니다. 두 adapter 모두 arbitrary RetrievalHit.metadata를 model/evidence result에 복사하지 않습니다.

Runner는 일반 IAgentToolProvider도 provider instance에 method를 bind해 per-run catalog에 합치고 shared @Agent catalog는 mutate하지 않습니다. Wrong owner, already-bound callable, duplicate schema name은 model request 전에 AgentDefinitionError입니다.

Unscoped adapter는 unscoped hit만 허용하고, tenant/namespace를 명시하면 반환 hit도 exact scope여야 합니다. JSON이 아닌 filter, duplicate ID, blank framing field, non-finite score, malformed span과 wrong result type은 AgentRetrievalError로 fail closed합니다.

Vector 확장은 ITextEmbedding + IVectorSearch + VectorRetriever, optional IReranker + RerankedRetriever의 replaceable port 조합입니다. Core에는 vector backend, in-memory fallback, index write API가 없습니다. 사용 흐름은 Agent RAG, embedding route는 AI Agent 심화를 확인하세요.

Memory, evaluation, cost와 telemetry

ITaskStore는 USER/ASSISTANT conversation transcript 전용입니다. Long-term memory는 별도 IMemoryStore의 save(), search(), delete()와 immutable MemoryEntry revision을 사용합니다. MemoryRetriever는 tenant/user/namespace와 MemoryKind tuple을 bind한 IRetriever이며 expired entry, superseded revision과 store가 delete한 entry를 hit에서 제외합니다. Duplicate/cross-scope/conflicting correction과 active correction cycle은 AgentMemoryError입니다. Core에는 production memory backend가 없습니다.

Offline evaluation은 AgentEvaluationDataset(cases=tuple), case마다 정확히 하나인 AgentEvaluationSample tuple, AgentEvaluationSuite(evaluators=tuple)을 명시적으로 조합합니다. Built-in evaluator는 ordered tool trace, strict structured output, exact reference precision/recall, retrieval reference groundedness를 계산합니다. ModelJudgeEvaluator는 injected IModelJudge만 사용하며 default judge가 없습니다. Report의 evidence candidate는 metric/correlation만 가진 AgentEvidenceKind.EVALUATION이고 repository에 자동 append되지 않습니다. AgentEvidenceKind.SIGNAL은 일반 non-terminal inbound signal audit 전용이며 revisioned steering의 raw payload는 이 경로에 기록하지 않습니다. Case/sample의 structured JSON과 tool arguments/metadata는 construction 시 deep snapshot됩니다.

ModelPricingCatalog는 opaque logical model ref별 ModelPrice를 보존하는 immutable versioned snapshot입니다. Per-million rate와 cost는 Decimal이며 optional cached/generic write rate는 input rate, TTL-specific write rate는 generic write rate로 fallback합니다. Pricing이 주입되면 max_cost 유무와 관계없이 매 terminal model step을 계산합니다. Routed ref/price/input-output usage가 없거나 total/TTL cache usage가 inconsistent하거나 distinct TTL rate에 write category가 없으면 agent_cost_unavailable, cumulative amount가 limit보다 크면 agent_max_cost_exceeded입니다. Checkpoint는 pricing fingerprint와 cumulative cost를 묶어 changed pricing resume을 agent_checkpoint_invalid로 거부합니다. Resume은 completed step의 MODEL evidence route/full usage로 cost를 재계산해 exact step coverage와 checkpoint total을 대조합니다. Built-in price는 없습니다.

ModelUsage는 cached_input_tokens, total cache_write_input_tokens, TTL별 cache_write_5m_input_tokens/cache_write_1h_input_tokens도 표현합니다. AgentSpanRecord는 RUN, MODEL, TOOL, RETRIEVAL의 completed nanosecond interval과 scalar metadata만 IAgentTelemetry.record()에 전달합니다. Prompt/context/completion, retrieval query/content, tool arguments/results는 core record에 넣지 않습니다. Sink failure는 AgentTelemetryError입니다. 전체 사용법과 실패 경계는 Agent Memory, Evaluation, Cost와 Telemetry를 확인하세요.

Durable checkpoint evidence

Durable runner는 state metadata의 raw checkpoint를 저장할 때마다 append-only AgentEvidenceKind.CHECKPOINT revision을 추가합니다. Evidence에는 revision, model step, history length, JSON shape size와 SHA-256 fingerprint가 들어가며 inline media body 자체를 복제하지 않습니다. Resume은 repository 반환 순서와 무관하게 가장 큰 revision을 선택하고 checkpoint revision/shape/fingerprint를 media base64 decode와 URI reconstruction보다 먼저 검증합니다. Older matching revision replay, missing/duplicate revision과 tampered body/limit/URI는 agent_checkpoint_invalid입니다.

Initial user history와 media safety limits는 MODEL evidence의 history length/input fingerprint에도 결속됩니다. Resume은 모든 completed model step의 evidence coverage와 같은 fingerprint를 요구합니다. Compaction summary는 raw media bytes 대신 bounded [media attachments: N] marker만 사용하고, checkpoint의 token/cost counters는 기존 usage/pricing evidence로 재검증됩니다. Raw checkpoint에는 inline media가 base64로 들어가므로 state repository의 접근·보존 정책은 애플리케이션이 소유합니다.

Checkpoint fingerprint는 원 conversation_id, user_turn, persist_session_turn도 포함합니다. Resume 호출의 임시 instruction은 restored history와 ITaskStore transcript를 바꾸지 않으며, 성공 또는 실패 뒤 server-side transcript에는 원 사용자 turn이 저장됩니다. Conversation이나 checkpoint-bound field가 달라지면 pending action 전에 agent_checkpoint_invalid입니다.

Public API

Agentic hexagonal architecture contracts for Spakky Framework.

DEFAULT_MEDIA_SAFETY_LIMITS = MediaSafetyLimits() module-attribute

Conservative default: HTTPS references and at most 20 MiB inline bytes.

Message = Progress module-attribute

Backward-compatible progress-yield payload alias.

TextDelta = Token module-attribute

Backward-compatible token-yield payload alias.

PLUGIN_NAME = Plugin(name='spakky-agent') module-attribute

Plugin identifier for the Spakky Agent package.

AgentCancellationCleanupCallable = Callable[[AgentCancellationRequest], Awaitable[AgentCancellationCleanupResult]]

Async hook shape invoked for model stream/tool/delegate cancellation cleanup.

AgentEvent = MessageDeltaEvent | ReasoningDeltaEvent | ToolCallStartEvent | ToolCallArgsDeltaEvent | ToolCallEndEvent | ToolCallResultEvent | RunStartedEvent | RunPausedEvent | RunFinishedEvent | StepStartedEvent | StepFinishedEvent | StateSnapshotEvent | StateDeltaEvent | ArtifactEvent | CustomEvent

Discriminated union of every protocol-neutral agent event.

Each member exposes a distinct kind literal so adapters dispatch with match/case exhaustiveness rather than runtime attribute probing.

JsonObject = Mapping[str, JsonValue]

JSON object payload used by public agent contracts.

JsonPrimitive = bool | float | int | str | None

Scalar JSON value accepted by agent public contracts.

JsonValue = JsonPrimitive | Mapping[str, JsonValue] | Sequence[JsonValue]

Recursive JSON-compatible value used at model, signal, and evidence boundaries.

AudioPart(media_type, uri=None, data=None, source=None, content_digest=None, _limits=DEFAULT_MEDIA_SAFETY_LIMITS) dataclass

Bases: _MediaPart

Portable audio input from a remote URI or bounded inline bytes.

DocumentPart(media_type, uri=None, data=None, source=None, content_digest=None, _limits=DEFAULT_MEDIA_SAFETY_LIMITS, filename=None) dataclass

Bases: _MediaPart

Portable application/text document input with explicit MIME provenance.

from_uri(uri, *, media_type, filename=None, source=None, content_digest=None, limits=DEFAULT_MEDIA_SAFETY_LIMITS) classmethod

Create a remote document with optional provider-facing filename.

Source code in core/spakky-agent/src/spakky/agent/content.py
@classmethod
@override
def from_uri(
    cls,
    uri: str,
    *,
    media_type: str,
    filename: str | None = None,
    source: str | None = None,
    content_digest: str | None = None,
    limits: MediaSafetyLimits = DEFAULT_MEDIA_SAFETY_LIMITS,
) -> Self:
    """Create a remote document with optional provider-facing filename."""
    return cls(
        media_type=media_type,
        uri=uri,
        filename=filename,
        source=source,
        content_digest=content_digest,
        _limits=limits,
    )

from_bytes(data, *, media_type, filename=None, source=None, content_digest=None, limits=DEFAULT_MEDIA_SAFETY_LIMITS) classmethod

Create an inline document with optional provider-facing filename.

Source code in core/spakky-agent/src/spakky/agent/content.py
@classmethod
@override
def from_bytes(
    cls,
    data: bytes,
    *,
    media_type: str,
    filename: str | None = None,
    source: str | None = None,
    content_digest: str | None = None,
    limits: MediaSafetyLimits = DEFAULT_MEDIA_SAFETY_LIMITS,
) -> Self:
    """Create an inline document with optional provider-facing filename."""
    return cls(
        media_type=media_type,
        data=data,
        filename=filename,
        source=source,
        content_digest=content_digest,
        _limits=limits,
    )

ImagePart(media_type, uri=None, data=None, source=None, content_digest=None, _limits=DEFAULT_MEDIA_SAFETY_LIMITS) dataclass

Bases: _MediaPart

Portable image input from a remote URI or bounded inline bytes.

MediaSafetyLimits(max_inline_bytes=20 * _MEBIBYTE, max_media_parts=16, allowed_uri_schemes=frozenset({'https'}), allowed_uri_hosts=None) dataclass

Replaceable vendor-neutral limits applied when media enters the model port.

__post_init__()

Reject unbounded or malformed media limits.

Source code in core/spakky-agent/src/spakky/agent/content.py
def __post_init__(self) -> None:
    """Reject unbounded or malformed media limits."""
    if (
        isinstance(self.max_inline_bytes, bool)
        or not isinstance(self.max_inline_bytes, int)
        or self.max_inline_bytes <= 0
    ):
        raise AgentDefinitionError("Inline media byte limit must be positive")
    if (
        isinstance(self.max_media_parts, bool)
        or not isinstance(self.max_media_parts, int)
        or self.max_media_parts <= 0
    ):
        raise AgentDefinitionError("Media part limit must be positive")
    if (
        not isinstance(self.allowed_uri_schemes, frozenset)
        or not self.allowed_uri_schemes
    ):
        raise AgentDefinitionError("Media URI schemes must be a nonempty frozenset")
    for scheme in self.allowed_uri_schemes:
        if (
            not isinstance(scheme, str)
            or fullmatch(_SCHEME_PATTERN, scheme) is None
            or scheme in _FORBIDDEN_URI_SCHEMES
        ):
            raise AgentDefinitionError("Media URI scheme is invalid")
    if self.allowed_uri_hosts is not None:
        if (
            not isinstance(self.allowed_uri_hosts, frozenset)
            or not self.allowed_uri_hosts
        ):
            raise AgentDefinitionError(
                "Media URI hosts must be a nonempty frozenset"
            )
        for host in self.allowed_uri_hosts:
            if (
                not isinstance(host, str)
                or host == ""
                or host != host.rstrip(".").casefold()
                or any(character.isspace() for character in host)
                or any(character in host for character in "/@?#")
            ):
                raise AgentDefinitionError("Media URI host authority is invalid")

TextPart(text) dataclass

One ordered text segment inside a multimodal model message.

VideoPart(media_type, uri=None, data=None, source=None, content_digest=None, _limits=DEFAULT_MEDIA_SAFETY_LIMITS) dataclass

Bases: _MediaPart

Portable video input where a selected provider supports it.

AgentCustomEvents

Emit application-defined events into the stream of the current run.

listening() staticmethod

Return whether emit would reach a consumer from this context.

Code that also runs outside a merged stream (a plain runner.run(), a background job) checks this before emitting.

Source code in core/spakky-agent/src/spakky/agent/custom_event.py
@staticmethod
def listening() -> bool:
    """Return whether ``emit`` would reach a consumer from this context.

    Code that also runs outside a merged stream (a plain ``runner.run()``,
    a background job) checks this before emitting.
    """
    channel = _CHANNEL.get()
    return channel is not None and channel.open

emit(name, value, *, metadata=None) staticmethod

Put a named custom event on the stream of the current run.

The event keeps its position relative to other events emitted by the same producer and is delivered without waiting for the runner's next event.

Parameters:

Name Type Description Default
name str

Application-defined event name; namespace it (for example "myapp.turn_part") to stay clear of adapter-reserved names.

required
value JsonValue

JSON-compatible payload relayed to the client unchanged.

required
metadata JsonObject | None

Neutral event metadata for in-process consumers. None means unspecified and is stored as an empty object.

None

Raises:

Type Description
AgentCustomEventChannelUnavailableError

No merged stream is listening in this context.

AgentDefinitionError

name is blank.

Source code in core/spakky-agent/src/spakky/agent/custom_event.py
@staticmethod
def emit(
    name: str,
    value: JsonValue,
    *,
    metadata: JsonObject | None = None,
) -> None:
    """Put a named custom event on the stream of the current run.

    The event keeps its position relative to other events emitted by the
    same producer and is delivered without waiting for the runner's next
    event.

    Args:
        name: Application-defined event name; namespace it (for example
            ``"myapp.turn_part"``) to stay clear of adapter-reserved names.
        value: JSON-compatible payload relayed to the client unchanged.
        metadata: Neutral event metadata for in-process consumers. ``None``
            means unspecified and is stored as an empty object.

    Raises:
        AgentCustomEventChannelUnavailableError: No merged stream is
            listening in this context.
        AgentDefinitionError: ``name`` is blank.
    """
    channel = _CHANNEL.get()
    if channel is None or not channel.open:
        raise AgentCustomEventChannelUnavailableError
    channel.put(
        CustomEvent(
            attribution=channel.attribution,
            name=name,
            value=value,
            metadata=metadata if metadata is not None else {},
        )
    )

merge(events, attribution) async staticmethod

Yield events interleaved live with custom events emitted meanwhile.

Parameters:

Name Type Description Default
events AsyncIterator[AgentEvent]

The neutral source stream, typically runner.run_events().

required
attribution AgentEventAttribution

Attribution stamped on every emitted custom event.

required

Yields:

Type Description
AsyncGenerator[AgentEvent, None]

Source events in source order and custom events in emit order.

AsyncGenerator[AgentEvent, None]

Custom events still queued when the source ends are yielded before

AsyncGenerator[AgentEvent, None]

the merged stream ends.

Raises:

Type Description
Exception

Whatever the source raises, after every item queued before the failure has been yielded.

Source code in core/spakky-agent/src/spakky/agent/custom_event.py
@staticmethod
async def merge(
    events: AsyncIterator[AgentEvent],
    attribution: AgentEventAttribution,
) -> AsyncGenerator[AgentEvent, None]:
    """Yield ``events`` interleaved live with custom events emitted meanwhile.

    Args:
        events: The neutral source stream, typically ``runner.run_events()``.
        attribution: Attribution stamped on every emitted custom event.

    Yields:
        Source events in source order and custom events in emit order.
        Custom events still queued when the source ends are yielded before
        the merged stream ends.

    Raises:
        Exception: Whatever the source raises, after every item queued
            before the failure has been yielded.
    """
    channel = _AgentCustomEventChannel(attribution)
    # A task copies its context when it is created, so the channel is bound
    # in the copy the pump runs in. The caller's context is left untouched:
    # an enclosing merge keeps its own channel, and there is no token to
    # reset from whichever context happens to close this generator.
    context = copy_context()
    context.run(_CHANNEL.set, channel)
    pump = create_task(channel.pump(events), context=context)
    source_finished = False
    try:
        while True:
            item = await channel.next()
            if item is None:
                source_finished = True
                break
            yield item
            channel.delivered()
        # The pump queues the end marker as its last action, so it is done;
        # awaiting it re-raises the source's failure or cancellation.
        await pump
    finally:
        channel.close()
        if not source_finished:
            # The consumer stopped early (closed or cancelled): stop the
            # source too and wait for its cleanup before returning.
            pump.cancel()
            await wait((pump,))
            AgentCustomEvents._raise_source_cleanup_failure(pump)

AgentCustomEventChannelUnavailableError

Bases: AbstractSpakkyAgentError

Raised when a custom event is emitted where no merged stream is listening.

AbstractSpakkyAgentError

Bases: AbstractSpakkyFrameworkError, ABC

Base class for agent-related errors.

AgentBootstrapError

Bases: AbstractSpakkyAgentError

Raised when agent bootstrap validation fails.

AgentDefinitionError

Bases: AbstractSpakkyAgentError

Raised when an agent contract cannot be defined safely.

AgentModelConfigurationError

Bases: AgentBootstrapError

Raised when an agent requires a model adapter but none is registered.

AgentMemoryError

Bases: AbstractSpakkyAgentError

Raised when long-term memory cannot safely cross its scoped boundary.

AgentOutputGuardError

Bases: AbstractSpakkyAgentError

Raised when an output guard detects unsafe streaming exposure.

AgentPersistenceConfigurationError

Bases: AgentBootstrapError

Raised when production agent persistence is required but not provided.

AgentRetrievalError

Bases: AbstractSpakkyAgentError

Raised when retrieval results cannot safely enter an agent run.

AgentSignalInboxConflictError

Bases: AbstractSpakkyAgentError

Raised when one runner opens two live inboxes for the same agent state.

AgentSignalMailboxConfigurationError

Bases: AgentBootstrapError

Raised when a run must wait for live input but has no signal mailbox.

AgentToolBindingError

Bases: AbstractSpakkyAgentError

Raised when a model tool-call payload cannot be bound safely.

AgentToolDispatchError

Bases: AbstractSpakkyAgentError

Raised when a model tool call names a tool absent from the catalog.

AgentToolDispatcher(target, catalog, runtime_context=None) dataclass

Resolve and invoke a catalog tool from a model tool call.

The dispatcher binds to a single agent instance whose @agent_tool methods are described by catalog. Catalog descriptors that own no instance parameter (such as MCP-normalized external tools) are invoked without the bound target.

descriptor_for(call)

Resolve the catalog descriptor a model tool call targets.

Source code in core/spakky-agent/src/spakky/agent/dispatcher.py
def descriptor_for(self, call: ModelToolCall) -> AgentToolDescriptor:
    """Resolve the catalog descriptor a model tool call targets."""
    for descriptor in self.catalog.descriptors:
        if descriptor.schema.name == call.name:
            return descriptor
    raise AgentToolDispatchError("Agent tool call names an unregistered tool")

dispatch(call) async

Bind a model tool call payload and invoke its catalog callable.

Source code in core/spakky-agent/src/spakky/agent/dispatcher.py
async def dispatch(self, call: ModelToolCall) -> object:
    """Bind a model tool call payload and invoke its catalog callable."""
    descriptor = self.descriptor_for(call)
    invocation = descriptor.bind_invocation(call.arguments)
    callable_ = descriptor.callable
    positional = self._with_injected_prefix(callable_, invocation.args)
    if iscoroutinefunction(callable_):
        awaitable: Awaitable[object] = callable_(
            *positional,
            **invocation.kwargs,
        )
        return await awaitable
    return callable_(*positional, **invocation.kwargs)

AgentRunExtension

Bases: ABC

Base of a typed application value carried by a run and its model requests.

An application subclasses it, usually as a frozen dataclass, instead of putting string keys into metadata. The runner copies a run's extensions into every model request, and a model adapter reads one with request.extension(Type). A run carries at most one extension of each type.

AgentContext(packs=(), manifest=None, digest=None) dataclass

Typed context supplied statically or by one injected provider.

ContextDigest(id, context_identity, source_manifest_ref, digest, derived_from_pack_ids=tuple(), compression_evidence_ref=None, algorithm=None, summary=None, created_at=None, metadata=dict()) dataclass

Derived compression evidence for a context identity.

ContextFreshness

Bases: StrEnum

Freshness classification for context rot and budget decisions.

ContextHealthSignal(id, symptom, manifest_ref=None, pack_id=None, evidence_ref=None, score=None, observed_at=None, metadata=dict()) dataclass

Observed context rot signal used to choose optimization actions.

evidence_payload()

Return JSON-compatible signal metadata for append-only evidence.

Source code in core/spakky-agent/src/spakky/agent/context.py
def evidence_payload(self) -> Mapping[str, JsonValue]:
    """Return JSON-compatible signal metadata for append-only evidence."""
    return {
        "id": self.id,
        "symptom": self.symptom.value,
        "manifest_ref": self.manifest_ref,
        "pack_id": self.pack_id,
        "evidence_ref": self.evidence_ref,
        "score": self.score,
        "observed_at": self.observed_at.isoformat()
        if self.observed_at is not None
        else None,
        "metadata": self.metadata,
    }

ContextManifest(id, entries, origin_ref=None, evidence_refs=tuple(), created_at=None, metadata=dict()) dataclass

Auditable composition record for model input context packs.

ContextManifestEntry(pack_id, source, role, origin_ref, evidence_ref=None, digest_ref=None, sensitive_fields=(), metadata=dict()) dataclass

One audited pack entry inside a context manifest.

ContextOptimizationAction(id, kind, signal_refs=tuple(), target_pack_ids=tuple(), manifest_ref=None, digest_ref=None, delegation_ref=None, result_evidence_ref=None, reason=None, metadata=dict()) dataclass

Selected optimization action derived from context health signals.

evidence_payload()

Return JSON-compatible action metadata without raw context contents.

Source code in core/spakky-agent/src/spakky/agent/context.py
def evidence_payload(self) -> Mapping[str, JsonValue]:
    """Return JSON-compatible action metadata without raw context contents."""
    return {
        "id": self.id,
        "kind": self.kind.value,
        "signal_refs": tuple(self.signal_refs),
        "target_pack_ids": tuple(self.target_pack_ids),
        "manifest_ref": self.manifest_ref,
        "digest_ref": self.digest_ref,
        "delegation_ref": self.delegation_ref,
        "result_evidence_ref": self.result_evidence_ref,
        "reason": self.reason,
        "metadata": self.metadata,
    }

ContextOptimizationActionKind

Bases: StrEnum

Optimization actions that can be selected from context health signals.

ContextOptimizationEvidenceStage

Bases: StrEnum

Where an optimization action evidence item sits in the agent flow.

ContextPack(id, content, source, role, freshness=ContextFreshness.UNKNOWN, relevance=None, token_budget=ContextTokenBudget(), sensitivity=ContextSensitivity.INTERNAL, sensitive_fields=(), metadata=dict(), placement=ContextPlacement.TRAILER) dataclass

LLM-facing context unit derived from state, signal, or evidence.

guarded_content(policy=None)

Return deterministic model-safe content for this context pack.

Source code in core/spakky-agent/src/spakky/agent/context.py
def guarded_content(
    self,
    policy: ContextExposurePolicy | None = None,
) -> str:
    """Return deterministic model-safe content for this context pack."""
    exposure_policy = policy or ContextExposurePolicy()
    if self.sensitivity == ContextSensitivity.REDACTED:
        return "[REDACTED]"
    guarded = guard_json_value(
        {"content": self.content},
        tuple(
            SensitiveFieldDescriptor(
                ("content", *descriptor.path), descriptor.field
            )
            for descriptor in self.sensitive_fields
        ),
        exposure_policy,
    )
    content = cast(Mapping[str, JsonValue], guarded).get("content")
    if isinstance(content, str):
        return content
    return "[REDACTED]"

message_metadata(policy=None)

Return non-content metadata for provider-neutral model messages.

Source code in core/spakky-agent/src/spakky/agent/context.py
def message_metadata(
    self,
    policy: ContextExposurePolicy | None = None,
) -> Mapping[str, JsonValue]:
    """Return non-content metadata for provider-neutral model messages."""
    exposure_policy = policy or ContextExposurePolicy()
    metadata: dict[str, JsonValue] = {
        "context_pack_id": self.id,
        "source": self.source,
        "role": self.role.value,
        "freshness": self.freshness.value,
        "relevance": self.relevance,
        "token_budget": {
            "max_tokens": self.token_budget.max_tokens,
            "estimated_tokens": self.token_budget.estimated_tokens,
            "reserved_output_tokens": self.token_budget.reserved_output_tokens,
        },
        "sensitivity": self.sensitivity.value,
        "metadata": self.metadata,
    }
    if exposure_policy.include_sensitive_context_metadata and self.sensitive_fields:
        metadata["sensitive_fields"] = tuple(
            descriptor.to_metadata() for descriptor in self.sensitive_fields
        )
    return metadata

ContextPlacement

Bases: StrEnum

Where a context pack sits in the assembled model prompt.

A stable prompt prefix is what lets a provider reuse its prompt cache. Packs that stay the same for a whole run belong before the conversation history; packs that change each step belong after it.

SYSTEM = 'system' class-attribute instance-attribute

Joined into the leading system section, after the agent instructions.

PRELUDE = 'prelude' class-attribute instance-attribute

A separate message after the system section and before the history.

TRAILER = 'trailer' class-attribute instance-attribute

A separate message after the history (the default).

ContextPackRole

Bases: StrEnum

Semantic role of a context pack inside a model request.

ContextRotSymptom

Bases: StrEnum

Typed context rot symptoms observed before model input assembly.

ContextSensitivity

Bases: StrEnum

Deterministic sensitivity metadata carried before model input.

ContextTokenBudget(max_tokens=None, estimated_tokens=None, reserved_output_tokens=None) dataclass

Token budget allocated to one context pack.

IAgentContextHandler

Bases: ABC

Select context optimization actions from health signals and manifests.

select_optimization_actions(signals, manifest) abstractmethod

Return optimization actions without mutating raw evidence.

Source code in core/spakky-agent/src/spakky/agent/context.py
@abstractmethod
def select_optimization_actions(
    self,
    signals: Sequence[ContextHealthSignal],
    manifest: "ContextManifest",
) -> Sequence[ContextOptimizationAction]:
    """Return optimization actions without mutating raw evidence."""
    ...

IAgentContextProvider

Bases: ABC

Optional async port that supplies context for one model step.

provide(run_input, model_step) abstractmethod async

Return context for the 1-based model step.

Source code in core/spakky-agent/src/spakky/agent/context.py
@abstractmethod
async def provide(
    self,
    run_input: "RunAgentInput",
    model_step: int,
) -> AgentContext:
    """Return context for the 1-based model step."""
    ...

AgentCancellationCleanupReport(state_id, signal_id, outcomes=()) dataclass

Aggregate cleanup evidence for one CANCEL signal.

cleanup_succeeded property

Return whether all cleanup hooks completed without failure.

failed_outcomes property

Return the hook outcomes that force FAILED terminal state.

__post_init__()

Reject reports that cannot be attached to state and signal evidence.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def __post_init__(self) -> None:
    """Reject reports that cannot be attached to state and signal evidence."""
    _require_non_blank(self.state_id, "Agent cancellation report state id")
    _require_non_blank(self.signal_id, "Agent cancellation report signal id")

to_payload()

Serialize the report for state metadata and evidence payloads.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def to_payload(self) -> JsonObject:
    """Serialize the report for state metadata and evidence payloads."""
    return {
        "state_id": self.state_id,
        "signal_id": self.signal_id,
        "cleanup_succeeded": self.cleanup_succeeded,
        "outcomes": tuple(outcome.to_payload() for outcome in self.outcomes),
    }

to_evidence_candidate(*, summary=None)

Represent cancellation cleanup as append-only evidence.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def to_evidence_candidate(
    self,
    *,
    summary: str | None = None,
) -> AgentEvidenceCandidate:
    """Represent cancellation cleanup as append-only evidence."""
    return AgentEvidenceCandidate(
        kind=AgentEvidenceKind.CANCELLATION,
        payload=self.to_payload(),
        summary=summary,
    )

AgentCancellationCleanupResult(target_kind, target_ref, status, reason=None, error_code=None, message=None, metadata=dict()) dataclass

Result returned by one cancellation cleanup hook.

failed_cleanup property

Return whether this hook prevents a clean CANCELLED terminal state.

__post_init__()

Reject outcomes that cannot be correlated with the cleanup target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def __post_init__(self) -> None:
    """Reject outcomes that cannot be correlated with the cleanup target."""
    _require_non_blank(self.target_ref, "Agent cancellation cleanup target ref")
    _require_optional_non_blank(self.reason, "Agent cancellation cleanup reason")
    _require_optional_non_blank(
        self.error_code,
        "Agent cancellation cleanup error code",
    )
    _require_optional_non_blank(self.message, "Agent cancellation cleanup message")

succeeded(*, target_kind, target_ref, reason=None, metadata=None) classmethod

Record a cleanup hook that released its target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
@classmethod
def succeeded(
    cls,
    *,
    target_kind: AgentCancellationTargetKind,
    target_ref: str,
    reason: str | None = None,
    metadata: JsonObject | None = None,
) -> "AgentCancellationCleanupResult":
    """Record a cleanup hook that released its target."""
    return cls(
        target_kind=target_kind,
        target_ref=target_ref,
        status=AgentCancellationCleanupStatus.SUCCEEDED,
        reason=reason,
        metadata={} if metadata is None else metadata,
    )

failed(*, target_kind, target_ref, error_code, message, metadata=None) classmethod

Record a cleanup hook that could not release its target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
@classmethod
def failed(
    cls,
    *,
    target_kind: AgentCancellationTargetKind,
    target_ref: str,
    error_code: str,
    message: str,
    metadata: JsonObject | None = None,
) -> "AgentCancellationCleanupResult":
    """Record a cleanup hook that could not release its target."""
    return cls(
        target_kind=target_kind,
        target_ref=target_ref,
        status=AgentCancellationCleanupStatus.FAILED,
        error_code=error_code,
        message=message,
        metadata={} if metadata is None else metadata,
    )

skipped(*, target_kind, target_ref, reason, metadata=None) classmethod

Record a cleanup target that was already inactive or unavailable.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
@classmethod
def skipped(
    cls,
    *,
    target_kind: AgentCancellationTargetKind,
    target_ref: str,
    reason: str,
    metadata: JsonObject | None = None,
) -> "AgentCancellationCleanupResult":
    """Record a cleanup target that was already inactive or unavailable."""
    return cls(
        target_kind=target_kind,
        target_ref=target_ref,
        status=AgentCancellationCleanupStatus.SKIPPED,
        reason=reason,
        metadata={} if metadata is None else metadata,
    )

to_payload()

Serialize this hook outcome into evidence/state metadata.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def to_payload(self) -> JsonObject:
    """Serialize this hook outcome into evidence/state metadata."""
    return {
        "target_kind": self.target_kind.value,
        "target_ref": self.target_ref,
        "status": self.status.value,
        "reason": self.reason,
        "error_code": self.error_code,
        "message": self.message,
        "metadata": self.metadata,
    }

AgentCancellationCleanupStatus

Bases: StrEnum

Outcome of one cancellation cleanup hook.

AgentCancellationCleanupTask(target_kind, target_ref, cleanup, metadata=dict()) dataclass

One cleanup hook registered for a running cancellation target.

__post_init__()

Reject hooks that cannot be identified in cleanup evidence.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def __post_init__(self) -> None:
    """Reject hooks that cannot be identified in cleanup evidence."""
    _require_non_blank(self.target_ref, "Agent cancellation cleanup target ref")

run(*, state, signal) async

Invoke the hook and verify that it reports the same target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
async def run(
    self,
    *,
    state: AgentState,
    signal: AgentSignal,
) -> AgentCancellationCleanupResult:
    """Invoke the hook and verify that it reports the same target."""
    request = AgentCancellationRequest.from_signal(
        state=state,
        signal=signal,
        target_kind=self.target_kind,
        target_ref=self.target_ref,
        metadata=self.metadata,
    )
    result = await self.cleanup(request)
    if (
        result.target_kind is not self.target_kind
        or result.target_ref != self.target_ref
    ):
        raise AgentDefinitionError(
            "Agent cancellation cleanup result target must match the task"
        )
    return result

AgentCancellationRequest(state_id, signal_id, target_kind, target_ref, reason=None, requested_by=None, metadata=dict()) dataclass

Cancellation request passed to a model stream, tool, or delegate hook.

__post_init__()

Reject requests that cannot be traced back to state/signal/target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def __post_init__(self) -> None:
    """Reject requests that cannot be traced back to state/signal/target."""
    _require_non_blank(self.state_id, "Agent cancellation state id")
    _require_non_blank(self.signal_id, "Agent cancellation signal id")
    _require_non_blank(self.target_ref, "Agent cancellation target ref")
    _require_optional_non_blank(self.reason, "Agent cancellation reason")
    _require_optional_non_blank(self.requested_by, "Agent cancellation requester")

from_signal(*, state, signal, target_kind, target_ref, metadata=None) classmethod

Build a hook request from the durable CANCEL signal payload.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
@classmethod
def from_signal(
    cls,
    *,
    state: AgentState,
    signal: AgentSignal,
    target_kind: AgentCancellationTargetKind,
    target_ref: str,
    metadata: JsonObject | None = None,
) -> "AgentCancellationRequest":
    """Build a hook request from the durable CANCEL signal payload."""
    _require_cancel_signal(signal)
    _require_signal_matches_state(state, signal)
    return cls(
        state_id=state.id,
        signal_id=signal.id,
        target_kind=target_kind,
        target_ref=target_ref,
        reason=_optional_string(signal.payload, "reason"),
        requested_by=_optional_string(signal.payload, "requested_by"),
        metadata={} if metadata is None else metadata,
    )

to_payload()

Serialize the request into append-only evidence metadata.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def to_payload(self) -> JsonObject:
    """Serialize the request into append-only evidence metadata."""
    return {
        "state_id": self.state_id,
        "signal_id": self.signal_id,
        "target_kind": self.target_kind.value,
        "target_ref": self.target_ref,
        "reason": self.reason,
        "requested_by": self.requested_by,
        "metadata": self.metadata,
    }

AgentCancellationTargetKind

Bases: StrEnum

Running execution target that can receive a cancellation cleanup hook.

AgentEvidence(id, agent_state_id, kind, payload=dict(), summary=None, digest=None, manifest_ref=None, reference=None, sensitive_fields=(), created_at=None, model_step=None, origin_refs=()) dataclass

Append-only artifact captured during an agent execution.

model_step = None class-attribute instance-attribute

Model step whose context this evidence records, for step-scoped kinds.

origin_refs = () class-attribute instance-attribute

Source references the recorded model context was built from.

AgentEvidenceCandidate(kind, payload=dict(), summary=None, digest=None, manifest_ref=None, reference=None, sensitive_fields=(), model_step=None, origin_refs=()) dataclass

Append-only evidence candidate before repository id assignment.

tool_result(*, tool_identity, tool_schema_name, result, capture, sensitive_fields=(), exposure_policy=None, summary=None) classmethod

Create evidence metadata for a captured tool result.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def tool_result(
    cls,
    *,
    tool_identity: str,
    tool_schema_name: str,
    result: JsonObject,
    capture: EvidenceCapture,
    sensitive_fields: tuple[SensitiveFieldDescriptor, ...] = (),
    exposure_policy: EvidenceExposurePolicy | None = None,
    summary: str | None = None,
) -> "AgentEvidenceCandidate":
    """Create evidence metadata for a captured tool result."""
    _require_non_blank(tool_identity, "Agent tool identity")
    _require_non_blank(tool_schema_name, "Agent tool schema name")
    policy = exposure_policy or EvidenceExposurePolicy()
    guarded_result = guard_json_value(result, sensitive_fields, policy)
    if not isinstance(guarded_result, Mapping):
        guarded_result = {}
    return cls(
        kind=AgentEvidenceKind.TOOL,
        payload={
            "tool_identity": tool_identity,
            "tool_schema_name": tool_schema_name,
            "capture": capture.value,
            "result": guarded_result,
        },
        sensitive_fields=sensitive_fields
        if policy.include_sensitive_metadata
        else (),
        summary=summary,
    )

model_decision(*, model, decision, summary=None) classmethod

Create evidence metadata for a model decision.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def model_decision(
    cls,
    *,
    model: str,
    decision: JsonObject,
    summary: str | None = None,
) -> "AgentEvidenceCandidate":
    """Create evidence metadata for a model decision."""
    _require_non_blank(model, "Agent model name")
    return cls(
        kind=AgentEvidenceKind.MODEL,
        payload={"model": model, "decision": decision},
        summary=summary,
    )

tool_decision(*, tool_identity, decision, summary=None) classmethod

Create evidence metadata for a tool-routing decision.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def tool_decision(
    cls,
    *,
    tool_identity: str,
    decision: JsonObject,
    summary: str | None = None,
) -> "AgentEvidenceCandidate":
    """Create evidence metadata for a tool-routing decision."""
    _require_non_blank(tool_identity, "Agent tool identity")
    return cls(
        kind=AgentEvidenceKind.TOOL,
        payload={"tool_identity": tool_identity, "decision": decision},
        summary=summary,
    )

context_optimization(*, action, stage, signals=(), summary=None) classmethod

Create before/after evidence for a context optimization action.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def context_optimization(
    cls,
    *,
    action: ContextOptimizationAction,
    stage: ContextOptimizationEvidenceStage,
    signals: Sequence[ContextHealthSignal] = (),
    summary: str | None = None,
) -> "AgentEvidenceCandidate":
    """Create before/after evidence for a context optimization action."""
    _require_non_blank(action.id, "Context optimization action id")
    return cls(
        kind=AgentEvidenceKind.CONTEXT_OPTIMIZATION,
        payload={
            "stage": stage.value,
            "action": action.evidence_payload(),
            "signals": tuple(signal.evidence_payload() for signal in signals),
        },
        summary=summary,
        digest=action.digest_ref,
        manifest_ref=action.manifest_ref,
        reference=action.result_evidence_ref,
    )

evaluation(*, evaluator, metric, passed, score, case_ref, sample_ref) classmethod

Create privacy-safe evidence for one offline evaluation metric.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def evaluation(
    cls,
    *,
    evaluator: str,
    metric: str,
    passed: bool,
    score: float,
    case_ref: str,
    sample_ref: str,
) -> "AgentEvidenceCandidate":
    """Create privacy-safe evidence for one offline evaluation metric."""
    _require_non_blank(evaluator, "Agent evaluator name")
    _require_non_blank(metric, "Agent evaluation metric")
    _require_non_blank(case_ref, "Agent evaluation case reference")
    _require_non_blank(sample_ref, "Agent evaluation sample reference")
    if not isinstance(passed, bool):
        raise AgentDefinitionError("Agent evaluation pass value must be boolean")
    if (
        isinstance(score, bool)
        or not isinstance(score, int | float)
        or not isfinite(score)
        or not 0 <= score <= 1
    ):
        raise AgentDefinitionError(
            "Agent evaluation score must be between zero and one"
        )
    return cls(
        kind=AgentEvidenceKind.EVALUATION,
        payload={
            "evaluator": evaluator,
            "metric": metric,
            "passed": passed,
            "score": float(score),
            "case_ref": case_ref,
            "sample_ref": sample_ref,
        },
        summary="offline agent evaluation result",
        reference=case_ref,
    )

to_evidence(*, evidence_id, agent_state_id, created_at=None)

Assign repository identity while preserving append-only contents.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
def to_evidence(
    self,
    *,
    evidence_id: str,
    agent_state_id: str,
    created_at: datetime | None = None,
) -> AgentEvidence:
    """Assign repository identity while preserving append-only contents."""
    _require_non_blank(evidence_id, "Agent evidence id")
    _require_non_blank(agent_state_id, "Agent state id")
    return AgentEvidence(
        id=evidence_id,
        agent_state_id=agent_state_id,
        kind=self.kind,
        payload=self.payload,
        summary=self.summary,
        digest=self.digest,
        manifest_ref=self.manifest_ref,
        reference=self.reference,
        sensitive_fields=self.sensitive_fields,
        created_at=created_at,
        model_step=self.model_step,
        origin_refs=self.origin_refs,
    )

AgentEvidenceKind

Bases: StrEnum

Kinds of append-only evidence captured by agent execution.

AgentPricingError

Bases: AbstractSpakkyAgentError

Raised when model cost cannot be calculated from trusted inputs.

ModelCost(model_ref, amount, currency, pricing_version, input_tokens, output_tokens, cached_input_tokens=0, cache_write_input_tokens=0, cache_write_5m_input_tokens=0, cache_write_1h_input_tokens=0) dataclass

Exact cost calculated for one model step.

ModelPrice(input_per_million, output_per_million, cached_input_per_million=None, cache_write_input_per_million=None, cache_write_5m_input_per_million=None, cache_write_1h_input_per_million=None) dataclass

Per-million-token rates for one operator catalog model reference.

ModelPricingCatalog(version, prices, currency='USD', metadata=dict()) dataclass

Versioned operator pricing keyed by opaque logical model reference.

fingerprint property

Return a stable digest binding version, currency, and every rate.

calculate(model_ref, usage)

Calculate exact step cost or fail when required usage is unavailable.

Source code in core/spakky-agent/src/spakky/agent/cost.py
def calculate(self, model_ref: str, usage: ModelUsage) -> ModelCost:
    """Calculate exact step cost or fail when required usage is unavailable."""
    _require_text(model_ref)
    price = self.prices.get(model_ref)
    if price is None:
        raise AgentPricingError
    input_tokens = _usage_tokens(usage.input_tokens)
    output_tokens = _usage_tokens(usage.output_tokens)
    cached_input_tokens = _usage_tokens(usage.cached_input_tokens, default=0)
    cache_write_input_tokens = _usage_tokens(
        usage.cache_write_input_tokens,
        default=0,
    )
    cache_write_5m_input_tokens = _usage_tokens(
        usage.cache_write_5m_input_tokens,
        default=0,
    )
    cache_write_1h_input_tokens = _usage_tokens(
        usage.cache_write_1h_input_tokens,
        default=0,
    )
    categorized_cache_write = (
        usage.cache_write_5m_input_tokens is not None
        or usage.cache_write_1h_input_tokens is not None
    )
    if (
        cache_write_input_tokens > 0
        and not categorized_cache_write
        and (
            price.cache_write_5m_input_per_million is not None
            or price.cache_write_1h_input_per_million is not None
        )
    ):
        raise AgentPricingError
    if cached_input_tokens + cache_write_input_tokens > input_tokens:
        raise AgentPricingError
    if categorized_cache_write and (
        cache_write_5m_input_tokens + cache_write_1h_input_tokens
        != cache_write_input_tokens
    ):
        raise AgentPricingError
    regular_input_tokens = (
        input_tokens - cached_input_tokens - cache_write_input_tokens
    )
    cached_rate = (
        price.cached_input_per_million
        if price.cached_input_per_million is not None
        else price.input_per_million
    )
    cache_write_rate = (
        price.cache_write_input_per_million
        if price.cache_write_input_per_million is not None
        else price.input_per_million
    )
    cache_write_5m_rate = (
        price.cache_write_5m_input_per_million
        if price.cache_write_5m_input_per_million is not None
        else cache_write_rate
    )
    cache_write_1h_rate = (
        price.cache_write_1h_input_per_million
        if price.cache_write_1h_input_per_million is not None
        else cache_write_rate
    )
    cache_write_amount = (
        Decimal(cache_write_5m_input_tokens) * cache_write_5m_rate
        + Decimal(cache_write_1h_input_tokens) * cache_write_1h_rate
        if categorized_cache_write
        else Decimal(cache_write_input_tokens) * cache_write_rate
    )
    amount = (
        Decimal(regular_input_tokens) * price.input_per_million
        + Decimal(cached_input_tokens) * cached_rate
        + cache_write_amount
        + Decimal(output_tokens) * price.output_per_million
    ) / _TOKENS_PER_MILLION
    return ModelCost(
        model_ref=model_ref,
        amount=amount,
        currency=self.currency,
        pricing_version=self.version,
        input_tokens=input_tokens,
        output_tokens=output_tokens,
        cached_input_tokens=cached_input_tokens,
        cache_write_input_tokens=cache_write_input_tokens,
        cache_write_5m_input_tokens=cache_write_5m_input_tokens,
        cache_write_1h_input_tokens=cache_write_1h_input_tokens,
    )

AgentEvaluationCase(id, expected_tool_calls=(), output_type=None, expected_output=None, expected_citations=()) dataclass

One offline case containing only explicit evaluator expectations.

__post_init__()

Validate all case expectations before any sample is scored.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Validate all case expectations before any sample is scored."""
    _EvaluationValidation.text(
        self.id,
        "Agent evaluation case id must be nonblank single-line text",
    )
    object.__setattr__(
        self,
        "expected_tool_calls",
        _EvaluationValidation.tool_calls(self.expected_tool_calls),
    )
    _EvaluationValidation.references(
        self.expected_citations,
        "Agent evaluation citations must be a tuple",
    )
    if self.output_type is None:
        if self.expected_output is not None:
            raise AgentDefinitionError(
                "Expected structured output requires an output type"
            )
        return
    if not isinstance(self.output_type, type):
        raise AgentDefinitionError("Agent evaluation output type must be a class")
    contract = _structured_output_contract(self.output_type)
    if self.expected_output is not None:
        expected_output = _json_value(self.expected_output)
        contract.materialize(expected_output)
        object.__setattr__(
            self,
            "expected_output",
            _freeze_json(expected_output),
        )

AgentEvaluationDataset(id, cases) dataclass

Ordered set of unique offline evaluation cases.

__post_init__()

Reject empty, mutable-shaped, or ambiguous datasets.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject empty, mutable-shaped, or ambiguous datasets."""
    _EvaluationValidation.text(
        self.id,
        "Agent evaluation dataset id must be nonblank single-line text",
    )
    if not isinstance(self.cases, tuple) or not self.cases:
        raise AgentDefinitionError("Agent evaluation dataset cannot be empty")
    if any(not isinstance(case, AgentEvaluationCase) for case in self.cases):
        raise AgentDefinitionError(
            "Agent evaluation dataset contains an invalid case"
        )
    case_ids = tuple(case.id for case in self.cases)
    if len(set(case_ids)) != len(case_ids):
        raise AgentDefinitionError("Agent evaluation case ids must be unique")

AgentEvaluationReport(dataset_ref, results) dataclass

Deterministically ordered results for one dataset evaluation.

passed property

Return whether every metric passed.

score property

Return the unweighted mean across the explicit metric results.

__post_init__()

Reject reports without an attributable metric result.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject reports without an attributable metric result."""
    _EvaluationValidation.text(
        self.dataset_ref,
        "Agent evaluation dataset reference must be nonblank single-line text",
    )
    if not isinstance(self.results, tuple) or not self.results:
        raise AgentDefinitionError("Agent evaluation report cannot be empty")
    if any(
        not isinstance(result, AgentEvaluationResult) for result in self.results
    ):
        raise AgentDefinitionError(
            "Agent evaluation report contains an invalid result"
        )

evidence_candidates()

Return privacy-safe evidence without raw outputs, prompts, or context.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def evidence_candidates(self) -> tuple[AgentEvidenceCandidate, ...]:
    """Return privacy-safe evidence without raw outputs, prompts, or context."""
    return tuple(result.to_evidence_candidate() for result in self.results)

AgentEvaluationResult(evaluator, metric, passed, score, case_ref, sample_ref) dataclass

One bounded metric result for one explicit case/sample pair.

__post_init__()

Reject results that cannot be compared or safely evidenced.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject results that cannot be compared or safely evidenced."""
    for value, message in (
        (
            self.evaluator,
            "Agent evaluator name must be nonblank single-line text",
        ),
        (
            self.metric,
            "Agent evaluation metric must be nonblank single-line text",
        ),
        (
            self.case_ref,
            "Agent evaluation case reference must be nonblank single-line text",
        ),
        (
            self.sample_ref,
            "Agent evaluation sample reference must be nonblank single-line text",
        ),
    ):
        _EvaluationValidation.text(value, message)
    if not isinstance(self.passed, bool):
        raise AgentDefinitionError("Agent evaluation pass value must be boolean")
    _EvaluationValidation.score(self.score)

to_evidence_candidate()

Project the metric to privacy-safe append-only evaluation evidence.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def to_evidence_candidate(self) -> AgentEvidenceCandidate:
    """Project the metric to privacy-safe append-only evaluation evidence."""
    return AgentEvidenceCandidate.evaluation(
        evaluator=self.evaluator,
        metric=self.metric,
        passed=self.passed,
        score=self.score,
        case_ref=self.case_ref,
        sample_ref=self.sample_ref,
    )

AgentEvaluationSample(id, case_ref, structured_output=None, tool_calls=(), citations=(), retrieval_refs=()) dataclass

Observed output and trace for exactly one offline case.

__post_init__()

Validate sample correlations and reference-only grounding inputs.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Validate sample correlations and reference-only grounding inputs."""
    _EvaluationValidation.text(
        self.id,
        "Agent evaluation sample id must be nonblank single-line text",
    )
    _EvaluationValidation.text(
        self.case_ref,
        "Agent evaluation sample case reference must be nonblank single-line text",
    )
    object.__setattr__(
        self,
        "tool_calls",
        _EvaluationValidation.tool_calls(self.tool_calls),
    )
    object.__setattr__(
        self,
        "structured_output",
        _snapshot_json(self.structured_output),
    )
    _EvaluationValidation.references(
        self.citations,
        "Agent evaluation citations must be a tuple",
    )
    _EvaluationValidation.references(
        self.retrieval_refs,
        "Agent evaluation retrieval references must be a tuple",
    )

AgentEvaluationSuite(evaluators) dataclass

Sequentially evaluate explicit samples in dataset and evaluator order.

__post_init__()

Reject suites whose evaluator order or identity is ambiguous.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject suites whose evaluator order or identity is ambiguous."""
    if not isinstance(self.evaluators, tuple) or not self.evaluators:
        raise AgentDefinitionError("Agent evaluation suite cannot be empty")
    if any(
        not isinstance(evaluator, IAgentEvaluator) for evaluator in self.evaluators
    ):
        raise AgentDefinitionError(
            "Agent evaluation suite contains an invalid evaluator"
        )
    names = tuple(evaluator.name for evaluator in self.evaluators)
    for name in names:
        _EvaluationValidation.text(
            name,
            "Agent evaluator name must be nonblank single-line text",
        )
    if len(set(names)) != len(names):
        raise AgentDefinitionError("Agent evaluator names must be unique")

evaluate(dataset, samples) async

Pair one explicit sample per case and preserve deterministic ordering.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
async def evaluate(
    self,
    dataset: AgentEvaluationDataset,
    samples: tuple[AgentEvaluationSample, ...],
) -> AgentEvaluationReport:
    """Pair one explicit sample per case and preserve deterministic ordering."""
    if not isinstance(dataset, AgentEvaluationDataset):
        raise AgentDefinitionError("Agent evaluation dataset is invalid")
    if not isinstance(samples, tuple) or any(
        not isinstance(sample, AgentEvaluationSample) for sample in samples
    ):
        raise AgentDefinitionError("Agent evaluation samples must be a tuple")
    sample_by_case = {sample.case_ref: sample for sample in samples}
    if len(sample_by_case) != len(samples):
        raise AgentDefinitionError(
            "Agent evaluation samples must be unique per case"
        )
    case_ids = tuple(case.id for case in dataset.cases)
    if set(sample_by_case) != set(case_ids):
        raise AgentDefinitionError(
            "Agent evaluation samples must exactly cover the dataset"
        )
    results: list[AgentEvaluationResult] = []
    for case in dataset.cases:
        sample = sample_by_case[case.id]
        for evaluator in self.evaluators:
            evaluated = await evaluator.evaluate(case, sample)
            self._append_validated_results(
                results,
                evaluated,
                evaluator=evaluator,
                case=case,
                sample=sample,
            )
    return AgentEvaluationReport(dataset_ref=dataset.id, results=tuple(results))

CitationEvaluator(minimum_precision=1.0, minimum_recall=1.0) dataclass

Bases: IAgentEvaluator

Calculate exact reference precision and recall.

__post_init__()

Validate both configured metric thresholds.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Validate both configured metric thresholds."""
    _EvaluationValidation.threshold(self.minimum_precision)
    _EvaluationValidation.threshold(self.minimum_recall)

IAgentEvaluator

Bases: ABC

Replaceable offline evaluator over an explicit case/sample pair.

name abstractmethod property

Return the stable evaluator identity used in reports and evidence.

evaluate(case, sample) abstractmethod async

Evaluate exactly one already-correlated case/sample pair.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
@abstractmethod
async def evaluate(
    self,
    case: AgentEvaluationCase,
    sample: AgentEvaluationSample,
) -> Sequence[AgentEvaluationResult]:
    """Evaluate exactly one already-correlated case/sample pair."""
    ...

IModelJudge

Bases: ABC

Optional externally supplied model-judge port with no default backend.

judge(case, sample) abstractmethod async

Return a bounded score without implying a network or model fallback.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
@abstractmethod
async def judge(
    self,
    case: AgentEvaluationCase,
    sample: AgentEvaluationSample,
) -> float:
    """Return a bounded score without implying a network or model fallback."""
    ...

ModelJudgeEvaluator(judge, metric='model_judge', minimum_score=0.5, evaluator_name='model_judge') dataclass

Bases: IAgentEvaluator

Wrap one explicitly supplied model judge without a default provider.

__post_init__()

Reject an absent judge or ambiguous metric configuration.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject an absent judge or ambiguous metric configuration."""
    if not isinstance(self.judge, IModelJudge):
        raise AgentDefinitionError("Model judge evaluator requires an IModelJudge")
    _EvaluationValidation.text(
        self.metric,
        "Model judge metric must be nonblank single-line text",
    )
    _EvaluationValidation.text(
        self.evaluator_name,
        "Model judge evaluator name must be nonblank single-line text",
    )
    _EvaluationValidation.threshold(self.minimum_score)

RetrievalGroundednessEvaluator(minimum_score=1.0) dataclass

Bases: IAgentEvaluator

Score the fraction of cited references present in retrieved evidence.

__post_init__()

Validate the configured groundedness threshold.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Validate the configured groundedness threshold."""
    _EvaluationValidation.threshold(self.minimum_score)

StructuredOutputEvaluator() dataclass

Bases: IAgentEvaluator

Validate strict structured output and optional exact expected content.

ToolTraceEvaluator() dataclass

Bases: IAgentEvaluator

Score exact ordered tool names and arguments while ignoring call ids.

AgentEventAttribution(agent_id, run_id, conversation_id, parent_run_id=None) dataclass

Attribution carried by every protocol-neutral agent event.

parent_run_id is None exactly when the run is a delegation-tree root (ADR-0013 §3 "parent link" / ADR-0009 parent linkage). The remaining ids are always present so adapters never have to synthesize linkage.

__post_init__()

Reject attribution that cannot identify an agent, run, or conversation.

Source code in core/spakky-agent/src/spakky/agent/event.py
def __post_init__(self) -> None:
    """Reject attribution that cannot identify an agent, run, or conversation."""
    if not self.agent_id.strip():
        raise AgentDefinitionError("Agent event agent id cannot be blank")
    if not self.run_id.strip():
        raise AgentDefinitionError("Agent event run id cannot be blank")
    if not self.conversation_id.strip():
        raise AgentDefinitionError("Agent event conversation id cannot be blank")
    if self.parent_run_id is not None and not self.parent_run_id.strip():
        raise AgentDefinitionError("Agent event parent run id cannot be blank")

AgentEventKind

Bases: StrEnum

Protocol-neutral event kinds emitted across an agent run.

The lifecycle kinds (RUN_STARTED … ARTIFACT) generalize ADR-0009's public AgentYield vocabulary and align 1:1 with the streaming events that AG-UI and A2A adapters must reproduce (ADR-0013 §3).

ArtifactEvent(attribution, artifact_id, content, name=None, metadata=dict()) dataclass

A produced artifact surfaced by an agent run.

CustomEvent(attribution, name, value, metadata=dict()) dataclass

An application-defined named event carrying a JSON value.

The framework assigns no meaning to name or value: application code running inside a run emits them through AgentCustomEvents and each adapter relays them on its own protocol surface. Names should be namespaced by the application (for example "myapp.turn_part") so they cannot collide with names an adapter reserves for its own projections.

__post_init__()

Reject a custom event a client could not dispatch on.

Source code in core/spakky-agent/src/spakky/agent/event.py
def __post_init__(self) -> None:
    """Reject a custom event a client could not dispatch on."""
    if not self.name.strip():
        raise AgentDefinitionError("Agent custom event name cannot be blank")

MessageDeltaEvent(attribution, message_id, delta, metadata=dict()) dataclass

Incremental assistant message text produced by the model.

ReasoningDeltaEvent(attribution, reasoning_id, delta, metadata=dict()) dataclass

Incremental model reasoning (thinking) text.

RunFinishedEvent(attribution, error=None, metadata=dict()) dataclass

A run has finished executing.

error is None for a successful run and carries a terminal failure payload otherwise (A2A failed task / AG-UI RUN_ERROR).

RunPausedEvent(attribution, reason, prompt, state_id, approval_id=None, tool_call_id=None, allowed_decisions=(), metadata=dict()) dataclass

A run has paused without terminal success or failure.

The event is intentionally protocol-neutral: it carries core lifecycle reason plus the input prompt/decision envelope adapters need to project their own input-required or auth-required protocol states.

__post_init__()

Reject pause events that cannot be shown or resumed.

Source code in core/spakky-agent/src/spakky/agent/event.py
def __post_init__(self) -> None:
    """Reject pause events that cannot be shown or resumed."""
    if not self.prompt.strip():
        raise AgentDefinitionError("Agent run pause prompt cannot be blank")
    if not self.state_id.strip():
        raise AgentDefinitionError("Agent run pause state id cannot be blank")
    if self.approval_id is not None and not self.approval_id.strip():
        raise AgentDefinitionError("Agent run pause approval id cannot be blank")
    if self.tool_call_id is not None and not self.tool_call_id.strip():
        raise AgentDefinitionError("Agent run pause tool call id cannot be blank")

RunStartedEvent(attribution, metadata=dict()) dataclass

A run has started executing.

StateDeltaEvent(attribution, patch, metadata=dict()) dataclass

An incremental change to shared run state.

patch is a sequence of JSON-Patch operations (RFC 6902), the same shape AG-UI STATE_DELTA carries, so adapters relay it without re-deriving a diff.

StateSnapshotEvent(attribution, snapshot, metadata=dict()) dataclass

A full snapshot of shared run state.

StepFinishedEvent(attribution, step_name, metadata=dict()) dataclass

A named step inside a run has finished.

StepStartedEvent(attribution, step_name, metadata=dict()) dataclass

A named step inside a run has started (one model-loop iteration).

ToolCallArgsDeltaEvent(attribution, call_id, args_delta, metadata=dict()) dataclass

Incremental serialized arguments for an in-flight tool call.

ToolCallEndEvent(attribution, call_id, metadata=dict()) dataclass

A tool call has finished streaming its arguments.

ToolCallResultEvent(attribution, call_id, tool_name, message_id, result=None, metadata=dict()) dataclass

The result returned by executing a completed tool call.

message_id identifies the conversation message this tool result belongs to, so an adapter can attach the result to the right message. AG-UI requires it as messageId on TOOL_CALL_RESULT; without it the result frame cannot be reconstructed losslessly.

ToolCallStartEvent(attribution, call_id, tool_name, parent_message_id=None, metadata=dict()) dataclass

A model has begun emitting a tool call with a known name.

parent_message_id links the tool call to the assistant message that requested it (None when the model emits the call outside any message). AG-UI projects this as parentMessageId on TOOL_CALL_START.

AgentApprovalBoundaryKind

Bases: StrEnum

Action boundaries where orchestration may require human approval.

AgentApprovalDecisionOutcome(request_id, decision, status, transition, reason=None, modified_payload=dict(), comment=None) dataclass

Typed result of an approval decision signal.

AgentApprovalPlan(action, request=None, state=None, yield_item=None) dataclass

Plan for an action boundary before executing it.

requires_approval property

Return whether orchestration must wait for a HITL decision.

AgentApprovalPlanAction

Bases: StrEnum

Approval plan outcome before an action boundary is executed.

AgentApprovalRequest(id, agent_state_id, boundary, prompt, risk, action_ref, allowed_decisions=DEFAULT_APPROVAL_DECISIONS, metadata=dict()) dataclass

Approval request materialized at a risky action boundary.

__post_init__()

Reject approval requests that cannot be matched by a signal.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def __post_init__(self) -> None:
    """Reject approval requests that cannot be matched by a signal."""
    _require_non_blank(self.id, "Agent approval id")
    _require_non_blank(self.agent_state_id, "Agent approval state id")
    _require_non_blank(self.prompt, "Agent approval prompt")
    _require_non_blank(self.action_ref, "Agent approval action ref")
    if len(self.allowed_decisions) == 0:
        raise AgentDefinitionError("Agent approval decisions cannot be empty")

from_tool_descriptor(*, approval_id, agent_state_id, descriptor, prompt=None, action_ref=None, call_id=None, metadata=None) classmethod

Build an approval request from a risky tool descriptor.

Source code in core/spakky-agent/src/spakky/agent/approval.py
@classmethod
def from_tool_descriptor(
    cls,
    *,
    approval_id: str,
    agent_state_id: str,
    descriptor: AgentToolDescriptor,
    prompt: str | None = None,
    action_ref: str | None = None,
    call_id: str | None = None,
    metadata: JsonObject | None = None,
) -> "AgentApprovalRequest":
    """Build an approval request from a risky tool descriptor."""
    request_metadata = _tool_approval_metadata(descriptor, call_id, metadata or {})
    return cls(
        id=approval_id,
        agent_state_id=agent_state_id,
        boundary=AgentApprovalBoundaryKind.TOOL_INVOCATION,
        prompt=prompt or f"Approve tool invocation: {descriptor.name}",
        risk=descriptor.metadata.risk,
        action_ref=action_ref or descriptor.identity.key,
        metadata=request_metadata,
    )

to_state(*, agent_type)

Materialize the approval wait as interrupted lifecycle state.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def to_state(self, *, agent_type: str) -> AgentState:
    """Materialize the approval wait as interrupted lifecycle state."""
    _require_non_blank(agent_type, "Agent approval agent type")
    return AgentState(
        id=self.agent_state_id,
        agent_type=agent_type,
        status=AgentStatus.INTERRUPTED,
        transition=AgentStateTransition.WAITING_APPROVAL,
        reason=AgentStateReason.APPROVAL_REQUIRED,
        current_activity=self.prompt,
        metadata={"approval": self.to_metadata()},
    )

to_yield()

Expose this approval request to an inbound adapter stream.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def to_yield(self) -> AgentYield[Approval]:
    """Expose this approval request to an inbound adapter stream."""
    return AgentYield(
        kind=AgentYieldKind.APPROVAL,
        payload=Approval(
            id=self.id,
            prompt=self.prompt,
            allowed_decisions=self.allowed_decisions,
            metadata=self.to_metadata(),
        ),
    )

to_metadata()

Return JSON-compatible metadata for state, yield, and evidence.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def to_metadata(self) -> JsonObject:
    """Return JSON-compatible metadata for state, yield, and evidence."""
    return {
        "id": self.id,
        "agent_state_id": self.agent_state_id,
        "boundary": self.boundary.value,
        "action_ref": self.action_ref,
        "risk_axes": [axis.value for axis in self.risk.axes],
        "allowed_decisions": [
            decision.value for decision in self.allowed_decisions
        ],
        "metadata": self.metadata,
    }

AgentActionBoundaryCheckpoint(action_id, action_kind, stage, idempotency=Idempotency.UNKNOWN, metadata=dict()) dataclass

Serializable checkpoint recorded before or after one external action.

__post_init__()

Reject checkpoints that cannot be correlated after restart.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
def __post_init__(self) -> None:
    """Reject checkpoints that cannot be correlated after restart."""
    if not self.action_id.strip():
        raise AgentDefinitionError("Agent action boundary id cannot be blank")

before_model_call(action_id, *, idempotency=Idempotency.UNKNOWN, metadata=None) classmethod

Create the checkpoint recorded before a model call is attempted.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def before_model_call(
    cls,
    action_id: str,
    *,
    idempotency: Idempotency = Idempotency.UNKNOWN,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded before a model call is attempted."""
    return cls._for_action(
        action_id,
        AgentActionKind.MODEL_CALL,
        AgentActionBoundaryStage.BEFORE,
        idempotency=idempotency,
        metadata=metadata,
    )

after_model_call(action_id, *, idempotency=Idempotency.UNKNOWN, metadata=None) classmethod

Create the checkpoint recorded after a model call completes.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def after_model_call(
    cls,
    action_id: str,
    *,
    idempotency: Idempotency = Idempotency.UNKNOWN,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded after a model call completes."""
    return cls._for_action(
        action_id,
        AgentActionKind.MODEL_CALL,
        AgentActionBoundaryStage.AFTER,
        idempotency=idempotency,
        metadata=metadata,
    )

before_tool_call(action_id, *, idempotency, metadata=None) classmethod

Create the checkpoint recorded before a tool call is attempted.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def before_tool_call(
    cls,
    action_id: str,
    *,
    idempotency: Idempotency,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded before a tool call is attempted."""
    return cls._for_action(
        action_id,
        AgentActionKind.TOOL_CALL,
        AgentActionBoundaryStage.BEFORE,
        idempotency=idempotency,
        metadata=metadata,
    )

after_tool_call(action_id, *, idempotency, metadata=None) classmethod

Create the checkpoint recorded after a tool call completes.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def after_tool_call(
    cls,
    action_id: str,
    *,
    idempotency: Idempotency,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded after a tool call completes."""
    return cls._for_action(
        action_id,
        AgentActionKind.TOOL_CALL,
        AgentActionBoundaryStage.AFTER,
        idempotency=idempotency,
        metadata=metadata,
    )

before_approval_wait(action_id, *, metadata=None) classmethod

Create the checkpoint recorded before waiting for approval.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def before_approval_wait(
    cls,
    action_id: str,
    *,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded before waiting for approval."""
    return cls._for_action(
        action_id,
        AgentActionKind.APPROVAL_WAIT,
        AgentActionBoundaryStage.BEFORE,
        idempotency=Idempotency.NON_IDEMPOTENT,
        metadata=metadata,
    )

after_approval_wait(action_id, *, metadata=None) classmethod

Create the checkpoint recorded after an approval wait resolves.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def after_approval_wait(
    cls,
    action_id: str,
    *,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded after an approval wait resolves."""
    return cls._for_action(
        action_id,
        AgentActionKind.APPROVAL_WAIT,
        AgentActionBoundaryStage.AFTER,
        idempotency=Idempotency.NON_IDEMPOTENT,
        metadata=metadata,
    )

to_evidence_candidate(*, summary=None)

Represent this checkpoint as append-only evidence.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
def to_evidence_candidate(
    self,
    *,
    summary: str | None = None,
) -> AgentEvidenceCandidate:
    """Represent this checkpoint as append-only evidence."""
    return AgentEvidenceCandidate(
        kind=AgentEvidenceKind.ACTION_BOUNDARY,
        payload={
            "action_id": self.action_id,
            "action_kind": self.action_kind.value,
            "stage": self.stage.value,
            "idempotency": self.idempotency.value,
            "metadata": self.metadata,
        },
        summary=summary,
    )

AgentActionBoundaryStage

Bases: StrEnum

Checkpoint side recorded around an action boundary.

AgentActionKind

Bases: StrEnum

Recoverable external action classes in an agent execution.

AgentResumeAction

Bases: StrEnum

Orchestration action selected from persisted checkpoint evidence.

AgentResumeBoundary(action_id, action_kind, stage, idempotency, evidence_id) dataclass

Last action boundary reconstructed from append-only evidence.

AgentResumePlan(state, action, boundary=None, signals=()) dataclass

Resume decision derived from persisted state and checkpoint evidence.

requires_human_input property

Return whether automatic replay must stop at HITL recovery.

can_resume_automatically property

Return whether orchestration may continue without approval.

IRetriever

Bases: ABC

Async retrieval port shared by context and tool adapters.

retrieve(query, *, limit, tenant_id, namespace, filters) abstractmethod async

Return ordered retrieval hits for one scoped query.

Source code in core/spakky-agent/src/spakky/agent/retrieval.py
@abstractmethod
async def retrieve(
    self,
    query: str,
    *,
    limit: int,
    tenant_id: str | None,
    namespace: str | None,
    filters: JsonObject,
) -> Sequence[RetrievalHit]:
    """Return ordered retrieval hits for one scoped query."""
    ...

RetrievalContext(retriever, limit=5, max_context_tokens=2048, allow_empty=False, tenant_id=None, namespace=None, filters=dict()) dataclass

Bases: IAgentContextProvider

Classic RAG adapter exposing retrieval as typed model context.

RetrievalHit(id, content, source, score=None, rerank_score=None, content_digest=None, revision=None, tenant_id=None, namespace=None, start_offset=None, end_offset=None, metadata=dict()) dataclass

One retrieved model-facing text result with typed provenance.

RetrievalTool(retriever, *, name='search', limit=5, tenant_id=None, namespace=None, filters=None)

Bases: IAgentToolProvider

Agentic RAG component contributing one retrieval tool.

Source code in core/spakky-agent/src/spakky/agent/retrieval.py
def __init__(
    self,
    retriever: IRetriever,
    *,
    name: str = "search",
    limit: int = 5,
    tenant_id: str | None = None,
    namespace: str | None = None,
    filters: JsonObject | None = None,
) -> None:
    _require_framing_text(name, "Retrieval tool name")
    limit = _positive_limit(limit, "Retrieval tool limit")
    _validate_scope(tenant_id, namespace)
    self._retriever = retriever
    self._name = name
    self._limit = limit
    self._tenant_id = tenant_id
    self._namespace = namespace
    self._filters = _snapshot_filters({} if filters is None else filters)

    async def invoke(query: str) -> list[_RetrievalToolHit]:
        return await self._invoke(query)

    definition = AgentToolDefinition(
        name=name,
        schema_name=name,
        description="Search scoped retrieval context.",
        metadata=AgentToolMetadata(
            effects=ToolEffects.read_only(),
            idempotency=Idempotency.IDEMPOTENT,
            evidence=EvidenceCapture.STRUCTURED,
            approval=ToolApprovalRequirement.NOT_REQUIRED,
        ),
    )
    self._tool_catalog = AgentToolCatalog(
        descriptors=(_build_descriptor(type(self), invoke, definition),)
    )

IMemoryStore

Bases: ABC

Backend-replaceable long-term memory persistence port.

Implementations must omit explicitly deleted entries from search. MemoryRetriever additionally removes expired and superseded revisions.

save(entry) abstractmethod async

Persist one immutable revision, including correction linkage.

Source code in core/spakky-agent/src/spakky/agent/memory.py
@abstractmethod
async def save(self, entry: MemoryEntry) -> None:
    """Persist one immutable revision, including correction linkage."""
    ...

search(query, *, limit, tenant_id, user_id, namespace, kinds, filters) abstractmethod async

Return ordered, undeleted candidates for one exact scope.

Source code in core/spakky-agent/src/spakky/agent/memory.py
@abstractmethod
async def search(
    self,
    query: str,
    *,
    limit: int,
    tenant_id: str,
    user_id: str,
    namespace: str,
    kinds: tuple[MemoryKind, ...],
    filters: JsonObject,
) -> Sequence[MemoryEntry]:
    """Return ordered, undeleted candidates for one exact scope."""
    ...

delete(entry_id, *, tenant_id, user_id, namespace) abstractmethod async

Explicitly delete one memory entry inside its exact scope.

Source code in core/spakky-agent/src/spakky/agent/memory.py
@abstractmethod
async def delete(
    self,
    entry_id: str,
    *,
    tenant_id: str,
    user_id: str,
    namespace: str,
) -> None:
    """Explicitly delete one memory entry inside its exact scope."""
    ...

MemoryEntry(id, kind, content, source, revision, content_digest, tenant_id, user_id, namespace, created_at, expires_at=None, supersedes=None) dataclass

One immutable, provenance-bound long-term memory revision.

ttl property

Return the declared lifetime, or None for non-expiring memory.

__post_init__()

Reject entries that cannot be safely scoped or versioned.

Source code in core/spakky-agent/src/spakky/agent/memory.py
def __post_init__(self) -> None:
    """Reject entries that cannot be safely scoped or versioned."""
    for value, label in (
        (self.id, "Memory entry id must be nonblank single-line text"),
        (self.source, "Memory source must be nonblank single-line text"),
        (self.revision, "Memory revision must be nonblank single-line text"),
        (
            self.content_digest,
            "Memory content digest must be nonblank single-line text",
        ),
        (self.tenant_id, "Memory tenant id must be nonblank single-line text"),
        (self.user_id, "Memory user id must be nonblank single-line text"),
        (self.namespace, "Memory namespace must be nonblank single-line text"),
    ):
        _MemoryValidation.definition_text(value, label)
    if not isinstance(self.kind, MemoryKind):
        raise AgentDefinitionError("Memory kind is invalid")
    if not isinstance(self.content, str) or not self.content.strip():
        raise AgentDefinitionError("Memory content cannot be blank")
    _MemoryValidation.definition_timestamp(
        self.created_at,
        "Memory created time must be timezone-aware",
    )
    if self.expires_at is not None:
        _MemoryValidation.definition_timestamp(
            self.expires_at,
            "Memory expiry time must be timezone-aware",
        )
        if self.expires_at <= self.created_at:
            raise AgentDefinitionError(
                "Memory expiry time must be after its created time"
            )
    if self.supersedes is not None:
        _MemoryValidation.definition_text(
            self.supersedes,
            "Superseded memory id must be nonblank single-line text",
        )
        if self.supersedes == self.id:
            raise AgentDefinitionError("Memory cannot supersede itself")

is_expired(at=None)

Check expiry at a deterministic point, defaulting to current UTC time.

Source code in core/spakky-agent/src/spakky/agent/memory.py
def is_expired(self, at: datetime | None = None) -> bool:
    """Check expiry at a deterministic point, defaulting to current UTC time."""
    point = datetime.now(UTC) if at is None else at
    _MemoryValidation.runtime_timestamp(
        point,
        "Memory expiry check time must be timezone-aware",
    )
    return self.expires_at is not None and self.expires_at <= point

MemoryKind

Bases: StrEnum

Long-term memory meanings exposed independently from storage backends.

MemoryRetriever(store, *, tenant_id, user_id, namespace, kinds=tuple(MemoryKind))

Bases: IRetriever

Bind the missing user dimension before exposing memory as retrieval.

Source code in core/spakky-agent/src/spakky/agent/memory.py
def __init__(
    self,
    store: IMemoryStore,
    *,
    tenant_id: str,
    user_id: str,
    namespace: str,
    kinds: tuple[MemoryKind, ...] = tuple(MemoryKind),
) -> None:
    if not isinstance(store, IMemoryStore):
        raise AgentDefinitionError("Memory retriever requires an IMemoryStore")
    for value, label in (
        (tenant_id, "Memory tenant id must be nonblank single-line text"),
        (user_id, "Memory user id must be nonblank single-line text"),
        (namespace, "Memory namespace must be nonblank single-line text"),
    ):
        _MemoryValidation.definition_text(value, label)
    if not isinstance(kinds, tuple) or not kinds:
        raise AgentDefinitionError("Memory retriever kinds cannot be empty")
    if any(not isinstance(kind, MemoryKind) for kind in kinds):
        raise AgentDefinitionError("Memory retriever kind is invalid")
    if len(set(kinds)) != len(kinds):
        raise AgentDefinitionError("Memory retriever kinds must be unique")
    self._store = store
    self._tenant_id = tenant_id
    self._user_id = user_id
    self._namespace = namespace
    self._kinds = kinds

retrieve(query, *, limit, tenant_id, namespace, filters) async

Retrieve active memory without weakening its bound user scope.

Source code in core/spakky-agent/src/spakky/agent/memory.py
@override
async def retrieve(
    self,
    query: str,
    *,
    limit: int,
    tenant_id: str | None,
    namespace: str | None,
    filters: JsonObject,
) -> Sequence[RetrievalHit]:
    """Retrieve active memory without weakening its bound user scope."""
    if not isinstance(query, str) or not query.strip():
        raise AgentMemoryError("Memory retrieval query must be nonblank text")
    if isinstance(limit, bool) or not isinstance(limit, int) or limit <= 0:
        raise AgentMemoryError("Memory retrieval limit must be positive")
    if tenant_id != self._tenant_id or namespace != self._namespace:
        raise AgentMemoryError("Memory retrieval scope does not match its binding")
    copied_filters = _MemoryValidation.json_object(filters)
    entries = await self._store.search(
        query,
        limit=limit,
        tenant_id=self._tenant_id,
        user_id=self._user_id,
        namespace=self._namespace,
        kinds=self._kinds,
        filters=copied_filters,
    )
    return self._active_hits(entries, limit=limit, at=datetime.now(UTC))

AgentDelegateTarget(agent_type, agent_name=None, metadata=dict()) dataclass

First-class delegate target represented by another @Agent component.

__post_init__()

Reject delegate targets that cannot identify an agent component.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegate targets that cannot identify an agent component."""
    if not self.agent_type.strip():
        raise AgentDefinitionError("Delegate target agent type cannot be blank")
    if self.agent_name is not None and not self.agent_name.strip():
        raise AgentDefinitionError("Delegate target agent name cannot be blank")

DelegationToolResult(summary, output=None, events=(), metadata=dict()) dataclass

Model-facing result plus child neutral events from a teammate call.

__post_init__()

Reject delegated tool results without a model-facing summary.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegated tool results without a model-facing summary."""
    if not self.summary.strip():
        raise AgentDefinitionError("Delegation tool result summary cannot be blank")

from_result(result, *, events=()) classmethod

Build a model-facing tool result from a delegation result object.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
@classmethod
def from_result(
    cls,
    result: DelegationResult,
    *,
    events: tuple[AgentEvent, ...] = (),
) -> "DelegationToolResult":
    """Build a model-facing tool result from a delegation result object."""
    return cls(
        summary=result.summary,
        output=result.output,
        events=events,
        metadata={
            "delegation_id": result.id,
            "packet_id": result.packet_id,
            "target_agent_type": result.target.agent_type,
            **result.metadata,
        },
    )

DelegationBudget(max_steps=None, max_tokens=None, timeout_seconds=None, deadline_at=None, metadata=dict()) dataclass

Budget metadata attached to a delegation packet.

__post_init__()

Reject delegation budgets that cannot be enforced consistently.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegation budgets that cannot be enforced consistently."""
    if self.max_steps is not None and self.max_steps <= 0:
        raise AgentDefinitionError("Delegation max steps must be positive")
    if self.max_tokens is not None and self.max_tokens <= 0:
        raise AgentDefinitionError("Delegation max tokens must be positive")
    if self.timeout_seconds is not None and self.timeout_seconds <= 0:
        raise AgentDefinitionError("Delegation timeout must be positive")

DelegationContextSlice(summary=None, evidence_refs=(), manifest_ref=None, metadata=dict()) dataclass

Minimal parent context projected for a child agent.

DelegationExpectedOutput(description=None, schema=dict(), metadata=dict()) dataclass

Expected child output description and optional JSON schema.

DelegationPacket(id, parent_agent_state_id, target, task, context=DelegationContextSlice(), constraints=(), expected_output=DelegationExpectedOutput(), budget=DelegationBudget(), allowed_capabilities=(), return_policy=DelegationReturnPolicy.SUMMARY_AND_EVIDENCE, metadata=dict()) dataclass

Task packet passed from a parent agent to a delegate agent.

__post_init__()

Reject delegation packets without parent linkage or task identity.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegation packets without parent linkage or task identity."""
    if not self.id.strip():
        raise AgentDefinitionError("Delegation id cannot be blank")
    if not self.parent_agent_state_id.strip():
        raise AgentDefinitionError("Delegation parent state id cannot be blank")

DelegationResult(id, packet_id, target, summary, output=None, evidence_refs=(), metadata=dict(), created_at=None) dataclass

Child agent result projected back to the parent execution.

__post_init__()

Reject delegated results that cannot be linked to a packet.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegated results that cannot be linked to a packet."""
    if not self.id.strip():
        raise AgentDefinitionError("Delegation result id cannot be blank")
    if not self.packet_id.strip():
        raise AgentDefinitionError("Delegation result packet id cannot be blank")
    if not self.summary.strip():
        raise AgentDefinitionError("Delegation result summary cannot be blank")

to_parent_evidence(*, evidence_id, parent_agent_state_id)

Represent a delegated result as append-only parent evidence.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def to_parent_evidence(
    self,
    *,
    evidence_id: str,
    parent_agent_state_id: str,
) -> AgentEvidence:
    """Represent a delegated result as append-only parent evidence."""
    payload: dict[str, JsonValue] = {
        "delegation_id": self.id,
        "packet_id": self.packet_id,
        "target_agent_type": self.target.agent_type,
        "evidence_refs": self.evidence_refs,
        "metadata": self.metadata,
    }
    if self.target.agent_name is not None:
        payload["target_agent_name"] = self.target.agent_name
    if self.output is not None:
        payload["output"] = self.output
    return AgentEvidence(
        id=evidence_id,
        agent_state_id=parent_agent_state_id,
        kind=AgentEvidenceKind.DELEGATION,
        payload=payload,
        summary=self.summary,
        created_at=self.created_at,
    )

to_parent_yield(*, evidence_id, parent_agent_state_id)

Expose the delegated result on the parent's AgentYield stream.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def to_parent_yield(
    self,
    *,
    evidence_id: str,
    parent_agent_state_id: str,
) -> AgentYield[Evidence]:
    """Expose the delegated result on the parent's AgentYield stream."""
    evidence = self.to_parent_evidence(
        evidence_id=evidence_id,
        parent_agent_state_id=parent_agent_state_id,
    )
    return AgentYield(
        kind=AgentYieldKind.EVIDENCE,
        payload=Evidence(
            evidence=evidence,
            metadata={"delegation_id": self.id, "packet_id": self.packet_id},
        ),
    )

DelegationReturnPolicy

Bases: StrEnum

How a child agent result should be projected back to the parent.

IAgentDelegate

Bases: ABC

Execution hook that runs a delegation packet against a delegate target.

delegate(packet) abstractmethod

Execute delegation without prescribing spawn topology or transport.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
@abstractmethod
def delegate(
    self,
    packet: DelegationPacket,
) -> AsyncGenerator[AgentYield[DelegationResult], None]:
    """Execute delegation without prescribing spawn topology or transport."""

delegate_tool_result(packet) async

Execute delegation and collect the terminal result for a tool call.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
async def delegate_tool_result(
    self,
    packet: DelegationPacket,
) -> DelegationToolResult:
    """Execute delegation and collect the terminal result for a tool call."""
    terminal: DelegationResult | None = None
    async for item in self.delegate(packet):
        if isinstance(item.payload, DelegationResult):
            terminal = item.payload
    if terminal is None:
        raise AgentToolDispatchError("Agent delegate produced no delegation result")
    return DelegationToolResult.from_result(terminal)

ICompactionStrategy

Bases: ABC

Provider-neutral context-compaction transform applied before a request.

A strategy maps a resolved history to a shorter one, reading the running ModelUsage and backend ModelCapability so it can scale its effect to how close the run is to the context limit. Implementations are pure transforms — they never mutate the input — so the runner can apply a declared chain by threading each strategy's output into the next.

compact(history, usage, capability) abstractmethod async

Return a compacted view of history for the next model request.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
@abstractmethod
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Return a compacted view of ``history`` for the next model request."""
    ...

KeepRecentMessagesCompactionStrategy(max_messages) dataclass

Bases: ICompactionStrategy

Sliding-window strategy that keeps only the most recent messages.

The cheapest compaction: drop the oldest messages and keep the last max_messages. It carries no model dependency, so it is the safe default tail of a chain that bounds history length regardless of content.

__post_init__()

Reject a window that would keep no messages.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
def __post_init__(self) -> None:
    """Reject a window that would keep no messages."""
    if self.max_messages <= 0:
        raise AgentDefinitionError(
            "Keep-recent compaction window must keep at least one message"
        )

compact(history, usage, capability) async

Keep the recent window without splitting a tool invocation group.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Keep the recent window without splitting a tool invocation group."""
    start = _recent_group_start(history, self.max_messages)
    return history[start:]

ProviderManagedCompactionStrategy() dataclass

Bases: ICompactionStrategy

No-op strategy for backends that manage their own context window.

Some providers compact server-side, so the framework must not also trim the transcript. Declaring this strategy makes that hand-off explicit in the spec rather than leaving compaction silently absent.

compact(history, usage, capability) async

Return the history unchanged — the provider owns compaction.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Return the history unchanged — the provider owns compaction."""
    return history

SummarizeOldTurnsCompactionStrategy(model, keep_recent, summary_instruction=DEFAULT_SUMMARY_INSTRUCTION) dataclass

Bases: ICompactionStrategy

Replace older turns with a model-generated summary, keeping recent ones.

The richest compaction: a secondary model call condenses the turns older than keep_recent into one EVIDENCE summary message that precedes the kept tail. This preserves earlier context as a briefing instead of dropping it, at the cost of one extra model round-trip. When the history is already within keep_recent there is nothing older to summarize, so the call is skipped.

__post_init__()

Reject a window that would leave no recent turns to anchor the summary.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
def __post_init__(self) -> None:
    """Reject a window that would leave no recent turns to anchor the summary."""
    if self.keep_recent <= 0:
        raise AgentDefinitionError(
            "Summarize compaction must keep at least one recent message"
        )
    if not self.summary_instruction.strip():
        raise AgentDefinitionError(
            "Summarize compaction instruction cannot be blank"
        )

compact(history, usage, capability) async

Summarize turns older than keep_recent ahead of the recent tail.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Summarize turns older than ``keep_recent`` ahead of the recent tail."""
    start = _recent_group_start(history, self.keep_recent)
    if start == 0:
        return history
    older = history[:start]
    recent = history[start:]
    summary = await self.model.complete(self._summary_request(older))
    return (self._summary_message(summary.content), *recent)

TrimToolResultsCompactionStrategy(max_characters) dataclass

Bases: ICompactionStrategy

Truncate verbose tool-result messages while preserving the dialogue.

Tool results (search dumps, file contents) dominate token cost yet rarely need to be replayed verbatim. This strategy truncates only TOOL role message content past max_characters and leaves the user/assistant turns untouched, so the model still sees that a tool ran and a clipped head of its output.

__post_init__()

Reject a non-positive truncation budget.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
def __post_init__(self) -> None:
    """Reject a non-positive truncation budget."""
    if self.max_characters <= 0:
        raise AgentDefinitionError(
            "Tool-result trim budget must be a positive character count"
        )

compact(history, usage, capability) async

Truncate over-budget tool-result content, leaving other roles intact.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Truncate over-budget tool-result content, leaving other roles intact."""
    return tuple(self._trim(message) for message in history)

Agent(spec=AgentExecutionSpec(), *, name='', scope=Scope.SINGLETON) dataclass

Bases: Pod

UseCase-equivalent Pod stereotype for agentic workflow components.

validate_bootstrap()

Re-run definition validation during application bootstrap.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def validate_bootstrap(self) -> None:
    """Re-run definition validation during application bootstrap."""
    self._validate_execute_contract(self._ensure_agent_class(self.target))

required_persistence_repository_types()

Return repository ports required by this Agent's durable path.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def required_persistence_repository_types(self) -> tuple[type[object], ...]:
    """Return repository ports required by this Agent's durable path."""
    from spakky.agent.interfaces.repository import (
        IAgentEvidenceRepository,
        IAgentSignalRepository,
        IAgentStateRepository,
    )

    if (
        self.spec.recovery is RecoveryStrategy.ACTION_BOUNDARY
        or len(self.spec.accepted_signals) > 0
    ):
        return (
            IAgentStateRepository,
            IAgentSignalRepository,
            IAgentEvidenceRepository,
        )
    return ()

AgentCompactionPolicy(strategies, trigger_token_threshold) dataclass

Declared compaction chain plus the token threshold that triggers it.

The strategies form an ordered chain of pluggable ICompactionStrategy ports applied in sequence once the running token estimate crosses trigger_token_threshold. The runner threads each strategy's output into the next, so chain order is the compaction order (ADR-0013 §7).

__post_init__()

Reject compaction policies that cannot be enforced consistently.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def __post_init__(self) -> None:
    """Reject compaction policies that cannot be enforced consistently."""
    if not self.strategies:
        raise AgentDefinitionError(
            "Agent compaction policy requires at least one strategy"
        )
    if self.trigger_token_threshold <= 0:
        raise AgentDefinitionError(
            "Agent compaction trigger token threshold must be positive"
        )

AgentExecutionLimits(max_steps=None, max_tool_calls=None, max_tokens=None, max_cost=None, timeout_seconds=None) dataclass

Optional execution limits; None leaves the corresponding budget unset.

__post_init__()

Reject limits that would fail later at bootstrap.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def __post_init__(self) -> None:
    """Reject limits that would fail later at bootstrap."""
    if self.max_steps is not None and self.max_steps <= 0:
        raise AgentDefinitionError("Agent model-step limit must be positive")
    if self.max_tool_calls is not None and self.max_tool_calls <= 0:
        raise AgentDefinitionError("Agent tool-call limit must be positive")
    if self.max_tokens is not None and self.max_tokens <= 0:
        raise AgentDefinitionError("Agent token limit must be positive")
    if self.max_cost is not None and (
        not isinstance(self.max_cost, Decimal)
        or not self.max_cost.is_finite()
        or self.max_cost <= 0
    ):
        raise AgentDefinitionError("Agent cost limit must be a positive Decimal")
    if self.timeout_seconds is not None and self.timeout_seconds <= 0:
        raise AgentDefinitionError("Agent timeout limit must be positive")

AgentExecutionSpec(name=None, objective=None, instructions=None, output_type=None, accepted_signals=(), recovery=RecoveryStrategy.NONE, streaming_exposure_mode=StreamingExposureMode.BALANCED, limits=AgentExecutionLimits(), teammates=(), compaction=None, refresh_context_each_step=False, delegation_allowed=False, metadata=dict(), sampling=(lambda: SamplingOptions(temperature=0.0))()) dataclass

Declarative execution semantics that cannot be inferred from DI alone.

__post_init__()

Reject execution specs that would fail later at bootstrap.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def __post_init__(self) -> None:
    """Reject execution specs that would fail later at bootstrap."""
    if self.name is not None and not self.name.strip():
        raise AgentDefinitionError("Agent name cannot be blank")
    if self.objective is not None and not self.objective.strip():
        raise AgentDefinitionError("Agent objective cannot be blank")
    if self.instructions is not None and not self.instructions.strip():
        raise AgentDefinitionError("Agent instructions cannot be blank")
    if self.output_type is not None and not isclass(self.output_type):
        raise AgentDefinitionError("Agent output type must be a class")
    if self.output_type is not None:
        _structured_output_contract(self.output_type)
    teammate_names = [teammate.name for teammate in self.teammates]
    if len(set(teammate_names)) != len(teammate_names):
        raise AgentDefinitionError("Agent teammate names must be unique")

AgentTeammate(name, pod=None, card_url=None) dataclass

Declared collaborator an agent may delegate to during execution.

A teammate is resolved either in-process by a local @Agent Pod type or remotely by an AgentCard endpoint URL. Exactly one binding is declared; the runtime exposes it as a synthetic teammate delegation tool and dispatches it through the local runner or an injected IAgentDelegate port.

__post_init__()

Reject teammates that cannot resolve to a single delegate target.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def __post_init__(self) -> None:
    """Reject teammates that cannot resolve to a single delegate target."""
    if not self.name.strip():
        raise AgentDefinitionError("Agent teammate name cannot be blank")
    if (self.pod is None) == (self.card_url is None):
        raise AgentDefinitionError(
            "Agent teammate must declare exactly one of a local pod "
            "or a remote AgentCard url"
        )
    if self.pod is not None and not isclass(self.pod):
        raise AgentDefinitionError("Agent teammate pod must be a class")
    if self.card_url is not None:
        parts = urlsplit(self.card_url)
        if parts.scheme not in REMOTE_AGENT_CARD_SCHEMES or not parts.netloc:
            raise AgentDefinitionError(
                "Agent teammate AgentCard url must be an http(s) endpoint"
            )

RecoveryStrategy

Bases: StrEnum

Recovery strategy requested by an agent execution contract.

StreamingExposureMode

Bases: StrEnum

Streaming output guard profile exposed by agent execution.

AgentSignalHookCatalog(descriptors=()) dataclass

Deterministic catalog of signal hooks discovered from an Agent class.

__post_init__()

Reject duplicate hook identities so dispatch order stays stable.

Source code in core/spakky-agent/src/spakky/agent/hooks.py
def __post_init__(self) -> None:
    """Reject duplicate hook identities so dispatch order stays stable."""
    identity_keys: set[str] = set()
    for descriptor in self.descriptors:
        if descriptor.identity.key in identity_keys:
            raise AgentDefinitionError("Agent signal hook identity must be unique")
        identity_keys.add(descriptor.identity.key)

hooks_for(kind)

Return every hook that handles the requested signal kind, in order.

Source code in core/spakky-agent/src/spakky/agent/hooks.py
def hooks_for(
    self,
    kind: AgentSignalKind,
) -> tuple[AgentSignalHookDescriptor, ...]:
    """Return every hook that handles the requested signal kind, in order."""
    return tuple(
        descriptor for descriptor in self.descriptors if descriptor.kind is kind
    )

AgentSignalHookDescriptor(identity, owner, callable, kind) dataclass

Discovered signal hook bound to an owner class and callable.

AgentSignalHookIdentity(owner_module, owner_qualname, member_name) dataclass

Hook identity independent from the developer-chosen method name.

key property

Return a stable key for deterministic ordering and logs.

RunAgentInput(state_id, instruction, conversation_id=None, parent_run_id=None, resume=False, message_history=(), model_selection=None, context=AgentContext(), metadata=dict(), attachments=(), steering_input_required=False, extensions=()) dataclass

Inbound contract for one framework-owned agent run.

extensions = () class-attribute instance-attribute

Typed application values copied into every model request of this run.

effective_conversation_id property

Return the multi-turn thread id, defaulting to the run id.

ADR-0013 §3 attribution requires a conversation id on every event. A single-turn caller may omit it, in which case the run id identifies the (degenerate) one-turn conversation.

__post_init__()

Reject inbound input that cannot correlate a run or seed a request.

Source code in core/spakky-agent/src/spakky/agent/inbound.py
def __post_init__(self) -> None:
    """Reject inbound input that cannot correlate a run or seed a request."""
    if not self.state_id.strip():
        raise AgentDefinitionError("Run agent input state id cannot be blank")
    if not self.instruction.strip():
        raise AgentDefinitionError("Run agent input instruction cannot be blank")
    if self.conversation_id is not None and not self.conversation_id.strip():
        raise AgentDefinitionError(
            "Run agent input conversation id cannot be blank"
        )
    if self.parent_run_id is not None and not self.parent_run_id.strip():
        raise AgentDefinitionError("Run agent input parent run id cannot be blank")
    if not isinstance(self.attachments, tuple) or any(
        not isinstance(
            attachment,
            ImagePart | AudioPart | VideoPart | DocumentPart,
        )
        for attachment in self.attachments
    ):
        raise AgentDefinitionError(
            "Run agent input attachments must be an immutable media tuple"
        )
    model_content_parts((TextPart(self.instruction), *self.attachments))
    object.__setattr__(self, "extensions", validated_extensions(self.extensions))

user_message()

Build the canonical user message, preserving the text-only shortcut.

Source code in core/spakky-agent/src/spakky/agent/inbound.py
def user_message(self) -> ModelMessage:
    """Build the canonical user message, preserving the text-only shortcut."""
    if not self.attachments:
        return ModelMessage.user(self.instruction)
    return ModelMessage.user((TextPart(self.instruction), *self.attachments))

IAgentModelResolver

Bases: ABC

Resolve the model adapter used for one Agent run.

resolve_model(agent_instance, run_input=None) abstractmethod

Return a run-specific model, or None to use injected fallback.

Source code in core/spakky-agent/src/spakky/agent/model_resolver.py
@abstractmethod
def resolve_model(
    self,
    agent_instance: object,
    run_input: RunAgentInput | None = None,
) -> IAgentModel | None:
    """Return a run-specific model, or ``None`` to use injected fallback."""
    ...

AgentRunner(agent, target, model, states=None, signals=None, evidence=None, task_store=None, context_provider=None, pricing=None, telemetry=None, signal_mailbox=None) dataclass

Framework-owned standard agent loop bound to one agent instance.

Durable repositories are None for a stateless agent (one that declares no accepted_signals and no action-boundary recovery). In that mode the runner skips state/evidence/signal handling and runs model -> tool -> final.

for_agent_instance(instance) classmethod

Resolve runner ports from an agent instance's injected attributes.

ADR-0009 stores constructor-injected ports as instance attributes, so the runner reads vars(instance) (the typed instance __dict__, not the banned getattr) and resolves each port by runtime type. Attribute names are developer-chosen, so resolution is type-driven, not name-driven.

Source code in core/spakky-agent/src/spakky/agent/runner.py
@classmethod
def for_agent_instance(cls, instance: object) -> "AgentRunner":
    """Resolve runner ports from an agent instance's injected attributes.

    ADR-0009 stores constructor-injected ports as instance attributes, so the
    runner reads ``vars(instance)`` (the typed instance ``__dict__``, not the
    banned ``getattr``) and resolves each port by runtime type. Attribute
    names are developer-chosen, so resolution is type-driven, not name-driven.
    """
    agent = Agent.get(type(instance))
    attributes = tuple(vars(instance).values())
    model = cls._resolve_required(attributes, IAgentModel)
    if model is None:
        raise AgentModelConfigurationError(
            "Agent run requires an IAgentModel port but none was injected"
        )
    states = cls._resolve_optional(attributes, IAgentStateRepository)
    signals = cls._resolve_optional(attributes, IAgentSignalRepository)
    evidence = cls._resolve_optional(attributes, IAgentEvidenceRepository)
    task_store = cls._resolve_optional(attributes, ITaskStore)
    context_provider = cls._resolve_optional(attributes, IAgentContextProvider)
    pricing = cls._resolve_optional(attributes, ModelPricingCatalog)
    telemetry = cls._resolve_optional(attributes, IAgentTelemetry)
    signal_mailbox = cls._resolve_optional(attributes, IAgentSignalSubscriber)
    if signal_mailbox is None:
        signal_mailbox = agent.signal_mailbox
    tool_providers = tuple(
        attribute
        for attribute in attributes
        if isinstance(attribute, IAgentToolProvider)
    )
    merged_catalog = AgentToolCatalog(
        descriptors=(
            *agent.tool_catalog.descriptors,
            *(
                descriptor
                for provider in tool_providers
                for descriptor in _bound_tool_provider_descriptors(provider)
            ),
        )
    )
    runner_agent = copy(agent)
    runner_agent.tool_catalog = merged_catalog
    runner = cls(
        agent=runner_agent,
        target=instance,
        model=model,
        states=states,
        signals=signals,
        evidence=evidence,
        task_store=task_store,
        context_provider=context_provider,
        pricing=pricing,
        telemetry=telemetry,
        signal_mailbox=signal_mailbox,
    )
    runner._require_durable_ports()
    return runner

with_model(model)

Return a runner using a run-specific model adapter.

Source code in core/spakky-agent/src/spakky/agent/runner.py
def with_model(self, model: IAgentModel) -> "AgentRunner":
    """Return a runner using a run-specific model adapter."""
    return replace(self, model=model)

with_pricing(pricing)

Return a runner using a snapshot of operator-owned pricing.

Source code in core/spakky-agent/src/spakky/agent/runner.py
def with_pricing(self, pricing: ModelPricingCatalog) -> "AgentRunner":
    """Return a runner using a snapshot of operator-owned pricing."""
    return replace(self, pricing=pricing)

with_telemetry(telemetry)

Return a runner emitting completed spans to one observer.

Source code in core/spakky-agent/src/spakky/agent/runner.py
def with_telemetry(self, telemetry: IAgentTelemetry) -> "AgentRunner":
    """Return a runner emitting completed spans to one observer."""
    return replace(self, telemetry=telemetry)

with_signal_mailbox(mailbox)

Return a runner receiving live signals through one mailbox port.

Source code in core/spakky-agent/src/spakky/agent/runner.py
def with_signal_mailbox(self, mailbox: IAgentSignalSubscriber) -> "AgentRunner":
    """Return a runner receiving live signals through one mailbox port."""
    return replace(self, signal_mailbox=mailbox)

run(run_input) async

Run one model-mediated agent loop, yielding the public stream.

Source code in core/spakky-agent/src/spakky/agent/runner.py
async def run(
    self,
    run_input: RunAgentInput,
) -> AsyncGenerator[AgentYield[object], None]:
    """Run one model-mediated agent loop, yielding the public stream."""
    started_at_ns = time_ns()
    completed = False
    outcome = "incomplete"
    error_code: str | None = None
    cost_attributes: dict[str, JsonValue] = {}
    try:
        stream = (
            self._run_stateless(run_input)
            if self.states is None
            else self._run_durable(run_input)
        )
        async for item in stream:
            if item.kind is AgentYieldKind.FINAL:
                completed = True
                outcome = "completed"
                if not isinstance(item.payload, Final):
                    raise AgentDefinitionError(
                        "Agent final yield contains an invalid payload"
                    )
                cost_attributes.update(
                    _telemetry_cost_attributes(item.payload.metadata)
                )
            elif item.kind is AgentYieldKind.APPROVAL:
                completed = True
                outcome = "paused"
                if not isinstance(item.payload, Approval):
                    raise AgentDefinitionError(
                        "Agent approval yield contains an invalid payload"
                    )
                cost_attributes.update(
                    _telemetry_cost_attributes(item.payload.metadata)
                )
            elif item.kind is AgentYieldKind.ERROR and isinstance(
                item.payload, Error
            ):
                completed = True
                outcome = "failed"
                error_code = item.payload.code
                cost_attributes.update(
                    _telemetry_cost_attributes(item.payload.metadata)
                )
            elif item.kind is AgentYieldKind.CANCEL:
                completed = True
                outcome = "cancelled"
                error_code = "cancelled"
                if not isinstance(item.payload, Cancel):
                    raise AgentDefinitionError(
                        "Agent cancel yield contains an invalid payload"
                    )
                cost_attributes.update(
                    _telemetry_cost_attributes(item.payload.metadata)
                )
            yield item
    except Exception:
        error_code = error_code or "agent_run_exception"
        raise
    finally:
        self._record_span(
            AgentSpanKind.RUN,
            "agent.run",
            started_at_ns,
            run_input.state_id,
            {
                "agent.conversation.id": run_input.effective_conversation_id,
                "agent.run.outcome": outcome,
                "agent.run.completed": completed,
                **cost_attributes,
            },
            error_code=error_code,
        )

run_events(run_input) async

Run the bounded loop while recording one privacy-safe run span.

Source code in core/spakky-agent/src/spakky/agent/runner.py
async def run_events(
    self,
    run_input: RunAgentInput,
) -> AsyncGenerator[AgentEvent, None]:
    """Run the bounded loop while recording one privacy-safe run span."""
    started_at_ns = time_ns()
    completed = False
    outcome = "incomplete"
    error_code: str | None = None
    cost_attributes: dict[str, JsonValue] = {}
    try:
        async for event in self._run_events_unobserved(run_input):
            if isinstance(event, RunPausedEvent):
                completed = True
                outcome = "paused"
                cost_attributes.update(_telemetry_cost_attributes(event.metadata))
            elif isinstance(event, RunFinishedEvent):
                completed = True
                cost_attributes.update(_telemetry_cost_attributes(event.metadata))
                if event.error is None:
                    outcome = "completed"
                else:
                    code = event.error.get("code")
                    error_code = (
                        code if isinstance(code, str) else "agent_run_failed"
                    )
                    outcome = "cancelled" if error_code == "cancelled" else "failed"
            yield event
    except Exception:
        error_code = error_code or "agent_run_exception"
        raise
    finally:
        self._record_span(
            AgentSpanKind.RUN,
            "agent.run",
            started_at_ns,
            run_input.state_id,
            {
                "agent.conversation.id": run_input.effective_conversation_id,
                "agent.run.outcome": outcome,
                "agent.run.completed": completed,
                **cost_attributes,
            },
            error_code=error_code,
        )

AgentRunResult(state_id, status, tool_calls, evidence_count) dataclass

Neutral terminal summary returned when a spec declares no output type.

AgentRunnerFactory(model_resolver=None, telemetry=None, pricing=None, signal_mailbox=None)

Bases: IAgentRunnerFactory

Default runner factory using the native framework-owned runner.

Source code in core/spakky-agent/src/spakky/agent/runner_factory.py
def __init__(
    self,
    model_resolver: IAgentModelResolver | None = None,
    telemetry: IAgentTelemetry | None = None,
    pricing: ModelPricingCatalog | None = None,
    signal_mailbox: IAgentSignalSubscriber | None = None,
) -> None:
    self._model_resolver = model_resolver
    self._telemetry = telemetry
    self._pricing = pricing
    self._signal_mailbox = signal_mailbox

open_runner(agent_instance, run_input=None) async

Yield the native runner for one request.

Source code in core/spakky-agent/src/spakky/agent/runner_factory.py
@override
@asynccontextmanager
async def open_runner(
    self,
    agent_instance: object,
    run_input: RunAgentInput | None = None,
) -> AsyncGenerator[AgentRunner, None]:
    """Yield the native runner for one request."""
    runner = AgentRunner.for_agent_instance(agent_instance)
    if self._model_resolver is not None:
        model = self._model_resolver.resolve_model(agent_instance, run_input)
        if model is not None:
            runner = runner.with_model(model)
    if self._telemetry is not None:
        runner = runner.with_telemetry(self._telemetry)
    if self._pricing is not None:
        runner = runner.with_pricing(self._pricing)
    if self._signal_mailbox is not None and runner.signal_mailbox is None:
        runner = runner.with_signal_mailbox(self._signal_mailbox)
    yield runner

IAgentRunnerFactory

Bases: ABC

Port for opening a request-scoped runner for one agent instance.

open_runner(agent_instance, run_input=None) abstractmethod

Yield a runner bound to agent_instance for one adapter request.

Source code in core/spakky-agent/src/spakky/agent/runner_factory.py
@abstractmethod
def open_runner(
    self,
    agent_instance: object,
    run_input: RunAgentInput | None = None,
) -> AbstractAsyncContextManager[AgentRunner]:
    """Yield a runner bound to ``agent_instance`` for one adapter request."""
    ...

IAgentEvidenceRepository

Bases: ABC

Append-only evidence repository exposed to agent-facing code.

append(evidence) abstractmethod

Append immutable evidence and return the stored artifact.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def append(self, evidence: AgentEvidence) -> AgentEvidence:
    """Append immutable evidence and return the stored artifact."""
    ...

get(evidence_id) abstractmethod

Return one evidence artifact by id.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get(self, evidence_id: str) -> AgentEvidence:
    """Return one evidence artifact by id."""
    ...

list_by_state(state_id) abstractmethod

Return evidence artifacts captured for an agent state in append order.

A resumed run replays this sequence, so the order must be the order of append calls. Stores that sort must order by created_at (the runner stamps strictly increasing values) and never by id as text: ...:evidence:10 sorts before ...:evidence:2.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_state(self, state_id: str) -> Sequence[AgentEvidence]:
    """Return evidence artifacts captured for an agent state in append order.

    A resumed run replays this sequence, so the order must be the order of
    ``append`` calls. Stores that sort must order by ``created_at`` (the
    runner stamps strictly increasing values) and never by ``id`` as text:
    ``...:evidence:10`` sorts before ``...:evidence:2``.
    """
    ...

list_by_manifest_ref(manifest_ref) abstractmethod

Return evidence artifacts of a context manifest in append order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_manifest_ref(self, manifest_ref: str) -> Sequence[AgentEvidence]:
    """Return evidence artifacts of a context manifest in append order."""
    ...

count_by_state(state_id)

Return how many evidence artifacts an agent state has.

Durable stores override this with a count query so appending evidence does not read every earlier artifact of the run.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def count_by_state(self, state_id: str) -> int:
    """Return how many evidence artifacts an agent state has.

    Durable stores override this with a count query so appending evidence
    does not read every earlier artifact of the run.
    """
    return len(self.list_by_state(state_id))

has_step_evidence(state_id, kind, model_step, digest)

Return whether one step-scoped context artifact was already recorded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def has_step_evidence(
    self,
    state_id: str,
    kind: AgentEvidenceKind,
    model_step: int,
    digest: str,
) -> bool:
    """Return whether one step-scoped context artifact was already recorded."""
    return any(
        item.kind == kind
        and item.model_step == model_step
        and item.digest == digest
        for item in self.list_by_state(state_id)
    )

list_by_origin_ref(origin_ref)

Return context evidence whose model context used origin_ref.

Stores without an origin index cannot answer this query.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def list_by_origin_ref(self, origin_ref: str) -> Sequence[AgentEvidence]:
    """Return context evidence whose model context used ``origin_ref``.

    Stores without an origin index cannot answer this query.
    """
    raise AgentEvidenceOriginQueryUnsupportedError()

IAgentSignalRepository

Bases: ABC

Durable inbound queue repository for agent signals.

append(signal) abstractmethod

Append a signal to the inbound queue and return the stored entry.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def append(self, signal: AgentSignal) -> AgentSignal:
    """Append a signal to the inbound queue and return the stored entry."""
    ...

list_pending(state_id) abstractmethod

Return unconsumed signals for an agent state in append/queue order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_pending(self, state_id: str) -> Sequence[AgentSignal]:
    """Return unconsumed signals for an agent state in append/queue order."""
    ...

mark_consumed(signal_id) abstractmethod

Mark one queued signal as consumed after a non-blocking poll.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def mark_consumed(self, signal_id: str) -> AgentSignal:
    """Mark one queued signal as consumed after a non-blocking poll."""
    ...

IAgentStateRepository

Bases: ABC

Materialized state repository for long-running agent executions.

get(state_id) abstractmethod

Return a persisted agent state by id.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get(self, state_id: str) -> AgentState:
    """Return a persisted agent state by id."""
    ...

get_or_none(state_id) abstractmethod

Return a persisted agent state by id, or None when absent.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get_or_none(self, state_id: str) -> AgentState | None:
    """Return a persisted agent state by id, or None when absent."""
    ...

save(state) abstractmethod

Persist the materialized state and return the saved snapshot.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def save(self, state: AgentState) -> AgentState:
    """Persist the materialized state and return the saved snapshot."""
    ...

list_by_status(status) abstractmethod

Return states matching an externally observable lifecycle status.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_status(self, status: AgentStatus) -> Sequence[AgentState]:
    """Return states matching an externally observable lifecycle status."""
    ...

list_resume_candidates() abstractmethod

Return active or interrupted states that may resume after restart.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_resume_candidates(self) -> Sequence[AgentState]:
    """Return active or interrupted states that may resume after restart."""
    ...

ConversationTurn(role, content, metadata=dict()) dataclass

One persisted exchange in a multi-turn conversation transcript.

A turn is the protocol-neutral unit a TaskStore persists: who spoke (role) and what was said (content). It is intentionally narrower than a model-request ModelMessage — the transcript records the user/assistant dialogue that seeds future turns, not the system or evidence framing the runner assembles fresh on each request. as_model_message projects a turn back into the model-request vocabulary when the runner replays history.

__post_init__()

Reject turns that cannot seed a future model request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
def __post_init__(self) -> None:
    """Reject turns that cannot seed a future model request."""
    if self.role not in (ModelMessageRole.USER, ModelMessageRole.ASSISTANT):
        raise AgentDefinitionError(
            "Conversation turn role must be user or assistant"
        )
    if not self.content.strip():
        raise AgentDefinitionError("Conversation turn content cannot be blank")

as_model_message()

Project this turn into a model-request message for history replay.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
def as_model_message(self) -> ModelMessage:
    """Project this turn into a model-request message for history replay."""
    return ModelMessage(
        role=self.role, content=self.content, metadata=self.metadata
    )

ITaskStore

Bases: ABC

Durable conversation-history store keyed by conversation_id.

Persists the running transcript of a server-side session so a later run with the same conversation_id continues the conversation (ADR-0013 §6). A2A can map its contextId to this key for transcript replay, while A2A task snapshots are stored by spakky-a2a's repository bridge.

load_history(conversation_id) abstractmethod

Return the persisted transcript for a conversation in turn order.

Returns an empty sequence for a conversation that has no persisted turns yet — the first turn of a brand-new conversation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
@abstractmethod
def load_history(self, conversation_id: str) -> Sequence[ConversationTurn]:
    """Return the persisted transcript for a conversation in turn order.

    Returns an empty sequence for a conversation that has no persisted turns
    yet — the first turn of a brand-new conversation.
    """
    ...

append_turns(conversation_id, turns) abstractmethod

Append new turns to a conversation's transcript in order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
@abstractmethod
def append_turns(
    self,
    conversation_id: str,
    turns: Sequence[ConversationTurn],
) -> None:
    """Append new turns to a conversation's transcript in order."""
    ...

AbstractAgentModelError()

Bases: AbstractSpakkyFrameworkError, ABC

Model failure that can carry a privacy-safe billable invocation receipt.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __init__(self) -> None:
    super().__init__()
    self.model_usage = None
    self.model_metadata = {}

attach_model_receipt(usage, metadata)

Attach known usage/routing after provider success but before later failure.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def attach_model_receipt(
    self,
    usage: ModelUsage,
    metadata: JsonObject,
) -> None:
    """Attach known usage/routing after provider success but before later failure."""
    if not isinstance(usage, ModelUsage):
        raise AgentDefinitionError("Agent model failure usage is invalid")
    self.model_usage = usage
    self.model_metadata = _snapshot_json_object(metadata)

AgentModelStepRestartError()

Bases: AbstractAgentModelError

Raised by a model adapter to discard the current model step and redo it.

Raise it from IAgentModel.stream() or complete() when the output of the step in flight cannot be trusted, for example when the provider stream broke midway. The runner drops everything that step produced: its text is not added to the transcript and the tool calls it proposed are not run. It tells consumers to drop what was already streamed with a Progress whose metadata has invalidate_output=True and code="agent_model_step_restarted", then sends the same request again as the next model step.

The discarded step still counts toward max_steps and the run deadline, so an adapter that keeps raising cannot loop forever when either is set; bound the retries in the adapter when both are unset. Call attach_model_receipt first when the provider already billed the step, so its usage stays in the run totals.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __init__(self) -> None:
    super().__init__()
    self.model_usage = None
    self.model_metadata = {}

IAgentModel

Bases: ABC

Outbound model adapter port owned by spakky-agent core.

capability abstractmethod property

Return the backend capability descriptor queryable before a run.

capability_for(selection=None)

Return capability for a run-specific model selection.

Existing fixed-model adapters can ignore the selector and inherit the default. Routing adapters can override this to expose per-model context windows, reasoning support, or token-counting support before a request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def capability_for(
    self,
    selection: ModelSelection | None = None,
) -> ModelCapability:
    """Return capability for a run-specific model selection.

    Existing fixed-model adapters can ignore the selector and inherit the
    default. Routing adapters can override this to expose per-model context
    windows, reasoning support, or token-counting support before a request.
    """
    _ = selection
    return self.capability

validate_request(request)

Fail before provider I/O when this model cannot honor the request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def validate_request(self, request: ModelRequest) -> None:
    """Fail before provider I/O when this model cannot honor the request."""
    if not isinstance(request, ModelRequest):
        raise AgentDefinitionError("Agent model request is invalid")
    capability = self.capability_for(request.model_selection)
    if not isinstance(capability, ModelCapability):
        raise AgentModelConfigurationError(
            "Agent model capability descriptor is invalid"
        )
    if not request.required_input_modalities() <= capability.input_modalities:
        raise AgentModelConfigurationError(
            "Agent model does not support every requested input modality"
        )

complete(request) abstractmethod async

Return a complete response, awaiting resource cleanup on cancellation.

Remote adapters must await cancellation acknowledgement before returning from cancellation cleanup; failures must propagate to stop continuation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@abstractmethod
async def complete(self, request: ModelRequest) -> ModelResponse:
    """Return a complete response, awaiting resource cleanup on cancellation.

    Remote adapters must await cancellation acknowledgement before returning
    from cancellation cleanup; failures must propagate to stop continuation.
    """
    ...

stream(request) abstractmethod

Return provider-neutral events with deterministic cancellation cleanup.

The runner cancels and awaits pending iteration on a revised input and explicitly closes async generators. Custom iterators must release their resources on cancellation of __anext__. Remote cancellation must be acknowledged before cleanup returns; unconfirmed cleanup must propagate.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@abstractmethod
def stream(self, request: ModelRequest) -> AsyncIterator[ModelStreamEvent]:
    """Return provider-neutral events with deterministic cancellation cleanup.

    The runner cancels and awaits pending iteration on a revised input and
    explicitly closes async generators. Custom iterators must release their
    resources on cancellation of ``__anext__``. Remote cancellation must be
    acknowledged before cleanup returns; unconfirmed cleanup must propagate.
    """
    ...

JsonSchemaConstraint(schema, strict=True) dataclass

JSON schema constraint shared by structured output and tool calling.

ModelCapability(supports_reasoning=False, context_window_tokens=None, supports_token_counting=False, input_modalities=frozenset({ModelModality.TEXT}), output_modalities=frozenset({ModelModality.TEXT}), supports_tools=False, supports_structured_output=False) dataclass

Provider-neutral declaration of a model backend's queryable abilities.

The agent runner consults this descriptor before a run to adjust behaviour without invoking the backend. Input/output modalities default to text only, while tool calling and structured output default to unsupported. Reasoning, context-window size, and token-counting support remain explicit so routing adapters can expose the exact abilities of each logical model route.

ModelError(code, message, retryable=False, metadata=dict()) dataclass

Provider-neutral model failure payload.

ModelMessage(role, content, metadata=dict()) dataclass

Provider-neutral model message.

__post_init__()

Snapshot multipart content while preserving canonical plain strings.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Snapshot multipart content while preserving canonical plain strings."""
    if not isinstance(self.role, ModelMessageRole):
        raise AgentDefinitionError("Model message role is invalid")
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))
    if isinstance(self.content, str):
        return
    object.__setattr__(self, "content", model_content_parts(self.content))

user(content, *, metadata=None) classmethod

Create a user message through the shortest canonical DX.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@classmethod
def user(
    cls,
    content: ModelContent,
    *,
    metadata: JsonObject | None = None,
) -> Self:
    """Create a user message through the shortest canonical DX."""
    return cls(
        role=ModelMessageRole.USER,
        content=content,
        metadata={} if metadata is None else metadata,
    )

ModelMessageRole

Bases: StrEnum

Roles accepted by provider-neutral model messages.

ModelModality

Bases: StrEnum

Portable input and output modalities declared by one model route.

ModelRequest(messages, context=tuple(), context_manifest=None, context_digest=None, structured_output=None, tool_calling=None, sampling=SamplingOptions(), streaming=StreamingOptions(), model_selection=None, metadata=dict(), extensions=()) dataclass

Provider-neutral request passed to an agent model adapter.

extensions = () class-attribute instance-attribute

Typed application values carried with the run, one per extension type.

__post_init__()

Deep-snapshot every mutable request input before async adapter work.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Deep-snapshot every mutable request input before async adapter work."""
    if not isinstance(self.messages, Sequence) or isinstance(
        self.messages,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model request messages must be a sequence")
    messages = tuple(self.messages)
    if any(not isinstance(message, ModelMessage) for message in messages):
        raise AgentDefinitionError("Model request contains an invalid message")
    validate_model_content_budget(tuple(message.content for message in messages))
    if not isinstance(self.context, Sequence) or isinstance(
        self.context,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model request context must be a sequence")
    context = tuple(self.context)
    if any(not isinstance(pack, ContextPack) for pack in context):
        raise AgentDefinitionError("Model request contains an invalid context pack")
    object.__setattr__(self, "messages", messages)
    object.__setattr__(self, "context", context)
    if self.context_manifest is not None:
        if not isinstance(self.context_manifest, ContextManifest):
            raise AgentDefinitionError("Model request context manifest is invalid")
        _snapshot_context_manifest(self.context_manifest)
    if self.context_digest is not None:
        if not isinstance(self.context_digest, ContextDigest):
            raise AgentDefinitionError("Model request context digest is invalid")
        _snapshot_context_digest(self.context_digest)
    if self.structured_output is not None:
        if not isinstance(self.structured_output, StructuredOutputSpec):
            raise AgentDefinitionError("Model structured output spec is invalid")
    if self.tool_calling is not None:
        if not isinstance(self.tool_calling, ToolCallingSpec):
            raise AgentDefinitionError("Model tool calling spec is invalid")
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))
    object.__setattr__(self, "extensions", validated_extensions(self.extensions))

snapshot()

Return a deep request copy shared across one async adapter invocation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def snapshot(self) -> "ModelRequest":
    """Return a deep request copy shared across one async adapter invocation."""
    return ModelRequest(
        messages=tuple(replace(message) for message in self.messages),
        context=tuple(_snapshot_context_pack(pack) for pack in self.context),
        context_manifest=(
            None
            if self.context_manifest is None
            else _snapshot_context_manifest(self.context_manifest)
        ),
        context_digest=(
            None
            if self.context_digest is None
            else _snapshot_context_digest(self.context_digest)
        ),
        structured_output=(
            None
            if self.structured_output is None
            else _snapshot_structured_output(self.structured_output)
        ),
        tool_calling=(
            None
            if self.tool_calling is None
            else _snapshot_tool_calling(self.tool_calling)
        ),
        sampling=self.sampling,
        streaming=self.streaming,
        model_selection=self.model_selection,
        metadata=_snapshot_json_object(self.metadata),
        extensions=self.extensions,
    )

assemble_messages(policy=None)

Assemble prompt messages from typed context packs without concatenation.

SYSTEM packs join the leading system message, PRELUDE packs come before the conversation history and TRAILER packs come after it. Packs that stay fixed for a run therefore keep the prompt prefix cacheable.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def assemble_messages(
    self,
    policy: ContextExposurePolicy | None = None,
) -> tuple[ModelMessage, ...]:
    """Assemble prompt messages from typed context packs without concatenation.

    ``SYSTEM`` packs join the leading system message, ``PRELUDE`` packs come
    before the conversation history and ``TRAILER`` packs come after it. Packs
    that stay fixed for a run therefore keep the prompt prefix cacheable.
    """
    exposure_policy = policy or ContextExposurePolicy()
    lead = next(
        (
            index
            for index, message in enumerate(self.messages)
            if message.role is not ModelMessageRole.SYSTEM
        ),
        len(self.messages),
    )
    leading = list(self.messages[:lead])
    system_text = tuple(
        pack.guarded_content(exposure_policy)
        for pack in self.context
        if pack.placement is ContextPlacement.SYSTEM
    )
    if system_text:
        instructions = leading[-1].content if leading else None
        if isinstance(instructions, str):
            leading[-1] = replace(
                leading[-1], content="\n\n".join((instructions, *system_text))
            )
        else:
            leading.append(
                ModelMessage(ModelMessageRole.SYSTEM, "\n\n".join(system_text))
            )

    def evidence(placement: ContextPlacement) -> tuple[ModelMessage, ...]:
        return tuple(
            ModelMessage(
                role=ModelMessageRole.EVIDENCE,
                content=pack.guarded_content(exposure_policy),
                metadata=pack.message_metadata(exposure_policy),
            )
            for pack in self.context
            if pack.placement is placement
        )

    return (
        *leading,
        *evidence(ContextPlacement.PRELUDE),
        *self.messages[lead:],
        *evidence(ContextPlacement.TRAILER),
    )

extension(kind)

Return this request's typed application extension of kind.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def extension[T: AgentRunExtension](self, kind: type[T]) -> T | None:
    """Return this request's typed application extension of ``kind``."""
    return next((item for item in self.extensions if isinstance(item, kind)), None)

required_input_modalities()

Derive every modality present in provider-bound message content.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def required_input_modalities(self) -> frozenset["ModelModality"]:
    """Derive every modality present in provider-bound message content."""
    modality_by_type = {
        TextPart: ModelModality.TEXT,
        ImagePart: ModelModality.IMAGE,
        AudioPart: ModelModality.AUDIO,
        VideoPart: ModelModality.VIDEO,
        DocumentPart: ModelModality.DOCUMENT,
    }
    modalities: set[ModelModality] = set()
    for message in self.assemble_messages():
        if isinstance(message.content, str):
            modalities.add(ModelModality.TEXT)
            continue
        for part in model_content_parts(message.content):
            modalities.add(modality_by_type[type(part)])
    return frozenset(modalities)

ModelResponse(content, structured_output=None, tool_calls=tuple(), usage=ModelUsage(), metadata=dict()) dataclass

Provider-neutral non-streaming model response.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive output payloads deterministically guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelResponse":
    """Return a copy with sensitive output payloads deterministically guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    content = self.content
    structured_output = self.structured_output
    content_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path in ((), ("content",))
    )
    if content_descriptors:
        guarded_content = guard_json_value(
            {"content": content},
            tuple(
                SensitiveFieldDescriptor(("content",), descriptor.field)
                for descriptor in content_descriptors
            ),
            exposure_policy,
        )
        content_value = cast(Mapping[str, JsonValue], guarded_content).get(
            "content"
        )
        if isinstance(content_value, str):
            content = content_value
        else:
            content = "[REDACTED]"
    structured_output_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path not in ((), ("content",))
    )
    if structured_output_descriptors:
        structured_output = guard_json_value(
            structured_output,
            structured_output_descriptors,
            exposure_policy,
        )
    return replace(self, content=content, structured_output=structured_output)

ModelSelection(model_ref) dataclass

Opaque operator-catalog model reference carried by one Agent run.

__post_init__()

Reject blank catalog references before they reach routing adapters.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Reject blank catalog references before they reach routing adapters."""
    if self.model_ref.strip() == "":
        raise AgentDefinitionError("Model selection model_ref cannot be blank")

ModelStreamEvent(kind, token_delta=None, message_delta=None, reasoning_delta=None, tool_call=None, tool_call_args_delta=None, structured_output=None, error=None, usage=None, metadata=dict()) dataclass

Provider-neutral model streaming event.

token_delta carries the generic streamed token channel. message_delta and reasoning_delta distinguish assistant-facing text from model reasoning so callers can route or suppress reasoning independently. tool_call_args_delta carries incremental tool-call argument text framed by TOOL_CALL_START and TOOL_CALL_END boundary events that reference the same tool_call.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive streaming payloads guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelStreamEvent":
    """Return a copy with sensitive streaming payloads guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    text_channels: dict[str, str | None] = {
        "token_delta": self.token_delta,
        "message_delta": self.message_delta,
        "reasoning_delta": self.reasoning_delta,
        "tool_call_args_delta": self.tool_call_args_delta,
    }
    guarded_text = {
        field_name: self._guard_text_delta(
            field_name, value, sensitive_fields, exposure_policy
        )
        for field_name, value in text_channels.items()
        if value is not None
    }
    text_paths = (
        (),
        *((field_name,) for field_name in text_channels),
    )
    structured_output = self.structured_output
    structured_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path not in text_paths
    )
    if structured_descriptors:
        structured_output = guard_json_value(
            structured_output,
            structured_descriptors,
            exposure_policy,
        )
    tool_call = self.tool_call
    if tool_call is not None:
        tool_call = tool_call.guarded(sensitive_fields, exposure_policy)
    return replace(
        self,
        structured_output=structured_output,
        tool_call=tool_call,
        **guarded_text,
    )

ModelStreamEventKind

Bases: StrEnum

Provider-neutral streaming event kinds emitted by a model adapter.

ModelToolCall(name, arguments, call_id=None, metadata=dict()) dataclass

Tool invocation candidate emitted by a model adapter.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive argument values deterministically guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelToolCall":
    """Return a copy with sensitive argument values deterministically guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    guarded_arguments = guard_json_value(
        self.arguments,
        sensitive_fields,
        exposure_policy,
    )
    if not isinstance(guarded_arguments, Mapping):
        guarded_arguments = {}
    return replace(self, arguments=guarded_arguments)

ModelToolChoice

Bases: StrEnum

Provider-neutral tool calling strategy requested from a model adapter.

ModelToolSpec(name, parameters, description=None, metadata=dict()) dataclass

LLM-facing tool descriptor normalized by agent tooling.

__post_init__()

Deep-freeze tool metadata before provider or cache observation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Deep-freeze tool metadata before provider or cache observation."""
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))

ModelUsage(input_tokens=None, output_tokens=None, total_tokens=None, cached_input_tokens=None, cache_write_input_tokens=None, cache_write_5m_input_tokens=None, cache_write_1h_input_tokens=None) dataclass

Token accounting reported by a model adapter.

SamplingOptions(temperature=None, top_p=None, max_tokens=None) dataclass

Portable model sampling options.

StreamingOptions(include_usage=True, include_progress=True) dataclass

Portable model streaming options.

StructuredOutputSpec(constraint, output_type_name=None) dataclass

Structured output contract requested from a model adapter.

ToolCallingSpec(tools, choice=ModelToolChoice.AUTO) dataclass

Tool calling contract requested from a model adapter.

__post_init__()

Snapshot the ordered tool catalog supplied by a mutable caller.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Snapshot the ordered tool catalog supplied by a mutable caller."""
    if not isinstance(self.tools, Sequence) or isinstance(
        self.tools,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model tool catalog must be a sequence")
    tools = tuple(self.tools)
    if any(not isinstance(tool, ModelToolSpec) for tool in tools):
        raise AgentDefinitionError("Model tool catalog contains an invalid tool")
    object.__setattr__(self, "tools", tools)

AgentRunMailbox(state_id, loop, owner=None)

Live, loop-bound inbox of one agent run with control and steering lanes.

deliver may be called from any thread. Accepted signals are queued in arrival order; drain hands them to the run at its next observation. wait wakes on any arrival and wait_control only on a AgentSignalLane.CONTROL arrival, so in-flight work is interrupted only by cancel or urgent input while ordinary steering waits for a safe point.

Bind a mailbox to one agent state and the event loop running it.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def __init__(
    self,
    state_id: str,
    loop: AbstractEventLoop,
    owner: "InProcessAgentSignalMailbox | None" = None,
) -> None:
    """Bind a mailbox to one agent state and the event loop running it."""
    self._state_id = state_id
    self._loop = loop
    self._owner = owner
    self._queue = deque()
    self._arrived = Event()
    self._control_arrived = Event()
    self._closed = False

state_id property

Return the agent state this mailbox receives signals for.

closed property

Return whether the run closed this mailbox.

deliver(signal)

Hand one committed signal to the run loop from any thread.

A producer already running on the run's own loop (for example a tool appending a signal) is accepted synchronously so the very next boundary observes it; any other thread or loop is handed over with call_soon_threadsafe.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def deliver(self, signal: AgentSignal) -> None:
    """Hand one committed signal to the run loop from any thread.

    A producer already running on the run's own loop (for example a tool
    appending a signal) is accepted synchronously so the very next boundary
    observes it; any other thread or loop is handed over with
    ``call_soon_threadsafe``.
    """
    if self._on_own_loop():
        self._accept(signal)
        return
    try:
        self._loop.call_soon_threadsafe(self._accept, signal)
    except RuntimeError:
        # The run loop already closed; the ledger row is replayed on resume.
        logger.debug(
            "Agent signal mailbox loop closed before delivery",
            extra={"state_id": self._state_id, "signal_id": signal.id},
        )

drain()

Return and clear every signal delivered since the last drain.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def drain(self) -> tuple[AgentSignal, ...]:
    """Return and clear every signal delivered since the last drain."""
    drained = tuple(self._queue)
    self._queue.clear()
    self._arrived.clear()
    self._control_arrived.clear()
    return drained

wait() async

Wait until any signal arrives after the last drain.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
async def wait(self) -> None:
    """Wait until any signal arrives after the last drain."""
    await self._arrived.wait()

wait_control() async

Wait until a control-lane signal arrives after the last drain.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
async def wait_control(self) -> None:
    """Wait until a control-lane signal arrives after the last drain."""
    await self._control_arrived.wait()

close()

Stop accepting signals and detach from the owning publisher.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def close(self) -> None:
    """Stop accepting signals and detach from the owning publisher."""
    self._closed = True
    self._queue.clear()
    if self._owner is not None:
        self._owner.unsubscribe(self)

IAgentSignalPublisher

Bases: ABC

Port that delivers committed signals to live run mailboxes.

publish(signal) abstractmethod

Deliver one signal whose ledger row is already committed.

Implementations must be thread-safe and must not block. Publishing a signal for a state with no live subscriber is not an error: the ledger row is replayed when that state's run next starts or resumes.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
@abstractmethod
def publish(self, signal: AgentSignal) -> None:
    """Deliver one signal whose ledger row is already committed.

    Implementations must be thread-safe and must not block. Publishing a
    signal for a state with no live subscriber is not an error: the ledger
    row is replayed when that state's run next starts or resumes.
    """
    ...

IAgentSignalSubscriber

Bases: ABC

Port that opens the live mailbox of one running agent state.

subscribe(state_id) abstractmethod

Open a mailbox bound to the calling event loop for state_id.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
@abstractmethod
def subscribe(self, state_id: str) -> "AgentRunMailbox":
    """Open a mailbox bound to the calling event loop for ``state_id``."""
    ...

InProcessAgentSignalMailbox()

Bases: IAgentSignalPublisher, IAgentSignalSubscriber

Default in-process signal hub routing committed signals to run mailboxes.

Create an empty subscriber registry.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def __init__(self) -> None:
    """Create an empty subscriber registry."""
    self._lock = Lock()
    self._subscribers = {}

unsubscribe(mailbox)

Detach a closed run mailbox from future publications.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def unsubscribe(self, mailbox: AgentRunMailbox) -> None:
    """Detach a closed run mailbox from future publications."""
    with self._lock:
        mailboxes = self._subscribers.get(mailbox.state_id)
        if mailboxes is None or mailbox not in mailboxes:
            return
        mailboxes.remove(mailbox)
        if not mailboxes:
            del self._subscribers[mailbox.state_id]

subscriber_count(state_id)

Return how many live runs currently listen for state_id.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def subscriber_count(self, state_id: str) -> int:
    """Return how many live runs currently listen for ``state_id``."""
    with self._lock:
        return len(self._subscribers.get(state_id, ()))

AgentSteeringUpdate

Bases: BaseModel

Revisioned input; provisional observations grant no tool/final authority.

input_id is caller-owned and scoped to a conversation/utterance. Withdrawal removes that input while retaining its revision tombstone for idempotence.

AgentSignal(id, agent_state_id, kind, payload=dict(), created_at=None, priority=AgentSignalPriority.NORMAL) dataclass

Inbound stimulus appended for an agent execution.

lane property

Return the live mailbox lane selected by kind and producer priority.

AgentSignalKind

Bases: StrEnum

Inbound stimulus kinds that an agent may accept while running.

AgentSignalLane

Bases: StrEnum

Live delivery lanes of a run mailbox.

CONTROL interrupts the in-flight model operation immediately (cancel and urgent revisioned steering). STEERING waits in the run mailbox until the next safe point, such as a finished model response or tool boundary.

AgentSignalPriority

Bases: StrEnum

Producer-assigned urgency used only for live mailbox lane routing.

Priority is a delivery hint, not part of the durable ledger row. Replayed signals are applied at the first safe boundary of a starting or resuming run, where no in-flight work exists to interrupt.

ApprovalDecision

Bases: StrEnum

Human-in-the-loop approval outcomes.

AgentSignalConsumptionBatch(state_id, poll_point, signals) dataclass

Signals consumed during one non-blocking poll.

consumed_count property

Return the number of signals consumed by this poll.

AgentSignalPollPoint

Bases: StrEnum

Places where orchestration may poll durable signals without waiting.

ContextExposurePolicy(include_pii_values=False, include_sensitive_values=False, include_sensitive_schema_metadata=False, include_sensitive_context_metadata=False) dataclass

Policy for LLM-facing context and schema metadata exposure.

can_expose_value(field)

Return whether a sensitive value may cross the model boundary.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def can_expose_value(self, field: "SensitiveField | SecretField") -> bool:
    """Return whether a sensitive value may cross the model boundary."""
    if isinstance(field, SecretField):
        return False
    if field.sensitivity == DataSensitivity.PII:
        return self.include_pii_values
    if field.sensitivity in (DataSensitivity.CONFIDENTIAL, DataSensitivity.SECRET):
        return self.include_sensitive_values
    return True

CredentialRef(id, provider=None) dataclass

Reference to a credential outside LLM-facing context.

__post_init__()

Reject blank credential references.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank credential references."""
    _require_non_blank(self.id, "Credential reference id")
    if self.provider is not None:
        _require_non_blank(self.provider, "Credential provider")

DataSensitivity

Bases: StrEnum

Canonical sensitivity classes carried by descriptors.

EvidenceExposurePolicy(include_pii_values=False, include_sensitive_values=False, include_sensitive_metadata=True) dataclass

Policy for evidence payload exposure before append-only capture.

can_expose_value(field)

Return whether a sensitive value may be stored in evidence payloads.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def can_expose_value(self, field: "SensitiveField | SecretField") -> bool:
    """Return whether a sensitive value may be stored in evidence payloads."""
    if isinstance(field, SecretField):
        return False
    if field.sensitivity == DataSensitivity.PII:
        return self.include_pii_values
    if field.sensitivity in (DataSensitivity.CONFIDENTIAL, DataSensitivity.SECRET):
        return self.include_sensitive_values
    return True

MaskingPolicy

Bases: StrEnum

Deterministic text masking strategies for sensitive values.

PII

Bases: StrEnum

PII categories that can be declared with typing.Annotated.

RedactionPolicy

Bases: StrEnum

Boundary action used when a value must not be exposed.

SecretField(redaction=RedactionPolicy.REFERENCE_ONLY, label=None, metadata=dict()) dataclass

typing.Annotated metadata for values that must never be model text.

sensitivity property

Return the normalized sensitivity class.

__post_init__()

Reject blank secret field labels.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank secret field labels."""
    if self.label is not None:
        _require_non_blank(self.label, "Secret field label")

guard_text(value)

Return deterministic replacement text for a secret value.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def guard_text(self, value: str) -> str:
    """Return deterministic replacement text for a secret value."""
    return SECRET_VALUE

to_metadata()

Serialize marker metadata without including the secret value.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_metadata(self) -> JsonObject:
    """Serialize marker metadata without including the secret value."""
    payload: dict[str, JsonValue] = {
        "kind": "secret",
        "sensitivity": DataSensitivity.SECRET.value,
        "redaction": self.redaction.value,
    }
    if self.label is not None:
        payload["label"] = self.label
    if self.metadata:
        payload["metadata"] = self.metadata
    return payload

SecretRef(id, credential=None) dataclass

Opaque reference to a secret value stored outside model context.

__post_init__()

Reject blank secret references.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank secret references."""
    _require_non_blank(self.id, "Secret reference id")

SensitiveField(category, masking=MaskingPolicy.REDACT, redaction=RedactionPolicy.REDACT, label=None, metadata=dict()) dataclass

typing.Annotated metadata for deterministic sensitive-field handling.

sensitivity property

Return the normalized sensitivity class.

category_name property

Return the stable public category name.

__post_init__()

Reject blank sensitive field labels.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank sensitive field labels."""
    if self.label is not None:
        _require_non_blank(self.label, "Sensitive field label")

guard_text(value)

Return deterministic model/evidence-safe text for this field.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def guard_text(self, value: str) -> str:
    """Return deterministic model/evidence-safe text for this field."""
    return _mask_text(value, self.masking, self.category_name)

to_metadata()

Serialize marker metadata without including the sensitive value.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_metadata(self) -> JsonObject:
    """Serialize marker metadata without including the sensitive value."""
    payload: dict[str, JsonValue] = {
        "kind": "sensitive",
        "category": self.category_name,
        "sensitivity": self.sensitivity.value,
        "masking": self.masking.value,
        "redaction": self.redaction.value,
    }
    if self.label is not None:
        payload["label"] = self.label
    if self.metadata:
        payload["metadata"] = self.metadata
    return payload

SensitiveFieldDescriptor(path, field) dataclass

Path-bound sensitive metadata extracted from Annotated types.

to_metadata()

Serialize descriptor metadata without leaking the field value.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_metadata(self) -> JsonObject:
    """Serialize descriptor metadata without leaking the field value."""
    return {
        "path": list(self.path),
        "field": self.field.to_metadata(),
    }

StreamingGuardFailureMode

Bases: StrEnum

Final audit behavior when a streaming guard missed a raw candidate.

StreamingRedactionAudit(status, detected_count, redacted_count, missed_matches, buffer_size, emitted_char_count, original_char_count) dataclass

Final aggregate audit for a bounded streaming redaction session.

missed_count property

Return the number of raw candidates still present after streaming.

to_evidence_payload()

Serialize audit evidence without raw streamed content.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_evidence_payload(self) -> JsonObject:
    """Serialize audit evidence without raw streamed content."""
    return {
        "kind": "streaming_redaction_audit",
        "status": self.status.value,
        "detected_count": self.detected_count,
        "redacted_count": self.redacted_count,
        "missed_count": self.missed_count,
        "missed_matches": tuple(
            match.to_payload() for match in self.missed_matches
        ),
        "buffer_size": self.buffer_size,
        "emitted_char_count": self.emitted_char_count,
        "original_char_count": self.original_char_count,
    }

to_error_payload()

Serialize a typed error payload for stream consumers.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_error_payload(self) -> JsonObject:
    """Serialize a typed error payload for stream consumers."""
    return {
        "code": "streaming_redaction_audit_failed",
        "message": "Streaming redaction final audit detected unmasked candidates",
        "retryable": False,
        "metadata": self.to_evidence_payload(),
    }

StreamingRedactionAuditStatus

Bases: StrEnum

Final aggregate streaming redaction audit status.

StreamingRedactionMatch(pattern_name, start, end, metadata=dict()) dataclass

Sanitized final-audit match location for a missed redaction candidate.

to_payload()

Serialize a match without the sensitive value itself.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_payload(self) -> JsonObject:
    """Serialize a match without the sensitive value itself."""
    payload: dict[str, JsonValue] = {
        "pattern_name": self.pattern_name,
        "start": self.start,
        "end": self.end,
    }
    if self.metadata:
        payload["metadata"] = self.metadata
    return payload

StreamingRedactionPolicy(patterns, buffer_size=64, emit_chunk_size=None, failure_mode=StreamingGuardFailureMode.RAISE) dataclass

Bounded buffering policy balancing stream latency and redaction correctness.

__post_init__()

Reject policies that would make the guard unbounded or silent.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject policies that would make the guard unbounded or silent."""
    if self.buffer_size <= 0:
        raise AgentDefinitionError(
            "Streaming redaction buffer size must be positive"
        )
    if self.emit_chunk_size is not None and self.emit_chunk_size <= 0:
        raise AgentDefinitionError(
            "Streaming redaction emit chunk size must be positive"
        )
    if len(self.patterns) == 0:
        raise AgentDefinitionError("Streaming redaction patterns cannot be empty")

StreamingRedactionResult(chunks, audit=None, error=None) dataclass

Output produced by a bounded streaming redaction step.

StreamingRedactionSession(policy)

Stateful bounded redactor for model token streams.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __init__(self, policy: StreamingRedactionPolicy) -> None:
    self._policy = policy
    self._patterns = tuple(policy.patterns)
    self._buffer = ""
    self._original_chunks: list[str] = []
    self._emitted_chunks: list[str] = []
    self._redacted_count = 0
    self._closed = False

push(chunk)

Redact one token chunk and emit only the safe bounded prefix.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def push(self, chunk: str) -> StreamingRedactionResult:
    """Redact one token chunk and emit only the safe bounded prefix."""
    self._ensure_open()
    if chunk == "":
        return StreamingRedactionResult(chunks=())
    self._original_chunks.append(chunk)
    self._buffer = self._redact_text(f"{self._buffer}{chunk}")
    chunks = self._emit_safe_prefix()
    return StreamingRedactionResult(chunks=chunks)

finish()

Flush the remaining buffer and run the mandatory final audit.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def finish(self) -> StreamingRedactionResult:
    """Flush the remaining buffer and run the mandatory final audit."""
    self._ensure_open()
    self._closed = True
    redacted_buffer = self._redact_text(self._buffer)
    chunks = self._split_for_emit(redacted_buffer)
    self._buffer = ""
    self._emitted_chunks.extend(chunks)
    audit = self._audit()
    if audit.status == StreamingRedactionAuditStatus.FAILED:
        if self._policy.failure_mode == StreamingGuardFailureMode.RAISE:
            raise AgentOutputGuardError(
                "Streaming redaction final audit detected unmasked candidates"
            )
        return StreamingRedactionResult(
            chunks=chunks,
            audit=audit,
            error=audit.to_error_payload(),
        )
    return StreamingRedactionResult(chunks=chunks, audit=audit)

StreamingSensitivePattern(name, pattern, replacement=REDACTED_VALUE, metadata=dict()) dataclass

Caller-supplied deterministic pattern used by streaming redaction.

__post_init__()

Reject blank names and invalid pattern syntax before streaming starts.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank names and invalid pattern syntax before streaming starts."""
    _require_non_blank(self.name, "Streaming sensitive pattern name")
    _require_non_blank(self.pattern, "Streaming sensitive pattern")
    try:
        re.compile(self.pattern)
    except re.error as e:
        raise AgentDefinitionError("Streaming sensitive pattern is invalid") from e

redact(value)

Return redacted text and the number of replacements applied.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def redact(self, value: str) -> tuple[str, int]:
    """Return redacted text and the number of replacements applied."""
    compiled = re.compile(self.pattern)
    return compiled.subn(self.replacement, value)

find_matches(value)

Return sanitized match locations without exposing raw text.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def find_matches(self, value: str) -> tuple["StreamingRedactionMatch", ...]:
    """Return sanitized match locations without exposing raw text."""
    compiled = re.compile(self.pattern)
    return tuple(
        StreamingRedactionMatch(
            pattern_name=self.name,
            start=match.start(),
            end=match.end(),
            metadata=self.metadata,
        )
        for match in compiled.finditer(value)
    )

AgentState(id, agent_type, status, transition=None, reason=None, current_activity=None, input_ref=None, output_ref=None, pending_signal_count=0, last_event_cursor=None, recovery_marker=None, metadata=dict(), created_at=None, updated_at=None) dataclass

Materialized state for a long-running agent execution.

__post_init__()

Reject state snapshots that cannot represent a real queue count.

Source code in core/spakky-agent/src/spakky/agent/state.py
def __post_init__(self) -> None:
    """Reject state snapshots that cannot represent a real queue count."""
    if self.pending_signal_count < 0:
        raise AgentDefinitionError("Agent pending signal count cannot be negative")

AgentStateReason

Bases: StrEnum

Structured reason that refines an externally observable lifecycle state.

AgentStateTransition

Bases: StrEnum

State transition vocabulary accepted by durable agent orchestration.

AgentStatus

Bases: StrEnum

Externally observable lifecycle states for an agent execution.

AgentSpanKind

Bases: StrEnum

Stable operation families emitted by AgentRunner.

AgentSpanRecord(name, kind, started_at_ns, ended_at_ns, attributes=dict(), status=AgentSpanStatus.OK, error_code=None) dataclass

Completed span data containing scalar metadata but no prompt payloads.

AgentSpanStatus

Bases: StrEnum

Terminal status of one completed operation record.

AgentTelemetryError

Bases: AbstractSpakkyAgentError

Raised when an injected telemetry adapter cannot record a span.

IAgentTelemetry

Bases: ABC

Optional outbound port receiving completed privacy-safe Agent spans.

record(span) abstractmethod

Record one completed span without changing Agent execution.

Source code in core/spakky-agent/src/spakky/agent/telemetry.py
@abstractmethod
def record(self, span: AgentSpanRecord) -> None:
    """Record one completed span without changing Agent execution."""
    ...

AgentToolCatalog(descriptors=()) dataclass

Deterministic catalog of descriptors discovered from an Agent class.

__post_init__()

Reject duplicate identity or schema names before model lookup.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject duplicate identity or schema names before model lookup."""
    identity_keys: set[str] = set()
    schema_names: set[str] = set()
    for descriptor in self.descriptors:
        if descriptor.identity.key in identity_keys:
            raise AgentDefinitionError("Agent tool identity must be unique")
        if descriptor.schema.name in schema_names:
            raise AgentDefinitionError("Agent tool schema name must be unique")
        identity_keys.add(descriptor.identity.key)
        schema_names.add(descriptor.schema.name)

by_identity(identity)

Lookup a descriptor by typed identity.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def by_identity(self, identity: AgentToolIdentity) -> AgentToolDescriptor:
    """Lookup a descriptor by typed identity."""
    for descriptor in self.descriptors:
        if descriptor.identity == identity:
            return descriptor
    raise AgentDefinitionError("Agent tool identity is not registered")

by_schema_name(schema_name)

Lookup a descriptor by model-facing schema name.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def by_schema_name(self, schema_name: str) -> AgentToolDescriptor:
    """Lookup a descriptor by model-facing schema name."""
    _require_non_blank(schema_name, "Agent tool schema name")
    for descriptor in self.descriptors:
        if descriptor.schema.name == schema_name:
            return descriptor
    raise AgentDefinitionError("Agent tool schema name is not registered")

AgentToolApprovalContext(prompt=None, action_ref=None, metadata=dict()) dataclass

Invocation-specific approval display and correlation metadata.

__post_init__()

Reject blank override strings before they enter approval state.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject blank override strings before they enter approval state."""
    if self.prompt is not None:
        _require_non_blank(self.prompt, "Agent tool approval prompt")
    if self.action_ref is not None:
        _require_non_blank(self.action_ref, "Agent tool approval action ref")

AgentToolBoundInvocation(args=(), kwargs=dict()) dataclass

Python-call-ready tool invocation arguments.

AgentToolDefinition(name, schema_name, description=None, metadata=AgentToolMetadata()) dataclass

Method-level metadata attached by @agent_tool before owner discovery.

__post_init__()

Reject definitions that would make catalog lookup ambiguous.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject definitions that would make catalog lookup ambiguous."""
    _require_non_blank(self.name, "Agent tool name")
    _require_non_blank(self.schema_name, "Agent tool schema name")
    if self.description is not None and not self.description.strip():
        raise AgentDefinitionError("Agent tool description cannot be blank")

AgentToolDescriptor(identity, owner, callable, schema, description=None, metadata=AgentToolMetadata()) dataclass

Discovered tool descriptor bound to an owner class and callable.

name property

Return the descriptor-local tool name.

bind_invocation(payload)

Bind a decoded model payload before the tool callable is invoked.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def bind_invocation(self, payload: JsonObject) -> "AgentToolBoundInvocation":
    """Bind a decoded model payload before the tool callable is invoked."""
    return bind_agent_tool_invocation(self.callable, payload)

approval_context(payload)

Return invocation-specific approval context for this payload.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def approval_context(self, payload: JsonObject) -> AgentToolApprovalContext:
    """Return invocation-specific approval context for this payload."""
    _ = payload
    return AgentToolApprovalContext()

AgentToolIdentity(owner_module, owner_qualname, name) dataclass

Descriptor identity independent from free-form model output text.

key property

Return a stable key for maps, logs, and evidence metadata.

__post_init__()

Reject identity parts that cannot be serialized or matched.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject identity parts that cannot be serialized or matched."""
    _require_non_blank(self.owner_module, "Agent tool owner module")
    _require_non_blank(self.owner_qualname, "Agent tool owner qualname")
    _require_non_blank(self.name, "Agent tool name")

AgentToolMetadata(permissions=(), effects=ToolEffects(), idempotency=Idempotency.UNKNOWN, data_access=DataAccess.NONE, externality=Externality.LOCAL, timeout=TimeoutPolicy(), result_budget=ResultBudget(), evidence=EvidenceCapture.NONE, approval=ToolApprovalRequirement.DERIVED) dataclass

Typed approval, idempotency, and evidence metadata for a descriptor.

risk property

Return derived risk axes without storing risk as source metadata.

resume property

Return resume metadata derived from stored idempotency.

requires_approval_candidate property

Return whether this tool is a HITL approval candidate.

AgentToolRuntimeContext(state_id, conversation_id, call_id, tool_name) dataclass

Runtime correlation data injected into framework-owned tool callables.

__post_init__()

Reject runtime context that cannot link events and evidence.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject runtime context that cannot link events and evidence."""
    _require_non_blank(self.state_id, "Agent tool runtime state id")
    _require_non_blank(self.conversation_id, "Agent tool runtime conversation id")
    _require_non_blank(self.call_id, "Agent tool runtime call id")
    _require_non_blank(self.tool_name, "Agent tool runtime tool name")

AgentToolSchemaHandle(name, input_schema_name, output_schema_name, input_schema=dict(), output_schema=dict(), input_sensitive_fields=(), output_sensitive_fields=()) dataclass

Stable schema names and generated JSON schemas owned by a descriptor.

__post_init__()

Reject blank schema handles.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject blank schema handles."""
    _require_non_blank(self.name, "Agent tool schema name")
    _require_non_blank(self.input_schema_name, "Agent tool input schema name")
    _require_non_blank(self.output_schema_name, "Agent tool output schema name")

input_schema_for(policy=None)

Return model-facing input schema under the requested exposure policy.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def input_schema_for(
    self,
    policy: ContextExposurePolicy | None = None,
) -> JsonObject:
    """Return model-facing input schema under the requested exposure policy."""
    return schema_with_sensitive_metadata(
        self.input_schema,
        self.input_sensitive_fields,
        policy or ContextExposurePolicy(),
    )

output_schema_for(policy=None)

Return model-facing output schema under the requested exposure policy.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def output_schema_for(
    self,
    policy: ContextExposurePolicy | None = None,
) -> JsonObject:
    """Return model-facing output schema under the requested exposure policy."""
    return schema_with_sensitive_metadata(
        self.output_schema,
        self.output_sensitive_fields,
        policy or ContextExposurePolicy(),
    )

DataAccess

Bases: StrEnum

Data access level declared by a tool.

EvidenceCapture

Bases: StrEnum

Evidence capture strategy for tool results.

Externality

Bases: StrEnum

External side-effect boundary declared by a tool.

IAgentToolProvider

Bases: ABC

Injected component contributing a deterministic agent tool catalog.

tool_catalog abstractmethod property

Return tools contributed by this component.

Idempotency

Bases: StrEnum

Action idempotency declared by a tool.

ResultBudget(max_bytes=None) dataclass

Optional result-size budget for model-facing tool output.

__post_init__()

Reject result budgets that cannot constrain output.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject result budgets that cannot constrain output."""
    if self.max_bytes is not None and self.max_bytes <= 0:
        raise AgentDefinitionError("Agent tool result budget must be positive")

TimeoutPolicy(seconds=None) dataclass

Optional timeout boundary for a tool invocation.

__post_init__()

Reject non-positive timeout policies at definition time.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject non-positive timeout policies at definition time."""
    if self.seconds is not None and self.seconds <= 0:
        raise AgentDefinitionError("Agent tool timeout must be positive")

ToolApprovalRequirement

Bases: StrEnum

Human approval requirement at the tool boundary.

ToolEffects(data_access=DataAccess.NONE, externality=Externality.LOCAL, destructive=False, network=False) dataclass

Typed effect metadata used to derive display risk outside core.

read_only() classmethod

Declare a local read-only tool.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def read_only(cls) -> "ToolEffects":
    """Declare a local read-only tool."""
    return cls(data_access=DataAccess.READ, externality=Externality.LOCAL)

write_state() classmethod

Declare a local state-writing tool.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def write_state(cls) -> "ToolEffects":
    """Declare a local state-writing tool."""
    return cls(data_access=DataAccess.WRITE, externality=Externality.LOCAL)

external_side_effect() classmethod

Declare a tool that crosses an external side-effect boundary.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def external_side_effect(cls) -> "ToolEffects":
    """Declare a tool that crosses an external side-effect boundary."""
    return cls(
        data_access=DataAccess.READ_WRITE,
        externality=Externality.EXTERNAL,
        network=True,
    )

destructive_action() classmethod

Declare a tool that may irreversibly mutate local or external state.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def destructive_action(cls) -> "ToolEffects":
    """Declare a tool that may irreversibly mutate local or external state."""
    return cls(
        data_access=DataAccess.WRITE,
        externality=Externality.EXTERNAL,
        destructive=True,
    )

ToolPermission(name) dataclass

Typed permission marker attached to a tool descriptor.

__post_init__()

Reject permission names that cannot be matched deterministically.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject permission names that cannot be matched deterministically."""
    if not self.name.strip():
        raise AgentDefinitionError("Agent tool permission name cannot be blank")

ToolResumeAction

Bases: StrEnum

Resume action allowed by stored tool idempotency metadata.

ToolResumeMetadata(idempotency=Idempotency.UNKNOWN) dataclass

Stored idempotency metadata used when resuming an incomplete action.

from_metadata(metadata) classmethod

Build resume metadata from a tool descriptor metadata object.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def from_metadata(cls, metadata: "AgentToolMetadata") -> "ToolResumeMetadata":
    """Build resume metadata from a tool descriptor metadata object."""
    return cls(idempotency=metadata.idempotency)

action_for_completed_boundary()

Return the resume action for an already completed action boundary.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def action_for_completed_boundary(self) -> ToolResumeAction:
    """Return the resume action for an already completed action boundary."""
    return ToolResumeAction.SKIP_COMPLETED

action_for_incomplete_boundary()

Return the resume action for an incomplete action boundary.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def action_for_incomplete_boundary(self) -> ToolResumeAction:
    """Return the resume action for an incomplete action boundary."""
    if self.idempotency in (
        Idempotency.IDEMPOTENT,
        Idempotency.CONDITIONALLY_IDEMPOTENT,
    ):
        return ToolResumeAction.RETRY
    return ToolResumeAction.REQUIRE_APPROVAL

ToolRisk(axes=()) dataclass

Derived typed risk axes for policy and evidence annotations.

requires_approval_candidate property

Return whether the risk is strong enough to suggest HITL approval.

__post_init__()

Reject duplicate axes so risk comparisons stay deterministic.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject duplicate axes so risk comparisons stay deterministic."""
    seen: set[ToolRiskAxis] = set()
    for axis in self.axes:
        if axis in seen:
            raise AgentDefinitionError("Agent tool risk axes must be unique")
        seen.add(axis)

from_metadata(metadata) classmethod

Derive risk axes from source tool metadata.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def from_metadata(cls, metadata: AgentToolMetadata) -> "ToolRisk":
    """Derive risk axes from source tool metadata."""
    axes: list[ToolRiskAxis] = []
    if metadata.data_access in (DataAccess.READ, DataAccess.READ_WRITE):
        axes.append(ToolRiskAxis.READ)
    if metadata.data_access in (DataAccess.WRITE, DataAccess.READ_WRITE):
        axes.append(ToolRiskAxis.WRITE)
    if metadata.data_access in (DataAccess.WRITE, DataAccess.READ_WRITE):
        axes.append(ToolRiskAxis.SIDE_EFFECT)
    if metadata.externality in (Externality.EXTERNAL, Externality.UNKNOWN):
        axes.append(ToolRiskAxis.SIDE_EFFECT)
    if metadata.effects.destructive:
        axes.append(ToolRiskAxis.DESTRUCTIVE)
    if metadata.effects.network or metadata.externality == Externality.EXTERNAL:
        axes.append(ToolRiskAxis.NETWORK)
    return cls(axes=_deduplicate_axes(axes))

includes(axis)

Return whether this risk contains the requested axis.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def includes(self, axis: ToolRiskAxis) -> bool:
    """Return whether this risk contains the requested axis."""
    return axis in self.axes

ToolRiskAxis

Bases: StrEnum

Derived risk axes exposed for policy and UI decisions.

AgentYield(kind, payload) dataclass

Typed stream item returned from an agent execute generator.

AgentYieldKind

Bases: StrEnum

Canonical public vocabulary yielded by agent execution.

Approval(id, prompt, allowed_decisions, metadata) dataclass

Approval request surfaced to the inbound adapter.

Cancel(reason=None, requested_by=None, metadata=dict()) dataclass

Cancellation acknowledgement surfaced to the caller.

Error(code, message, retryable=False, metadata=dict()) dataclass

Recoverable or terminal execution error surfaced to the caller.

Evidence(evidence, metadata=dict()) dataclass

Evidence item surfaced to the inbound adapter.

Final(output, metadata) dataclass

Final output carried by a generator stream.

Progress(message, current_step=None, metadata=dict()) dataclass

Agent progress update intended for direct inbound adapter consumption.

Token(text, metadata=dict()) dataclass

Incremental model token intended for streaming clients.

Tool(name, call_id=None, arguments=dict(), result=None, metadata=dict()) dataclass

Tool call or tool result surfaced by agent execution.

begin_agent_cancellation(state, signal)

Materialize receipt of a CANCEL signal as CANCELLING state.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def begin_agent_cancellation(
    state: AgentState,
    signal: AgentSignal,
) -> AgentState:
    """Materialize receipt of a CANCEL signal as CANCELLING state."""
    _require_cancel_signal(signal)
    _require_signal_matches_state(state, signal)
    return replace(
        state,
        status=AgentStatus.CANCELLING,
        transition=AgentStateTransition.CANCELLING,
        reason=AgentStateReason.CANCELLATION_REQUESTED,
        metadata={
            **state.metadata,
            "cancellation_signal_id": signal.id,
            "cancellation_reason": _optional_string(signal.payload, "reason"),
            "cancellation_requested_by": _optional_string(
                signal.payload,
                "requested_by",
            ),
        },
    )

complete_agent_cancellation(state, report)

Resolve CANCELLING state into CANCELLED or FAILED cleanup outcome.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def complete_agent_cancellation(
    state: AgentState,
    report: AgentCancellationCleanupReport,
) -> AgentState:
    """Resolve CANCELLING state into CANCELLED or FAILED cleanup outcome."""
    if state.id != report.state_id:
        raise AgentDefinitionError("Agent cancellation report state id mismatch")
    metadata = {**state.metadata, "cancellation_cleanup": report.to_payload()}
    if report.cleanup_succeeded:
        return replace(
            state,
            status=AgentStatus.CANCELLED,
            transition=AgentStateTransition.CANCELLED,
            reason=AgentStateReason.CANCELLATION_REQUESTED,
            metadata=metadata,
        )
    return replace(
        state,
        status=AgentStatus.FAILED,
        transition=AgentStateTransition.FAILED,
        reason=AgentStateReason.CANCELLATION_CLEANUP_FAILED,
        metadata=metadata,
    )

run_agent_cancellation_cleanup(*, state, signal, tasks) async

Invoke model stream/tool/delegate cleanup hooks for a CANCEL signal.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
async def run_agent_cancellation_cleanup(
    *,
    state: AgentState,
    signal: AgentSignal,
    tasks: Sequence[AgentCancellationCleanupTask],
) -> AgentCancellationCleanupReport:
    """Invoke model stream/tool/delegate cleanup hooks for a CANCEL signal."""
    _require_cancel_signal(signal)
    outcomes: list[AgentCancellationCleanupResult] = []
    for task in tasks:
        outcomes.append(await task.run(state=state, signal=signal))
    return AgentCancellationCleanupReport(
        state_id=state.id,
        signal_id=signal.id,
        outcomes=tuple(outcomes),
    )

materialize_agent_approval_decision_state(current, outcome)

Apply a typed approval decision outcome to an existing state snapshot.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def materialize_agent_approval_decision_state(
    current: AgentState,
    outcome: AgentApprovalDecisionOutcome,
) -> AgentState:
    """Apply a typed approval decision outcome to an existing state snapshot."""
    return AgentState(
        id=current.id,
        agent_type=current.agent_type,
        status=outcome.status,
        transition=outcome.transition,
        reason=outcome.reason,
        current_activity=_activity_for_decision(outcome),
        input_ref=current.input_ref,
        output_ref=current.output_ref,
        pending_signal_count=current.pending_signal_count,
        last_event_cursor=current.last_event_cursor,
        recovery_marker=current.recovery_marker,
        metadata={
            **current.metadata,
            "approval_decision": {
                "request_id": outcome.request_id,
                "decision": outcome.decision.value,
                "modified_payload": outcome.modified_payload,
                "comment": outcome.comment,
            },
        },
        created_at=current.created_at,
        updated_at=current.updated_at,
    )

parse_agent_approval_decision_signal(signal, *, request=None)

Parse an approval decision signal into a typed workflow outcome.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def parse_agent_approval_decision_signal(
    signal: AgentSignal,
    *,
    request: AgentApprovalRequest | None = None,
) -> AgentApprovalDecisionOutcome:
    """Parse an approval decision signal into a typed workflow outcome."""
    if signal.kind != AgentSignalKind.APPROVAL_DECISION:
        raise AgentDefinitionError(
            "Agent approval signal kind must be approval_decision"
        )

    request_id = _require_payload_text(signal.payload, "request_id")
    if request is not None and request_id != request.id:
        raise AgentDefinitionError("Agent approval signal request id does not match")
    if request is not None and signal.agent_state_id != request.agent_state_id:
        raise AgentDefinitionError("Agent approval signal state id does not match")

    decision = _parse_approval_decision(
        _require_payload_text(signal.payload, "decision")
    )
    modified_payload = _payload_object(signal.payload.get("modified_payload", {}))
    comment = _optional_payload_text(signal.payload, "comment")
    status, transition, reason = _decision_state_target(decision)

    return AgentApprovalDecisionOutcome(
        request_id=request_id,
        decision=decision,
        status=status,
        transition=transition,
        reason=reason,
        modified_payload=modified_payload,
        comment=comment,
    )

plan_agent_tool_approval(*, descriptor, approval_id, agent_state_id, agent_type, prompt=None, action_ref=None, call_id=None, metadata=None)

Plan whether a tool invocation should proceed or wait for approval.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def plan_agent_tool_approval(
    *,
    descriptor: AgentToolDescriptor,
    approval_id: str,
    agent_state_id: str,
    agent_type: str,
    prompt: str | None = None,
    action_ref: str | None = None,
    call_id: str | None = None,
    metadata: JsonObject | None = None,
) -> AgentApprovalPlan:
    """Plan whether a tool invocation should proceed or wait for approval."""
    if not descriptor.metadata.requires_approval_candidate:
        return AgentApprovalPlan(action=AgentApprovalPlanAction.PROCEED)

    request = AgentApprovalRequest.from_tool_descriptor(
        approval_id=approval_id,
        agent_state_id=agent_state_id,
        descriptor=descriptor,
        prompt=prompt,
        action_ref=action_ref,
        call_id=call_id,
        metadata=metadata,
    )
    return AgentApprovalPlan(
        action=AgentApprovalPlanAction.WAIT_FOR_APPROVAL,
        request=request,
        state=request.to_state(agent_type=agent_type),
        yield_item=request.to_yield(),
    )

plan_agent_resume(state, evidence, signals=())

Restore the next resume action using only persisted state and evidence.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
def plan_agent_resume(
    state: AgentState,
    evidence: Sequence[AgentEvidence],
    signals: Sequence[AgentSignal] = (),
) -> AgentResumePlan:
    """Restore the next resume action using only persisted state and evidence."""
    persisted_signals = tuple(signals)
    if state.status in (
        AgentStatus.COMPLETED,
        AgentStatus.FAILED,
        AgentStatus.CANCELLED,
    ):
        return AgentResumePlan(
            state=state,
            action=AgentResumeAction.NOT_RESUMABLE,
            signals=persisted_signals,
        )

    boundary = _last_action_boundary(evidence)
    if boundary is None:
        return AgentResumePlan(
            state=state,
            action=AgentResumeAction.START,
            signals=persisted_signals,
        )

    if boundary.stage is AgentActionBoundaryStage.AFTER:
        return AgentResumePlan(
            state=replace(state, recovery_marker=boundary.action_id),
            action=AgentResumeAction.SKIP_COMPLETED,
            boundary=boundary,
            signals=persisted_signals,
        )

    if boundary.action_kind is AgentActionKind.APPROVAL_WAIT:
        return AgentResumePlan(
            state=_interrupt_for_human_recovery(state, boundary),
            action=AgentResumeAction.REQUIRE_HITL,
            boundary=boundary,
            signals=persisted_signals,
        )

    resume_action = ToolResumeMetadata(
        idempotency=boundary.idempotency,
    ).action_for_incomplete_boundary()
    if resume_action is ToolResumeAction.RETRY:
        return AgentResumePlan(
            state=replace(state, recovery_marker=boundary.action_id),
            action=AgentResumeAction.RETRY,
            boundary=boundary,
            signals=persisted_signals,
        )
    return AgentResumePlan(
        state=_interrupt_for_human_recovery(state, boundary),
        action=AgentResumeAction.REQUIRE_HITL,
        boundary=boundary,
        signals=persisted_signals,
    )

discover_agent_signal_hooks(owner)

Discover @on_signal methods in deterministic class-definition order.

Source code in core/spakky-agent/src/spakky/agent/hooks.py
def discover_agent_signal_hooks(owner: type[object]) -> AgentSignalHookCatalog:
    """Discover ``@on_signal`` methods in deterministic class-definition order."""
    descriptors: list[AgentSignalHookDescriptor] = []
    resolved_member_names: set[str] = set()
    for declaring_owner in owner.__mro__:
        if declaring_owner is object:
            continue
        for member_name, member in vars(declaring_owner).items():
            if member_name in resolved_member_names:
                continue
            resolved_member_names.add(member_name)
            if not isinstance(member, FunctionType):
                continue
            definition = _get_signal_hook_definition(member)
            if definition is None:
                continue
            _validate_hook_contract(member)
            descriptors.append(
                AgentSignalHookDescriptor(
                    identity=AgentSignalHookIdentity(
                        owner_module=declaring_owner.__module__,
                        owner_qualname=declaring_owner.__qualname__,
                        member_name=member_name,
                    ),
                    owner=declaring_owner,
                    callable=member,
                    kind=definition.kind,
                ),
            )
    ordered = tuple(
        sorted(descriptors, key=lambda descriptor: descriptor.identity.key),
    )
    return AgentSignalHookCatalog(descriptors=ordered)

on_signal(kind)

Declare a method that reacts to one inbound signal kind.

The decorated method must be an async generator yielding AgentYield items and accepting exactly one signal: AgentSignal argument besides self. The runner invokes it when it consumes a signal of kind at a poll point, and forwards every yielded item into the public stream.

Source code in core/spakky-agent/src/spakky/agent/hooks.py
def on_signal(kind: AgentSignalKind) -> Callable[[FunctionType], FunctionType]:
    """Declare a method that reacts to one inbound signal kind.

    The decorated method must be an async generator yielding ``AgentYield``
    items and accepting exactly one ``signal: AgentSignal`` argument besides
    ``self``. The runner invokes it when it consumes a signal of ``kind`` at a
    poll point, and forwards every yielded item into the public stream.
    """

    def decorate(function: FunctionType) -> FunctionType:
        function.__dict__[AGENT_SIGNAL_HOOK_DEFINITION_KEY] = AgentSignalHookDefinition(
            kind=kind,
        )
        return function

    return decorate

consume_pending_agent_signals(repository, state_id, *, poll_point=AgentSignalPollPoint.SAFE_BOUNDARY, accepted_signals=None, max_signals=None)

Consume currently pending signals without sleeping or waiting for new input.

The repository remains responsible for durable queue ordering. This helper consumes only the eligible prefix of the pending queue so later signals never overtake an earlier unaccepted signal.

Source code in core/spakky-agent/src/spakky/agent/signal_consumption.py
def consume_pending_agent_signals(
    repository: IAgentSignalRepository,
    state_id: str,
    *,
    poll_point: AgentSignalPollPoint = AgentSignalPollPoint.SAFE_BOUNDARY,
    accepted_signals: Sequence[AgentSignalKind] | None = None,
    max_signals: int | None = None,
) -> AgentSignalConsumptionBatch:
    """Consume currently pending signals without sleeping or waiting for new input.

    The repository remains responsible for durable queue ordering. This helper
    consumes only the eligible prefix of the pending queue so later signals never
    overtake an earlier unaccepted signal.
    """
    if not state_id.strip():
        raise AgentDefinitionError("Agent signal state id cannot be blank")
    if max_signals is not None and max_signals <= 0:
        raise AgentDefinitionError("Agent signal max_signals must be positive")

    accepted = frozenset(accepted_signals) if accepted_signals is not None else None
    pending = tuple(repository.list_pending(state_id))
    selected = _select_consumable_prefix(
        pending,
        accepted_signals=accepted,
        max_signals=max_signals,
    )
    consumed = tuple(repository.mark_consumed(signal.id) for signal in selected)

    return AgentSignalConsumptionBatch(
        state_id=state_id,
        poll_point=poll_point,
        signals=consumed,
    )

agent_tool(*, name=None, schema_name=None, description=None, permissions=(), effects=None, idempotency=Idempotency.UNKNOWN, data_access=None, externality=None, timeout=None, result_budget=None, evidence=EvidenceCapture.NONE, approval=ToolApprovalRequirement.DERIVED)

Attach typed agent-tool metadata to a method object.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def agent_tool(
    *,
    name: str | None = None,
    schema_name: str | None = None,
    description: str | None = None,
    permissions: Sequence[ToolPermission] = (),
    effects: ToolEffects | None = None,
    idempotency: Idempotency = Idempotency.UNKNOWN,
    data_access: DataAccess | None = None,
    externality: Externality | None = None,
    timeout: TimeoutPolicy | None = None,
    result_budget: ResultBudget | None = None,
    evidence: EvidenceCapture = EvidenceCapture.NONE,
    approval: ToolApprovalRequirement = ToolApprovalRequirement.DERIVED,
) -> Callable[[FunctionType], FunctionType]:
    """Attach typed agent-tool metadata to a method object."""

    def decorate(function: FunctionType) -> FunctionType:
        tool_name = _normalize_name(name, function.__name__, "Agent tool name")
        normalized_schema_name = _normalize_name(
            schema_name,
            tool_name,
            "Agent tool schema name",
        )
        tool_effects = effects or ToolEffects()
        metadata = AgentToolMetadata(
            permissions=tuple(permissions),
            effects=tool_effects,
            idempotency=idempotency,
            data_access=data_access or tool_effects.data_access,
            externality=externality or tool_effects.externality,
            timeout=timeout or TimeoutPolicy(),
            result_budget=result_budget or ResultBudget(),
            evidence=evidence,
            approval=approval,
        )
        definition = AgentToolDefinition(
            name=tool_name,
            schema_name=normalized_schema_name,
            description=description,
            metadata=metadata,
        )
        function.__dict__[AGENT_TOOL_DEFINITION_KEY] = definition
        return function

    return decorate

bind_agent_tool_invocation(function, payload)

Bind a structured model payload to a tool function signature.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def bind_agent_tool_invocation(
    function: AgentToolCallable,
    payload: JsonObject,
) -> AgentToolBoundInvocation:
    """Bind a structured model payload to a tool function signature."""
    invocation = _parse_invocation_payload(payload)
    try:
        function_signature = signature(function)
    except (TypeError, ValueError) as e:
        raise AgentToolBindingError(
            "Agent tool callable signature cannot be inspected"
        ) from e
    call_signature = _drop_injected_parameters(function_signature)
    try:
        bound = call_signature.bind(*invocation.args, **invocation.kwargs)
    except TypeError as e:
        raise AgentToolBindingError(
            "Agent tool invocation payload cannot be bound"
        ) from e
    bound.apply_defaults()
    return AgentToolBoundInvocation(
        args=tuple(bound.args),
        kwargs=dict(bound.kwargs),
    )

discover_agent_tools(owner)

Discover @agent_tool methods in deterministic class-definition order.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def discover_agent_tools(owner: type[object]) -> AgentToolCatalog:
    """Discover @agent_tool methods in deterministic class-definition order."""
    descriptors: list[AgentToolDescriptor] = []
    resolved_member_names: set[str] = set()
    for declaring_owner in owner.__mro__:
        if declaring_owner is object:
            continue
        for member_name, member in vars(declaring_owner).items():
            if member_name in resolved_member_names:
                continue
            resolved_member_names.add(member_name)
            function = _unwrap_function(member)
            if function is None:
                continue
            definition = get_agent_tool_definition(function)
            if definition is None:
                continue
            descriptors.append(
                _build_descriptor(declaring_owner, function, definition),
            )
    ordered = tuple(
        sorted(
            descriptors,
            key=lambda descriptor: descriptor.identity.key,
        ),
    )
    return AgentToolCatalog(descriptors=ordered)

Content

Portable immutable multimodal model-content contracts.

DEFAULT_MEDIA_SAFETY_LIMITS = MediaSafetyLimits() module-attribute

Conservative default: HTTPS references and at most 20 MiB inline bytes.

MediaSafetyLimits(max_inline_bytes=20 * _MEBIBYTE, max_media_parts=16, allowed_uri_schemes=frozenset({'https'}), allowed_uri_hosts=None) dataclass

Replaceable vendor-neutral limits applied when media enters the model port.

__post_init__()

Reject unbounded or malformed media limits.

Source code in core/spakky-agent/src/spakky/agent/content.py
def __post_init__(self) -> None:
    """Reject unbounded or malformed media limits."""
    if (
        isinstance(self.max_inline_bytes, bool)
        or not isinstance(self.max_inline_bytes, int)
        or self.max_inline_bytes <= 0
    ):
        raise AgentDefinitionError("Inline media byte limit must be positive")
    if (
        isinstance(self.max_media_parts, bool)
        or not isinstance(self.max_media_parts, int)
        or self.max_media_parts <= 0
    ):
        raise AgentDefinitionError("Media part limit must be positive")
    if (
        not isinstance(self.allowed_uri_schemes, frozenset)
        or not self.allowed_uri_schemes
    ):
        raise AgentDefinitionError("Media URI schemes must be a nonempty frozenset")
    for scheme in self.allowed_uri_schemes:
        if (
            not isinstance(scheme, str)
            or fullmatch(_SCHEME_PATTERN, scheme) is None
            or scheme in _FORBIDDEN_URI_SCHEMES
        ):
            raise AgentDefinitionError("Media URI scheme is invalid")
    if self.allowed_uri_hosts is not None:
        if (
            not isinstance(self.allowed_uri_hosts, frozenset)
            or not self.allowed_uri_hosts
        ):
            raise AgentDefinitionError(
                "Media URI hosts must be a nonempty frozenset"
            )
        for host in self.allowed_uri_hosts:
            if (
                not isinstance(host, str)
                or host == ""
                or host != host.rstrip(".").casefold()
                or any(character.isspace() for character in host)
                or any(character in host for character in "/@?#")
            ):
                raise AgentDefinitionError("Media URI host authority is invalid")

TextPart(text) dataclass

One ordered text segment inside a multimodal model message.

ImagePart(media_type, uri=None, data=None, source=None, content_digest=None, _limits=DEFAULT_MEDIA_SAFETY_LIMITS) dataclass

Bases: _MediaPart

Portable image input from a remote URI or bounded inline bytes.

AudioPart(media_type, uri=None, data=None, source=None, content_digest=None, _limits=DEFAULT_MEDIA_SAFETY_LIMITS) dataclass

Bases: _MediaPart

Portable audio input from a remote URI or bounded inline bytes.

VideoPart(media_type, uri=None, data=None, source=None, content_digest=None, _limits=DEFAULT_MEDIA_SAFETY_LIMITS) dataclass

Bases: _MediaPart

Portable video input where a selected provider supports it.

DocumentPart(media_type, uri=None, data=None, source=None, content_digest=None, _limits=DEFAULT_MEDIA_SAFETY_LIMITS, filename=None) dataclass

Bases: _MediaPart

Portable application/text document input with explicit MIME provenance.

from_uri(uri, *, media_type, filename=None, source=None, content_digest=None, limits=DEFAULT_MEDIA_SAFETY_LIMITS) classmethod

Create a remote document with optional provider-facing filename.

Source code in core/spakky-agent/src/spakky/agent/content.py
@classmethod
@override
def from_uri(
    cls,
    uri: str,
    *,
    media_type: str,
    filename: str | None = None,
    source: str | None = None,
    content_digest: str | None = None,
    limits: MediaSafetyLimits = DEFAULT_MEDIA_SAFETY_LIMITS,
) -> Self:
    """Create a remote document with optional provider-facing filename."""
    return cls(
        media_type=media_type,
        uri=uri,
        filename=filename,
        source=source,
        content_digest=content_digest,
        _limits=limits,
    )

from_bytes(data, *, media_type, filename=None, source=None, content_digest=None, limits=DEFAULT_MEDIA_SAFETY_LIMITS) classmethod

Create an inline document with optional provider-facing filename.

Source code in core/spakky-agent/src/spakky/agent/content.py
@classmethod
@override
def from_bytes(
    cls,
    data: bytes,
    *,
    media_type: str,
    filename: str | None = None,
    source: str | None = None,
    content_digest: str | None = None,
    limits: MediaSafetyLimits = DEFAULT_MEDIA_SAFETY_LIMITS,
) -> Self:
    """Create an inline document with optional provider-facing filename."""
    return cls(
        media_type=media_type,
        data=data,
        filename=filename,
        source=source,
        content_digest=content_digest,
        _limits=limits,
    )

model_content_parts(content)

Normalize legacy text or an already snapshotted sequence to ordered parts.

Source code in core/spakky-agent/src/spakky/agent/content.py
def model_content_parts(content: ModelContent) -> tuple[ModelContentPart, ...]:
    """Normalize legacy text or an already snapshotted sequence to ordered parts."""
    if isinstance(content, str):
        return (TextPart(content),)
    if not isinstance(content, Sequence) or isinstance(content, bytes | bytearray):
        raise AgentDefinitionError(
            "Model message content must be text or content parts"
        )
    parts = tuple(content)
    if not parts or any(not isinstance(part, _CONTENT_PART_TYPES) for part in parts):
        raise AgentDefinitionError("Model message content parts are invalid")
    _validate_media_budget(parts)
    return parts

validate_model_content_budget(contents)

Enforce one aggregate media budget across a complete model request.

Source code in core/spakky-agent/src/spakky/agent/content.py
def validate_model_content_budget(contents: Sequence[ModelContent]) -> None:
    """Enforce one aggregate media budget across a complete model request."""
    parts = tuple(part for content in contents for part in model_content_parts(content))
    _validate_media_budget(parts)

model_content_text(content)

Return only ordered textual segments without inventing media descriptions.

Source code in core/spakky-agent/src/spakky/agent/content.py
def model_content_text(content: ModelContent) -> str:
    """Return only ordered textual segments without inventing media descriptions."""
    if isinstance(content, str):
        return content
    return "".join(
        part.text for part in model_content_parts(content) if isinstance(part, TextPart)
    )

model_content_size(content)

Return UTF-8 text plus known inline media bytes; remote size is unknown.

Source code in core/spakky-agent/src/spakky/agent/content.py
def model_content_size(content: ModelContent) -> int:
    """Return UTF-8 text plus known inline media bytes; remote size is unknown."""
    if isinstance(content, str):
        return len(content.encode("utf-8"))
    size = 0
    for part in model_content_parts(content):
        if isinstance(part, TextPart):
            size += len(part.text.encode("utf-8"))
        elif part.size is not None:
            size += part.size
    return size

serialize_model_content(content)

Serialize model content to a deterministic JSON-safe checkpoint shape.

Source code in core/spakky-agent/src/spakky/agent/content.py
def serialize_model_content(content: ModelContent) -> JsonValue:
    """Serialize model content to a deterministic JSON-safe checkpoint shape."""
    if isinstance(content, str):
        return content
    serialized: list[JsonObject] = []
    for part in model_content_parts(content):
        if isinstance(part, TextPart):
            serialized.append({"type": "text", "text": part.text})
            continue
        item: dict[str, JsonValue] = {
            "type": part._KIND,
            "media_type": part.media_type,
            "limits": {
                "max_inline_bytes": part._limits.max_inline_bytes,
                "max_media_parts": part._limits.max_media_parts,
                "allowed_uri_schemes": tuple(sorted(part._limits.allowed_uri_schemes)),
                "allowed_uri_hosts": (
                    None
                    if part._limits.allowed_uri_hosts is None
                    else tuple(sorted(part._limits.allowed_uri_hosts))
                ),
            },
        }
        if part.uri is not None:
            item["uri"] = part.uri
        else:
            if part.data is None:
                raise AgentDefinitionError("Inline model media bytes are missing")
            item["data"] = b64encode(part.data).decode("ascii")
        if part.source is not None:
            item["source"] = part.source
        if part.content_digest is not None:
            item["content_digest"] = part.content_digest
        if isinstance(part, DocumentPart) and part.filename is not None:
            item["filename"] = part.filename
        serialized.append(item)
    return tuple(serialized)

restore_model_content(value)

Restore trusted types from an untrusted JSON checkpoint boundary.

Source code in core/spakky-agent/src/spakky/agent/content.py
def restore_model_content(value: object) -> str | tuple[ModelContentPart, ...]:
    """Restore trusted types from an untrusted JSON checkpoint boundary."""
    if isinstance(value, str):
        return value
    if not isinstance(value, Sequence) or isinstance(value, bytes | bytearray):
        raise AgentDefinitionError("Serialized model content must be text or an array")
    restored: list[ModelContentPart] = []
    for item in value:
        if not isinstance(item, Mapping):
            raise AgentDefinitionError(
                "Serialized model content part must be an object"
            )
        kind = item.get("type")
        if kind == "text":
            if set(item) != {"type", "text"} or not isinstance(item.get("text"), str):
                raise AgentDefinitionError("Serialized text content part is invalid")
            restored.append(TextPart(item["text"]))
            continue
        media_class = _media_class(kind)
        allowed_keys = {
            "type",
            "media_type",
            "uri",
            "data",
            "source",
            "content_digest",
            "filename",
            "limits",
        }
        if not set(item) <= allowed_keys:
            raise AgentDefinitionError(
                "Serialized media content part has unknown fields"
            )
        media_type = item.get("media_type")
        source = item.get("source")
        content_digest = item.get("content_digest")
        filename = item.get("filename")
        raw_limits = item.get("limits")
        if not isinstance(media_type, str):
            raise AgentDefinitionError("Serialized media MIME type is invalid")
        if source is not None and not isinstance(source, str):
            raise AgentDefinitionError("Serialized media source provenance is invalid")
        if content_digest is not None and not isinstance(content_digest, str):
            raise AgentDefinitionError("Serialized media digest provenance is invalid")
        if filename is not None and not isinstance(filename, str):
            raise AgentDefinitionError("Serialized document filename is invalid")
        if media_class is not DocumentPart and filename is not None:
            raise AgentDefinitionError("Serialized filename requires document content")
        limits = _restore_limits(raw_limits)
        uri = item.get("uri")
        encoded = item.get("data")
        if uri is not None:
            if not isinstance(uri, str) or encoded is not None:
                raise AgentDefinitionError("Serialized media source is ambiguous")
            if media_class is DocumentPart:
                restored.append(
                    DocumentPart.from_uri(
                        uri,
                        media_type=media_type,
                        filename=filename,
                        source=source,
                        content_digest=content_digest,
                        limits=limits,
                    )
                )
            else:
                restored.append(
                    media_class.from_uri(
                        uri,
                        media_type=media_type,
                        source=source,
                        content_digest=content_digest,
                        limits=limits,
                    )
                )
            continue
        if not isinstance(encoded, str):
            raise AgentDefinitionError("Serialized inline media data is invalid")
        max_encoded_size = ((limits.max_inline_bytes + 2) // 3) * 4
        if len(encoded) > max_encoded_size:
            raise AgentDefinitionError(
                "Serialized inline media exceeds its encoded byte limit"
            )
        try:
            data = b64decode(encoded, validate=True)
        except (Base64Error, ValueError) as error:
            raise AgentDefinitionError(
                "Serialized inline media base64 is invalid"
            ) from error
        if media_class is DocumentPart:
            restored.append(
                DocumentPart.from_bytes(
                    data,
                    media_type=media_type,
                    filename=filename,
                    source=source,
                    content_digest=content_digest,
                    limits=limits,
                )
            )
        else:
            restored.append(
                media_class.from_bytes(
                    data,
                    media_type=media_type,
                    source=source,
                    content_digest=content_digest,
                    limits=limits,
                )
            )
    return tuple(model_content_parts(tuple(restored)))

실행

Agent execution metadata contracts.

REMOTE_AGENT_CARD_SCHEMES = ('http', 'https') module-attribute

URL schemes accepted for a remote teammate's AgentCard endpoint.

RecoveryStrategy

Bases: StrEnum

Recovery strategy requested by an agent execution contract.

StreamingExposureMode

Bases: StrEnum

Streaming output guard profile exposed by agent execution.

AgentExecutionLimits(max_steps=None, max_tool_calls=None, max_tokens=None, max_cost=None, timeout_seconds=None) dataclass

Optional execution limits; None leaves the corresponding budget unset.

__post_init__()

Reject limits that would fail later at bootstrap.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def __post_init__(self) -> None:
    """Reject limits that would fail later at bootstrap."""
    if self.max_steps is not None and self.max_steps <= 0:
        raise AgentDefinitionError("Agent model-step limit must be positive")
    if self.max_tool_calls is not None and self.max_tool_calls <= 0:
        raise AgentDefinitionError("Agent tool-call limit must be positive")
    if self.max_tokens is not None and self.max_tokens <= 0:
        raise AgentDefinitionError("Agent token limit must be positive")
    if self.max_cost is not None and (
        not isinstance(self.max_cost, Decimal)
        or not self.max_cost.is_finite()
        or self.max_cost <= 0
    ):
        raise AgentDefinitionError("Agent cost limit must be a positive Decimal")
    if self.timeout_seconds is not None and self.timeout_seconds <= 0:
        raise AgentDefinitionError("Agent timeout limit must be positive")

AgentTeammate(name, pod=None, card_url=None) dataclass

Declared collaborator an agent may delegate to during execution.

A teammate is resolved either in-process by a local @Agent Pod type or remotely by an AgentCard endpoint URL. Exactly one binding is declared; the runtime exposes it as a synthetic teammate delegation tool and dispatches it through the local runner or an injected IAgentDelegate port.

__post_init__()

Reject teammates that cannot resolve to a single delegate target.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def __post_init__(self) -> None:
    """Reject teammates that cannot resolve to a single delegate target."""
    if not self.name.strip():
        raise AgentDefinitionError("Agent teammate name cannot be blank")
    if (self.pod is None) == (self.card_url is None):
        raise AgentDefinitionError(
            "Agent teammate must declare exactly one of a local pod "
            "or a remote AgentCard url"
        )
    if self.pod is not None and not isclass(self.pod):
        raise AgentDefinitionError("Agent teammate pod must be a class")
    if self.card_url is not None:
        parts = urlsplit(self.card_url)
        if parts.scheme not in REMOTE_AGENT_CARD_SCHEMES or not parts.netloc:
            raise AgentDefinitionError(
                "Agent teammate AgentCard url must be an http(s) endpoint"
            )

AgentCompactionPolicy(strategies, trigger_token_threshold) dataclass

Declared compaction chain plus the token threshold that triggers it.

The strategies form an ordered chain of pluggable ICompactionStrategy ports applied in sequence once the running token estimate crosses trigger_token_threshold. The runner threads each strategy's output into the next, so chain order is the compaction order (ADR-0013 §7).

__post_init__()

Reject compaction policies that cannot be enforced consistently.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def __post_init__(self) -> None:
    """Reject compaction policies that cannot be enforced consistently."""
    if not self.strategies:
        raise AgentDefinitionError(
            "Agent compaction policy requires at least one strategy"
        )
    if self.trigger_token_threshold <= 0:
        raise AgentDefinitionError(
            "Agent compaction trigger token threshold must be positive"
        )

AgentExecutionSpec(name=None, objective=None, instructions=None, output_type=None, accepted_signals=(), recovery=RecoveryStrategy.NONE, streaming_exposure_mode=StreamingExposureMode.BALANCED, limits=AgentExecutionLimits(), teammates=(), compaction=None, refresh_context_each_step=False, delegation_allowed=False, metadata=dict(), sampling=(lambda: SamplingOptions(temperature=0.0))()) dataclass

Declarative execution semantics that cannot be inferred from DI alone.

__post_init__()

Reject execution specs that would fail later at bootstrap.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def __post_init__(self) -> None:
    """Reject execution specs that would fail later at bootstrap."""
    if self.name is not None and not self.name.strip():
        raise AgentDefinitionError("Agent name cannot be blank")
    if self.objective is not None and not self.objective.strip():
        raise AgentDefinitionError("Agent objective cannot be blank")
    if self.instructions is not None and not self.instructions.strip():
        raise AgentDefinitionError("Agent instructions cannot be blank")
    if self.output_type is not None and not isclass(self.output_type):
        raise AgentDefinitionError("Agent output type must be a class")
    if self.output_type is not None:
        _structured_output_contract(self.output_type)
    teammate_names = [teammate.name for teammate in self.teammates]
    if len(set(teammate_names)) != len(teammate_names):
        raise AgentDefinitionError("Agent teammate names must be unique")

Agent(spec=AgentExecutionSpec(), *, name='', scope=Scope.SINGLETON) dataclass

Bases: Pod

UseCase-equivalent Pod stereotype for agentic workflow components.

validate_bootstrap()

Re-run definition validation during application bootstrap.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def validate_bootstrap(self) -> None:
    """Re-run definition validation during application bootstrap."""
    self._validate_execute_contract(self._ensure_agent_class(self.target))

required_persistence_repository_types()

Return repository ports required by this Agent's durable path.

Source code in core/spakky-agent/src/spakky/agent/execution.py
def required_persistence_repository_types(self) -> tuple[type[object], ...]:
    """Return repository ports required by this Agent's durable path."""
    from spakky.agent.interfaces.repository import (
        IAgentEvidenceRepository,
        IAgentSignalRepository,
        IAgentStateRepository,
    )

    if (
        self.spec.recovery is RecoveryStrategy.ACTION_BOUNDARY
        or len(self.spec.accepted_signals) > 0
    ):
        return (
            IAgentStateRepository,
            IAgentSignalRepository,
            IAgentEvidenceRepository,
        )
    return ()

Inbound run contract consumed by the framework-owned agent runner.

ADR-0013 §1 hands the execution loop to the framework runner. A caller (an inbound adapter today, an AG-UI/A2A protocol adapter later) hands the runner a RunAgentInput describing one run: which durable run to correlate against, the user instruction that seeds the model request, and whether the run resumes a paused/interrupted execution (ADR-0013 §5 HITL resume / restart recovery).

A stateless caller may also carry the prior transcript inline through message_history (ADR-0013 §6 client-injected history, pydantic-ai message_history precedent). When it is empty and a TaskStore is wired, the runner instead loads the server-persisted transcript by effective_conversation_id — the two multi-turn paths are mutually exclusive per run, never merged.

Approval decisions are not carried here. The unified pause -> approval request -> resume flow (ADR-0013 §5) delivers a decision through the durable signal repository, not through this input, so the runner polls the signal queue non-blockingly rather than reading a decision off the inbound contract.

RunAgentInput(state_id, instruction, conversation_id=None, parent_run_id=None, resume=False, message_history=(), model_selection=None, context=AgentContext(), metadata=dict(), attachments=(), steering_input_required=False, extensions=()) dataclass

Inbound contract for one framework-owned agent run.

extensions = () class-attribute instance-attribute

Typed application values copied into every model request of this run.

effective_conversation_id property

Return the multi-turn thread id, defaulting to the run id.

ADR-0013 §3 attribution requires a conversation id on every event. A single-turn caller may omit it, in which case the run id identifies the (degenerate) one-turn conversation.

__post_init__()

Reject inbound input that cannot correlate a run or seed a request.

Source code in core/spakky-agent/src/spakky/agent/inbound.py
def __post_init__(self) -> None:
    """Reject inbound input that cannot correlate a run or seed a request."""
    if not self.state_id.strip():
        raise AgentDefinitionError("Run agent input state id cannot be blank")
    if not self.instruction.strip():
        raise AgentDefinitionError("Run agent input instruction cannot be blank")
    if self.conversation_id is not None and not self.conversation_id.strip():
        raise AgentDefinitionError(
            "Run agent input conversation id cannot be blank"
        )
    if self.parent_run_id is not None and not self.parent_run_id.strip():
        raise AgentDefinitionError("Run agent input parent run id cannot be blank")
    if not isinstance(self.attachments, tuple) or any(
        not isinstance(
            attachment,
            ImagePart | AudioPart | VideoPart | DocumentPart,
        )
        for attachment in self.attachments
    ):
        raise AgentDefinitionError(
            "Run agent input attachments must be an immutable media tuple"
        )
    model_content_parts((TextPart(self.instruction), *self.attachments))
    object.__setattr__(self, "extensions", validated_extensions(self.extensions))

user_message()

Build the canonical user message, preserving the text-only shortcut.

Source code in core/spakky-agent/src/spakky/agent/inbound.py
def user_message(self) -> ModelMessage:
    """Build the canonical user message, preserving the text-only shortcut."""
    if not self.attachments:
        return ModelMessage.user(self.instruction)
    return ModelMessage.user((TextPart(self.instruction), *self.attachments))

Framework-owned agent execution loop (ADR-0013 §1).

The runner generalizes the manual model -> tool -> evidence -> terminate loop that ADR-0009 left in developer execute() bodies. A developer declares an @Agent spec plus @agent_tool methods; the framework provides the loop. The runner consumes the provider-neutral model stream (C2), dispatches tool calls through the discovered catalog (C4), records boundary/evidence (C3 model contracts), consumes durable signals, drives the unified HITL pause -> approval request -> resume flow (ADR-0013 §5), and terminates with a typed final output shaped by spec.output_type.

The runner exposes two streams over the same orchestration. run() yields the public AgentYield vocabulary that inbound adapters already consume. run_events() yields the protocol-neutral AgentEvent taxonomy (ADR-0013 §3) that AG-UI (#414) and A2A (#415) adapters project losslessly: the runner emits message/reasoning deltas, the tool-call start/args-delta/end/result lifecycle, and run/step boundaries as distinct events carrying attribution (agent / run / parent / conversation), rather than collapsing them into coarse AgentYield items that an adapter would have to re-expand. The fine-grained model-stream channels (C2 ModelStreamEventKind message/reasoning/tool-args deltas) project one-to-one onto the neutral taxonomy; REASONING_DELTA is omitted when the model declares no reasoning capability (graceful degrade, ADR-0013 §4).

DEFAULT_SYSTEM_INSTRUCTION = 'Use the declared tools to accomplish the objective.' module-attribute

Fallback system message when an agent spec declares no instructions.

ESTIMATED_CHARACTERS_PER_TOKEN = 4 module-attribute

Provider-neutral characters-per-token ratio for the compaction trigger estimate.

The core cannot call a provider tokenizer (it stays protocol-neutral, ADR-0013 §2), so the compaction trigger estimates token count from transcript length using the widely-used ~4-characters-per-token approximation. The estimate only decides whether the declared chain runs; the strategies themselves bound the result, so an approximate trigger is sufficient.

EVIDENCE_CLOCK_STEP = timedelta(microseconds=1) module-attribute

Smallest gap kept between two evidence timestamps of one runner.

RUNNER_CHECKPOINT_METADATA_KEY = 'runner_checkpoint' module-attribute

Durable state metadata key holding an interrupted iterative loop.

MODEL_STEP_RESTART_CODE = 'agent_model_step_restarted' module-attribute

Progress and telemetry code of a model step its adapter asked to redo.

AgentRunResult(state_id, status, tool_calls, evidence_count) dataclass

Neutral terminal summary returned when a spec declares no output type.

AgentRunner(agent, target, model, states=None, signals=None, evidence=None, task_store=None, context_provider=None, pricing=None, telemetry=None, signal_mailbox=None) dataclass

Framework-owned standard agent loop bound to one agent instance.

Durable repositories are None for a stateless agent (one that declares no accepted_signals and no action-boundary recovery). In that mode the runner skips state/evidence/signal handling and runs model -> tool -> final.

for_agent_instance(instance) classmethod

Resolve runner ports from an agent instance's injected attributes.

ADR-0009 stores constructor-injected ports as instance attributes, so the runner reads vars(instance) (the typed instance __dict__, not the banned getattr) and resolves each port by runtime type. Attribute names are developer-chosen, so resolution is type-driven, not name-driven.

Source code in core/spakky-agent/src/spakky/agent/runner.py
@classmethod
def for_agent_instance(cls, instance: object) -> "AgentRunner":
    """Resolve runner ports from an agent instance's injected attributes.

    ADR-0009 stores constructor-injected ports as instance attributes, so the
    runner reads ``vars(instance)`` (the typed instance ``__dict__``, not the
    banned ``getattr``) and resolves each port by runtime type. Attribute
    names are developer-chosen, so resolution is type-driven, not name-driven.
    """
    agent = Agent.get(type(instance))
    attributes = tuple(vars(instance).values())
    model = cls._resolve_required(attributes, IAgentModel)
    if model is None:
        raise AgentModelConfigurationError(
            "Agent run requires an IAgentModel port but none was injected"
        )
    states = cls._resolve_optional(attributes, IAgentStateRepository)
    signals = cls._resolve_optional(attributes, IAgentSignalRepository)
    evidence = cls._resolve_optional(attributes, IAgentEvidenceRepository)
    task_store = cls._resolve_optional(attributes, ITaskStore)
    context_provider = cls._resolve_optional(attributes, IAgentContextProvider)
    pricing = cls._resolve_optional(attributes, ModelPricingCatalog)
    telemetry = cls._resolve_optional(attributes, IAgentTelemetry)
    signal_mailbox = cls._resolve_optional(attributes, IAgentSignalSubscriber)
    if signal_mailbox is None:
        signal_mailbox = agent.signal_mailbox
    tool_providers = tuple(
        attribute
        for attribute in attributes
        if isinstance(attribute, IAgentToolProvider)
    )
    merged_catalog = AgentToolCatalog(
        descriptors=(
            *agent.tool_catalog.descriptors,
            *(
                descriptor
                for provider in tool_providers
                for descriptor in _bound_tool_provider_descriptors(provider)
            ),
        )
    )
    runner_agent = copy(agent)
    runner_agent.tool_catalog = merged_catalog
    runner = cls(
        agent=runner_agent,
        target=instance,
        model=model,
        states=states,
        signals=signals,
        evidence=evidence,
        task_store=task_store,
        context_provider=context_provider,
        pricing=pricing,
        telemetry=telemetry,
        signal_mailbox=signal_mailbox,
    )
    runner._require_durable_ports()
    return runner

with_model(model)

Return a runner using a run-specific model adapter.

Source code in core/spakky-agent/src/spakky/agent/runner.py
def with_model(self, model: IAgentModel) -> "AgentRunner":
    """Return a runner using a run-specific model adapter."""
    return replace(self, model=model)

with_pricing(pricing)

Return a runner using a snapshot of operator-owned pricing.

Source code in core/spakky-agent/src/spakky/agent/runner.py
def with_pricing(self, pricing: ModelPricingCatalog) -> "AgentRunner":
    """Return a runner using a snapshot of operator-owned pricing."""
    return replace(self, pricing=pricing)

with_telemetry(telemetry)

Return a runner emitting completed spans to one observer.

Source code in core/spakky-agent/src/spakky/agent/runner.py
def with_telemetry(self, telemetry: IAgentTelemetry) -> "AgentRunner":
    """Return a runner emitting completed spans to one observer."""
    return replace(self, telemetry=telemetry)

with_signal_mailbox(mailbox)

Return a runner receiving live signals through one mailbox port.

Source code in core/spakky-agent/src/spakky/agent/runner.py
def with_signal_mailbox(self, mailbox: IAgentSignalSubscriber) -> "AgentRunner":
    """Return a runner receiving live signals through one mailbox port."""
    return replace(self, signal_mailbox=mailbox)

run(run_input) async

Run one model-mediated agent loop, yielding the public stream.

Source code in core/spakky-agent/src/spakky/agent/runner.py
async def run(
    self,
    run_input: RunAgentInput,
) -> AsyncGenerator[AgentYield[object], None]:
    """Run one model-mediated agent loop, yielding the public stream."""
    started_at_ns = time_ns()
    completed = False
    outcome = "incomplete"
    error_code: str | None = None
    cost_attributes: dict[str, JsonValue] = {}
    try:
        stream = (
            self._run_stateless(run_input)
            if self.states is None
            else self._run_durable(run_input)
        )
        async for item in stream:
            if item.kind is AgentYieldKind.FINAL:
                completed = True
                outcome = "completed"
                if not isinstance(item.payload, Final):
                    raise AgentDefinitionError(
                        "Agent final yield contains an invalid payload"
                    )
                cost_attributes.update(
                    _telemetry_cost_attributes(item.payload.metadata)
                )
            elif item.kind is AgentYieldKind.APPROVAL:
                completed = True
                outcome = "paused"
                if not isinstance(item.payload, Approval):
                    raise AgentDefinitionError(
                        "Agent approval yield contains an invalid payload"
                    )
                cost_attributes.update(
                    _telemetry_cost_attributes(item.payload.metadata)
                )
            elif item.kind is AgentYieldKind.ERROR and isinstance(
                item.payload, Error
            ):
                completed = True
                outcome = "failed"
                error_code = item.payload.code
                cost_attributes.update(
                    _telemetry_cost_attributes(item.payload.metadata)
                )
            elif item.kind is AgentYieldKind.CANCEL:
                completed = True
                outcome = "cancelled"
                error_code = "cancelled"
                if not isinstance(item.payload, Cancel):
                    raise AgentDefinitionError(
                        "Agent cancel yield contains an invalid payload"
                    )
                cost_attributes.update(
                    _telemetry_cost_attributes(item.payload.metadata)
                )
            yield item
    except Exception:
        error_code = error_code or "agent_run_exception"
        raise
    finally:
        self._record_span(
            AgentSpanKind.RUN,
            "agent.run",
            started_at_ns,
            run_input.state_id,
            {
                "agent.conversation.id": run_input.effective_conversation_id,
                "agent.run.outcome": outcome,
                "agent.run.completed": completed,
                **cost_attributes,
            },
            error_code=error_code,
        )

run_events(run_input) async

Run the bounded loop while recording one privacy-safe run span.

Source code in core/spakky-agent/src/spakky/agent/runner.py
async def run_events(
    self,
    run_input: RunAgentInput,
) -> AsyncGenerator[AgentEvent, None]:
    """Run the bounded loop while recording one privacy-safe run span."""
    started_at_ns = time_ns()
    completed = False
    outcome = "incomplete"
    error_code: str | None = None
    cost_attributes: dict[str, JsonValue] = {}
    try:
        async for event in self._run_events_unobserved(run_input):
            if isinstance(event, RunPausedEvent):
                completed = True
                outcome = "paused"
                cost_attributes.update(_telemetry_cost_attributes(event.metadata))
            elif isinstance(event, RunFinishedEvent):
                completed = True
                cost_attributes.update(_telemetry_cost_attributes(event.metadata))
                if event.error is None:
                    outcome = "completed"
                else:
                    code = event.error.get("code")
                    error_code = (
                        code if isinstance(code, str) else "agent_run_failed"
                    )
                    outcome = "cancelled" if error_code == "cancelled" else "failed"
            yield event
    except Exception:
        error_code = error_code or "agent_run_exception"
        raise
    finally:
        self._record_span(
            AgentSpanKind.RUN,
            "agent.run",
            started_at_ns,
            run_input.state_id,
            {
                "agent.conversation.id": run_input.effective_conversation_id,
                "agent.run.outcome": outcome,
                "agent.run.completed": completed,
                **cost_attributes,
            },
            error_code=error_code,
        )

runner_backed_execute(self, run_input) async

Framework-provided execute() bound onto a declaration-only @Agent.

@Agent binds this as the agent's execute() when the developer declares only a spec plus @agent_tool methods (ADR-0013 §1). It builds a runner from the agent instance's injected ports and replays its stream.

Source code in core/spakky-agent/src/spakky/agent/runner.py
async def runner_backed_execute(
    self: object,
    run_input: RunAgentInput,
) -> AsyncGenerator[AgentYield[object], None]:
    """Framework-provided ``execute()`` bound onto a declaration-only @Agent.

    ``@Agent`` binds this as the agent's ``execute()`` when the developer
    declares only a spec plus ``@agent_tool`` methods (ADR-0013 §1). It builds a
    runner from the agent instance's injected ports and replays its stream.
    """
    runner = AgentRunner.for_agent_instance(self)
    async for item in runner.run(run_input):
        yield item

DI entry point for opening agent runners.

Protocol adapters should not construct :class:AgentRunner directly when an application may load runner-augmenting plugins such as MCP. They ask this factory port for a runner scoped to one request instead; plugins can then bind the port to their own implementation while the default remains the native framework runner.

IAgentRunnerFactory

Bases: ABC

Port for opening a request-scoped runner for one agent instance.

open_runner(agent_instance, run_input=None) abstractmethod

Yield a runner bound to agent_instance for one adapter request.

Source code in core/spakky-agent/src/spakky/agent/runner_factory.py
@abstractmethod
def open_runner(
    self,
    agent_instance: object,
    run_input: RunAgentInput | None = None,
) -> AbstractAsyncContextManager[AgentRunner]:
    """Yield a runner bound to ``agent_instance`` for one adapter request."""
    ...

AgentRunnerFactory(model_resolver=None, telemetry=None, pricing=None, signal_mailbox=None)

Bases: IAgentRunnerFactory

Default runner factory using the native framework-owned runner.

Source code in core/spakky-agent/src/spakky/agent/runner_factory.py
def __init__(
    self,
    model_resolver: IAgentModelResolver | None = None,
    telemetry: IAgentTelemetry | None = None,
    pricing: ModelPricingCatalog | None = None,
    signal_mailbox: IAgentSignalSubscriber | None = None,
) -> None:
    self._model_resolver = model_resolver
    self._telemetry = telemetry
    self._pricing = pricing
    self._signal_mailbox = signal_mailbox

open_runner(agent_instance, run_input=None) async

Yield the native runner for one request.

Source code in core/spakky-agent/src/spakky/agent/runner_factory.py
@override
@asynccontextmanager
async def open_runner(
    self,
    agent_instance: object,
    run_input: RunAgentInput | None = None,
) -> AsyncGenerator[AgentRunner, None]:
    """Yield the native runner for one request."""
    runner = AgentRunner.for_agent_instance(agent_instance)
    if self._model_resolver is not None:
        model = self._model_resolver.resolve_model(agent_instance, run_input)
        if model is not None:
            runner = runner.with_model(model)
    if self._telemetry is not None:
        runner = runner.with_telemetry(self._telemetry)
    if self._pricing is not None:
        runner = runner.with_pricing(self._pricing)
    if self._signal_mailbox is not None and runner.signal_mailbox is None:
        runner = runner.with_signal_mailbox(self._signal_mailbox)
    yield runner

Event

Protocol-neutral agent event taxonomy.

This taxonomy is the single neutral source that AG-UI, A2A, and MCP adapters normalize into their respective protocols. The core stays protocol-neutral (ADR-0013 §2 / §3): no event field is named after, or shaped by, any single external protocol, yet every event carries enough attribution for each adapter to reconstruct that protocol's linkage without loss.

Attribution carried by every event (ADR-0013 §3):

  • agent_id — which agent emitted the event (team-mode composite attribution).
  • run_id — the run this event belongs to. AG-UI projects this as runId; A2A projects this as the A2A Task id.
  • parent_run_id — the parent run in a delegation tree (None for a root run that has no delegating parent). AG-UI projects this as parentRunId; A2A projects this as the parent task in its task hierarchy.
  • conversation_id — the multi-turn conversation this run participates in. AG-UI projects this as threadId; A2A projects this as contextId.

AgentEvent = MessageDeltaEvent | ReasoningDeltaEvent | ToolCallStartEvent | ToolCallArgsDeltaEvent | ToolCallEndEvent | ToolCallResultEvent | RunStartedEvent | RunPausedEvent | RunFinishedEvent | StepStartedEvent | StepFinishedEvent | StateSnapshotEvent | StateDeltaEvent | ArtifactEvent | CustomEvent

Discriminated union of every protocol-neutral agent event.

Each member exposes a distinct kind literal so adapters dispatch with match/case exhaustiveness rather than runtime attribute probing.

AgentEventKind

Bases: StrEnum

Protocol-neutral event kinds emitted across an agent run.

The lifecycle kinds (RUN_STARTED … ARTIFACT) generalize ADR-0009's public AgentYield vocabulary and align 1:1 with the streaming events that AG-UI and A2A adapters must reproduce (ADR-0013 §3).

AgentEventAttribution(agent_id, run_id, conversation_id, parent_run_id=None) dataclass

Attribution carried by every protocol-neutral agent event.

parent_run_id is None exactly when the run is a delegation-tree root (ADR-0013 §3 "parent link" / ADR-0009 parent linkage). The remaining ids are always present so adapters never have to synthesize linkage.

__post_init__()

Reject attribution that cannot identify an agent, run, or conversation.

Source code in core/spakky-agent/src/spakky/agent/event.py
def __post_init__(self) -> None:
    """Reject attribution that cannot identify an agent, run, or conversation."""
    if not self.agent_id.strip():
        raise AgentDefinitionError("Agent event agent id cannot be blank")
    if not self.run_id.strip():
        raise AgentDefinitionError("Agent event run id cannot be blank")
    if not self.conversation_id.strip():
        raise AgentDefinitionError("Agent event conversation id cannot be blank")
    if self.parent_run_id is not None and not self.parent_run_id.strip():
        raise AgentDefinitionError("Agent event parent run id cannot be blank")

MessageDeltaEvent(attribution, message_id, delta, metadata=dict()) dataclass

Incremental assistant message text produced by the model.

ReasoningDeltaEvent(attribution, reasoning_id, delta, metadata=dict()) dataclass

Incremental model reasoning (thinking) text.

ToolCallStartEvent(attribution, call_id, tool_name, parent_message_id=None, metadata=dict()) dataclass

A model has begun emitting a tool call with a known name.

parent_message_id links the tool call to the assistant message that requested it (None when the model emits the call outside any message). AG-UI projects this as parentMessageId on TOOL_CALL_START.

ToolCallArgsDeltaEvent(attribution, call_id, args_delta, metadata=dict()) dataclass

Incremental serialized arguments for an in-flight tool call.

ToolCallEndEvent(attribution, call_id, metadata=dict()) dataclass

A tool call has finished streaming its arguments.

ToolCallResultEvent(attribution, call_id, tool_name, message_id, result=None, metadata=dict()) dataclass

The result returned by executing a completed tool call.

message_id identifies the conversation message this tool result belongs to, so an adapter can attach the result to the right message. AG-UI requires it as messageId on TOOL_CALL_RESULT; without it the result frame cannot be reconstructed losslessly.

RunStartedEvent(attribution, metadata=dict()) dataclass

A run has started executing.

RunPausedEvent(attribution, reason, prompt, state_id, approval_id=None, tool_call_id=None, allowed_decisions=(), metadata=dict()) dataclass

A run has paused without terminal success or failure.

The event is intentionally protocol-neutral: it carries core lifecycle reason plus the input prompt/decision envelope adapters need to project their own input-required or auth-required protocol states.

__post_init__()

Reject pause events that cannot be shown or resumed.

Source code in core/spakky-agent/src/spakky/agent/event.py
def __post_init__(self) -> None:
    """Reject pause events that cannot be shown or resumed."""
    if not self.prompt.strip():
        raise AgentDefinitionError("Agent run pause prompt cannot be blank")
    if not self.state_id.strip():
        raise AgentDefinitionError("Agent run pause state id cannot be blank")
    if self.approval_id is not None and not self.approval_id.strip():
        raise AgentDefinitionError("Agent run pause approval id cannot be blank")
    if self.tool_call_id is not None and not self.tool_call_id.strip():
        raise AgentDefinitionError("Agent run pause tool call id cannot be blank")

RunFinishedEvent(attribution, error=None, metadata=dict()) dataclass

A run has finished executing.

error is None for a successful run and carries a terminal failure payload otherwise (A2A failed task / AG-UI RUN_ERROR).

StepStartedEvent(attribution, step_name, metadata=dict()) dataclass

A named step inside a run has started (one model-loop iteration).

StepFinishedEvent(attribution, step_name, metadata=dict()) dataclass

A named step inside a run has finished.

StateSnapshotEvent(attribution, snapshot, metadata=dict()) dataclass

A full snapshot of shared run state.

StateDeltaEvent(attribution, patch, metadata=dict()) dataclass

An incremental change to shared run state.

patch is a sequence of JSON-Patch operations (RFC 6902), the same shape AG-UI STATE_DELTA carries, so adapters relay it without re-deriving a diff.

ArtifactEvent(attribution, artifact_id, content, name=None, metadata=dict()) dataclass

A produced artifact surfaced by an agent run.

CustomEvent(attribution, name, value, metadata=dict()) dataclass

An application-defined named event carrying a JSON value.

The framework assigns no meaning to name or value: application code running inside a run emits them through AgentCustomEvents and each adapter relays them on its own protocol surface. Names should be namespaced by the application (for example "myapp.turn_part") so they cannot collide with names an adapter reserves for its own projections.

__post_init__()

Reject a custom event a client could not dispatch on.

Source code in core/spakky-agent/src/spakky/agent/event.py
def __post_init__(self) -> None:
    """Reject a custom event a client could not dispatch on."""
    if not self.name.strip():
        raise AgentDefinitionError("Agent custom event name cannot be blank")

Run-scoped channel for application-defined custom agent events.

Application code running inside an agent run (a tool, or a service a tool calls) has no handle on the event stream the client receives. This module gives it one without threading a parameter through every call: an adapter wraps the runner's neutral stream with AgentCustomEvents.merge, which binds a channel in a ContextVar for the task that iterates the source, and AgentCustomEvents.emit puts a named CustomEvent on that channel.

The merged stream hands every item to its consumer through one queue, so a custom event emitted while the source is still awaiting (for example during a long tool call) reaches the consumer before the source's next event.

The source is iterated by a single pump task for its whole lifetime. The runner holds task-affine constructs (asyncio.timeout_at and friends) across its yield points, so advancing it from a fresh task per step would break them. The pump advances the source only after the consumer has asked for the item after the previous one, which keeps the source exactly as lazy as iterating it directly: a slow or disconnected consumer does not let the run race ahead.

AgentCustomEvents

Emit application-defined events into the stream of the current run.

listening() staticmethod

Return whether emit would reach a consumer from this context.

Code that also runs outside a merged stream (a plain runner.run(), a background job) checks this before emitting.

Source code in core/spakky-agent/src/spakky/agent/custom_event.py
@staticmethod
def listening() -> bool:
    """Return whether ``emit`` would reach a consumer from this context.

    Code that also runs outside a merged stream (a plain ``runner.run()``,
    a background job) checks this before emitting.
    """
    channel = _CHANNEL.get()
    return channel is not None and channel.open

emit(name, value, *, metadata=None) staticmethod

Put a named custom event on the stream of the current run.

The event keeps its position relative to other events emitted by the same producer and is delivered without waiting for the runner's next event.

Parameters:

Name Type Description Default
name str

Application-defined event name; namespace it (for example "myapp.turn_part") to stay clear of adapter-reserved names.

required
value JsonValue

JSON-compatible payload relayed to the client unchanged.

required
metadata JsonObject | None

Neutral event metadata for in-process consumers. None means unspecified and is stored as an empty object.

None

Raises:

Type Description
AgentCustomEventChannelUnavailableError

No merged stream is listening in this context.

AgentDefinitionError

name is blank.

Source code in core/spakky-agent/src/spakky/agent/custom_event.py
@staticmethod
def emit(
    name: str,
    value: JsonValue,
    *,
    metadata: JsonObject | None = None,
) -> None:
    """Put a named custom event on the stream of the current run.

    The event keeps its position relative to other events emitted by the
    same producer and is delivered without waiting for the runner's next
    event.

    Args:
        name: Application-defined event name; namespace it (for example
            ``"myapp.turn_part"``) to stay clear of adapter-reserved names.
        value: JSON-compatible payload relayed to the client unchanged.
        metadata: Neutral event metadata for in-process consumers. ``None``
            means unspecified and is stored as an empty object.

    Raises:
        AgentCustomEventChannelUnavailableError: No merged stream is
            listening in this context.
        AgentDefinitionError: ``name`` is blank.
    """
    channel = _CHANNEL.get()
    if channel is None or not channel.open:
        raise AgentCustomEventChannelUnavailableError
    channel.put(
        CustomEvent(
            attribution=channel.attribution,
            name=name,
            value=value,
            metadata=metadata if metadata is not None else {},
        )
    )

merge(events, attribution) async staticmethod

Yield events interleaved live with custom events emitted meanwhile.

Parameters:

Name Type Description Default
events AsyncIterator[AgentEvent]

The neutral source stream, typically runner.run_events().

required
attribution AgentEventAttribution

Attribution stamped on every emitted custom event.

required

Yields:

Type Description
AsyncGenerator[AgentEvent, None]

Source events in source order and custom events in emit order.

AsyncGenerator[AgentEvent, None]

Custom events still queued when the source ends are yielded before

AsyncGenerator[AgentEvent, None]

the merged stream ends.

Raises:

Type Description
Exception

Whatever the source raises, after every item queued before the failure has been yielded.

Source code in core/spakky-agent/src/spakky/agent/custom_event.py
@staticmethod
async def merge(
    events: AsyncIterator[AgentEvent],
    attribution: AgentEventAttribution,
) -> AsyncGenerator[AgentEvent, None]:
    """Yield ``events`` interleaved live with custom events emitted meanwhile.

    Args:
        events: The neutral source stream, typically ``runner.run_events()``.
        attribution: Attribution stamped on every emitted custom event.

    Yields:
        Source events in source order and custom events in emit order.
        Custom events still queued when the source ends are yielded before
        the merged stream ends.

    Raises:
        Exception: Whatever the source raises, after every item queued
            before the failure has been yielded.
    """
    channel = _AgentCustomEventChannel(attribution)
    # A task copies its context when it is created, so the channel is bound
    # in the copy the pump runs in. The caller's context is left untouched:
    # an enclosing merge keeps its own channel, and there is no token to
    # reset from whichever context happens to close this generator.
    context = copy_context()
    context.run(_CHANNEL.set, channel)
    pump = create_task(channel.pump(events), context=context)
    source_finished = False
    try:
        while True:
            item = await channel.next()
            if item is None:
                source_finished = True
                break
            yield item
            channel.delivered()
        # The pump queues the end marker as its last action, so it is done;
        # awaiting it re-raises the source's failure or cancellation.
        await pump
    finally:
        channel.close()
        if not source_finished:
            # The consumer stopped early (closed or cancelled): stop the
            # source too and wait for its cleanup before returning.
            pump.cancel()
            await wait((pump,))
            AgentCustomEvents._raise_source_cleanup_failure(pump)

Dispatcher

Declarative tool dispatch over a discovered agent tool catalog.

ADR-0013 §1 hands the model-call -> tool-invoke step to the framework runner. This module removes the developer-written if call.name == ... chain and the manual payload extraction it implied: a model tool call is resolved against the catalog, its arguments are bound through the descriptor, and the descriptor's callable is invoked. External MCP tools (follow-up F1) normalize into the same AgentToolCatalog and therefore dispatch through this identical path.

AgentToolDispatcher(target, catalog, runtime_context=None) dataclass

Resolve and invoke a catalog tool from a model tool call.

The dispatcher binds to a single agent instance whose @agent_tool methods are described by catalog. Catalog descriptors that own no instance parameter (such as MCP-normalized external tools) are invoked without the bound target.

descriptor_for(call)

Resolve the catalog descriptor a model tool call targets.

Source code in core/spakky-agent/src/spakky/agent/dispatcher.py
def descriptor_for(self, call: ModelToolCall) -> AgentToolDescriptor:
    """Resolve the catalog descriptor a model tool call targets."""
    for descriptor in self.catalog.descriptors:
        if descriptor.schema.name == call.name:
            return descriptor
    raise AgentToolDispatchError("Agent tool call names an unregistered tool")

dispatch(call) async

Bind a model tool call payload and invoke its catalog callable.

Source code in core/spakky-agent/src/spakky/agent/dispatcher.py
async def dispatch(self, call: ModelToolCall) -> object:
    """Bind a model tool call payload and invoke its catalog callable."""
    descriptor = self.descriptor_for(call)
    invocation = descriptor.bind_invocation(call.arguments)
    callable_ = descriptor.callable
    positional = self._with_injected_prefix(callable_, invocation.args)
    if iscoroutinefunction(callable_):
        awaitable: Awaitable[object] = callable_(
            *positional,
            **invocation.kwargs,
        )
        return await awaitable
    return callable_(*positional, **invocation.kwargs)

State

Agent lifecycle state contracts.

AgentStatus

Bases: StrEnum

Externally observable lifecycle states for an agent execution.

AgentStateTransition

Bases: StrEnum

State transition vocabulary accepted by durable agent orchestration.

AgentStateReason

Bases: StrEnum

Structured reason that refines an externally observable lifecycle state.

AgentState(id, agent_type, status, transition=None, reason=None, current_activity=None, input_ref=None, output_ref=None, pending_signal_count=0, last_event_cursor=None, recovery_marker=None, metadata=dict(), created_at=None, updated_at=None) dataclass

Materialized state for a long-running agent execution.

__post_init__()

Reject state snapshots that cannot represent a real queue count.

Source code in core/spakky-agent/src/spakky/agent/state.py
def __post_init__(self) -> None:
    """Reject state snapshots that cannot represent a real queue count."""
    if self.pending_signal_count < 0:
        raise AgentDefinitionError("Agent pending signal count cannot be negative")

Signal

Agent signal contracts.

AgentSignalKind

Bases: StrEnum

Inbound stimulus kinds that an agent may accept while running.

AgentSignalPriority

Bases: StrEnum

Producer-assigned urgency used only for live mailbox lane routing.

Priority is a delivery hint, not part of the durable ledger row. Replayed signals are applied at the first safe boundary of a starting or resuming run, where no in-flight work exists to interrupt.

AgentSignalLane

Bases: StrEnum

Live delivery lanes of a run mailbox.

CONTROL interrupts the in-flight model operation immediately (cancel and urgent revisioned steering). STEERING waits in the run mailbox until the next safe point, such as a finished model response or tool boundary.

ApprovalDecision

Bases: StrEnum

Human-in-the-loop approval outcomes.

AgentSignal(id, agent_state_id, kind, payload=dict(), created_at=None, priority=AgentSignalPriority.NORMAL) dataclass

Inbound stimulus appended for an agent execution.

lane property

Return the live mailbox lane selected by kind and producer priority.

AgentSteeringUpdate

Bases: BaseModel

Revisioned input; provisional observations grant no tool/final authority.

input_id is caller-owned and scoped to a conversation/utterance. Withdrawal removes that input while retaining its revision tombstone for idempotence.

Non-blocking consumption helpers for durable agent signals.

AgentSignalPollPoint

Bases: StrEnum

Places where orchestration may poll durable signals without waiting.

AgentSignalConsumptionBatch(state_id, poll_point, signals) dataclass

Signals consumed during one non-blocking poll.

consumed_count property

Return the number of signals consumed by this poll.

consume_pending_agent_signals(repository, state_id, *, poll_point=AgentSignalPollPoint.SAFE_BOUNDARY, accepted_signals=None, max_signals=None)

Consume currently pending signals without sleeping or waiting for new input.

The repository remains responsible for durable queue ordering. This helper consumes only the eligible prefix of the pending queue so later signals never overtake an earlier unaccepted signal.

Source code in core/spakky-agent/src/spakky/agent/signal_consumption.py
def consume_pending_agent_signals(
    repository: IAgentSignalRepository,
    state_id: str,
    *,
    poll_point: AgentSignalPollPoint = AgentSignalPollPoint.SAFE_BOUNDARY,
    accepted_signals: Sequence[AgentSignalKind] | None = None,
    max_signals: int | None = None,
) -> AgentSignalConsumptionBatch:
    """Consume currently pending signals without sleeping or waiting for new input.

    The repository remains responsible for durable queue ordering. This helper
    consumes only the eligible prefix of the pending queue so later signals never
    overtake an earlier unaccepted signal.
    """
    if not state_id.strip():
        raise AgentDefinitionError("Agent signal state id cannot be blank")
    if max_signals is not None and max_signals <= 0:
        raise AgentDefinitionError("Agent signal max_signals must be positive")

    accepted = frozenset(accepted_signals) if accepted_signals is not None else None
    pending = tuple(repository.list_pending(state_id))
    selected = _select_consumable_prefix(
        pending,
        accepted_signals=accepted,
        max_signals=max_signals,
    )
    consumed = tuple(repository.mark_consumed(signal.id) for signal in selected)

    return AgentSignalConsumptionBatch(
        state_id=state_id,
        poll_point=poll_point,
        signals=consumed,
    )

Live per-run signal mailboxes beside the durable signal ledger.

The IAgentSignalRepository row remains the durable ledger (outbox) of every signal. Live delivery is a separate port: a producer publishes a signal to an IAgentSignalPublisher only after its own transaction commits, and a running agent receives it through the AgentRunMailbox it subscribed for its state. A run replays unconsumed ledger rows once when it starts or resumes, then waits on the mailbox instead of re-reading the ledger, so an idle run issues no signal queries at all.

The default InProcessAgentSignalMailbox delivers inside one process. It is safe to publish from any thread or event loop: delivery is handed to the run's own loop with call_soon_threadsafe. A cross-process transport (for example PostgreSQL NOTIFY or Kafka) can implement IAgentSignalPublisher on the producer side and feed received signals into the in-process mailbox.

IAgentSignalPublisher

Bases: ABC

Port that delivers committed signals to live run mailboxes.

publish(signal) abstractmethod

Deliver one signal whose ledger row is already committed.

Implementations must be thread-safe and must not block. Publishing a signal for a state with no live subscriber is not an error: the ledger row is replayed when that state's run next starts or resumes.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
@abstractmethod
def publish(self, signal: AgentSignal) -> None:
    """Deliver one signal whose ledger row is already committed.

    Implementations must be thread-safe and must not block. Publishing a
    signal for a state with no live subscriber is not an error: the ledger
    row is replayed when that state's run next starts or resumes.
    """
    ...

IAgentSignalSubscriber

Bases: ABC

Port that opens the live mailbox of one running agent state.

subscribe(state_id) abstractmethod

Open a mailbox bound to the calling event loop for state_id.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
@abstractmethod
def subscribe(self, state_id: str) -> "AgentRunMailbox":
    """Open a mailbox bound to the calling event loop for ``state_id``."""
    ...

AgentRunMailbox(state_id, loop, owner=None)

Live, loop-bound inbox of one agent run with control and steering lanes.

deliver may be called from any thread. Accepted signals are queued in arrival order; drain hands them to the run at its next observation. wait wakes on any arrival and wait_control only on a AgentSignalLane.CONTROL arrival, so in-flight work is interrupted only by cancel or urgent input while ordinary steering waits for a safe point.

Bind a mailbox to one agent state and the event loop running it.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def __init__(
    self,
    state_id: str,
    loop: AbstractEventLoop,
    owner: "InProcessAgentSignalMailbox | None" = None,
) -> None:
    """Bind a mailbox to one agent state and the event loop running it."""
    self._state_id = state_id
    self._loop = loop
    self._owner = owner
    self._queue = deque()
    self._arrived = Event()
    self._control_arrived = Event()
    self._closed = False

state_id property

Return the agent state this mailbox receives signals for.

closed property

Return whether the run closed this mailbox.

deliver(signal)

Hand one committed signal to the run loop from any thread.

A producer already running on the run's own loop (for example a tool appending a signal) is accepted synchronously so the very next boundary observes it; any other thread or loop is handed over with call_soon_threadsafe.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def deliver(self, signal: AgentSignal) -> None:
    """Hand one committed signal to the run loop from any thread.

    A producer already running on the run's own loop (for example a tool
    appending a signal) is accepted synchronously so the very next boundary
    observes it; any other thread or loop is handed over with
    ``call_soon_threadsafe``.
    """
    if self._on_own_loop():
        self._accept(signal)
        return
    try:
        self._loop.call_soon_threadsafe(self._accept, signal)
    except RuntimeError:
        # The run loop already closed; the ledger row is replayed on resume.
        logger.debug(
            "Agent signal mailbox loop closed before delivery",
            extra={"state_id": self._state_id, "signal_id": signal.id},
        )

drain()

Return and clear every signal delivered since the last drain.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def drain(self) -> tuple[AgentSignal, ...]:
    """Return and clear every signal delivered since the last drain."""
    drained = tuple(self._queue)
    self._queue.clear()
    self._arrived.clear()
    self._control_arrived.clear()
    return drained

wait() async

Wait until any signal arrives after the last drain.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
async def wait(self) -> None:
    """Wait until any signal arrives after the last drain."""
    await self._arrived.wait()

wait_control() async

Wait until a control-lane signal arrives after the last drain.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
async def wait_control(self) -> None:
    """Wait until a control-lane signal arrives after the last drain."""
    await self._control_arrived.wait()

close()

Stop accepting signals and detach from the owning publisher.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def close(self) -> None:
    """Stop accepting signals and detach from the owning publisher."""
    self._closed = True
    self._queue.clear()
    if self._owner is not None:
        self._owner.unsubscribe(self)

InProcessAgentSignalMailbox()

Bases: IAgentSignalPublisher, IAgentSignalSubscriber

Default in-process signal hub routing committed signals to run mailboxes.

Create an empty subscriber registry.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def __init__(self) -> None:
    """Create an empty subscriber registry."""
    self._lock = Lock()
    self._subscribers = {}

unsubscribe(mailbox)

Detach a closed run mailbox from future publications.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def unsubscribe(self, mailbox: AgentRunMailbox) -> None:
    """Detach a closed run mailbox from future publications."""
    with self._lock:
        mailboxes = self._subscribers.get(mailbox.state_id)
        if mailboxes is None or mailbox not in mailboxes:
            return
        mailboxes.remove(mailbox)
        if not mailboxes:
            del self._subscribers[mailbox.state_id]

subscriber_count(state_id)

Return how many live runs currently listen for state_id.

Source code in core/spakky-agent/src/spakky/agent/mailbox.py
def subscriber_count(self, state_id: str) -> int:
    """Return how many live runs currently listen for ``state_id``."""
    with self._lock:
        return len(self._subscribers.get(state_id, ()))

Evidence

Agent evidence contracts.

AgentEvidenceKind

Bases: StrEnum

Kinds of append-only evidence captured by agent execution.

AgentEvidence(id, agent_state_id, kind, payload=dict(), summary=None, digest=None, manifest_ref=None, reference=None, sensitive_fields=(), created_at=None, model_step=None, origin_refs=()) dataclass

Append-only artifact captured during an agent execution.

model_step = None class-attribute instance-attribute

Model step whose context this evidence records, for step-scoped kinds.

origin_refs = () class-attribute instance-attribute

Source references the recorded model context was built from.

AgentEvidenceCandidate(kind, payload=dict(), summary=None, digest=None, manifest_ref=None, reference=None, sensitive_fields=(), model_step=None, origin_refs=()) dataclass

Append-only evidence candidate before repository id assignment.

tool_result(*, tool_identity, tool_schema_name, result, capture, sensitive_fields=(), exposure_policy=None, summary=None) classmethod

Create evidence metadata for a captured tool result.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def tool_result(
    cls,
    *,
    tool_identity: str,
    tool_schema_name: str,
    result: JsonObject,
    capture: EvidenceCapture,
    sensitive_fields: tuple[SensitiveFieldDescriptor, ...] = (),
    exposure_policy: EvidenceExposurePolicy | None = None,
    summary: str | None = None,
) -> "AgentEvidenceCandidate":
    """Create evidence metadata for a captured tool result."""
    _require_non_blank(tool_identity, "Agent tool identity")
    _require_non_blank(tool_schema_name, "Agent tool schema name")
    policy = exposure_policy or EvidenceExposurePolicy()
    guarded_result = guard_json_value(result, sensitive_fields, policy)
    if not isinstance(guarded_result, Mapping):
        guarded_result = {}
    return cls(
        kind=AgentEvidenceKind.TOOL,
        payload={
            "tool_identity": tool_identity,
            "tool_schema_name": tool_schema_name,
            "capture": capture.value,
            "result": guarded_result,
        },
        sensitive_fields=sensitive_fields
        if policy.include_sensitive_metadata
        else (),
        summary=summary,
    )

model_decision(*, model, decision, summary=None) classmethod

Create evidence metadata for a model decision.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def model_decision(
    cls,
    *,
    model: str,
    decision: JsonObject,
    summary: str | None = None,
) -> "AgentEvidenceCandidate":
    """Create evidence metadata for a model decision."""
    _require_non_blank(model, "Agent model name")
    return cls(
        kind=AgentEvidenceKind.MODEL,
        payload={"model": model, "decision": decision},
        summary=summary,
    )

tool_decision(*, tool_identity, decision, summary=None) classmethod

Create evidence metadata for a tool-routing decision.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def tool_decision(
    cls,
    *,
    tool_identity: str,
    decision: JsonObject,
    summary: str | None = None,
) -> "AgentEvidenceCandidate":
    """Create evidence metadata for a tool-routing decision."""
    _require_non_blank(tool_identity, "Agent tool identity")
    return cls(
        kind=AgentEvidenceKind.TOOL,
        payload={"tool_identity": tool_identity, "decision": decision},
        summary=summary,
    )

context_optimization(*, action, stage, signals=(), summary=None) classmethod

Create before/after evidence for a context optimization action.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def context_optimization(
    cls,
    *,
    action: ContextOptimizationAction,
    stage: ContextOptimizationEvidenceStage,
    signals: Sequence[ContextHealthSignal] = (),
    summary: str | None = None,
) -> "AgentEvidenceCandidate":
    """Create before/after evidence for a context optimization action."""
    _require_non_blank(action.id, "Context optimization action id")
    return cls(
        kind=AgentEvidenceKind.CONTEXT_OPTIMIZATION,
        payload={
            "stage": stage.value,
            "action": action.evidence_payload(),
            "signals": tuple(signal.evidence_payload() for signal in signals),
        },
        summary=summary,
        digest=action.digest_ref,
        manifest_ref=action.manifest_ref,
        reference=action.result_evidence_ref,
    )

evaluation(*, evaluator, metric, passed, score, case_ref, sample_ref) classmethod

Create privacy-safe evidence for one offline evaluation metric.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
@classmethod
def evaluation(
    cls,
    *,
    evaluator: str,
    metric: str,
    passed: bool,
    score: float,
    case_ref: str,
    sample_ref: str,
) -> "AgentEvidenceCandidate":
    """Create privacy-safe evidence for one offline evaluation metric."""
    _require_non_blank(evaluator, "Agent evaluator name")
    _require_non_blank(metric, "Agent evaluation metric")
    _require_non_blank(case_ref, "Agent evaluation case reference")
    _require_non_blank(sample_ref, "Agent evaluation sample reference")
    if not isinstance(passed, bool):
        raise AgentDefinitionError("Agent evaluation pass value must be boolean")
    if (
        isinstance(score, bool)
        or not isinstance(score, int | float)
        or not isfinite(score)
        or not 0 <= score <= 1
    ):
        raise AgentDefinitionError(
            "Agent evaluation score must be between zero and one"
        )
    return cls(
        kind=AgentEvidenceKind.EVALUATION,
        payload={
            "evaluator": evaluator,
            "metric": metric,
            "passed": passed,
            "score": float(score),
            "case_ref": case_ref,
            "sample_ref": sample_ref,
        },
        summary="offline agent evaluation result",
        reference=case_ref,
    )

to_evidence(*, evidence_id, agent_state_id, created_at=None)

Assign repository identity while preserving append-only contents.

Source code in core/spakky-agent/src/spakky/agent/evidence.py
def to_evidence(
    self,
    *,
    evidence_id: str,
    agent_state_id: str,
    created_at: datetime | None = None,
) -> AgentEvidence:
    """Assign repository identity while preserving append-only contents."""
    _require_non_blank(evidence_id, "Agent evidence id")
    _require_non_blank(agent_state_id, "Agent state id")
    return AgentEvidence(
        id=evidence_id,
        agent_state_id=agent_state_id,
        kind=self.kind,
        payload=self.payload,
        summary=self.summary,
        digest=self.digest,
        manifest_ref=self.manifest_ref,
        reference=self.reference,
        sensitive_fields=self.sensitive_fields,
        created_at=created_at,
        model_step=self.model_step,
        origin_refs=self.origin_refs,
    )

Context

Typed context contracts for agent model input assembly.

ContextPackRole

Bases: StrEnum

Semantic role of a context pack inside a model request.

ContextFreshness

Bases: StrEnum

Freshness classification for context rot and budget decisions.

ContextSensitivity

Bases: StrEnum

Deterministic sensitivity metadata carried before model input.

ContextRotSymptom

Bases: StrEnum

Typed context rot symptoms observed before model input assembly.

ContextOptimizationActionKind

Bases: StrEnum

Optimization actions that can be selected from context health signals.

ContextOptimizationEvidenceStage

Bases: StrEnum

Where an optimization action evidence item sits in the agent flow.

ContextTokenBudget(max_tokens=None, estimated_tokens=None, reserved_output_tokens=None) dataclass

Token budget allocated to one context pack.

ContextHealthSignal(id, symptom, manifest_ref=None, pack_id=None, evidence_ref=None, score=None, observed_at=None, metadata=dict()) dataclass

Observed context rot signal used to choose optimization actions.

evidence_payload()

Return JSON-compatible signal metadata for append-only evidence.

Source code in core/spakky-agent/src/spakky/agent/context.py
def evidence_payload(self) -> Mapping[str, JsonValue]:
    """Return JSON-compatible signal metadata for append-only evidence."""
    return {
        "id": self.id,
        "symptom": self.symptom.value,
        "manifest_ref": self.manifest_ref,
        "pack_id": self.pack_id,
        "evidence_ref": self.evidence_ref,
        "score": self.score,
        "observed_at": self.observed_at.isoformat()
        if self.observed_at is not None
        else None,
        "metadata": self.metadata,
    }

ContextOptimizationAction(id, kind, signal_refs=tuple(), target_pack_ids=tuple(), manifest_ref=None, digest_ref=None, delegation_ref=None, result_evidence_ref=None, reason=None, metadata=dict()) dataclass

Selected optimization action derived from context health signals.

evidence_payload()

Return JSON-compatible action metadata without raw context contents.

Source code in core/spakky-agent/src/spakky/agent/context.py
def evidence_payload(self) -> Mapping[str, JsonValue]:
    """Return JSON-compatible action metadata without raw context contents."""
    return {
        "id": self.id,
        "kind": self.kind.value,
        "signal_refs": tuple(self.signal_refs),
        "target_pack_ids": tuple(self.target_pack_ids),
        "manifest_ref": self.manifest_ref,
        "digest_ref": self.digest_ref,
        "delegation_ref": self.delegation_ref,
        "result_evidence_ref": self.result_evidence_ref,
        "reason": self.reason,
        "metadata": self.metadata,
    }

IAgentContextHandler

Bases: ABC

Select context optimization actions from health signals and manifests.

select_optimization_actions(signals, manifest) abstractmethod

Return optimization actions without mutating raw evidence.

Source code in core/spakky-agent/src/spakky/agent/context.py
@abstractmethod
def select_optimization_actions(
    self,
    signals: Sequence[ContextHealthSignal],
    manifest: "ContextManifest",
) -> Sequence[ContextOptimizationAction]:
    """Return optimization actions without mutating raw evidence."""
    ...

ContextPlacement

Bases: StrEnum

Where a context pack sits in the assembled model prompt.

A stable prompt prefix is what lets a provider reuse its prompt cache. Packs that stay the same for a whole run belong before the conversation history; packs that change each step belong after it.

SYSTEM = 'system' class-attribute instance-attribute

Joined into the leading system section, after the agent instructions.

PRELUDE = 'prelude' class-attribute instance-attribute

A separate message after the system section and before the history.

TRAILER = 'trailer' class-attribute instance-attribute

A separate message after the history (the default).

ContextPack(id, content, source, role, freshness=ContextFreshness.UNKNOWN, relevance=None, token_budget=ContextTokenBudget(), sensitivity=ContextSensitivity.INTERNAL, sensitive_fields=(), metadata=dict(), placement=ContextPlacement.TRAILER) dataclass

LLM-facing context unit derived from state, signal, or evidence.

guarded_content(policy=None)

Return deterministic model-safe content for this context pack.

Source code in core/spakky-agent/src/spakky/agent/context.py
def guarded_content(
    self,
    policy: ContextExposurePolicy | None = None,
) -> str:
    """Return deterministic model-safe content for this context pack."""
    exposure_policy = policy or ContextExposurePolicy()
    if self.sensitivity == ContextSensitivity.REDACTED:
        return "[REDACTED]"
    guarded = guard_json_value(
        {"content": self.content},
        tuple(
            SensitiveFieldDescriptor(
                ("content", *descriptor.path), descriptor.field
            )
            for descriptor in self.sensitive_fields
        ),
        exposure_policy,
    )
    content = cast(Mapping[str, JsonValue], guarded).get("content")
    if isinstance(content, str):
        return content
    return "[REDACTED]"

message_metadata(policy=None)

Return non-content metadata for provider-neutral model messages.

Source code in core/spakky-agent/src/spakky/agent/context.py
def message_metadata(
    self,
    policy: ContextExposurePolicy | None = None,
) -> Mapping[str, JsonValue]:
    """Return non-content metadata for provider-neutral model messages."""
    exposure_policy = policy or ContextExposurePolicy()
    metadata: dict[str, JsonValue] = {
        "context_pack_id": self.id,
        "source": self.source,
        "role": self.role.value,
        "freshness": self.freshness.value,
        "relevance": self.relevance,
        "token_budget": {
            "max_tokens": self.token_budget.max_tokens,
            "estimated_tokens": self.token_budget.estimated_tokens,
            "reserved_output_tokens": self.token_budget.reserved_output_tokens,
        },
        "sensitivity": self.sensitivity.value,
        "metadata": self.metadata,
    }
    if exposure_policy.include_sensitive_context_metadata and self.sensitive_fields:
        metadata["sensitive_fields"] = tuple(
            descriptor.to_metadata() for descriptor in self.sensitive_fields
        )
    return metadata

ContextManifestEntry(pack_id, source, role, origin_ref, evidence_ref=None, digest_ref=None, sensitive_fields=(), metadata=dict()) dataclass

One audited pack entry inside a context manifest.

ContextManifest(id, entries, origin_ref=None, evidence_refs=tuple(), created_at=None, metadata=dict()) dataclass

Auditable composition record for model input context packs.

ContextDigest(id, context_identity, source_manifest_ref, digest, derived_from_pack_ids=tuple(), compression_evidence_ref=None, algorithm=None, summary=None, created_at=None, metadata=dict()) dataclass

Derived compression evidence for a context identity.

AgentContext(packs=(), manifest=None, digest=None) dataclass

Typed context supplied statically or by one injected provider.

IAgentContextProvider

Bases: ABC

Optional async port that supplies context for one model step.

provide(run_input, model_step) abstractmethod async

Return context for the 1-based model step.

Source code in core/spakky-agent/src/spakky/agent/context.py
@abstractmethod
async def provide(
    self,
    run_input: "RunAgentInput",
    model_step: int,
) -> AgentContext:
    """Return context for the 1-based model step."""
    ...

combine_agent_contexts(static, dynamic)

Combine static and dynamic context, validating exact provenance coverage.

Source code in core/spakky-agent/src/spakky/agent/context.py
def combine_agent_contexts(
    static: AgentContext,
    dynamic: AgentContext | None,
) -> AgentContext:
    """Combine static and dynamic context, validating exact provenance coverage."""
    contexts = (static,) if dynamic is None else (static, dynamic)
    envelopes = tuple(_validated_envelope(context) for context in contexts)
    packs = tuple(pack for context, _, _ in envelopes for pack in context.packs)
    pack_ids = tuple(pack.id for pack in packs)
    if len(set(pack_ids)) != len(pack_ids):
        raise AgentDefinitionError("Agent context pack ids must be unique")
    populated = tuple(envelope for envelope in envelopes if envelope[0].packs)
    if len(populated) == 0:
        manifest = None
        digest = None
    elif len(populated) == 1:
        _, manifest, digest = populated[0]
    else:
        if any(digest is not None for _, _, digest in populated):
            raise AgentDefinitionError(
                "Agent context cannot compose partial context digests"
            )
        component_manifests = tuple(
            manifest for _, manifest, _ in populated if manifest is not None
        )
        manifest = _composite_manifest(component_manifests, packs)
        digest = None
    return AgentContext(packs=packs, manifest=manifest, digest=digest)

prepare_agent_context(context)

Return model-safe budgeted packs without mutating caller-owned context.

Source code in core/spakky-agent/src/spakky/agent/context.py
def prepare_agent_context(context: AgentContext) -> AgentContext:
    """Return model-safe budgeted packs without mutating caller-owned context."""
    prepared = tuple(_prepare_pack(pack) for pack in context.packs)
    manifest = context.manifest
    if manifest is not None:
        component_refs = manifest.metadata.get("component_manifest_refs", ())
        safe_metadata: JsonObject = {}
        if (
            isinstance(component_refs, Sequence)
            and not isinstance(component_refs, str | bytes)
            and len(component_refs) > 0
            and all(isinstance(item, str) for item in component_refs)
        ):
            safe_metadata = {"component_manifest_refs": tuple(component_refs)}
        manifest = replace(
            manifest,
            entries=tuple(
                replace(entry, sensitive_fields=(), metadata={})
                for entry in manifest.entries
            ),
            metadata=safe_metadata,
        )
    digest = context.digest
    if digest is not None:
        digest = replace(digest, summary=None, metadata={})
    return AgentContext(packs=prepared, manifest=manifest, digest=digest)

Retrieval

Minimal retrieval contracts for classic and agentic RAG.

RetrievalHit(id, content, source, score=None, rerank_score=None, content_digest=None, revision=None, tenant_id=None, namespace=None, start_offset=None, end_offset=None, metadata=dict()) dataclass

One retrieved model-facing text result with typed provenance.

IRetriever

Bases: ABC

Async retrieval port shared by context and tool adapters.

retrieve(query, *, limit, tenant_id, namespace, filters) abstractmethod async

Return ordered retrieval hits for one scoped query.

Source code in core/spakky-agent/src/spakky/agent/retrieval.py
@abstractmethod
async def retrieve(
    self,
    query: str,
    *,
    limit: int,
    tenant_id: str | None,
    namespace: str | None,
    filters: JsonObject,
) -> Sequence[RetrievalHit]:
    """Return ordered retrieval hits for one scoped query."""
    ...

RetrievalContext(retriever, limit=5, max_context_tokens=2048, allow_empty=False, tenant_id=None, namespace=None, filters=dict()) dataclass

Bases: IAgentContextProvider

Classic RAG adapter exposing retrieval as typed model context.

RetrievalTool(retriever, *, name='search', limit=5, tenant_id=None, namespace=None, filters=None)

Bases: IAgentToolProvider

Agentic RAG component contributing one retrieval tool.

Source code in core/spakky-agent/src/spakky/agent/retrieval.py
def __init__(
    self,
    retriever: IRetriever,
    *,
    name: str = "search",
    limit: int = 5,
    tenant_id: str | None = None,
    namespace: str | None = None,
    filters: JsonObject | None = None,
) -> None:
    _require_framing_text(name, "Retrieval tool name")
    limit = _positive_limit(limit, "Retrieval tool limit")
    _validate_scope(tenant_id, namespace)
    self._retriever = retriever
    self._name = name
    self._limit = limit
    self._tenant_id = tenant_id
    self._namespace = namespace
    self._filters = _snapshot_filters({} if filters is None else filters)

    async def invoke(query: str) -> list[_RetrievalToolHit]:
        return await self._invoke(query)

    definition = AgentToolDefinition(
        name=name,
        schema_name=name,
        description="Search scoped retrieval context.",
        metadata=AgentToolMetadata(
            effects=ToolEffects.read_only(),
            idempotency=Idempotency.IDEMPOTENT,
            evidence=EvidenceCapture.STRUCTURED,
            approval=ToolApprovalRequirement.NOT_REQUIRED,
        ),
    )
    self._tool_catalog = AgentToolCatalog(
        descriptors=(_build_descriptor(type(self), invoke, definition),)
    )

Memory

Typed, scoped long-term memory contracts over the retrieval boundary.

MemoryKind

Bases: StrEnum

Long-term memory meanings exposed independently from storage backends.

MemoryEntry(id, kind, content, source, revision, content_digest, tenant_id, user_id, namespace, created_at, expires_at=None, supersedes=None) dataclass

One immutable, provenance-bound long-term memory revision.

ttl property

Return the declared lifetime, or None for non-expiring memory.

__post_init__()

Reject entries that cannot be safely scoped or versioned.

Source code in core/spakky-agent/src/spakky/agent/memory.py
def __post_init__(self) -> None:
    """Reject entries that cannot be safely scoped or versioned."""
    for value, label in (
        (self.id, "Memory entry id must be nonblank single-line text"),
        (self.source, "Memory source must be nonblank single-line text"),
        (self.revision, "Memory revision must be nonblank single-line text"),
        (
            self.content_digest,
            "Memory content digest must be nonblank single-line text",
        ),
        (self.tenant_id, "Memory tenant id must be nonblank single-line text"),
        (self.user_id, "Memory user id must be nonblank single-line text"),
        (self.namespace, "Memory namespace must be nonblank single-line text"),
    ):
        _MemoryValidation.definition_text(value, label)
    if not isinstance(self.kind, MemoryKind):
        raise AgentDefinitionError("Memory kind is invalid")
    if not isinstance(self.content, str) or not self.content.strip():
        raise AgentDefinitionError("Memory content cannot be blank")
    _MemoryValidation.definition_timestamp(
        self.created_at,
        "Memory created time must be timezone-aware",
    )
    if self.expires_at is not None:
        _MemoryValidation.definition_timestamp(
            self.expires_at,
            "Memory expiry time must be timezone-aware",
        )
        if self.expires_at <= self.created_at:
            raise AgentDefinitionError(
                "Memory expiry time must be after its created time"
            )
    if self.supersedes is not None:
        _MemoryValidation.definition_text(
            self.supersedes,
            "Superseded memory id must be nonblank single-line text",
        )
        if self.supersedes == self.id:
            raise AgentDefinitionError("Memory cannot supersede itself")

is_expired(at=None)

Check expiry at a deterministic point, defaulting to current UTC time.

Source code in core/spakky-agent/src/spakky/agent/memory.py
def is_expired(self, at: datetime | None = None) -> bool:
    """Check expiry at a deterministic point, defaulting to current UTC time."""
    point = datetime.now(UTC) if at is None else at
    _MemoryValidation.runtime_timestamp(
        point,
        "Memory expiry check time must be timezone-aware",
    )
    return self.expires_at is not None and self.expires_at <= point

IMemoryStore

Bases: ABC

Backend-replaceable long-term memory persistence port.

Implementations must omit explicitly deleted entries from search. MemoryRetriever additionally removes expired and superseded revisions.

save(entry) abstractmethod async

Persist one immutable revision, including correction linkage.

Source code in core/spakky-agent/src/spakky/agent/memory.py
@abstractmethod
async def save(self, entry: MemoryEntry) -> None:
    """Persist one immutable revision, including correction linkage."""
    ...

search(query, *, limit, tenant_id, user_id, namespace, kinds, filters) abstractmethod async

Return ordered, undeleted candidates for one exact scope.

Source code in core/spakky-agent/src/spakky/agent/memory.py
@abstractmethod
async def search(
    self,
    query: str,
    *,
    limit: int,
    tenant_id: str,
    user_id: str,
    namespace: str,
    kinds: tuple[MemoryKind, ...],
    filters: JsonObject,
) -> Sequence[MemoryEntry]:
    """Return ordered, undeleted candidates for one exact scope."""
    ...

delete(entry_id, *, tenant_id, user_id, namespace) abstractmethod async

Explicitly delete one memory entry inside its exact scope.

Source code in core/spakky-agent/src/spakky/agent/memory.py
@abstractmethod
async def delete(
    self,
    entry_id: str,
    *,
    tenant_id: str,
    user_id: str,
    namespace: str,
) -> None:
    """Explicitly delete one memory entry inside its exact scope."""
    ...

MemoryRetriever(store, *, tenant_id, user_id, namespace, kinds=tuple(MemoryKind))

Bases: IRetriever

Bind the missing user dimension before exposing memory as retrieval.

Source code in core/spakky-agent/src/spakky/agent/memory.py
def __init__(
    self,
    store: IMemoryStore,
    *,
    tenant_id: str,
    user_id: str,
    namespace: str,
    kinds: tuple[MemoryKind, ...] = tuple(MemoryKind),
) -> None:
    if not isinstance(store, IMemoryStore):
        raise AgentDefinitionError("Memory retriever requires an IMemoryStore")
    for value, label in (
        (tenant_id, "Memory tenant id must be nonblank single-line text"),
        (user_id, "Memory user id must be nonblank single-line text"),
        (namespace, "Memory namespace must be nonblank single-line text"),
    ):
        _MemoryValidation.definition_text(value, label)
    if not isinstance(kinds, tuple) or not kinds:
        raise AgentDefinitionError("Memory retriever kinds cannot be empty")
    if any(not isinstance(kind, MemoryKind) for kind in kinds):
        raise AgentDefinitionError("Memory retriever kind is invalid")
    if len(set(kinds)) != len(kinds):
        raise AgentDefinitionError("Memory retriever kinds must be unique")
    self._store = store
    self._tenant_id = tenant_id
    self._user_id = user_id
    self._namespace = namespace
    self._kinds = kinds

retrieve(query, *, limit, tenant_id, namespace, filters) async

Retrieve active memory without weakening its bound user scope.

Source code in core/spakky-agent/src/spakky/agent/memory.py
@override
async def retrieve(
    self,
    query: str,
    *,
    limit: int,
    tenant_id: str | None,
    namespace: str | None,
    filters: JsonObject,
) -> Sequence[RetrievalHit]:
    """Retrieve active memory without weakening its bound user scope."""
    if not isinstance(query, str) or not query.strip():
        raise AgentMemoryError("Memory retrieval query must be nonblank text")
    if isinstance(limit, bool) or not isinstance(limit, int) or limit <= 0:
        raise AgentMemoryError("Memory retrieval limit must be positive")
    if tenant_id != self._tenant_id or namespace != self._namespace:
        raise AgentMemoryError("Memory retrieval scope does not match its binding")
    copied_filters = _MemoryValidation.json_object(filters)
    entries = await self._store.search(
        query,
        limit=limit,
        tenant_id=self._tenant_id,
        user_id=self._user_id,
        namespace=self._namespace,
        kinds=self._kinds,
        filters=copied_filters,
    )
    return self._active_hits(entries, limit=limit, at=datetime.now(UTC))

Evaluation

Pure offline agent evaluation contracts and deterministic built-ins.

AgentEvaluationCase(id, expected_tool_calls=(), output_type=None, expected_output=None, expected_citations=()) dataclass

One offline case containing only explicit evaluator expectations.

__post_init__()

Validate all case expectations before any sample is scored.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Validate all case expectations before any sample is scored."""
    _EvaluationValidation.text(
        self.id,
        "Agent evaluation case id must be nonblank single-line text",
    )
    object.__setattr__(
        self,
        "expected_tool_calls",
        _EvaluationValidation.tool_calls(self.expected_tool_calls),
    )
    _EvaluationValidation.references(
        self.expected_citations,
        "Agent evaluation citations must be a tuple",
    )
    if self.output_type is None:
        if self.expected_output is not None:
            raise AgentDefinitionError(
                "Expected structured output requires an output type"
            )
        return
    if not isinstance(self.output_type, type):
        raise AgentDefinitionError("Agent evaluation output type must be a class")
    contract = _structured_output_contract(self.output_type)
    if self.expected_output is not None:
        expected_output = _json_value(self.expected_output)
        contract.materialize(expected_output)
        object.__setattr__(
            self,
            "expected_output",
            _freeze_json(expected_output),
        )

AgentEvaluationDataset(id, cases) dataclass

Ordered set of unique offline evaluation cases.

__post_init__()

Reject empty, mutable-shaped, or ambiguous datasets.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject empty, mutable-shaped, or ambiguous datasets."""
    _EvaluationValidation.text(
        self.id,
        "Agent evaluation dataset id must be nonblank single-line text",
    )
    if not isinstance(self.cases, tuple) or not self.cases:
        raise AgentDefinitionError("Agent evaluation dataset cannot be empty")
    if any(not isinstance(case, AgentEvaluationCase) for case in self.cases):
        raise AgentDefinitionError(
            "Agent evaluation dataset contains an invalid case"
        )
    case_ids = tuple(case.id for case in self.cases)
    if len(set(case_ids)) != len(case_ids):
        raise AgentDefinitionError("Agent evaluation case ids must be unique")

AgentEvaluationSample(id, case_ref, structured_output=None, tool_calls=(), citations=(), retrieval_refs=()) dataclass

Observed output and trace for exactly one offline case.

__post_init__()

Validate sample correlations and reference-only grounding inputs.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Validate sample correlations and reference-only grounding inputs."""
    _EvaluationValidation.text(
        self.id,
        "Agent evaluation sample id must be nonblank single-line text",
    )
    _EvaluationValidation.text(
        self.case_ref,
        "Agent evaluation sample case reference must be nonblank single-line text",
    )
    object.__setattr__(
        self,
        "tool_calls",
        _EvaluationValidation.tool_calls(self.tool_calls),
    )
    object.__setattr__(
        self,
        "structured_output",
        _snapshot_json(self.structured_output),
    )
    _EvaluationValidation.references(
        self.citations,
        "Agent evaluation citations must be a tuple",
    )
    _EvaluationValidation.references(
        self.retrieval_refs,
        "Agent evaluation retrieval references must be a tuple",
    )

AgentEvaluationResult(evaluator, metric, passed, score, case_ref, sample_ref) dataclass

One bounded metric result for one explicit case/sample pair.

__post_init__()

Reject results that cannot be compared or safely evidenced.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject results that cannot be compared or safely evidenced."""
    for value, message in (
        (
            self.evaluator,
            "Agent evaluator name must be nonblank single-line text",
        ),
        (
            self.metric,
            "Agent evaluation metric must be nonblank single-line text",
        ),
        (
            self.case_ref,
            "Agent evaluation case reference must be nonblank single-line text",
        ),
        (
            self.sample_ref,
            "Agent evaluation sample reference must be nonblank single-line text",
        ),
    ):
        _EvaluationValidation.text(value, message)
    if not isinstance(self.passed, bool):
        raise AgentDefinitionError("Agent evaluation pass value must be boolean")
    _EvaluationValidation.score(self.score)

to_evidence_candidate()

Project the metric to privacy-safe append-only evaluation evidence.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def to_evidence_candidate(self) -> AgentEvidenceCandidate:
    """Project the metric to privacy-safe append-only evaluation evidence."""
    return AgentEvidenceCandidate.evaluation(
        evaluator=self.evaluator,
        metric=self.metric,
        passed=self.passed,
        score=self.score,
        case_ref=self.case_ref,
        sample_ref=self.sample_ref,
    )

AgentEvaluationReport(dataset_ref, results) dataclass

Deterministically ordered results for one dataset evaluation.

passed property

Return whether every metric passed.

score property

Return the unweighted mean across the explicit metric results.

__post_init__()

Reject reports without an attributable metric result.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject reports without an attributable metric result."""
    _EvaluationValidation.text(
        self.dataset_ref,
        "Agent evaluation dataset reference must be nonblank single-line text",
    )
    if not isinstance(self.results, tuple) or not self.results:
        raise AgentDefinitionError("Agent evaluation report cannot be empty")
    if any(
        not isinstance(result, AgentEvaluationResult) for result in self.results
    ):
        raise AgentDefinitionError(
            "Agent evaluation report contains an invalid result"
        )

evidence_candidates()

Return privacy-safe evidence without raw outputs, prompts, or context.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def evidence_candidates(self) -> tuple[AgentEvidenceCandidate, ...]:
    """Return privacy-safe evidence without raw outputs, prompts, or context."""
    return tuple(result.to_evidence_candidate() for result in self.results)

IAgentEvaluator

Bases: ABC

Replaceable offline evaluator over an explicit case/sample pair.

name abstractmethod property

Return the stable evaluator identity used in reports and evidence.

evaluate(case, sample) abstractmethod async

Evaluate exactly one already-correlated case/sample pair.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
@abstractmethod
async def evaluate(
    self,
    case: AgentEvaluationCase,
    sample: AgentEvaluationSample,
) -> Sequence[AgentEvaluationResult]:
    """Evaluate exactly one already-correlated case/sample pair."""
    ...

IModelJudge

Bases: ABC

Optional externally supplied model-judge port with no default backend.

judge(case, sample) abstractmethod async

Return a bounded score without implying a network or model fallback.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
@abstractmethod
async def judge(
    self,
    case: AgentEvaluationCase,
    sample: AgentEvaluationSample,
) -> float:
    """Return a bounded score without implying a network or model fallback."""
    ...

AgentEvaluationSuite(evaluators) dataclass

Sequentially evaluate explicit samples in dataset and evaluator order.

__post_init__()

Reject suites whose evaluator order or identity is ambiguous.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject suites whose evaluator order or identity is ambiguous."""
    if not isinstance(self.evaluators, tuple) or not self.evaluators:
        raise AgentDefinitionError("Agent evaluation suite cannot be empty")
    if any(
        not isinstance(evaluator, IAgentEvaluator) for evaluator in self.evaluators
    ):
        raise AgentDefinitionError(
            "Agent evaluation suite contains an invalid evaluator"
        )
    names = tuple(evaluator.name for evaluator in self.evaluators)
    for name in names:
        _EvaluationValidation.text(
            name,
            "Agent evaluator name must be nonblank single-line text",
        )
    if len(set(names)) != len(names):
        raise AgentDefinitionError("Agent evaluator names must be unique")

evaluate(dataset, samples) async

Pair one explicit sample per case and preserve deterministic ordering.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
async def evaluate(
    self,
    dataset: AgentEvaluationDataset,
    samples: tuple[AgentEvaluationSample, ...],
) -> AgentEvaluationReport:
    """Pair one explicit sample per case and preserve deterministic ordering."""
    if not isinstance(dataset, AgentEvaluationDataset):
        raise AgentDefinitionError("Agent evaluation dataset is invalid")
    if not isinstance(samples, tuple) or any(
        not isinstance(sample, AgentEvaluationSample) for sample in samples
    ):
        raise AgentDefinitionError("Agent evaluation samples must be a tuple")
    sample_by_case = {sample.case_ref: sample for sample in samples}
    if len(sample_by_case) != len(samples):
        raise AgentDefinitionError(
            "Agent evaluation samples must be unique per case"
        )
    case_ids = tuple(case.id for case in dataset.cases)
    if set(sample_by_case) != set(case_ids):
        raise AgentDefinitionError(
            "Agent evaluation samples must exactly cover the dataset"
        )
    results: list[AgentEvaluationResult] = []
    for case in dataset.cases:
        sample = sample_by_case[case.id]
        for evaluator in self.evaluators:
            evaluated = await evaluator.evaluate(case, sample)
            self._append_validated_results(
                results,
                evaluated,
                evaluator=evaluator,
                case=case,
                sample=sample,
            )
    return AgentEvaluationReport(dataset_ref=dataset.id, results=tuple(results))

ToolTraceEvaluator() dataclass

Bases: IAgentEvaluator

Score exact ordered tool names and arguments while ignoring call ids.

StructuredOutputEvaluator() dataclass

Bases: IAgentEvaluator

Validate strict structured output and optional exact expected content.

CitationEvaluator(minimum_precision=1.0, minimum_recall=1.0) dataclass

Bases: IAgentEvaluator

Calculate exact reference precision and recall.

__post_init__()

Validate both configured metric thresholds.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Validate both configured metric thresholds."""
    _EvaluationValidation.threshold(self.minimum_precision)
    _EvaluationValidation.threshold(self.minimum_recall)

RetrievalGroundednessEvaluator(minimum_score=1.0) dataclass

Bases: IAgentEvaluator

Score the fraction of cited references present in retrieved evidence.

__post_init__()

Validate the configured groundedness threshold.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Validate the configured groundedness threshold."""
    _EvaluationValidation.threshold(self.minimum_score)

ModelJudgeEvaluator(judge, metric='model_judge', minimum_score=0.5, evaluator_name='model_judge') dataclass

Bases: IAgentEvaluator

Wrap one explicitly supplied model judge without a default provider.

__post_init__()

Reject an absent judge or ambiguous metric configuration.

Source code in core/spakky-agent/src/spakky/agent/evaluation.py
def __post_init__(self) -> None:
    """Reject an absent judge or ambiguous metric configuration."""
    if not isinstance(self.judge, IModelJudge):
        raise AgentDefinitionError("Model judge evaluator requires an IModelJudge")
    _EvaluationValidation.text(
        self.metric,
        "Model judge metric must be nonblank single-line text",
    )
    _EvaluationValidation.text(
        self.evaluator_name,
        "Model judge evaluator name must be nonblank single-line text",
    )
    _EvaluationValidation.threshold(self.minimum_score)

Cost

Operator-owned model pricing and deterministic token-cost calculation.

AgentPricingError

Bases: AbstractSpakkyAgentError

Raised when model cost cannot be calculated from trusted inputs.

ModelPrice(input_per_million, output_per_million, cached_input_per_million=None, cache_write_input_per_million=None, cache_write_5m_input_per_million=None, cache_write_1h_input_per_million=None) dataclass

Per-million-token rates for one operator catalog model reference.

ModelCost(model_ref, amount, currency, pricing_version, input_tokens, output_tokens, cached_input_tokens=0, cache_write_input_tokens=0, cache_write_5m_input_tokens=0, cache_write_1h_input_tokens=0) dataclass

Exact cost calculated for one model step.

ModelPricingCatalog(version, prices, currency='USD', metadata=dict()) dataclass

Versioned operator pricing keyed by opaque logical model reference.

fingerprint property

Return a stable digest binding version, currency, and every rate.

calculate(model_ref, usage)

Calculate exact step cost or fail when required usage is unavailable.

Source code in core/spakky-agent/src/spakky/agent/cost.py
def calculate(self, model_ref: str, usage: ModelUsage) -> ModelCost:
    """Calculate exact step cost or fail when required usage is unavailable."""
    _require_text(model_ref)
    price = self.prices.get(model_ref)
    if price is None:
        raise AgentPricingError
    input_tokens = _usage_tokens(usage.input_tokens)
    output_tokens = _usage_tokens(usage.output_tokens)
    cached_input_tokens = _usage_tokens(usage.cached_input_tokens, default=0)
    cache_write_input_tokens = _usage_tokens(
        usage.cache_write_input_tokens,
        default=0,
    )
    cache_write_5m_input_tokens = _usage_tokens(
        usage.cache_write_5m_input_tokens,
        default=0,
    )
    cache_write_1h_input_tokens = _usage_tokens(
        usage.cache_write_1h_input_tokens,
        default=0,
    )
    categorized_cache_write = (
        usage.cache_write_5m_input_tokens is not None
        or usage.cache_write_1h_input_tokens is not None
    )
    if (
        cache_write_input_tokens > 0
        and not categorized_cache_write
        and (
            price.cache_write_5m_input_per_million is not None
            or price.cache_write_1h_input_per_million is not None
        )
    ):
        raise AgentPricingError
    if cached_input_tokens + cache_write_input_tokens > input_tokens:
        raise AgentPricingError
    if categorized_cache_write and (
        cache_write_5m_input_tokens + cache_write_1h_input_tokens
        != cache_write_input_tokens
    ):
        raise AgentPricingError
    regular_input_tokens = (
        input_tokens - cached_input_tokens - cache_write_input_tokens
    )
    cached_rate = (
        price.cached_input_per_million
        if price.cached_input_per_million is not None
        else price.input_per_million
    )
    cache_write_rate = (
        price.cache_write_input_per_million
        if price.cache_write_input_per_million is not None
        else price.input_per_million
    )
    cache_write_5m_rate = (
        price.cache_write_5m_input_per_million
        if price.cache_write_5m_input_per_million is not None
        else cache_write_rate
    )
    cache_write_1h_rate = (
        price.cache_write_1h_input_per_million
        if price.cache_write_1h_input_per_million is not None
        else cache_write_rate
    )
    cache_write_amount = (
        Decimal(cache_write_5m_input_tokens) * cache_write_5m_rate
        + Decimal(cache_write_1h_input_tokens) * cache_write_1h_rate
        if categorized_cache_write
        else Decimal(cache_write_input_tokens) * cache_write_rate
    )
    amount = (
        Decimal(regular_input_tokens) * price.input_per_million
        + Decimal(cached_input_tokens) * cached_rate
        + cache_write_amount
        + Decimal(output_tokens) * price.output_per_million
    ) / _TOKENS_PER_MILLION
    return ModelCost(
        model_ref=model_ref,
        amount=amount,
        currency=self.currency,
        pricing_version=self.version,
        input_tokens=input_tokens,
        output_tokens=output_tokens,
        cached_input_tokens=cached_input_tokens,
        cache_write_input_tokens=cache_write_input_tokens,
        cache_write_5m_input_tokens=cache_write_5m_input_tokens,
        cache_write_1h_input_tokens=cache_write_1h_input_tokens,
    )

Telemetry

Privacy-safe telemetry records emitted by the standard Agent runtime.

AgentSpanKind

Bases: StrEnum

Stable operation families emitted by AgentRunner.

AgentSpanStatus

Bases: StrEnum

Terminal status of one completed operation record.

AgentTelemetryError

Bases: AbstractSpakkyAgentError

Raised when an injected telemetry adapter cannot record a span.

AgentSpanRecord(name, kind, started_at_ns, ended_at_ns, attributes=dict(), status=AgentSpanStatus.OK, error_code=None) dataclass

Completed span data containing scalar metadata but no prompt payloads.

IAgentTelemetry

Bases: ABC

Optional outbound port receiving completed privacy-safe Agent spans.

record(span) abstractmethod

Record one completed span without changing Agent execution.

Source code in core/spakky-agent/src/spakky/agent/telemetry.py
@abstractmethod
def record(self, span: AgentSpanRecord) -> None:
    """Record one completed span without changing Agent execution."""
    ...

Compaction

Pluggable context-compaction strategies (ADR-0013 §7).

A long conversation eventually outgrows a model backend's context window. The framework runner owns when to compact (ADR-0013 §1 declarative loop ownership); this module owns how. ICompactionStrategy is the provider-neutral port a developer declares in an @Agent spec, and the runner applies the declared chain to the resolved history before each model request once the running token estimate crosses the policy threshold.

The port shape follows pydantic-ai's message-history processor / ProcessHistory capability: a processor receives the message list (plus run context such as token usage) and returns a transformed list. Here the contextual inputs are made explicit parameters — the running ModelUsage and the backend ModelCapability — so a strategy decides how aggressively to compact from the same signals the runner uses to decide whether to compact. Strategies are pure transforms over tuple[ModelMessage, ...] and compose by sequential application, so a chain of strategies is just each applied to the previous one's output.

SUMMARY_MESSAGE_METADATA_KEY = 'compaction' module-attribute

Metadata flag marking a message the summarize strategy synthesized.

SUMMARY_MESSAGE_METADATA_VALUE = 'summary' module-attribute

Metadata value identifying a synthesized transcript summary message.

DEFAULT_SUMMARY_INSTRUCTION = 'Summarize the earlier conversation turns below into a concise briefing that preserves decisions, facts, and open questions. Reply with the summary only.' module-attribute

Fallback instruction for the secondary model that summarizes old turns.

ICompactionStrategy

Bases: ABC

Provider-neutral context-compaction transform applied before a request.

A strategy maps a resolved history to a shorter one, reading the running ModelUsage and backend ModelCapability so it can scale its effect to how close the run is to the context limit. Implementations are pure transforms — they never mutate the input — so the runner can apply a declared chain by threading each strategy's output into the next.

compact(history, usage, capability) abstractmethod async

Return a compacted view of history for the next model request.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
@abstractmethod
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Return a compacted view of ``history`` for the next model request."""
    ...

KeepRecentMessagesCompactionStrategy(max_messages) dataclass

Bases: ICompactionStrategy

Sliding-window strategy that keeps only the most recent messages.

The cheapest compaction: drop the oldest messages and keep the last max_messages. It carries no model dependency, so it is the safe default tail of a chain that bounds history length regardless of content.

__post_init__()

Reject a window that would keep no messages.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
def __post_init__(self) -> None:
    """Reject a window that would keep no messages."""
    if self.max_messages <= 0:
        raise AgentDefinitionError(
            "Keep-recent compaction window must keep at least one message"
        )

compact(history, usage, capability) async

Keep the recent window without splitting a tool invocation group.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Keep the recent window without splitting a tool invocation group."""
    start = _recent_group_start(history, self.max_messages)
    return history[start:]

TrimToolResultsCompactionStrategy(max_characters) dataclass

Bases: ICompactionStrategy

Truncate verbose tool-result messages while preserving the dialogue.

Tool results (search dumps, file contents) dominate token cost yet rarely need to be replayed verbatim. This strategy truncates only TOOL role message content past max_characters and leaves the user/assistant turns untouched, so the model still sees that a tool ran and a clipped head of its output.

__post_init__()

Reject a non-positive truncation budget.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
def __post_init__(self) -> None:
    """Reject a non-positive truncation budget."""
    if self.max_characters <= 0:
        raise AgentDefinitionError(
            "Tool-result trim budget must be a positive character count"
        )

compact(history, usage, capability) async

Truncate over-budget tool-result content, leaving other roles intact.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Truncate over-budget tool-result content, leaving other roles intact."""
    return tuple(self._trim(message) for message in history)

ProviderManagedCompactionStrategy() dataclass

Bases: ICompactionStrategy

No-op strategy for backends that manage their own context window.

Some providers compact server-side, so the framework must not also trim the transcript. Declaring this strategy makes that hand-off explicit in the spec rather than leaving compaction silently absent.

compact(history, usage, capability) async

Return the history unchanged — the provider owns compaction.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Return the history unchanged — the provider owns compaction."""
    return history

SummarizeOldTurnsCompactionStrategy(model, keep_recent, summary_instruction=DEFAULT_SUMMARY_INSTRUCTION) dataclass

Bases: ICompactionStrategy

Replace older turns with a model-generated summary, keeping recent ones.

The richest compaction: a secondary model call condenses the turns older than keep_recent into one EVIDENCE summary message that precedes the kept tail. This preserves earlier context as a briefing instead of dropping it, at the cost of one extra model round-trip. When the history is already within keep_recent there is nothing older to summarize, so the call is skipped.

__post_init__()

Reject a window that would leave no recent turns to anchor the summary.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
def __post_init__(self) -> None:
    """Reject a window that would leave no recent turns to anchor the summary."""
    if self.keep_recent <= 0:
        raise AgentDefinitionError(
            "Summarize compaction must keep at least one recent message"
        )
    if not self.summary_instruction.strip():
        raise AgentDefinitionError(
            "Summarize compaction instruction cannot be blank"
        )

compact(history, usage, capability) async

Summarize turns older than keep_recent ahead of the recent tail.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
async def compact(
    self,
    history: tuple[ModelMessage, ...],
    usage: ModelUsage,
    capability: ModelCapability,
) -> tuple[ModelMessage, ...]:
    """Summarize turns older than ``keep_recent`` ahead of the recent tail."""
    start = _recent_group_start(history, self.keep_recent)
    if start == 0:
        return history
    older = history[:start]
    recent = history[start:]
    summary = await self.model.complete(self._summary_request(older))
    return (self._summary_message(summary.content), *recent)

validate_tool_call_groups(history)

Reject orphaned or incomplete assistant/tool correlation groups.

Source code in core/spakky-agent/src/spakky/agent/compaction.py
def validate_tool_call_groups(
    history: tuple[ModelMessage, ...],
) -> tuple[ModelMessage, ...]:
    """Reject orphaned or incomplete assistant/tool correlation groups."""
    _history_groups(history)
    return history

Recovery

Action-boundary recovery contracts for durable agent execution.

AgentActionKind

Bases: StrEnum

Recoverable external action classes in an agent execution.

AgentActionBoundaryStage

Bases: StrEnum

Checkpoint side recorded around an action boundary.

AgentResumeAction

Bases: StrEnum

Orchestration action selected from persisted checkpoint evidence.

AgentActionBoundaryCheckpoint(action_id, action_kind, stage, idempotency=Idempotency.UNKNOWN, metadata=dict()) dataclass

Serializable checkpoint recorded before or after one external action.

__post_init__()

Reject checkpoints that cannot be correlated after restart.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
def __post_init__(self) -> None:
    """Reject checkpoints that cannot be correlated after restart."""
    if not self.action_id.strip():
        raise AgentDefinitionError("Agent action boundary id cannot be blank")

before_model_call(action_id, *, idempotency=Idempotency.UNKNOWN, metadata=None) classmethod

Create the checkpoint recorded before a model call is attempted.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def before_model_call(
    cls,
    action_id: str,
    *,
    idempotency: Idempotency = Idempotency.UNKNOWN,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded before a model call is attempted."""
    return cls._for_action(
        action_id,
        AgentActionKind.MODEL_CALL,
        AgentActionBoundaryStage.BEFORE,
        idempotency=idempotency,
        metadata=metadata,
    )

after_model_call(action_id, *, idempotency=Idempotency.UNKNOWN, metadata=None) classmethod

Create the checkpoint recorded after a model call completes.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def after_model_call(
    cls,
    action_id: str,
    *,
    idempotency: Idempotency = Idempotency.UNKNOWN,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded after a model call completes."""
    return cls._for_action(
        action_id,
        AgentActionKind.MODEL_CALL,
        AgentActionBoundaryStage.AFTER,
        idempotency=idempotency,
        metadata=metadata,
    )

before_tool_call(action_id, *, idempotency, metadata=None) classmethod

Create the checkpoint recorded before a tool call is attempted.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def before_tool_call(
    cls,
    action_id: str,
    *,
    idempotency: Idempotency,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded before a tool call is attempted."""
    return cls._for_action(
        action_id,
        AgentActionKind.TOOL_CALL,
        AgentActionBoundaryStage.BEFORE,
        idempotency=idempotency,
        metadata=metadata,
    )

after_tool_call(action_id, *, idempotency, metadata=None) classmethod

Create the checkpoint recorded after a tool call completes.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def after_tool_call(
    cls,
    action_id: str,
    *,
    idempotency: Idempotency,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded after a tool call completes."""
    return cls._for_action(
        action_id,
        AgentActionKind.TOOL_CALL,
        AgentActionBoundaryStage.AFTER,
        idempotency=idempotency,
        metadata=metadata,
    )

before_approval_wait(action_id, *, metadata=None) classmethod

Create the checkpoint recorded before waiting for approval.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def before_approval_wait(
    cls,
    action_id: str,
    *,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded before waiting for approval."""
    return cls._for_action(
        action_id,
        AgentActionKind.APPROVAL_WAIT,
        AgentActionBoundaryStage.BEFORE,
        idempotency=Idempotency.NON_IDEMPOTENT,
        metadata=metadata,
    )

after_approval_wait(action_id, *, metadata=None) classmethod

Create the checkpoint recorded after an approval wait resolves.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
@classmethod
def after_approval_wait(
    cls,
    action_id: str,
    *,
    metadata: JsonObject | None = None,
) -> "AgentActionBoundaryCheckpoint":
    """Create the checkpoint recorded after an approval wait resolves."""
    return cls._for_action(
        action_id,
        AgentActionKind.APPROVAL_WAIT,
        AgentActionBoundaryStage.AFTER,
        idempotency=Idempotency.NON_IDEMPOTENT,
        metadata=metadata,
    )

to_evidence_candidate(*, summary=None)

Represent this checkpoint as append-only evidence.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
def to_evidence_candidate(
    self,
    *,
    summary: str | None = None,
) -> AgentEvidenceCandidate:
    """Represent this checkpoint as append-only evidence."""
    return AgentEvidenceCandidate(
        kind=AgentEvidenceKind.ACTION_BOUNDARY,
        payload={
            "action_id": self.action_id,
            "action_kind": self.action_kind.value,
            "stage": self.stage.value,
            "idempotency": self.idempotency.value,
            "metadata": self.metadata,
        },
        summary=summary,
    )

AgentResumeBoundary(action_id, action_kind, stage, idempotency, evidence_id) dataclass

Last action boundary reconstructed from append-only evidence.

AgentResumePlan(state, action, boundary=None, signals=()) dataclass

Resume decision derived from persisted state and checkpoint evidence.

requires_human_input property

Return whether automatic replay must stop at HITL recovery.

can_resume_automatically property

Return whether orchestration may continue without approval.

plan_agent_resume(state, evidence, signals=())

Restore the next resume action using only persisted state and evidence.

Source code in core/spakky-agent/src/spakky/agent/recovery.py
def plan_agent_resume(
    state: AgentState,
    evidence: Sequence[AgentEvidence],
    signals: Sequence[AgentSignal] = (),
) -> AgentResumePlan:
    """Restore the next resume action using only persisted state and evidence."""
    persisted_signals = tuple(signals)
    if state.status in (
        AgentStatus.COMPLETED,
        AgentStatus.FAILED,
        AgentStatus.CANCELLED,
    ):
        return AgentResumePlan(
            state=state,
            action=AgentResumeAction.NOT_RESUMABLE,
            signals=persisted_signals,
        )

    boundary = _last_action_boundary(evidence)
    if boundary is None:
        return AgentResumePlan(
            state=state,
            action=AgentResumeAction.START,
            signals=persisted_signals,
        )

    if boundary.stage is AgentActionBoundaryStage.AFTER:
        return AgentResumePlan(
            state=replace(state, recovery_marker=boundary.action_id),
            action=AgentResumeAction.SKIP_COMPLETED,
            boundary=boundary,
            signals=persisted_signals,
        )

    if boundary.action_kind is AgentActionKind.APPROVAL_WAIT:
        return AgentResumePlan(
            state=_interrupt_for_human_recovery(state, boundary),
            action=AgentResumeAction.REQUIRE_HITL,
            boundary=boundary,
            signals=persisted_signals,
        )

    resume_action = ToolResumeMetadata(
        idempotency=boundary.idempotency,
    ).action_for_incomplete_boundary()
    if resume_action is ToolResumeAction.RETRY:
        return AgentResumePlan(
            state=replace(state, recovery_marker=boundary.action_id),
            action=AgentResumeAction.RETRY,
            boundary=boundary,
            signals=persisted_signals,
        )
    return AgentResumePlan(
        state=_interrupt_for_human_recovery(state, boundary),
        action=AgentResumeAction.REQUIRE_HITL,
        boundary=boundary,
        signals=persisted_signals,
    )

Approval

Human-in-the-loop approval workflow contracts.

AgentApprovalBoundaryKind

Bases: StrEnum

Action boundaries where orchestration may require human approval.

AgentApprovalPlanAction

Bases: StrEnum

Approval plan outcome before an action boundary is executed.

AgentApprovalRequest(id, agent_state_id, boundary, prompt, risk, action_ref, allowed_decisions=DEFAULT_APPROVAL_DECISIONS, metadata=dict()) dataclass

Approval request materialized at a risky action boundary.

__post_init__()

Reject approval requests that cannot be matched by a signal.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def __post_init__(self) -> None:
    """Reject approval requests that cannot be matched by a signal."""
    _require_non_blank(self.id, "Agent approval id")
    _require_non_blank(self.agent_state_id, "Agent approval state id")
    _require_non_blank(self.prompt, "Agent approval prompt")
    _require_non_blank(self.action_ref, "Agent approval action ref")
    if len(self.allowed_decisions) == 0:
        raise AgentDefinitionError("Agent approval decisions cannot be empty")

from_tool_descriptor(*, approval_id, agent_state_id, descriptor, prompt=None, action_ref=None, call_id=None, metadata=None) classmethod

Build an approval request from a risky tool descriptor.

Source code in core/spakky-agent/src/spakky/agent/approval.py
@classmethod
def from_tool_descriptor(
    cls,
    *,
    approval_id: str,
    agent_state_id: str,
    descriptor: AgentToolDescriptor,
    prompt: str | None = None,
    action_ref: str | None = None,
    call_id: str | None = None,
    metadata: JsonObject | None = None,
) -> "AgentApprovalRequest":
    """Build an approval request from a risky tool descriptor."""
    request_metadata = _tool_approval_metadata(descriptor, call_id, metadata or {})
    return cls(
        id=approval_id,
        agent_state_id=agent_state_id,
        boundary=AgentApprovalBoundaryKind.TOOL_INVOCATION,
        prompt=prompt or f"Approve tool invocation: {descriptor.name}",
        risk=descriptor.metadata.risk,
        action_ref=action_ref or descriptor.identity.key,
        metadata=request_metadata,
    )

to_state(*, agent_type)

Materialize the approval wait as interrupted lifecycle state.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def to_state(self, *, agent_type: str) -> AgentState:
    """Materialize the approval wait as interrupted lifecycle state."""
    _require_non_blank(agent_type, "Agent approval agent type")
    return AgentState(
        id=self.agent_state_id,
        agent_type=agent_type,
        status=AgentStatus.INTERRUPTED,
        transition=AgentStateTransition.WAITING_APPROVAL,
        reason=AgentStateReason.APPROVAL_REQUIRED,
        current_activity=self.prompt,
        metadata={"approval": self.to_metadata()},
    )

to_yield()

Expose this approval request to an inbound adapter stream.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def to_yield(self) -> AgentYield[Approval]:
    """Expose this approval request to an inbound adapter stream."""
    return AgentYield(
        kind=AgentYieldKind.APPROVAL,
        payload=Approval(
            id=self.id,
            prompt=self.prompt,
            allowed_decisions=self.allowed_decisions,
            metadata=self.to_metadata(),
        ),
    )

to_metadata()

Return JSON-compatible metadata for state, yield, and evidence.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def to_metadata(self) -> JsonObject:
    """Return JSON-compatible metadata for state, yield, and evidence."""
    return {
        "id": self.id,
        "agent_state_id": self.agent_state_id,
        "boundary": self.boundary.value,
        "action_ref": self.action_ref,
        "risk_axes": [axis.value for axis in self.risk.axes],
        "allowed_decisions": [
            decision.value for decision in self.allowed_decisions
        ],
        "metadata": self.metadata,
    }

AgentApprovalPlan(action, request=None, state=None, yield_item=None) dataclass

Plan for an action boundary before executing it.

requires_approval property

Return whether orchestration must wait for a HITL decision.

AgentApprovalDecisionOutcome(request_id, decision, status, transition, reason=None, modified_payload=dict(), comment=None) dataclass

Typed result of an approval decision signal.

plan_agent_tool_approval(*, descriptor, approval_id, agent_state_id, agent_type, prompt=None, action_ref=None, call_id=None, metadata=None)

Plan whether a tool invocation should proceed or wait for approval.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def plan_agent_tool_approval(
    *,
    descriptor: AgentToolDescriptor,
    approval_id: str,
    agent_state_id: str,
    agent_type: str,
    prompt: str | None = None,
    action_ref: str | None = None,
    call_id: str | None = None,
    metadata: JsonObject | None = None,
) -> AgentApprovalPlan:
    """Plan whether a tool invocation should proceed or wait for approval."""
    if not descriptor.metadata.requires_approval_candidate:
        return AgentApprovalPlan(action=AgentApprovalPlanAction.PROCEED)

    request = AgentApprovalRequest.from_tool_descriptor(
        approval_id=approval_id,
        agent_state_id=agent_state_id,
        descriptor=descriptor,
        prompt=prompt,
        action_ref=action_ref,
        call_id=call_id,
        metadata=metadata,
    )
    return AgentApprovalPlan(
        action=AgentApprovalPlanAction.WAIT_FOR_APPROVAL,
        request=request,
        state=request.to_state(agent_type=agent_type),
        yield_item=request.to_yield(),
    )

parse_agent_approval_decision_signal(signal, *, request=None)

Parse an approval decision signal into a typed workflow outcome.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def parse_agent_approval_decision_signal(
    signal: AgentSignal,
    *,
    request: AgentApprovalRequest | None = None,
) -> AgentApprovalDecisionOutcome:
    """Parse an approval decision signal into a typed workflow outcome."""
    if signal.kind != AgentSignalKind.APPROVAL_DECISION:
        raise AgentDefinitionError(
            "Agent approval signal kind must be approval_decision"
        )

    request_id = _require_payload_text(signal.payload, "request_id")
    if request is not None and request_id != request.id:
        raise AgentDefinitionError("Agent approval signal request id does not match")
    if request is not None and signal.agent_state_id != request.agent_state_id:
        raise AgentDefinitionError("Agent approval signal state id does not match")

    decision = _parse_approval_decision(
        _require_payload_text(signal.payload, "decision")
    )
    modified_payload = _payload_object(signal.payload.get("modified_payload", {}))
    comment = _optional_payload_text(signal.payload, "comment")
    status, transition, reason = _decision_state_target(decision)

    return AgentApprovalDecisionOutcome(
        request_id=request_id,
        decision=decision,
        status=status,
        transition=transition,
        reason=reason,
        modified_payload=modified_payload,
        comment=comment,
    )

materialize_agent_approval_decision_state(current, outcome)

Apply a typed approval decision outcome to an existing state snapshot.

Source code in core/spakky-agent/src/spakky/agent/approval.py
def materialize_agent_approval_decision_state(
    current: AgentState,
    outcome: AgentApprovalDecisionOutcome,
) -> AgentState:
    """Apply a typed approval decision outcome to an existing state snapshot."""
    return AgentState(
        id=current.id,
        agent_type=current.agent_type,
        status=outcome.status,
        transition=outcome.transition,
        reason=outcome.reason,
        current_activity=_activity_for_decision(outcome),
        input_ref=current.input_ref,
        output_ref=current.output_ref,
        pending_signal_count=current.pending_signal_count,
        last_event_cursor=current.last_event_cursor,
        recovery_marker=current.recovery_marker,
        metadata={
            **current.metadata,
            "approval_decision": {
                "request_id": outcome.request_id,
                "decision": outcome.decision.value,
                "modified_payload": outcome.modified_payload,
                "comment": outcome.comment,
            },
        },
        created_at=current.created_at,
        updated_at=current.updated_at,
    )

Cancellation

Cancellation lifecycle and cleanup contracts for agent execution.

AgentCancellationCleanupCallable = Callable[[AgentCancellationRequest], Awaitable[AgentCancellationCleanupResult]]

Async hook shape invoked for model stream/tool/delegate cancellation cleanup.

AgentCancellationTargetKind

Bases: StrEnum

Running execution target that can receive a cancellation cleanup hook.

AgentCancellationCleanupStatus

Bases: StrEnum

Outcome of one cancellation cleanup hook.

AgentCancellationRequest(state_id, signal_id, target_kind, target_ref, reason=None, requested_by=None, metadata=dict()) dataclass

Cancellation request passed to a model stream, tool, or delegate hook.

__post_init__()

Reject requests that cannot be traced back to state/signal/target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def __post_init__(self) -> None:
    """Reject requests that cannot be traced back to state/signal/target."""
    _require_non_blank(self.state_id, "Agent cancellation state id")
    _require_non_blank(self.signal_id, "Agent cancellation signal id")
    _require_non_blank(self.target_ref, "Agent cancellation target ref")
    _require_optional_non_blank(self.reason, "Agent cancellation reason")
    _require_optional_non_blank(self.requested_by, "Agent cancellation requester")

from_signal(*, state, signal, target_kind, target_ref, metadata=None) classmethod

Build a hook request from the durable CANCEL signal payload.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
@classmethod
def from_signal(
    cls,
    *,
    state: AgentState,
    signal: AgentSignal,
    target_kind: AgentCancellationTargetKind,
    target_ref: str,
    metadata: JsonObject | None = None,
) -> "AgentCancellationRequest":
    """Build a hook request from the durable CANCEL signal payload."""
    _require_cancel_signal(signal)
    _require_signal_matches_state(state, signal)
    return cls(
        state_id=state.id,
        signal_id=signal.id,
        target_kind=target_kind,
        target_ref=target_ref,
        reason=_optional_string(signal.payload, "reason"),
        requested_by=_optional_string(signal.payload, "requested_by"),
        metadata={} if metadata is None else metadata,
    )

to_payload()

Serialize the request into append-only evidence metadata.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def to_payload(self) -> JsonObject:
    """Serialize the request into append-only evidence metadata."""
    return {
        "state_id": self.state_id,
        "signal_id": self.signal_id,
        "target_kind": self.target_kind.value,
        "target_ref": self.target_ref,
        "reason": self.reason,
        "requested_by": self.requested_by,
        "metadata": self.metadata,
    }

AgentCancellationCleanupResult(target_kind, target_ref, status, reason=None, error_code=None, message=None, metadata=dict()) dataclass

Result returned by one cancellation cleanup hook.

failed_cleanup property

Return whether this hook prevents a clean CANCELLED terminal state.

__post_init__()

Reject outcomes that cannot be correlated with the cleanup target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def __post_init__(self) -> None:
    """Reject outcomes that cannot be correlated with the cleanup target."""
    _require_non_blank(self.target_ref, "Agent cancellation cleanup target ref")
    _require_optional_non_blank(self.reason, "Agent cancellation cleanup reason")
    _require_optional_non_blank(
        self.error_code,
        "Agent cancellation cleanup error code",
    )
    _require_optional_non_blank(self.message, "Agent cancellation cleanup message")

succeeded(*, target_kind, target_ref, reason=None, metadata=None) classmethod

Record a cleanup hook that released its target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
@classmethod
def succeeded(
    cls,
    *,
    target_kind: AgentCancellationTargetKind,
    target_ref: str,
    reason: str | None = None,
    metadata: JsonObject | None = None,
) -> "AgentCancellationCleanupResult":
    """Record a cleanup hook that released its target."""
    return cls(
        target_kind=target_kind,
        target_ref=target_ref,
        status=AgentCancellationCleanupStatus.SUCCEEDED,
        reason=reason,
        metadata={} if metadata is None else metadata,
    )

failed(*, target_kind, target_ref, error_code, message, metadata=None) classmethod

Record a cleanup hook that could not release its target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
@classmethod
def failed(
    cls,
    *,
    target_kind: AgentCancellationTargetKind,
    target_ref: str,
    error_code: str,
    message: str,
    metadata: JsonObject | None = None,
) -> "AgentCancellationCleanupResult":
    """Record a cleanup hook that could not release its target."""
    return cls(
        target_kind=target_kind,
        target_ref=target_ref,
        status=AgentCancellationCleanupStatus.FAILED,
        error_code=error_code,
        message=message,
        metadata={} if metadata is None else metadata,
    )

skipped(*, target_kind, target_ref, reason, metadata=None) classmethod

Record a cleanup target that was already inactive or unavailable.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
@classmethod
def skipped(
    cls,
    *,
    target_kind: AgentCancellationTargetKind,
    target_ref: str,
    reason: str,
    metadata: JsonObject | None = None,
) -> "AgentCancellationCleanupResult":
    """Record a cleanup target that was already inactive or unavailable."""
    return cls(
        target_kind=target_kind,
        target_ref=target_ref,
        status=AgentCancellationCleanupStatus.SKIPPED,
        reason=reason,
        metadata={} if metadata is None else metadata,
    )

to_payload()

Serialize this hook outcome into evidence/state metadata.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def to_payload(self) -> JsonObject:
    """Serialize this hook outcome into evidence/state metadata."""
    return {
        "target_kind": self.target_kind.value,
        "target_ref": self.target_ref,
        "status": self.status.value,
        "reason": self.reason,
        "error_code": self.error_code,
        "message": self.message,
        "metadata": self.metadata,
    }

AgentCancellationCleanupTask(target_kind, target_ref, cleanup, metadata=dict()) dataclass

One cleanup hook registered for a running cancellation target.

__post_init__()

Reject hooks that cannot be identified in cleanup evidence.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def __post_init__(self) -> None:
    """Reject hooks that cannot be identified in cleanup evidence."""
    _require_non_blank(self.target_ref, "Agent cancellation cleanup target ref")

run(*, state, signal) async

Invoke the hook and verify that it reports the same target.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
async def run(
    self,
    *,
    state: AgentState,
    signal: AgentSignal,
) -> AgentCancellationCleanupResult:
    """Invoke the hook and verify that it reports the same target."""
    request = AgentCancellationRequest.from_signal(
        state=state,
        signal=signal,
        target_kind=self.target_kind,
        target_ref=self.target_ref,
        metadata=self.metadata,
    )
    result = await self.cleanup(request)
    if (
        result.target_kind is not self.target_kind
        or result.target_ref != self.target_ref
    ):
        raise AgentDefinitionError(
            "Agent cancellation cleanup result target must match the task"
        )
    return result

AgentCancellationCleanupReport(state_id, signal_id, outcomes=()) dataclass

Aggregate cleanup evidence for one CANCEL signal.

cleanup_succeeded property

Return whether all cleanup hooks completed without failure.

failed_outcomes property

Return the hook outcomes that force FAILED terminal state.

__post_init__()

Reject reports that cannot be attached to state and signal evidence.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def __post_init__(self) -> None:
    """Reject reports that cannot be attached to state and signal evidence."""
    _require_non_blank(self.state_id, "Agent cancellation report state id")
    _require_non_blank(self.signal_id, "Agent cancellation report signal id")

to_payload()

Serialize the report for state metadata and evidence payloads.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def to_payload(self) -> JsonObject:
    """Serialize the report for state metadata and evidence payloads."""
    return {
        "state_id": self.state_id,
        "signal_id": self.signal_id,
        "cleanup_succeeded": self.cleanup_succeeded,
        "outcomes": tuple(outcome.to_payload() for outcome in self.outcomes),
    }

to_evidence_candidate(*, summary=None)

Represent cancellation cleanup as append-only evidence.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def to_evidence_candidate(
    self,
    *,
    summary: str | None = None,
) -> AgentEvidenceCandidate:
    """Represent cancellation cleanup as append-only evidence."""
    return AgentEvidenceCandidate(
        kind=AgentEvidenceKind.CANCELLATION,
        payload=self.to_payload(),
        summary=summary,
    )

run_agent_cancellation_cleanup(*, state, signal, tasks) async

Invoke model stream/tool/delegate cleanup hooks for a CANCEL signal.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
async def run_agent_cancellation_cleanup(
    *,
    state: AgentState,
    signal: AgentSignal,
    tasks: Sequence[AgentCancellationCleanupTask],
) -> AgentCancellationCleanupReport:
    """Invoke model stream/tool/delegate cleanup hooks for a CANCEL signal."""
    _require_cancel_signal(signal)
    outcomes: list[AgentCancellationCleanupResult] = []
    for task in tasks:
        outcomes.append(await task.run(state=state, signal=signal))
    return AgentCancellationCleanupReport(
        state_id=state.id,
        signal_id=signal.id,
        outcomes=tuple(outcomes),
    )

begin_agent_cancellation(state, signal)

Materialize receipt of a CANCEL signal as CANCELLING state.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def begin_agent_cancellation(
    state: AgentState,
    signal: AgentSignal,
) -> AgentState:
    """Materialize receipt of a CANCEL signal as CANCELLING state."""
    _require_cancel_signal(signal)
    _require_signal_matches_state(state, signal)
    return replace(
        state,
        status=AgentStatus.CANCELLING,
        transition=AgentStateTransition.CANCELLING,
        reason=AgentStateReason.CANCELLATION_REQUESTED,
        metadata={
            **state.metadata,
            "cancellation_signal_id": signal.id,
            "cancellation_reason": _optional_string(signal.payload, "reason"),
            "cancellation_requested_by": _optional_string(
                signal.payload,
                "requested_by",
            ),
        },
    )

complete_agent_cancellation(state, report)

Resolve CANCELLING state into CANCELLED or FAILED cleanup outcome.

Source code in core/spakky-agent/src/spakky/agent/cancellation.py
def complete_agent_cancellation(
    state: AgentState,
    report: AgentCancellationCleanupReport,
) -> AgentState:
    """Resolve CANCELLING state into CANCELLED or FAILED cleanup outcome."""
    if state.id != report.state_id:
        raise AgentDefinitionError("Agent cancellation report state id mismatch")
    metadata = {**state.metadata, "cancellation_cleanup": report.to_payload()}
    if report.cleanup_succeeded:
        return replace(
            state,
            status=AgentStatus.CANCELLED,
            transition=AgentStateTransition.CANCELLED,
            reason=AgentStateReason.CANCELLATION_REQUESTED,
            metadata=metadata,
        )
    return replace(
        state,
        status=AgentStatus.FAILED,
        transition=AgentStateTransition.FAILED,
        reason=AgentStateReason.CANCELLATION_CLEANUP_FAILED,
        metadata=metadata,
    )

Delegation

Agent-to-agent delegation contracts.

DelegationReturnPolicy

Bases: StrEnum

How a child agent result should be projected back to the parent.

AgentDelegateTarget(agent_type, agent_name=None, metadata=dict()) dataclass

First-class delegate target represented by another @Agent component.

__post_init__()

Reject delegate targets that cannot identify an agent component.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegate targets that cannot identify an agent component."""
    if not self.agent_type.strip():
        raise AgentDefinitionError("Delegate target agent type cannot be blank")
    if self.agent_name is not None and not self.agent_name.strip():
        raise AgentDefinitionError("Delegate target agent name cannot be blank")

DelegationBudget(max_steps=None, max_tokens=None, timeout_seconds=None, deadline_at=None, metadata=dict()) dataclass

Budget metadata attached to a delegation packet.

__post_init__()

Reject delegation budgets that cannot be enforced consistently.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegation budgets that cannot be enforced consistently."""
    if self.max_steps is not None and self.max_steps <= 0:
        raise AgentDefinitionError("Delegation max steps must be positive")
    if self.max_tokens is not None and self.max_tokens <= 0:
        raise AgentDefinitionError("Delegation max tokens must be positive")
    if self.timeout_seconds is not None and self.timeout_seconds <= 0:
        raise AgentDefinitionError("Delegation timeout must be positive")

DelegationContextSlice(summary=None, evidence_refs=(), manifest_ref=None, metadata=dict()) dataclass

Minimal parent context projected for a child agent.

DelegationExpectedOutput(description=None, schema=dict(), metadata=dict()) dataclass

Expected child output description and optional JSON schema.

DelegationPacket(id, parent_agent_state_id, target, task, context=DelegationContextSlice(), constraints=(), expected_output=DelegationExpectedOutput(), budget=DelegationBudget(), allowed_capabilities=(), return_policy=DelegationReturnPolicy.SUMMARY_AND_EVIDENCE, metadata=dict()) dataclass

Task packet passed from a parent agent to a delegate agent.

__post_init__()

Reject delegation packets without parent linkage or task identity.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegation packets without parent linkage or task identity."""
    if not self.id.strip():
        raise AgentDefinitionError("Delegation id cannot be blank")
    if not self.parent_agent_state_id.strip():
        raise AgentDefinitionError("Delegation parent state id cannot be blank")

DelegationResult(id, packet_id, target, summary, output=None, evidence_refs=(), metadata=dict(), created_at=None) dataclass

Child agent result projected back to the parent execution.

__post_init__()

Reject delegated results that cannot be linked to a packet.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegated results that cannot be linked to a packet."""
    if not self.id.strip():
        raise AgentDefinitionError("Delegation result id cannot be blank")
    if not self.packet_id.strip():
        raise AgentDefinitionError("Delegation result packet id cannot be blank")
    if not self.summary.strip():
        raise AgentDefinitionError("Delegation result summary cannot be blank")

to_parent_evidence(*, evidence_id, parent_agent_state_id)

Represent a delegated result as append-only parent evidence.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def to_parent_evidence(
    self,
    *,
    evidence_id: str,
    parent_agent_state_id: str,
) -> AgentEvidence:
    """Represent a delegated result as append-only parent evidence."""
    payload: dict[str, JsonValue] = {
        "delegation_id": self.id,
        "packet_id": self.packet_id,
        "target_agent_type": self.target.agent_type,
        "evidence_refs": self.evidence_refs,
        "metadata": self.metadata,
    }
    if self.target.agent_name is not None:
        payload["target_agent_name"] = self.target.agent_name
    if self.output is not None:
        payload["output"] = self.output
    return AgentEvidence(
        id=evidence_id,
        agent_state_id=parent_agent_state_id,
        kind=AgentEvidenceKind.DELEGATION,
        payload=payload,
        summary=self.summary,
        created_at=self.created_at,
    )

to_parent_yield(*, evidence_id, parent_agent_state_id)

Expose the delegated result on the parent's AgentYield stream.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def to_parent_yield(
    self,
    *,
    evidence_id: str,
    parent_agent_state_id: str,
) -> AgentYield[Evidence]:
    """Expose the delegated result on the parent's AgentYield stream."""
    evidence = self.to_parent_evidence(
        evidence_id=evidence_id,
        parent_agent_state_id=parent_agent_state_id,
    )
    return AgentYield(
        kind=AgentYieldKind.EVIDENCE,
        payload=Evidence(
            evidence=evidence,
            metadata={"delegation_id": self.id, "packet_id": self.packet_id},
        ),
    )

DelegationToolResult(summary, output=None, events=(), metadata=dict()) dataclass

Model-facing result plus child neutral events from a teammate call.

__post_init__()

Reject delegated tool results without a model-facing summary.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def __post_init__(self) -> None:
    """Reject delegated tool results without a model-facing summary."""
    if not self.summary.strip():
        raise AgentDefinitionError("Delegation tool result summary cannot be blank")

from_result(result, *, events=()) classmethod

Build a model-facing tool result from a delegation result object.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
@classmethod
def from_result(
    cls,
    result: DelegationResult,
    *,
    events: tuple[AgentEvent, ...] = (),
) -> "DelegationToolResult":
    """Build a model-facing tool result from a delegation result object."""
    return cls(
        summary=result.summary,
        output=result.output,
        events=events,
        metadata={
            "delegation_id": result.id,
            "packet_id": result.packet_id,
            "target_agent_type": result.target.agent_type,
            **result.metadata,
        },
    )

IAgentDelegate

Bases: ABC

Execution hook that runs a delegation packet against a delegate target.

delegate(packet) abstractmethod

Execute delegation without prescribing spawn topology or transport.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
@abstractmethod
def delegate(
    self,
    packet: DelegationPacket,
) -> AsyncGenerator[AgentYield[DelegationResult], None]:
    """Execute delegation without prescribing spawn topology or transport."""

delegate_tool_result(packet) async

Execute delegation and collect the terminal result for a tool call.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
async def delegate_tool_result(
    self,
    packet: DelegationPacket,
) -> DelegationToolResult:
    """Execute delegation and collect the terminal result for a tool call."""
    terminal: DelegationResult | None = None
    async for item in self.delegate(packet):
        if isinstance(item.payload, DelegationResult):
            terminal = item.payload
    if terminal is None:
        raise AgentToolDispatchError("Agent delegate produced no delegation result")
    return DelegationToolResult.from_result(terminal)

build_teammate_tool_descriptors(owner, teammates)

Build model-callable delegation tools from an @Agent teammate spec.

Source code in core/spakky-agent/src/spakky/agent/delegation.py
def build_teammate_tool_descriptors(
    owner: type[object],
    teammates,
) -> tuple[AgentToolDescriptor, ...]:
    """Build model-callable delegation tools from an ``@Agent`` teammate spec."""
    return tuple(
        _build_teammate_tool_descriptor(owner, teammate) for teammate in teammates
    )

Safety

Deterministic sensitive-data contracts for agent boundaries.

DataSensitivity

Bases: StrEnum

Canonical sensitivity classes carried by descriptors.

PII

Bases: StrEnum

PII categories that can be declared with typing.Annotated.

MaskingPolicy

Bases: StrEnum

Deterministic text masking strategies for sensitive values.

RedactionPolicy

Bases: StrEnum

Boundary action used when a value must not be exposed.

StreamingGuardFailureMode

Bases: StrEnum

Final audit behavior when a streaming guard missed a raw candidate.

StreamingRedactionAuditStatus

Bases: StrEnum

Final aggregate streaming redaction audit status.

ContextExposurePolicy(include_pii_values=False, include_sensitive_values=False, include_sensitive_schema_metadata=False, include_sensitive_context_metadata=False) dataclass

Policy for LLM-facing context and schema metadata exposure.

can_expose_value(field)

Return whether a sensitive value may cross the model boundary.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def can_expose_value(self, field: "SensitiveField | SecretField") -> bool:
    """Return whether a sensitive value may cross the model boundary."""
    if isinstance(field, SecretField):
        return False
    if field.sensitivity == DataSensitivity.PII:
        return self.include_pii_values
    if field.sensitivity in (DataSensitivity.CONFIDENTIAL, DataSensitivity.SECRET):
        return self.include_sensitive_values
    return True

EvidenceExposurePolicy(include_pii_values=False, include_sensitive_values=False, include_sensitive_metadata=True) dataclass

Policy for evidence payload exposure before append-only capture.

can_expose_value(field)

Return whether a sensitive value may be stored in evidence payloads.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def can_expose_value(self, field: "SensitiveField | SecretField") -> bool:
    """Return whether a sensitive value may be stored in evidence payloads."""
    if isinstance(field, SecretField):
        return False
    if field.sensitivity == DataSensitivity.PII:
        return self.include_pii_values
    if field.sensitivity in (DataSensitivity.CONFIDENTIAL, DataSensitivity.SECRET):
        return self.include_sensitive_values
    return True

CredentialRef(id, provider=None) dataclass

Reference to a credential outside LLM-facing context.

__post_init__()

Reject blank credential references.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank credential references."""
    _require_non_blank(self.id, "Credential reference id")
    if self.provider is not None:
        _require_non_blank(self.provider, "Credential provider")

SecretRef(id, credential=None) dataclass

Opaque reference to a secret value stored outside model context.

__post_init__()

Reject blank secret references.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank secret references."""
    _require_non_blank(self.id, "Secret reference id")

SensitiveField(category, masking=MaskingPolicy.REDACT, redaction=RedactionPolicy.REDACT, label=None, metadata=dict()) dataclass

typing.Annotated metadata for deterministic sensitive-field handling.

sensitivity property

Return the normalized sensitivity class.

category_name property

Return the stable public category name.

__post_init__()

Reject blank sensitive field labels.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank sensitive field labels."""
    if self.label is not None:
        _require_non_blank(self.label, "Sensitive field label")

guard_text(value)

Return deterministic model/evidence-safe text for this field.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def guard_text(self, value: str) -> str:
    """Return deterministic model/evidence-safe text for this field."""
    return _mask_text(value, self.masking, self.category_name)

to_metadata()

Serialize marker metadata without including the sensitive value.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_metadata(self) -> JsonObject:
    """Serialize marker metadata without including the sensitive value."""
    payload: dict[str, JsonValue] = {
        "kind": "sensitive",
        "category": self.category_name,
        "sensitivity": self.sensitivity.value,
        "masking": self.masking.value,
        "redaction": self.redaction.value,
    }
    if self.label is not None:
        payload["label"] = self.label
    if self.metadata:
        payload["metadata"] = self.metadata
    return payload

SecretField(redaction=RedactionPolicy.REFERENCE_ONLY, label=None, metadata=dict()) dataclass

typing.Annotated metadata for values that must never be model text.

sensitivity property

Return the normalized sensitivity class.

__post_init__()

Reject blank secret field labels.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank secret field labels."""
    if self.label is not None:
        _require_non_blank(self.label, "Secret field label")

guard_text(value)

Return deterministic replacement text for a secret value.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def guard_text(self, value: str) -> str:
    """Return deterministic replacement text for a secret value."""
    return SECRET_VALUE

to_metadata()

Serialize marker metadata without including the secret value.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_metadata(self) -> JsonObject:
    """Serialize marker metadata without including the secret value."""
    payload: dict[str, JsonValue] = {
        "kind": "secret",
        "sensitivity": DataSensitivity.SECRET.value,
        "redaction": self.redaction.value,
    }
    if self.label is not None:
        payload["label"] = self.label
    if self.metadata:
        payload["metadata"] = self.metadata
    return payload

SensitiveFieldDescriptor(path, field) dataclass

Path-bound sensitive metadata extracted from Annotated types.

to_metadata()

Serialize descriptor metadata without leaking the field value.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_metadata(self) -> JsonObject:
    """Serialize descriptor metadata without leaking the field value."""
    return {
        "path": list(self.path),
        "field": self.field.to_metadata(),
    }

StreamingSensitivePattern(name, pattern, replacement=REDACTED_VALUE, metadata=dict()) dataclass

Caller-supplied deterministic pattern used by streaming redaction.

__post_init__()

Reject blank names and invalid pattern syntax before streaming starts.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject blank names and invalid pattern syntax before streaming starts."""
    _require_non_blank(self.name, "Streaming sensitive pattern name")
    _require_non_blank(self.pattern, "Streaming sensitive pattern")
    try:
        re.compile(self.pattern)
    except re.error as e:
        raise AgentDefinitionError("Streaming sensitive pattern is invalid") from e

redact(value)

Return redacted text and the number of replacements applied.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def redact(self, value: str) -> tuple[str, int]:
    """Return redacted text and the number of replacements applied."""
    compiled = re.compile(self.pattern)
    return compiled.subn(self.replacement, value)

find_matches(value)

Return sanitized match locations without exposing raw text.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def find_matches(self, value: str) -> tuple["StreamingRedactionMatch", ...]:
    """Return sanitized match locations without exposing raw text."""
    compiled = re.compile(self.pattern)
    return tuple(
        StreamingRedactionMatch(
            pattern_name=self.name,
            start=match.start(),
            end=match.end(),
            metadata=self.metadata,
        )
        for match in compiled.finditer(value)
    )

StreamingRedactionPolicy(patterns, buffer_size=64, emit_chunk_size=None, failure_mode=StreamingGuardFailureMode.RAISE) dataclass

Bounded buffering policy balancing stream latency and redaction correctness.

__post_init__()

Reject policies that would make the guard unbounded or silent.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __post_init__(self) -> None:
    """Reject policies that would make the guard unbounded or silent."""
    if self.buffer_size <= 0:
        raise AgentDefinitionError(
            "Streaming redaction buffer size must be positive"
        )
    if self.emit_chunk_size is not None and self.emit_chunk_size <= 0:
        raise AgentDefinitionError(
            "Streaming redaction emit chunk size must be positive"
        )
    if len(self.patterns) == 0:
        raise AgentDefinitionError("Streaming redaction patterns cannot be empty")

StreamingRedactionMatch(pattern_name, start, end, metadata=dict()) dataclass

Sanitized final-audit match location for a missed redaction candidate.

to_payload()

Serialize a match without the sensitive value itself.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_payload(self) -> JsonObject:
    """Serialize a match without the sensitive value itself."""
    payload: dict[str, JsonValue] = {
        "pattern_name": self.pattern_name,
        "start": self.start,
        "end": self.end,
    }
    if self.metadata:
        payload["metadata"] = self.metadata
    return payload

StreamingRedactionAudit(status, detected_count, redacted_count, missed_matches, buffer_size, emitted_char_count, original_char_count) dataclass

Final aggregate audit for a bounded streaming redaction session.

missed_count property

Return the number of raw candidates still present after streaming.

to_evidence_payload()

Serialize audit evidence without raw streamed content.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_evidence_payload(self) -> JsonObject:
    """Serialize audit evidence without raw streamed content."""
    return {
        "kind": "streaming_redaction_audit",
        "status": self.status.value,
        "detected_count": self.detected_count,
        "redacted_count": self.redacted_count,
        "missed_count": self.missed_count,
        "missed_matches": tuple(
            match.to_payload() for match in self.missed_matches
        ),
        "buffer_size": self.buffer_size,
        "emitted_char_count": self.emitted_char_count,
        "original_char_count": self.original_char_count,
    }

to_error_payload()

Serialize a typed error payload for stream consumers.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def to_error_payload(self) -> JsonObject:
    """Serialize a typed error payload for stream consumers."""
    return {
        "code": "streaming_redaction_audit_failed",
        "message": "Streaming redaction final audit detected unmasked candidates",
        "retryable": False,
        "metadata": self.to_evidence_payload(),
    }

StreamingRedactionResult(chunks, audit=None, error=None) dataclass

Output produced by a bounded streaming redaction step.

StreamingRedactionSession(policy)

Stateful bounded redactor for model token streams.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def __init__(self, policy: StreamingRedactionPolicy) -> None:
    self._policy = policy
    self._patterns = tuple(policy.patterns)
    self._buffer = ""
    self._original_chunks: list[str] = []
    self._emitted_chunks: list[str] = []
    self._redacted_count = 0
    self._closed = False

push(chunk)

Redact one token chunk and emit only the safe bounded prefix.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def push(self, chunk: str) -> StreamingRedactionResult:
    """Redact one token chunk and emit only the safe bounded prefix."""
    self._ensure_open()
    if chunk == "":
        return StreamingRedactionResult(chunks=())
    self._original_chunks.append(chunk)
    self._buffer = self._redact_text(f"{self._buffer}{chunk}")
    chunks = self._emit_safe_prefix()
    return StreamingRedactionResult(chunks=chunks)

finish()

Flush the remaining buffer and run the mandatory final audit.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def finish(self) -> StreamingRedactionResult:
    """Flush the remaining buffer and run the mandatory final audit."""
    self._ensure_open()
    self._closed = True
    redacted_buffer = self._redact_text(self._buffer)
    chunks = self._split_for_emit(redacted_buffer)
    self._buffer = ""
    self._emitted_chunks.extend(chunks)
    audit = self._audit()
    if audit.status == StreamingRedactionAuditStatus.FAILED:
        if self._policy.failure_mode == StreamingGuardFailureMode.RAISE:
            raise AgentOutputGuardError(
                "Streaming redaction final audit detected unmasked candidates"
            )
        return StreamingRedactionResult(
            chunks=chunks,
            audit=audit,
            error=audit.to_error_payload(),
        )
    return StreamingRedactionResult(chunks=chunks, audit=audit)

guard_json_value(value, sensitive_fields, policy)

Redact JSON-compatible values according to path-bound descriptors.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def guard_json_value(
    value: JsonValue,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: ContextExposurePolicy | EvidenceExposurePolicy,
) -> JsonValue:
    """Redact JSON-compatible values according to path-bound descriptors."""
    result = value
    for descriptor in sensitive_fields:
        result = _guard_json_path(result, descriptor.path, descriptor.field, policy)
    return result

schema_with_sensitive_metadata(schema, sensitive_fields, policy)

Return a JSON schema copy with policy-approved sensitivity extensions.

Source code in core/spakky-agent/src/spakky/agent/safety.py
def schema_with_sensitive_metadata(
    schema: Mapping[str, JsonValue],
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: ContextExposurePolicy,
) -> JsonObject:
    """Return a JSON schema copy with policy-approved sensitivity extensions."""
    if not policy.include_sensitive_schema_metadata or not sensitive_fields:
        return schema
    result = _copy_json_object(schema)
    for descriptor in sensitive_fields:
        _attach_schema_extension(result, descriptor.path, descriptor.to_metadata())
    return result

Tooling

Agent tool descriptor discovery contracts.

Idempotency

Bases: StrEnum

Action idempotency declared by a tool.

ToolResumeAction

Bases: StrEnum

Resume action allowed by stored tool idempotency metadata.

DataAccess

Bases: StrEnum

Data access level declared by a tool.

Externality

Bases: StrEnum

External side-effect boundary declared by a tool.

EvidenceCapture

Bases: StrEnum

Evidence capture strategy for tool results.

ToolApprovalRequirement

Bases: StrEnum

Human approval requirement at the tool boundary.

ToolRiskAxis

Bases: StrEnum

Derived risk axes exposed for policy and UI decisions.

ToolPermission(name) dataclass

Typed permission marker attached to a tool descriptor.

__post_init__()

Reject permission names that cannot be matched deterministically.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject permission names that cannot be matched deterministically."""
    if not self.name.strip():
        raise AgentDefinitionError("Agent tool permission name cannot be blank")

ToolEffects(data_access=DataAccess.NONE, externality=Externality.LOCAL, destructive=False, network=False) dataclass

Typed effect metadata used to derive display risk outside core.

read_only() classmethod

Declare a local read-only tool.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def read_only(cls) -> "ToolEffects":
    """Declare a local read-only tool."""
    return cls(data_access=DataAccess.READ, externality=Externality.LOCAL)

write_state() classmethod

Declare a local state-writing tool.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def write_state(cls) -> "ToolEffects":
    """Declare a local state-writing tool."""
    return cls(data_access=DataAccess.WRITE, externality=Externality.LOCAL)

external_side_effect() classmethod

Declare a tool that crosses an external side-effect boundary.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def external_side_effect(cls) -> "ToolEffects":
    """Declare a tool that crosses an external side-effect boundary."""
    return cls(
        data_access=DataAccess.READ_WRITE,
        externality=Externality.EXTERNAL,
        network=True,
    )

destructive_action() classmethod

Declare a tool that may irreversibly mutate local or external state.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def destructive_action(cls) -> "ToolEffects":
    """Declare a tool that may irreversibly mutate local or external state."""
    return cls(
        data_access=DataAccess.WRITE,
        externality=Externality.EXTERNAL,
        destructive=True,
    )

TimeoutPolicy(seconds=None) dataclass

Optional timeout boundary for a tool invocation.

__post_init__()

Reject non-positive timeout policies at definition time.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject non-positive timeout policies at definition time."""
    if self.seconds is not None and self.seconds <= 0:
        raise AgentDefinitionError("Agent tool timeout must be positive")

ResultBudget(max_bytes=None) dataclass

Optional result-size budget for model-facing tool output.

__post_init__()

Reject result budgets that cannot constrain output.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject result budgets that cannot constrain output."""
    if self.max_bytes is not None and self.max_bytes <= 0:
        raise AgentDefinitionError("Agent tool result budget must be positive")

ToolResumeMetadata(idempotency=Idempotency.UNKNOWN) dataclass

Stored idempotency metadata used when resuming an incomplete action.

from_metadata(metadata) classmethod

Build resume metadata from a tool descriptor metadata object.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def from_metadata(cls, metadata: "AgentToolMetadata") -> "ToolResumeMetadata":
    """Build resume metadata from a tool descriptor metadata object."""
    return cls(idempotency=metadata.idempotency)

action_for_completed_boundary()

Return the resume action for an already completed action boundary.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def action_for_completed_boundary(self) -> ToolResumeAction:
    """Return the resume action for an already completed action boundary."""
    return ToolResumeAction.SKIP_COMPLETED

action_for_incomplete_boundary()

Return the resume action for an incomplete action boundary.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def action_for_incomplete_boundary(self) -> ToolResumeAction:
    """Return the resume action for an incomplete action boundary."""
    if self.idempotency in (
        Idempotency.IDEMPOTENT,
        Idempotency.CONDITIONALLY_IDEMPOTENT,
    ):
        return ToolResumeAction.RETRY
    return ToolResumeAction.REQUIRE_APPROVAL

AgentToolSchemaHandle(name, input_schema_name, output_schema_name, input_schema=dict(), output_schema=dict(), input_sensitive_fields=(), output_sensitive_fields=()) dataclass

Stable schema names and generated JSON schemas owned by a descriptor.

__post_init__()

Reject blank schema handles.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject blank schema handles."""
    _require_non_blank(self.name, "Agent tool schema name")
    _require_non_blank(self.input_schema_name, "Agent tool input schema name")
    _require_non_blank(self.output_schema_name, "Agent tool output schema name")

input_schema_for(policy=None)

Return model-facing input schema under the requested exposure policy.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def input_schema_for(
    self,
    policy: ContextExposurePolicy | None = None,
) -> JsonObject:
    """Return model-facing input schema under the requested exposure policy."""
    return schema_with_sensitive_metadata(
        self.input_schema,
        self.input_sensitive_fields,
        policy or ContextExposurePolicy(),
    )

output_schema_for(policy=None)

Return model-facing output schema under the requested exposure policy.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def output_schema_for(
    self,
    policy: ContextExposurePolicy | None = None,
) -> JsonObject:
    """Return model-facing output schema under the requested exposure policy."""
    return schema_with_sensitive_metadata(
        self.output_schema,
        self.output_sensitive_fields,
        policy or ContextExposurePolicy(),
    )

AgentToolIdentity(owner_module, owner_qualname, name) dataclass

Descriptor identity independent from free-form model output text.

key property

Return a stable key for maps, logs, and evidence metadata.

__post_init__()

Reject identity parts that cannot be serialized or matched.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject identity parts that cannot be serialized or matched."""
    _require_non_blank(self.owner_module, "Agent tool owner module")
    _require_non_blank(self.owner_qualname, "Agent tool owner qualname")
    _require_non_blank(self.name, "Agent tool name")

AgentToolMetadata(permissions=(), effects=ToolEffects(), idempotency=Idempotency.UNKNOWN, data_access=DataAccess.NONE, externality=Externality.LOCAL, timeout=TimeoutPolicy(), result_budget=ResultBudget(), evidence=EvidenceCapture.NONE, approval=ToolApprovalRequirement.DERIVED) dataclass

Typed approval, idempotency, and evidence metadata for a descriptor.

risk property

Return derived risk axes without storing risk as source metadata.

resume property

Return resume metadata derived from stored idempotency.

requires_approval_candidate property

Return whether this tool is a HITL approval candidate.

AgentToolApprovalContext(prompt=None, action_ref=None, metadata=dict()) dataclass

Invocation-specific approval display and correlation metadata.

__post_init__()

Reject blank override strings before they enter approval state.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject blank override strings before they enter approval state."""
    if self.prompt is not None:
        _require_non_blank(self.prompt, "Agent tool approval prompt")
    if self.action_ref is not None:
        _require_non_blank(self.action_ref, "Agent tool approval action ref")

ToolRisk(axes=()) dataclass

Derived typed risk axes for policy and evidence annotations.

requires_approval_candidate property

Return whether the risk is strong enough to suggest HITL approval.

__post_init__()

Reject duplicate axes so risk comparisons stay deterministic.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject duplicate axes so risk comparisons stay deterministic."""
    seen: set[ToolRiskAxis] = set()
    for axis in self.axes:
        if axis in seen:
            raise AgentDefinitionError("Agent tool risk axes must be unique")
        seen.add(axis)

from_metadata(metadata) classmethod

Derive risk axes from source tool metadata.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
@classmethod
def from_metadata(cls, metadata: AgentToolMetadata) -> "ToolRisk":
    """Derive risk axes from source tool metadata."""
    axes: list[ToolRiskAxis] = []
    if metadata.data_access in (DataAccess.READ, DataAccess.READ_WRITE):
        axes.append(ToolRiskAxis.READ)
    if metadata.data_access in (DataAccess.WRITE, DataAccess.READ_WRITE):
        axes.append(ToolRiskAxis.WRITE)
    if metadata.data_access in (DataAccess.WRITE, DataAccess.READ_WRITE):
        axes.append(ToolRiskAxis.SIDE_EFFECT)
    if metadata.externality in (Externality.EXTERNAL, Externality.UNKNOWN):
        axes.append(ToolRiskAxis.SIDE_EFFECT)
    if metadata.effects.destructive:
        axes.append(ToolRiskAxis.DESTRUCTIVE)
    if metadata.effects.network or metadata.externality == Externality.EXTERNAL:
        axes.append(ToolRiskAxis.NETWORK)
    return cls(axes=_deduplicate_axes(axes))

includes(axis)

Return whether this risk contains the requested axis.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def includes(self, axis: ToolRiskAxis) -> bool:
    """Return whether this risk contains the requested axis."""
    return axis in self.axes

AgentToolRuntimeContext(state_id, conversation_id, call_id, tool_name) dataclass

Runtime correlation data injected into framework-owned tool callables.

__post_init__()

Reject runtime context that cannot link events and evidence.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject runtime context that cannot link events and evidence."""
    _require_non_blank(self.state_id, "Agent tool runtime state id")
    _require_non_blank(self.conversation_id, "Agent tool runtime conversation id")
    _require_non_blank(self.call_id, "Agent tool runtime call id")
    _require_non_blank(self.tool_name, "Agent tool runtime tool name")

AgentToolDefinition(name, schema_name, description=None, metadata=AgentToolMetadata()) dataclass

Method-level metadata attached by @agent_tool before owner discovery.

__post_init__()

Reject definitions that would make catalog lookup ambiguous.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject definitions that would make catalog lookup ambiguous."""
    _require_non_blank(self.name, "Agent tool name")
    _require_non_blank(self.schema_name, "Agent tool schema name")
    if self.description is not None and not self.description.strip():
        raise AgentDefinitionError("Agent tool description cannot be blank")

AgentToolDescriptor(identity, owner, callable, schema, description=None, metadata=AgentToolMetadata()) dataclass

Discovered tool descriptor bound to an owner class and callable.

name property

Return the descriptor-local tool name.

bind_invocation(payload)

Bind a decoded model payload before the tool callable is invoked.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def bind_invocation(self, payload: JsonObject) -> "AgentToolBoundInvocation":
    """Bind a decoded model payload before the tool callable is invoked."""
    return bind_agent_tool_invocation(self.callable, payload)

approval_context(payload)

Return invocation-specific approval context for this payload.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def approval_context(self, payload: JsonObject) -> AgentToolApprovalContext:
    """Return invocation-specific approval context for this payload."""
    _ = payload
    return AgentToolApprovalContext()

AgentToolBoundInvocation(args=(), kwargs=dict()) dataclass

Python-call-ready tool invocation arguments.

AgentToolCatalog(descriptors=()) dataclass

Deterministic catalog of descriptors discovered from an Agent class.

__post_init__()

Reject duplicate identity or schema names before model lookup.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def __post_init__(self) -> None:
    """Reject duplicate identity or schema names before model lookup."""
    identity_keys: set[str] = set()
    schema_names: set[str] = set()
    for descriptor in self.descriptors:
        if descriptor.identity.key in identity_keys:
            raise AgentDefinitionError("Agent tool identity must be unique")
        if descriptor.schema.name in schema_names:
            raise AgentDefinitionError("Agent tool schema name must be unique")
        identity_keys.add(descriptor.identity.key)
        schema_names.add(descriptor.schema.name)

by_identity(identity)

Lookup a descriptor by typed identity.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def by_identity(self, identity: AgentToolIdentity) -> AgentToolDescriptor:
    """Lookup a descriptor by typed identity."""
    for descriptor in self.descriptors:
        if descriptor.identity == identity:
            return descriptor
    raise AgentDefinitionError("Agent tool identity is not registered")

by_schema_name(schema_name)

Lookup a descriptor by model-facing schema name.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def by_schema_name(self, schema_name: str) -> AgentToolDescriptor:
    """Lookup a descriptor by model-facing schema name."""
    _require_non_blank(schema_name, "Agent tool schema name")
    for descriptor in self.descriptors:
        if descriptor.schema.name == schema_name:
            return descriptor
    raise AgentDefinitionError("Agent tool schema name is not registered")

IAgentToolProvider

Bases: ABC

Injected component contributing a deterministic agent tool catalog.

tool_catalog abstractmethod property

Return tools contributed by this component.

agent_tool(*, name=None, schema_name=None, description=None, permissions=(), effects=None, idempotency=Idempotency.UNKNOWN, data_access=None, externality=None, timeout=None, result_budget=None, evidence=EvidenceCapture.NONE, approval=ToolApprovalRequirement.DERIVED)

Attach typed agent-tool metadata to a method object.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def agent_tool(
    *,
    name: str | None = None,
    schema_name: str | None = None,
    description: str | None = None,
    permissions: Sequence[ToolPermission] = (),
    effects: ToolEffects | None = None,
    idempotency: Idempotency = Idempotency.UNKNOWN,
    data_access: DataAccess | None = None,
    externality: Externality | None = None,
    timeout: TimeoutPolicy | None = None,
    result_budget: ResultBudget | None = None,
    evidence: EvidenceCapture = EvidenceCapture.NONE,
    approval: ToolApprovalRequirement = ToolApprovalRequirement.DERIVED,
) -> Callable[[FunctionType], FunctionType]:
    """Attach typed agent-tool metadata to a method object."""

    def decorate(function: FunctionType) -> FunctionType:
        tool_name = _normalize_name(name, function.__name__, "Agent tool name")
        normalized_schema_name = _normalize_name(
            schema_name,
            tool_name,
            "Agent tool schema name",
        )
        tool_effects = effects or ToolEffects()
        metadata = AgentToolMetadata(
            permissions=tuple(permissions),
            effects=tool_effects,
            idempotency=idempotency,
            data_access=data_access or tool_effects.data_access,
            externality=externality or tool_effects.externality,
            timeout=timeout or TimeoutPolicy(),
            result_budget=result_budget or ResultBudget(),
            evidence=evidence,
            approval=approval,
        )
        definition = AgentToolDefinition(
            name=tool_name,
            schema_name=normalized_schema_name,
            description=description,
            metadata=metadata,
        )
        function.__dict__[AGENT_TOOL_DEFINITION_KEY] = definition
        return function

    return decorate

discover_agent_tools(owner)

Discover @agent_tool methods in deterministic class-definition order.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def discover_agent_tools(owner: type[object]) -> AgentToolCatalog:
    """Discover @agent_tool methods in deterministic class-definition order."""
    descriptors: list[AgentToolDescriptor] = []
    resolved_member_names: set[str] = set()
    for declaring_owner in owner.__mro__:
        if declaring_owner is object:
            continue
        for member_name, member in vars(declaring_owner).items():
            if member_name in resolved_member_names:
                continue
            resolved_member_names.add(member_name)
            function = _unwrap_function(member)
            if function is None:
                continue
            definition = get_agent_tool_definition(function)
            if definition is None:
                continue
            descriptors.append(
                _build_descriptor(declaring_owner, function, definition),
            )
    ordered = tuple(
        sorted(
            descriptors,
            key=lambda descriptor: descriptor.identity.key,
        ),
    )
    return AgentToolCatalog(descriptors=ordered)

get_agent_tool_definition(function)

Return decorator metadata attached to a function object.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def get_agent_tool_definition(
    function: FunctionType,
) -> AgentToolDefinition | None:
    """Return decorator metadata attached to a function object."""
    candidate = vars(function).get(AGENT_TOOL_DEFINITION_KEY)
    if candidate is None:
        return None
    if not isinstance(candidate, AgentToolDefinition):
        raise AgentDefinitionError("Agent tool metadata is invalid")
    return candidate

bind_agent_tool_invocation(function, payload)

Bind a structured model payload to a tool function signature.

Source code in core/spakky-agent/src/spakky/agent/tooling.py
def bind_agent_tool_invocation(
    function: AgentToolCallable,
    payload: JsonObject,
) -> AgentToolBoundInvocation:
    """Bind a structured model payload to a tool function signature."""
    invocation = _parse_invocation_payload(payload)
    try:
        function_signature = signature(function)
    except (TypeError, ValueError) as e:
        raise AgentToolBindingError(
            "Agent tool callable signature cannot be inspected"
        ) from e
    call_signature = _drop_injected_parameters(function_signature)
    try:
        bound = call_signature.bind(*invocation.args, **invocation.kwargs)
    except TypeError as e:
        raise AgentToolBindingError(
            "Agent tool invocation payload cannot be bound"
        ) from e
    bound.apply_defaults()
    return AgentToolBoundInvocation(
        args=tuple(bound.args),
        kwargs=dict(bound.kwargs),
    )

Signal Hooks

Declarative signal-hook discovery contracts (ADR-0013 §1).

The framework runner owns the execution loop, but a developer still needs a declarative seam to react to inbound signals (a steering instruction, an external event, a user message) and emit their own stream items without writing a loop body. @on_signal(kind) is that seam: it marks a coroutine generator method the same way @agent_tool marks a tool method, and the runner invokes every matching hook when it consumes a signal of that kind at a poll point.

Discovery mirrors discover_agent_tools exactly — an MRO walk reading vars() (not the banned getattr) so the raw function objects are found before descriptor binding — so the two declarative seams stay structurally identical for a reader.

AgentSignalHookDefinition(kind) dataclass

Method-level metadata attached by @on_signal before owner discovery.

AgentSignalHookIdentity(owner_module, owner_qualname, member_name) dataclass

Hook identity independent from the developer-chosen method name.

key property

Return a stable key for deterministic ordering and logs.

AgentSignalHookDescriptor(identity, owner, callable, kind) dataclass

Discovered signal hook bound to an owner class and callable.

AgentSignalHookCatalog(descriptors=()) dataclass

Deterministic catalog of signal hooks discovered from an Agent class.

__post_init__()

Reject duplicate hook identities so dispatch order stays stable.

Source code in core/spakky-agent/src/spakky/agent/hooks.py
def __post_init__(self) -> None:
    """Reject duplicate hook identities so dispatch order stays stable."""
    identity_keys: set[str] = set()
    for descriptor in self.descriptors:
        if descriptor.identity.key in identity_keys:
            raise AgentDefinitionError("Agent signal hook identity must be unique")
        identity_keys.add(descriptor.identity.key)

hooks_for(kind)

Return every hook that handles the requested signal kind, in order.

Source code in core/spakky-agent/src/spakky/agent/hooks.py
def hooks_for(
    self,
    kind: AgentSignalKind,
) -> tuple[AgentSignalHookDescriptor, ...]:
    """Return every hook that handles the requested signal kind, in order."""
    return tuple(
        descriptor for descriptor in self.descriptors if descriptor.kind is kind
    )

on_signal(kind)

Declare a method that reacts to one inbound signal kind.

The decorated method must be an async generator yielding AgentYield items and accepting exactly one signal: AgentSignal argument besides self. The runner invokes it when it consumes a signal of kind at a poll point, and forwards every yielded item into the public stream.

Source code in core/spakky-agent/src/spakky/agent/hooks.py
def on_signal(kind: AgentSignalKind) -> Callable[[FunctionType], FunctionType]:
    """Declare a method that reacts to one inbound signal kind.

    The decorated method must be an async generator yielding ``AgentYield``
    items and accepting exactly one ``signal: AgentSignal`` argument besides
    ``self``. The runner invokes it when it consumes a signal of ``kind`` at a
    poll point, and forwards every yielded item into the public stream.
    """

    def decorate(function: FunctionType) -> FunctionType:
        function.__dict__[AGENT_SIGNAL_HOOK_DEFINITION_KEY] = AgentSignalHookDefinition(
            kind=kind,
        )
        return function

    return decorate

discover_agent_signal_hooks(owner)

Discover @on_signal methods in deterministic class-definition order.

Source code in core/spakky-agent/src/spakky/agent/hooks.py
def discover_agent_signal_hooks(owner: type[object]) -> AgentSignalHookCatalog:
    """Discover ``@on_signal`` methods in deterministic class-definition order."""
    descriptors: list[AgentSignalHookDescriptor] = []
    resolved_member_names: set[str] = set()
    for declaring_owner in owner.__mro__:
        if declaring_owner is object:
            continue
        for member_name, member in vars(declaring_owner).items():
            if member_name in resolved_member_names:
                continue
            resolved_member_names.add(member_name)
            if not isinstance(member, FunctionType):
                continue
            definition = _get_signal_hook_definition(member)
            if definition is None:
                continue
            _validate_hook_contract(member)
            descriptors.append(
                AgentSignalHookDescriptor(
                    identity=AgentSignalHookIdentity(
                        owner_module=declaring_owner.__module__,
                        owner_qualname=declaring_owner.__qualname__,
                        member_name=member_name,
                    ),
                    owner=declaring_owner,
                    callable=member,
                    kind=definition.kind,
                ),
            )
    ordered = tuple(
        sorted(descriptors, key=lambda descriptor: descriptor.identity.key),
    )
    return AgentSignalHookCatalog(descriptors=ordered)

Yield

Agent streaming yield contracts.

TextDelta = Token module-attribute

Backward-compatible token-yield payload alias.

Message = Progress module-attribute

Backward-compatible progress-yield payload alias.

AgentYieldKind

Bases: StrEnum

Canonical public vocabulary yielded by agent execution.

AgentYield(kind, payload) dataclass

Typed stream item returned from an agent execute generator.

Token(text, metadata=dict()) dataclass

Incremental model token intended for streaming clients.

Progress(message, current_step=None, metadata=dict()) dataclass

Agent progress update intended for direct inbound adapter consumption.

Tool(name, call_id=None, arguments=dict(), result=None, metadata=dict()) dataclass

Tool call or tool result surfaced by agent execution.

Evidence(evidence, metadata=dict()) dataclass

Evidence item surfaced to the inbound adapter.

Approval(id, prompt, allowed_decisions, metadata) dataclass

Approval request surfaced to the inbound adapter.

Error(code, message, retryable=False, metadata=dict()) dataclass

Recoverable or terminal execution error surfaced to the caller.

Cancel(reason=None, requested_by=None, metadata=dict()) dataclass

Cancellation acknowledgement surfaced to the caller.

Final(output, metadata) dataclass

Final output carried by a generator stream.

Model Interface

Agent public interface ports.

ContextDigest(id, context_identity, source_manifest_ref, digest, derived_from_pack_ids=tuple(), compression_evidence_ref=None, algorithm=None, summary=None, created_at=None, metadata=dict()) dataclass

Derived compression evidence for a context identity.

ContextFreshness

Bases: StrEnum

Freshness classification for context rot and budget decisions.

ContextManifest(id, entries, origin_ref=None, evidence_refs=tuple(), created_at=None, metadata=dict()) dataclass

Auditable composition record for model input context packs.

ContextManifestEntry(pack_id, source, role, origin_ref, evidence_ref=None, digest_ref=None, sensitive_fields=(), metadata=dict()) dataclass

One audited pack entry inside a context manifest.

ContextPack(id, content, source, role, freshness=ContextFreshness.UNKNOWN, relevance=None, token_budget=ContextTokenBudget(), sensitivity=ContextSensitivity.INTERNAL, sensitive_fields=(), metadata=dict(), placement=ContextPlacement.TRAILER) dataclass

LLM-facing context unit derived from state, signal, or evidence.

guarded_content(policy=None)

Return deterministic model-safe content for this context pack.

Source code in core/spakky-agent/src/spakky/agent/context.py
def guarded_content(
    self,
    policy: ContextExposurePolicy | None = None,
) -> str:
    """Return deterministic model-safe content for this context pack."""
    exposure_policy = policy or ContextExposurePolicy()
    if self.sensitivity == ContextSensitivity.REDACTED:
        return "[REDACTED]"
    guarded = guard_json_value(
        {"content": self.content},
        tuple(
            SensitiveFieldDescriptor(
                ("content", *descriptor.path), descriptor.field
            )
            for descriptor in self.sensitive_fields
        ),
        exposure_policy,
    )
    content = cast(Mapping[str, JsonValue], guarded).get("content")
    if isinstance(content, str):
        return content
    return "[REDACTED]"

message_metadata(policy=None)

Return non-content metadata for provider-neutral model messages.

Source code in core/spakky-agent/src/spakky/agent/context.py
def message_metadata(
    self,
    policy: ContextExposurePolicy | None = None,
) -> Mapping[str, JsonValue]:
    """Return non-content metadata for provider-neutral model messages."""
    exposure_policy = policy or ContextExposurePolicy()
    metadata: dict[str, JsonValue] = {
        "context_pack_id": self.id,
        "source": self.source,
        "role": self.role.value,
        "freshness": self.freshness.value,
        "relevance": self.relevance,
        "token_budget": {
            "max_tokens": self.token_budget.max_tokens,
            "estimated_tokens": self.token_budget.estimated_tokens,
            "reserved_output_tokens": self.token_budget.reserved_output_tokens,
        },
        "sensitivity": self.sensitivity.value,
        "metadata": self.metadata,
    }
    if exposure_policy.include_sensitive_context_metadata and self.sensitive_fields:
        metadata["sensitive_fields"] = tuple(
            descriptor.to_metadata() for descriptor in self.sensitive_fields
        )
    return metadata

ContextPackRole

Bases: StrEnum

Semantic role of a context pack inside a model request.

ContextSensitivity

Bases: StrEnum

Deterministic sensitivity metadata carried before model input.

ContextTokenBudget(max_tokens=None, estimated_tokens=None, reserved_output_tokens=None) dataclass

Token budget allocated to one context pack.

IAgentModel

Bases: ABC

Outbound model adapter port owned by spakky-agent core.

capability abstractmethod property

Return the backend capability descriptor queryable before a run.

capability_for(selection=None)

Return capability for a run-specific model selection.

Existing fixed-model adapters can ignore the selector and inherit the default. Routing adapters can override this to expose per-model context windows, reasoning support, or token-counting support before a request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def capability_for(
    self,
    selection: ModelSelection | None = None,
) -> ModelCapability:
    """Return capability for a run-specific model selection.

    Existing fixed-model adapters can ignore the selector and inherit the
    default. Routing adapters can override this to expose per-model context
    windows, reasoning support, or token-counting support before a request.
    """
    _ = selection
    return self.capability

validate_request(request)

Fail before provider I/O when this model cannot honor the request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def validate_request(self, request: ModelRequest) -> None:
    """Fail before provider I/O when this model cannot honor the request."""
    if not isinstance(request, ModelRequest):
        raise AgentDefinitionError("Agent model request is invalid")
    capability = self.capability_for(request.model_selection)
    if not isinstance(capability, ModelCapability):
        raise AgentModelConfigurationError(
            "Agent model capability descriptor is invalid"
        )
    if not request.required_input_modalities() <= capability.input_modalities:
        raise AgentModelConfigurationError(
            "Agent model does not support every requested input modality"
        )

complete(request) abstractmethod async

Return a complete response, awaiting resource cleanup on cancellation.

Remote adapters must await cancellation acknowledgement before returning from cancellation cleanup; failures must propagate to stop continuation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@abstractmethod
async def complete(self, request: ModelRequest) -> ModelResponse:
    """Return a complete response, awaiting resource cleanup on cancellation.

    Remote adapters must await cancellation acknowledgement before returning
    from cancellation cleanup; failures must propagate to stop continuation.
    """
    ...

stream(request) abstractmethod

Return provider-neutral events with deterministic cancellation cleanup.

The runner cancels and awaits pending iteration on a revised input and explicitly closes async generators. Custom iterators must release their resources on cancellation of __anext__. Remote cancellation must be acknowledged before cleanup returns; unconfirmed cleanup must propagate.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@abstractmethod
def stream(self, request: ModelRequest) -> AsyncIterator[ModelStreamEvent]:
    """Return provider-neutral events with deterministic cancellation cleanup.

    The runner cancels and awaits pending iteration on a revised input and
    explicitly closes async generators. Custom iterators must release their
    resources on cancellation of ``__anext__``. Remote cancellation must be
    acknowledged before cleanup returns; unconfirmed cleanup must propagate.
    """
    ...

JsonSchemaConstraint(schema, strict=True) dataclass

JSON schema constraint shared by structured output and tool calling.

ModelCapability(supports_reasoning=False, context_window_tokens=None, supports_token_counting=False, input_modalities=frozenset({ModelModality.TEXT}), output_modalities=frozenset({ModelModality.TEXT}), supports_tools=False, supports_structured_output=False) dataclass

Provider-neutral declaration of a model backend's queryable abilities.

The agent runner consults this descriptor before a run to adjust behaviour without invoking the backend. Input/output modalities default to text only, while tool calling and structured output default to unsupported. Reasoning, context-window size, and token-counting support remain explicit so routing adapters can expose the exact abilities of each logical model route.

ModelError(code, message, retryable=False, metadata=dict()) dataclass

Provider-neutral model failure payload.

ModelMessage(role, content, metadata=dict()) dataclass

Provider-neutral model message.

__post_init__()

Snapshot multipart content while preserving canonical plain strings.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Snapshot multipart content while preserving canonical plain strings."""
    if not isinstance(self.role, ModelMessageRole):
        raise AgentDefinitionError("Model message role is invalid")
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))
    if isinstance(self.content, str):
        return
    object.__setattr__(self, "content", model_content_parts(self.content))

user(content, *, metadata=None) classmethod

Create a user message through the shortest canonical DX.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@classmethod
def user(
    cls,
    content: ModelContent,
    *,
    metadata: JsonObject | None = None,
) -> Self:
    """Create a user message through the shortest canonical DX."""
    return cls(
        role=ModelMessageRole.USER,
        content=content,
        metadata={} if metadata is None else metadata,
    )

ModelMessageRole

Bases: StrEnum

Roles accepted by provider-neutral model messages.

ModelModality

Bases: StrEnum

Portable input and output modalities declared by one model route.

ModelRequest(messages, context=tuple(), context_manifest=None, context_digest=None, structured_output=None, tool_calling=None, sampling=SamplingOptions(), streaming=StreamingOptions(), model_selection=None, metadata=dict(), extensions=()) dataclass

Provider-neutral request passed to an agent model adapter.

extensions = () class-attribute instance-attribute

Typed application values carried with the run, one per extension type.

__post_init__()

Deep-snapshot every mutable request input before async adapter work.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Deep-snapshot every mutable request input before async adapter work."""
    if not isinstance(self.messages, Sequence) or isinstance(
        self.messages,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model request messages must be a sequence")
    messages = tuple(self.messages)
    if any(not isinstance(message, ModelMessage) for message in messages):
        raise AgentDefinitionError("Model request contains an invalid message")
    validate_model_content_budget(tuple(message.content for message in messages))
    if not isinstance(self.context, Sequence) or isinstance(
        self.context,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model request context must be a sequence")
    context = tuple(self.context)
    if any(not isinstance(pack, ContextPack) for pack in context):
        raise AgentDefinitionError("Model request contains an invalid context pack")
    object.__setattr__(self, "messages", messages)
    object.__setattr__(self, "context", context)
    if self.context_manifest is not None:
        if not isinstance(self.context_manifest, ContextManifest):
            raise AgentDefinitionError("Model request context manifest is invalid")
        _snapshot_context_manifest(self.context_manifest)
    if self.context_digest is not None:
        if not isinstance(self.context_digest, ContextDigest):
            raise AgentDefinitionError("Model request context digest is invalid")
        _snapshot_context_digest(self.context_digest)
    if self.structured_output is not None:
        if not isinstance(self.structured_output, StructuredOutputSpec):
            raise AgentDefinitionError("Model structured output spec is invalid")
    if self.tool_calling is not None:
        if not isinstance(self.tool_calling, ToolCallingSpec):
            raise AgentDefinitionError("Model tool calling spec is invalid")
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))
    object.__setattr__(self, "extensions", validated_extensions(self.extensions))

snapshot()

Return a deep request copy shared across one async adapter invocation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def snapshot(self) -> "ModelRequest":
    """Return a deep request copy shared across one async adapter invocation."""
    return ModelRequest(
        messages=tuple(replace(message) for message in self.messages),
        context=tuple(_snapshot_context_pack(pack) for pack in self.context),
        context_manifest=(
            None
            if self.context_manifest is None
            else _snapshot_context_manifest(self.context_manifest)
        ),
        context_digest=(
            None
            if self.context_digest is None
            else _snapshot_context_digest(self.context_digest)
        ),
        structured_output=(
            None
            if self.structured_output is None
            else _snapshot_structured_output(self.structured_output)
        ),
        tool_calling=(
            None
            if self.tool_calling is None
            else _snapshot_tool_calling(self.tool_calling)
        ),
        sampling=self.sampling,
        streaming=self.streaming,
        model_selection=self.model_selection,
        metadata=_snapshot_json_object(self.metadata),
        extensions=self.extensions,
    )

assemble_messages(policy=None)

Assemble prompt messages from typed context packs without concatenation.

SYSTEM packs join the leading system message, PRELUDE packs come before the conversation history and TRAILER packs come after it. Packs that stay fixed for a run therefore keep the prompt prefix cacheable.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def assemble_messages(
    self,
    policy: ContextExposurePolicy | None = None,
) -> tuple[ModelMessage, ...]:
    """Assemble prompt messages from typed context packs without concatenation.

    ``SYSTEM`` packs join the leading system message, ``PRELUDE`` packs come
    before the conversation history and ``TRAILER`` packs come after it. Packs
    that stay fixed for a run therefore keep the prompt prefix cacheable.
    """
    exposure_policy = policy or ContextExposurePolicy()
    lead = next(
        (
            index
            for index, message in enumerate(self.messages)
            if message.role is not ModelMessageRole.SYSTEM
        ),
        len(self.messages),
    )
    leading = list(self.messages[:lead])
    system_text = tuple(
        pack.guarded_content(exposure_policy)
        for pack in self.context
        if pack.placement is ContextPlacement.SYSTEM
    )
    if system_text:
        instructions = leading[-1].content if leading else None
        if isinstance(instructions, str):
            leading[-1] = replace(
                leading[-1], content="\n\n".join((instructions, *system_text))
            )
        else:
            leading.append(
                ModelMessage(ModelMessageRole.SYSTEM, "\n\n".join(system_text))
            )

    def evidence(placement: ContextPlacement) -> tuple[ModelMessage, ...]:
        return tuple(
            ModelMessage(
                role=ModelMessageRole.EVIDENCE,
                content=pack.guarded_content(exposure_policy),
                metadata=pack.message_metadata(exposure_policy),
            )
            for pack in self.context
            if pack.placement is placement
        )

    return (
        *leading,
        *evidence(ContextPlacement.PRELUDE),
        *self.messages[lead:],
        *evidence(ContextPlacement.TRAILER),
    )

extension(kind)

Return this request's typed application extension of kind.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def extension[T: AgentRunExtension](self, kind: type[T]) -> T | None:
    """Return this request's typed application extension of ``kind``."""
    return next((item for item in self.extensions if isinstance(item, kind)), None)

required_input_modalities()

Derive every modality present in provider-bound message content.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def required_input_modalities(self) -> frozenset["ModelModality"]:
    """Derive every modality present in provider-bound message content."""
    modality_by_type = {
        TextPart: ModelModality.TEXT,
        ImagePart: ModelModality.IMAGE,
        AudioPart: ModelModality.AUDIO,
        VideoPart: ModelModality.VIDEO,
        DocumentPart: ModelModality.DOCUMENT,
    }
    modalities: set[ModelModality] = set()
    for message in self.assemble_messages():
        if isinstance(message.content, str):
            modalities.add(ModelModality.TEXT)
            continue
        for part in model_content_parts(message.content):
            modalities.add(modality_by_type[type(part)])
    return frozenset(modalities)

ModelResponse(content, structured_output=None, tool_calls=tuple(), usage=ModelUsage(), metadata=dict()) dataclass

Provider-neutral non-streaming model response.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive output payloads deterministically guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelResponse":
    """Return a copy with sensitive output payloads deterministically guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    content = self.content
    structured_output = self.structured_output
    content_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path in ((), ("content",))
    )
    if content_descriptors:
        guarded_content = guard_json_value(
            {"content": content},
            tuple(
                SensitiveFieldDescriptor(("content",), descriptor.field)
                for descriptor in content_descriptors
            ),
            exposure_policy,
        )
        content_value = cast(Mapping[str, JsonValue], guarded_content).get(
            "content"
        )
        if isinstance(content_value, str):
            content = content_value
        else:
            content = "[REDACTED]"
    structured_output_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path not in ((), ("content",))
    )
    if structured_output_descriptors:
        structured_output = guard_json_value(
            structured_output,
            structured_output_descriptors,
            exposure_policy,
        )
    return replace(self, content=content, structured_output=structured_output)

ModelSelection(model_ref) dataclass

Opaque operator-catalog model reference carried by one Agent run.

__post_init__()

Reject blank catalog references before they reach routing adapters.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Reject blank catalog references before they reach routing adapters."""
    if self.model_ref.strip() == "":
        raise AgentDefinitionError("Model selection model_ref cannot be blank")

ModelStreamEvent(kind, token_delta=None, message_delta=None, reasoning_delta=None, tool_call=None, tool_call_args_delta=None, structured_output=None, error=None, usage=None, metadata=dict()) dataclass

Provider-neutral model streaming event.

token_delta carries the generic streamed token channel. message_delta and reasoning_delta distinguish assistant-facing text from model reasoning so callers can route or suppress reasoning independently. tool_call_args_delta carries incremental tool-call argument text framed by TOOL_CALL_START and TOOL_CALL_END boundary events that reference the same tool_call.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive streaming payloads guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelStreamEvent":
    """Return a copy with sensitive streaming payloads guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    text_channels: dict[str, str | None] = {
        "token_delta": self.token_delta,
        "message_delta": self.message_delta,
        "reasoning_delta": self.reasoning_delta,
        "tool_call_args_delta": self.tool_call_args_delta,
    }
    guarded_text = {
        field_name: self._guard_text_delta(
            field_name, value, sensitive_fields, exposure_policy
        )
        for field_name, value in text_channels.items()
        if value is not None
    }
    text_paths = (
        (),
        *((field_name,) for field_name in text_channels),
    )
    structured_output = self.structured_output
    structured_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path not in text_paths
    )
    if structured_descriptors:
        structured_output = guard_json_value(
            structured_output,
            structured_descriptors,
            exposure_policy,
        )
    tool_call = self.tool_call
    if tool_call is not None:
        tool_call = tool_call.guarded(sensitive_fields, exposure_policy)
    return replace(
        self,
        structured_output=structured_output,
        tool_call=tool_call,
        **guarded_text,
    )

ModelStreamEventKind

Bases: StrEnum

Provider-neutral streaming event kinds emitted by a model adapter.

ModelToolCall(name, arguments, call_id=None, metadata=dict()) dataclass

Tool invocation candidate emitted by a model adapter.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive argument values deterministically guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelToolCall":
    """Return a copy with sensitive argument values deterministically guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    guarded_arguments = guard_json_value(
        self.arguments,
        sensitive_fields,
        exposure_policy,
    )
    if not isinstance(guarded_arguments, Mapping):
        guarded_arguments = {}
    return replace(self, arguments=guarded_arguments)

ModelToolChoice

Bases: StrEnum

Provider-neutral tool calling strategy requested from a model adapter.

ModelToolSpec(name, parameters, description=None, metadata=dict()) dataclass

LLM-facing tool descriptor normalized by agent tooling.

__post_init__()

Deep-freeze tool metadata before provider or cache observation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Deep-freeze tool metadata before provider or cache observation."""
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))

ModelUsage(input_tokens=None, output_tokens=None, total_tokens=None, cached_input_tokens=None, cache_write_input_tokens=None, cache_write_5m_input_tokens=None, cache_write_1h_input_tokens=None) dataclass

Token accounting reported by a model adapter.

SamplingOptions(temperature=None, top_p=None, max_tokens=None) dataclass

Portable model sampling options.

StreamingOptions(include_usage=True, include_progress=True) dataclass

Portable model streaming options.

StructuredOutputSpec(constraint, output_type_name=None) dataclass

Structured output contract requested from a model adapter.

ToolCallingSpec(tools, choice=ModelToolChoice.AUTO) dataclass

Tool calling contract requested from a model adapter.

__post_init__()

Snapshot the ordered tool catalog supplied by a mutable caller.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Snapshot the ordered tool catalog supplied by a mutable caller."""
    if not isinstance(self.tools, Sequence) or isinstance(
        self.tools,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model tool catalog must be a sequence")
    tools = tuple(self.tools)
    if any(not isinstance(tool, ModelToolSpec) for tool in tools):
        raise AgentDefinitionError("Model tool catalog contains an invalid tool")
    object.__setattr__(self, "tools", tools)

IAgentEvidenceRepository

Bases: ABC

Append-only evidence repository exposed to agent-facing code.

append(evidence) abstractmethod

Append immutable evidence and return the stored artifact.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def append(self, evidence: AgentEvidence) -> AgentEvidence:
    """Append immutable evidence and return the stored artifact."""
    ...

get(evidence_id) abstractmethod

Return one evidence artifact by id.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get(self, evidence_id: str) -> AgentEvidence:
    """Return one evidence artifact by id."""
    ...

list_by_state(state_id) abstractmethod

Return evidence artifacts captured for an agent state in append order.

A resumed run replays this sequence, so the order must be the order of append calls. Stores that sort must order by created_at (the runner stamps strictly increasing values) and never by id as text: ...:evidence:10 sorts before ...:evidence:2.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_state(self, state_id: str) -> Sequence[AgentEvidence]:
    """Return evidence artifacts captured for an agent state in append order.

    A resumed run replays this sequence, so the order must be the order of
    ``append`` calls. Stores that sort must order by ``created_at`` (the
    runner stamps strictly increasing values) and never by ``id`` as text:
    ``...:evidence:10`` sorts before ``...:evidence:2``.
    """
    ...

list_by_manifest_ref(manifest_ref) abstractmethod

Return evidence artifacts of a context manifest in append order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_manifest_ref(self, manifest_ref: str) -> Sequence[AgentEvidence]:
    """Return evidence artifacts of a context manifest in append order."""
    ...

count_by_state(state_id)

Return how many evidence artifacts an agent state has.

Durable stores override this with a count query so appending evidence does not read every earlier artifact of the run.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def count_by_state(self, state_id: str) -> int:
    """Return how many evidence artifacts an agent state has.

    Durable stores override this with a count query so appending evidence
    does not read every earlier artifact of the run.
    """
    return len(self.list_by_state(state_id))

has_step_evidence(state_id, kind, model_step, digest)

Return whether one step-scoped context artifact was already recorded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def has_step_evidence(
    self,
    state_id: str,
    kind: AgentEvidenceKind,
    model_step: int,
    digest: str,
) -> bool:
    """Return whether one step-scoped context artifact was already recorded."""
    return any(
        item.kind == kind
        and item.model_step == model_step
        and item.digest == digest
        for item in self.list_by_state(state_id)
    )

list_by_origin_ref(origin_ref)

Return context evidence whose model context used origin_ref.

Stores without an origin index cannot answer this query.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def list_by_origin_ref(self, origin_ref: str) -> Sequence[AgentEvidence]:
    """Return context evidence whose model context used ``origin_ref``.

    Stores without an origin index cannot answer this query.
    """
    raise AgentEvidenceOriginQueryUnsupportedError()

IAgentSignalRepository

Bases: ABC

Durable inbound queue repository for agent signals.

append(signal) abstractmethod

Append a signal to the inbound queue and return the stored entry.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def append(self, signal: AgentSignal) -> AgentSignal:
    """Append a signal to the inbound queue and return the stored entry."""
    ...

list_pending(state_id) abstractmethod

Return unconsumed signals for an agent state in append/queue order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_pending(self, state_id: str) -> Sequence[AgentSignal]:
    """Return unconsumed signals for an agent state in append/queue order."""
    ...

mark_consumed(signal_id) abstractmethod

Mark one queued signal as consumed after a non-blocking poll.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def mark_consumed(self, signal_id: str) -> AgentSignal:
    """Mark one queued signal as consumed after a non-blocking poll."""
    ...

IAgentStateRepository

Bases: ABC

Materialized state repository for long-running agent executions.

get(state_id) abstractmethod

Return a persisted agent state by id.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get(self, state_id: str) -> AgentState:
    """Return a persisted agent state by id."""
    ...

get_or_none(state_id) abstractmethod

Return a persisted agent state by id, or None when absent.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get_or_none(self, state_id: str) -> AgentState | None:
    """Return a persisted agent state by id, or None when absent."""
    ...

save(state) abstractmethod

Persist the materialized state and return the saved snapshot.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def save(self, state: AgentState) -> AgentState:
    """Persist the materialized state and return the saved snapshot."""
    ...

list_by_status(status) abstractmethod

Return states matching an externally observable lifecycle status.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_status(self, status: AgentStatus) -> Sequence[AgentState]:
    """Return states matching an externally observable lifecycle status."""
    ...

list_resume_candidates() abstractmethod

Return active or interrupted states that may resume after restart.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_resume_candidates(self) -> Sequence[AgentState]:
    """Return active or interrupted states that may resume after restart."""
    ...

ConversationTurn(role, content, metadata=dict()) dataclass

One persisted exchange in a multi-turn conversation transcript.

A turn is the protocol-neutral unit a TaskStore persists: who spoke (role) and what was said (content). It is intentionally narrower than a model-request ModelMessage — the transcript records the user/assistant dialogue that seeds future turns, not the system or evidence framing the runner assembles fresh on each request. as_model_message projects a turn back into the model-request vocabulary when the runner replays history.

__post_init__()

Reject turns that cannot seed a future model request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
def __post_init__(self) -> None:
    """Reject turns that cannot seed a future model request."""
    if self.role not in (ModelMessageRole.USER, ModelMessageRole.ASSISTANT):
        raise AgentDefinitionError(
            "Conversation turn role must be user or assistant"
        )
    if not self.content.strip():
        raise AgentDefinitionError("Conversation turn content cannot be blank")

as_model_message()

Project this turn into a model-request message for history replay.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
def as_model_message(self) -> ModelMessage:
    """Project this turn into a model-request message for history replay."""
    return ModelMessage(
        role=self.role, content=self.content, metadata=self.metadata
    )

ITaskStore

Bases: ABC

Durable conversation-history store keyed by conversation_id.

Persists the running transcript of a server-side session so a later run with the same conversation_id continues the conversation (ADR-0013 §6). A2A can map its contextId to this key for transcript replay, while A2A task snapshots are stored by spakky-a2a's repository bridge.

load_history(conversation_id) abstractmethod

Return the persisted transcript for a conversation in turn order.

Returns an empty sequence for a conversation that has no persisted turns yet — the first turn of a brand-new conversation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
@abstractmethod
def load_history(self, conversation_id: str) -> Sequence[ConversationTurn]:
    """Return the persisted transcript for a conversation in turn order.

    Returns an empty sequence for a conversation that has no persisted turns
    yet — the first turn of a brand-new conversation.
    """
    ...

append_turns(conversation_id, turns) abstractmethod

Append new turns to a conversation's transcript in order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
@abstractmethod
def append_turns(
    self,
    conversation_id: str,
    turns: Sequence[ConversationTurn],
) -> None:
    """Append new turns to a conversation's transcript in order."""
    ...

Provider-neutral agent model port.

ModelMessageRole

Bases: StrEnum

Roles accepted by provider-neutral model messages.

ModelMessage(role, content, metadata=dict()) dataclass

Provider-neutral model message.

__post_init__()

Snapshot multipart content while preserving canonical plain strings.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Snapshot multipart content while preserving canonical plain strings."""
    if not isinstance(self.role, ModelMessageRole):
        raise AgentDefinitionError("Model message role is invalid")
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))
    if isinstance(self.content, str):
        return
    object.__setattr__(self, "content", model_content_parts(self.content))

user(content, *, metadata=None) classmethod

Create a user message through the shortest canonical DX.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@classmethod
def user(
    cls,
    content: ModelContent,
    *,
    metadata: JsonObject | None = None,
) -> Self:
    """Create a user message through the shortest canonical DX."""
    return cls(
        role=ModelMessageRole.USER,
        content=content,
        metadata={} if metadata is None else metadata,
    )

JsonSchemaConstraint(schema, strict=True) dataclass

JSON schema constraint shared by structured output and tool calling.

StructuredOutputSpec(constraint, output_type_name=None) dataclass

Structured output contract requested from a model adapter.

ModelToolChoice

Bases: StrEnum

Provider-neutral tool calling strategy requested from a model adapter.

ModelToolSpec(name, parameters, description=None, metadata=dict()) dataclass

LLM-facing tool descriptor normalized by agent tooling.

__post_init__()

Deep-freeze tool metadata before provider or cache observation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Deep-freeze tool metadata before provider or cache observation."""
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))

ToolCallingSpec(tools, choice=ModelToolChoice.AUTO) dataclass

Tool calling contract requested from a model adapter.

__post_init__()

Snapshot the ordered tool catalog supplied by a mutable caller.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Snapshot the ordered tool catalog supplied by a mutable caller."""
    if not isinstance(self.tools, Sequence) or isinstance(
        self.tools,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model tool catalog must be a sequence")
    tools = tuple(self.tools)
    if any(not isinstance(tool, ModelToolSpec) for tool in tools):
        raise AgentDefinitionError("Model tool catalog contains an invalid tool")
    object.__setattr__(self, "tools", tools)

SamplingOptions(temperature=None, top_p=None, max_tokens=None) dataclass

Portable model sampling options.

StreamingOptions(include_usage=True, include_progress=True) dataclass

Portable model streaming options.

ModelSelection(model_ref) dataclass

Opaque operator-catalog model reference carried by one Agent run.

__post_init__()

Reject blank catalog references before they reach routing adapters.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Reject blank catalog references before they reach routing adapters."""
    if self.model_ref.strip() == "":
        raise AgentDefinitionError("Model selection model_ref cannot be blank")

ModelRequest(messages, context=tuple(), context_manifest=None, context_digest=None, structured_output=None, tool_calling=None, sampling=SamplingOptions(), streaming=StreamingOptions(), model_selection=None, metadata=dict(), extensions=()) dataclass

Provider-neutral request passed to an agent model adapter.

extensions = () class-attribute instance-attribute

Typed application values carried with the run, one per extension type.

__post_init__()

Deep-snapshot every mutable request input before async adapter work.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __post_init__(self) -> None:
    """Deep-snapshot every mutable request input before async adapter work."""
    if not isinstance(self.messages, Sequence) or isinstance(
        self.messages,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model request messages must be a sequence")
    messages = tuple(self.messages)
    if any(not isinstance(message, ModelMessage) for message in messages):
        raise AgentDefinitionError("Model request contains an invalid message")
    validate_model_content_budget(tuple(message.content for message in messages))
    if not isinstance(self.context, Sequence) or isinstance(
        self.context,
        str | bytes | bytearray,
    ):
        raise AgentDefinitionError("Model request context must be a sequence")
    context = tuple(self.context)
    if any(not isinstance(pack, ContextPack) for pack in context):
        raise AgentDefinitionError("Model request contains an invalid context pack")
    object.__setattr__(self, "messages", messages)
    object.__setattr__(self, "context", context)
    if self.context_manifest is not None:
        if not isinstance(self.context_manifest, ContextManifest):
            raise AgentDefinitionError("Model request context manifest is invalid")
        _snapshot_context_manifest(self.context_manifest)
    if self.context_digest is not None:
        if not isinstance(self.context_digest, ContextDigest):
            raise AgentDefinitionError("Model request context digest is invalid")
        _snapshot_context_digest(self.context_digest)
    if self.structured_output is not None:
        if not isinstance(self.structured_output, StructuredOutputSpec):
            raise AgentDefinitionError("Model structured output spec is invalid")
    if self.tool_calling is not None:
        if not isinstance(self.tool_calling, ToolCallingSpec):
            raise AgentDefinitionError("Model tool calling spec is invalid")
    object.__setattr__(self, "metadata", _snapshot_json_object(self.metadata))
    object.__setattr__(self, "extensions", validated_extensions(self.extensions))

snapshot()

Return a deep request copy shared across one async adapter invocation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def snapshot(self) -> "ModelRequest":
    """Return a deep request copy shared across one async adapter invocation."""
    return ModelRequest(
        messages=tuple(replace(message) for message in self.messages),
        context=tuple(_snapshot_context_pack(pack) for pack in self.context),
        context_manifest=(
            None
            if self.context_manifest is None
            else _snapshot_context_manifest(self.context_manifest)
        ),
        context_digest=(
            None
            if self.context_digest is None
            else _snapshot_context_digest(self.context_digest)
        ),
        structured_output=(
            None
            if self.structured_output is None
            else _snapshot_structured_output(self.structured_output)
        ),
        tool_calling=(
            None
            if self.tool_calling is None
            else _snapshot_tool_calling(self.tool_calling)
        ),
        sampling=self.sampling,
        streaming=self.streaming,
        model_selection=self.model_selection,
        metadata=_snapshot_json_object(self.metadata),
        extensions=self.extensions,
    )

assemble_messages(policy=None)

Assemble prompt messages from typed context packs without concatenation.

SYSTEM packs join the leading system message, PRELUDE packs come before the conversation history and TRAILER packs come after it. Packs that stay fixed for a run therefore keep the prompt prefix cacheable.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def assemble_messages(
    self,
    policy: ContextExposurePolicy | None = None,
) -> tuple[ModelMessage, ...]:
    """Assemble prompt messages from typed context packs without concatenation.

    ``SYSTEM`` packs join the leading system message, ``PRELUDE`` packs come
    before the conversation history and ``TRAILER`` packs come after it. Packs
    that stay fixed for a run therefore keep the prompt prefix cacheable.
    """
    exposure_policy = policy or ContextExposurePolicy()
    lead = next(
        (
            index
            for index, message in enumerate(self.messages)
            if message.role is not ModelMessageRole.SYSTEM
        ),
        len(self.messages),
    )
    leading = list(self.messages[:lead])
    system_text = tuple(
        pack.guarded_content(exposure_policy)
        for pack in self.context
        if pack.placement is ContextPlacement.SYSTEM
    )
    if system_text:
        instructions = leading[-1].content if leading else None
        if isinstance(instructions, str):
            leading[-1] = replace(
                leading[-1], content="\n\n".join((instructions, *system_text))
            )
        else:
            leading.append(
                ModelMessage(ModelMessageRole.SYSTEM, "\n\n".join(system_text))
            )

    def evidence(placement: ContextPlacement) -> tuple[ModelMessage, ...]:
        return tuple(
            ModelMessage(
                role=ModelMessageRole.EVIDENCE,
                content=pack.guarded_content(exposure_policy),
                metadata=pack.message_metadata(exposure_policy),
            )
            for pack in self.context
            if pack.placement is placement
        )

    return (
        *leading,
        *evidence(ContextPlacement.PRELUDE),
        *self.messages[lead:],
        *evidence(ContextPlacement.TRAILER),
    )

extension(kind)

Return this request's typed application extension of kind.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def extension[T: AgentRunExtension](self, kind: type[T]) -> T | None:
    """Return this request's typed application extension of ``kind``."""
    return next((item for item in self.extensions if isinstance(item, kind)), None)

required_input_modalities()

Derive every modality present in provider-bound message content.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def required_input_modalities(self) -> frozenset["ModelModality"]:
    """Derive every modality present in provider-bound message content."""
    modality_by_type = {
        TextPart: ModelModality.TEXT,
        ImagePart: ModelModality.IMAGE,
        AudioPart: ModelModality.AUDIO,
        VideoPart: ModelModality.VIDEO,
        DocumentPart: ModelModality.DOCUMENT,
    }
    modalities: set[ModelModality] = set()
    for message in self.assemble_messages():
        if isinstance(message.content, str):
            modalities.add(ModelModality.TEXT)
            continue
        for part in model_content_parts(message.content):
            modalities.add(modality_by_type[type(part)])
    return frozenset(modalities)

ModelUsage(input_tokens=None, output_tokens=None, total_tokens=None, cached_input_tokens=None, cache_write_input_tokens=None, cache_write_5m_input_tokens=None, cache_write_1h_input_tokens=None) dataclass

Token accounting reported by a model adapter.

AbstractAgentModelError()

Bases: AbstractSpakkyFrameworkError, ABC

Model failure that can carry a privacy-safe billable invocation receipt.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __init__(self) -> None:
    super().__init__()
    self.model_usage = None
    self.model_metadata = {}

attach_model_receipt(usage, metadata)

Attach known usage/routing after provider success but before later failure.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def attach_model_receipt(
    self,
    usage: ModelUsage,
    metadata: JsonObject,
) -> None:
    """Attach known usage/routing after provider success but before later failure."""
    if not isinstance(usage, ModelUsage):
        raise AgentDefinitionError("Agent model failure usage is invalid")
    self.model_usage = usage
    self.model_metadata = _snapshot_json_object(metadata)

AgentModelStepRestartError()

Bases: AbstractAgentModelError

Raised by a model adapter to discard the current model step and redo it.

Raise it from IAgentModel.stream() or complete() when the output of the step in flight cannot be trusted, for example when the provider stream broke midway. The runner drops everything that step produced: its text is not added to the transcript and the tool calls it proposed are not run. It tells consumers to drop what was already streamed with a Progress whose metadata has invalidate_output=True and code="agent_model_step_restarted", then sends the same request again as the next model step.

The discarded step still counts toward max_steps and the run deadline, so an adapter that keeps raising cannot loop forever when either is set; bound the retries in the adapter when both are unset. Call attach_model_receipt first when the provider already billed the step, so its usage stays in the run totals.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def __init__(self) -> None:
    super().__init__()
    self.model_usage = None
    self.model_metadata = {}

ModelToolCall(name, arguments, call_id=None, metadata=dict()) dataclass

Tool invocation candidate emitted by a model adapter.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive argument values deterministically guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelToolCall":
    """Return a copy with sensitive argument values deterministically guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    guarded_arguments = guard_json_value(
        self.arguments,
        sensitive_fields,
        exposure_policy,
    )
    if not isinstance(guarded_arguments, Mapping):
        guarded_arguments = {}
    return replace(self, arguments=guarded_arguments)

ModelError(code, message, retryable=False, metadata=dict()) dataclass

Provider-neutral model failure payload.

ModelResponse(content, structured_output=None, tool_calls=tuple(), usage=ModelUsage(), metadata=dict()) dataclass

Provider-neutral non-streaming model response.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive output payloads deterministically guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelResponse":
    """Return a copy with sensitive output payloads deterministically guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    content = self.content
    structured_output = self.structured_output
    content_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path in ((), ("content",))
    )
    if content_descriptors:
        guarded_content = guard_json_value(
            {"content": content},
            tuple(
                SensitiveFieldDescriptor(("content",), descriptor.field)
                for descriptor in content_descriptors
            ),
            exposure_policy,
        )
        content_value = cast(Mapping[str, JsonValue], guarded_content).get(
            "content"
        )
        if isinstance(content_value, str):
            content = content_value
        else:
            content = "[REDACTED]"
    structured_output_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path not in ((), ("content",))
    )
    if structured_output_descriptors:
        structured_output = guard_json_value(
            structured_output,
            structured_output_descriptors,
            exposure_policy,
        )
    return replace(self, content=content, structured_output=structured_output)

ModelStreamEventKind

Bases: StrEnum

Provider-neutral streaming event kinds emitted by a model adapter.

ModelStreamEvent(kind, token_delta=None, message_delta=None, reasoning_delta=None, tool_call=None, tool_call_args_delta=None, structured_output=None, error=None, usage=None, metadata=dict()) dataclass

Provider-neutral model streaming event.

token_delta carries the generic streamed token channel. message_delta and reasoning_delta distinguish assistant-facing text from model reasoning so callers can route or suppress reasoning independently. tool_call_args_delta carries incremental tool-call argument text framed by TOOL_CALL_START and TOOL_CALL_END boundary events that reference the same tool_call.

guarded(sensitive_fields, policy=None)

Return a copy with sensitive streaming payloads guarded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def guarded(
    self,
    sensitive_fields: Sequence[SensitiveFieldDescriptor],
    policy: EvidenceExposurePolicy | None = None,
) -> "ModelStreamEvent":
    """Return a copy with sensitive streaming payloads guarded."""
    exposure_policy = policy or EvidenceExposurePolicy()
    text_channels: dict[str, str | None] = {
        "token_delta": self.token_delta,
        "message_delta": self.message_delta,
        "reasoning_delta": self.reasoning_delta,
        "tool_call_args_delta": self.tool_call_args_delta,
    }
    guarded_text = {
        field_name: self._guard_text_delta(
            field_name, value, sensitive_fields, exposure_policy
        )
        for field_name, value in text_channels.items()
        if value is not None
    }
    text_paths = (
        (),
        *((field_name,) for field_name in text_channels),
    )
    structured_output = self.structured_output
    structured_descriptors = tuple(
        descriptor
        for descriptor in sensitive_fields
        if descriptor.path not in text_paths
    )
    if structured_descriptors:
        structured_output = guard_json_value(
            structured_output,
            structured_descriptors,
            exposure_policy,
        )
    tool_call = self.tool_call
    if tool_call is not None:
        tool_call = tool_call.guarded(sensitive_fields, exposure_policy)
    return replace(
        self,
        structured_output=structured_output,
        tool_call=tool_call,
        **guarded_text,
    )

ModelModality

Bases: StrEnum

Portable input and output modalities declared by one model route.

ModelCapability(supports_reasoning=False, context_window_tokens=None, supports_token_counting=False, input_modalities=frozenset({ModelModality.TEXT}), output_modalities=frozenset({ModelModality.TEXT}), supports_tools=False, supports_structured_output=False) dataclass

Provider-neutral declaration of a model backend's queryable abilities.

The agent runner consults this descriptor before a run to adjust behaviour without invoking the backend. Input/output modalities default to text only, while tool calling and structured output default to unsupported. Reasoning, context-window size, and token-counting support remain explicit so routing adapters can expose the exact abilities of each logical model route.

IAgentModel

Bases: ABC

Outbound model adapter port owned by spakky-agent core.

capability abstractmethod property

Return the backend capability descriptor queryable before a run.

capability_for(selection=None)

Return capability for a run-specific model selection.

Existing fixed-model adapters can ignore the selector and inherit the default. Routing adapters can override this to expose per-model context windows, reasoning support, or token-counting support before a request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def capability_for(
    self,
    selection: ModelSelection | None = None,
) -> ModelCapability:
    """Return capability for a run-specific model selection.

    Existing fixed-model adapters can ignore the selector and inherit the
    default. Routing adapters can override this to expose per-model context
    windows, reasoning support, or token-counting support before a request.
    """
    _ = selection
    return self.capability

validate_request(request)

Fail before provider I/O when this model cannot honor the request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
def validate_request(self, request: ModelRequest) -> None:
    """Fail before provider I/O when this model cannot honor the request."""
    if not isinstance(request, ModelRequest):
        raise AgentDefinitionError("Agent model request is invalid")
    capability = self.capability_for(request.model_selection)
    if not isinstance(capability, ModelCapability):
        raise AgentModelConfigurationError(
            "Agent model capability descriptor is invalid"
        )
    if not request.required_input_modalities() <= capability.input_modalities:
        raise AgentModelConfigurationError(
            "Agent model does not support every requested input modality"
        )

complete(request) abstractmethod async

Return a complete response, awaiting resource cleanup on cancellation.

Remote adapters must await cancellation acknowledgement before returning from cancellation cleanup; failures must propagate to stop continuation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@abstractmethod
async def complete(self, request: ModelRequest) -> ModelResponse:
    """Return a complete response, awaiting resource cleanup on cancellation.

    Remote adapters must await cancellation acknowledgement before returning
    from cancellation cleanup; failures must propagate to stop continuation.
    """
    ...

stream(request) abstractmethod

Return provider-neutral events with deterministic cancellation cleanup.

The runner cancels and awaits pending iteration on a revised input and explicitly closes async generators. Custom iterators must release their resources on cancellation of __anext__. Remote cancellation must be acknowledged before cleanup returns; unconfirmed cleanup must propagate.

Source code in core/spakky-agent/src/spakky/agent/interfaces/model.py
@abstractmethod
def stream(self, request: ModelRequest) -> AsyncIterator[ModelStreamEvent]:
    """Return provider-neutral events with deterministic cancellation cleanup.

    The runner cancels and awaits pending iteration on a revised input and
    explicitly closes async generators. Custom iterators must release their
    resources on cancellation of ``__anext__``. Remote cancellation must be
    acknowledged before cleanup returns; unconfirmed cleanup must propagate.
    """
    ...

Persistence ports for durable agent state, signal, and evidence.

IAgentStateRepository

Bases: ABC

Materialized state repository for long-running agent executions.

get(state_id) abstractmethod

Return a persisted agent state by id.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get(self, state_id: str) -> AgentState:
    """Return a persisted agent state by id."""
    ...

get_or_none(state_id) abstractmethod

Return a persisted agent state by id, or None when absent.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get_or_none(self, state_id: str) -> AgentState | None:
    """Return a persisted agent state by id, or None when absent."""
    ...

save(state) abstractmethod

Persist the materialized state and return the saved snapshot.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def save(self, state: AgentState) -> AgentState:
    """Persist the materialized state and return the saved snapshot."""
    ...

list_by_status(status) abstractmethod

Return states matching an externally observable lifecycle status.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_status(self, status: AgentStatus) -> Sequence[AgentState]:
    """Return states matching an externally observable lifecycle status."""
    ...

list_resume_candidates() abstractmethod

Return active or interrupted states that may resume after restart.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_resume_candidates(self) -> Sequence[AgentState]:
    """Return active or interrupted states that may resume after restart."""
    ...

IAgentSignalRepository

Bases: ABC

Durable inbound queue repository for agent signals.

append(signal) abstractmethod

Append a signal to the inbound queue and return the stored entry.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def append(self, signal: AgentSignal) -> AgentSignal:
    """Append a signal to the inbound queue and return the stored entry."""
    ...

list_pending(state_id) abstractmethod

Return unconsumed signals for an agent state in append/queue order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_pending(self, state_id: str) -> Sequence[AgentSignal]:
    """Return unconsumed signals for an agent state in append/queue order."""
    ...

mark_consumed(signal_id) abstractmethod

Mark one queued signal as consumed after a non-blocking poll.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def mark_consumed(self, signal_id: str) -> AgentSignal:
    """Mark one queued signal as consumed after a non-blocking poll."""
    ...

IAgentEvidenceRepository

Bases: ABC

Append-only evidence repository exposed to agent-facing code.

append(evidence) abstractmethod

Append immutable evidence and return the stored artifact.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def append(self, evidence: AgentEvidence) -> AgentEvidence:
    """Append immutable evidence and return the stored artifact."""
    ...

get(evidence_id) abstractmethod

Return one evidence artifact by id.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def get(self, evidence_id: str) -> AgentEvidence:
    """Return one evidence artifact by id."""
    ...

list_by_state(state_id) abstractmethod

Return evidence artifacts captured for an agent state in append order.

A resumed run replays this sequence, so the order must be the order of append calls. Stores that sort must order by created_at (the runner stamps strictly increasing values) and never by id as text: ...:evidence:10 sorts before ...:evidence:2.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_state(self, state_id: str) -> Sequence[AgentEvidence]:
    """Return evidence artifacts captured for an agent state in append order.

    A resumed run replays this sequence, so the order must be the order of
    ``append`` calls. Stores that sort must order by ``created_at`` (the
    runner stamps strictly increasing values) and never by ``id`` as text:
    ``...:evidence:10`` sorts before ``...:evidence:2``.
    """
    ...

list_by_manifest_ref(manifest_ref) abstractmethod

Return evidence artifacts of a context manifest in append order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
@abstractmethod
def list_by_manifest_ref(self, manifest_ref: str) -> Sequence[AgentEvidence]:
    """Return evidence artifacts of a context manifest in append order."""
    ...

count_by_state(state_id)

Return how many evidence artifacts an agent state has.

Durable stores override this with a count query so appending evidence does not read every earlier artifact of the run.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def count_by_state(self, state_id: str) -> int:
    """Return how many evidence artifacts an agent state has.

    Durable stores override this with a count query so appending evidence
    does not read every earlier artifact of the run.
    """
    return len(self.list_by_state(state_id))

has_step_evidence(state_id, kind, model_step, digest)

Return whether one step-scoped context artifact was already recorded.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def has_step_evidence(
    self,
    state_id: str,
    kind: AgentEvidenceKind,
    model_step: int,
    digest: str,
) -> bool:
    """Return whether one step-scoped context artifact was already recorded."""
    return any(
        item.kind == kind
        and item.model_step == model_step
        and item.digest == digest
        for item in self.list_by_state(state_id)
    )

list_by_origin_ref(origin_ref)

Return context evidence whose model context used origin_ref.

Stores without an origin index cannot answer this query.

Source code in core/spakky-agent/src/spakky/agent/interfaces/repository.py
def list_by_origin_ref(self, origin_ref: str) -> Sequence[AgentEvidence]:
    """Return context evidence whose model context used ``origin_ref``.

    Stores without an origin index cannot answer this query.
    """
    raise AgentEvidenceOriginQueryUnsupportedError()

Persistence port for multi-turn conversation history (ADR-0013 §6).

ADR-0013 §6 supports multi-turn conversations through two paths that the framework runner reconciles:

  • server-side persisted sessions — the framework persists the running transcript and continues it by conversation_id. This port is that conversation-history persistence contract. It is protocol-neutral, but it is not the A2A task snapshot repository: spakky-a2a owns A2A Task storage through its plugin repository and bridges it to a2a-sdk TaskStore.
  • client-injected history — a stateless caller passes the prior transcript on each run (RunAgentInput.message_history) and no store is consulted.

The conversation_id key is the protocol-neutral thread identifier carried by every event (AgentEventAttribution.conversation_id) and seeded by RunAgentInput.effective_conversation_id. AG-UI projects it as threadId and A2A projects it as contextId when an adapter wants transcript replay; A2A protocol Task records remain plugin-owned snapshots.

ConversationTurn(role, content, metadata=dict()) dataclass

One persisted exchange in a multi-turn conversation transcript.

A turn is the protocol-neutral unit a TaskStore persists: who spoke (role) and what was said (content). It is intentionally narrower than a model-request ModelMessage — the transcript records the user/assistant dialogue that seeds future turns, not the system or evidence framing the runner assembles fresh on each request. as_model_message projects a turn back into the model-request vocabulary when the runner replays history.

__post_init__()

Reject turns that cannot seed a future model request.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
def __post_init__(self) -> None:
    """Reject turns that cannot seed a future model request."""
    if self.role not in (ModelMessageRole.USER, ModelMessageRole.ASSISTANT):
        raise AgentDefinitionError(
            "Conversation turn role must be user or assistant"
        )
    if not self.content.strip():
        raise AgentDefinitionError("Conversation turn content cannot be blank")

as_model_message()

Project this turn into a model-request message for history replay.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
def as_model_message(self) -> ModelMessage:
    """Project this turn into a model-request message for history replay."""
    return ModelMessage(
        role=self.role, content=self.content, metadata=self.metadata
    )

ITaskStore

Bases: ABC

Durable conversation-history store keyed by conversation_id.

Persists the running transcript of a server-side session so a later run with the same conversation_id continues the conversation (ADR-0013 §6). A2A can map its contextId to this key for transcript replay, while A2A task snapshots are stored by spakky-a2a's repository bridge.

load_history(conversation_id) abstractmethod

Return the persisted transcript for a conversation in turn order.

Returns an empty sequence for a conversation that has no persisted turns yet — the first turn of a brand-new conversation.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
@abstractmethod
def load_history(self, conversation_id: str) -> Sequence[ConversationTurn]:
    """Return the persisted transcript for a conversation in turn order.

    Returns an empty sequence for a conversation that has no persisted turns
    yet — the first turn of a brand-new conversation.
    """
    ...

append_turns(conversation_id, turns) abstractmethod

Append new turns to a conversation's transcript in order.

Source code in core/spakky-agent/src/spakky/agent/interfaces/task_store.py
@abstractmethod
def append_turns(
    self,
    conversation_id: str,
    turns: Sequence[ConversationTurn],
) -> None:
    """Append new turns to a conversation's transcript in order."""
    ...

Types

Shared JSON-compatible type aliases for agent contracts.

JsonPrimitive = bool | float | int | str | None

Scalar JSON value accepted by agent public contracts.

JsonValue = JsonPrimitive | Mapping[str, JsonValue] | Sequence[JsonValue]

Recursive JSON-compatible value used at model, signal, and evidence boundaries.

JsonObject = Mapping[str, JsonValue]

JSON object payload used by public agent contracts.

Plugin

Plugin initialization entry point for spakky-agent.

initialize(app)

Initialize spakky-agent core contracts.

The package intentionally registers no persistence implementation; production repositories must arrive through feature contributions. It registers the default in-process live signal mailbox that repositories publish committed signals to and runners subscribe to.

Source code in core/spakky-agent/src/spakky/agent/main.py
def initialize(app: SpakkyApplication) -> None:
    """Initialize spakky-agent core contracts.

    The package intentionally registers no persistence implementation; production
    repositories must arrive through feature contributions. It registers the
    default in-process live signal mailbox that repositories publish committed
    signals to and runners subscribe to.
    """
    app.add(InProcessAgentSignalMailbox)
    app.add(AgentRunnerFactory)
    app.add(AgentBootstrapValidationPostProcessor)

Bootstrap validation for Agent Pod instances.

AgentBootstrapValidationPostProcessor()

Bases: IPostProcessor, IContainerAware

Validate Agent metadata during application bootstrap.

Initialize without assuming application context injection happened.

Source code in core/spakky-agent/src/spakky/agent/post_processor.py
def __init__(self) -> None:
    """Initialize without assuming application context injection happened."""
    self._container = None

set_container(container)

Receive the active container for contribution validation.

Source code in core/spakky-agent/src/spakky/agent/post_processor.py
@override
def set_container(self, container: IContainer) -> None:
    """Receive the active container for contribution validation."""
    self._container = container

post_process(pod)

Fail startup when an Agent contract is no longer valid.

Source code in core/spakky-agent/src/spakky/agent/post_processor.py
@override
def post_process(self, pod: object) -> object:
    """Fail startup when an Agent contract is no longer valid."""
    agent = Agent.get_or_none(type(pod))
    if agent is None:
        return pod
    try:
        agent.validate_bootstrap()
    except AgentDefinitionError as e:
        raise AgentBootstrapError("Agent bootstrap contract is invalid") from e
    self._validate_persistence_contributions(agent)
    self._bind_signal_mailbox(agent)
    return pod

에러

Error classes for the spakky-agent package.

AbstractSpakkyAgentError

Bases: AbstractSpakkyFrameworkError, ABC

Base class for agent-related errors.

AgentDefinitionError

Bases: AbstractSpakkyAgentError

Raised when an agent contract cannot be defined safely.

AgentToolBindingError

Bases: AbstractSpakkyAgentError

Raised when a model tool-call payload cannot be bound safely.

AgentToolDispatchError

Bases: AbstractSpakkyAgentError

Raised when a model tool call names a tool absent from the catalog.

AgentEvidenceOriginQueryUnsupportedError

Bases: AbstractSpakkyAgentError

Raised when an evidence store has no index of context origin references.

AgentBootstrapError

Bases: AbstractSpakkyAgentError

Raised when agent bootstrap validation fails.

AgentPersistenceConfigurationError

Bases: AgentBootstrapError

Raised when production agent persistence is required but not provided.

AgentModelConfigurationError

Bases: AgentBootstrapError

Raised when an agent requires a model adapter but none is registered.

AgentOutputGuardError

Bases: AbstractSpakkyAgentError

Raised when an output guard detects unsafe streaming exposure.

AgentRetrievalError

Bases: AbstractSpakkyAgentError

Raised when retrieval results cannot safely enter an agent run.

AgentMemoryError

Bases: AbstractSpakkyAgentError

Raised when long-term memory cannot safely cross its scoped boundary.

AgentSignalMailboxConfigurationError

Bases: AgentBootstrapError

Raised when a run must wait for live input but has no signal mailbox.

AgentSignalInboxConflictError

Bases: AbstractSpakkyAgentError

Raised when one runner opens two live inboxes for the same agent state.

AgentCustomEventChannelUnavailableError

Bases: AbstractSpakkyAgentError

Raised when a custom event is emitted where no merged stream is listening.