Spectre (Spectre v0.4.0)

Copy Markdown View Source

OTP-native agents with declarative recognition, Server callbacks and governed acts.

New applications in 0.4 use Spectre.Stack for installed capabilities, Spectre.Agent for recognition, and Spectre.Server for behaviour. Spectre.Server.Runtime owns the conversation in one GenServer. Governed consequences enter the host bridge Spectre.Server.GAM and the Spectre.GAM kernel; a model proposal is neither authority nor proof of execution.

With a Server-bound Agent and a host consumer:

{:ok, server} = Spectre.summon(agent: MyApp.SupportAgent, consumer: self())
{:ok, interaction_id} = Spectre.Server.input(server, "I need help")

Responses arrive as {Spectre.Server, server, {:response, interaction_id, text, metadata}}. See the Getting Started, AgentServer, Stack Tools and GAM guides for complete examples and host setup. The GAM manifesto explains the authority, evidence, act and duty model.

Retained 0.3 APIs

This module also exposes the legacy Instance/Session/Run facade, including ask/3, turn/3 and execute/3. Those functions do not replace Spectre.Server.input/3 and do not automatically migrate old policy gates, state or checkpoints into GAM. summon/1 chooses the Server path only when the Agent declares a server: binding. The migration guide distinguishes these runtime contracts.

Summary

Functions

Activates a re-read bootstrap or approved governed Candidate through generation CAS.

Returns the currently committed Definition Activation for an Instance.

Admits an ownership-based event through the Instance sequencer.

Returns committed admitted Event Envelopes.

Runs configured action lifecycle hooks for a result.

Handles one turn through the retained Instance/Session runtime.

Runs deterministic proactive-delivery authorization without sending.

Waits for the canonical Result produced by a stream handle.

Cancels the active policy/effect boundary and returns an updated result.

Returns the strict JSON canonical Agent checkpoint.

Returns canonical checkpoint persistence status.

Returns the lifecycle axes for one Definition or the active Definition.

Returns committed delivery audit receipts.

Dismisses a session supervised by Spectre.Supervisor.

Drains new admission while retaining owned continuations.

Starts or reuses the Instance for agent + subject, always returning {:ok, pid} or {:error, reason}.

Erases configured data for one offline Instance.

Executes the currently pending effect through its registered capability boundary. Actions use their provider mount; other effect kinds use the executor contributed by the owning extension.

Waits for durable persistence of the current canonical revision.

Starts or returns the unique supervised Instance for agent + subject.

Looks up the live local Instance for agent + subject.

Returns one committed operational-loop view.

Lists visible committed operational loops.

Returns committed operational events.

Requests a reversible loop pause.

Stores revocable proactive-delivery consent.

Returns quarantined Event Envelopes.

Reconciles an ambiguous canonical-checkpoint write before any retry.

Records a Beam/host transport outcome against an authorization receipt.

Registers a durable Vigil on an Agent Instance.

Renews a nonterminal Work, Vigil or controller expiry.

Replaces the current in-memory state of a supervised session.

Resolves exactly one visible operational loop without model guessing.

Resolves an open policy from a trusted host decision.

Resumes a Run owned by an Agent Instance.

Resumes a reversibly paused loop.

Returns the replacement Enumerable for a stream interrupted by Instance restart.

Revokes proactive-delivery consent.

Rolls activation back to an explicitly selected ancestor Candidate.

Returns one active or explicitly selected first-class Skill-state branch.

Lists first-class Skill-state branches.

Starts an authorized external controller on the shared runtime.

Starts a verified data-driven Work materialization on an Agent Instance.

Starts a precise Work on an Agent Instance.

Returns the current in-memory state of a supervised session.

Starts a bounded pull stream on an Agent Instance.

Subscribes the caller to committed local operational events.

Summons the Server bound to an Agent, or its legacy Instance/Session runtime.

Transitions one dormant Skill-state branch retention status.

Delivers a declared trigger to a waiting loop.

Runs the retained Instance/Run path to its first observable boundary.

Removes the caller's local operational-event subscription.

Applies the durable pause-update-resume sequence.

Applies a version-fenced loop update.

Updates one active Skill-state branch through schema and revision fences.

Returns the running Spectre library version.

Functions

activate(instance, candidate_ref, opts \\ [])

