Liking cljdoc? Tell your friends :D

com.blockether.vis.internal.loop.transcript

Prompt and transcript assembly for provider requests.

Replays prior turns as conversation, freezes iteration results into append-only messages, replays images and preserved reasoning, exposes the single python_execution tool, places prompt-cache breakpoints, tracks cache reuse, and sends an assembled request through the session's LLM client.

Prompt and transcript assembly for provider requests.

Replays prior turns as conversation, freezes iteration results into append-only
messages, replays images and preserved reasoning, exposes the single
`python_execution` tool, places prompt-cache breakpoints, tracks cache reuse,
and sends an assembled request through the session's LLM client.
raw docstring

actual-llm-modelclj

(actual-llm-model resolved-model ask-result)

Model that actually served an ask-result. See actual-llm-provider.

Model that actually served an ask-result. See `actual-llm-provider`.
sourceraw docstring

actual-llm-providerclj

(actual-llm-provider resolved-model ask-result)

Provider that actually served an ask-result. svar may route/fallback inside ask-code!, so prefer routed metadata over Vis' pre-call guess.

Provider that actually served an ask-result. svar may route/fallback
inside ask-code!, so prefer routed metadata over Vis' pre-call guess.
sourceraw docstring

answer-markdownclj

(answer-markdown answer)

Disposable model-facing text projection of a final typed answer. Canonical content remains structured and this projection is never transported as a second answer shape.

Disposable model-facing text projection of a final typed answer. Canonical
content remains structured and this projection is never transported as a
second answer shape.
sourceraw docstring

apply-summariesclj

(apply-summaries trailer-iters summaries)

Compact trailer-iters using fold_session intents, releasing covered payloads at iteration granularity. A summary carries concrete scopes, an optional gist, and its owning at_turn; a gist-less intent is a drop. Range intents are resolved by expand-through against the trailer's iteration scopes and the turns its boundary entries name.

Every covered iteration collapses: its output and assistant/tool-result pair leave memory as well as the wire. Explicit whole-turn intent (turns) also collapses that turn's request and closing entries, but only for turns before the intent's owner: a turn's own request and answer survive a fold issued during it. The earliest covered entry receives one synthetic form containing the gist or a dropped marker. Pure and deterministic; persisted iteration records are untouched. Real compaction, not presentation.

Compact `trailer-iters` using `fold_session` intents, releasing covered payloads at
iteration granularity. A summary carries concrete `scopes`, an optional
`gist`, and its owning `at_turn`; a gist-less intent is a drop. Range intents
are resolved by `expand-through` against the trailer's iteration scopes and
the turns its boundary entries name.

Every covered iteration collapses: its output and assistant/tool-result pair
leave memory as well as the wire. Explicit whole-turn intent (`turns`) also
collapses that turn's request and closing entries, but only for turns before
the intent's owner: a turn's own request and answer survive a fold issued
during it. The earliest covered entry receives one synthetic form containing
the gist or a dropped marker. Pure and deterministic; persisted iteration
records are untouched. Real compaction, not presentation.
sourceraw docstring

ask-code-with-session!clj

(ask-code-with-session! environment resolved-model ask-opts)

Keep one opaque Svar session per effective router for a provider whose prompt cache is a server continuation; other providers stay one-shot.

Keep one opaque Svar session per effective router for a provider whose prompt
cache is a server continuation; other providers stay one-shot.
sourceraw docstring

attach-llm-routing-summaryclj

(attach-llm-routing-summary result selected-model iteration-result)
source

block-duration-msclj

(block-duration-ms block)
source

close-llm-session!clj

(close-llm-session! session-atom)

Close and forget an environment-owned stateful provider session.

Close and forget an environment-owned stateful provider session.
sourceraw docstring

compact-prompt-cache-entryclj

(compact-prompt-cache-entry entry)

Restore telemetry from a disk checkpoint without retaining request or answer text.

Restore telemetry from a disk checkpoint without retaining request or answer text.
sourceraw docstring

context-overflow-token-dataclj

(context-overflow-token-data overflow)

Keep rejection counts separate from response usage. Preflight may count remotely; the tokens error type alone identifies neither a provider refusal nor a local count.

Keep rejection counts separate from response usage. Preflight may count remotely;
the tokens error type alone identifies neither a provider refusal nor a local count.
sourceraw docstring

conversation-messagesclj

