perspt-agent 0.6.6

SRBN Orchestrator and Agent logic for Perspt
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Per-call prompt and resident-context binding for the worker loop
//! (PSP-10 systems 23–24, Gate Z and Definition 6).

use anyhow::Result;

use super::{
    emit, resident, EventLog, LoopContext, LoopEvent, PromptEnvelope, ToolLoop, TurnState,
};

/// The serialized token and byte cost of one composed request.
fn wire_cost(
    accountant: &perspt_sdk::prompt::TokenAccountantRef,
    conversation: &perspt_sdk::Conversation,
) -> (u64, u64) {
    let mut tokens = 0u64;
    let mut bytes = 0u64;
    for message in conversation.messages() {
        let serialized = serde_json::to_string(message).unwrap_or_default();
        tokens += accountant.count_message(&serialized);
        bytes += serialized.len() as u64;
    }
    (tokens, bytes)
}

/// The live per-call prompt identity (recompiled when the tool surface or
/// the failover route changes).
#[derive(Default)]
pub(super) struct PromptBinding {
    pub(super) surface_hash: String,
    pub(super) route_key: String,
    pub(super) invocation_digest: String,
    pub(super) platform_digest: String,
    pub(super) domain_digest: String,
    pub(super) resident_digest: String,
}

impl PromptBinding {
    /// The binding the seed-time envelope compiled, when one exists.
    pub(super) fn seed(envelope: &PromptEnvelope, model: &perspt_sdk::ModelId) -> Self {
        match &envelope.invocation {
            Some(invocation) => Self {
                surface_hash: invocation.platform.tool_spec_hash.clone(),
                route_key: format!("{model}"),
                invocation_digest: invocation.invocation_digest.clone(),
                platform_digest: invocation.platform.program_digest.clone(),
                domain_digest: invocation.domain.program_digest.clone(),
                resident_digest: String::new(),
            },
            None => Self::default(),
        }
    }
}