Activates a re-read bootstrap or approved governed Candidate through generation CAS.

activation(instance)

Returns the currently committed Definition Activation for an Instance.

admit_event(instance, event, opts \\ [])

Admits an ownership-based event through the Instance sequencer.

admitted_events(instance, opts \\ [])

Returns committed admitted Event Envelopes.

after_action(agent, event, result, ctx, opts \\ [])

@spec after_action(
  module(),
  atom(),
  Spectre.Result.t(),
  Spectre.Context.t() | map(),
  keyword()
) ::
  :ok | {:error, [term()]}

Runs configured action lifecycle hooks for a result.

The common host-app use is to call this after a successful message delivery:

Spectre.after_action(MyAgent, :delivered, result, ctx)

Hooks are kept outside route execution so delivery acknowledgements and audit events can be retried independently from the user-facing turn.

ask(agent_or_session, input, opts \\ [])

@spec ask(
  module() | GenServer.server(),
  Spectre.Input.t() | String.t() | map(),
  keyword()
) ::
  {:ok, Spectre.Result.t()} | {:error, term()}

Handles one turn through the retained Instance/Session runtime.

For a Server-bound Agent, use Spectre.Server.input/3 on its Server instead.

When the first argument is an agent module built with use Spectre.Agent, Spectre runs a stateless turn and uses the configured state adapter or the explicit :state option. When the first argument is a session pid/name, Spectre sends the turn to that supervised process.

Spectre.ask(MyApp.Agent, %{text: "hello", meta: %{locale: "en"}})

{:ok, session} = Spectre.summon(agent: MyApp.Agent)
Spectre.ask(session, "continue the same conversation")

authorize_delivery(instance, event_id, destination, policy, opts \\ [])

Runs deterministic proactive-delivery authorization without sending.

await_result(stream, timeout \\ :timer.minutes(5))

@spec await_result(Spectre.Inference.Stream.t(), timeout()) ::
  {:ok, Spectre.Result.t()} | {:error, term()}

Waits for the canonical Result produced by a stream handle.

cancel(input, ctx)

@spec cancel(Spectre.Input.t() | String.t() | map(), Spectre.Context.t() | map()) ::
  {:ok, Spectre.Result.t()}

Cancels the active policy/effect boundary and returns an updated result.

{:ok, result} = Spectre.cancel("cancel", ctx)

checkpoint(instance)

Returns the strict JSON canonical Agent checkpoint.

checkpoint_status(instance)

Returns canonical checkpoint persistence status.

definition_lifecycle(instance, definition_ref \\ :active)

Returns the lifecycle axes for one Definition or the active Definition.

delivery_receipts(instance, opts \\ [])

Returns committed delivery audit receipts.

dismiss(supervisor, pid)

@spec dismiss(GenServer.server(), pid()) :: :ok | {:error, term()}

Dismisses a session supervised by Spectre.Supervisor.

:ok = Spectre.dismiss(MyApp.SpectreSupervisor, pid)

drain_definition(instance, definition_ref \\ :active, opts \\ [])

Drains new admission while retaining owned continuations.

ensure_instance(supervisor, agent, subject, opts \\ [])

@spec ensure_instance(
  GenServer.server(),
  module() | Spectre.AgentRef.t(),
  term(),
  keyword()
) ::
  {:ok, pid()} | {:error, term()}

Starts or reuses the Instance for agent + subject, always returning {:ok, pid} or {:error, reason}.

instance/4 mirrors the underlying supervisor's richer return shapes ({:ok, pid}, {:ok, pid, info}, {:error, {:already_started, pid}}). Hosts that only need the pid use this normalized form:

{:ok, pid} = Spectre.ensure_instance(MySup, MyAgent, "conversation:42")

erase_instance(agent_or_ref, subject, opts \\ [])

@spec erase_instance(
  module() | Spectre.AgentRef.t() | Spectre.Instance.Ref.t(),
  Spectre.Subject.t() | term(),
  keyword()
) :: {:ok, Spectre.Instance.Erasure.Proof.t()} | {:error, term()}

Erases configured data for one offline Instance.

The operation refuses a live local Instance, requires an erasure-capable Checkpoint Store and Owner, erases configured Journal and pending receipt payload data first, and installs a fenced anti-resurrection marker. :confirm must equal the exact stable Spectre.Instance.Ref.key.