(conversation-messages base trailer-iters replay-target options)

Combine the selected base and folded trailer exactly as sent to the provider.

Combine the selected base and folded trailer exactly as sent to the provider.
sourceraw docstring

conversation-suffixclj

(conversation-suffix trailer-iters target)
(conversation-suffix trailer-iters target opts)

The append-only conversation suffix itself: conversation-suffix-groups concatenated in iteration order. Callers that need to know WHICH iteration a message came from (the fold estimator, which prices what one fold removes) take the groups; everyone building a request takes this.

The append-only conversation suffix itself: `conversation-suffix-groups`
concatenated in iteration order. Callers that need to know WHICH iteration a
message came from (the fold estimator, which prices what one fold removes) take
the groups; everyone building a request takes this.
sourceraw docstring

conversation-trailer-for-baseclj

(conversation-trailer-for-base trailer-iters resumed?)

Hide what an exact carried request prefix already holds: every prior turn's request, steps and answer, and the current turn's own request.

Hide what an exact carried request prefix already holds: every prior turn's
request, steps and answer, and the current turn's own request.
sourceraw docstring

current-session-summariesclj

(current-session-summaries environment)

Immutable fold-ledger value used to decide whether a provider prefix is still semantic.

Immutable fold-ledger value used to decide whether a provider prefix is still semantic.
sourceraw docstring

estimator-undercountclj

(estimator-undercount reported-tokens local-tokens)

How far the local estimate undercounts a rejection's reported size.

The rejection may be preflight or provider-side; this is a conservative budget factor, not provider-usage telemetry. nil when either side is missing, never below 1.0.

How far the local estimate undercounts a rejection's reported size.

The rejection may be preflight or provider-side; this is a conservative budget
factor, not provider-usage telemetry. nil when either side is missing, never below 1.0.
sourceraw docstring

eval-block-roleclj

(eval-block-role result)

Block role for the outer lifecycle event — one of the four values in the iteration-block role enum: :answer the model's final answer to the user :tool any Python evaluation (tool call OR raw user code) :nudge system-emitted reminders / diagnostics :thinking model reasoning blocks The previous :vis/error role is gone — errors are derived from :success? on the envelope (or block-level :error slot for non-tool evals). Replaces the prior eval-rendering-kind fn.

Block role for the outer lifecycle event — one of the four values
in the iteration-block role enum:
  :answer    the model's final answer to the user
  :tool      any Python evaluation (tool call OR raw user code)
  :nudge     system-emitted reminders / diagnostics
  :thinking  model reasoning blocks
The previous `:vis/error` role is gone — errors are derived from
`:success?` on the envelope (or block-level `:error` slot for
non-tool evals). Replaces the prior `eval-rendering-kind` fn.
sourceraw docstring

eval-envelopeclj

(eval-envelope turn-prefix iteration form-idx form-count result rendering-kind)

Generic canonical envelope for every executed block that passes through the Vis eval pipeline. Tool calls can add nested metadata in their returned envelope; this records the outer block evaluation so plain calls and tool calls share a common block-level trace.

Generic canonical envelope for every executed block that passes
through the Vis eval pipeline. Tool calls can add nested metadata
in their returned envelope; this records the outer block
evaluation so plain calls and tool calls share a common block-level
trace.
sourceraw docstring

failed-turn-contentclj

(failed-turn-content answer trace)

Content blocks for a turn that ended in FAILURE - never a throw.

content/answer-content VALIDATES, and the fallback answer a failed turn carries is frequently not answer-shaped: a provider-exhaustion turn hands back a raw error value. Unguarded, that validation throw escapes send! BEFORE persist-turn-outcome! runs, so the turn keeps no status, no error and no counters, the UI shows an empty turn, and "Final answer must be canonical content or Markdown prose" replaces the provider failure that actually killed it in the log. Measured: an upstream stream timeout turned into a turn with no answer and no error card at all, and the human had to type 'Continue'.

On a throw the content is rebuilt from the last iteration error in trace - the same provider failure the gateway card names.

Content blocks for a turn that ended in FAILURE - never a throw.