impl ToolLoop<'_> {
    /// The token reserve the offered tool schemas consume on the wire.
    pub(super) fn tool_schema_reserve(&self, specs: &[perspt_sdk::ToolSpec]) -> u64 {
        let accountant = perspt_sdk::prompt::TokenAccountantRef::approx_bytes_v1();
        specs
            .iter()
            .map(|spec| {
                accountant.count_text(&format!("{}{}{}", spec.name, spec.description, spec.schema))
            })
            .sum()
    }

    /// Definition 6's input allowance for this call.
    fn input_allowance(&self, tool_reserve: u64) -> u64 {
        let window = u64::from(
            self.transport
                .capabilities(&self.model)
                .max_context_tokens
                .max(1),
        );
        window
            .saturating_sub(self.budgets.resident.output_reserve_tokens)
            .saturating_sub(tool_reserve)
            .saturating_sub(self.budgets.resident.guard_reserve_tokens)
    }

    /// Definition 6, live: assemble the resident working set over the
    /// conversation's content-addressed pages before every transport call.
    /// An infeasible mandatory closure records `ContextInfeasible` and
    /// makes no model call. Recording happens after the composed-request
    /// fit, so the ledger carries exactly what was transmitted.
    pub(super) fn assemble_resident_context(
        &self,
        turn: u32,
        specs: &[perspt_sdk::ToolSpec],
        context: &LoopContext,
        state: &mut TurnState,
    ) -> Result<Option<perspt_sdk::prompt::ResidentContext>> {
        if !self.budgets.resident.paging_enabled {
            return Ok(None);
        }
        let tool_reserve = self.tool_schema_reserve(specs);
        let window = u64::from(
            self.transport
                .capabilities(&self.model)
                .max_context_tokens
                .max(1),
        );
        let outcome = resident::assemble_worker_resident(
            context.conversation(),
            context.birth_deps(),
            &state.accepted_checkpoint.witness.state_root,
            self.partial_seed_root.as_deref(),
            window,
            tool_reserve,
            &self.budgets.resident,
        )
        .map_err(|e| anyhow::anyhow!("resident assembly: {e}"))?;
        match outcome {
            perspt_sdk::prompt::ResidentOutcome::Infeasible {
                required,
                allowance,
            } => self.refuse_infeasible(turn, required, allowance, state),
            perspt_sdk::prompt::ResidentOutcome::Assembled(assembled) => Ok(Some(assembled)),
        }
    }

    /// Record `ContextInfeasible` and fail closed — no model call is made.
    fn refuse_infeasible<T>(
        &self,
        turn: u32,
        required: u64,
        allowance: u64,
        state: &mut TurnState,
    ) -> Result<T> {
        emit(
            self.recorder,
            &mut state.log,
            LoopEvent::ContextInfeasible {
                forest_id: String::new(),
                branch_id: String::new(),
                turn,
                required,
                allowance,
            },
        )?;
        anyhow::bail!(
            "context budget infeasible: the composed request needs {required} \
             tokens over the {allowance}-token input allowance; no model call \
             was made"
        );
    }

    /// Enforce Definition 6 on the **composed transport request**: the
    /// serialized view (tombstones included) must fit the input allowance
    /// and the dialect's byte limit. On overflow, optional pages are popped
    /// in reverse selection order and the view rebuilt; a mandatory-only
    /// view that still overflows fails closed with `ContextInfeasible`.
    /// Only then is the working set ledgered — the record is exactly what
    /// was transmitted.
    pub(super) fn fit_composed_request(
        &self,
        turn: u32,
        specs: &[perspt_sdk::ToolSpec],
        context: &LoopContext,
        assembled: Option<perspt_sdk::prompt::ResidentContext>,
        state: &mut TurnState,
    ) -> Result<perspt_sdk::Conversation> {
        let accountant = perspt_sdk::prompt::TokenAccountantRef::approx_bytes_v1();
        let allowance = self.input_allowance(self.tool_schema_reserve(specs));
        let byte_limit = crate::turn::route_dialect(self.transport, &self.model)
            .1
            .max_prompt_bytes;
        let Some(mut assembled) = assembled else {
            // Paging off (evaluation ablation): the bound still holds per
            // Gate AF — an oversized request fails closed, it is not sent.
            let conversation = context.conversation().clone();
            let (tokens, bytes) = wire_cost(&accountant, &conversation);
            if tokens > allowance || bytes > byte_limit {
                return self.refuse_infeasible(turn, tokens, allowance, state);
            }
            return Ok(conversation);
        };
        loop {
            let ids: std::collections::BTreeSet<String> = assembled
                .pages
                .iter()
                .map(|page| page.page_id.clone())
                .collect();
            let (mut view, evicted) = resident::resident_view(context.conversation(), &ids);
            if evicted == 0 {
                view = context.conversation().clone();
            } else if let Some(note) = resident::evicted_index_note(context.conversation(), &ids) {
                // The transport-only page index: the model's typed view of
                // what context_recall can restore. Never enters the
                // projection; its cost is part of the composed request.
                view.push(perspt_sdk::Message::User { content: note });
            }
            let (tokens, bytes) = wire_cost(&accountant, &view);
            if tokens <= allowance && bytes <= byte_limit {
                assembled.resident_digest = perspt_sdk::prompt::resident_page_digest(
                    assembled.pages.iter().map(|page| page.page_id.as_str()),
                );
                self.record_working_set(turn, &assembled, state)?;
                return Ok(view);
            }
            if assembled.pages.len() > assembled.mandatory_len {
                assembled.pages.pop();
                continue;
            }
            return self.refuse_infeasible(turn, tokens, allowance, state);
        }
    }

    /// Ledger the assembled working set: the selection (with its digest)
    /// when it changed, and the per-call resident page list always.
    fn record_working_set(
        &self,
        turn: u32,
        assembled: &perspt_sdk::prompt::ResidentContext,
        state: &mut TurnState,
    ) -> Result<()> {
        let page_ids: Vec<String> = assembled
            .pages
            .iter()
            .map(|page| page.page_id.clone())
            .collect();
        if state.prompt.resident_digest != assembled.resident_digest {
            emit(
                self.recorder,
                &mut state.log,
                LoopEvent::ContextPagesSelected {
                    forest_id: String::new(),
                    branch_id: String::new(),
                    turn,
                    resident_digest: assembled.resident_digest.clone(),
                    page_ids: page_ids.clone(),
                },
            )?;
        }
        emit(
            self.recorder,
            &mut state.log,
            LoopEvent::ContextWorkingSet {
                forest_id: String::new(),
                branch_id: String::new(),
                turn,
                page_ids,
            },
        )?;
        state.prompt.resident_digest = assembled.resident_digest.clone();
        Ok(())
    }

    /// Gate AC: reserve one verifier action from the shared search budget
    /// before a measurement runs, then snapshot the usage into the ledger
    /// so the charge survives a crash during the run. A refusal aborts the
    /// branch before the action executes; the forest observes it and
    /// abandons the branch.
    pub(super) fn reserve_verifier_action(&self, log: &mut EventLog) -> Result<()> {
        let Some(budget) = &self.search_budget else {
            return Ok(());
        };
        budget
            .reserve(perspt_sdk::search::ReservationRequest {
                verifier_runs: 1,
                ..Default::default()
            })
            .map(|_ticket| ())
            .map_err(|error| {
                anyhow::anyhow!("search budget refused the verifier reservation: {error}")
            })?;
        self.snapshot_search_usage(log)
    }

    /// Ledger the shared budget's current usage under the owning forest's
    /// identity. Emitted after every reservation and settlement so the
    /// durable record is always the reserved worst case or the settled
    /// actuals — a crash between snapshots can only over-charge, never
    /// refill (Gate AC: limits are never silently refilled).
    pub(super) fn snapshot_search_usage(&self, log: &mut EventLog) -> Result<()> {
        let Some(budget) = &self.search_budget else {
            return Ok(());
        };
        let (forest_id, epoch) = budget.identity();
        if forest_id.is_empty() {
            return Ok(());
        }
        emit(
            self.recorder,
            log,
            LoopEvent::SearchUsageSnapshot {
                forest_id,
                epoch,
                usage: budget.snapshot(),
            },
        )
    }

    /// Gate AC: reserve one model turn's worst case from the shared search
    /// budget **before** the transport call — the turn, its per-turn call
    /// and mutation allowances, its bounded result bytes, and the composed
    /// request's tokens plus the output reserve. `None` outside a forest.
    pub(super) fn reserve_model_turn(
        &self,
        conversation: &perspt_sdk::Conversation,
    ) -> Result<Option<(perspt_sdk::search::ReservationTicket, u64)>> {
        let Some(budget) = &self.search_budget else {
            return Ok(None);
        };
        let accountant = perspt_sdk::prompt::TokenAccountantRef::approx_bytes_v1();
        let (wire_tokens, _) = wire_cost(&accountant, conversation);
        let per_call_result = 8 * 1024 + 256;
        let request = perspt_sdk::search::ReservationRequest {
            model_turns: 1,
            tool_calls: self.budgets.max_calls_per_turn,
            mutations: self.budgets.max_calls_per_turn,
            tokens: wire_tokens + self.budgets.resident.output_reserve_tokens,
            result_bytes: u64::from(self.budgets.max_calls_per_turn) * per_call_result,
            ..Default::default()
        };
        let ticket = budget.reserve(request).map_err(|error| {
            anyhow::anyhow!("search budget refused the model-turn reservation: {error}")
        })?;
        Ok(Some((ticket, wire_tokens)))
    }

    /// Settle the turn with observed actuals: the calls the model actually
    /// returned, the mutations actually admitted, and each response's
    /// bounded byte cost. Overshoot clamps at the limits and closes the
    /// forest (never persisted above a limit).
    pub(super) fn settle_model_turn(
        &self,
        held: Option<(perspt_sdk::search::ReservationTicket, u64)>,
        output: &perspt_sdk::TurnOutput,
        mutations: u32,
    ) -> Result<()> {
        let (Some(budget), Some((ticket, wire_tokens))) = (&self.search_budget, held) else {
            return Ok(());
        };
        let accountant = perspt_sdk::prompt::TokenAccountantRef::approx_bytes_v1();
        let calls = output.tool_calls().len() as u32;
        let output_tokens = match output {
            perspt_sdk::TurnOutput::Text(text) => accountant.count_text(text),
            perspt_sdk::TurnOutput::ToolCalls(calls) => {
                accountant.count_text(&serde_json::to_string(calls).unwrap_or_default())
            }
        };
        let actual = perspt_sdk::search::ReservationRequest {
            model_turns: 1,
            tool_calls: calls,
            mutations,
            tokens: wire_tokens + output_tokens,
            result_bytes: u64::from(calls) * (8 * 1024 + 256),
            ..Default::default()
        };
        budget
            .settle(ticket, actual)
            .map_err(|error| anyhow::anyhow!("search budget closed on settlement: {error}"))
    }

    /// Ledger the exact prompt binding of this call (PSP-10 Gate Z):
    /// recompile through the SDK compiler when the offered tool surface or
    /// the failover route changed, then record one invocation per call.
    pub(super) fn bind_prompt_program(
        &self,
        turn: u32,
        specs: &[perspt_sdk::ToolSpec],
        state: &mut TurnState,
    ) -> Result<()> {
        let Some(stage) = &self.system_prompt.stage else {
            return Ok(());
        };
        let surface_hash = perspt_sdk::prompt::tool_surface_hash(specs);
        let route_key = format!("{}", self.model);
        if state.prompt.surface_hash != surface_hash || state.prompt.route_key != route_key {
            let (route, dialect) = crate::turn::route_dialect(self.transport, &self.model);
            let invocation = perspt_core::prompts::compile_invocation(
                stage,
                &self.system_prompt.domain_sections,
                &route,
                &dialect,
                &surface_hash,
            )
            .map_err(|e| anyhow::anyhow!("prompt recompilation failed closed: {e}"))?;
            emit(
                self.recorder,
                &mut state.log,
                LoopEvent::PromptProgramCompiled {
                    turn,
                    program: invocation.platform.clone(),
                },
            )?;
            if !invocation.domain.messages.is_empty() {
                emit(
                    self.recorder,
                    &mut state.log,
                    LoopEvent::PromptProgramCompiled {
                        turn,
                        program: invocation.domain.clone(),
                    },
                )?;
            }
            state.prompt = PromptBinding {
                surface_hash,
                route_key,
                invocation_digest: invocation.invocation_digest.clone(),
                platform_digest: invocation.platform.program_digest.clone(),
                domain_digest: invocation.domain.program_digest.clone(),
                resident_digest: std::mem::take(&mut state.prompt.resident_digest),
            };
        }
        emit(
            self.recorder,
            &mut state.log,
            LoopEvent::PromptProgramInvoked {
                turn,
                invocation_digest: state.prompt.invocation_digest.clone(),
                platform_digest: state.prompt.platform_digest.clone(),
                domain_digest: state.prompt.domain_digest.clone(),
                tool_spec_hash: state.prompt.surface_hash.clone(),
                resident_context_digest: state.prompt.resident_digest.clone(),
            },
        )
    }
}