diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 3d2d110..3cd970c 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -14,8 +14,8 @@ use crate::{ ConsumerPort, ConsumerRegistry, ControllerError, ControllerModels, ControllerPendingReason, ControllerRunner, ControllerWorkCustody, Cover, CoverBudget, CreateJurisdictionIntent, CreateWorldIntent, DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, - NarrativeRun, OperationalRun, PrincipalCommandIntent, PrincipalId, SeedOutcome, SeedPort, - Statement, SubjectKind, SubmissionDisposition, SubmitReceipt, TickMinutes, + NarrativeRun, OperationalRun, PrincipalCommandIntent, PrincipalId, SdkBinding, SeedOutcome, + SeedPort, Statement, SubjectKind, SubmissionDisposition, SubmitReceipt, TickMinutes, VaultEvidenceSource, WorldMailbox, WorldPhase, WorldSnapshot, derive_cover, open_controller_work, open_inference, }, @@ -434,7 +434,18 @@ fn open_controller( key_path, caller_runtime_id: runtime_id.to_owned(), }); - let inference = open_inference(connector, &models)?; + // Ghostlight reads no credential for this transport. The sidecar inherits + // the ambient Claude Code login; this process never names, copies, or logs + // it. + let sdk = std::env::var_os("GHOSTLIGHT_SDK_SIDECAR") + .map(PathBuf::from) + .map(|sidecar_entry| SdkBinding { + sidecar_entry, + caller_runtime_id: runtime_id.to_owned(), + model_prefix: std::env::var("GHOSTLIGHT_SDK_MODEL_PREFIX") + .unwrap_or_else(|_| "claude".into()), + }); + let inference = open_inference(connector, sdk, &models)?; let work = open_controller_work(service_root.join("controller-work.cc"))?; ControllerRunner::open(world.clone(), inference, work, models).map_err(Into::into) } @@ -2462,6 +2473,9 @@ mod tests { endpoint: SocketAddr, credential: PathBuf, runtime_id: String, + /// Present only when the smoke is run against the Claude SDK sidecar + /// instead of, or alongside, the connector. + sdk: Option, models: ControllerModels, } @@ -2492,6 +2506,7 @@ mod tests { endpoint: "127.0.0.1:9".parse().unwrap(), credential: controller_key.clone(), runtime_id: "ghostlight-runtime-test".into(), + sdk: None, models: ControllerModels { projector: "gpt-5.6-luna".into(), persona: "gpt-5.6-sol".into(), @@ -2504,8 +2519,9 @@ mod tests { Some(ConnectorBinding { endpoint: live.endpoint, key_path: live.credential.clone(), - caller_runtime_id: live.runtime_id, + caller_runtime_id: live.runtime_id.clone(), }), + live.sdk, &live.models, ) .unwrap(); @@ -3601,16 +3617,25 @@ mod tests { /// deficit per round, subjects qualified, and the prose a tick produces /// from a world that now has people in it. #[tokio::test] - #[ignore = "requires a running CodexConnector and a vault; see GHOSTLIGHT_SMOKE_* environment"] + #[ignore = "requires a vault plus either a running CodexConnector or a built Claude SDK sidecar with an ambient Claude Code login; see GHOSTLIGHT_SMOKE_* and GHOSTLIGHT_SDK_* environment"] async fn live_smoke_seeds_then_ticks_a_world_against_the_connector() { let _ = tracing_subscriber::fmt() .with_env_filter(EnvFilter::from_default_env()) .try_init(); let env = |name: &str| std::env::var(name).unwrap_or_else(|_| panic!("{name} is required")); + let runtime_id = env("GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID"); let live = LiveController { endpoint: env("GHOSTLIGHT_CONTROLLER_CONNECTOR").parse().unwrap(), credential: PathBuf::from(env("GHOSTLIGHT_CONTROLLER_CREDENTIAL")), - runtime_id: env("GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID"), + runtime_id: runtime_id.clone(), + sdk: std::env::var_os("GHOSTLIGHT_SDK_SIDECAR") + .map(PathBuf::from) + .map(|sidecar_entry| SdkBinding { + sidecar_entry, + caller_runtime_id: runtime_id, + model_prefix: std::env::var("GHOSTLIGHT_SDK_MODEL_PREFIX") + .unwrap_or_else(|_| "claude".into()), + }), models: ControllerModels { projector: env("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL"), persona: env("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL"), diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index c5380e0..618a557 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -10,6 +10,9 @@ use super::elaboration::{ ElaborationCheckpoint, ElaborationRunner, EvidenceSource, NullEvidenceSource, SeedCheckpoint, SeedRunner, valid_elaboration_progression, valid_seed_progression, }; +use super::sdk_inference::{ + ChildProcessLink, DEFAULT_SDK_MODEL_PREFIX, RoutedInferencePort, SdkBinding, SdkInferencePort, +}; use super::tool_schema; use crate::world::{ AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, Cell, CellId, CommandId, @@ -53,18 +56,18 @@ const MAX_CONNECTOR_FRAME_BYTES: usize = 1_052_672; /// How far ahead an invocation may claim to be valid. The connector refuses /// an expiry beyond its own skew bound as `Expired`, so this is the daemon's /// number, not ours; it is admission validity, not generation time. -const REQUEST_EXPIRY: Duration = Duration::from_secs(300); +pub(super) const REQUEST_EXPIRY: Duration = Duration::from_secs(300); /// One provider round's whole lifetime as seen from this side of the socket: /// the connector replies once at the end, so the read timeout bounds an /// entire generation, and a seed patch at medium effort was measured past /// five minutes. -const RESPONSE_TIMEOUT: Duration = Duration::from_secs(900); -const TOOL_STEP_BUDGET: usize = 4; +pub(super) const RESPONSE_TIMEOUT: Duration = Duration::from_secs(900); +pub(super) const TOOL_STEP_BUDGET: usize = 4; /// The grouped protocol asks for every call in one round, so this budget buys /// exactly one repair round after decode gaps are reported back. It deliberately /// does not scale with the cell: a cell that needs three rounds of repair is a /// cell that should have been smaller. -const CELL_TOOL_STEP_BUDGET: usize = 2; +pub(super) const CELL_TOOL_STEP_BUDGET: usize = 2; /// Separates a constituent handle from the tool it names. Attribution is /// carried by tool identity, never by a model-written argument. const HANDLE_SEPARATOR: &str = "__"; @@ -110,6 +113,14 @@ pub(crate) struct InferenceRequest { provider: CodexProviderRequest, } +impl InferenceRequest { + /// The model this request names, read before it is prepared. Routing is the + /// one decision that has to be made on an unprepared request. + pub(super) fn provider_model(&self) -> &str { + &self.provider.model + } +} + /// The exact connector invocation, including expiry and native provenance. /// Replaying this value may recover a completed connector response; rebuilding /// it under the same request ID would be a replay conflict. @@ -136,7 +147,10 @@ pub(crate) struct InferenceOutput { } impl InferenceOutput { - fn prose_only(self, purpose: InferencePurpose) -> Result<(String, String), ControllerError> { + pub(super) fn prose_only( + self, + purpose: InferencePurpose, + ) -> Result<(String, String), ControllerError> { let mut prose = String::new(); for event in self.events { match event { @@ -174,32 +188,32 @@ enum InferenceFaultDisposition { } impl InferenceFault { - fn new(detail: impl Into) -> Self { + pub(super) fn new(detail: impl Into) -> Self { Self { disposition: InferenceFaultDisposition::RecoveryRequired, detail: detail.into(), } } - fn retryable(detail: impl Into) -> Self { + pub(super) fn retryable(detail: impl Into) -> Self { Self { disposition: InferenceFaultDisposition::Retryable, detail: detail.into(), } } - fn integrity_violation(detail: impl Into) -> Self { + pub(super) fn integrity_violation(detail: impl Into) -> Self { Self { disposition: InferenceFaultDisposition::IntegrityViolation, detail: detail.into(), } } - fn recovery_required(&self) -> bool { + pub(super) fn recovery_required(&self) -> bool { self.disposition == InferenceFaultDisposition::RecoveryRequired } - fn integrity_was_violated(&self) -> bool { + pub(super) fn integrity_was_violated(&self) -> bool { self.disposition == InferenceFaultDisposition::IntegrityViolation } @@ -222,11 +236,36 @@ impl InferenceFault { } } +/// One lane's own answer to "what does this tool call return", lent to the +/// inference port for exactly one query. A port that runs the tool loop needs a +/// real result before the model will take another turn, and the only correct +/// result is the one the lane's evaluator will recompute when it re-derives the +/// finished round from `completed`. So this is not a second implementation: it +/// is the same fold, over the calls made so far, into fresh state. A port that +/// computed its own answer would put a string in front of the model that no +/// durable evidence records and no check can catch. +pub(crate) trait ToolResultOracle: Send { + /// The lane's remaining round budget, lowered to a transport's turn cap so + /// one query cannot exceed what the evaluator would have allowed. + fn remaining_rounds(&self) -> u32; + + /// The next call in this query. Errors are the lane's own hard contract + /// errors; the port aborts the query rather than inventing a string. + fn answer(&mut self, name: &str, arguments: &str) -> Result; +} + #[async_trait] pub(crate) trait InferencePort: Send + Sync { fn prepare(&self, request: InferenceRequest) -> Result; async fn infer(&self, request: PreparedInference) -> Result; + + /// Lends a lane's tool-result owner to the port for one query, keyed by the + /// prepared request's own id. The default ignores it: the connector returns + /// tool calls inert and the evaluator computes every result at + /// re-derivation, so only a port that runs the tool loop needs one. + fn lend_tool_results(&self, _prepared: &PreparedInference, _oracle: Box) { + } } /// Builds a `PreparedInference` outside the real CodexConnector wiring. Exists @@ -434,7 +473,7 @@ impl InferencePort for CodexConnectorInferencePort { } } -fn unix_ms() -> Result { +pub(super) fn unix_ms() -> Result { let millis = SystemTime::now() .duration_since(UNIX_EPOCH) .map_err(|error| InferenceFault::new(error.to_string()))? @@ -2061,7 +2100,10 @@ pub(crate) struct ControllerModels { pub(crate) operational_agent: String, /// The authoring lane's model. The existing config shape already gates /// cognition by model name, so the driver starts on this and no mode flag - /// is added. + /// is added. The model name also selects the transport: a + /// `GHOSTLIGHT_SDK_MODEL_PREFIX`-prefixed model reaches the SDK sidecar and + /// anything else reaches the connector, which is why there is still no mode + /// flag. pub(crate) elaborator: String, } @@ -2094,6 +2136,8 @@ pub(crate) enum ControllerOpenError { WorkStore(String), #[error("no configured inference backend claims the controller model `{model}`")] UnroutableModel { model: String }, + #[error("the SDK sidecar entry `{path}` is not a file")] + SdkSidecarMissing { path: String }, } /// Everything the CodexConnector transport needs to open, gathered so @@ -2108,6 +2152,7 @@ pub(crate) struct ConnectorBinding { /// backend claims fails here, at open, rather than at its first tick. pub(crate) fn open_inference( connector: Option, + sdk: Option, models: &ControllerModels, ) -> Result, ControllerOpenError> { let connector: Option> = match connector { @@ -2118,12 +2163,31 @@ pub(crate) fn open_inference( )?)), None => None, }; - let Some(connector) = connector else { - return Err(ControllerOpenError::UnroutableModel { - model: models.projector.clone(), - }); + let mut sdk_model_prefix = DEFAULT_SDK_MODEL_PREFIX.to_owned(); + let sdk: Option> = match sdk { + Some(binding) => { + if !binding.sidecar_entry.is_file() { + return Err(ControllerOpenError::SdkSidecarMissing { + path: binding.sidecar_entry.display().to_string(), + }); + } + sdk_model_prefix = binding.model_prefix; + Some(Arc::new(SdkInferencePort::new( + Arc::new(ChildProcessLink::new(binding.sidecar_entry)), + binding.caller_runtime_id, + ))) + } + None => None, }; - Ok(connector) + let routed = RoutedInferencePort::new(connector, sdk, sdk_model_prefix); + for model in models.each() { + if routed.route(model).is_none() { + return Err(ControllerOpenError::UnroutableModel { + model: model.clone(), + }); + } + } + Ok(Arc::new(routed)) } impl From for ControllerOpenError { @@ -2728,6 +2792,10 @@ impl ControllerRunner { }; self.ensure_scope_unchanged(&opportunity).await?; let model = invocation.invocation.request.model.clone(); + self.inference.lend_tool_results( + &invocation, + Box::new(OperationalOracle::new(&granted, &completed)), + ); let output = match self.infer(invocation).await { Ok(output) => output, Err(error) => match inference_pending_reason(&error) { @@ -3027,6 +3095,10 @@ impl ControllerRunner { )); }; let model = invocation.invocation.request.model.clone(); + self.inference.lend_tool_results( + &invocation, + Box::new(GroupedOracle::new(&constituents, &completed)), + ); let output = match self.infer(invocation).await { Ok(output) => output, Err(error) => match inference_pending_reason(&error) { @@ -3440,6 +3512,10 @@ impl ControllerRunner { )); }; let model = invocation.invocation.request.model.clone(); + self.inference.lend_tool_results( + &invocation, + Box::new(InterpreterOracle::new(&turn, &completed)), + ); let output = match self.infer(invocation).await { Ok(output) => output, Err(error) => match inference_pending_reason(&error) { @@ -4584,6 +4660,51 @@ pub(super) fn interpreter_tool_result( } } +/// Replays every completed round's calls into fresh state, then answers this +/// query's calls in order. Construction is the replay: after it, `answer` is +/// exactly the evaluator's next step. +pub(super) struct InterpreterOracle { + source: PersonaTurn, + fold: InterpreterFold, + remaining: u32, +} + +impl InterpreterOracle { + pub(super) fn new(source: &PersonaTurn, completed: &[InferenceOutput]) -> Self { + let mut fold = InterpreterFold::new(source.clone()); + for output in completed { + for event in &output.events { + if let InferenceEvent::ToolCall { + name, arguments, .. + } = event + { + let _ = interpreter_tool_result(source, &mut fold, name, arguments); + } + } + } + Self { + source: source.clone(), + fold, + remaining: TOOL_STEP_BUDGET.saturating_sub(completed.len()) as u32, + } + } +} + +impl ToolResultOracle for InterpreterOracle { + fn remaining_rounds(&self) -> u32 { + self.remaining + } + + fn answer(&mut self, name: &str, arguments: &str) -> Result { + Ok(interpreter_tool_result( + &self.source, + &mut self.fold, + name, + arguments, + )) + } +} + fn evaluate_interpreter_loop( source: &PersonaTurn, prompt: &str, @@ -4849,6 +4970,45 @@ pub(super) fn grouped_tool_result( }) } +/// The grouped lane's replay-then-answer oracle. Same shape as the +/// interpreter's, over `CELL_TOOL_STEP_BUDGET`. +pub(super) struct GroupedOracle { + constituents: Vec, + fold: GroupedFold, + remaining: u32, +} + +impl GroupedOracle { + pub(super) fn new(constituents: &[ConstituentWork], completed: &[InferenceOutput]) -> Self { + let mut fold = GroupedFold::new(); + for output in completed { + for event in &output.events { + if let InferenceEvent::ToolCall { + name, arguments, .. + } = event + { + let _ = grouped_tool_result(constituents, &mut fold, name, arguments); + } + } + } + Self { + constituents: constituents.to_vec(), + fold, + remaining: CELL_TOOL_STEP_BUDGET.saturating_sub(completed.len()) as u32, + } + } +} + +impl ToolResultOracle for GroupedOracle { + fn remaining_rounds(&self) -> u32 { + self.remaining + } + + fn answer(&mut self, name: &str, arguments: &str) -> Result { + grouped_tool_result(&self.constituents, &mut self.fold, name, arguments) + } +} + fn evaluate_grouped_loop( prompt: &str, constituents: &[ConstituentWork], @@ -5082,6 +5242,48 @@ pub(super) fn operational_tool_result( }) } +/// The operational lane's replay-then-answer oracle. `begin_round` runs at +/// every replayed round boundary and once more after the replay, so the live +/// query's first call sees `terminal_choice: None` exactly as round *n* does. +pub(super) struct OperationalOracle { + granted: Vec, + fold: OperationalFold, + remaining: u32, +} + +impl OperationalOracle { + pub(super) fn new(granted: &[AffordanceSnapshot], completed: &[InferenceOutput]) -> Self { + let mut fold = OperationalFold::new(); + for output in completed { + fold.begin_round(); + for event in &output.events { + if let InferenceEvent::ToolCall { + name, arguments, .. + } = event + { + let _ = operational_tool_result(granted, &mut fold, name, arguments); + } + } + } + fold.begin_round(); + Self { + granted: granted.to_vec(), + fold, + remaining: TOOL_STEP_BUDGET.saturating_sub(completed.len()) as u32, + } + } +} + +impl ToolResultOracle for OperationalOracle { + fn remaining_rounds(&self) -> u32 { + self.remaining + } + + fn answer(&mut self, name: &str, arguments: &str) -> Result { + operational_tool_result(&self.granted, &mut self.fold, name, arguments) + } +} + fn evaluate_operational_loop( prompt: &str, granted: &[AffordanceSnapshot], @@ -5406,7 +5608,10 @@ fn interpreter_tools() -> Vec { /// `prefix` is empty on the detail path, so its schemas stay byte-identical, /// and `c__` on the grouped path, where the tool name is what attributes /// a proposal to one constituent. One owner, two spellings of the same catalog. -fn catalog_tools(prefix: &str, granted: &[AffordanceSnapshot]) -> Vec { +pub(super) fn catalog_tools( + prefix: &str, + granted: &[AffordanceSnapshot], +) -> Vec { let mut tools: Vec = granted .iter() .map(|entry| { @@ -6683,6 +6888,207 @@ mod tests { ) } + /// A tool-call event as the SDK port would report one. + fn oracle_call(call_id: &str, name: &str, arguments: &str) -> InferenceEvent { + InferenceEvent::ToolCall { + call_id: call_id.into(), + name: name.into(), + arguments: arguments.into(), + } + } + + fn oracle_round(calls: &[(&str, &str, &str)], receipt: &str) -> InferenceOutput { + InferenceOutput { + events: calls + .iter() + .map(|(id, name, arguments)| oracle_call(id, name, arguments)) + .collect(), + receipt_digest: format!("sha256:{receipt}"), + } + } + + fn tool_results(conversation: &[CodexInputItem]) -> Vec { + conversation + .iter() + .filter_map(|item| match item { + CodexInputItem::ToolResult { output, .. } => Some(output.clone()), + _ => None, + }) + .collect() + } + + /// Spec test 1, interpreter lane. The string the oracle hands the model is + /// the string the evaluator recomputes for the same call, in order. + #[test] + fn the_interpreter_oracle_answers_what_its_evaluator_recomputes() { + let opportunity = fixture_opportunity(ControllerMode::NarrativePersona); + let source = "I say, \"The rain has teeth tonight.\""; + let turn = fixture_persona_turn(&opportunity, source); + let speech = "The rain has teeth tonight."; + let start = source.find(speech).unwrap(); + let span = json!({ + "source_start_byte": start, + "source_end_byte": start + speech.len(), + }) + .to_string(); + let calls: Vec<(&str, &str, &str)> = vec![ + ("call-0", INTERPRETER_SPEAK_TOOL, span.as_str()), + // A second speak, so `captured_speech` is exercised. + ("call-1", INTERPRETER_SPEAK_TOOL, span.as_str()), + ("call-2", INTERPRETER_RECORD_GAP_TOOL, "not json at all"), + ("call-3", "speek", "{}"), + ]; + let mut oracle = InterpreterOracle::new(&turn, &[]); + let answers: Vec = calls + .iter() + .map(|(_, name, arguments)| oracle.answer(name, arguments).unwrap()) + .collect(); + let output = oracle_round(&calls, "interpreter-oracle"); + let InterpreterLoopEvaluation::Continue { conversation } = + evaluate_interpreter_loop(&turn, "Translate the prose.", &[output]).unwrap() + else { + panic!("a non-terminal interpreter round finalized") + }; + assert_eq!(answers, tool_results(&conversation)); + } + + /// Spec test 1, operational lane, plus spec test 2's replay: an oracle + /// seeded from a completed round continues the same fold, and its + /// `terminal_choice` resets at the round boundary while `needs` does not. + #[test] + fn the_operational_oracle_answers_what_its_evaluator_recomputes() { + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let granted = vec![speak_snapshot(opportunity.affordance_ids[0])]; + let speak = granted[0].entry.kind.0.clone(); + let first: Vec<(&str, &str, &str)> = vec![ + ("call-0", RECORD_NEED_TOOL, r#"{"detail":"no route"}"#), + ("call-1", RECORD_NEED_TOOL, "not json at all"), + // A granted tool whose arguments do not decode: a need, not a + // terminal choice, so the round stays open. + ("call-2", speak.as_str(), "not json at all"), + ("call-3", "speek", "{}"), + ]; + let mut oracle = OperationalOracle::new(&granted, &[]); + let answers: Vec = first + .iter() + .map(|(_, name, arguments)| oracle.answer(name, arguments).unwrap()) + .collect(); + let round_zero = oracle_round(&first, "operational-oracle"); + let OperationalLoopEvaluation::Continue { conversation } = + evaluate_operational_loop("Hold the bridge.", &granted, &[round_zero.clone()]).unwrap() + else { + panic!("a non-terminal operational round finalized") + }; + assert_eq!(answers, tool_results(&conversation)); + + // Round one, from an oracle constructed over round zero. + let second: Vec<(&str, &str, &str)> = vec![ + ("call-4", RECORD_NEED_TOOL, r#"{"detail":"still no route"}"#), + ("call-5", "speek", "{}"), + ]; + let mut resumed = OperationalOracle::new(&granted, &[round_zero.clone()]); + let resumed_answers: Vec = second + .iter() + .map(|(_, name, arguments)| resumed.answer(name, arguments).unwrap()) + .collect(); + let round_one = oracle_round(&second, "operational-oracle-one"); + let OperationalLoopEvaluation::Continue { conversation } = + evaluate_operational_loop("Hold the bridge.", &granted, &[round_zero, round_one]) + .unwrap() + else { + panic!("a non-terminal operational round finalized") + }; + assert_eq!( + resumed_answers, + tool_results(&conversation)[first.len()..].to_vec() + ); + + // The one string a terminal choice owns, and the one the lane has no + // string for at all. + let mut terminal = OperationalOracle::new(&granted, &[]); + let speech = json!({ "text": "Hold the bridge." }).to_string(); + assert_eq!( + terminal.answer(&speak, &speech).unwrap(), + "invocation captured" + ); + assert_eq!( + terminal.answer(&speak, &speech).unwrap(), + "one terminal choice is already captured" + ); + assert!(matches!( + terminal.answer(FINISH_WITHOUT_PROPOSAL_TOOL, "{}"), + Err(ControllerError::ProviderContract { .. }) + )); + } + + /// Spec test 1, grouped lane. Two handles, and a tool that names none. + #[test] + fn the_grouped_oracle_answers_what_its_evaluator_recomputes() { + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let constituents = vec![ + ConstituentWork { + subject: opportunity.scope.subject_id, + opportunity: opportunity.clone(), + granted: vec![speak_snapshot(opportunity.affordance_ids[0])], + command_id: CommandId::new(), + }, + ConstituentWork { + subject: opportunity.scope.subject_id, + opportunity: opportunity.clone(), + granted: vec![speak_snapshot(opportunity.affordance_ids[0])], + command_id: CommandId::new(), + }, + ]; + let speak = constituents[0].granted[0].entry.kind.0.clone(); + let handle_one = format!("c0__{speak}"); + let calls: Vec<(&str, &str, &str)> = vec![ + ("call-0", "c99__carry", "{}"), + ("call-1", "c0__record_need", r#"{"detail":"no route"}"#), + ("call-2", "c1__record_need", "not json at all"), + ("call-3", handle_one.as_str(), "not json at all"), + ("call-4", "c1__notgranted", "{}"), + ]; + let mut oracle = GroupedOracle::new(&constituents, &[]); + let answers: Vec = calls + .iter() + .map(|(_, name, arguments)| oracle.answer(name, arguments).unwrap()) + .collect(); + let output = oracle_round(&calls, "grouped-oracle"); + let GroupedLoopEvaluation::Continue { conversation } = + evaluate_grouped_loop("Decide together.", &constituents, &[output]).unwrap() + else { + panic!("a non-terminal grouped round finalized") + }; + assert_eq!(answers, tool_results(&conversation)); + } + + /// Spec test 4, and the reachable half of spec test 3: two ports that + /// prepare under the same identity produce the same `PreparedInference`, + /// and it satisfies the checkpoint's own identity check. + #[test] + fn both_ports_prepare_the_same_invocation() { + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let granted = vec![speak_snapshot(opportunity.affordance_ids[0])]; + let command_id = CommandId::new(); + let build = || { + operational_request( + command_id, + 0, + "claude-opus-5", + &granted, + vec![CodexInputItem::UserText { + text: "Hold the bridge.".into(), + }], + ) + .unwrap() + }; + let expiry = 4_102_444_800_000; + let connector_side = prepare_invocation("ghostlight-runtime", expiry, build()).unwrap(); + let sdk_side = prepare_invocation("ghostlight-runtime", expiry, build()).unwrap(); + assert_eq!(connector_side, sdk_side); + assert!(prepared_matches_request(&sdk_side, &build(), command_id, 0)); + } + fn narrative_interpreter_in_flight( command_id: CommandId, opportunity: &DecisionOpportunity, @@ -7537,6 +7943,7 @@ mod tests { key_path: connector_credential.into(), caller_runtime_id: runtime_id, }), + None, &models, ) .unwrap(); diff --git a/crates/ghostlight-dungeon/src/world/elaboration.rs b/crates/ghostlight-dungeon/src/world/elaboration.rs index 254e09f..a084581 100644 --- a/crates/ghostlight-dungeon/src/world/elaboration.rs +++ b/crates/ghostlight-dungeon/src/world/elaboration.rs @@ -13,8 +13,8 @@ use super::controllers::{ ControllerError, ControllerNeed, ControllerWork, ControllerWorkLookup, ControllerWorkStore, ControllerWorkWrite, InferenceEvent, InferenceOutput, InferencePort, InferencePurpose, - InferenceRequest, PreparedInference, RequestShape, canonical_model, prepared_matches_request, - tool_decode_need, tool_request, + InferenceRequest, PreparedInference, RequestShape, ToolResultOracle, canonical_model, + prepared_matches_request, tool_decode_need, tool_request, }; #[cfg(test)] use super::patch::RECORD_GAP_PATCH_TOOL; @@ -41,11 +41,11 @@ use uuid::Uuid; /// The elaborator wants many tool calls inside one round and several rounds for /// repair, where the operational agent wants one terminal choice. /// `TOOL_STEP_BUDGET` is left alone for the lane it belongs to. -const ELABORATION_ROUND_BUDGET: usize = 6; +pub(super) const ELABORATION_ROUND_BUDGET: usize = 6; /// A seed session authors a whole shortfall, not one answer: several subjects, /// each with a grant, a goal, and an obligation, then a submit. Measured on /// the road at one declaration per response, six rounds discarded everything. -const SEED_ROUND_BUDGET: usize = 24; +pub(super) const SEED_ROUND_BUDGET: usize = 24; const ELABORATION_NAMESPACE: &str = "ghostlight.command.elaboration.v1"; @@ -414,6 +414,10 @@ impl ElaborationRunner { invocation: invocation.clone(), }) .await?; + self.inference.lend_tool_results( + &invocation, + Box::new(ElaborationOracle::new(&completed, ELABORATION_ROUND_BUDGET)), + ); let output = self.inference .infer(invocation.clone()) @@ -926,6 +930,65 @@ pub(super) fn evaluate_elaboration_loop( Ok(ElaborationLoopEvaluation::Continue { conversation }) } +/// The authoring lanes' replay-then-answer oracle. The budget is an argument +/// because elaboration and seed share one `InferencePurpose` and differ only in +/// how many rounds they may spend, which is why the cap rides here and not on +/// the purpose. +pub(super) struct ElaborationOracle { + draft: WorldPatch, + gaps: Vec, + submitted: bool, + remaining: u32, +} + +impl ElaborationOracle { + pub(super) fn new(completed: &[InferenceOutput], budget: usize) -> Self { + let mut oracle = Self { + draft: WorldPatch { + declarations: Vec::new(), + operations: Vec::new(), + evidence: Vec::new(), + }, + gaps: Vec::new(), + submitted: false, + remaining: budget.saturating_sub(completed.len()) as u32, + }; + for output in completed { + for event in &output.events { + if let InferenceEvent::ToolCall { + name, arguments, .. + } = event + { + let _ = apply_tool_call( + name, + arguments, + &mut oracle.draft, + &mut oracle.gaps, + &mut oracle.submitted, + ); + } + } + } + oracle + } +} + +impl ToolResultOracle for ElaborationOracle { + fn remaining_rounds(&self) -> u32 { + self.remaining + } + + fn answer(&mut self, name: &str, arguments: &str) -> Result { + Ok(apply_tool_call( + name, + arguments, + &mut self.draft, + &mut self.gaps, + &mut self.submitted, + )) + } +} + fn apply_tool_call( name: &str, arguments: &str, @@ -1442,6 +1505,10 @@ impl SeedRunner { invocation: invocation.clone(), }) .await?; + self.inference.lend_tool_results( + &invocation, + Box::new(ElaborationOracle::new(&completed, SEED_ROUND_BUDGET)), + ); let output = self.inference.infer(invocation).await.map_err(|source| { ControllerError::Inference { purpose: InferencePurpose::Elaboration, diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index be26b3c..7f89725 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -14,6 +14,7 @@ mod elaboration; mod journal; mod mailbox; mod patch; +mod sdk_inference; mod tool_schema; mod vault; @@ -54,6 +55,7 @@ use patch::{ }; #[cfg(test)] pub(crate) use patch::{AuthorityGrantRef, AuthorityTargetRef}; +pub(crate) use sdk_inference::SdkBinding; pub(crate) use vault::VaultEvidenceSource; // Test-only narrowing of the controller organ's inference and work-store // seams, so `runtime`'s own spec tests can drive `ControllerRunner` over a diff --git a/crates/ghostlight-dungeon/src/world/sdk_inference.rs b/crates/ghostlight-dungeon/src/world/sdk_inference.rs new file mode 100644 index 0000000..4ba19da --- /dev/null +++ b/crates/ghostlight-dungeon/src/world/sdk_inference.rs @@ -0,0 +1,1470 @@ +//! The Claude Agent SDK behind Ghostlight's inference seam, and the rule that +//! decides which lane reaches it. +//! +//! This module owns one authority: the protocol that drives a Node sidecar +//! through one SDK query and lowers the result back into the same +//! `InferenceOutput` the connector port produces. It builds no request shape of +//! its own, computes no tool result, and holds no credential. + +use super::controllers::{ + InferenceEvent, InferenceFault, InferenceOutput, InferencePort, InferenceRequest, + PreparedInference, REQUEST_EXPIRY, RESPONSE_TIMEOUT, ToolResultOracle, prepare_invocation, + unix_ms, +}; +use async_trait::async_trait; +use codex_connector::CodexInputItem; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::process::Stdio; +use std::sync::{Arc, Mutex}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::sync::Mutex as AsyncMutex; + +/// One frame on the sidecar pipe: a 4-byte big-endian length prefix followed by +/// `rmp_serde::to_vec_named` bytes, so every variant is a string-keyed map on +/// the TypeScript side. The cap is the connector's own frame cap, because the +/// largest request either transport carries is the same grouped cell. +pub(super) const MAX_SIDECAR_FRAME_BYTES: usize = 1_052_672; + +/// The reasoning-effort values the SDK's own `EffortLevel` admits. A request +/// carrying anything else is refused rather than silently mis-mapped. +const SDK_EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"]; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(super) enum SidecarFrame { + Query { + query_id: u64, + model: String, + instructions: String, + prompt: String, + transcript: Vec, + tools: Vec, + effort: Option, + max_output_tokens: Option, + turn_cap: u32, + }, + ToolCall { + query_id: u64, + call_id: String, + name: String, + arguments: String, + }, + ToolResult { + query_id: u64, + call_id: String, + output: String, + }, + Output { + query_id: u64, + events: Vec, + receipt: SdkResultMaterial, + }, + Fault { + query_id: u64, + reason: SidecarFaultReason, + detail: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct SidecarTool { + pub(super) name: String, + pub(super) description: String, + pub(super) parameters_json: String, +} + +/// One block of one assistant message, in order. `dispatched` is false only for +/// a `tool_use` block naming a tool the sidecar did not register — the harness +/// answered that one itself and the oracle never saw it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(super) enum SidecarEvent { + Text { + text: String, + }, + ToolCall { + call_id: String, + name: String, + arguments: String, + dispatched: bool, + }, +} + +/// What the sidecar reports about the SDK session that produced one output. +/// Every field here is the sidecar's; the identity half of the receipt is +/// filled in by this port from the invocation it already holds. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct SdkResultMaterial { + pub(super) session_id: String, + pub(super) result_uuid: String, + pub(super) subtype: String, + pub(super) stop_reason: Option, + pub(super) num_turns: u32, + pub(super) assistant_message_uuids: Vec, + pub(super) assistant_request_ids: Vec, + pub(super) usage: Vec, + /// A decimal string, because the receipt derives `Eq` and because this is a + /// client-side estimate rather than a billing statement. + pub(super) total_cost_usd_estimate: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub(super) struct SdkModelUsage { + pub(super) model: String, + pub(super) input_tokens: u64, + pub(super) output_tokens: u64, + pub(super) cache_read_input_tokens: u64, + pub(super) cache_creation_input_tokens: u64, +} + +/// The failures the sidecar is allowed to name. It reports a reason; this +/// module assigns the disposition, so TypeScript can never quarantine the +/// world's cognition by naming an integrity violation directly. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum SidecarFaultReason { + RateLimited, + Overloaded, + ServerError, + ApiTimeout, + AuthenticationFailed, + OrgNotAllowed, + BillingError, + InvalidRequest, + ModelNotFound, + MaxOutputTokens, + MaxBudgetUsd, + ExecutionError, + Unknown, + ProtocolViolation, + ToolRegistrationFailed, + TurnCapRefused, +} + +impl SidecarFaultReason { + fn into_fault(self, detail: String) -> InferenceFault { + let detail = format!("SDK sidecar reported {self:?}: {detail}"); + match self { + Self::RateLimited | Self::Overloaded | Self::ServerError | Self::ApiTimeout => { + InferenceFault::retryable(detail) + } + Self::AuthenticationFailed + | Self::OrgNotAllowed + | Self::BillingError + | Self::InvalidRequest + | Self::ModelNotFound + | Self::MaxOutputTokens + | Self::MaxBudgetUsd + | Self::ExecutionError + | Self::Unknown => InferenceFault::new(detail), + Self::ProtocolViolation | Self::ToolRegistrationFailed | Self::TurnCapRefused => { + InferenceFault::integrity_violation(detail) + } + } + } +} + +#[derive(Debug)] +pub(super) enum SidecarLinkError { + /// The pipe reached EOF or the child exited. Never a partial output. + Closed, + /// A length prefix over the cap, a truncated body, or an undecodable one. + Codec(String), + /// The child could not be started. The entry file existed at open, so this + /// is an environment fault an operator must fix. + Spawn(String), +} + +/// The child-process seam, so the protocol driver is testable without Node, a +/// credential, or a process. `ChildProcessLink` is production; the tests drive a +/// scripted in-process link over the same trait. +#[async_trait] +pub(super) trait SidecarLink: Send + Sync { + async fn send(&self, frame: SidecarFrame) -> Result<(), SidecarLinkError>; + async fn recv(&self) -> Result; + /// Kills and respawns the child, so no query inherits another query's + /// half-read pipe. Called by the driver on every fault, and only there. + async fn restart(&self) -> Result<(), SidecarLinkError>; +} + +/// Reads one length-prefixed MessagePack frame. Free so the codec is testable +/// over a `tokio::io::duplex` pair without a process. +pub(super) async fn read_frame( + reader: &mut R, +) -> Result { + let mut prefix = [0_u8; 4]; + reader + .read_exact(&mut prefix) + .await + .map_err(|_| SidecarLinkError::Closed)?; + let length = u32::from_be_bytes(prefix) as usize; + if length == 0 || length > MAX_SIDECAR_FRAME_BYTES { + return Err(SidecarLinkError::Codec(format!( + "sidecar frame length {length} is outside 1..={MAX_SIDECAR_FRAME_BYTES}" + ))); + } + let mut body = vec![0_u8; length]; + reader + .read_exact(&mut body) + .await + .map_err(|error| SidecarLinkError::Codec(error.to_string()))?; + rmp_serde::from_slice(&body).map_err(|error| SidecarLinkError::Codec(error.to_string())) +} + +fn encode_frame(frame: &SidecarFrame) -> Result, SidecarLinkError> { + let body = rmp_serde::to_vec_named(frame) + .map_err(|error| SidecarLinkError::Codec(error.to_string()))?; + if body.len() > MAX_SIDECAR_FRAME_BYTES { + return Err(SidecarLinkError::Codec(format!( + "sidecar frame of {} bytes exceeds {MAX_SIDECAR_FRAME_BYTES}", + body.len() + ))); + } + let mut framed = Vec::with_capacity(body.len() + 4); + framed.extend_from_slice(&(body.len() as u32).to_be_bytes()); + framed.extend_from_slice(&body); + Ok(framed) +} + +struct SidecarChild { + child: Child, + stdin: ChildStdin, + stdout: ChildStdout, +} + +/// One persistent `node ` child, respawned on fault. `stderr` is +/// inherited: the sidecar logs its own faults there and never a prompt, a tool +/// argument, or a tool result. +pub(super) struct ChildProcessLink { + entry: PathBuf, + child: AsyncMutex>, +} + +impl ChildProcessLink { + pub(super) fn new(entry: PathBuf) -> Self { + Self { + entry, + child: AsyncMutex::new(None), + } + } + + fn spawn(&self) -> Result { + let mut child = Command::new("node") + .arg(&self.entry) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .map_err(|error| SidecarLinkError::Spawn(error.to_string()))?; + let stdin = child + .stdin + .take() + .ok_or_else(|| SidecarLinkError::Spawn("sidecar stdin was not piped".into()))?; + let stdout = child + .stdout + .take() + .ok_or_else(|| SidecarLinkError::Spawn("sidecar stdout was not piped".into()))?; + Ok(SidecarChild { + child, + stdin, + stdout, + }) + } +} + +#[async_trait] +impl SidecarLink for ChildProcessLink { + async fn send(&self, frame: SidecarFrame) -> Result<(), SidecarLinkError> { + let bytes = encode_frame(&frame)?; + let mut held = self.child.lock().await; + if held.is_none() { + *held = Some(self.spawn()?); + } + let child = held.as_mut().expect("the child was just ensured"); + child + .stdin + .write_all(&bytes) + .await + .map_err(|_| SidecarLinkError::Closed)?; + child + .stdin + .flush() + .await + .map_err(|_| SidecarLinkError::Closed) + } + + async fn recv(&self) -> Result { + let mut held = self.child.lock().await; + let Some(child) = held.as_mut() else { + return Err(SidecarLinkError::Closed); + }; + // The driver's only clock is the connector's own response timeout: a + // seed patch at medium effort was measured past five minutes, so no + // tighter deadline may be imposed here. + match tokio::time::timeout(RESPONSE_TIMEOUT, read_frame(&mut child.stdout)).await { + Ok(frame) => frame, + Err(_) => Err(SidecarLinkError::Closed), + } + } + + async fn restart(&self) -> Result<(), SidecarLinkError> { + let mut held = self.child.lock().await; + if let Some(mut child) = held.take() { + let _ = child.child.start_kill(); + let _ = child.child.wait().await; + } + Ok(()) + } +} + +/// What the SDK reported, bound to the identity Ghostlight computed. The +/// identity half is filled here from the invocation, so the sidecar cannot +/// assert a request it was not given; the SDK half is the session and the +/// messages that produced this output. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct SdkInferenceReceipt { + schema_id: String, + request_id: String, + conversation_id: String, + caller_runtime_id: String, + native_request_sha256: [u8; 32], + provider_request_sha256: [u8; 32], + model: String, + session_id: String, + result_uuid: String, + subtype: String, + stop_reason: Option, + num_turns: u32, + assistant_message_uuids: Vec, + assistant_request_ids: Vec, + usage: Vec, + total_cost_usd_estimate: String, +} + +const SDK_RECEIPT_SCHEMA: &str = "ghostlight.sdk_inference_receipt.v1"; + +/// The model-name prefix that names the SDK transport when nothing configures +/// one. It holds even with no SDK port built, so a `claude-`prefixed lane on a +/// connector-only deployment is refused at open instead of quietly reaching the +/// wrong backend. +pub(super) const DEFAULT_SDK_MODEL_PREFIX: &str = "claude"; + +/// Everything the SDK sidecar needs to open, gathered so `open_inference` takes +/// a binding rather than reading the environment itself. +pub(crate) struct SdkBinding { + pub(crate) sidecar_entry: PathBuf, + pub(crate) caller_runtime_id: String, + pub(crate) model_prefix: String, +} + +/// The Claude Agent SDK behind Ghostlight's inference seam, through a Node +/// sidecar this port owns. It is a stopgap for one reason — it borrows the +/// Claude Code subscription credential, which Ghostlight never sees — and it +/// carries two liabilities that a Messages-API port would not: +/// +/// The receipt is the SDK's message, not wire bytes. Its identity half is +/// computed here from the invocation, but its provenance half is a session id +/// and message uuids reported by a child process this port spawned. It attests +/// that this exact request produced this exact SDK session; it does not attest +/// against a party Ghostlight does not control, which is what the connector's +/// receipt does. `PersonaTurnBinding` keeps its meaning within that limit: the +/// two digests it binds still differ per round and still cannot be swapped. +/// +/// A prior round's conversation reaches the model as prose. The SDK owns the +/// assistant side of its transcript, so typed `tool_call`/`tool_result` turns +/// cannot be replayed into it. `parallel_tool_calls` and `tool_choice` have no +/// SDK counterpart and are not sent; they still ride in the request and into +/// every digest. +/// +/// When an `ANTHROPIC_API_KEY` and a budget exist, a Messages-API port is a +/// closer structural match to `InferencePort` than the SDK is — inert +/// `tool_use` blocks, a caller-appended `tool_result`, a real request id, real +/// concurrency, no subprocess — and this port is deleted rather than extended. +pub(super) struct SdkInferencePort { + link: Arc, + caller_runtime_id: String, + /// Holding this is the one-query-in-flight permit and the source of query + /// ids. One child, one query: the pipe carries a single query's tool-call + /// rendezvous, and every SDK query spawns its own Claude Code subprocess + /// regardless, so a second in-flight query buys a second subprocess rather + /// than a shared connection. + gate: AsyncMutex, + oracles: Mutex>>, +} + +impl SdkInferencePort { + pub(super) fn new(link: Arc, caller_runtime_id: impl Into) -> Self { + Self { + link, + caller_runtime_id: caller_runtime_id.into(), + gate: AsyncMutex::new(0), + oracles: Mutex::new(BTreeMap::new()), + } + } + + fn take_oracle(&self, request_id: &str) -> Option> { + self.oracles + .lock() + .expect("the oracle map is never poisoned") + .remove(request_id) + } + + async fn run_query( + &self, + prepared: PreparedInference, + mut oracle: Option>, + turn_cap: u32, + ) -> Result { + let mut gate = self.gate.lock().await; + *gate = gate.wrapping_add(1); + let query_id = *gate; + let frame = lower_query(query_id, &prepared, turn_cap)?; + if let Err(error) = self.link.send(frame).await { + let _ = self.link.restart().await; + return Err(link_fault(error)); + } + let mut answered: Vec<(String, String, String)> = Vec::new(); + loop { + let frame = match self.link.recv().await { + Ok(frame) => frame, + Err(error) => { + let _ = self.link.restart().await; + return Err(link_fault(error)); + } + }; + match frame { + SidecarFrame::ToolCall { + query_id: seen, + call_id, + name, + arguments, + } if seen == query_id => { + let Some(oracle) = oracle.as_mut() else { + let _ = self.link.restart().await; + return Err(InferenceFault::integrity_violation( + "the SDK sidecar issued a tool call for a request that carries no tools", + )); + }; + match oracle.answer(&name, &arguments) { + Ok(output) => { + answered.push((call_id.clone(), name, arguments)); + if let Err(error) = self + .link + .send(SidecarFrame::ToolResult { + query_id, + call_id, + output, + }) + .await + { + let _ = self.link.restart().await; + return Err(link_fault(error)); + } + } + Err(error) => { + let _ = self.link.restart().await; + return Err(InferenceFault::new(error.to_string())); + } + } + } + SidecarFrame::Output { + query_id: seen, + events, + receipt, + } if seen == query_id => { + return assemble_output(&prepared, events, receipt, &answered); + } + SidecarFrame::Fault { + query_id: seen, + reason, + detail, + } if seen == query_id => { + let _ = self.link.restart().await; + return Err(reason.into_fault(detail)); + } + _ => { + let _ = self.link.restart().await; + return Err(InferenceFault::integrity_violation( + "the SDK sidecar sent a frame this query did not ask for", + )); + } + } + } + } +} + +fn link_fault(error: SidecarLinkError) -> InferenceFault { + match error { + SidecarLinkError::Closed => { + InferenceFault::new("the SDK sidecar exited during a query".to_string()) + } + SidecarLinkError::Spawn(detail) => { + InferenceFault::new(format!("the SDK sidecar could not start: {detail}")) + } + SidecarLinkError::Codec(detail) => { + InferenceFault::integrity_violation(format!("SDK sidecar framing: {detail}")) + } + } +} + +/// Lowers one prepared request into the frame the sidecar reads. Deciding that +/// the first input item is the prompt and the rest are a prior-round transcript +/// is Ghostlight's claim about its own conversation type, so it is made here, +/// next to the evaluators that built those items — and no SDK option name +/// appears in this crate. +pub(super) fn lower_query( + query_id: u64, + prepared: &PreparedInference, + turn_cap: u32, +) -> Result { + let request = &prepared.invocation.request; + if let Some(effort) = request.reasoning_effort.as_deref() + && !SDK_EFFORT_LEVELS.contains(&effort) + { + return Err(InferenceFault::integrity_violation(format!( + "reasoning effort `{effort}` has no SDK counterpart" + ))); + } + let mut items = request.input.iter(); + let Some(CodexInputItem::UserText { text: prompt }) = items.next() else { + return Err(InferenceFault::integrity_violation( + "an SDK request must open with exactly one user text item", + )); + }; + let mut transcript = Vec::new(); + for item in items { + match item { + CodexInputItem::AssistantText { text } => transcript.push(format!("assistant: {text}")), + CodexInputItem::ToolCall { + name, arguments, .. + } => transcript.push(format!("tool call {name}: {arguments}")), + CodexInputItem::ToolResult { output, .. } => { + transcript.push(format!("tool result: {output}")) + } + CodexInputItem::UserText { .. } => { + return Err(InferenceFault::integrity_violation( + "an SDK request carries one user text item and no other", + )); + } + } + } + Ok(SidecarFrame::Query { + query_id, + model: request.model.clone(), + instructions: request.instructions.clone(), + prompt: prompt.clone(), + transcript, + tools: request + .tools + .iter() + .map(|tool| SidecarTool { + name: tool.name.clone(), + description: tool.description.clone(), + parameters_json: tool.parameters_json.clone(), + }) + .collect(), + effort: request.reasoning_effort.clone(), + max_output_tokens: request.max_output_tokens, + turn_cap, + }) +} + +/// A call id the connector's own validators would refuse cannot be persisted: +/// the evaluator rebuilds these into `CodexInputItem`s that `validate()` will +/// see again. +fn call_id_is_valid(call_id: &str) -> bool { + !call_id.is_empty() && call_id.len() <= 64 && call_id.is_ascii() +} + +fn tool_name_is_valid(name: &str) -> bool { + !name.is_empty() + && name.len() <= 64 + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') +} + +fn assemble_output( + prepared: &PreparedInference, + events: Vec, + material: SdkResultMaterial, + answered: &[(String, String, String)], +) -> Result { + let request = &prepared.invocation.request; + let mut lowered = Vec::with_capacity(events.len()); + let mut dispatched: Vec<(String, String, String)> = Vec::new(); + for event in events { + match event { + SidecarEvent::Text { text } => lowered.push(InferenceEvent::Text(text)), + SidecarEvent::ToolCall { + call_id, + name, + arguments, + dispatched: was_dispatched, + } => { + if !call_id_is_valid(&call_id) || !tool_name_is_valid(&name) { + return Err(InferenceFault::integrity_violation( + "the SDK sidecar reported a call id or tool name the provider contract refuses", + )); + } + if was_dispatched { + dispatched.push((call_id.clone(), name.clone(), arguments.clone())); + } else if request.tools.iter().any(|tool| tool.name == name) { + // A registered tool the sidecar did not dispatch is a + // dropped call, not an invented name. + return Err(InferenceFault::integrity_violation( + "the SDK sidecar left a registered tool call unanswered", + )); + } + lowered.push(InferenceEvent::ToolCall { + call_id, + name, + arguments, + }); + } + } + } + if dispatched != answered { + return Err(InferenceFault::integrity_violation( + "the SDK sidecar's dispatched calls do not match the calls this port answered", + )); + } + let receipt = SdkInferenceReceipt { + schema_id: SDK_RECEIPT_SCHEMA.to_owned(), + request_id: request.request_id.clone(), + conversation_id: request.conversation_id.clone(), + caller_runtime_id: prepared.invocation.caller_runtime_id.clone(), + native_request_sha256: prepared.invocation.native_request_sha256, + provider_request_sha256: prepared.invocation.provider_request_sha256, + model: request.model.clone(), + session_id: material.session_id, + result_uuid: material.result_uuid, + subtype: material.subtype, + stop_reason: material.stop_reason, + num_turns: material.num_turns, + assistant_message_uuids: material.assistant_message_uuids, + assistant_request_ids: material.assistant_request_ids, + usage: { + let mut usage = material.usage; + usage.sort(); + usage + }, + total_cost_usd_estimate: material.total_cost_usd_estimate, + }; + let receipt_bytes = rmp_serde::to_vec_named(&receipt) + .map_err(|error| InferenceFault::new(error.to_string()))?; + Ok(InferenceOutput { + events: lowered, + receipt_digest: format!("sha256:{:x}", Sha256::digest(&receipt_bytes)), + }) +} + +#[async_trait] +impl InferencePort for SdkInferencePort { + fn prepare(&self, request: InferenceRequest) -> Result { + prepare_invocation( + &self.caller_runtime_id, + unix_ms()?.saturating_add(REQUEST_EXPIRY.as_millis() as u64), + request, + ) + } + + async fn infer(&self, request: PreparedInference) -> Result { + if request.invocation.caller_runtime_id != self.caller_runtime_id { + return Err(InferenceFault::integrity_violation( + "persisted inference caller does not match the configured runtime identity", + )); + } + if request.invocation.expires_at_unix_ms <= unix_ms()? { + return Err(InferenceFault::new( + "persisted inference invocation expired before it reached the SDK sidecar", + )); + } + let oracle = self.take_oracle(&request.invocation.request.request_id); + let has_tools = !request.invocation.request.tools.is_empty(); + let turn_cap = match (&oracle, has_tools) { + (Some(oracle), true) => oracle.remaining_rounds(), + (None, false) => 1, + _ => { + return Err(InferenceFault::integrity_violation( + "a tool request reached the SDK port without its lane's tool-result owner", + )); + } + }; + self.run_query(request, oracle, turn_cap).await + } + + fn lend_tool_results(&self, prepared: &PreparedInference, oracle: Box) { + self.oracles + .lock() + .expect("the oracle map is never poisoned") + .insert(prepared.invocation.request.request_id.clone(), oracle); + } +} + +/// Which port a lane uses is which model it is configured with. The config +/// already gates cognition by model name and deliberately refuses a mode flag, +/// so the transport is bound where the model is named and nowhere else. +pub(super) struct RoutedInferencePort { + connector: Option>, + sdk: Option>, + sdk_model_prefix: String, +} + +impl RoutedInferencePort { + pub(super) fn new( + connector: Option>, + sdk: Option>, + sdk_model_prefix: impl Into, + ) -> Self { + Self { + connector, + sdk, + sdk_model_prefix: sdk_model_prefix.into(), + } + } + + /// The model name carries the transport. A prefixed model that no SDK port + /// claims routes nowhere rather than falling back: a fallback is what would + /// make a typo in a model environment variable silent. + pub(super) fn route(&self, model: &str) -> Option<&Arc> { + if model.starts_with(&self.sdk_model_prefix) { + self.sdk.as_ref() + } else { + self.connector.as_ref() + } + } +} + +#[async_trait] +impl InferencePort for RoutedInferencePort { + fn prepare(&self, request: InferenceRequest) -> Result { + let model = request.provider_model().to_owned(); + match self.route(&model) { + Some(port) => port.prepare(request), + None => Err(InferenceFault::integrity_violation(format!( + "no configured inference backend claims the model `{model}`" + ))), + } + } + + async fn infer(&self, request: PreparedInference) -> Result { + let model = request.invocation.request.model.clone(); + match self.route(&model) { + Some(port) => port.infer(request).await, + None => Err(InferenceFault::integrity_violation(format!( + "no configured inference backend claims the model `{model}`" + ))), + } + } + + fn lend_tool_results(&self, prepared: &PreparedInference, oracle: Box) { + if let Some(port) = self.route(&prepared.invocation.request.model) { + port.lend_tool_results(prepared, oracle); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::world::CommandId; + use crate::world::controllers::{ + ConnectorBinding, ControllerModels, ControllerOpenError, InferencePurpose, + OperationalOracle, RequestShape, catalog_tools, open_inference, tool_request, + }; + use crate::world::elaboration::{ + ElaborationLoopEvaluation, ElaborationOracle, SEED_ROUND_BUDGET, evaluate_elaboration_loop, + }; + use crate::world::patch::{ + RECORD_GAP_PATCH_TOOL, SUBMIT_PATCH_TOOL, kernel_speak_entry, patch_tools, + }; + use crate::world::{AffordanceId, AffordanceSnapshot}; + use codex_connector::CodexToolDefinition; + use std::collections::VecDeque; + + const TEST_RUNTIME: &str = "ghostlight-sdk-test"; + const TEST_MODEL: &str = "claude-opus-5"; + + /// A `SidecarLink` with no child and no Node: it replays a scripted frame + /// sequence and records every frame the port sends, so the protocol driver + /// is exercised without a process or a credential. + struct ScriptedLink { + outbound: Mutex>, + sent: Mutex>, + restarts: Mutex, + } + + impl ScriptedLink { + fn new(outbound: Vec) -> Arc { + Arc::new(Self { + outbound: Mutex::new(outbound.into()), + sent: Mutex::new(Vec::new()), + restarts: Mutex::new(0), + }) + } + + fn sent(&self) -> Vec { + self.sent.lock().unwrap().clone() + } + + fn restarts(&self) -> usize { + *self.restarts.lock().unwrap() + } + } + + #[async_trait] + impl SidecarLink for ScriptedLink { + async fn send(&self, frame: SidecarFrame) -> Result<(), SidecarLinkError> { + self.sent.lock().unwrap().push(frame); + Ok(()) + } + + async fn recv(&self) -> Result { + self.outbound + .lock() + .unwrap() + .pop_front() + .ok_or(SidecarLinkError::Closed) + } + + async fn restart(&self) -> Result<(), SidecarLinkError> { + *self.restarts.lock().unwrap() += 1; + Ok(()) + } + } + + fn material() -> SdkResultMaterial { + SdkResultMaterial { + session_id: "session-one".into(), + result_uuid: "result-one".into(), + subtype: "success".into(), + stop_reason: Some("end_turn".into()), + num_turns: 1, + assistant_message_uuids: vec!["assistant-one".into()], + assistant_request_ids: vec!["req_one".into()], + usage: vec![SdkModelUsage { + model: TEST_MODEL.into(), + input_tokens: 12, + output_tokens: 34, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + }], + total_cost_usd_estimate: "0.0123".into(), + } + } + + fn seed_prepared(port: &SdkInferencePort, prompt: &str) -> PreparedInference { + let request = tool_request( + CommandId::new(), + 0, + InferencePurpose::Elaboration, + TEST_MODEL, + "Author the shortfall.", + vec![CodexInputItem::UserText { + text: prompt.into(), + }], + patch_tools(), + RequestShape { + max_output_tokens: 4_000, + parallel_tool_calls: false, + }, + ) + .expect("the seed request builds"); + port.prepare(request).expect("the SDK port prepares") + } + + fn prose_request(prompt: &str) -> InferenceRequest { + tool_request( + CommandId::new(), + 0, + InferencePurpose::Persona, + TEST_MODEL, + "Respond only in natural prose.", + vec![CodexInputItem::UserText { + text: prompt.into(), + }], + Vec::::new(), + RequestShape { + max_output_tokens: 1_200, + parallel_tool_calls: false, + }, + ) + .expect("the prose request builds") + } + + fn prose_prepared(port: &SdkInferencePort, prompt: &str) -> PreparedInference { + port.prepare(prose_request(prompt)) + .expect("the SDK port prepares") + } + + fn tool_call_frame(call_id: &str, name: &str, arguments: &str) -> SidecarFrame { + SidecarFrame::ToolCall { + query_id: 1, + call_id: call_id.into(), + name: name.into(), + arguments: arguments.into(), + } + } + + fn dispatched_event(call_id: &str, name: &str, arguments: &str) -> SidecarEvent { + SidecarEvent::ToolCall { + call_id: call_id.into(), + name: name.into(), + arguments: arguments.into(), + dispatched: true, + } + } + + /// Spec test 5. + #[tokio::test] + async fn a_persona_query_returns_one_prose_output() { + let link = ScriptedLink::new(vec![SidecarFrame::Output { + query_id: 1, + events: vec![SidecarEvent::Text { + text: "The rain has teeth tonight.".into(), + }], + receipt: material(), + }]); + let port = SdkInferencePort::new(link.clone(), TEST_RUNTIME); + let prepared = prose_prepared(&port, "Say something true."); + let output = port.infer(prepared).await.expect("the prose query returns"); + assert_eq!( + output.events, + vec![InferenceEvent::Text("The rain has teeth tonight.".into())] + ); + let sent = link.sent(); + let [ + SidecarFrame::Query { + tools, turn_cap, .. + }, + ] = sent.as_slice() + else { + panic!("the port sent something other than one query frame") + }; + assert!(tools.is_empty(), "a prose request carried tools"); + assert_eq!(*turn_cap, 1, "a prose request asked for more than one turn"); + assert!(output.receipt_digest.starts_with("sha256:")); + } + + /// Spec test 6. The required end-to-end: every tool result the model saw + /// came from the lane's own fold, and the finished output re-derives + /// through the seed evaluator to the same capture. + #[tokio::test] + async fn a_multi_tool_query_re_derives_in_the_seed_evaluator() { + let calls = [ + ("call-0", RECORD_GAP_PATCH_TOOL, r#"{"detail":"no route"}"#), + ("call-1", RECORD_GAP_PATCH_TOOL, "not json at all"), + ("call-3", SUBMIT_PATCH_TOOL, "{}"), + ]; + let mut outbound: Vec = calls + .iter() + .map(|(id, name, arguments)| tool_call_frame(id, name, arguments)) + .collect(); + let mut events: Vec = calls + .iter() + .map(|(id, name, arguments)| dispatched_event(id, name, arguments)) + .collect(); + // A name the request never registered: the harness answered it, so it + // is reported undispatched and the oracle never saw it. + events.insert( + 2, + SidecarEvent::ToolCall { + call_id: "call-2".into(), + name: "speek".into(), + arguments: "{}".into(), + dispatched: false, + }, + ); + outbound.push(SidecarFrame::Output { + query_id: 1, + events, + receipt: material(), + }); + let link = ScriptedLink::new(outbound); + let port = SdkInferencePort::new(link.clone(), TEST_RUNTIME); + let prompt = "Author the shortfall."; + let prepared = seed_prepared(&port, prompt); + port.lend_tool_results( + &prepared, + Box::new(ElaborationOracle::new(&[], SEED_ROUND_BUDGET)), + ); + let output = port.infer(prepared).await.expect("the seed query returns"); + + // Every answer the port sent is the string the evaluator recomputes. + let answers: Vec = link + .sent() + .into_iter() + .filter_map(|frame| match frame { + SidecarFrame::ToolResult { output, .. } => Some(output), + _ => None, + }) + .collect(); + assert_eq!( + answers, + vec![ + "gap recorded".to_string(), + "arguments recorded as a gap".to_string(), + "patch submitted".to_string(), + ] + ); + + let evaluation = evaluate_elaboration_loop(prompt, &[], &[output], SEED_ROUND_BUDGET) + .expect("the seed evaluator re-derives"); + let ElaborationLoopEvaluation::Complete { capture } = evaluation else { + panic!("one SDK query did not close the seed round") + }; + assert!(capture.submitted, "the re-derived capture did not submit"); + } + + /// Spec test 7. + #[tokio::test] + async fn a_sidecar_crash_mid_query_is_recovery_required() { + let link = ScriptedLink::new(vec![ + tool_call_frame("call-0", RECORD_GAP_PATCH_TOOL, r#"{"detail":"one"}"#), + tool_call_frame("call-1", RECORD_GAP_PATCH_TOOL, r#"{"detail":"two"}"#), + ]); + let port = SdkInferencePort::new(link.clone(), TEST_RUNTIME); + let prepared = seed_prepared(&port, "Author the shortfall."); + port.lend_tool_results( + &prepared, + Box::new(ElaborationOracle::new(&[], SEED_ROUND_BUDGET)), + ); + let fault = port + .infer(prepared) + .await + .expect_err("a closed pipe produced an output"); + assert!(fault.recovery_required(), "{fault:?}"); + assert!(!fault.integrity_was_violated()); + assert_eq!(link.restarts(), 1); + } + + /// Spec test 8. + #[tokio::test] + async fn a_malformed_frame_is_an_integrity_violation() { + async fn refuse(body: Vec) -> InferenceFault { + let (mut client, mut server) = tokio::io::duplex(1 << 16); + client.write_all(&body).await.unwrap(); + drop(client); + link_fault(read_frame(&mut server).await.expect_err("a frame decoded")) + } + let mut over_cap = ((MAX_SIDECAR_FRAME_BYTES + 1) as u32) + .to_be_bytes() + .to_vec(); + over_cap.extend_from_slice(b"body"); + assert!(refuse(over_cap).await.integrity_was_violated()); + + let mut truncated = 64_u32.to_be_bytes().to_vec(); + truncated.extend_from_slice(b"short"); + assert!(refuse(truncated).await.integrity_was_violated()); + + let mut garbage = 5_u32.to_be_bytes().to_vec(); + garbage.extend_from_slice(&[0xC1, 0xC1, 0xC1, 0xC1, 0xC1]); + assert!(refuse(garbage).await.integrity_was_violated()); + } + + /// Spec test 9. + #[tokio::test] + async fn an_over_cap_or_misrouted_frame_is_refused() { + for frame in [ + SidecarFrame::Output { + query_id: 99, + events: Vec::new(), + receipt: material(), + }, + SidecarFrame::Query { + query_id: 1, + model: TEST_MODEL.into(), + instructions: "no".into(), + prompt: "no".into(), + transcript: Vec::new(), + tools: Vec::new(), + effort: None, + max_output_tokens: None, + turn_cap: 1, + }, + ] { + let link = ScriptedLink::new(vec![frame]); + let port = SdkInferencePort::new(link.clone(), TEST_RUNTIME); + let prepared = prose_prepared(&port, "Say something true."); + let fault = port + .infer(prepared) + .await + .expect_err("a misrouted frame produced an output"); + assert!(fault.integrity_was_violated(), "{fault:?}"); + assert_eq!(link.restarts(), 1); + } + } + + /// Spec test 10. + #[tokio::test] + async fn the_event_gates_catch_a_lying_sidecar() { + let answered = ("call-0", RECORD_GAP_PATCH_TOOL, r#"{"detail":"one"}"#); + let lies = [ + // A dispatched call the port never answered. + vec![dispatched_event("call-9", RECORD_GAP_PATCH_TOOL, "{}")], + // A registered tool reported as undispatched: a dropped call. + vec![ + dispatched_event(answered.0, answered.1, answered.2), + SidecarEvent::ToolCall { + call_id: "call-1".into(), + name: RECORD_GAP_PATCH_TOOL.into(), + arguments: "{}".into(), + dispatched: false, + }, + ], + // A call id the provider contract refuses. + vec![dispatched_event(&"x".repeat(65), answered.1, answered.2)], + ]; + for events in lies { + let link = ScriptedLink::new(vec![ + tool_call_frame(answered.0, answered.1, answered.2), + SidecarFrame::Output { + query_id: 1, + events, + receipt: material(), + }, + ]); + let port = SdkInferencePort::new(link.clone(), TEST_RUNTIME); + let prepared = seed_prepared(&port, "Author the shortfall."); + port.lend_tool_results( + &prepared, + Box::new(ElaborationOracle::new(&[], SEED_ROUND_BUDGET)), + ); + let fault = port + .infer(prepared) + .await + .expect_err("a lying sidecar produced an output"); + assert!(fault.integrity_was_violated(), "{fault:?}"); + } + + // An undispatched call naming a tool the request does not carry is + // accepted, and its event survives into the output. + let link = ScriptedLink::new(vec![ + tool_call_frame(answered.0, answered.1, answered.2), + SidecarFrame::Output { + query_id: 1, + events: vec![ + dispatched_event(answered.0, answered.1, answered.2), + SidecarEvent::ToolCall { + call_id: "call-1".into(), + name: "speek".into(), + arguments: "{}".into(), + dispatched: false, + }, + ], + receipt: material(), + }, + ]); + let port = SdkInferencePort::new(link, TEST_RUNTIME); + let prepared = seed_prepared(&port, "Author the shortfall."); + port.lend_tool_results( + &prepared, + Box::new(ElaborationOracle::new(&[], SEED_ROUND_BUDGET)), + ); + let output = port + .infer(prepared) + .await + .expect("an invented name is a gap, not a violation"); + assert_eq!(output.events.len(), 2); + } + + /// Spec test 11. The digest is a pure function of the receipt, so it is + /// compared directly rather than through two whole queries. + #[tokio::test] + async fn a_receipt_digest_is_deterministic_and_bound_to_the_request() { + let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); + let prepared = prose_prepared(&port, "Say something true."); + let events = vec![SidecarEvent::Text { text: "ok".into() }]; + let first = assemble_output(&prepared, events.clone(), material(), &[]).unwrap(); + let again = assemble_output(&prepared, events.clone(), material(), &[]).unwrap(); + assert_eq!(first.receipt_digest, again.receipt_digest); + assert_eq!(first.receipt_digest.len(), "sha256:".len() + 64); + assert!( + first.receipt_digest["sha256:".len()..] + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + ); + assert!( + first + .clone() + .prose_only(InferencePurpose::Persona) + .is_ok_and(|(prose, _)| prose == "ok") + ); + + let mut other_session = material(); + other_session.session_id = "session-two".into(); + assert_ne!( + first.receipt_digest, + assemble_output(&prepared, events.clone(), other_session, &[]) + .unwrap() + .receipt_digest + ); + let mut other_usage = material(); + other_usage.usage[0].output_tokens += 1; + assert_ne!( + first.receipt_digest, + assemble_output(&prepared, events.clone(), other_usage, &[]) + .unwrap() + .receipt_digest + ); + let other_request = prose_prepared(&port, "Say something else."); + assert_ne!( + first.receipt_digest, + assemble_output(&other_request, events, material(), &[]) + .unwrap() + .receipt_digest + ); + } + + /// Spec test 14. + #[tokio::test] + async fn an_expired_invocation_is_recovery_required() { + let link = ScriptedLink::new(Vec::new()); + let port = SdkInferencePort::new(link.clone(), TEST_RUNTIME); + let stale = prepare_invocation(TEST_RUNTIME, 1_000, prose_request("Say something true.")) + .expect("the stale invocation builds"); + let fault = port + .infer(stale) + .await + .expect_err("a stale invocation re-ran"); + assert!(fault.recovery_required(), "{fault:?}"); + assert!( + link.sent().is_empty(), + "a stale invocation reached the pipe" + ); + } + + /// Spec test 15. + #[tokio::test] + async fn the_oracle_error_aborts_the_query() { + let granted = vec![AffordanceSnapshot { + id: AffordanceId::issue(), + entry: kernel_speak_entry(), + }]; + let speak = granted[0].entry.kind.0.clone(); + let link = ScriptedLink::new(vec![ + tool_call_frame("call-0", &speak, r#"{"text":"Hold the bridge."}"#), + tool_call_frame("call-1", "finish_without_proposal", "{}"), + SidecarFrame::Output { + query_id: 1, + events: Vec::new(), + receipt: material(), + }, + ]); + let port = SdkInferencePort::new(link.clone(), TEST_RUNTIME); + let request = tool_request( + CommandId::new(), + 0, + InferencePurpose::OperationalAgent, + TEST_MODEL, + "Use only the supplied tools.", + vec![CodexInputItem::UserText { + text: "Hold the bridge.".into(), + }], + catalog_tools("", &granted), + RequestShape { + max_output_tokens: 1_200, + parallel_tool_calls: false, + }, + ) + .expect("the operational request builds"); + let prepared = port.prepare(request).expect("the SDK port prepares"); + port.lend_tool_results(&prepared, Box::new(OperationalOracle::new(&granted, &[]))); + let fault = port + .infer(prepared) + .await + .expect_err("a contradicted terminal produced an output"); + assert!(fault.recovery_required(), "{fault:?}"); + assert_eq!(link.restarts(), 1); + assert_eq!( + link.sent() + .into_iter() + .filter(|frame| matches!(frame, SidecarFrame::ToolResult { .. })) + .count(), + 1, + "the port answered a call it had no string for" + ); + } + + /// Spec test 12. + #[test] + fn a_model_prefix_routes_a_lane_to_its_port() { + let sdk = Arc::new(SdkInferencePort::new( + ScriptedLink::new(Vec::new()), + TEST_RUNTIME, + )) as Arc; + let connector = Arc::new(SdkInferencePort::new( + ScriptedLink::new(Vec::new()), + "ghostlight-connector-stand-in", + )) as Arc; + let routed = RoutedInferencePort::new( + Some(Arc::clone(&connector)), + Some(Arc::clone(&sdk)), + DEFAULT_SDK_MODEL_PREFIX, + ); + assert!(Arc::ptr_eq(routed.route("claude-opus-5").unwrap(), &sdk)); + assert!(Arc::ptr_eq( + routed.route("gpt-5.6-terra").unwrap(), + &connector + )); + let moved = + RoutedInferencePort::new(Some(Arc::clone(&connector)), Some(Arc::clone(&sdk)), "gpt-"); + assert!(Arc::ptr_eq(moved.route("gpt-5.6-terra").unwrap(), &sdk)); + assert!(Arc::ptr_eq( + moved.route("claude-opus-5").unwrap(), + &connector + )); + } + + fn models(model: &str) -> ControllerModels { + ControllerModels { + projector: model.into(), + persona: model.into(), + interpreter: model.into(), + operational_agent: model.into(), + elaborator: model.into(), + } + } + + /// Spec test 13. + #[test] + fn an_unroutable_model_fails_at_open() { + let directory = tempfile::tempdir().unwrap(); + let entry = directory.path().join("main.js"); + std::fs::write(&entry, "// sidecar").unwrap(); + let key = directory.path().join("controller.key"); + std::fs::write(&key, "sdk-port-test-key").unwrap(); + let sdk = || SdkBinding { + sidecar_entry: entry.clone(), + caller_runtime_id: TEST_RUNTIME.into(), + model_prefix: DEFAULT_SDK_MODEL_PREFIX.into(), + }; + let connector = || ConnectorBinding { + endpoint: "127.0.0.1:9".parse().unwrap(), + key_path: key.clone(), + caller_runtime_id: TEST_RUNTIME.into(), + }; + + assert!(matches!( + open_inference(None, Some(sdk()), &models("gpt-5.6-terra")), + Err(ControllerOpenError::UnroutableModel { .. }) + )); + assert!(matches!( + open_inference(Some(connector()), None, &models("claude-opus-5")), + Err(ControllerOpenError::UnroutableModel { .. }) + )); + assert!(matches!( + open_inference( + None, + Some(SdkBinding { + sidecar_entry: directory.path().join("absent.js"), + caller_runtime_id: TEST_RUNTIME.into(), + model_prefix: DEFAULT_SDK_MODEL_PREFIX.into(), + }), + &models(TEST_MODEL), + ), + Err(ControllerOpenError::SdkSidecarMissing { .. }) + )); + assert!( + open_inference(Some(connector()), Some(sdk()), &models(TEST_MODEL)).is_ok(), + "a configuration where every model routes did not open" + ); + } + + /// The Rust half of the sidecar's frame round-trip pair (spec test 18): + /// pins the exact `rmp_serde::to_vec_named` bytes the TypeScript decoder is + /// tested against, so the two halves cannot drift apart silently. + #[tokio::test] + async fn frame_fixtures_match_the_checked_in_sidecar_bytes() { + let fixtures: Vec<(&str, SidecarFrame)> = vec![ + ( + "query", + SidecarFrame::Query { + query_id: 7, + model: TEST_MODEL.into(), + instructions: "Author the shortfall.".into(), + prompt: "Answer the deficit.".into(), + transcript: vec!["assistant: thinking".into(), "tool result: ok".into()], + tools: vec![SidecarTool { + name: "submit".into(), + description: "Submit the draft.".into(), + parameters_json: r#"{"type":"object","additionalProperties":false,"required":[],"properties":{}}"# + .into(), + }], + effort: Some("medium".into()), + max_output_tokens: Some(4_000), + turn_cap: 24, + }, + ), + ( + "tool_call", + SidecarFrame::ToolCall { + query_id: 7, + call_id: "call-0".into(), + name: "submit".into(), + arguments: "{}".into(), + }, + ), + ( + "tool_result", + SidecarFrame::ToolResult { + query_id: 7, + call_id: "call-0".into(), + output: "patch submitted".into(), + }, + ), + ( + "output", + SidecarFrame::Output { + query_id: 7, + events: vec![ + SidecarEvent::Text { + text: "Done.".into(), + }, + dispatched_event("call-0", "submit", "{}"), + ], + receipt: material(), + }, + ), + ( + "fault", + SidecarFrame::Fault { + query_id: 7, + reason: SidecarFaultReason::RateLimited, + detail: "429".into(), + }, + ), + ]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../sidecar/claude-sdk/test/frames"); + for (name, frame) in fixtures { + let bytes = encode_frame(&frame).expect("the fixture frame encodes"); + let path = root.join(format!("{name}.bin")); + if std::env::var_os("GHOSTLIGHT_WRITE_SIDECAR_FIXTURES").is_some() { + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(&path, &bytes).unwrap(); + } + let on_disk = std::fs::read(&path).unwrap_or_else(|error| { + panic!( + "the sidecar frame fixture {} is missing ({error}); regenerate with GHOSTLIGHT_WRITE_SIDECAR_FIXTURES=1", + path.display() + ) + }); + assert_eq!( + bytes, on_disk, + "the sidecar frame fixture {name} drifted from the Rust encoder" + ); + let mut reader = std::io::Cursor::new(on_disk); + assert_eq!( + read_frame(&mut reader).await.expect("the fixture decodes"), + frame + ); + } + } +} diff --git a/sidecar/claude-sdk/test/frames/fault.bin b/sidecar/claude-sdk/test/frames/fault.bin new file mode 100644 index 0000000..0cf3677 Binary files /dev/null and b/sidecar/claude-sdk/test/frames/fault.bin differ diff --git a/sidecar/claude-sdk/test/frames/output.bin b/sidecar/claude-sdk/test/frames/output.bin new file mode 100644 index 0000000..40d21ba Binary files /dev/null and b/sidecar/claude-sdk/test/frames/output.bin differ diff --git a/sidecar/claude-sdk/test/frames/query.bin b/sidecar/claude-sdk/test/frames/query.bin new file mode 100644 index 0000000..02385e3 Binary files /dev/null and b/sidecar/claude-sdk/test/frames/query.bin differ diff --git a/sidecar/claude-sdk/test/frames/tool_call.bin b/sidecar/claude-sdk/test/frames/tool_call.bin new file mode 100644 index 0000000..631b07b Binary files /dev/null and b/sidecar/claude-sdk/test/frames/tool_call.bin differ diff --git a/sidecar/claude-sdk/test/frames/tool_result.bin b/sidecar/claude-sdk/test/frames/tool_result.bin new file mode 100644 index 0000000..7a29358 Binary files /dev/null and b/sidecar/claude-sdk/test/frames/tool_result.bin differ