`content/answer-content` VALIDATES, and the fallback answer a failed turn
carries is frequently not answer-shaped: a provider-exhaustion turn hands back
a raw error value. Unguarded, that validation throw escapes `send!` BEFORE
[[persist-turn-outcome!]] runs, so the turn keeps no status, no error and no
counters, the UI shows an empty turn, and "Final answer must be canonical
content or Markdown prose" replaces the provider failure that actually killed
it in the log. Measured: an upstream stream timeout turned into a turn with no
answer and no error card at all, and the human had to type 'Continue'.

On a throw the content is rebuilt from the last iteration error in `trace` -
the same provider failure the gateway card names.
sourceraw docstring

iteration-record-scopeclj

(iteration-record-scope rec)

Use an input-only iteration's scope without inventing a tool form.

Use an input-only iteration's scope without inventing a tool form.
sourceraw docstring

llm-idclj

(llm-id provider model)
source

llm-routing-summaryclj

(llm-routing-summary selected-model iteration-result)
source

load-prompt-cache-stateclj

(load-prompt-cache-state db-info session-state-id)

Load one fresh exact-prefix checkpoint; malformed or stale state is a safe miss.

Load one fresh exact-prefix checkpoint; malformed or stale state is a safe miss.
sourceraw docstring

log-context-token-counts!clj

(log-context-token-counts! messages
                           health
                           provider
                           model
                           request-context
                           observation)

Compare the persisted request estimate with its own response usage, not a prior request or retry. The health record names the prepared or logical projection. Reasoning contributes only logical aggregate sizes; counting failure is non-fatal.

Compare the persisted request estimate with its own response usage, not a prior
request or retry. The health record names the prepared or logical projection.
Reasoning contributes only logical aggregate sizes; counting failure is non-fatal.
sourceraw docstring

markdown-answer?clj

(markdown-answer? v)

True for the canonical final-answer VALUE: {:answer string}. The answer is the plain prose the model replies with; answer-fn wraps that string into this {:answer string} shape. The only other accepted value is the needs-input-answer? map.

True for the canonical final-answer VALUE: `{:answer string}`.
The answer is the plain prose the model replies with; `answer-fn` wraps that
string into this `{:answer string}` shape. The only other accepted value is
the `needs-input-answer?` map.
sourceraw docstring

message-cache-dataclj

(message-cache-data prior messages)

Fingerprint messages without retaining their payloads. Weak identity hints avoid serializing unchanged live messages again; collection only costs a rehash.

Fingerprint messages without retaining their payloads. Weak identity hints avoid
serializing unchanged live messages again; collection only costs a rehash.
sourceraw docstring

model-accounting-routingclj

(model-accounting-routing routing {:keys [provider name model]})

Inspect this resolved route, even when inference is allowed to fall back elsewhere.

Inspect this resolved route, even when inference is allowed to fall back elsewhere.
sourceraw docstring

model-facing-toolsclj

(model-facing-tools caps)

The ONE provider-visible tool. python_execution IS the model-facing surface: every other capability is already a bare Python name inside that sandbox, so a second JSON schema advertises a door the model can open anyway — and charges for it on every request. Discovery of the rest is pulled, not pushed: apropos(pattern) filters names and doc(name) retrieves, both from inside a block.

The raw-result contract is folded into the description here, so the one tool cannot reach a provider without saying what it hands back. Nothing is advertised strict: a per-wire grammar opt-in has no place on a surface that must reach every provider.

The ONE provider-visible tool. `python_execution` IS the model-facing surface:
every other capability is already a bare Python name inside that sandbox, so a
second JSON schema advertises a door the model can open anyway — and charges
for it on every request. Discovery of the rest is pulled, not pushed:
`apropos(pattern)` filters names and `doc(name)` retrieves, both from inside a block.

The raw-result contract is folded into the description here, so the one tool
cannot reach a provider without saying what it hands back. Nothing is
advertised `strict`: a per-wire grammar opt-in has no place on a surface that
must reach every provider.
sourceraw docstring

needs-input-answer?clj

(needs-input-answer? v)

True for explicit clarification/needs-input answer payloads.

Foundation exposes this through (needs-input ...); the loop keeps the predicate data-shaped instead of depending on foundation namespaces so the core runtime has no extension cycle.

True for explicit clarification/needs-input answer payloads.

Foundation exposes this through `(needs-input ...)`; the loop
keeps the predicate data-shaped instead of depending on foundation
namespaces so the core runtime has no extension cycle.
sourceraw docstring

normalize-tool-callsclj

(normalize-tool-calls tool-calls)

