import "std/agent/loop_call_resolution"
import "std/agent/loop_foundation"
import "std/agent/loop_resource_dispatch"
import "std/agent/loop_support"
import "std/agent/loop_tool_calls"
import "std/agent/loop_turn_options"
import { agent_transcript_text } from "std/agent/transcript"
import { protocol_violation_messages, violation_reports_lost_call } from "std/llm/tool_parse_result"
/**
* Build the one-shot directive injected as a final system fragment when the
* loop terminates mid-tool-use. It tells the model the turn/budget is spent,
* that no more tool calls are possible, and how to wrap up. A declared output
* contract replaces the prose response tags with its JSON-only shape.
*/
/**
* The response-protocol tail every wrap-up directive ends with. Without a
* declared output contract, the reply uses the terminal user-response tags and
* optional done sentinel. With a contract, it must be only the declared JSON
* value. The default and host-supplied directive share this protocol owner.
*
* @effects: [agent]
* @errors: []
*/
pub fn __agent_loop_wrapup_response_protocol_tail(opts: dict) {
if __agent_loop_has_terminal_output_contract(opts) {
return " Reply with ONLY a JSON value matching the declared output contract. Do not "
+ "emit prose, `<user_response>` or `<done>` tags, or any other surrounding text."
}
const sentinel = opts?.done_sentinel
if sentinel == nil || to_string(sentinel) == "" {
return " End with a concise `<user_response>...</user_response>` containing the final answer."
}
const tag = to_string(sentinel)
return " Emit a concise `<user_response>...</user_response>` with the final answer, then end with "
+ "`<done>"
+ tag
+ "</done>` exactly, as instructed by the response protocol."
}
/**
* Outcome-authority constraint appended to a HOST-supplied wrap-up directive.
*
* The terminal outcome (budget/turn exhaustion, stuck, verify-capped) is decided
* by the loop and stated to the model as fact; the wrap-up narrates it, it does
* NOT re-adjudicate it. A host directive may forget to say so, so the loop always
* appends this — a wrap-up that claims "I completed the task" on a failed run is
* the exact failure this guards against.
*/
pub const __AGENT_LOOP_WRAPUP_OUTCOME_AUTHORITY: string =
"The run's terminal outcome is already decided and is stated as fact in this instruction and the context above; narrate it truthfully and do NOT re-judge it or claim success on a run that did not succeed."
/**
* The wrap-up directive for a terminal turn.
*
* Default (no `opts.wrapup_directive`): today's generic budget/turn-limit
* summary directive, byte-identical to before, injected into the wrap-up SYSTEM
* prompt by the caller.
*
* Host-supplied (`opts.wrapup_directive` non-empty): the host owns the wording
* (product-specific sad-path narration, few-shot, language-generic framing). The
* loop composes it with the outcome-authority constraint and the shared
* response-protocol tail. The caller renders THIS variant as a trailing user
* message (keeping the system prompt byte-identical for prefix-cache reuse),
* never into the system prompt.
*
* @effects: [agent]
* @errors: []
*/
pub fn __agent_loop_wrapup_directive(opts: dict) {
const host_directive = trim(to_string(opts?.wrapup_directive ?? ""))
const tail = __agent_loop_wrapup_response_protocol_tail(opts)
if host_directive != "" {
return host_directive + " " + __AGENT_LOOP_WRAPUP_OUTCOME_AUTHORITY + tail
}
const base = "You have reached your turn/budget limit and cannot call any more tools. "
+ "Provide your final answer now: briefly summarize what you accomplished and what you "
+ "verified. Do not emit any tool call."
return base + tail
}
/**
* True when the host opted into a product-supplied terminal wrap-up by passing a
* non-empty `opts.wrapup_directive`. Gates the trailing-message rendering path,
* the structured-context block, and the tools==0 eligibility broadening.
*
* @effects: [agent]
* @errors: []
*/
pub fn __agent_loop_has_host_wrapup_directive(opts: dict) {
return trim(to_string(opts?.wrapup_directive ?? "")) != ""
}
/**
* The effective wrap-up context: the host's structured `opts.wrapup_context`
* (product facts such as files touched with line counts, verification receipts,
* veto context) with the loop's own terminal facts merged on top so they are
* AUTHORITATIVE — a host context can never override the real terminal kind or
* stop reason (the outcome-authority contract). Terminal facts are always
* present on the host path even when the host supplies no context, so the model
* always learns which terminal it is narrating.
*
* @effects: [agent]
* @errors: []
*/
pub fn __agent_loop_effective_wrapup_context(opts: dict, final_status: any, stop_reason: string?) {
const host_context = if type_of(opts?.wrapup_context) == "dict" {
opts.wrapup_context
} else {
{}
}
return host_context
+ {terminal_kind: final_status, final_status: final_status, stop_reason: stop_reason ?? ""}
}
/**
* Render an effective wrap-up context dict into a compact, labeled,
* language-generic facts block appended after the directive in the trailing
* wrap-up message. The loop stays agnostic to the host's key names — it emits
* the dict as deterministic JSON so any host's terminal facts reach the model
* verbatim while the host's directive explains how to read them. Returns "" only
* when serialization fails.
*
* @effects: [agent]
* @errors: []
*/
pub fn __agent_loop_render_wrapup_context(context: dict) {
if context == nil || type_of(context) != "dict" || len(keys(context)) == 0 {
return ""
}
const rendered = try {
json_stringify(context)
} catch (e) {
""
}
if trim(to_string(rendered)) == "" {
return ""
}
return "\n\nTerminal context (authoritative facts):\n" + to_string(rendered)
}
/**
* True when the terminal turn cannot itself carry the final user response.
* Exhaustion/cap states need a closing report because the loop imposed the
* stop. A verified policy stop needs one because it ends without an assistant
* response. Natural `done` remains ineligible because its text is already the
* final response.
*
* @effects: [agent]
* @errors: []
*/
pub fn __agent_loop_wrapup_eligible_status(final_status: string, stop_reason: string?) {
return final_status == "budget_exhausted"
|| final_status == "completion_unverified"
|| final_status == "verify_exhausted"
|| final_status == "stuck"
|| (final_status == "done" && stop_reason == "verified_policy_stop")
}
/**
* Stop reasons the loop FORCES after a bound of its own fired. A forced stop is
* terminal: it is the loop's own decision, made after it had already spent the
* recovery it was willing to spend, so re-opening it would make the bound
* meaningless.
*
* This is a registry rather than a substring test so adding a forced reason is
* one edit in one place. `max_nudges` is deliberately NOT here: it belongs to
* the post-turn nudge budget, not to loop recovery, and folding it in would
* change a subsystem this issue did not measure.
*
* @effects: []
* @errors: []
*/
pub fn __agent_loop_forced_terminal_stop_reasons() -> list<string> {
return ["thrash_hard_stop"]
}
pub fn __agent_loop_is_forced_terminal_stop(stop_reason: string?) -> bool {
return contains(__agent_loop_forced_terminal_stop_reasons(), to_string(stop_reason ?? ""))
}
pub fn __agent_loop_terminal_callback_continue_allowed(final_status: string, stop_reason: string?) {
// A forced stop stays stopped. `stuck` covers both a soft stall exit, which a
// terminal callback may still rescue, and a forced hard stop, which it may not.
if __agent_loop_is_forced_terminal_stop(stop_reason) {
return false
}
if final_status == "stuck" {
return true
}
return final_status == "budget_exhausted" && (stop_reason ?? "") == "max_iterations"
}
pub fn __agent_loop_terminal_callback_extend_by(budget: dict) {
const by = budget?.extend_by ?? 0
if type_of(by) == "int" && by > 0 {
return by
}
return 1
}
pub fn __agent_loop_tool_call_names(tool_calls: list?) {
let names = []
for call in tool_calls ?? [] {
const name = __tool_call_name(call)
if name != "" && !contains(names, name) {
names.push(name)
}
}
return names
}
pub fn __agent_loop_repeated_observation_recovery_feedback(warning: dict?) {
const tool_name = to_string(warning?.tool_name ?? "")
const action = if tool_name != "" {
"`" + tool_name + "`"
} else {
"the same tool"
}
return "Repeated identical " + action + " calls are not making progress. "
+ "Do not issue that same call again. Change strategy with a targeted action "
+ "that changes evidence, such as reading the exact file or symbol named by "
+ "the task, then edit only once you have the needed facts."
}
pub fn __agent_loop_monologue_recovery_feedback(visible_text: string?) {
let intent = trim(to_string(visible_text ?? ""))
if len(intent) > 900 {
intent = intent[0:900] + "..."
}
const intent_block = if intent != "" {
"\nYour stated intent was:\n" + intent
} else {
""
}
return "You are describing the next action instead of taking it. On the next turn, "
+ "emit exactly one concrete tool call as the first action; do not continue in prose. "
+ "Use the available tool that matches your stated intent, with explicit arguments."
+ intent_block
}
/**
* The revision of the evidence a recovery decision considered.
*
* Two hard stops carrying the same signature are the same evidence seen twice,
* not new information. Recovery may proceed again only when this value changed,
* so "the model is still doing the identical thing" can never buy an unbounded
* series of rescues.
*
* @effects: []
* @errors: []
*/
pub fn __agent_loop_recovery_evidence_revision(warning: dict?) -> string {
const signature = to_string(warning?.signature ?? "")
if signature != "" {
return signature
}
const digest = to_string(warning?.signature_digest ?? "")
if digest != "" {
return digest
}
return to_string(warning?.pattern ?? "") + ":" + to_string(warning?.arguments_digest ?? "")
}
/**
* Finite per-turn ceiling on consecutive recoveries, regardless of how often the
* evidence changes.
*
* @effects: []
* @errors: []
*/
pub fn __agent_loop_max_consecutive_recoveries() -> int {
return 2
}
/**
* Which bound refused this recovery, or `""` when none did.
*
* Reported in the receipt so a refusal names the rule that produced it instead
* of being indistinguishable from "the pattern had no rung".
*
* @effects: []
* @errors: []
*/
pub fn __agent_loop_recovery_bound_fired(
warning: dict?,
consecutive_recoveries: int,
last_evidence_revision: string,
allowance: int? = nil,
) -> string {
// The allowance comes from the call-budget policy when the caller has one, so
// the bound that refuses a rescue and the number the projection reports are
// the same value. `nil` falls back to this module's own bound, which is what
// the policy is built from, so the two cannot disagree.
const limit = to_int(allowance ?? __agent_loop_max_consecutive_recoveries())
?? __agent_loop_max_consecutive_recoveries()
if consecutive_recoveries >= limit {
return "max_consecutive_recoveries"
}
if consecutive_recoveries > 0
&& __agent_loop_recovery_evidence_revision(warning) == last_evidence_revision {
return "unchanged_evidence"
}
return ""
}
pub fn __agent_loop_thrash_recovery_allowed(
warning: dict?,
tool_calls: list?,
consecutive_recoveries: int = 0,
last_evidence_revision: string = "",
allowance: int? = nil,
) {
if !(warning?.hard_stop ?? false) {
return false
}
if __agent_loop_recovery_bound_fired(
warning,
consecutive_recoveries,
last_evidence_revision,
allowance,
)
!= "" {
return false
}
const pattern = to_string(warning?.pattern ?? "")
if pattern == "repeated_same_observation" {
return len(tool_calls ?? []) > 0
}
return pattern == "no_progress_monologue" && len(tool_calls ?? []) == 0
}
pub fn __agent_loop_thrash_recovery_reason(warning: dict?) -> string {
if to_string(warning?.pattern ?? "") == "no_progress_monologue" {
return "monologue_recovery_continue"
}
return "thrash_recovery_continue"
}
pub fn __agent_loop_thrash_recovery_feedback(warning: dict?, visible_text: string?) -> string {
if to_string(warning?.pattern ?? "") == "no_progress_monologue" {
return __agent_loop_monologue_recovery_feedback(visible_text)
}
return __agent_loop_repeated_observation_recovery_feedback(warning)
}
pub fn __agent_loop_thrash_recovery_key(warning: dict?) -> string {
if to_string(warning?.pattern ?? "") == "no_progress_monologue" {
return "monologue_recovery"
}
return "thrash_recovery"
}
pub fn __agent_loop_thrash_recovery_skip_reason(warning: dict?) -> string {
if to_string(warning?.pattern ?? "") == "no_progress_monologue" {
return "monologue_recovery"
}
return "thrash_recovery"
}
pub fn __agent_loop_thrash_recovery_skip_outcome(
warning: dict?,
tool_calls: list?,
stall_hard_stop_rescues: int,
last_evidence_revision: string = "",
allowance: int? = nil,
) {
const pattern = to_string(warning?.pattern ?? "")
if pattern != "repeated_same_observation" && pattern != "no_progress_monologue" {
return "no_rung_for_pattern"
}
if pattern == "repeated_same_observation" && len(tool_calls ?? []) == 0 {
return "no_tool_calls"
}
if pattern == "no_progress_monologue" && len(tool_calls ?? []) > 0 {
return "unexpected_tool_calls"
}
const bound = __agent_loop_recovery_bound_fired(
warning,
stall_hard_stop_rescues,
last_evidence_revision,
allowance,
)
if bound != "" {
return bound
}
return "recovery_not_allowed"
}
pub fn __agent_loop_stall_warning_receipt(warning: dict?) {
return {
pattern: to_string(warning?.pattern ?? ""),
tool_name: to_string(warning?.tool_name ?? ""),
repeat_count: to_int(warning?.repeat_count ?? warning?.count ?? 0) ?? 0,
threshold: to_int(warning?.threshold ?? 0) ?? 0,
consecutive_trips: to_int(warning?.consecutive_trips ?? 0) ?? 0,
hard_stop: warning?.hard_stop ?? false,
arguments_digest: to_string(warning?.arguments_digest ?? ""),
signature_digest: to_string(warning?.signature_digest ?? ""),
signature: to_string(warning?.signature ?? ""),
}
}
pub fn __agent_loop_emit_thrash_recovery_checkpoint(
agent: HarnessAgent,
session_id: any,
iteration: any,
tool_calls: list?,
warning: dict?,
old_limit: any,
new_limit: any,
status: string = "fired",
action: string = "thrash_rescue",
reason: string = "thrash_recovery_continue",
outcome: any = nil,
consecutive_recoveries: int = 0,
bound: string = "",
) {
let checkpoint = {
schema: "harn.agent_loop_recovery_receipt.v1",
kind: "thrash_hard_stop_recovery",
receipt_kind: "thrash_hard_stop_recovery",
status: status,
action: action,
reason: reason,
iteration: iteration,
old_limit: old_limit,
new_limit: new_limit,
tool_count: len(tool_calls ?? []),
tool_names: __agent_loop_tool_call_names(tool_calls),
warning: __agent_loop_stall_warning_receipt(warning),
// How many recoveries this run had already spent when the decision was made,
// which bound refused it (`""` when none did), and the exact evidence
// revision the decision considered.
consecutive_recoveries: consecutive_recoveries,
bound: bound,
evidence_revision: __agent_loop_recovery_evidence_revision(warning),
}
if outcome != nil {
checkpoint = checkpoint + {outcome: outcome}
}
agent_emit_event(agent, session_id, "typed_checkpoint", checkpoint)
}
/**
* Forced terminal wrap-up turn. When the loop exits on exhaustion/cap while the
* last turn still called tools, the surfaced final text would otherwise be a
* dangling tool-call turn with no clean `<user_response>`/sentinel. This runs
* exactly one extra LLM call with tools requested off to elicit the model's
* final user-facing answer or declared JSON output, records it as the final
* assistant turn so `agent_session_finalize` surfaces it, and never mutates
* `final_status`/`stop_reason`. Provider/tool-format leaks can still yield
* tool calls on this turn, so the loop records explicit skipped receipts before
* falling back. Defensive: any error falls back to existing behavior. Returns
* whether text was recorded and whether the wrap-up was eligible for publication.
*
* @effects: [agent]
* @errors: []
*/
pub type AgentLoopFinalWrapupResult = {recorded: bool, publication_admitted: bool}
pub fn __agent_loop_failed_final_wrapup() -> AgentLoopFinalWrapupResult {
return {recorded: false, publication_admitted: false}
}
pub fn __agent_loop_final_wrapup(
harness: Harness,
message: any,
session: dict,
opts: dict,
final_status: any,
stop_reason: string?,
iteration: int,
) -> AgentLoopFinalWrapupResult {
const directive = __agent_loop_wrapup_directive(opts)
// Disable tools for this turn so the model cannot dispatch: empty tool
// surface + a system directive forbidding tool calls. Carry the tool format
// forward so the response protocol still matches what the model was trained
// on this run.
const wrapup_opts = opts
+ {
tools: nil,
active_skills: nil,
skill_catalog_prompt: "",
transcript_projection: opts?.transcript_projection,
}
const turn_prompt = __agent_loop_build_turn_prompt(harness, session, wrapup_opts, iteration)
const host_wrapup = __agent_loop_has_host_wrapup_directive(wrapup_opts)
// System prompt + message array. A host-supplied directive is delivered as a
// trailing user message and the system prompt is left byte-identical to the
// loop's turns, so the whole system+history prefix is reused verbatim by the
// provider prompt cache / local KV cache — the wrap-up pays only for the one
// appended instruction. The default (no host directive) keeps today's exact
// behavior: the generic directive rides in the system prompt.
const base_system = if trim(turn_prompt.system ?? "") != "" {
turn_prompt.system
} else {
""
}
const turn_system = if host_wrapup {
base_system
} else {
let parts = []
if base_system != "" {
parts.push(base_system)
}
parts.push(directive)
join(parts, "\n\n")
}
const wrapup_context = __agent_loop_effective_wrapup_context(
wrapup_opts,
final_status,
stop_reason,
)
const turn_messages = if host_wrapup {
turn_prompt.messages
+ [{role: "user", content: directive + __agent_loop_render_wrapup_context(wrapup_context)}]
} else {
turn_prompt.messages
}
const llm_opts = __agent_loop_effective_llm_options(
harness.llm,
wrapup_opts + {_final_wrapup: true},
)
+ {
messages: turn_messages,
session_id: session.session_id,
tool_format: wrapup_opts?.tool_format,
tools: nil,
_iteration: iteration + 1,
_final_wrapup: true,
_user_visible: false,
_on_delta: nil,
_call_stage: "wrapup",
}
let call = agent_invoke_llm(harness, message, turn_system, llm_opts)
if !call.ok {
return {recorded: false, publication_admitted: false}
}
const llm_result = call.value
// Keep accepted wrap-up usage in the same session accounting path as main
// and repair calls. This records the already-completed call once; it does
// not issue another provider request or alter the terminal decision.
agent_session_record_usage(harness.agent, session.session_id, llm_result, llm_opts, iteration + 1)
const raw_text = llm_result?.raw_text ?? llm_result?.text ?? ""
// Detection keeps the original registry so a canonical named call can be
// parsed and reported. The LLM invocation and dispatcher remain tool-free.
const parsed = agent_parse_tool_calls(
harness.agent,
raw_text,
opts?.tools,
wrapup_opts?.tool_format,
)
const wrapup_tool_calls = __resolve_tool_calls(llm_result, parsed)
const lost_call_violations = (parsed?.protocol_violations ?? []).filter(
violation_reports_lost_call,
)
const wrapup_tool_diagnostics = (parsed?.tool_parse_errors ?? [])
+ protocol_violation_messages(lost_call_violations)
const has_unconsumed_tool_call = len(wrapup_tool_calls) > 0
|| len(wrapup_tool_diagnostics) > 0
const wrapup_tool_parse_status = if !has_unconsumed_tool_call {
nil
} else if len(wrapup_tool_calls) == 0 {
"malformed"
} else if len(wrapup_tool_diagnostics) > 0 {
"partial"
} else {
"parsed"
}
const unconsumed_tool_call = if !has_unconsumed_tool_call {
nil
} else {
{
parse_status: wrapup_tool_parse_status,
parsed_call_count: len(wrapup_tool_calls),
tool_names: __agent_loop_tool_call_names(wrapup_tool_calls),
diagnostics: wrapup_tool_diagnostics,
evidence_line: "the final summary contained an unconsumed tool call",
}
}
if len(wrapup_tool_calls) > 0 {
agent_session_record_undispatched_tool_results(
harness.agent,
session.session_id,
wrapup_tool_calls,
"skipped",
"not dispatched: final wrap-up turns cannot call tools",
)
}
if has_unconsumed_tool_call {
const receipt_kind = if len(wrapup_tool_calls) > 0 {
"final_wrapup_tool_calls_skipped"
} else {
"final_wrapup_tool_call_malformed"
}
agent_emit_event(
harness.agent,
session.session_id,
"typed_checkpoint",
{
schema: "harn.agent_loop_final_wrapup_receipt.v1",
kind: receipt_kind,
receipt_kind: receipt_kind,
status: if len(wrapup_tool_calls) > 0 {
"skipped"
} else {
"malformed"
},
final_status: final_status,
stop_reason: stop_reason ?? "",
iteration: iteration,
tool_count: len(wrapup_tool_calls),
tool_names: __agent_loop_tool_call_names(wrapup_tool_calls),
parse_status: wrapup_tool_parse_status,
diagnostics: wrapup_tool_diagnostics,
evidence_line: unconsumed_tool_call.evidence_line,
host_directive: host_wrapup,
terminal_kind: final_status,
},
)
}
const visible_text = __visible_text(parsed, raw_text)
const has_visible_text = to_string(visible_text) != ""
if has_visible_text {
const normalized = llm_result
+ {
text: visible_text,
visible_text: visible_text,
_defer_visible: true,
_publication_eligible: !has_unconsumed_tool_call,
}
agent_session_record_assistant(harness.agent, session.session_id, normalized)
}
if has_visible_text || has_unconsumed_tool_call {
let _ = try {
agent_emit_event(
harness.agent,
session.session_id,
"final_wrapup",
{
final_status: final_status,
stop_reason: stop_reason ?? "",
iteration: iteration,
host_directive: host_wrapup,
terminal_kind: final_status,
unconsumed_tool_call: unconsumed_tool_call,
},
)
}
}
return {recorded: has_visible_text, publication_admitted: !has_unconsumed_tool_call}
}
/**
* Flatten the MCP server specs declared by the currently active skills.
*
* Drives the per-turn mid-conversation MCP mount (gated by the default-off
* `mid_conversation_mcp_mount` opt): the loop feeds the result to
* `agent_mcp_mount_additional`, which mounts only the servers not already
* active so a mid-conversation skill's tools become visible AND callable
* without re-mounting live servers. Empty when no active skill declares MCP
* servers, which keeps the flag-off path untouched.
*
* @effects: [agent]
* @errors: []
*/
pub fn __agent_loop_active_skill_mcp_specs(active_skills: list?) {
let specs = []
for active_skill in active_skills ?? [] {
for spec in active_skill?.mcp ?? [] {
specs = specs + [spec]
}
}
return specs
}
/**
* Parse a terminal JSON answer and, when present, validate its schema.
*
* @effects: [agent]
* @errors: []
*/
pub type AgentLoopOutputContractValue = {ok: bool, value: any?}
pub fn __agent_loop_output_contract_value(text: any, schema: any) -> AgentLoopOutputContractValue {
const parsed = try {
json_extract(text)
}
if is_err(parsed) {
return {ok: false, value: nil}
}
const value = unwrap(parsed)
if schema == nil {
return {ok: true, value: value}
}
const valid = try {
schema_is(value, schema)
}
if is_err(valid) || !unwrap(valid) {
return {ok: false, value: value}
}
return {ok: true, value: value}
}
pub fn __agent_loop_output_contract_repair_prompt(schema: any, text: string) -> string {
if schema == nil {
return "Your previous final answer was not valid JSON.\n"
+ "Reply with ONLY a valid JSON value.\n\nPrevious answer:\n\n"
+ text
}
return "Your previous final answer did not satisfy the required output schema.\n"
+ "Reply with ONLY a JSON value that validates against this JSON Schema:\n\n"
+ json_stringify_pretty(schema)
+ "\n\nYour previous final answer was:\n\n"
+ text
}
/**
* Apply `agent_loop`'s terminal `output` contract. Intermediate turns omit the
* contract so tool calling remains available. A failed terminal parse or
* schema check gets one repair call through the same `llm_caller` seam.
*
* @effects: [agent]
* @errors: []
*/
pub fn __agent_loop_prepare_output_contract(
harness: Harness,
opts: dict,
session: dict,
iteration: int,
allow_repair: bool = true,
) -> dict {
const schema = __agent_loop_output_contract(opts)?.schema
const messages = agent_session_messages(harness.agent, session.session_id)
const last = if len(messages) > 0 {
messages[len(messages) - 1]
} else {
nil
}
let text = if last?.role == "assistant" {
agent_transcript_text(last?.content ?? last?.text ?? "")
} else {
""
}
const direct = __agent_loop_output_contract_value(text, schema)
if direct.ok {
return {output: direct.value, output_valid: true}
}
// The wrap-up is already the one bounded terminal request. Preserve its
// measured result without spending a second request after the loop stopped.
if !allow_repair {
return {output: nil, output_valid: false}
}
const repair_opts = __agent_loop_effective_llm_options(
harness.llm,
opts + {_output_contract_repair: true},
)
+ {
_user_visible: false,
_on_delta: nil,
session_id: session.session_id,
tools: nil,
tool_choice: nil,
tool_format: opts?.tool_format,
_iteration: iteration + 1,
_output_contract_repair: true,
_call_stage: "repair",
}
const repair = try {
agent_invoke_llm(
harness,
__agent_loop_output_contract_repair_prompt(schema, text),
nil,
repair_opts,
)
}
if is_err(repair) {
return {output: direct.value, output_valid: false}
}
let call = unwrap(repair)
if !(call?.ok ?? false) {
return {output: direct.value, output_valid: false}
}
agent_session_record_usage(
harness.agent,
session.session_id,
call.value,
repair_opts,
iteration + 1,
)
const repaired_text = to_string(call?.value?.visible_text ?? call?.value?.text ?? "")
const second = __agent_loop_output_contract_value(repaired_text, schema)
const normalized = call.value
+ {text: repaired_text, visible_text: repaired_text, _defer_visible: true}
agent_session_record_assistant(harness.agent, session.session_id, normalized)
return {
text: repaired_text,
visible_text: repaired_text,
output: second.value,
output_valid: second.ok,
}
}