返回 CodeWhale
core_call.rs
根目录 / crates / engine / src / extension_host / core_call.rs
1 //! `core/call`: an extension tool, while it handles a `tool/call`, asking the
2 //! core to run one of the core's tools for it.
3 //!
4 //! The call goes through the same gate as a call the model makes. The turn
5 //! loop serves it (`Engine::gate_nested_call`, source `Extension`): planning
6 //! (allow and deny lists, preparation, hooks, ask-rules, Auto-Review, repo
7 //! law, the authority envelope), then the approval card when one is needed,
8 //! then execution by the same machinery code mode uses
9 //! ([`CodemodeInvoker`]). Nothing the host sends decides any of it: not an
10 //! approval, not the card's text (Rust composes it, naming the extension and
11 //! the tool it is inside), not an argv or a URL, not the ticket's contents.
12 //!
13 //! **When it exists.** An invocation ticket is minted only for an extension
14 //! tool call that runs under a nested-call gate the turn loop is serving *for
15 //! that tool* (`NestedCallGate::extension`, set by the turn loop when the model
16 //! called the tool directly, in a sub-agent's turn as in the session's). A tool
17 //! run from inside `execute_tools` (code mode hands nested specs no gate), a
18 //! command, a timer, activation code and every test without a turn have none,
19 //! so their `core/call`s are refused ("out of turn"). The ticket lives exactly
20 //! as long as the invocation: it is revoked when the `tool/call` ends
21 //! (answered, failed, timed out or dropped), when its owner is revoked and when
22 //! its host exits, and each of those withdraws the invocation's pending core
23 //! calls and any approval card one is waiting on.
24 //!
25 //! **What is refused outright** ([`refusal`], checked before planning on the
26 //! name the host sent and again by the turn loop on the name planning resolved
27 //! it to and the final, hook-rewritten input): everything code mode refuses
28 //! before its gate (`execute_tools`, interpreters, `agent`, `workflow`, `rlm`,
29 //! `request_user_input`, interactive shells, sandbox escalation, Computer Use
30 //! consent and scripts, MCP sign-in); any extension tool (no recursion); tool
31 //! search and tool-result retrieval; the memory writer and the tools that
32 //! change what the session may do or schedule work beyond it; and every MCP
33 //! tool, Computer Use included (not in v1: CURRENT_DECISIONS 26, the founder's
34 //! recorded default).
35 //!
36 //! **What prompts** ([`origin_approval`]): an extension's call needs approval
37 //! unless the tool is in the small read-only, workspace-local table
38 //! [`EXT_AUTO_ELIGIBLE`] and planning found nothing that asks; its approval
39 //! keys are scoped to the extension plugin build
40 //! (`approval_cache::extension_origin_approval_keys`), so a grant the user gave
41 //! the model never covers an extension's call and the reverse. Shell and
42 //! network calls force a prompt: a session grant is not consulted, and
43 //! Full Access still opens their card. Never refuses them
44 //! (`resolve_approval_request_disposition`), while Auto-Review sends held calls
45 //! to its reviewer; explicit denials always win.
46 //! The broker's own gate tools ([`dsh_broker::GATE_TOOLS`]) are the exception:
47 //! the permission mode alone decides them, and only a broker arm reaches them
48 //! (a plugin's own `core/call` of one is refused by name).
49 //!
50 //! **Caps.** Per invocation: 50 core tool calls in all, counted together
51 //! across `core/call` and the nested calls of broker arms, 4 at
52 //! once (code mode's own cap), and one approval card at a time (the turn
53 //! loop serves one request at a time). Per host: the channel's 256 in-flight
54 //! host requests. A burst of invalid tickets ends the host (`ticket`).
55 //!
56 //! **Time.** The `tool/call` deadline is measured on the invocation's pausable
57 //! clock, which stops while a `core/call` waits on the gate, so a person
58 //! taking a minute on a card does not time the tool out. An approval is never
59 //! decided for the person: when the host cancels, the owner is revoked, the
60 //! host exits or the invocation ends, the wait is withdrawn and recorded
61 //! cancelled.
62 //!
63 //! Known limits:
64 //! * The refusal list names tools; a tool added later that changes the mode,
65 //! the posture or the permissions has to be added to [`REFUSED_NAMES`]
66 //! (a test fails when a name in it stops being a tool the core registers).
67 //! * A withdrawn call retires its card through the typed `ApprovalWithdrawn`
68 //! event on terminal and runtime clients. A later answer has no live waiter.
69 //! * Results come back as text (and structured JSON when the tool's content
70 //! was JSON); images and other rich blocks are dropped, as in code mode.
71 //! * One extension tool call at a time holds the turn's tool lock, so a
72 //! tool's `core/call`s run beside it, not through the lock.
73
74 use std::collections::HashMap;
75 use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
76 use std::sync::{Arc, Mutex};
77 use std::time::Duration;
78
79 use codewhale_workflow_js::ToolCallResponse;
80 use serde_json::{Value, json};
81 use tokio_util::sync::CancellationToken;
82
83 use super::ManagerShared;
84 use super::dsh_broker::{self, Arm, BrokerCall, BrokerEffect, BrokerRefusal, OpenAct};
85 use super::protocol::{
86 ContentBlockWire, CoreCallParams, DshBrokerParams, DshBrokerTicketWire, DshService,
87 RpcErrorWire, SessionCheckpointParams, ToolResultWire, UserQuestionParams, error_code,
88 };
89 use super::supervisor::HostRequestContext;
90 use super::ticket::{Grant, Presented, Ticket, TicketKind};
91 use super::tier::{HostCohort, HostTier};
92 use crate::core::authority::{ToolCategory, get_tool_category_for_call};
93 use crate::core::events::SessionCheckpointCaller;
94 use crate::tools::codemode::{
95 CodemodeInvoker, ExtensionCaller, NestedCallGate, NestedDecision, NestedFailure, PauseClock,
96 };
97 use crate::tools::spec::{ToolCapability, ToolContext, ToolSpec};
98 use codewhale_config::OwnerRef;
99
100 /// The protocol method an invocation ticket is good for.
101 pub const METHOD: &str = "core/call";
102 const CHECKPOINT_METHOD: &str = "session/checkpoint";
103 const QUESTION_METHOD: &str = "user-questions/ask";
104 const SUBAGENT_METHOD: &str = "subagent/start";
105 /// `core/call`s one invocation may make in all.
106 pub const MAX_CALLS_PER_INVOCATION: u32 = 50;
107 /// A backstop only: an invocation ends (and revokes its ticket) long before
108 /// this, and its own deadline pauses while a person decides.
109 const TICKET_TTL: Duration = Duration::from_secs(24 * 60 * 60);
110 const GRANT_PROBE: Duration = Duration::from_millis(50);
111 /// Receipts attached to an extension tool's result metadata.
112 pub const RECEIPTS_ATTACHED: usize = 50;
113 pub const MAX_ACT_RECORD_BYTES: usize = 1024;
114
115 /// Tools an extension may never reach through `core/call`, by lower-case
116 /// name, checked on the spelling the host sent and on the canonical action
117 /// alias planning resolves it to.
118 const REFUSED_NAMES: &[&str] = &[
119 // Discovery and retrieval: schema activation and spilled output are the
120 // turn's own.
121 "tool_search",
122 "tool_search_tool_regex",
123 "tool_search_tool_bm25",
124 "retrieve_tool_result",
125 // The memory writer.
126 "remember",
127 // What the session may do, or work scheduled beyond it.
128 "request_plugin_install",
129 "create_goal",
130 "update_goal",
131 "automation",
132 "send_later",
133 "start_mcp_server",
134 "start_registry_mcp_server",
135 "plugin_manager",
136 ];
137
138 /// Read-only, workspace-local tools an extension's call may run without a
139 /// prompt, when planning also finds nothing that asks for one. Every other
140 /// tool an extension asks for needs approval. A test pins that each is a
141 /// registered, read-only, auto-approved tool.
142 pub const EXT_AUTO_ELIGIBLE: &[&str] =
143 &["read", "read_file", "list_dir", "file_search", "grep_files"];
144
145 /// Tools that run commands or reach the network and are not in the shell and
146 /// network categories by name: an extension's call of one forces a prompt too.
147 const FORCED_PROMPT_NAMES: &[&str] = &["web.run", "git_fetch", "run_tests", "run_verifiers"];
148
149 fn canonical(name: &str, input: &Value) -> String {
150 // Preserve the family's registered spelling until its action is resolved.
151 // Lowercasing `Git` first would hide `Git{action:"fetch"}` from policy.
152 let family = codewhale_execpolicy::canonical_action::CANONICAL_ACTION_ALIASES
153 .iter()
154 .find(|(family, _, _)| family.eq_ignore_ascii_case(name))
155 .map_or(name, |(family, _, _)| *family);
156 codewhale_execpolicy::canonical_action::canonical_action_alias(family, input)
157 .to_ascii_lowercase()
158 }
159
160 fn is_extension_tool(specs: &[Arc<dyn ToolSpec>], name: &str) -> bool {
161 specs
162 .iter()
163 .find(|spec| spec.name().eq_ignore_ascii_case(name))
164 .is_some_and(|spec| spec.extension_caller().is_some())
165 }
166
167 /// Whether the core refuses an extension's call of `name` outright, and why:
168 /// code mode's own refusals plus the extension list (module docs). Pure over
169 /// the tool snapshot, so the turn loop can run it again on what planning
170 /// resolved. `ExtraRefusal`'s shape.
171 pub fn refusal(specs: &[Arc<dyn ToolSpec>], name: &str, input: &Value) -> Option<String> {
172 if let Some(note) = crate::tools::codemode::refusal_before_gate(name, input) {
173 return Some(note);
174 }
175 let lower = name.to_ascii_lowercase();
176 let resolved = canonical(name, input);
177 if is_extension_tool(specs, name) || is_extension_tool(specs, &resolved) {
178 return Some(format!(
179 "`{name}` is a plugin tool; a plugin's core/call cannot reach another plugin's tool (or its own)"
180 ));
181 }
182 if crate::mcp::McpPool::is_mcp_tool(&lower) || crate::mcp::McpPool::is_mcp_tool(&resolved) {
183 return Some(format!(
184 "`{name}` is an MCP tool (Computer Use included); plugins cannot call MCP tools through core/call"
185 ));
186 }
187 let family = |candidate: &str| {
188 REFUSED_NAMES.contains(&candidate)
189 || codewhale_tools::names::is_tool_search_tool(candidate)
190 || candidate.starts_with("automation_")
191 };
192 if family(&lower) || family(&resolved) {
193 return Some(format!(
194 "`{name}` is not available to a plugin's core/call (tool search and retrieval, the memory writer, and tools that change what the session may do or schedule work stay the model's own)"
195 ));
196 }
197 None
198 }
199
200 /// How an extension's call of a tool differs from the model's, after planning
201 /// has decided what the model's call would need.
202 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
203 pub enum OriginApproval {
204 /// Planning's decision stands (the tool is in [`EXT_AUTO_ELIGIBLE`] and
205 /// nothing asked for approval, or it is one of the broker's gate tools,
206 /// which the permission mode alone decides).
207 Unchanged,
208 /// Needs approval; an extension-scoped session grant may satisfy it.
209 Prompt,
210 /// A shell or network call: needs a prompt that no grant, and no posture
211 /// that cannot open one, may satisfy.
212 ForcePrompt,
213 }
214
215 /// The approval an extension's call of `name` needs. `planned_requires_approval`
216 /// is what planning decided without regard to origin (a read outside the
217 /// workspace, a hook's ask or repo law all say yes there, and stay yes).
218 pub fn origin_approval(
219 name: &str,
220 input: &Value,
221 planned_requires_approval: bool,
222 spec: Option<&dyn ToolSpec>,
223 ) -> OriginApproval {
224 use crate::tools::execution_envelope::{CallClass, classify_call};
225
226 let lower = name.to_ascii_lowercase();
227 let resolved = canonical(name, input);
228 if dsh_broker::is_gate_tool(&lower) && spec.is_some_and(dsh_broker::is_gate_spec) {
229 return OriginApproval::Unchanged;
230 }
231 let forced = |candidate: &str| {
232 matches!(
233 get_tool_category_for_call(candidate, input),
234 ToolCategory::Shell | ToolCategory::Network
235 ) || FORCED_PROMPT_NAMES.contains(&candidate)
236 };
237 // Names cover core meta-tools; the registered capability and concrete
238 // execution classification also cover tools added without a name-list row.
239 let reaches_or_executes = spec.is_some_and(|spec| {
240 spec.capabilities().contains(&ToolCapability::Network)
241 || matches!(
242 classify_call(spec.name(), input, spec),
243 CallClass::VerificationFilter
244 | CallClass::UnboundedVerification
245 | CallClass::BoundedFetch
246 | CallClass::Executes
247 | CallClass::Reaches
248 )
249 });
250 if forced(&lower) || forced(&resolved) || reaches_or_executes {
251 OriginApproval::ForcePrompt
252 } else if EXT_AUTO_ELIGIBLE.contains(&resolved.as_str()) && !planned_requires_approval {
253 OriginApproval::Unchanged
254 } else {
255 OriginApproval::Prompt
256 }
257 }
258
259 #[must_use]
260 pub fn auto_review_held(
261 name: &str,
262 input: &Value,
263 planned_requires_approval: bool,
264 spec: Option<&dyn ToolSpec>,
265 ) -> bool {
266 let lower = name.to_ascii_lowercase();
267 if dsh_broker::is_gate_tool(&lower) && spec.is_some_and(dsh_broker::is_gate_spec) {
268 return planned_requires_approval;
269 }
270 !matches!(
271 origin_approval(name, input, planned_requires_approval, spec),
272 OriginApproval::Unchanged
273 )
274 }
275
276 /// One extension tool call's standing to ask the core for things: its ticket
277 /// and the machinery the asks run on. Lives from the `tool/call`'s start to
278 /// its end.
279 static NEXT_INVOCATION_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
280
281 #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
282 pub struct PluginChangeMark {
283 pub plugin: String,
284 pub action: String,
285 pub content_hash: Option<String>,
286 pub decided_by: Option<String>,
287 pub services: Vec<String>,
288 pub tools_added: Vec<String>,
289 pub tools_removed: Vec<String>,
290 }
291
292 pub struct Invocation {
293 pub cohort: HostCohort,
294 host_generation: u64,
295 owner: OwnerRef,
296 scope: Option<codewhale_config::EntryRef>,
297 plugins: Option<Arc<codewhale_plugins::PluginRegistry>>,
298 content_hash: String,
299 calls: CodemodeInvoker,
300 gate: NestedCallGate,
301 root_caller: Option<SessionCheckpointCaller>,
302 broker: Option<BrokerScope>,
303 nested_calls: AtomicU32,
304 next_broker_token: AtomicU64,
305 id: u64,
306 broker_acts: Mutex<(usize, Vec<Value>, bool)>,
307 plugin_change: Mutex<(Option<PluginChangeMark>, bool)>,
308 held_image: Mutex<(Option<(u64, HeldImage)>, bool)>,
309 tickets: Vec<Ticket>,
310 caller_tools: Vec<String>,
311 gates: Vec<&'static str>,
312 act_slots: tokio::sync::Semaphore,
313 activations: Mutex<
314 HashMap<
315 String,
316 (
317 crate::tools::subagent::SharedSubAgentManager,
318 crate::tools::subagent::ChildActivationContext,
319 ),
320 >,
321 >,
322 retired_children: Mutex<std::collections::HashSet<String>>,
323 session_call_lock: tokio::sync::Mutex<()>,
324 /// Fires when the invocation ends or is revoked: withdraws every
325 /// `core/call` still waiting or running for it.
326 cancel: CancellationToken,
327 }
328
329 impl Invocation {
330 pub fn tier(&self) -> HostTier {
331 self.cohort.tier()
332 }
333 }
334
335 struct BrokerScope {
336 session_id: String,
337 context: Arc<ToolContext>,
338 }
339
340 #[derive(Clone)]
341 pub(super) struct HeldImage {
342 pub(super) attachment_id: String,
343 pub(super) media_type: String,
344 pub(super) bytes: usize,
345 pub(super) width: u32,
346 pub(super) height: u32,
347 pub(super) data_base64: String,
348 }
349
350 impl Invocation {
351 fn push_act_record(&self, service: &str, entry: Value) -> bool {
352 let mut entry = match entry {
353 Value::Object(fields) => fields,
354 other => {
355 let mut fields = serde_json::Map::new();
356 fields.insert("detail".to_string(), other);
357 fields
358 }
359 };
360 entry.insert("service".to_string(), Value::String(service.to_string()));
361 let mut entry = Value::Object(entry);
362 if entry.to_string().len() > MAX_ACT_RECORD_BYTES {
363 let cut = |key: &str| {
364 entry
365 .get(key)
366 .and_then(Value::as_str)
367 .map_or(Value::Null, |text| {
368 Value::String(text.chars().take(dsh_broker::MAX_ACT_TARGET).collect())
369 })
370 };
371 entry = json!({
372 "service": service,
373 "method": cut("method"),
374 "outcome": cut("outcome"),
375 "cut": true,
376 });
377 }
378 let mut acts = self
379 .broker_acts
380 .lock()
381 .unwrap_or_else(std::sync::PoisonError::into_inner);
382 if acts.2 {
383 return false;
384 }
385 acts.0 += 1;
386 if acts.1.len() < RECEIPTS_ATTACHED {
387 acts.1.push(entry);
388 }
389 true
390 }
391
392 fn rollback_held_image(&self, broker_token: u64, reason: &str) -> bool {
393 let rolled = {
394 let mut guard = self
395 .held_image
396 .lock()
397 .unwrap_or_else(std::sync::PoisonError::into_inner);
398 if guard.1 {
399 return false;
400 }
401 if !guard
402 .0
403 .as_ref()
404 .is_some_and(|(token, _)| *token == broker_token)
405 {
406 return false;
407 }
408 guard.0.take().map(|(_, held)| held)
409 };
410 if let Some(held) = rolled {
411 let _ = self.push_act_record(
412 DshService::Attachments.name(),
413 json!({
414 "method": "save",
415 "outcome": "refused_after_hold",
416 "reason": reason,
417 "attachment_id": held.attachment_id,
418 "media_type": held.media_type,
419 "bytes": held.bytes,
420 "width": held.width,
421 "height": held.height,
422 }),
423 );
424 true
425 } else {
426 false
427 }
428 }
429 }
430
431 pub struct BrokerContext {
432 invocation: Arc<Invocation>,
433 tool: Arc<ToolContext>,
434 service: DshService,
435 cancel: CancellationToken,
436 broker_token: u64,
437 }
438
439 impl BrokerContext {
440 #[must_use]
441 pub fn tool(&self) -> &ToolContext {
442 &self.tool
443 }
444
445 #[must_use]
446 pub fn cancel(&self) -> &CancellationToken {
447 &self.cancel
448 }
449
450 #[must_use]
451 pub fn caller_tools(&self) -> &[String] {
452 &self.invocation.caller_tools
453 }
454
455 #[must_use]
456 pub fn mcp_pool(&self) -> Option<Arc<tokio::sync::Mutex<crate::mcp::McpPool>>> {
457 self.invocation.gate.mcp_pool()
458 }
459
460 #[must_use]
461 pub fn invocation_id(&self) -> u64 {
462 self.invocation.id
463 }
464
465 pub fn record_plugin_change(&self, mark: PluginChangeMark) {
466 let mut guard = self
467 .invocation
468 .plugin_change
469 .lock()
470 .unwrap_or_else(std::sync::PoisonError::into_inner);
471 if !guard.1 {
472 guard.0 = Some(mark);
473 }
474 }
475
476 pub fn record(&self, entry: Value) -> bool {
477 self.invocation.push_act_record(self.service.name(), entry)
478 }
479
480 pub(super) fn can_hold_image(&self) -> Result<(), bool> {
481 let guard = self
482 .invocation
483 .held_image
484 .lock()
485 .unwrap_or_else(std::sync::PoisonError::into_inner);
486 if guard.1 {
487 return Err(true);
488 }
489 if guard.0.is_some() {
490 return Err(false);
491 }
492 Ok(())
493 }
494
495 pub(super) fn hold_image(&self, image: HeldImage) -> Result<(), bool> {
496 let mut guard = self
497 .invocation
498 .held_image
499 .lock()
500 .unwrap_or_else(std::sync::PoisonError::into_inner);
501 if guard.1 {
502 return Err(true);
503 }
504 if guard.0.is_some() {
505 return Err(false);
506 }
507 guard.0 = Some((self.broker_token, image));
508 Ok(())
509 }
510
511 pub(super) fn held_image(&self, attachment_id: &str) -> Option<HeldImage> {
512 self.invocation
513 .held_image
514 .lock()
515 .unwrap_or_else(std::sync::PoisonError::into_inner)
516 .0
517 .as_ref()
518 .map(|(_, held)| held)
519 .filter(|held| held.attachment_id == attachment_id)
520 .cloned()
521 }
522
523 pub async fn act(
524 &self,
525 method: &str,
526 effect: BrokerEffect,
527 target: Option<&str>,
528 ) -> Result<(), BrokerRefusal> {
529 let raw_target = target;
530 let target: Option<String> =
531 raw_target.map(|target| target.chars().take(dsh_broker::MAX_ACT_TARGET).collect());
532 let record = |outcome: &str| -> bool {
533 let mut entry =
534 json!({ "method": method, "effect": effect.name(), "outcome": outcome });
535 if let Some(target) = &target {
536 entry["target"] = json!(target);
537 }
538 self.record(entry)
539 };
540 if self.cancel.is_cancelled() {
541 return Err(self.withdrawn());
542 }
543 if effect == BrokerEffect::Read {
544 if let Err(refusal) = self.count() {
545 record(refusal.code());
546 return Err(refusal);
547 }
548 if !record("read") {
549 return Err(self.withdrawn());
550 }
551 return Ok(());
552 }
553 if self.service == DshService::Plugins {
554 if let Err(refusal) = self.count() {
555 record(refusal.code());
556 return Err(refusal);
557 }
558 let mut live_tool = (*self.tool).clone();
559 let live_authority = live_tool.refresh_live_posture();
560 match super::creator_policy::admit_broker_act(
561 &live_tool,
562 live_authority.as_ref(),
563 method,
564 effect,
565 raw_target,
566 ) {
567 Ok((decider, posture)) => {
568 let mut entry = json!({
569 "method": method,
570 "effect": effect.name(),
571 "outcome": "allowed",
572 "decider": decider,
573 "posture": posture,
574 });
575 if let Some(target) = &target {
576 entry["target"] = json!(target);
577 }
578 if !self.record(entry) {
579 return Err(self.withdrawn());
580 }
581 return Ok(());
582 }
583 Err(message) => {
584 record("refused");
585 return Err(BrokerRefusal::Refused {
586 service: self.service,
587 message,
588 });
589 }
590 }
591 }
592 let gate_tool = effect.gate_tool();
593 if !self.invocation.gates.contains(&gate_tool) {
594 record("refused");
595 return Err(BrokerRefusal::Refused {
596 service: self.service,
597 message: "the permission gate is not available in this turn".to_string(),
598 });
599 }
600 let slot = tokio::select! {
601 slot = self.invocation.act_slots.acquire() => slot.ok(),
602 () = self.cancel.cancelled() => None,
603 () = self.invocation.cancel.cancelled() => None,
604 };
605 if slot.is_none() {
606 return Err(self.withdrawn());
607 }
608 if let Err(refusal) = self.count() {
609 record(refusal.code());
610 return Err(refusal);
611 }
612 let mut input = json!({
613 "plugin": self.invocation.owner.plugin_id,
614 "service": self.service.name(),
615 "method": method,
616 "effect": effect.name(),
617 });
618 if let Some(target) = &target {
619 input["target"] = json!(target);
620 }
621 let Some(_open) = OpenAct::open(&input, Arc::as_ptr(&self.invocation) as usize) else {
622 record("refused");
623 return Err(BrokerRefusal::Refused {
624 service: self.service,
625 message: "too many broker acts are waiting on the permission gate".to_string(),
626 });
627 };
628 match self.call_counted(gate_tool, input.clone()).await {
629 Ok(response) if response.ok && dsh_broker::answered_for(&input, &response.result) => {
630 if !record("allowed") {
631 return Err(self.withdrawn());
632 }
633 Ok(())
634 }
635 Ok(_) => {
636 record("refused");
637 Err(BrokerRefusal::Refused {
638 service: self.service,
639 message: "the permission gate refused this act".to_string(),
640 })
641 }
642 Err(refusal) => {
643 record(refusal.code());
644 Err(refusal)
645 }
646 }
647 }
648
649 fn withdrawn(&self) -> BrokerRefusal {
650 BrokerRefusal::nested(
651 self.service,
652 NestedFailure::Unavailable("the broker call was withdrawn".to_string()),
653 )
654 }
655
656 fn count(&self) -> Result<(), BrokerRefusal> {
657 if self.invocation.nested_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CALLS_PER_INVOCATION {
658 return Err(BrokerRefusal::nested(
659 self.service,
660 NestedFailure::Rejected {
661 decision: NestedDecision::Refused,
662 message: format!(
663 "a tool call may make at most {MAX_CALLS_PER_INVOCATION} core tool calls"
664 ),
665 },
666 ));
667 }
668 Ok(())
669 }
670
671 pub async fn core_call(
672 &self,
673 name: &str,
674 input: Value,
675 ) -> Result<ToolCallResponse, BrokerRefusal> {
676 if self.cancel.is_cancelled() {
677 return Err(self.withdrawn());
678 }
679 self.count()?;
680 self.call_counted(name, input).await
681 }
682
683 async fn call_counted(
684 &self,
685 name: &str,
686 input: Value,
687 ) -> Result<ToolCallResponse, BrokerRefusal> {
688 self.invocation
689 .calls
690 .call(name.to_string(), input, Some(&self.cancel))
691 .await
692 .map_err(|failure| BrokerRefusal::nested(self.service, failure))
693 }
694 }
695
696 #[cfg(test)]
697 impl BrokerContext {
698 pub fn detached_for_test(owner: &OwnerRef, service: DshService) -> Self {
699 let tool = ToolContext::new(std::path::PathBuf::from("."));
700 let gate = NestedCallGate::admitting_for_test();
701 let calls = CodemodeInvoker::for_extension(
702 dsh_broker::BrokerActTool::all().to_vec(),
703 tool.clone(),
704 gate.clone(),
705 String::new(),
706 |_, _, _| None,
707 );
708 let invocation = Arc::new(Invocation {
709 cohort: HostCohort::reviewed(),
710 host_generation: 0,
711 owner: owner.clone(),
712 scope: None,
713 plugins: None,
714 content_hash: String::new(),
715 calls,
716 gate,
717 root_caller: None,
718 broker: None,
719 nested_calls: AtomicU32::new(0),
720 next_broker_token: AtomicU64::new(1),
721 id: NEXT_INVOCATION_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
722 broker_acts: Mutex::new((0, Vec::new(), false)),
723 plugin_change: Mutex::new((None, false)),
724 held_image: Mutex::new((None, false)),
725 tickets: Vec::new(),
726 caller_tools: Vec::new(),
727 gates: dsh_broker::GATE_TOOLS.to_vec(),
728 act_slots: tokio::sync::Semaphore::new(dsh_broker::MAX_OPEN_ACTS_PER_INVOCATION),
729 activations: Mutex::new(HashMap::new()),
730 retired_children: Mutex::new(std::collections::HashSet::new()),
731 session_call_lock: tokio::sync::Mutex::new(()),
732 cancel: CancellationToken::new(),
733 });
734 Self {
735 invocation,
736 tool: Arc::new(tool),
737 service,
738 cancel: CancellationToken::new(),
739 broker_token: 0,
740 }
741 }
742 }
743
744 /// The tickets and invocations of one manager.
745 #[derive(Default)]
746 pub struct CoreCalls {
747 pub(super) tickets: super::ticket::TicketTable,
748 invocations: Mutex<HashMap<String, Arc<Invocation>>>,
749 }
750
751 impl CoreCalls {
752 /// Start an invocation for the `tool/call` `call_id` of `owner`'s tool
753 /// running on `tier`'s host process `host_generation`, if `gate` is the
754 /// nested-call gate the turn loop serves for exactly this tool
755 /// (`expected`). `None` otherwise: no ticket, so no `core/call`.
756 #[cfg(any(test, feature = "test-support"))]
757 pub fn begin(
758 self: &Arc<Self>,
759 cohort: impl Into<HostCohort>,
760 host_generation: u64,
761 owner: &OwnerRef,
762 call_id: &str,
763 expected: &ExtensionCaller,
764 context: &ToolContext,
765 gate: &NestedCallGate,
766 ) -> Option<InvocationGuard> {
767 self.begin_scoped(
768 cohort,
769 host_generation,
770 owner,
771 call_id,
772 expected,
773 context,
774 gate,
775 None,
776 String::new(),
777 &dsh_broker::test_grants().unwrap_or_default(),
778 )
779 }
780 #[allow(clippy::too_many_arguments)]
781 pub fn begin_scoped(
782 self: &Arc<Self>,
783 cohort: impl Into<HostCohort>,
784 host_generation: u64,
785 owner: &OwnerRef,
786 call_id: &str,
787 expected: &ExtensionCaller,
788 context: &ToolContext,
789 gate: &NestedCallGate,
790 scope: Option<codewhale_config::EntryRef>,
791 content_hash: String,
792 broker_services: &[DshService],
793 ) -> Option<InvocationGuard> {
794 let cohort = cohort.into();
795 let tier = cohort.tier();
796 let (caller, specs) = gate.extension()?;
797 if caller != expected {
798 return None;
799 }
800 let calls = CodemodeInvoker::for_extension(
801 specs.to_vec(),
802 context.clone(),
803 gate.clone(),
804 call_id.to_string(),
805 refusal,
806 );
807 let ticket = self.tickets.mint(Grant {
808 kind: TicketKind::Invocation,
809 cohort: cohort.clone(),
810 host_generation,
811 owner: owner.clone(),
812 method: METHOD,
813 target: json!({ "call_id": call_id }),
814 ttl: TICKET_TTL,
815 uses: MAX_CALLS_PER_INVOCATION,
816 });
817 let root_caller = context
818 .execution
819 .session_objects
820 .as_ref()
821 .filter(|session| !session.session_id.is_empty())
822 .zip(
823 context
824 .execution
825 .origin_turn_id
826 .as_ref()
827 .filter(|id| !id.is_empty()),
828 )
829 .filter(|_| context.execution.owner_agent_id.is_none())
830 .map(|(session, turn_id)| SessionCheckpointCaller {
831 session_id: session.session_id.clone(),
832 agent_id: None,
833 turn_id: turn_id.clone(),
834 call_id: call_id.to_string(),
835 workspace: context.workspace.clone(),
836 });
837 let checkpoint_ticket = root_caller.as_ref().map(|_| {
838 self.tickets.mint(Grant {
839 kind: TicketKind::Invocation,
840 cohort: cohort.clone(),
841 host_generation,
842 owner: owner.clone(),
843 method: CHECKPOINT_METHOD,
844 target: json!({ "call_id": call_id }),
845 ttl: TICKET_TTL,
846 uses: MAX_CALLS_PER_INVOCATION,
847 })
848 });
849 let question_ticket = root_caller.as_ref().map(|_| {
850 self.tickets.mint(Grant {
851 kind: TicketKind::Invocation,
852 cohort: cohort.clone(),
853 host_generation,
854 owner: owner.clone(),
855 method: QUESTION_METHOD,
856 target: json!({ "call_id": call_id }),
857 ttl: TICKET_TTL,
858 uses: MAX_CALLS_PER_INVOCATION,
859 })
860 });
861 let subagent_ticket = root_caller.as_ref().map(|_| {
862 self.tickets.mint(Grant {
863 kind: TicketKind::Invocation,
864 cohort: cohort.clone(),
865 host_generation,
866 owner: owner.clone(),
867 method: SUBAGENT_METHOD,
868 target: json!({ "call_id": call_id }),
869 ttl: TICKET_TTL,
870 uses: MAX_CALLS_PER_INVOCATION,
871 })
872 });
873 let broker_session = context
874 .execution
875 .session_objects
876 .as_ref()
877 .map(|session| session.session_id.clone())
878 .filter(|id| !id.is_empty());
879 let root_agent = context.execution.owner_agent_id.is_none();
880 let broker_tickets: Vec<(DshService, Ticket)> = broker_session
881 .iter()
882 .flat_map(|session| {
883 let ticket_cohort = cohort.clone();
884 DshService::EVERY
885 .into_iter()
886 .filter(|service| {
887 broker_services.contains(service)
888 && dsh_broker::mintable(tier, owner, *service, root_agent)
889 })
890 .map(move |service| {
891 (
892 service,
893 self.tickets.mint(Grant {
894 kind: TicketKind::Invocation,
895 cohort: ticket_cohort.clone(),
896 host_generation,
897 owner: owner.clone(),
898 method: dsh_broker::ticket_method(service),
899 target: json!({ "call_id": call_id, "session_id": session }),
900 ttl: TICKET_TTL,
901 uses: MAX_CALLS_PER_INVOCATION,
902 }),
903 )
904 })
905 })
906 .collect();
907 let broker = broker_session
908 .filter(|_| !broker_tickets.is_empty())
909 .map(|session_id| {
910 let mut context = context.clone();
911 context.execution.nested_call_gate = None;
912 BrokerScope {
913 session_id,
914 context: Arc::new(context),
915 }
916 });
917 let gates: Vec<&'static str> = dsh_broker::GATE_TOOLS
918 .into_iter()
919 .filter(|gate| {
920 specs.iter().any(|spec| {
921 spec.name().eq_ignore_ascii_case(gate)
922 && dsh_broker::is_gate_spec(spec.as_ref())
923 })
924 })
925 .collect();
926 let caller_tools = specs
927 .iter()
928 .map(|spec| spec.name().to_string())
929 .filter(|name| !dsh_broker::is_gate_tool(name))
930 .filter(|name| {
931 !context
932 .disallowed_tools
933 .iter()
934 .any(|denied| denied.eq_ignore_ascii_case(name))
935 })
936 .collect();
937 let invocation = Arc::new(Invocation {
938 cohort,
939 host_generation,
940 owner: owner.clone(),
941 scope,
942 plugins: context.plugin_registry.clone(),
943 content_hash,
944 calls,
945 gate: gate.clone(),
946 root_caller,
947 broker,
948 nested_calls: AtomicU32::new(0),
949 next_broker_token: AtomicU64::new(1),
950 id: NEXT_INVOCATION_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
951 broker_acts: Mutex::new((0, Vec::new(), false)),
952 plugin_change: Mutex::new((None, false)),
953 held_image: Mutex::new((None, false)),
954 tickets: std::iter::once(ticket.clone())
955 .chain(checkpoint_ticket.iter().cloned())
956 .chain(question_ticket.iter().cloned())
957 .chain(subagent_ticket.iter().cloned())
958 .chain(broker_tickets.iter().map(|(_, ticket)| ticket.clone()))
959 .collect(),
960 caller_tools,
961 gates,
962 act_slots: tokio::sync::Semaphore::new(dsh_broker::MAX_OPEN_ACTS_PER_INVOCATION),
963 activations: Mutex::new(HashMap::new()),
964 retired_children: Mutex::new(std::collections::HashSet::new()),
965 session_call_lock: tokio::sync::Mutex::new(()),
966 cancel: CancellationToken::new(),
967 });
968 self.invocations
969 .lock()
970 .expect("invocations lock")
971 .insert(ticket.expose().to_string(), Arc::clone(&invocation));
972 if let Some(checkpoint_ticket) = checkpoint_ticket.as_ref() {
973 self.invocations.lock().expect("invocations lock").insert(
974 checkpoint_ticket.expose().to_string(),
975 Arc::clone(&invocation),
976 );
977 }
978 if let Some(question_ticket) = question_ticket.as_ref() {
979 self.invocations.lock().expect("invocations lock").insert(
980 question_ticket.expose().to_string(),
981 Arc::clone(&invocation),
982 );
983 }
984 if let Some(subagent_ticket) = subagent_ticket.as_ref() {
985 self.invocations.lock().expect("invocations lock").insert(
986 subagent_ticket.expose().to_string(),
987 Arc::clone(&invocation),
988 );
989 }
990 for (_, broker_ticket) in &broker_tickets {
991 self.invocations
992 .lock()
993 .expect("invocations lock")
994 .insert(broker_ticket.expose().to_string(), Arc::clone(&invocation));
995 }
996 Some(InvocationGuard {
997 broker_tickets,
998 question_ticket,
999 subagent_ticket,
1000 checkpoint_ticket,
1001 core_calls: Arc::clone(self),
1002 ticket,
1003 invocation,
1004 })
1005 }
1006
1007 /// The invocation `ticket` belongs to, still live.
1008 fn invocation(&self, ticket: &str) -> Option<Arc<Invocation>> {
1009 self.invocations
1010 .lock()
1011 .expect("invocations lock")
1012 .get(ticket)
1013 .cloned()
1014 }
1015
1016 /// Revoke and withdraw whatever `keep` says to drop.
1017 fn revoke_where(&self, drop_it: impl Fn(&Invocation) -> bool) {
1018 let gone: Vec<Arc<Invocation>> = {
1019 let mut invocations = self.invocations.lock().expect("invocations lock");
1020 let keys: Vec<String> = invocations
1021 .iter()
1022 .filter(|(_, invocation)| drop_it(invocation))
1023 .map(|(key, _)| key.clone())
1024 .collect();
1025 keys.iter()
1026 .filter_map(|key| invocations.remove(key))
1027 .collect()
1028 };
1029 for invocation in gone {
1030 for ticket in &invocation.tickets {
1031 self.tickets.revoke(ticket);
1032 }
1033 invocation.cancel.cancel();
1034 }
1035 }
1036
1037 /// `plugin_id`'s owner was revoked: every ticket it holds is revoked and
1038 /// every core call it has pending is withdrawn.
1039 pub fn revoke_owner(&self, plugin_id: &str) {
1040 self.tickets.revoke_owner(plugin_id);
1041 self.revoke_where(|invocation| invocation.owner.plugin_id == plugin_id);
1042 }
1043
1044 pub fn revoke_scope(&self, plugin_id: &str, scope: &codewhale_config::EntryRef) {
1045 self.revoke_where(|invocation| {
1046 invocation.owner.plugin_id == plugin_id && invocation.scope.as_ref() == Some(scope)
1047 });
1048 }
1049
1050 pub fn revoke_attachment(&self, id: u64) {
1051 self.revoke_attachment_except(id, None);
1052 }
1053
1054 pub fn revoke_attachment_except(&self, id: u64, exempt_invocation_id: Option<u64>) {
1055 self.revoke_where(|invocation| {
1056 exempt_invocation_id != Some(invocation.id)
1057 && invocation
1058 .plugins
1059 .as_ref()
1060 .and_then(|plugins| plugins.caller_selection())
1061 .is_some_and(|selection| selection.attachment_id == id)
1062 });
1063 }
1064
1065 /// One host process exited.
1066 pub fn revoke_host(&self, cohort: impl Into<HostCohort>, host_generation: u64) {
1067 let cohort = cohort.into();
1068 self.tickets.revoke_host(&cohort, host_generation);
1069 self.revoke_where(|invocation| {
1070 invocation.cohort == cohort && invocation.host_generation == host_generation
1071 });
1072 }
1073
1074 /// How many tickets are live.
1075 #[cfg(any(test, feature = "test-support"))]
1076 pub fn live_tickets(&self) -> usize {
1077 self.tickets.live()
1078 }
1079
1080 fn end(&self, ticket: &Ticket) {
1081 if let Some(invocation) = self.invocation(ticket.expose()) {
1082 self.revoke_where(|candidate| std::ptr::eq(candidate, invocation.as_ref()));
1083 } else {
1084 self.tickets.revoke(ticket);
1085 }
1086 }
1087
1088 #[allow(clippy::too_many_arguments)]
1089 fn redeem_invocation(
1090 &self,
1091 shared: &ManagerShared,
1092 cohort: &HostCohort,
1093 host_generation: u64,
1094 owner: &OwnerRef,
1095 ticket: &str,
1096 method: &str,
1097 cx: &HostRequestContext,
1098 ) -> Result<Arc<Invocation>, RpcErrorWire> {
1099 self.redeem_invocation_or_limit(shared, cohort, host_generation, owner, ticket, method, cx)
1100 .map_err(|(_, error)| error)
1101 }
1102
1103 #[allow(clippy::too_many_arguments)]
1104 fn redeem_invocation_or_limit(
1105 &self,
1106 shared: &ManagerShared,
1107 cohort: &HostCohort,
1108 host_generation: u64,
1109 owner: &OwnerRef,
1110 ticket: &str,
1111 method: &str,
1112 cx: &HostRequestContext,
1113 ) -> Result<Arc<Invocation>, (bool, RpcErrorWire)> {
1114 let refuse = |code, message| {
1115 (
1116 false,
1117 RpcErrorWire {
1118 code,
1119 message,
1120 data: None,
1121 },
1122 )
1123 };
1124 let redeemed = self.tickets.redeem(&Presented {
1125 ticket,
1126 kind: TicketKind::Invocation,
1127 cohort: cohort.clone(),
1128 host_generation,
1129 owner,
1130 method,
1131 target: None,
1132 });
1133 if let Err(refused) = redeemed {
1134 if refused.violation {
1135 cx.violation(format!(
1136 "too many invalid {method} tickets from one host process"
1137 ));
1138 }
1139 let (_, error) = refuse(error_code::REFUSED, refused.reason.describe().to_string());
1140 return Err((refused.reason == super::ticket::Refusal::Exhausted, error));
1141 }
1142 let live = shared
1143 .registry
1144 .lock()
1145 .expect("registry lock")
1146 .cohort_of(owner)
1147 .as_ref()
1148 == Some(cohort);
1149 let Some(invocation) = self.invocation(ticket).filter(|_| live) else {
1150 return Err(refuse(
1151 error_code::REFUSED,
1152 format!("the invocation this {method} belongs to has ended"),
1153 ));
1154 };
1155 shared
1156 .check_selection(
1157 invocation
1158 .plugins
1159 .as_ref()
1160 .and_then(|plugins| plugins.caller_selection()),
1161 invocation.plugins.as_deref(),
1162 &owner.plugin_id,
1163 &invocation.content_hash,
1164 invocation.scope.as_ref(),
1165 )
1166 .map_err(|message| refuse(error_code::REFUSED, message))?;
1167 if invocation.cancel.is_cancelled() {
1168 return Err(refuse(
1169 error_code::REFUSED,
1170 "the invocation has ended".to_string(),
1171 ));
1172 }
1173 Ok(invocation)
1174 }
1175
1176 pub async fn serve_checkpoint(
1177 &self,
1178 shared: &ManagerShared,
1179 cohort: impl Into<HostCohort>,
1180 host_generation: u64,
1181 params: SessionCheckpointParams,
1182 cx: HostRequestContext,
1183 ) -> Result<Value, RpcErrorWire> {
1184 let cohort = cohort.into();
1185 let refuse = |code, message| RpcErrorWire {
1186 code,
1187 message,
1188 data: None,
1189 };
1190 let invocation = self.redeem_invocation(
1191 shared,
1192 &cohort,
1193 host_generation,
1194 &params.owner,
1195 &params.ticket,
1196 CHECKPOINT_METHOD,
1197 &cx,
1198 )?;
1199 let caller = invocation.root_caller.clone().ok_or_else(|| {
1200 refuse(
1201 error_code::NOT_AVAILABLE,
1202 "session checkpoint requires a live root invocation".into(),
1203 )
1204 })?;
1205 let withdraw = invocation.cancel.child_token();
1206 let _withdraw_guard = withdraw.clone().drop_guard();
1207 let outcome = tokio::select! {
1208 biased;
1209 () = cx.cancel.cancelled() => Err(crate::tools::spec::ToolError::cancelled("session checkpoint was cancelled by its host")),
1210 () = withdraw.cancelled() => Err(crate::tools::spec::ToolError::cancelled("session checkpoint invocation ended")),
1211 result = async {
1212 let _session_call = invocation.session_call_lock.lock().await;
1213 invocation.gate.checkpoint(caller, withdraw.clone()).await
1214 } => result,
1215 };
1216 if cx.cancel.is_cancelled() || invocation.cancel.is_cancelled() {
1217 return Err(refuse(
1218 error_code::CANCELLED,
1219 "session checkpoint invocation was withdrawn".into(),
1220 ));
1221 }
1222 if shared
1223 .registry
1224 .lock()
1225 .expect("registry lock")
1226 .cohort_of(&params.owner)
1227 .as_ref()
1228 != Some(&cohort)
1229 {
1230 return Err(refuse(
1231 error_code::REFUSED,
1232 "session checkpoint owner is no longer current".into(),
1233 ));
1234 }
1235 shared
1236 .check_selection(
1237 invocation
1238 .plugins
1239 .as_ref()
1240 .and_then(|plugins| plugins.caller_selection()),
1241 invocation.plugins.as_deref(),
1242 &params.owner.plugin_id,
1243 &invocation.content_hash,
1244 invocation.scope.as_ref(),
1245 )
1246 .map_err(|message| refuse(error_code::REFUSED, message))?;
1247 outcome.map(Value::Bool).map_err(|error| {
1248 let code = if matches!(&error, crate::tools::spec::ToolError::Cancelled { .. }) {
1249 error_code::CANCELLED
1250 } else {
1251 error_code::NOT_AVAILABLE
1252 };
1253 refuse(code, error.to_string())
1254 })
1255 }
1256
1257 pub async fn serve_question(
1258 &self,
1259 shared: &ManagerShared,
1260 cohort: impl Into<HostCohort>,
1261 host_generation: u64,
1262 params: UserQuestionParams,
1263 cx: HostRequestContext,
1264 ) -> Result<Value, RpcErrorWire> {
1265 let cohort = cohort.into();
1266 let refuse = |code, message| RpcErrorWire {
1267 code,
1268 message,
1269 data: None,
1270 };
1271 let invocation = self.redeem_invocation(
1272 shared,
1273 &cohort,
1274 host_generation,
1275 &params.owner,
1276 &params.ticket,
1277 QUESTION_METHOD,
1278 &cx,
1279 )?;
1280 let caller = invocation.root_caller.clone().ok_or_else(|| {
1281 refuse(
1282 error_code::NOT_AVAILABLE,
1283 "user question requires a live root invocation".into(),
1284 )
1285 })?;
1286 let request = crate::tools::user_input::UserInputRequest {
1287 require_typed_answers: true,
1288 questions: params
1289 .questions
1290 .into_iter()
1291 .map(|mut question| {
1292 question.allow_free_text = true;
1293 question
1294 })
1295 .collect(),
1296 };
1297 request
1298 .validate_transport()
1299 .map_err(|error| refuse(error_code::INVALID_PARAMS, error.to_string()))?;
1300 let withdraw = invocation.cancel.child_token();
1301 let _withdraw_guard = withdraw.clone().drop_guard();
1302 let outcome = tokio::select! {
1303 biased;
1304 () = cx.cancel.cancelled() => Err(crate::tools::spec::ToolError::cancelled("user question was cancelled by its host")),
1305 () = withdraw.cancelled() => Err(crate::tools::spec::ToolError::cancelled("user question invocation ended")),
1306 result = async {
1307 let _session_call = invocation.session_call_lock.lock().await;
1308 invocation.gate.user_question(caller, request, withdraw.clone(), invocation.calls.clock()).await
1309 } => result,
1310 };
1311 if cx.cancel.is_cancelled() || invocation.cancel.is_cancelled() {
1312 return Err(refuse(
1313 error_code::CANCELLED,
1314 "user question invocation was withdrawn".into(),
1315 ));
1316 }
1317 if shared
1318 .registry
1319 .lock()
1320 .expect("registry lock")
1321 .cohort_of(&params.owner)
1322 .as_ref()
1323 != Some(&cohort)
1324 {
1325 return Err(refuse(
1326 error_code::REFUSED,
1327 "user question owner is no longer current".into(),
1328 ));
1329 }
1330 shared
1331 .check_selection(
1332 invocation
1333 .plugins
1334 .as_ref()
1335 .and_then(|plugins| plugins.caller_selection()),
1336 invocation.plugins.as_deref(),
1337 &params.owner.plugin_id,
1338 &invocation.content_hash,
1339 invocation.scope.as_ref(),
1340 )
1341 .map_err(|message| refuse(error_code::REFUSED, message))?;
1342 outcome
1343 .map(|response| serde_json::to_value(response).expect("user input response serializes"))
1344 .map_err(|error| {
1345 let question_code = error
1346 .metadata()
1347 .and_then(|metadata| metadata.get("user_question_error"))
1348 .and_then(Value::as_str)
1349 .filter(|code| matches!(*code, "NO_PROVIDER" | "ASK_CANCELLED"));
1350 let code = if matches!(&error, crate::tools::spec::ToolError::Cancelled { .. })
1351 || question_code == Some("ASK_CANCELLED")
1352 {
1353 error_code::CANCELLED
1354 } else {
1355 error_code::NOT_AVAILABLE
1356 };
1357 let data = question_code.map(|code| json!({"user_question_error": code}));
1358 RpcErrorWire {
1359 code,
1360 message: error.to_string(),
1361 data,
1362 }
1363 })
1364 }
1365
1366 pub async fn serve_subagent(
1367 &self,
1368 shared: &ManagerShared,
1369 cohort: impl Into<HostCohort>,
1370 host_generation: u64,
1371 request: super::protocol::HostRequest,
1372 cx: HostRequestContext,
1373 ) -> Result<Value, RpcErrorWire> {
1374 let cohort = cohort.into();
1375 use super::protocol::HostRequest;
1376 use crate::tools::subagent::{
1377 ChildActivationRequest, dispose_child_activation, resolve_child_activation_output,
1378 };
1379 use codewhale_agent_contract::worker_profile::{
1380 ChildActivationDelivery, FrozenChildConfiguration,
1381 };
1382 let refuse = |code, message: String| RpcErrorWire {
1383 code,
1384 message,
1385 data: None,
1386 };
1387 let (owner, ticket, child_id) = match &request {
1388 HostRequest::SubagentStart(p) => (&p.owner, &p.ticket, &p.child_id),
1389 HostRequest::SubagentResult(p) | HostRequest::SubagentDispose(p) => {
1390 (&p.owner, &p.ticket, &p.child_id)
1391 }
1392 HostRequest::SubagentPrompt(p) => (&p.owner, &p.ticket, &p.child_id),
1393 _ => {
1394 return Err(refuse(
1395 error_code::INVALID_PARAMS,
1396 "not a subagent request".into(),
1397 ));
1398 }
1399 };
1400 let (owner, child_id) = (owner.clone(), child_id.clone());
1401 let invocation = self.redeem_invocation(
1402 shared,
1403 &cohort,
1404 host_generation,
1405 &owner,
1406 ticket,
1407 SUBAGENT_METHOD,
1408 &cx,
1409 )?;
1410 if invocation.root_caller.is_none() {
1411 return Err(refuse(
1412 error_code::NOT_AVAILABLE,
1413 "child agents require a live root invocation".into(),
1414 ));
1415 }
1416 let withdraw = invocation.cancel.child_token();
1417 let _withdraw_guard = withdraw.clone().drop_guard();
1418 let entry = |child_id: &str| {
1419 invocation
1420 .activations
1421 .lock()
1422 .expect("activations lock")
1423 .get(child_id)
1424 .cloned()
1425 };
1426 let result = match request {
1427 HostRequest::SubagentStart(params) => {
1428 if params.child_id.is_empty()
1429 || params.child_id.len() > 128
1430 || !params
1431 .child_id
1432 .bytes()
1433 .all(|byte| byte.is_ascii_alphanumeric() || b"-_.:".contains(&byte))
1434 {
1435 return Err(refuse(
1436 error_code::INVALID_PARAMS,
1437 "child id must be 1-128 ASCII letters, digits, '-', '_', '.' or ':'".into(),
1438 ));
1439 }
1440 if params.prompt.trim().is_empty() {
1441 return Err(refuse(
1442 error_code::INVALID_PARAMS,
1443 "child prompt is empty".into(),
1444 ));
1445 }
1446 let delivery = match params.delivery.as_str() {
1447 "caller" => ChildActivationDelivery::Caller,
1448 "parent" => ChildActivationDelivery::Parent,
1449 _ => {
1450 return Err(refuse(
1451 error_code::INVALID_PARAMS,
1452 "child delivery must be caller or parent".into(),
1453 ));
1454 }
1455 };
1456 if entry(&params.child_id).is_some() {
1457 return Err(refuse(
1458 error_code::REFUSED,
1459 "child id is already active in this invocation".into(),
1460 ));
1461 }
1462 let launch = Arc::new(ChildActivationRequest {
1463 public_child_id: params.child_id.clone(),
1464 configuration: FrozenChildConfiguration {
1465 persona: params.persona,
1466 denied_tools: params.denied_tools,
1467 delivery,
1468 },
1469 launched: std::sync::Mutex::new(None),
1470 });
1471 let mut input = json!({
1472 "action": "start",
1473 "prompt": params.prompt,
1474 "fork_context": false,
1475 });
1476 if let Some(model) = params.model {
1477 input["model"] = json!(model);
1478 }
1479 let started = tokio::select! {
1480 biased;
1481 () = cx.cancel.cancelled() => Err(refuse(error_code::CANCELLED, "child start was cancelled by its host".into())),
1482 () = withdraw.cancelled() => Err(refuse(error_code::CANCELLED, "child start invocation ended".into())),
1483 started = invocation.calls.start_child_activation(input, &withdraw, Arc::clone(&launch)) => match started {
1484 Ok(response) if response.ok => Ok(()),
1485 Ok(response) => Err(refuse(error_code::REFUSED, response.result.as_str().map_or_else(|| response.result.to_string(), str::to_string))),
1486 Err(NestedFailure::Rejected { decision, message }) => Err(refuse(
1487 if decision == NestedDecision::Denied { error_code::DENIED } else { error_code::REFUSED },
1488 message,
1489 )),
1490 Err(NestedFailure::Unavailable(message)) => Err(refuse(error_code::NOT_AVAILABLE, message)),
1491 },
1492 };
1493 let launched = launch
1494 .launched
1495 .lock()
1496 .expect("child activation lock")
1497 .take();
1498 match (started, launched) {
1499 (Ok(()), Some((manager, context))) => {
1500 let accepted = tokio::select! {
1501 biased;
1502 () = cx.cancel.cancelled() => None,
1503 () = withdraw.cancelled() => None,
1504 accepted = context.accepted() => Some(accepted),
1505 };
1506 match accepted {
1507 Some(Ok(admission)) => {
1508 invocation
1509 .activations
1510 .lock()
1511 .expect("activations lock")
1512 .insert(params.child_id.clone(), (manager, context));
1513 let watched = Arc::clone(&invocation);
1514 let watched_id = params.child_id.clone();
1515 tokio::spawn(async move {
1516 watched.cancel.cancelled().await;
1517 let entry = watched
1518 .activations
1519 .lock()
1520 .expect("activations lock")
1521 .remove(&watched_id);
1522 if let Some((manager, context)) = entry {
1523 let _ =
1524 dispose_child_activation(&manager, &context.identity)
1525 .await;
1526 }
1527 });
1528 Ok(json!({
1529 "child_id": params.child_id,
1530 "message_id": admission.submission_id,
1531 }))
1532 }
1533 other => {
1534 let _ = dispose_child_activation(&manager, &context.identity).await;
1535 Err(match other {
1536 Some(Err(error)) => refuse(
1537 error_code::NOT_AVAILABLE,
1538 format!("child did not accept its first message: {error}"),
1539 ),
1540 _ => refuse(
1541 error_code::CANCELLED,
1542 "child start was withdrawn".into(),
1543 ),
1544 })
1545 }
1546 }
1547 }
1548 (Ok(()), None) => Err(refuse(
1549 error_code::NOT_AVAILABLE,
1550 "the agent start did not record a child activation".into(),
1551 )),
1552 (Err(error), launched) => {
1553 if let Some((manager, context)) = launched {
1554 let _ = dispose_child_activation(&manager, &context.identity).await;
1555 }
1556 Err(error)
1557 }
1558 }
1559 }
1560 HostRequest::SubagentResult(_) => {
1561 let (manager, context) = entry(&child_id).ok_or_else(|| {
1562 refuse(
1563 error_code::NOT_AVAILABLE,
1564 "no live child activation with that id".into(),
1565 )
1566 })?;
1567 let settled = tokio::select! {
1568 biased;
1569 () = cx.cancel.cancelled() => return Err(refuse(error_code::CANCELLED, "child result wait was cancelled".into())),
1570 () = withdraw.cancelled() => return Err(refuse(error_code::CANCELLED, "child result invocation ended".into())),
1571 settled = context.settled() => settled,
1572 };
1573 match settled {
1574 Err(error) => Err(refuse(error_code::NOT_AVAILABLE, error.to_string())),
1575 Ok(_) => {
1576 match resolve_child_activation_output(&manager, &context.identity).await {
1577 Err(error) => Err(refuse(error_code::NOT_AVAILABLE, error.to_string())),
1578 Ok((blocks, stop_reason)) => {
1579 let total = blocks.len();
1580 let output: Vec<Value> = blocks
1581 .into_iter()
1582 .filter_map(|block| match block {
1583 codewhale_models::ContentBlock::Text { text, .. } => {
1584 Some(json!({"type": "text", "text": text}))
1585 }
1586 _ => None,
1587 })
1588 .collect();
1589 Ok(json!({
1590 "stop_reason": stop_reason,
1591 "output": output,
1592 "omitted_blocks": total - output.len(),
1593 }))
1594 }
1595 }
1596 }
1597 }
1598 }
1599 HostRequest::SubagentDispose(_) => {
1600 invocation
1601 .retired_children
1602 .lock()
1603 .expect("retired children lock")
1604 .insert(child_id.clone());
1605 let entry = invocation
1606 .activations
1607 .lock()
1608 .expect("activations lock")
1609 .remove(&child_id);
1610 match entry {
1611 None => Ok(json!({})),
1612 Some((manager, context)) => {
1613 dispose_child_activation(&manager, &context.identity)
1614 .await
1615 .map(|_| json!({}))
1616 .map_err(|error| refuse(error_code::NOT_AVAILABLE, error.to_string()))
1617 }
1618 }
1619 }
1620 HostRequest::SubagentPrompt(params) => {
1621 if params.child_id.is_empty()
1622 || params.child_id.len() > 128
1623 || !params
1624 .child_id
1625 .bytes()
1626 .all(|byte| byte.is_ascii_alphanumeric() || b"-_.:".contains(&byte))
1627 {
1628 return Err(refuse(
1629 error_code::INVALID_PARAMS,
1630 "child id must be 1-128 ASCII letters, digits, '-', '_', '.' or ':'".into(),
1631 ));
1632 }
1633 if params.prompt.trim().is_empty() {
1634 return Err(refuse(
1635 error_code::INVALID_PARAMS,
1636 "child prompt is empty".into(),
1637 ));
1638 }
1639 if !matches!(
1640 params.mode.as_str(),
1641 "queue" | "steer" | "followup" | "message"
1642 ) {
1643 return Err(refuse(
1644 error_code::INVALID_PARAMS,
1645 "subagent prompt mode must be queue, steer, followup, or message".into(),
1646 ));
1647 }
1648 if invocation
1649 .retired_children
1650 .lock()
1651 .expect("retired children lock")
1652 .contains(&params.child_id)
1653 {
1654 return Err(refuse(
1655 error_code::REFUSED,
1656 "child has been retired and cannot be resumed".into(),
1657 ));
1658 }
1659 let (manager, context) = entry(&params.child_id).ok_or_else(|| {
1660 refuse(
1661 error_code::NOT_AVAILABLE,
1662 "no live child activation with that id".into(),
1663 )
1664 })?;
1665 let manager_owned = manager.clone();
1666 let identity_owned = context.identity.clone();
1667 let prompt_owned = params.prompt.clone();
1668 let delivery = tokio::select! {
1669 biased;
1670 () = cx.cancel.cancelled() => return Err(refuse(error_code::CANCELLED, "child prompt was cancelled by its host".into())),
1671 () = withdraw.cancelled() => return Err(refuse(error_code::CANCELLED, "child prompt invocation ended".into())),
1672 delivery = codewhale_runtime::runtime_control::owner_work(move || {
1673 let mut guard = manager_owned.blocking_write();
1674 guard.followup_child(&identity_owned.child_id, prompt_owned)
1675 }) => delivery,
1676 };
1677 match delivery {
1678 Ok(receipt) => Ok(json!({
1679 "child_id": params.child_id,
1680 "message_id": uuid::Uuid::new_v4().to_string(),
1681 "status": receipt.status,
1682 "queue_depth": receipt.queue_depth,
1683 "woke": receipt.woke,
1684 })),
1685 Err(error) => {
1686 let message = error.to_string();
1687 if message.contains("cannot resume") {
1688 invocation
1689 .retired_children
1690 .lock()
1691 .expect("retired children lock")
1692 .insert(params.child_id);
1693 Err(refuse(error_code::REFUSED, message))
1694 } else {
1695 Err(refuse(error_code::NOT_AVAILABLE, message))
1696 }
1697 }
1698 }
1699 }
1700 _ => unreachable!("subagent request variants are matched above"),
1701 };
1702 shared
1703 .check_selection(
1704 invocation
1705 .plugins
1706 .as_ref()
1707 .and_then(|plugins| plugins.caller_selection()),
1708 invocation.plugins.as_deref(),
1709 &owner.plugin_id,
1710 &invocation.content_hash,
1711 invocation.scope.as_ref(),
1712 )
1713 .map_err(|message| refuse(error_code::REFUSED, message))?;
1714 result
1715 }
1716
1717 pub async fn serve_broker(
1718 &self,
1719 shared: &ManagerShared,
1720 cohort: impl Into<HostCohort>,
1721 host_generation: u64,
1722 params: DshBrokerParams,
1723 cx: HostRequestContext,
1724 ) -> Result<Value, RpcErrorWire> {
1725 self.serve_broker_in(
1726 dsh_broker::TABLE,
1727 shared,
1728 cohort,
1729 host_generation,
1730 params,
1731 cx,
1732 )
1733 .await
1734 }
1735
1736 pub(super) async fn serve_broker_in(
1737 &self,
1738 table: &[(DshService, Arm)],
1739 shared: &ManagerShared,
1740 cohort: impl Into<HostCohort>,
1741 host_generation: u64,
1742 params: DshBrokerParams,
1743 cx: HostRequestContext,
1744 ) -> Result<Value, RpcErrorWire> {
1745 let cohort = cohort.into();
1746 let refused = |message: String| {
1747 dsh_broker::coded(
1748 RpcErrorWire {
1749 code: error_code::REFUSED,
1750 message,
1751 data: None,
1752 },
1753 dsh_broker::TICKET_REFUSED,
1754 )
1755 };
1756 let cancelled = |message: &str| {
1757 dsh_broker::coded(
1758 RpcErrorWire {
1759 code: error_code::CANCELLED,
1760 message: message.to_string(),
1761 data: None,
1762 },
1763 dsh_broker::CANCELLED,
1764 )
1765 };
1766 let service = DshService::parse(&params.service)
1767 .ok_or_else(|| BrokerRefusal::UnknownService(params.service.clone()).wire())?;
1768 let invocation = self
1769 .redeem_invocation_or_limit(
1770 shared,
1771 &cohort,
1772 host_generation,
1773 &params.owner,
1774 &params.ticket,
1775 dsh_broker::ticket_method(service),
1776 &cx,
1777 )
1778 .map_err(|(limit, mut error)| {
1779 if limit {
1780 error.message = format!(
1781 "this tool call's limit for the {} service is used up",
1782 service.name()
1783 );
1784 dsh_broker::coded(error, dsh_broker::LIMIT)
1785 } else {
1786 dsh_broker::coded(error, dsh_broker::TICKET_REFUSED)
1787 }
1788 })?;
1789 let (session_id, tool) = invocation
1790 .broker
1791 .as_ref()
1792 .map(|scope| (scope.session_id.clone(), Arc::clone(&scope.context)))
1793 .ok_or_else(|| refused("dsh/broker requires an invocation in a session".into()))?;
1794 if service.builtin_only() && tool.execution.owner_agent_id.is_some() {
1795 return Err(BrokerRefusal::NotGranted(service).wire());
1796 }
1797 if !shared.broker_granted(&params.owner, service).await {
1798 return Err(BrokerRefusal::NotGranted(service).wire());
1799 }
1800 let arm = dsh_broker::arm_in(table, service)
1801 .ok_or_else(|| BrokerRefusal::NotAvailable(service).wire())?;
1802 let withdraw = invocation.cancel.child_token();
1803 let _withdraw_guard = withdraw.clone().drop_guard();
1804 let broker_token = invocation.next_broker_token.fetch_add(1, Ordering::Relaxed);
1805 struct HeldImageRollback {
1806 invocation: Arc<Invocation>,
1807 broker_token: u64,
1808 armed: bool,
1809 }
1810 impl HeldImageRollback {
1811 fn commit(&mut self) {
1812 self.armed = false;
1813 }
1814 fn rollback(&mut self, reason: &str) {
1815 if self.armed {
1816 self.armed = false;
1817 self.invocation
1818 .rollback_held_image(self.broker_token, reason);
1819 }
1820 }
1821 }
1822 impl Drop for HeldImageRollback {
1823 fn drop(&mut self) {
1824 if self.armed {
1825 self.invocation
1826 .rollback_held_image(self.broker_token, "aborted");
1827 }
1828 }
1829 }
1830 let mut rollback = HeldImageRollback {
1831 invocation: Arc::clone(&invocation),
1832 broker_token,
1833 armed: true,
1834 };
1835 let arm_cancel = withdraw.child_token();
1836 let call = BrokerCall {
1837 owner: params.owner.clone(),
1838 session_id,
1839 service,
1840 method: params.method,
1841 input: params.input,
1842 context: BrokerContext {
1843 invocation: Arc::clone(&invocation),
1844 tool,
1845 service,
1846 cancel: arm_cancel.clone(),
1847 broker_token,
1848 },
1849 };
1850 let withdrawn = async {
1851 loop {
1852 tokio::time::sleep(GRANT_PROBE).await;
1853 if !shared.broker_granted(&params.owner, service).await {
1854 break;
1855 }
1856 }
1857 };
1858 let arm_future = arm(call);
1859 tokio::pin!(arm_future);
1860 let outcome = match tokio::select! {
1861 biased;
1862 () = cx.cancel.cancelled() => Err(("cancelled", cancelled("dsh/broker was cancelled by its host"))),
1863 () = withdraw.cancelled() => Err(("invocation_ended", cancelled("dsh/broker invocation ended"))),
1864 () = withdrawn => Err(("grant_revoked", BrokerRefusal::NotGranted(service).wire())),
1865 outcome = &mut arm_future => Ok(outcome),
1866 } {
1867 Ok(outcome) => outcome,
1868 Err((reason, wire)) => {
1869 if matches!(service, DshService::Plugins) {
1870 arm_cancel.cancel();
1871 let _ = tokio::time::timeout(Duration::from_secs(5), &mut arm_future).await;
1872 }
1873 rollback.rollback(reason);
1874 return Err(wire);
1875 }
1876 };
1877 if cx.cancel.is_cancelled() {
1878 rollback.rollback("cancelled");
1879 return Err(cancelled("dsh/broker was cancelled by its host"));
1880 }
1881 if withdraw.is_cancelled() {
1882 rollback.rollback("invocation_ended");
1883 return Err(cancelled("dsh/broker invocation ended"));
1884 }
1885 if shared
1886 .registry
1887 .lock()
1888 .expect("registry lock")
1889 .cohort_of(&params.owner)
1890 .as_ref()
1891 != Some(&cohort)
1892 {
1893 rollback.rollback("owner_stale");
1894 return Err(refused("dsh/broker owner is no longer current".into()));
1895 }
1896 if let Err(err) = shared.check_selection(
1897 invocation
1898 .plugins
1899 .as_ref()
1900 .and_then(|plugins| plugins.caller_selection()),
1901 invocation.plugins.as_deref(),
1902 &params.owner.plugin_id,
1903 &invocation.content_hash,
1904 invocation.scope.as_ref(),
1905 ) {
1906 rollback.rollback("selection_changed");
1907 return Err(refused(err));
1908 }
1909 if !shared.broker_granted(&params.owner, service).await {
1910 rollback.rollback("grant_revoked");
1911 return Err(BrokerRefusal::NotGranted(service).wire());
1912 }
1913 match outcome {
1914 Ok(value) => {
1915 rollback.commit();
1916 Ok(value)
1917 }
1918 Err(err) => {
1919 rollback.rollback("refused");
1920 Err(err.wire())
1921 }
1922 }
1923 }
1924
1925 /// Redeem `params` presented by `tier`'s host process `host_generation`
1926 /// and run the call. An invalid presentation is a refusal, and a burst of
1927 /// them a violation `cx` reports.
1928 pub async fn serve(
1929 &self,
1930 shared: &ManagerShared,
1931 cohort: impl Into<HostCohort>,
1932 host_generation: u64,
1933 params: CoreCallParams,
1934 cx: HostRequestContext,
1935 ) -> Result<Value, RpcErrorWire> {
1936 let cohort = cohort.into();
1937 let refuse = |code: i64, message: String| RpcErrorWire {
1938 code,
1939 message,
1940 data: None,
1941 };
1942 let invocation = self.redeem_invocation(
1943 shared,
1944 &cohort,
1945 host_generation,
1946 &params.owner,
1947 &params.ticket,
1948 METHOD,
1949 &cx,
1950 )?;
1951 if dsh_broker::is_gate_tool(&params.name) {
1952 return Err(refuse(
1953 error_code::REFUSED,
1954 format!(
1955 "`{}` is the host broker's permission gate; only the broker reaches it",
1956 params.name
1957 ),
1958 ));
1959 }
1960 if invocation.nested_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CALLS_PER_INVOCATION {
1961 return Err(refuse(
1962 error_code::REFUSED,
1963 super::ticket::Refusal::Exhausted.describe().to_string(),
1964 ));
1965 }
1966 // Withdrawn when the host cancels this request, its owner is revoked,
1967 // the host exits (`cx.cancel`), or the invocation ends.
1968 let withdraw = invocation.cancel.child_token();
1969 {
1970 let (withdraw, host) = (withdraw.clone(), cx.cancel.clone());
1971 tokio::spawn(async move {
1972 tokio::select! {
1973 () = host.cancelled() => withdraw.cancel(),
1974 () = withdraw.cancelled() => {}
1975 }
1976 });
1977 }
1978 let outcome = invocation
1979 .calls
1980 .call(params.name, params.input, Some(&withdraw))
1981 .await;
1982 shared
1983 .check_selection(
1984 invocation
1985 .plugins
1986 .as_ref()
1987 .and_then(|plugins| plugins.caller_selection()),
1988 invocation.plugins.as_deref(),
1989 &params.owner.plugin_id,
1990 &invocation.content_hash,
1991 invocation.scope.as_ref(),
1992 )
1993 .map_err(|message| refuse(error_code::REFUSED, message))?;
1994 let result = match outcome {
1995 Ok(response) => Ok(wire_from_response(response)),
1996 Err(NestedFailure::Rejected { decision, message }) => Err(refuse(
1997 if decision == NestedDecision::Denied {
1998 error_code::DENIED
1999 } else {
2000 error_code::REFUSED
2001 },
2002 message,
2003 )),
2004 Err(NestedFailure::Unavailable(message)) => Err(refuse(
2005 if withdraw.is_cancelled() {
2006 error_code::CANCELLED
2007 } else {
2008 error_code::NOT_AVAILABLE
2009 },
2010 message,
2011 )),
2012 };
2013 // Stop the forwarder when the call is over.
2014 withdraw.cancel();
2015 result.map(|wire| serde_json::to_value(wire).expect("wire results serialize"))
2016 }
2017 }
2018
2019 /// An extension tool's answer to its `core/call`: the tool's text (and its
2020 /// structured JSON when the content was JSON), bounded as code mode bounds it.
2021 pub fn wire_from_response(response: ToolCallResponse) -> ToolResultWire {
2022 if !response.ok {
2023 let text = match response.result {
2024 Value::String(text) => text,
2025 Value::Object(ref map) => match map.get("content") {
2026 Some(Value::String(text)) => text.clone(),
2027 Some(other) if !other.is_null() => other.to_string(),
2028 _ => response.result.to_string(),
2029 },
2030 other => other.to_string(),
2031 };
2032 return ToolResultWire {
2033 content: vec![ContentBlockWire::Text { text }],
2034 is_error: true,
2035 structured: None,
2036 };
2037 }
2038 let content = response
2039 .result
2040 .get("content")
2041 .cloned()
2042 .unwrap_or(Value::Null);
2043 let (mut text, structured) = match content {
2044 Value::String(text) => (text, None),
2045 other => (other.to_string(), Some(other)),
2046 };
2047 if let Some(cut) = response
2048 .result
2049 .get("truncated")
2050 .filter(|truncated| !truncated.is_null())
2051 {
2052 let number = |key: &str| cut.get(key).and_then(Value::as_u64).unwrap_or(0);
2053 text.push_str(&format!(
2054 "\n[output truncated: {} bytes in all, the first {} are shown]",
2055 number("original_bytes"),
2056 number("kept_bytes")
2057 ));
2058 }
2059 ToolResultWire {
2060 content: vec![ContentBlockWire::Text { text }],
2061 is_error: false,
2062 structured,
2063 }
2064 }
2065
2066 /// Holds an invocation open. Dropping it (the `tool/call` ended or its future
2067 /// was dropped) revokes its tickets and withdraws whatever is still pending.
2068 pub struct InvocationGuard {
2069 core_calls: Arc<CoreCalls>,
2070 ticket: Ticket,
2071 checkpoint_ticket: Option<Ticket>,
2072 question_ticket: Option<Ticket>,
2073 subagent_ticket: Option<Ticket>,
2074 broker_tickets: Vec<(DshService, Ticket)>,
2075 invocation: Arc<Invocation>,
2076 }
2077
2078 impl InvocationGuard {
2079 /// The ticket id to put in this call's `tool/call` (and nowhere else).
2080 pub fn ticket(&self) -> &str {
2081 self.ticket.expose()
2082 }
2083
2084 pub fn checkpoint_ticket(&self) -> Option<&str> {
2085 self.checkpoint_ticket.as_ref().map(Ticket::expose)
2086 }
2087
2088 pub fn question_ticket(&self) -> Option<&str> {
2089 self.question_ticket.as_ref().map(Ticket::expose)
2090 }
2091
2092 pub fn subagent_ticket(&self) -> Option<&str> {
2093 self.subagent_ticket.as_ref().map(Ticket::expose)
2094 }
2095
2096 pub fn broker_tickets(&self) -> Option<Vec<DshBrokerTicketWire>> {
2097 (!self.broker_tickets.is_empty()).then(|| {
2098 self.broker_tickets
2099 .iter()
2100 .map(|(service, ticket)| DshBrokerTicketWire {
2101 service: service.name().to_string(),
2102 ticket: ticket.expose().to_string(),
2103 })
2104 .collect()
2105 })
2106 }
2107
2108 pub fn caller_tools(&self) -> Option<Vec<String>> {
2109 self.subagent_ticket
2110 .as_ref()
2111 .map(|_| self.invocation.caller_tools.clone())
2112 }
2113
2114 /// The clock the `tool/call` deadline runs on: paused while one of this
2115 /// invocation's core calls waits on the gate.
2116 pub fn clock(&self) -> Arc<Mutex<PauseClock>> {
2117 self.invocation.calls.clock()
2118 }
2119
2120 /// The receipts of the core calls made so far, bounded, for the tool's
2121 /// result metadata; `None` when it made none.
2122 pub fn receipts(&self) -> Option<Value> {
2123 self.snapshot(false)
2124 }
2125
2126 pub(super) fn seal_held_image(&self) -> Option<HeldImage> {
2127 let mut guard = self
2128 .invocation
2129 .held_image
2130 .lock()
2131 .unwrap_or_else(std::sync::PoisonError::into_inner);
2132 guard.1 = true;
2133 let held = guard.0.take().map(|(_, held)| held);
2134 self.invocation.cancel.cancel();
2135 held
2136 }
2137
2138 pub(super) fn record_service_act(&self, service: DshService, entry: Value) -> bool {
2139 self.invocation.push_act_record(service.name(), entry)
2140 }
2141
2142 pub fn seal_receipts(&self) -> Option<Value> {
2143 let _ = self.seal_held_image();
2144 self.snapshot(true)
2145 }
2146
2147 pub fn seal_plugin_change(&self) -> Option<PluginChangeMark> {
2148 let mut guard = self
2149 .invocation
2150 .plugin_change
2151 .lock()
2152 .unwrap_or_else(std::sync::PoisonError::into_inner);
2153 guard.1 = true;
2154 guard.0.clone()
2155 }
2156
2157 fn snapshot(&self, seal: bool) -> Option<Value> {
2158 let (total, acts) = {
2159 let mut guard = self
2160 .invocation
2161 .broker_acts
2162 .lock()
2163 .unwrap_or_else(std::sync::PoisonError::into_inner);
2164 if seal {
2165 guard.2 = true;
2166 }
2167 (guard.0, guard.1.clone())
2168 };
2169 if seal {
2170 self.invocation.cancel.cancel();
2171 }
2172 let mut receipts = self.invocation.calls.receipts_json(RECEIPTS_ATTACHED);
2173 if total > 0 {
2174 receipts["broker_acts"] = json!({ "total": total, "acts": acts });
2175 }
2176 (receipts["total"].as_u64().unwrap_or(0) > 0 || total > 0).then_some(receipts)
2177 }
2178 }
2179
2180 impl Drop for InvocationGuard {
2181 fn drop(&mut self) {
2182 self.core_calls.end(&self.ticket);
2183 }
2184 }
2185
2186 #[cfg(test)]
2187 mod seal_tests {
2188 use super::*;
2189 use crate::tools::codemode::{NestedCallRequest, NestedCallVerdict};
2190 use crate::tools::spec::ToolResult;
2191
2192 #[tokio::test]
2193 async fn a_successful_gate_answer_after_sealing_cannot_record_or_perform_an_act() {
2194 let owner = OwnerRef {
2195 plugin_id: "sealed-gate".into(),
2196 generation: 1,
2197 owner_token: "fixture".into(),
2198 };
2199 let caller = ExtensionCaller {
2200 origin: "extension:sealed-gate".into(),
2201 tool: "sealed_tool".into(),
2202 scope: "ext:sealed-gate@hash".into(),
2203 };
2204 let context = ToolContext::new(std::path::PathBuf::from("."));
2205 let (events, _events) = tokio::sync::mpsc::channel(8);
2206 let (gate, mut requests) = NestedCallGate::new(None, events, Duration::from_secs(5));
2207 let gate = gate.for_extension(caller.clone(), dsh_broker::BrokerActTool::all().to_vec());
2208 let calls = Arc::new(CoreCalls::default());
2209 let guard = calls
2210 .begin(
2211 HostCohort::reviewed(),
2212 1,
2213 &owner,
2214 "call",
2215 &caller,
2216 &context,
2217 &gate,
2218 )
2219 .expect("invocation");
2220 let broker = BrokerContext {
2221 invocation: Arc::clone(&guard.invocation),
2222 tool: Arc::new(context),
2223 service: DshService::Remote,
2224 cancel: CancellationToken::new(),
2225 broker_token: 0,
2226 };
2227 assert!(broker.record(json!({"method": "before", "outcome": "read"})));
2228 let performed = std::sync::atomic::AtomicBool::new(false);
2229 let (result, sealed) = tokio::join!(
2230 async {
2231 broker
2232 .act("write", BrokerEffect::Write, Some("late"))
2233 .await?;
2234 performed.store(true, Ordering::SeqCst);
2235 Ok::<(), BrokerRefusal>(())
2236 },
2237 async {
2238 let Some(NestedCallRequest::Tool(request)) = requests.recv().await else {
2239 panic!("the act must reach its gate before sealing");
2240 };
2241 let sealed = guard.seal_receipts().expect("the earlier record survives");
2242 assert!(!broker.cancel.is_cancelled());
2243 assert!(
2244 request
2245 .reply
2246 .send(NestedCallVerdict::Answered {
2247 result: ToolResult::success(request.input.to_string()),
2248 hook_context: None,
2249 })
2250 .is_ok(),
2251 "the gate response is still delivered"
2252 );
2253 sealed
2254 }
2255 );
2256 assert!(
2257 result.is_err(),
2258 "a successful late answer must be refused: {result:?}"
2259 );
2260 assert!(!performed.load(Ordering::SeqCst));
2261 assert!(!broker.record(json!({"method": "late", "outcome": "allowed"})));
2262 assert_eq!(sealed["broker_acts"]["total"], 1);
2263 assert_eq!(
2264 guard.receipts().unwrap()["broker_acts"],
2265 sealed["broker_acts"]
2266 );
2267 }
2268 }
2269
2269 lines RUST