The returned proof covers configured Journal records, pending receipt payloads referenced by the canonical outbox, and stable/legacy Instance checkpoints. Delivered receipt records and host-owned State, Memory, telemetry, provider, replica, export, and backup data remain outside it.

execute(state_or_agent, context_or_result, opts \\ [])

@spec execute(Spectre.State.t(), Spectre.Context.t() | map(), keyword()) ::
  {:ok, Spectre.Result.t()} | {:error, term()}
@spec execute(module() | GenServer.server(), Spectre.Result.t(), keyword()) ::
  {:ok, Spectre.Result.t()} | {:error, term()}

Executes the currently pending effect through its registered capability boundary. Actions use their provider mount; other effect kinds use the executor contributed by the owning extension.

{:ok, result} = Spectre.execute(state, ctx)
{:ok, result} = Spectre.execute(MyAgent, approved_result)

flush_checkpoint(instance, opts \\ [])

Waits for durable persistence of the current canonical revision.

instance(supervisor, agent, subject, opts \\ [])

Starts or returns the unique supervised Instance for agent + subject.

lookup_instance(agent, subject, registry \\ Spectre.Instance.Registry)

@spec lookup_instance(
  module() | Spectre.AgentRef.t(),
  Spectre.Subject.t() | term(),
  atom()
) :: {:ok, pid()} | {:error, :instance_not_found}

Looks up the live local Instance for agent + subject.

loop(instance, ref, opts \\ [])

Returns one committed operational-loop view.

loops(instance, opts \\ [])

Lists visible committed operational loops.

operation_events(instance, opts \\ [])

Returns committed operational events.

pause_loop(instance, ref, opts \\ [])

Requests a reversible loop pause.

put_delivery_consent(instance, consent, opts \\ [])

Stores revocable proactive-delivery consent.

quarantined_events(instance, opts \\ [])

Returns quarantined Event Envelopes.

reconcile_checkpoint(instance, opts \\ [])

Reconciles an ambiguous canonical-checkpoint write before any retry.

record_delivery(instance, receipt_id, outcome, detail, opts \\ [])

Records a Beam/host transport outcome against an authorization receipt.

register_vigil(instance, controller, input, opts \\ [])

Registers a durable Vigil on an Agent Instance.

renew_loop(instance, ref, expires_at, opts \\ [])

Renews a nonterminal Work, Vigil or controller expiry.

reset(session, state \\ %State{})

@spec reset(GenServer.server(), Spectre.State.t() | map() | keyword()) ::
  :ok | {:error, :instance_busy}

Replaces the current in-memory state of a supervised session.

:ok = Spectre.reset(session, %Spectre.State{current_flow: :checkout})

resolve_loop(instance, selector \\ nil, opts \\ [])

Resolves exactly one visible operational loop without model guessing.

resolve_policy(agent_or_session, result, resolution, opts \\ [])

@spec resolve_policy(
  module() | GenServer.server(),
  Spectre.Result.t() | {:awaitable, term()},
  Spectre.Policy.resolution(),
  keyword()
) :: {:ok, Spectre.Result.t()} | {:error, term()}

Resolves an open policy from a trusted host decision.

This is intended for durable facts already known by the host, such as terms accepted in another channel. The resolution label must be declared by the policy. For agent modules, Spectre persists the approved/rejected state before returning. For sessions it also advances the session's in-memory state.

Pass {:awaitable, id} instead of a Result to resolve the exact gate against current state. This form is required for externally addressed approvals because conversation turns may advance while the gate remains open.

This function is a host authority boundary, not an authentication mechanism. The caller must authenticate and authorize the actor. The compact tuple form creates a source: :host resolution; pass an explicit Spectre.Policy.Resolution to attach application-owned audit metadata.

{:ok, approved} =
  Spectre.resolve_policy(
    MyApp.Agent,
    awaiting_result,
    {:accept, :terms_accepted},
    assigns: %{user: user}
  )

{:ok, resolution} =
  Spectre.Policy.Resolution.new(
    :accept,
    :terms_accepted,
    :host,
    %{approval_ticket: "approval-42"}
  )

{:ok, approved} =
  Spectre.resolve_policy(
    session,
    {:awaitable, awaitable.id},
    resolution
  )

resume(instance, ref, command, opts \\ [])