THE DOOR: every tool call svar returns enters the engine HERE.

svar hands model-authored arguments over strings-only — its response parse leaves tool-argument subtrees UNINTERNED, so a provider can no longer deliver :path — which makes this pass exactly one thing: the single place MODEL DRIFT is repaired (a literal ":path" key, a stray keyword value out of an extension's EDN), at the point where ask-code!'s result becomes engine data.

Vis is strings-only end to end — the sandbox, the synthesized Python, persistence and the wire all speak snake_case strings — so the whole tool-call vector is normalized ONCE. Everything downstream — call synthesis, replay elision, receipts and iteration records — reads plain string keys and must NOT re-check a keyword variant.

A repeated call id is a provider defect: report it and pass every call through. Nothing here merges or drops calls.

THE DOOR: every tool call svar returns enters the engine HERE.

svar hands model-authored arguments over strings-only — its response parse
leaves tool-argument subtrees UNINTERNED, so a provider can no longer deliver
`:path` — which makes this pass exactly one thing: the single place MODEL
DRIFT is repaired (a literal `":path"` key, a stray keyword value out of an
extension's EDN), at the point where `ask-code!`'s result becomes engine
data.

Vis is strings-only end to end — the sandbox, the synthesized Python,
persistence and the wire all speak snake_case strings — so the whole
tool-call vector is normalized ONCE. Everything downstream — call synthesis,
replay elision, receipts and iteration records — reads plain
string keys and must NOT re-check a keyword variant.

A repeated call id is a provider defect: report it and pass every call
through. Nothing here merges or drops calls.
sourceraw docstring

note-prompt-cache-request!clj

(note-prompt-cache-request! history-atom
                            provider
                            model
                            prompt-cache-context
                            messages
                            input-tokens
                            cache-read-tokens
                            request-start-ms)

Replace one route's request baseline and answer {:reusable-tokens n :continuity kw :reuse-kind :exact|:estimated|nil}.

Exact append-only requests use the prior provider-counted input. Rewrites use a serialized-size estimate in provider cache order: Svar's fixed Python tool/preamble, then Vis messages, but only through the last breakpoint the shared prefix reached. Bytes after that anchor were never independently cacheable. A provider cache-read is hard evidence and floors an estimate; the current input always caps it.

A changed Svar context id means tools, account namespace, adapter preamble, route or cache policy changed. Its baseline rotates under :cache-context-changed and cannot authorize replay of the old large request.

Replace one route's request baseline and answer `{:reusable-tokens n
:continuity kw :reuse-kind :exact|:estimated|nil}`.

Exact append-only requests use the prior provider-counted input. Rewrites use a
serialized-size estimate in provider cache order: Svar's fixed Python tool/preamble,
then Vis messages, but only through the last breakpoint the shared prefix reached.
Bytes after that anchor were never independently cacheable. A provider cache-read is
hard evidence and floors an estimate; the current input always caps it.

A changed Svar context id means tools, account namespace, adapter preamble, route
or cache policy changed. Its baseline rotates under `:cache-context-changed` and
cannot authorize replay of the old large request.
sourceraw docstring

persist-prompt-cache-state!clj

(persist-prompt-cache-state! environment provider model completion)

Best-effort overwrite of the one restart-safe exact-prefix checkpoint.

Best-effort overwrite of the one restart-safe exact-prefix checkpoint.
sourceraw docstring

persist-turn-outcome!clj

(persist-turn-outcome! db-info session-turn-id opts)
(persist-turn-outcome! db-info session-turn-id opts claim!)

Persist a claimed terminal outcome. If its snapshot fails, retry without CTX before degrading to bounded error content. Preserve status and counters even when neither the answer nor context can be stored. Log every failed write; never include a potentially unbounded or private payload in the fallback. Returns false if another terminal owns the turn or all writes fail.

Persist a claimed terminal outcome. If its snapshot fails, retry without CTX
before degrading to bounded error content. Preserve status and counters even
when neither the answer nor context can be stored. Log every failed write;
never include a potentially unbounded or private payload in the fallback.
Returns false if another terminal owns the turn or all writes fail.
sourceraw docstring

persisted-user-inputclj

(persisted-user-input user-input)

user-input as the step record stores it, without image bytes. When the step stored its files on the turn, :attachments keeps their row metadata, so a replay names each one by attachment id and a channel can fetch its pixels; a file the wire refused is then named once, by that id.

`user-input` as the step record stores it, without image bytes. When the step
stored its files on the turn, `:attachments` keeps their row metadata, so a
replay names each one by attachment id and a channel can fetch its pixels; a
file the wire refused is then named once, by that id.
sourceraw docstring

previous-request-usageclj

(previous-request-usage environment current-turn-id)

Return the latest persisted provider request before current-turn-id.

:session/utilization is rendered before the next provider call, so iteration 1 cannot use current-turn API usage yet. Seed only the last request size used for context pressure. Provider-cache telemetry is Svar-owned, process-local, and intentionally never reconstructed from historical database rows.

Return the latest persisted provider request before `current-turn-id`.

`:session/utilization` is rendered before the next provider call, so iteration 1
cannot use current-turn API usage yet. Seed only the last request size used for
context pressure. Provider-cache telemetry is Svar-owned, process-local, and
intentionally never reconstructed from historical database rows.
sourceraw docstring

prior-turn-trailerclj

(prior-turn-trailer environment current-turn-id turn-position summaries)

The conversation before the current turn as trailer entries, oldest first: for each prior turn its request, its settled steps and its closing answer.

Fold summaries apply before any iteration body, artifact or turn row is read, so a collapsed entry costs no read. Synthetic slash turns stay local-only; the current turn, running turns and later turns are excluded. Nothing here replays provider-native reasoning (:preserved-thinking/replay? false).

The conversation before the current turn as trailer entries, oldest first:
for each prior turn its request, its settled steps and its closing answer.

Fold summaries apply before any iteration body, artifact or turn row is read,
so a collapsed entry costs no read. Synthetic slash turns stay local-only;
the current turn, running turns and later turns are excluded. Nothing here
replays provider-native reasoning (`:preserved-thinking/replay? false`).
sourceraw docstring

prompt-cache-policyclj

(prompt-cache-policy provider)

Static descriptor shared with Svar's cache-context fingerprint. It describes the placement [[apply-cache-breakpoints]] owns; Vis exposes one provider tool, python_execution, whose final wire schema is fingerprinted separately by Svar.

Static descriptor shared with Svar's cache-context fingerprint. It describes the
placement [[apply-cache-breakpoints]] owns; Vis exposes one provider tool,
`python_execution`, whose final wire schema is fingerprinted separately by Svar.
sourceraw docstring

prompt-message-base!clj

(prompt-message-base! base-atom summaries canonical-messages-fn)

Keep BASE while its fold ledger is unchanged; otherwise canonicalize exactly once.

Keep BASE while its fold ledger is unchanged; otherwise canonicalize exactly once.
sourceraw docstring

prose-beyond-codeclj

(prose-beyond-code prose tool-calls)

The assistant prose (a model :content string streamed ALONGSIDE a tool call) is worth showing ONLY when it carries commentary BEYOND the code it's about to run. Models frequently restate the exact python_execution code in their message — as a fenced block or verbatim — which then renders as a dim DUPLICATE of the real code block. So strip any fenced code from the prose and compare what's left (and the whole prose, de-whitespaced) against the concatenated tool-call code; return the prose when it still says something, else nil. tool-calls are the model's python_execution calls; their :input carries code.

The assistant `prose` (a model `:content` string streamed ALONGSIDE a tool
call) is worth showing ONLY when it carries commentary BEYOND the code it's
about to run. Models frequently restate the exact `python_execution` code in their
message — as a ```fenced``` block or verbatim — which then renders as a dim
DUPLICATE of the real code block. So strip any fenced code from the prose and
compare what's left (and the whole prose, de-whitespaced) against the
concatenated tool-call code; return the prose when it still says something,
else nil. `tool-calls` are the model's `python_execution` calls; their `:input` carries
`code`.
sourceraw docstring

provider-call-chunkclj

(provider-call-chunk iteration-position resolved-model started-at-ms)
(provider-call-chunk iteration-position
                     resolved-model
                     started-at-ms
                     watchdog-timeouts)

The lifecycle marker that opens ONE provider call.

It names the provider and the model the request is dispatched to: when the stream then goes silent, that marker is the only thing the gateway watchdog has left to attribute the stall to, and a failure card that cannot say WHICH provider went quiet tells the human nothing.

It also names WHY the request is being made (:reason): a tool-result continuation that the loop decided on its own must not look like the human pressing enter again.

The lifecycle marker that opens ONE provider call.

It names the provider and the model the request is dispatched to: when the
stream then goes silent, that marker is the only thing the gateway watchdog
has left to attribute the stall to, and a failure card that cannot say WHICH
provider went quiet tells the human nothing.

It also names WHY the request is being made (`:reason`): a tool-result
continuation that the loop decided on its own must not look like the human
pressing enter again.
sourceraw docstring

provider-history-metadataclj

(provider-history-metadata db turn-ids)

Read byte-free history, validating only explicitly identified local-command candidates.

Read byte-free history, validating only explicitly identified local-command candidates.
sourceraw docstring

reasoning-effort-configurable?clj

(reasoning-effort-configurable? resolved-model)

True when a model accepts a CALLER-selected reasoning effort.

svar decides this, not Vis: :reasoning-effort? is stamped on every model the router normalizes, from the WIRE that model rides. :reasoning? only says the model thinks — GitHub Copilot's Gemini/Grok tiers think but are :server-managed on the OpenAI-compatible wire, and Z.ai GLM thinking is binary, so neither accepts a depth and neither may show a depth control. Copilot's Claude tier rides the native Anthropic wire and DOES take one.

True when a model accepts a CALLER-selected reasoning effort.

svar decides this, not Vis: `:reasoning-effort?` is stamped on every model
the router normalizes, from the WIRE that model rides. `:reasoning?` only
says the model thinks — GitHub Copilot's Gemini/Grok tiers think but are
`:server-managed` on the OpenAI-compatible wire, and Z.ai GLM thinking is
binary, so neither accepts a depth and neither may show a depth control.
Copilot's Claude tier rides the native Anthropic wire and DOES take one.
sourceraw docstring

reasoning-effort-iteration-evidenceclj

(reasoning-effort-iteration-evidence iteration
                                     requested
                                     selected-model
                                     iteration-result)
source

recall-optionsclj

(recall-options {:keys [describe-images] :as options})

options for a render that RE-PRICES the trailer — each fold-search candidate, an overflow rescue, a fold estimate — with the describer swapped for a cache-only recall. What the request's own render described survives the fold, and no candidate starts a round trip of its own.

`options` for a render that RE-PRICES the trailer — each fold-search candidate, an
overflow rescue, a fold estimate — with the describer swapped for a cache-only
recall. What the request's own render described survives the fold, and no
candidate starts a round trip of its own.
sourceraw docstring

record-provider-inputclj

(record-provider-input ctx response)

Stamp this response's input, even when missing, and settle a pending fold batch. The signed reduction is net request shrinkage, not isolated fold savings or cost.

Stamp this response's input, even when missing, and settle a pending fold batch.
The signed reduction is net request shrinkage, not isolated fold savings or cost.
sourceraw docstring

replay-contextclj

(replay-context resolved-model)

Small identity map for the model the next provider call will run against: provider, model name, and the :capabilities its config entry declared.

Thinking replay reads the first two. Provider-native thinking signatures are not portable: z.ai stores reasoning text under :thinking-signature, Anthropic expects an HMAC signature, and OpenAI Responses stores a JSON reasoning item. Replaying across a provider/model switch corrupts the next request (Anthropic 400: invalid signature in thinking block).

The image gate reads all three — see target-supports-vision?.

Small identity map for the model the next provider call will run against:
provider, model name, and the `:capabilities` its config entry declared.

Thinking replay reads the first two. Provider-native thinking signatures are
not portable: z.ai stores reasoning text under `:thinking-signature`,
Anthropic expects an HMAC signature, and OpenAI Responses stores a JSON
reasoning item. Replaying across a provider/model switch corrupts the next
request (Anthropic 400: invalid signature in thinking block).

The image gate reads all three — see `target-supports-vision?`.
sourceraw docstring

replay-image-describerclj

(replay-image-describer environment context preferred-provider)

Describer for replayed figures, or nil when the vision fallback is off or nothing in the fleet can see. Resolved per request (a provider switch mid-session takes effect immediately) but it costs only router arithmetic: the calls happen lazily, per image actually in play, and each image is described once, then recalled.

Describer for replayed figures, or nil when the vision fallback is off or nothing
in the fleet can see. Resolved per request (a provider switch mid-session takes
effect immediately) but it costs only router arithmetic: the calls happen lazily,
per image actually in play, and each image is described once, then recalled.
sourceraw docstring

request-fold-estimatorclj

(request-fold-estimator {:keys [message-base-atom canonical-messages-fn
                                trailer-iters emergency-summaries-atom
                                replay-target conversation-options
                                count-messages-fn]})

Price the before/after request projections, including carried prefixes and replacement gists. Neither the live base nor its fold ledger is changed by this local-tokenizer estimate.

Price the before/after request projections, including carried prefixes and replacement gists.
Neither the live base nor its fold ledger is changed by this local-tokenizer estimate.
sourceraw docstring

request-log-contextclj

(request-log-context environment iteration context)

Content-free identity shared by Svar dispatch, token comparison and rescue logs.

Content-free identity shared by Svar dispatch, token comparison and rescue logs.
sourceraw docstring

resolved-prompt-cache-contextclj

(resolved-prompt-cache-context environment resolved-model routing extra-body)

Ask Svar for the opaque fixed-prefix/cache-namespace identity of one pinned route.

Ask Svar for the opaque fixed-prefix/cache-namespace identity of one pinned route.
sourceraw docstring

resumable-prompt-message-baseclj

(resumable-prompt-message-base state
                               provider
                               model
                               prompt-cache-context
                               turn-position
                               summaries
                               stable-messages
                               turn-messages)

Return an exact cross-turn provider prefix, or nil when any safety key changed.

A hit preserves the complete final request byte-for-byte, then appends the accepted assistant answer and this turn's user message. Same route, adjacent turn, fresh cache residency, unchanged fold ledger, and an identical stable system prefix are all required; the canonical conversation owns every miss.

Return an exact cross-turn provider prefix, or nil when any safety key changed.

A hit preserves the complete final request byte-for-byte, then appends the
accepted assistant answer and this turn's user message. Same route, adjacent
turn, fresh cache residency, unchanged fold ledger, and an identical stable
system prefix are all required; the canonical conversation owns every miss.
sourceraw docstring

runtime-turn-prefixclj

(runtime-turn-prefix environment)
source

same-prompt-cache-context?clj

(same-prompt-cache-context? left right)
source

session-turn-positionclj

(session-turn-position environment session-turn-id)
source

stamp-iter-universe!clj

(stamp-iter-universe! ctx-atom trailer-iters)
(stamp-iter-universe! ctx-atom trailer-iters wire-iters)
(stamp-iter-universe! ctx-atom trailer-iters wire-iters pricing)

Record the raw iteration universe while pricing only wire-iters — the current provider-visible projection. A resolved model tokenizes each entry's rendered messages; without one, weights degrade to tokenizer estimates. A prior turn's request and closing messages price as its engine_turn_weights entry, so a whole-turn fold knows what it removes beyond the turn's steps.

Record the raw iteration universe while pricing only `wire-iters` — the current
provider-visible projection. A resolved model tokenizes each entry's rendered
messages; without one, weights degrade to tokenizer estimates. A prior turn's
request and closing messages price as its `engine_turn_weights` entry, so a
whole-turn fold knows what it removes beyond the turn's steps.
sourceraw docstring

stamp-prompt-cache-status!clj

(stamp-prompt-cache-status! ctx-atom status)

Store Svar's opaque current-turn prompt-cache status for diagnostics.

Store Svar's opaque current-turn prompt-cache status for diagnostics.
sourceraw docstring

stamp-served-route!clj

(stamp-served-route! env iteration-result)

Record the provider/model that actually answered this iteration.

Record the provider/model that actually answered this iteration.
sourceraw docstring

stamp-utilization!clj

(stamp-utilization! ctx-atom util)

Monotonic update of "engine_utilization" on the ctx-atom. UPGRADES when a real measurement (util) exists; NEVER removes an existing value. A transient nil — iter-1 seed miss, or an errored iteration that returned no usage — must not BLANK an already-shown utilization; that flicker is the sometimes works / sometimes doesn't bug. The last value carries on the per-session live atom (:engine/* is stripped only at persist time) until a fresh request refreshes it; a brand-new session starts blank because nothing was ever stamped.

Monotonic update of `"engine_utilization"` on the ctx-atom. UPGRADES when a
real measurement (`util`) exists; NEVER removes an existing value. A
transient nil — iter-1 seed miss, or an errored iteration that returned no
usage — must not BLANK an already-shown utilization; that flicker is the
`sometimes works / sometimes doesn't` bug. The last value carries on the
per-session live atom (`:engine/*` is stripped only at persist time) until
a fresh request refreshes it; a brand-new session starts blank because
nothing was ever stamped.
sourceraw docstring

target-supports-vision?clj

(target-supports-vision? target)

True when THIS PROVIDER's serving of the replay target takes image input.

Provider-scoped on purpose. The model NAME is not the answer: Copilot proxies vision-capable Claude/GPT under names svar's static table never learned, every OpenRouter model is a namespaced slug, and gpt-4o-search-preview matches the gpt-4o vision pattern while serving text only — an image block sent there is a 400 that repeats on every later turn, because attachments replay. So the question goes to provider-model-metadata, which reads models.dev's per-provider input modalities and lets a :capabilities set written in config override them.

A provider that already ANSWERED the question outranks every table, at the scope its answer proves: an endpoint whose WIRE refused an image content part outright is blind for everything it serves (vision-describe/image-blind-provider?), while a model that answered it cannot read pixels is blind by NAME wherever it is served from (vision-describe/image-blind-model?) and leaves its provider's other models seeing.

True when THIS PROVIDER's serving of the replay `target` takes image input.

Provider-scoped on purpose. The model NAME is not the answer: Copilot proxies
vision-capable Claude/GPT under names svar's static table never learned, every
OpenRouter model is a namespaced slug, and `gpt-4o-search-preview` matches the
`gpt-4o` vision pattern while serving text only — an image block sent there is a
400 that repeats on every later turn, because attachments replay. So the question
goes to `provider-model-metadata`, which reads models.dev's per-provider input
modalities and lets a `:capabilities` set written in config override them.

A provider that already ANSWERED the question outranks every table, at the scope
its answer proves: an endpoint whose WIRE refused an image content part outright
is blind for everything it serves (`vision-describe/image-blind-provider?`), while
a model that answered it cannot read pixels is blind by NAME wherever it is served
from (`vision-describe/image-blind-model?`) and leaves its provider's other models
seeing.
sourceraw docstring

terminal-incomplete-turn-status?clj

(terminal-incomplete-turn-status? status)
source

turn-error-dataclj

(turn-error-data answer)

First canonical error block from a final answer, or nil.

First canonical error block from a final answer, or nil.
sourceraw docstring

turn-eval-evidenceclj

(turn-eval-evidence requested trace)
source

user-input-messagesclj

(user-input-messages user-input vision?)

The user messages one step received from the queue (→ Send now), in queue order, or []. Each entry becomes one user message: its request text, then one image block for each attachment that carries bytes when vision? is true. A file that cannot go on the wire is named in the text, so the model can open it itself: by its attachment id when the step stored it, as a prior turn's request names its files, and otherwise by its name.

The user messages one step received from the queue (`→ Send now`), in queue
order, or `[]`. Each entry becomes one `user` message: its request text, then
one image block for each attachment that carries bytes when `vision?` is true.
A file that cannot go on the wire is named in the text, so the model can open
it itself: by its attachment id when the step stored it, as a prior turn's
request names its files, and otherwise by its name.
sourceraw docstring

user-slash-iteration?clj

(user-slash-iteration? iteration)

True for a synthetic slash-command iteration. These rows stay in local transcript/audit history but must never enter a later provider request.

True for a synthetic slash-command iteration. These rows stay in local
transcript/audit history but must never enter a later provider request.
sourceraw docstring

validate-iteration-blocks!clj

(validate-iteration-blocks! blocks)

Fail fast if a stored block lost its execution envelope.

Fail fast if a stored block lost its execution envelope.
sourceraw docstring

verbosity-configurable?clj

(verbosity-configurable? resolved-model)

True when a model accepts a caller-selected answer verbosity.

Also svar's call: :verbosity-style is stamped from the wire, so every provider on the OpenAI Responses endpoint (Codex AND GitHub Copilot's GPT tier) gets the knob and nothing else does. Never test a provider id here.

True when a model accepts a caller-selected answer verbosity.

Also svar's call: `:verbosity-style` is stamped from the wire, so every
provider on the OpenAI Responses endpoint (Codex AND GitHub Copilot's GPT
tier) gets the knob and nothing else does. Never test a provider id here.
sourceraw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close