@spec resume(GenServer.server(), Spectre.Run.Ref.t(), term(), keyword()) ::
  {:ok, Spectre.Turn.t()} | {:error, term()}

Resumes a Run owned by an Agent Instance.

resume_loop(instance, ref, opts \\ [])

Resumes a reversibly paused loop.

resume_stream(instance, stream, opts \\ [])

@spec resume_stream(GenServer.server(), Spectre.Inference.Stream.t(), keyword()) ::
  {:ok, Spectre.Inference.Stream.t()} | {:error, term()}

Returns the replacement Enumerable for a stream interrupted by Instance restart.

revoke_definition(instance, definition_ref \\ :active, opts \\ [])

Revokes current Definition authority.

revoke_delivery_consent(instance, consent_id, opts \\ [])

Revokes proactive-delivery consent.

rollback(instance, candidate_ref, opts \\ [])

Rolls activation back to an explicitly selected ancestor Candidate.

skill_state(instance, skill_id, opts \\ [])

Returns one active or explicitly selected first-class Skill-state branch.

skill_state_branches(instance, skill_id, opts \\ [])

Lists first-class Skill-state branches.

start_controller(instance, controller, input, opts \\ [])

Starts an authorized external controller on the shared runtime.

start_execution(instance, materialization, opts \\ [])

Starts a verified data-driven Work materialization on an Agent Instance.

start_work(instance, controller, input, opts \\ [])

Starts a precise Work on an Agent Instance.

state(session)

@spec state(GenServer.server()) :: Spectre.State.t()

Returns the current in-memory state of a supervised session.

%Spectre.State{} = Spectre.state(session)

stop_loop(instance, ref, reason \\ :stopped, opts \\ [])

Stops a loop terminally.

stream(instance, input, opts \\ [])

@spec stream(GenServer.server(), Spectre.Input.t() | String.t() | map(), keyword()) ::
  {:ok, Spectre.Inference.Stream.t()} | {:error, term()}

Starts a bounded pull stream on an Agent Instance.

Streaming is an Instance capability because the Run, budget, fencing and terminal result remain canonical. Stateless agent-module calls are rejected explicitly instead of falling back to a buffered one-shot completion.

subscribe_operation_events(instance_or_ref, opts \\ [])

Subscribes the caller to committed local operational events.

summon(opts)

@spec summon(keyword()) :: GenServer.on_start()

Summons the Server bound to an Agent, or its legacy Instance/Session runtime.

{:ok, pid} = Spectre.summon(agent: MyApp.Agent, subject: account.id)

An Agent with server: uses the Server runtime. Supplying :subject selects its unique local owner. Agents without server: preserve the legacy subject-scoped Instance or conversation-scoped Session path.

summon(supervisor, agent, opts)

Summons a session under a Spectre.Supervisor.

{:ok, pid} = Spectre.summon(MyApp.SpectreSupervisor, MyApp.Agent, [])

transition_definition_lifecycle(instance, definition_ref, axis, value, opts \\ [])

Transitions one Definition lifecycle axis.

transition_skill_state_retention(instance, skill_id, branch_id, retention, opts \\ [])

Transitions one dormant Skill-state branch retention status.

trigger_loop(instance, ref, trigger, opts \\ [])

Delivers a declared trigger to a waiting loop.

turn(agent_or_session, input, opts \\ [])

@spec turn(
  module() | GenServer.server(),
  Spectre.Input.t() | String.t() | map(),
  keyword()
) ::
  {:ok, Spectre.Turn.t()} | {:error, term()}

Runs the retained Instance/Run path to its first observable boundary.

This returns a legacy public Turn, not a Server command result or GAM Act.

{:ok, turn} = Spectre.turn(MyApp.Agent, "hello")
{:reply, result} = turn.decision
{:reply, "Hello!", ref} = turn.observable

unsubscribe_operation_events(instance_or_ref)

Removes the caller's local operational-event subscription.

update_and_resume_loop(instance, ref, update, opts \\ [])

Applies the durable pause-update-resume sequence.

update_loop(instance, ref, update, opts \\ [])

Applies a version-fenced loop update.

update_skill_state(instance, skill_id, value, opts \\ [])

Updates one active Skill-state branch through schema and revision fences.

version()

@spec version() :: String.t()

Returns the running Spectre library version.