diff --git a/.gitignore b/.gitignore index 3c71615..d7d5e59 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ node_modules/ -sidecar/claude-sdk/dist/ target/ # Disposable local scaffolding. These accumulated to ~87MB of untracked debris diff --git a/AGENTS.md b/AGENTS.md index f0e4406..2c2c5c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,6 @@ what exists today and what does not. - Parked Dungeon (daemon, play table, Eve surface, browser host, Idunn recipe): tag `parked/ghostlight-eve-surface`; not on main. - Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`. -- Claude SDK sidecar: `sidecar/claude-sdk/`. - Architecture rationale (the parked Dungeon's): `docs/architecture/ghostlight-dungeon-mvp.md`. `notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09 rebuild, not the current plan. diff --git a/README.md b/README.md index ff4a893..2a63414 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,6 @@ nothing on main serves HTTP. The Dungeon returns when Thing 2 gives it a UI | `crates/ghostlight/` | The sealed kernel library. | | `crates/ghostlight-persona-projection/` | Membrane between structured state and a prose-only Persona. | | `crates/ghostlight-verse/` | The `ghostlight-verse` operator command line (`genesis`, `run`). | -| `sidecar/claude-sdk/` | Node process serving `claude`-prefixed models to the kernel; a stopgap for a direct Messages API port. | | `AGENTS.md` | Invariants and where things are. | | `docs/architecture/ghostlight-dungeon-mvp.md` | The parked Dungeon's authority architecture (design record). | | `notes/` | The verse campaign's target and map, the handoff pointer, local smoke notes. | @@ -107,15 +106,14 @@ cargo test --locked -p ghostlight cargo test --locked -p ghostlight-verse ``` -The kernel alone needs only `cargo test -p ghostlight`. The sidecar has -`npm run sdk:build` and `npm run sdk:test`. The acceptance test +The kernel alone needs only `cargo test -p ghostlight`. The acceptance test `controllers::tests::real_local_model_cognition_modes_commit_speech` is ignored by default and needs a real model. Inference is routed by model name: `local/` goes to an OpenAI-compatible -loopback endpoint, `claude` to the SDK sidecar, and the verse runner's `hosted/` -to an https endpoint. Ghostlight never reads, stores or forwards a model -credential beyond a key file named at run time. +loopback endpoint, the verse runner's `hosted/` goes to an https endpoint, +and any other model goes to the connector. Ghostlight never reads, stores or +forwards a model credential beyond a key file named at run time. Runtime documents are MessagePack-backed CultCache. JSON appears only at schema publication, model-provider and diagnostic boundaries. diff --git a/crates/ghostlight-dungeon/src/play.rs b/crates/ghostlight-dungeon/src/play.rs index b69b308..7b191e2 100644 --- a/crates/ghostlight-dungeon/src/play.rs +++ b/crates/ghostlight-dungeon/src/play.rs @@ -9169,7 +9169,7 @@ pub(crate) mod tests { }; let inference = match timeout { Some(timeout) => ghostlight::open_local_port_with_timeout(binding, timeout).unwrap(), - None => ghostlight::open_inference(None, None, Some(binding), None, &["local/play"]).unwrap(), + None => ghostlight::open_inference(None, Some(binding), None, &["local/play"]).unwrap(), }; let table = PlayTable::new( fixture.world.clone(), diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index 36529a7..110be4c 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -143,7 +143,7 @@ pub(crate) fn open_shared() -> anyhow::Result { let mut all: Vec<&str> = models.each().to_vec(); all.push(&play_model); let inference: Arc = - open_inference(Some(connector_binding()?), None, None, None, &all)?; + open_inference(Some(connector_binding()?), None, None, &all)?; Ok(Shared { inference, models, diff --git a/crates/ghostlight-verse/src/main.rs b/crates/ghostlight-verse/src/main.rs index 2c7d020..8484e1f 100644 --- a/crates/ghostlight-verse/src/main.rs +++ b/crates/ghostlight-verse/src/main.rs @@ -374,7 +374,7 @@ fn open_lane( } else { bail!("--model names no inference lane (expected a hosted/ or local/ prefix)"); } - open_inference(None, None, local, hosted, &models.each()) + open_inference(None, local, hosted, &models.each()) .map_err(|error| anyhow!(lane_fault(&error))) } @@ -392,7 +392,6 @@ fn lane_fault(error: &ControllerOpenError) -> &'static str { ControllerOpenError::Connector(_) => "the connector lane cannot open", ControllerOpenError::WorkStore(_) => "the controller work journal cannot open", ControllerOpenError::UnroutableModel { .. } => "--model is claimed by no inference lane", - ControllerOpenError::SdkSidecarMissing { .. } => "the SDK sidecar entry is not a file", ControllerOpenError::LocalEndpointNotLoopback { .. } => { "--base-url for a local model must be a loopback address" } @@ -403,9 +402,6 @@ fn lane_fault(error: &ControllerOpenError) -> &'static str { "--key-file is unreadable, empty, or not one run of visible ASCII" } ControllerOpenError::SharedModelPrefix { .. } => "two inference lanes claim one model prefix", - ControllerOpenError::SidecarClaimsConnectorModel { .. } => { - "the SDK sidecar prefix claims a connector model" - } ControllerOpenError::EmptyModelPrefix { .. } => "an inference lane's model prefix is empty", } } diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 46349e0..678fe67 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -14,9 +14,7 @@ use super::elaboration::{ use super::local_inference::{ DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding, open_hosted_port, open_local_port, }; -use super::sdk_inference::{ - ChildProcessLink, DEFAULT_SDK_MODEL_PREFIX, RoutedInferencePort, SdkBinding, SdkInferencePort, -}; +use super::routed_inference::RoutedInferencePort; use super::tool_schema; #[cfg(test)] use crate::AffordanceId; @@ -2710,10 +2708,7 @@ pub struct ControllerModels { pub 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. 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. + /// is added. pub elaborator: String, } @@ -2748,16 +2743,12 @@ pub 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 }, #[error("the local inference endpoint `{endpoint}` is not loopback")] LocalEndpointNotLoopback { endpoint: SocketAddr }, #[error("the hosted inference endpoint must be an https URL")] HostedEndpointNotHttps, #[error("the hosted inference key file is unreadable, empty, or is not one run of visible ASCII")] HostedKeyUnreadable, - #[error("the SDK sidecar prefix claims the connector model `{model}`")] - SidecarClaimsConnectorModel { model: String }, #[error("two inference transports both claim model prefix `{prefix}`")] SharedModelPrefix { prefix: String }, #[error("the {transport} inference transport's model prefix must not be empty")] @@ -2772,13 +2763,6 @@ pub struct ConnectorBinding { pub caller_runtime_id: String, } -/// Whether a model name is one claude-connector serves: its allow list is the -/// `claude--5-5` family. The connector owns the list; this reads only the -/// naming shape so an overlapping sidecar prefix is refused at open. -fn names_connector_model(model: &str) -> bool { - model.starts_with("claude-") && model.ends_with("-5-5") -} - /// Builds the one port every lane shares. A lane whose model no configured /// backend claims fails here, at open, rather than at its first tick. `models` /// is every model that must route, not just `ControllerModels`'s own fields, @@ -2786,7 +2770,6 @@ fn names_connector_model(model: &str) -> bool { /// does not carry (the play lane's, Cut 8). pub fn open_inference( connector: Option, - sdk: Option, local: Option, hosted: Option, models: &[&str], @@ -2799,25 +2782,6 @@ pub fn open_inference( )?)), None => None, }; - 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(), - }); - } - if binding.model_prefix.is_empty() { - return Err(ControllerOpenError::EmptyModelPrefix { transport: "SDK" }); - } - sdk_model_prefix = binding.model_prefix; - Some(Arc::new(SdkInferencePort::new( - Arc::new(ChildProcessLink::new(binding.sidecar_entry)), - binding.caller_runtime_id, - ))) - } - None => None, - }; // Ghostlight never holds a credential for this transport: a loopback // local model server needs none, and `open_local_port` refuses anything // else by construction, inside the port's own constructor, rather than by @@ -2847,26 +2811,13 @@ pub fn open_inference( }; let claims: Vec<(String, Arc)> = local.into_iter().chain(hosted).collect(); let mut claimed: Vec<&str> = claims.iter().map(|(prefix, _)| prefix.as_str()).collect(); - if sdk.is_some() { - claimed.push(&sdk_model_prefix); - } claimed.sort_unstable(); if let Some(pair) = claimed.windows(2).find(|pair| pair[0] == pair[1]) { return Err(ControllerOpenError::SharedModelPrefix { prefix: pair[0].to_owned(), }); } - if connector.is_some() && sdk.is_some() { - if let Some(model) = models - .iter() - .find(|model| names_connector_model(model) && model.starts_with(&sdk_model_prefix)) - { - return Err(ControllerOpenError::SidecarClaimsConnectorModel { - model: (*model).to_owned(), - }); - } - } - let routed = RoutedInferencePort::new(connector, sdk, sdk_model_prefix, claims); + let routed = RoutedInferencePort::new(connector, claims); for &model in models { if routed.route(model).is_none() { return Err(ControllerOpenError::UnroutableModel { @@ -11728,18 +11679,16 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur }; let expiry = 4_102_444_800_000; let connector_side = PreparedInference::prepare("ghostlight-runtime", expiry, build()).unwrap(); - let sdk_side = PreparedInference::prepare("ghostlight-runtime", expiry, build()).unwrap(); - assert_eq!(connector_side, sdk_side); - assert!(prepared_matches_request(&sdk_side, &build(), command_id, 0)); + let second_side = PreparedInference::prepare("ghostlight-runtime", expiry, build()).unwrap(); + assert_eq!(connector_side, second_side); + assert!(prepared_matches_request(&second_side, &build(), command_id, 0)); } - /// Soul: every request builder, prepared exactly as `SdkInferencePort` - /// prepares one, satisfies `prepared_matches_request` — and the - /// content-addressed request id is the same value the connector's own - /// preparation produces, so a checkpoint written under one transport is - /// still the same identity under the other. + /// Soul: every request builder, prepared through `PreparedInference::prepare`, + /// satisfies `prepared_matches_request` — and the content-addressed request + /// id is deterministic across callers. #[test] - fn soul_an_sdk_prepared_request_passes_every_builder_identity() { + fn soul_a_prepared_request_passes_every_builder_identity() { let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); let granted = vec![speak_snapshot(opportunity.affordance_ids[0])]; let constituents = vec![ConstituentWork { @@ -11757,7 +11706,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let model = TEST_LANE_MODEL; assert!( canonical_model(model), - "the SDK-routed model is not a canonical controller model" + "the test model is not a canonical controller model" ); let builders: Vec<(InferencePurpose, usize, Box InferenceRequest>)> = vec![ ( @@ -13017,7 +12966,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur model_prefix: local_model_prefix, caller_runtime_id: runtime_id, }); - let inference = open_inference(connector, None, local, None, &models.each()).unwrap(); + let inference = open_inference(connector, local, None, &models.each()).unwrap(); let work = open_controller_work(directory.path().join("controller-work.cc")).unwrap(); let runner = ControllerRunner::open(mailbox.clone(), inference, work, models).unwrap(); @@ -18200,7 +18149,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let sent = serde_json::to_vec(&seen[0]).unwrap().len(); assert!(sent > 8_000, "the vault's evidence reached the request ({sent} bytes)"); assert!( - sent < crate::sdk_inference::MAX_SIDECAR_FRAME_BYTES / 4, + sent < MAX_CONNECTOR_FRAME_BYTES / 4, "a seed request over a vault of 18 MB stays far under the frame bound ({sent} bytes)" ); } diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index a30a01a..f4b417d 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -78,7 +78,7 @@ mod lens; mod local_inference; mod mailbox; mod patch; -mod sdk_inference; +mod routed_inference; mod table; mod tool_schema; mod vault; @@ -155,7 +155,6 @@ pub(crate) use patch::{ AffordanceKindName, AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind, EffectSlot, OutcomeBand, Precondition, RoleSpec, }; -pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding}; pub use table::{ DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call, decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor, diff --git a/crates/ghostlight/src/local_inference.rs b/crates/ghostlight/src/local_inference.rs index a145da7..6bfeb05 100644 --- a/crates/ghostlight/src/local_inference.rs +++ b/crates/ghostlight/src/local_inference.rs @@ -573,7 +573,7 @@ mod tests { }; use crate::elaboration::{ElaborationLoopEvaluation, SEED_ROUND_BUDGET, evaluate_elaboration_loop}; use crate::patch::{RECORD_GAP_PATCH_TOOL, SUBMIT_PATCH_TOOL, patch_tools}; - use crate::sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, RoutedInferencePort, SdkBinding}; + use crate::routed_inference::RoutedInferencePort; use crate::CommandId; use model_connector::ToolDefinition; use std::collections::VecDeque; @@ -942,16 +942,8 @@ mod tests { /// Spec test. #[test] fn a_non_loopback_endpoint_is_refused_at_open() { - let directory = tempfile::tempdir().unwrap(); - let sdk_entry = directory.path().join("main.js"); - std::fs::write(&sdk_entry, "// sidecar").unwrap(); let error = open_inference( None, - Some(SdkBinding { - sidecar_entry: sdk_entry, - caller_runtime_id: TEST_RUNTIME.into(), - model_prefix: DEFAULT_SDK_MODEL_PREFIX.into(), - }), Some(LocalBinding { endpoint: "93.184.216.34:443".parse().unwrap(), model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(), @@ -1030,42 +1022,42 @@ mod tests { /// that claim the identical prefix outright. #[test] fn routing_prefers_the_longest_claim_and_refuses_a_shared_prefix() { + let directory = tempfile::tempdir().unwrap(); + let key_path = write_key_file(&directory, SYNTHETIC_KEY.as_bytes()); let local_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc; - let sdk_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc; + let narrow_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc; let connector_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc; let routed = RoutedInferencePort::new( Some(Arc::clone(&connector_port)), - Some(Arc::clone(&sdk_port)), - "claude", - vec![("claude-local/".to_owned(), Arc::clone(&local_port))], + vec![ + ("local/".to_owned(), Arc::clone(&local_port)), + ("local/narrow/".to_owned(), Arc::clone(&narrow_port)), + ], ); assert!(Arc::ptr_eq( - routed.route("claude-local/llama-8b").unwrap(), - &local_port + routed.route("local/narrow/llama-8b").unwrap(), + &narrow_port )); - assert!(Arc::ptr_eq(routed.route("claude-opus-5").unwrap(), &sdk_port)); + assert!(Arc::ptr_eq(routed.route("local/llama-8b").unwrap(), &local_port)); assert!(Arc::ptr_eq( routed.route("gpt-5.6-terra").unwrap(), &connector_port )); - let directory = tempfile::tempdir().unwrap(); - let sdk_entry = directory.path().join("main.js"); - std::fs::write(&sdk_entry, "// sidecar").unwrap(); let error = open_inference( None, - Some(SdkBinding { - sidecar_entry: sdk_entry, - caller_runtime_id: TEST_RUNTIME.into(), - model_prefix: "claude".into(), - }), Some(LocalBinding { endpoint: "127.0.0.1:1".parse().unwrap(), - model_prefix: "claude".into(), + model_prefix: "shared/".into(), caller_runtime_id: TEST_RUNTIME.into(), }), - None, - &["claude-opus-5"], + Some(HostedBinding { + base_url: "https://api.example.test".into(), + key_path, + model_prefix: "shared/".into(), + caller_runtime_id: TEST_RUNTIME.into(), + }), + &["shared/x"], ) .err() .expect("two ports sharing one prefix opened"); @@ -1340,7 +1332,6 @@ mod tests { #[test] fn an_empty_local_model_prefix_is_refused_at_open() { let error = open_inference( - None, None, Some(LocalBinding { endpoint: "127.0.0.1:1".parse().unwrap(), @@ -1358,32 +1349,6 @@ mod tests { )); } - /// Spec test (PA.f19). Open refuses an empty SDK model prefix for the - /// same reason. - #[test] - fn an_empty_sdk_model_prefix_is_refused_at_open() { - let directory = tempfile::tempdir().unwrap(); - let sdk_entry = directory.path().join("main.js"); - std::fs::write(&sdk_entry, "// sidecar").unwrap(); - let error = open_inference( - None, - Some(SdkBinding { - sidecar_entry: sdk_entry, - caller_runtime_id: TEST_RUNTIME.into(), - model_prefix: String::new(), - }), - None, - None, - &[TEST_MODEL], - ) - .err() - .expect("an empty SDK model prefix opened"); - assert!(matches!( - error, - ControllerOpenError::EmptyModelPrefix { transport: "SDK" } - )); - } - /// Spec test (PA.f19). Duplicate call ids in one reply pass neither the /// port's own validators nor the evaluator's; the port refuses them /// itself, as an integrity violation, rather than letting the evaluator @@ -1957,7 +1922,6 @@ mod tests { assert!(!error.to_string().contains("example"), "the refusal echoed the URL"); } let through_open_inference = open_inference( - None, None, None, Some(hosted_binding("http://api.example.test", key_path.clone())), @@ -2218,22 +2182,22 @@ mod tests { }; let hosted = || hosted_binding("https://api.example.test", key_path.clone()); let models = ["local/llama-8b", "hosted/deepseek-chat"]; - assert!(open_inference(None, None, Some(local_binding()), Some(hosted()), &models).is_ok()); + assert!(open_inference(None, Some(local_binding()), Some(hosted()), &models).is_ok()); // Without the hosted binding its model has no owner: loud, not a fallback. assert!(matches!( - open_inference(None, None, Some(local_binding()), None, &models), + open_inference(None, Some(local_binding()), None, &models), Err(ControllerOpenError::UnroutableModel { .. }) )); let mut clashing = hosted(); clashing.model_prefix = DEFAULT_LOCAL_MODEL_PREFIX.into(); assert!(matches!( - open_inference(None, None, Some(local_binding()), Some(clashing), &["local/x"]), + open_inference(None, Some(local_binding()), Some(clashing), &["local/x"]), Err(ControllerOpenError::SharedModelPrefix { .. }) )); let mut empty = hosted(); empty.model_prefix = String::new(); assert!(matches!( - open_inference(None, None, None, Some(empty), &["x"]), + open_inference(None, None, Some(empty), &["x"]), Err(ControllerOpenError::EmptyModelPrefix { transport: "hosted" }) )); @@ -2242,8 +2206,6 @@ mod tests { let hosted_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc; let routed = RoutedInferencePort::new( None, - None, - "claude", vec![ ("local/".to_owned(), Arc::clone(&local_port)), ("hosted/".to_owned(), Arc::clone(&hosted_port)), @@ -2257,8 +2219,6 @@ mod tests { let narrow_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc; let routed = RoutedInferencePort::new( None, - None, - "claude", vec![ ("hosted/".to_owned(), Arc::clone(&hosted_port)), ("hosted/deep/".to_owned(), Arc::clone(&narrow_port)), diff --git a/crates/ghostlight/src/routed_inference.rs b/crates/ghostlight/src/routed_inference.rs new file mode 100644 index 0000000..91172b8 --- /dev/null +++ b/crates/ghostlight/src/routed_inference.rs @@ -0,0 +1,303 @@ +//! Prefix-based routing across the configured inference transports. +//! +//! `RoutedInferencePort` routes each model identifier to the longest matching +//! claimed prefix (`local/`, `hosted/`, etc.) and falls back to the connector +//! when no configured prefix claims the model. + +use super::controllers::{ + InferenceFault, InferenceOutput, InferencePort, InferenceRequest, PreparedInference, + ToolResultOracle, +}; +use async_trait::async_trait; +use std::sync::Arc; + +/// 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>, + /// The OpenAI-compatible ports (the loopback one and the hosted one), each + /// with its own claimed prefix carried beside it, so `route` can compare + /// lengths without a parallel field per port to keep in sync. + claims: Vec<(String, Arc)>, +} + +impl RoutedInferencePort { + pub(super) fn new( + connector: Option>, + claims: Vec<(String, Arc)>, + ) -> Self { + Self { connector, claims } + } + + /// The model name carries the transport. When more than one prefix matches, + /// the longest claim wins. Any model no configured prefix claims falls to + /// the connector, or routes nowhere when no connector is bound. + pub(super) fn route(&self, model: &str) -> Option<&Arc> { + if let Some((_, port)) = self + .claims + .iter() + .filter(|(prefix, _)| model.starts_with(prefix.as_str())) + .max_by_key(|(prefix, _)| prefix.len()) + { + return Some(port); + } + 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( + "no configured inference backend claims the requested 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( + "no configured inference backend claims the requested 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::CommandId; + use crate::controllers::{ + ConnectorBinding, ControllerModels, ControllerOpenError, InferencePurpose, RequestShape, + open_inference, tool_request, unix_ms, + }; + use crate::local_inference::{ + DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding, + }; + use model_connector::{InputItem, ToolDefinition}; + + const TEST_RUNTIME: &str = "ghostlight-routed-test"; + const TEST_MODEL: &str = "claude-opus-5-5"; + + struct StubPort; + + #[async_trait] + impl InferencePort for StubPort { + fn prepare(&self, request: InferenceRequest) -> Result { + PreparedInference::prepare(TEST_RUNTIME, unix_ms().saturating_add(60_000), request) + } + + async fn infer(&self, _request: PreparedInference) -> Result { + Err(InferenceFault::integrity_violation("stub port")) + } + } + + fn prose_request(prompt: &str) -> InferenceRequest { + tool_request( + CommandId::new(), + 0, + InferencePurpose::Persona, + TEST_MODEL, + "Respond only in natural prose.", + vec![InputItem::UserText { + text: prompt.into(), + }], + Vec::::new(), + RequestShape { + max_output_tokens: 1_200, + parallel_tool_calls: false, + }, + ) + .expect("the prose request builds") + } + + fn models(model: &str) -> ControllerModels { + ControllerModels { + projector: model.into(), + persona: model.into(), + interpreter: model.into(), + operational_agent: model.into(), + elaborator: model.into(), + } + } + + #[test] + fn open_inference_routes_connector_local_hosted_only() { + let directory = tempfile::tempdir().unwrap(); + let connector_key = directory.path().join("connector.key"); + let hosted_key = directory.path().join("hosted.key"); + std::fs::write(&connector_key, "connector-test-key").unwrap(); + std::fs::write(&hosted_key, "hosted-test-key").unwrap(); + + let connector = ConnectorBinding { + endpoint: "127.0.0.1:9".parse().unwrap(), + key_path: connector_key, + caller_runtime_id: TEST_RUNTIME.into(), + }; + let local = LocalBinding { + endpoint: "127.0.0.1:9".parse().unwrap(), + model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(), + caller_runtime_id: TEST_RUNTIME.into(), + }; + let hosted = HostedBinding { + base_url: "https://api.example.test".into(), + key_path: hosted_key.clone(), + model_prefix: DEFAULT_HOSTED_MODEL_PREFIX.into(), + caller_runtime_id: TEST_RUNTIME.into(), + }; + + assert!( + open_inference( + Some(connector), + Some(local), + Some(hosted), + &["claude-opus-5-5", "local/llama-8b", "hosted/deepseek-chat"], + ) + .is_ok() + ); + + let connector_port = Arc::new(StubPort) as Arc; + let local_port = Arc::new(StubPort) as Arc; + let hosted_port = Arc::new(StubPort) as Arc; + let routed = RoutedInferencePort::new( + Some(Arc::clone(&connector_port)), + vec![ + (DEFAULT_LOCAL_MODEL_PREFIX.to_owned(), Arc::clone(&local_port)), + (DEFAULT_HOSTED_MODEL_PREFIX.to_owned(), Arc::clone(&hosted_port)), + ], + ); + assert!(Arc::ptr_eq( + routed.route("claude-opus-5-5").unwrap(), + &connector_port + )); + assert!(Arc::ptr_eq( + routed.route("local/llama-8b").unwrap(), + &local_port + )); + assert!(Arc::ptr_eq( + routed.route("hosted/deepseek-chat").unwrap(), + &hosted_port + )); + + let clashing_local = LocalBinding { + endpoint: "127.0.0.1:9".parse().unwrap(), + model_prefix: "shared/".into(), + caller_runtime_id: TEST_RUNTIME.into(), + }; + let clashing_hosted = HostedBinding { + base_url: "https://api.example.test".into(), + key_path: hosted_key, + model_prefix: "shared/".into(), + caller_runtime_id: TEST_RUNTIME.into(), + }; + assert!(matches!( + open_inference(None, Some(clashing_local), Some(clashing_hosted), &["shared/x"]), + Err(ControllerOpenError::SharedModelPrefix { prefix }) if prefix == "shared/" + )); + } + + /// Spec test 12. + #[test] + fn a_model_prefix_routes_a_lane_to_its_port() { + let claimed = Arc::new(StubPort) as Arc; + let connector = Arc::new(StubPort) as Arc; + let routed = RoutedInferencePort::new( + Some(Arc::clone(&connector)), + vec![("local/".to_owned(), Arc::clone(&claimed))], + ); + assert!(Arc::ptr_eq( + routed.route("local/llama-8b").unwrap(), + &claimed + )); + assert!(Arc::ptr_eq( + routed.route("claude-opus-5-5").unwrap(), + &connector + )); + assert!(Arc::ptr_eq( + routed.route("gpt-5.6-terra").unwrap(), + &connector + )); + } + + /// Spec test 13. + #[test] + fn an_unroutable_model_fails_at_open() { + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("controller.key"); + std::fs::write(&key, "routed-port-test-key").unwrap(); + let connector = || ConnectorBinding { + endpoint: "127.0.0.1:9".parse().unwrap(), + key_path: key.clone(), + caller_runtime_id: TEST_RUNTIME.into(), + }; + let local = || LocalBinding { + endpoint: "127.0.0.1:9".parse().unwrap(), + model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(), + caller_runtime_id: TEST_RUNTIME.into(), + }; + + assert!(matches!( + open_inference(None, Some(local()), None, &models("gpt-5.6-terra").each()), + Err(ControllerOpenError::UnroutableModel { .. }) + )); + // The connector serves any model no local or hosted prefix claims. + assert!( + open_inference(Some(connector()), None, None, &models("claude-haiku-5-5").each()).is_ok() + ); + assert!( + open_inference(Some(connector()), None, None, &models("claude-opus-5").each()).is_ok() + ); + assert!( + open_inference(Some(connector()), None, None, &models(TEST_MODEL).each()).is_ok(), + "a configuration where every model routes did not open" + ); + } + + /// Soul: an unroutable model is refused at `infer` as well as at open. + #[tokio::test] + async fn soul_routing_refuses_rather_than_falling_back() { + let connector = Arc::new(StubPort) as Arc; + let connector_only = RoutedInferencePort::new(Some(Arc::clone(&connector)), Vec::new()); + assert!(Arc::ptr_eq( + connector_only.route(TEST_MODEL).unwrap(), + &connector + )); + // A prefix that does not match, and no connector: the model has no + // owner and routes nowhere. + let unclaimed = RoutedInferencePort::new( + None, + vec![("hosted/".to_owned(), Arc::new(StubPort) as Arc)], + ); + assert!(unclaimed.route(TEST_MODEL).is_none()); + let prepared = + PreparedInference::prepare(TEST_RUNTIME, 4_102_444_800_000, prose_request("Say it.")) + .unwrap(); + for fault in [ + unclaimed + .prepare(prose_request("Say it.")) + .expect_err("an unroutable model prepared"), + unclaimed + .infer(prepared) + .await + .expect_err("an unroutable model inferred"), + ] { + assert!(fault.integrity_was_violated(), "{fault:?}"); + assert!( + fault.to_string().contains("no configured inference backend"), + "{fault:?}" + ); + } + } +} diff --git a/crates/ghostlight/src/sdk_inference.rs b/crates/ghostlight/src/sdk_inference.rs deleted file mode 100644 index 06f69df..0000000 --- a/crates/ghostlight/src/sdk_inference.rs +++ /dev/null @@ -1,2200 +0,0 @@ -//! 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, TokenUsage, - PreparedInference, REQUEST_EXPIRY, RESPONSE_TIMEOUT, ToolResultOracle, call_id_is_valid, - tool_name_is_valid, unix_ms, -}; -use async_trait::async_trait; -use model_connector::{InputItem, ReasoningEffort}; -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; - -#[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 reply's token usage summed over the models the run used. The whole -/// prompt is the fresh input plus both cache figures (Anthropic reports them -/// apart); the cached part is what was read from cache. A run that reported -/// no usage at all is `None`, never a zero. -fn sdk_usage(usage: &[SdkModelUsage]) -> Option { - if usage.is_empty() { - return None; - } - let sum = |field: fn(&SdkModelUsage) -> u64| usage.iter().map(field).sum::(); - Some(TokenUsage { - prompt: sum(|u| u.input_tokens) + sum(|u| u.cache_read_input_tokens) + sum(|u| u.cache_creation_input_tokens), - completion: sum(|u| u.output_tokens), - cached_prompt: Some(sum(|u| u.cache_read_input_tokens)), - }) -} - -/// 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 { - /// The sidecar's own `detail` text is never carried: the reason names the - /// failure and the fault's text is fixed per reason. - fn into_fault(self) -> InferenceFault { - let detail = match self { - Self::RateLimited => "SDK sidecar reported rate limited", - Self::Overloaded => "SDK sidecar reported overloaded", - Self::ServerError => "SDK sidecar reported a server error", - Self::ApiTimeout => "SDK sidecar reported an API timeout", - Self::AuthenticationFailed => "SDK sidecar reported authentication failed", - Self::OrgNotAllowed => "SDK sidecar reported organization not allowed", - Self::BillingError => "SDK sidecar reported a billing error", - Self::InvalidRequest => "SDK sidecar reported an invalid request", - Self::ModelNotFound => "SDK sidecar reported model not found", - Self::MaxOutputTokens => "SDK sidecar reported max output tokens", - Self::MaxBudgetUsd => "SDK sidecar reported max budget", - Self::ExecutionError => "SDK sidecar reported an execution error", - Self::Unknown => "SDK sidecar reported an unknown failure", - Self::ProtocolViolation => "SDK sidecar reported a protocol violation", - Self::ToolRegistrationFailed => "SDK sidecar reported tool registration failed", - Self::TurnCapRefused => "SDK sidecar reported the turn cap refused", - }; - 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, - /// The child could not be started. The entry file existed at open, so this - /// is an environment fault an operator must fix. - Spawn, -} - -/// 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); - } - let mut body = vec![0_u8; length]; - reader - .read_exact(&mut body) - .await - .map_err(|_| SidecarLinkError::Codec)?; - rmp_serde::from_slice(&body).map_err(|_| SidecarLinkError::Codec) -} - -fn encode_frame(frame: &SidecarFrame) -> Result, SidecarLinkError> { - let body = rmp_serde::to_vec_named(frame) - .map_err(|_| SidecarLinkError::Codec)?; - if body.len() > MAX_SIDECAR_FRAME_BYTES { - return Err(SidecarLinkError::Codec); - } - 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(|_| SidecarLinkError::Spawn)?; - let stdin = child - .stdin - .take() - .ok_or(SidecarLinkError::Spawn)?; - let stdout = child - .stdout - .take() - .ok_or(SidecarLinkError::Spawn)?; - 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 claims a model only when the sidecar is configured; the connector -/// serves `claude-` models on its own, and `open_inference` refuses a sidecar -/// whose prefix would take a connector model. -pub 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 struct SdkBinding { - pub sidecar_entry: PathBuf, - pub caller_runtime_id: String, - pub 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(_) => { - let _ = self.link.restart().await; - return Err(InferenceFault::new("the tool-result owner refused a tool call")); - } - } - } - SidecarFrame::Output { - query_id: seen, - events, - receipt, - } if seen == query_id => { - return assemble_output(&prepared, events, receipt, &answered); - } - SidecarFrame::Fault { - query_id: seen, - reason, - .. - } if seen == query_id => { - let _ = self.link.restart().await; - return Err(reason.into_fault()); - } - _ => { - 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") - } - SidecarLinkError::Spawn => InferenceFault::new("the SDK sidecar could not start"), - SidecarLinkError::Codec => { - InferenceFault::integrity_violation("the SDK sidecar's framing was invalid") - } - } -} - -/// 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; - let mut items = request.input.iter(); - let Some(InputItem::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 { - InputItem::AssistantText { text } => transcript.push(format!("assistant: {text}")), - InputItem::ToolCall { - name, arguments, .. - } => transcript.push(format!("tool call {name}: {arguments}")), - InputItem::ToolResult { output, .. } => { - transcript.push(format!("tool result: {output}")) - } - // A later user turn is a kernel refusal reopening the session; the - // transcript is already a textual replay of the conversation, so - // it rides there like every other turn. - InputItem::UserText { text } => transcript.push(format!("user: {text}")), - InputItem::ReasoningState { .. } => { - return Err(InferenceFault::integrity_violation( - "an SDK request carried provider reasoning state", - )); - } - } - } - 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.map(|effort| { - match effort { - ReasoningEffort::Low => "low", - ReasoningEffort::Medium => "medium", - ReasoningEffort::High => "high", - ReasoningEffort::Max => "max", - } - .to_owned() - }), - max_output_tokens: Some(request.max_output_tokens), - turn_cap, - }) -} - -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(|_| InferenceFault::new("the SDK receipt could not be encoded"))?; - let output = InferenceOutput::new(lowered, format!("sha256:{:x}", Sha256::digest(&receipt_bytes))); - Ok(match sdk_usage(&receipt.usage) { - Some(usage) => output.with_usage(usage), - None => output, - }) -} - -#[async_trait] -impl InferencePort for SdkInferencePort { - fn prepare(&self, request: InferenceRequest) -> Result { - PreparedInference::prepare( - &self.caller_runtime_id, - unix_ms()?.saturating_add(REQUEST_EXPIRY.as_millis() as u64), - request, - ) - } - - async fn infer(&self, request: PreparedInference) -> Result { - // Above every gate, so the lend is reclaimed on every exit path. An - // oracle left behind by a refused invocation would keep a dead lane's - // tool-result owner alive under a request id nothing will call again. - let oracle = self.take_oracle(&request.invocation.request.request_id); - 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 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, - /// The OpenAI-compatible ports (the loopback one and the hosted one), each - /// with its own claimed prefix carried beside it, so `route` can compare - /// lengths without a parallel field per port to keep in sync. - claims: Vec<(String, Arc)>, -} - -impl RoutedInferencePort { - pub(super) fn new( - connector: Option>, - sdk: Option>, - sdk_model_prefix: impl Into, - claims: Vec<(String, Arc)>, - ) -> Self { - Self { - connector, - sdk, - sdk_model_prefix: sdk_model_prefix.into(), - claims, - } - } - - /// The model name carries the transport. A prefixed model that no - /// configured port claims routes nowhere rather than falling back: a - /// fallback is what would make a typo in a model environment variable - /// silent. When more than one prefix matches, the longest claim wins, so a - /// local prefix that extends the SDK's own (`claude-local/` beside - /// `claude`) is unambiguous without either operator having to avoid the - /// other's namespace. - pub(super) fn route(&self, model: &str) -> Option<&Arc> { - // A prefix claims the model whether or not its port is configured: a - // claimed-but-unconfigured prefix refuses rather than falling back to - // the connector, which is what keeps a typo'd model prefix loud - // instead of silently reaching the wrong backend. - let local_claim = self - .claims - .iter() - .filter(|(prefix, _)| model.starts_with(prefix.as_str())) - .max_by_key(|(prefix, _)| prefix.len()) - .map(|(prefix, port)| (prefix.len(), port)); - // The SDK prefix claims only when the sidecar is configured: the - // connector serves `claude-` models too, so an unconfigured sidecar - // must leave them to it. - let sdk_claim = (self.sdk.is_some() && model.starts_with(&self.sdk_model_prefix)) - .then_some(self.sdk_model_prefix.len()); - match (local_claim, sdk_claim) { - (Some((local_len, local_port)), Some(sdk_len)) => { - if local_len >= sdk_len { - Some(local_port) - } else { - self.sdk.as_ref() - } - } - (Some((_, local_port)), None) => Some(local_port), - (None, Some(_)) => self.sdk.as_ref(), - (None, None) => 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( - "no configured inference backend claims the requested 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( - "no configured inference backend claims the requested 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::CommandId; - use crate::controllers::{ - ConnectorBinding, ControllerModels, ControllerOpenError, InferencePurpose, - OperationalOracle, RequestShape, catalog_tools, open_inference, tool_request, - }; - use crate::elaboration::{ - ElaborationLoopEvaluation, ElaborationOracle, SEED_ROUND_BUDGET, evaluate_elaboration_loop, - }; - use crate::patch::{ - RECORD_GAP_PATCH_TOOL, SUBMIT_PATCH_TOOL, kernel_speak_entry, patch_tools, - }; - use crate::{AffordanceId, AffordanceSnapshot}; - use model_connector::ToolDefinition; - 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![InputItem::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![InputItem::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 are not a JSON object; recorded as a gap, nothing captured".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.requires_recovery(), "{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); - } - - /// The SDK lane reports the run's tokens summed over its models: the whole - /// prompt is fresh input plus both cache figures, the cached part is the - /// cache read, and a run that reported nothing is `None`, not a zero. - #[tokio::test] - async fn the_sdk_receipts_token_counts_reach_inference_output() { - 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 mut two_models = material(); - two_models.usage = vec![ - SdkModelUsage { - model: TEST_MODEL.into(), - input_tokens: 11, - output_tokens: 5, - cache_read_input_tokens: 3, - cache_creation_input_tokens: 2, - }, - SdkModelUsage { - model: "claude-haiku-5".into(), - input_tokens: 100, - output_tokens: 40, - cache_read_input_tokens: 7, - cache_creation_input_tokens: 0, - }, - ]; - let output = assemble_output(&prepared, events.clone(), two_models, &[]).unwrap(); - assert_eq!( - output.usage(), - Some(TokenUsage { prompt: 123, completion: 45, cached_prompt: Some(10) }) - ); - let mut none = material(); - none.usage = Vec::new(); - assert_eq!(assemble_output(&prepared, events, none, &[]).unwrap().usage(), None); - } - - /// 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 = PreparedInference::prepare(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.requires_recovery(), "{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(), - render_path: None, - }]; - 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![InputItem::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.requires_recovery(), "{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, - Vec::new(), - ); - 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-", - Vec::new(), - ); - 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()), None, None, &models("gpt-5.6-terra").each()), - Err(ControllerOpenError::UnroutableModel { .. }) - )); - // The connector alone serves `claude-` models. - assert!( - open_inference(Some(connector()), None, None, None, &models("claude-haiku-5-5").each()).is_ok() - ); - // A sidecar whose prefix would take a model the connector serves is - // refused at open, not left to steal the route. - assert!(matches!( - open_inference(Some(connector()), Some(sdk()), None, None, &models("claude-haiku-5-5").each()), - Err(ControllerOpenError::SidecarClaimsConnectorModel { .. }) - )); - // The same sidecar beside the connector is fine for a model the - // connector does not serve. - assert!( - open_inference(Some(connector()), Some(sdk()), None, None, &models("claude-opus-5").each()).is_ok() - ); - 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(), - }), - None, - None, - &models(TEST_MODEL).each(), - ), - Err(ControllerOpenError::SdkSidecarMissing { .. }) - )); - assert!( - open_inference(Some(connector()), Some(sdk()), None, None, &models(TEST_MODEL).each()).is_ok(), - "a configuration where every model routes did not open" - ); - } - - /// Soul: the port's `prepare` is `PreparedInference::prepare` and nothing else, so - /// everything but the expiry stamp is identical to what any other port - /// would have written for the same request. - #[test] - fn soul_the_sdk_port_prepares_the_identity_prepare_invocation_owns() { - let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); - let request = prose_request("Say something true."); - let through_port = port.prepare(request.clone()).expect("the port prepares"); - let through_owner = PreparedInference::prepare(TEST_RUNTIME, 4_102_444_800_000, request.clone()) - .expect("the owner prepares"); - assert_eq!(through_port.purpose, through_owner.purpose); - assert_eq!( - through_port.invocation.request, - through_owner.invocation.request - ); - assert_eq!( - through_port.invocation.native_request_sha256, - through_owner.invocation.native_request_sha256 - ); - assert_eq!( - through_port.invocation.provider_request_sha256, - through_owner.invocation.provider_request_sha256 - ); - assert_eq!( - through_port.invocation.caller_runtime_id, - through_owner.invocation.caller_runtime_id - ); - assert_eq!( - through_port.invocation.request.request_id, - through_owner.invocation.request.request_id - ); - } - - /// Soul: a frame naming a kind or a fault reason the wire does not carry is - /// refused by the codec, before the driver can act on a half-understood - /// frame. The closed enums are the gate, and this proves they are closed. - #[tokio::test] - async fn soul_an_unknown_kind_or_fault_reason_is_refused_at_read_frame() { - #[derive(Serialize)] - struct Bogus<'a> { - kind: &'a str, - query_id: u64, - reason: &'a str, - detail: &'a str, - } - async fn refuse(body: Vec) -> InferenceFault { - let mut framed = (body.len() as u32).to_be_bytes().to_vec(); - framed.extend_from_slice(&body); - let mut reader = std::io::Cursor::new(framed); - link_fault( - read_frame(&mut reader) - .await - .expect_err("an unknown shape decoded"), - ) - } - // A kind that is not on the wire. - let unknown_kind = rmp_serde::to_vec_named(&Bogus { - kind: "hallucination", - query_id: 1, - reason: "rate_limited", - detail: "", - }) - .unwrap(); - assert!(refuse(unknown_kind).await.integrity_was_violated()); - // A fault whose reason the disposition table does not name. Nothing may - // reach `into_fault` that the table has no row for. - let unknown_reason = rmp_serde::to_vec_named(&Bogus { - kind: "fault", - query_id: 1, - reason: "the_world_should_be_quarantined", - detail: "", - }) - .unwrap(); - assert!(refuse(unknown_reason).await.integrity_was_violated()); - } - - /// Soul: every reason the sidecar may name maps to the disposition the - /// plan's table assigns, and no TypeScript-named reason can quarantine the - /// world except the three the sidecar's own gates raise. - #[test] - fn soul_every_sidecar_reason_carries_its_named_disposition() { - use SidecarFaultReason::*; - for reason in [RateLimited, Overloaded, ServerError, ApiTimeout] { - let fault = reason.into_fault(); - assert!( - !fault.requires_recovery() && !fault.integrity_was_violated(), - "{reason:?} was not retryable" - ); - } - for reason in [ - AuthenticationFailed, - OrgNotAllowed, - BillingError, - InvalidRequest, - ModelNotFound, - MaxOutputTokens, - MaxBudgetUsd, - ExecutionError, - Unknown, - ] { - assert!( - reason.into_fault().requires_recovery(), - "{reason:?} was not recovery-required" - ); - } - for reason in [ProtocolViolation, ToolRegistrationFailed, TurnCapRefused] { - assert!( - reason.into_fault().integrity_was_violated(), - "{reason:?} did not violate integrity" - ); - } - } - - /// Soul: the lend gate refuses both mismatches, in both directions. - #[tokio::test] - async fn soul_a_lend_that_does_not_match_the_request_is_refused() { - // A tool request with no oracle lent. - let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); - let prepared = seed_prepared(&port, "Author the shortfall."); - let fault = port - .infer(prepared) - .await - .expect_err("a tool request ran without its lane's owner"); - assert!(fault.integrity_was_violated(), "{fault:?}"); - - // A prose request with an oracle lent. - let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); - let prepared = prose_prepared(&port, "Say something true."); - port.lend_tool_results( - &prepared, - Box::new(ElaborationOracle::new(&[], &[], SEED_ROUND_BUDGET)), - ); - let fault = port - .infer(prepared) - .await - .expect_err("a prose request ran with a tool-result owner"); - assert!(fault.integrity_was_violated(), "{fault:?}"); - } - - /// Soul: the take runs above every gate, so a refused `infer` reclaims the - /// lend rather than leaving a dead lane's tool-result owner in the map. - #[tokio::test] - async fn soul_a_lend_refused_before_the_query_is_still_reclaimed() { - let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); - let stale = PreparedInference::prepare(TEST_RUNTIME, 1_000, prose_request("Say something true.")) - .expect("the stale invocation builds"); - port.lend_tool_results( - &stale, - Box::new(ElaborationOracle::new(&[], &[], SEED_ROUND_BUDGET)), - ); - assert!(port.infer(stale.clone()).await.is_err()); - assert!( - port.oracles.lock().unwrap().is_empty(), - "the expiry gate left the lend behind" - ); - - // A caller-identity mismatch reclaims it too. - let other = SdkInferencePort::new(ScriptedLink::new(Vec::new()), "ghostlight-other"); - other.lend_tool_results( - &stale, - Box::new(ElaborationOracle::new(&[], &[], SEED_ROUND_BUDGET)), - ); - let fault = other - .infer(stale) - .await - .expect_err("a foreign caller's invocation ran"); - assert!(fault.integrity_was_violated(), "{fault:?}"); - assert!( - other.oracles.lock().unwrap().is_empty(), - "the caller-identity gate left the lend behind" - ); - - // A completed query does reclaim its own lend. - let link = ScriptedLink::new(vec![SidecarFrame::Output { - query_id: 1, - events: Vec::new(), - 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)), - ); - port.infer(prepared).await.expect("the empty query returns"); - assert!(port.oracles.lock().unwrap().is_empty()); - } - - /// Soul: the receipt is bound to the request without carrying a word of it. - /// Nothing the model was shown, and nothing it wrote, may reach a digest - /// that is persisted as provenance. - #[test] - fn soul_the_receipt_carries_no_prompt_or_tool_text() { - let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); - let secret = "the rain has teeth tonight"; - let prepared = prose_prepared(&port, secret); - let receipt = SdkInferenceReceipt { - schema_id: SDK_RECEIPT_SCHEMA.to_owned(), - request_id: prepared.invocation.request.request_id.clone(), - conversation_id: prepared.invocation.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: prepared.invocation.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: material().usage, - total_cost_usd_estimate: material().total_cost_usd_estimate, - }; - let bytes = rmp_serde::to_vec_named(&receipt).unwrap(); - let rendered = String::from_utf8_lossy(&bytes); - assert!(!rendered.contains(secret), "the receipt carries the prompt"); - assert!( - !rendered.contains(&prepared.invocation.request.instructions), - "the receipt carries the instructions" - ); - // And the digest the output carries is the digest of exactly this. - let output = assemble_output( - &prepared, - vec![SidecarEvent::Text { text: "ok".into() }], - material(), - &[], - ) - .unwrap(); - assert_eq!( - output.receipt_digest, - format!("sha256:{:x}", Sha256::digest(&bytes)) - ); - // A different stop reason is a different receipt. - let mut stopped = material(); - stopped.stop_reason = Some("max_tokens".into()); - assert_ne!( - output.receipt_digest, - assemble_output( - &prepared, - vec![SidecarEvent::Text { text: "ok".into() }], - stopped, - &[] - ) - .unwrap() - .receipt_digest - ); - } - - /// Soul: the order of the dispatched calls is part of the gate, not just - /// the set. A sidecar that answered the same two calls in the other order - /// put a different string in front of the model than the evaluator will - /// recompute. - #[tokio::test] - async fn soul_dispatched_calls_out_of_order_are_refused() { - let calls = [ - ("call-0", RECORD_GAP_PATCH_TOOL, r#"{"detail":"one"}"#), - ("call-1", RECORD_GAP_PATCH_TOOL, r#"{"detail":"two"}"#), - ]; - let mut outbound: Vec = calls - .iter() - .map(|(id, name, arguments)| tool_call_frame(id, name, arguments)) - .collect(); - outbound.push(SidecarFrame::Output { - query_id: 1, - events: vec![ - dispatched_event(calls[1].0, calls[1].1, calls[1].2), - dispatched_event(calls[0].0, calls[0].1, calls[0].2), - ], - receipt: material(), - }); - let link = ScriptedLink::new(outbound); - 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 fault = port - .infer(prepared) - .await - .expect_err("a reordered dispatch produced an output"); - assert!(fault.integrity_was_violated(), "{fault:?}"); - } - - fn assert_names_no(fault: &InferenceFault, canary: &str) { - let rendered = format!("{fault} | {fault:?}"); - assert!(!rendered.contains(canary), "{canary} leaked into {rendered}"); - } - - /// The SDK port's share of the no-input-text rule: text the sidecar sent, - /// a request's effort and a request's model - /// name each arrive as a canary, and none reaches the fault. The fault - /// type carries only fixed text, so this fails if a port ever routes a - /// computed string into it (through `Box::leak`, say). - #[tokio::test] - async fn an_sdk_fault_carries_no_text_it_was_handed() { - const CANARY: &str = "CANARY-sdk-91b6d0"; - - // The sidecar's own detail, for every reason it may name. - for reason in [ - SidecarFaultReason::RateLimited, - SidecarFaultReason::Overloaded, - SidecarFaultReason::ServerError, - SidecarFaultReason::ApiTimeout, - SidecarFaultReason::AuthenticationFailed, - SidecarFaultReason::OrgNotAllowed, - SidecarFaultReason::BillingError, - SidecarFaultReason::InvalidRequest, - SidecarFaultReason::ModelNotFound, - SidecarFaultReason::MaxOutputTokens, - SidecarFaultReason::MaxBudgetUsd, - SidecarFaultReason::ExecutionError, - SidecarFaultReason::Unknown, - SidecarFaultReason::ProtocolViolation, - SidecarFaultReason::ToolRegistrationFailed, - SidecarFaultReason::TurnCapRefused, - ] { - let link = ScriptedLink::new(vec![SidecarFrame::Fault { - query_id: 1, - reason, - detail: CANARY.into(), - }]); - let port = SdkInferencePort::new(link, TEST_RUNTIME); - let prepared = prose_prepared(&port, "Say something true."); - let fault = port.infer(prepared).await.expect_err("a fault frame produced an output"); - assert_names_no(&fault, CANARY); - } - - // A model no backend claims, prepared and inferred through the router. - let directory = tempfile::tempdir().unwrap(); - let entry = directory.path().join("main.js"); - std::fs::write(&entry, "// sidecar").unwrap(); - let routed = open_inference( - None, - Some(SdkBinding { - sidecar_entry: entry, - caller_runtime_id: TEST_RUNTIME.into(), - model_prefix: DEFAULT_SDK_MODEL_PREFIX.into(), - }), - None, - None, - &models(TEST_MODEL).each(), - ) - .expect("the SDK model routes"); - let request = tool_request( - CommandId::new(), - 0, - InferencePurpose::Persona, - CANARY, - "Respond only in natural prose.", - vec![InputItem::UserText { text: "Say something true.".into() }], - Vec::::new(), - RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false }, - ) - .expect("the request builds"); - let fault = routed.prepare(request).err().expect("an unroutable model prepared"); - assert_names_no(&fault, CANARY); - } - - /// Soul: the lowering's own gate table, every row. - #[test] - fn soul_lower_query_refuses_the_shapes_the_gate_table_names() { - let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME); - // `lower_query` reads the provider request off the prepared value, so - // the shapes it must refuse are written there directly. Nothing here - // asserts a digest; the identity tests own that. - let build = |input: Vec, effort: Option| { - let mut prepared = prose_prepared(&port, "Say something true."); - prepared.invocation.request.input = input; - prepared.invocation.request.reasoning_effort = effort; - prepared - }; - let user = |text: &str| InputItem::UserText { text: text.into() }; - - // Every typed effort lowers. - for effort in [ - ReasoningEffort::Low, - ReasoningEffort::Medium, - ReasoningEffort::High, - ReasoningEffort::Max, - ] { - assert!(lower_query(1, &build(vec![user("go")], Some(effort)), 1).is_ok()); - } - - // The first item must be user text. - for input in [ - vec![InputItem::AssistantText { text: "no".into() }], - Vec::new(), - ] { - let fault = lower_query(1, &build(input, None), 1) - .expect_err("a request that opens wrong lowered"); - assert!(fault.integrity_was_violated(), "{fault:?}"); - } - // A later user turn is a refusal reopening the session; it rides in - // the transcript like every other turn. - let SidecarFrame::Query { transcript, .. } = - lower_query(1, &build(vec![user("go"), user("again")], None), 1) - .expect("a reopened session lowers") - else { - panic!("not a query") - }; - assert_eq!(transcript, vec!["user: again".to_string()]); - - // A prior round renders exactly as the sidecar's fixed header expects. - let frame = lower_query( - 9, - &build( - vec![ - user("go"), - InputItem::AssistantText { - text: "thinking".into(), - }, - InputItem::ToolCall { - call_id: "call-0".into(), - name: "record_gap".into(), - arguments: "{}".into(), - }, - InputItem::ToolResult { - call_id: "call-0".into(), - output: "gap recorded".into(), - }, - ], - Some(ReasoningEffort::Medium), - ), - 4, - ) - .expect("a multi-item request lowers"); - let SidecarFrame::Query { - query_id, - prompt, - transcript, - turn_cap, - effort, - .. - } = frame - else { - panic!("the lowering produced something other than a query") - }; - assert_eq!( - (query_id, turn_cap, effort.as_deref()), - (9, 4, Some("medium")) - ); - assert_eq!(prompt, "go"); - assert_eq!( - transcript, - vec![ - "assistant: thinking".to_string(), - "tool call record_gap: {}".to_string(), - "tool result: gap recorded".to_string(), - ] - ); - } - - /// Soul: an unroutable model is refused at `infer` as well as at open, and - /// an SDK-only deployment needs no connector and therefore no credential. - #[tokio::test] - async fn soul_routing_refuses_rather_than_falling_back() { - assert_eq!(DEFAULT_SDK_MODEL_PREFIX, "claude"); - let stand_in = || { - Arc::new(SdkInferencePort::new( - ScriptedLink::new(Vec::new()), - TEST_RUNTIME, - )) as Arc - }; - // A connector with no sidecar serves `claude-` models itself. - let connector = stand_in(); - let connector_only = RoutedInferencePort::new( - Some(Arc::clone(&connector)), - None, - DEFAULT_SDK_MODEL_PREFIX, - Vec::new(), - ); - assert!(Arc::ptr_eq( - connector_only.route(TEST_MODEL).unwrap(), - &connector - )); - // A sidecar on a prefix that does not match, and no connector: the - // model has no owner and routes nowhere. - let connector_only = RoutedInferencePort::new(None, Some(stand_in()), "sdk/", Vec::new()); - assert!(connector_only.route(TEST_MODEL).is_none()); - let prepared = - PreparedInference::prepare(TEST_RUNTIME, 4_102_444_800_000, prose_request("Say it.")).unwrap(); - for fault in [ - connector_only - .prepare(prose_request("Say it.")) - .expect_err("an unroutable model prepared"), - connector_only - .infer(prepared) - .await - .expect_err("an unroutable model inferred"), - ] { - assert!(fault.integrity_was_violated(), "{fault:?}"); - assert!(fault.to_string().contains("no configured inference backend"), "{fault:?}"); - } - - // An SDK-only deployment opens with no connector binding at all, so no - // credential path is read. - let directory = tempfile::tempdir().unwrap(); - let entry = directory.path().join("main.js"); - std::fs::write(&entry, "// sidecar").unwrap(); - assert!( - open_inference( - None, - Some(SdkBinding { - sidecar_entry: entry, - caller_runtime_id: TEST_RUNTIME.into(), - model_prefix: DEFAULT_SDK_MODEL_PREFIX.into(), - }), - None, - None, - &models(TEST_MODEL).each(), - ) - .is_ok() - ); - } - - /// Soul: Ghostlight holds no credential, so no credential name appears in - /// the code that opens, routes, or drives this transport. - #[test] - fn soul_no_credential_name_appears_in_the_ports_own_source() { - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - // Assembled from halves so this test's own source is not a match. - let needles: [String; 8] = [ - format!(".{}", "credentials.json"), - format!("CLAUDE_CODE{}", "_OAUTH_TOKEN"), - format!(".{}", "claude.json"), - format!("apiKey{}", "Helper"), - format!("USER{}", "PROFILE"), - format!("home{}", "_dir"), - format!("GHOSTLIGHT_SDK{}", "_TOKEN"), - format!("GHOSTLIGHT_SDK{}", "_CREDENTIAL"), - ]; - let mut sources = Vec::new(); - for file in ["sdk_inference.rs", "controllers.rs"] { - let text = std::fs::read_to_string(root.join(file)) - .expect("the source reads") - .replace("\r\n", "\n"); - // Only the production half; a test may name what production must - // not. - let production = text - .split_once("\n#[cfg(test)]\nmod tests {") - .map(|(before, _)| before.to_owned()) - .unwrap_or(text); - for needle in &needles { - assert!( - !production.contains(needle.as_str()), - "{file} names {needle}" - ); - } - // `ANTHROPIC_API_KEY` is named once, in the port's doc comment, as - // the condition under which this port is deleted. It must appear - // nowhere that could read it. - let anthropic = format!("ANTHROPIC{}", "_"); - for line in production.lines() { - if line.contains(anthropic.as_str()) { - assert!( - line.trim_start().starts_with("///") || line.trim_start().starts_with("//"), - "{file} names an ANTHROPIC variable outside a comment: {line}" - ); - } - } - sources.push((file, production)); - } - // The one credential path that does exist belongs to the connector and - // is read only when a connector binding is built. - assert_eq!( - sources[1].1.matches("from_secret_file").count(), - 2, - "the connector key is read somewhere new" - ); - // The sidecar child inherits the ambient environment and is given none. - assert!( - !sources[0].1.contains(".env("), - "the port sets a child environment" - ); - assert!(!sources[0].1.contains("env_clear")); - } - - /// The Rust half of the sidecar's schema-grammar pair (spec test 17): - /// publishes every `parameters_json` the two catalogs actually emit, so the - /// sidecar's closed converter is tested against real strings rather than - /// hand-written ones. - #[test] - fn schema_fixtures_match_the_checked_in_sidecar_grammar() { - let granted = vec![AffordanceSnapshot { - id: AffordanceId::issue(), - entry: kernel_speak_entry(), - render_path: None, - }]; - let mut emitted: Vec<(String, String)> = patch_tools() - .into_iter() - .chain(catalog_tools("", &granted)) - .chain(catalog_tools("c3__", &granted)) - .map(|tool| (tool.name, tool.parameters_json)) - .collect(); - emitted.sort(); - emitted.dedup(); - let rendered = serde_json::to_string_pretty( - &emitted - .into_iter() - .map( - |(name, schema)| serde_json::json!({ "name": name, "parameters_json": schema }), - ) - .collect::>(), - ) - .unwrap(); - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../sidecar/claude-sdk/test/schemas.json"); - if std::env::var_os("GHOSTLIGHT_WRITE_SIDECAR_FIXTURES").is_some() { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(&path, format!("{rendered}\n")).unwrap(); - } - let on_disk = std::fs::read_to_string(&path).unwrap_or_else(|error| { - panic!( - "the sidecar schema fixture {} is missing ({error}); regenerate with GHOSTLIGHT_WRITE_SIDECAR_FIXTURES=1", - path.display() - ) - }); - assert_eq!( - on_disk.replace("\r\n", "\n"), - format!("{rendered}\n"), - "the emitted tool schemas drifted from the sidecar's converter fixture" - ); - } - - /// 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/crates/ghostlight/src/table.rs b/crates/ghostlight/src/table.rs index f408c96..d792c0a 100644 --- a/crates/ghostlight/src/table.rs +++ b/crates/ghostlight/src/table.rs @@ -3264,7 +3264,7 @@ mod tests { ("local_inference.rs", include_str!("local_inference.rs")), ("mailbox.rs", include_str!("mailbox.rs")), ("patch.rs", include_str!("patch.rs")), - ("sdk_inference.rs", include_str!("sdk_inference.rs")), + ("routed_inference.rs", include_str!("routed_inference.rs")), ("tool_schema.rs", include_str!("tool_schema.rs")), ("vault.rs", include_str!("vault.rs")), ]; diff --git a/notes/ghostlight-implementation-plan.md b/notes/ghostlight-implementation-plan.md index fca9742..2274a34 100644 --- a/notes/ghostlight-implementation-plan.md +++ b/notes/ghostlight-implementation-plan.md @@ -496,144 +496,9 @@ region-wide or global witness still discards a grouped cell's in-flight work for every constituent it touches, which is the debt this pass explicitly declined to pay. -### 11. Claude SDK inference port — landed +### 11. Inference routing and road follow-ups (historical) -Objective: run Ghostlight's inference lanes on the Claude subscription while -no Codex subscription or API budget exists, without moving the harness. - -Landed mechanism: two `InferencePort` implementors behind one -`RoutedInferencePort`, chosen per lane by the configured model's prefix -(`GHOSTLIGHT_SDK_MODEL_PREFIX`, default `claude`) — a `claude`-prefixed model -reaches `SdkInferencePort`, anything else reaches the existing -`CodexConnectorInferencePort` unchanged. `SdkInferencePort` spawns a Node -sidecar (`sidecar/claude-sdk/`, a TypeScript package on -`@anthropic-ai/claude-agent-sdk` `0.3.261`, `@msgpack/msgpack` `3.1.3`, and -`zod` `4.5.4`, all exact-pinned) as a child process over stdio, framed as a -4-byte big-endian length prefix plus `rmp_serde::to_vec_named` bytes. One -request is one SDK query with the system prompt replaced, built-ins -stripped, settings sources empty, the request's tools registered as -in-process SDK tools, a derived turn cap, and the request's model. -Execute-through: each tool call the model makes crosses the pipe and is -answered by `ToolResultOracle`, one trait with four implementors -(`InterpreterOracle`, `OperationalOracle`, `GroupedOracle`, -`ElaborationOracle`) — each is the lane's own evaluator fold, extracted -whole into a free function (`interpreter_tool_result`, -`operational_tool_result`, `grouped_tool_result`, and the already-factored -`apply_tool_call`) and replayed over `completed` at construction, so the -string handed to the model is the same one re-derivation will recompute. -The sidecar computes no tool result itself. - -One free function, `prepare_invocation`, is the sole owner of prepared -identity for both ports; `ControllerRunner::open` is injection-only — -`with_test_ports` is gone, and `open` takes `Arc`, -`Arc`, and `ControllerModels` and nothing -transport-specific. `runtime::open_controller` builds `ConnectorBinding` -and `SdkBinding` from the environment and calls `open_inference`, then -`open_controller_work`, then `ControllerRunner::open`; `open_inference` -routes every one of the five `ControllerModels` at open time and refuses a -model no configured backend claims (`ControllerOpenError::UnroutableModel`) -or a sidecar entry that is not a file -(`ControllerOpenError::SdkSidecarMissing`) before the first tick, not after. - -Environment: `GHOSTLIGHT_SDK_SIDECAR` (the built sidecar entry path; its -absence means no SDK binding, not a default path) and -`GHOSTLIGHT_SDK_MODEL_PREFIX` (default `claude`) are read once in -`runtime::open_controller`. `GHOSTLIGHT_CONTROLLER_CREDENTIAL` is no longer -unconditionally required — an SDK-only configuration reads no credential -path at all. `GHOSTLIGHT_WRITE_SIDECAR_FIXTURES` regenerates the checked-in -schema and frame fixtures the Rust and TypeScript sides pin against each -other; it is a fixture-authoring switch, not a runtime binding. - -Cut line held: no second identity scheme (`prepare_invocation` is the one -owner, both ports call it); no daemon, network port, or CultMesh surface for -the sidecar (it is a plain child process, restarted on fault, holding no -query state between queries); no credential handling in Ghostlight (the -sidecar inherits the ambient Claude Code login and this repo reads, copies, -forwards, or logs none of it); the connector port and its `execute` are -untouched; the port is chosen per lane by the configured model, with no mode -flag. Two forks the original design did not anticipate: `ControllerRunner::open` -became injection-only rather than keeping a `#[cfg(test)]` twin, because -removing the two transport-specific parameters made the twin's only purpose -vanish; and the turn cap rides on the oracle (`remaining_rounds`) rather than -on `InferencePurpose`, because the elaboration and seed lanes share one -purpose but carry different round budgets. - -Named liabilities, stated where `SdkInferencePort` is defined, not hidden in -the lowering: - -- The receipt is the SDK's message, not wire bytes. Its identity half is - computed from the invocation Ghostlight already holds; 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. -- A prior round's conversation reaches the model as prose, not as typed - turns. The SDK owns the assistant side of its own transcript, so typed - `tool_call`/`tool_result` turns from an earlier round cannot be replayed - into it; they are rendered as strings under one fixed header and appended - to the prompt. -- The Zod validation of a tool call's arguments happens in the sidecar - before the handler runs, so a model's undecodable arguments never reach - Rust as an argument string the oracle can fold over; the sidecar reports - a normal dispatched tool call and Rust's own evaluator recomputes the - decode failure as an ordinary gap — on the connector path the same - failure is a gap recorded by the evaluator directly. Both are gaps; the - divergence in exactly which layer detects an undecodable argument can - only reach a later round's prompt through the prose transcript. -- `error_max_turns` handling is inferred from the SDK's own documentation, - not observed: the sidecar is written to catch the throw the TypeScript - SDK performs after yielding the error result, assemble the events already - collected, and emit a normal `Output` whose receipt records - `subtype: "error_max_turns"`, so the lane sees one ordinary round and - proceeds rather than faulting. No live query has exercised this path. -- Because the turn cap is the lane's *remaining* round budget and the lane - still counts rounds even when the cap is not reached, a lane whose model - never terminates in one turn can spend a triangular number of turns across - a round sequence (seed: 24+23+…, bounded by `SEED_ROUND_BUDGET`) against - the connector's flat per-round cost. This is unmeasured: no live run has - produced a number to weigh it against. - -The SDK port has since carried the road runs recorded in the handoff (runs 8 -to 12, through the sidecar, the only live provider). The ad-hoc smoke that -drove them was deleted with the tick driver in the play agent's Cut 1 -(`d69e9d4`). No live smoke exists until the play agent's gate. - -Exit condition, unchanged from the port's own doc comment: 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 `SdkInferencePort` is deleted rather than -extended, keeping `RoutedInferencePort` and swapping what it routes to. -Rejected: a backend inside CodexConnector (a deliberately isolated Codex -fork). - -One validator on both transports: the sidecar's schema conversion is loose -(every property optional, unknown keys kept), so the arguments the model -emitted reach Rust's decoder unstripped and a refused argument is the gap -the evaluator already records, on the SDK path exactly as on the connector -path. Residual: a property whose value has the wrong type reaches Rust as -absent rather than as the wrong value, because the SDK derives the -advertised tool schema from the same object and refuses a dynamic -pass-through; the decoder reports it as missing. The result-subtype mapping -(`error_max_turns` is an output; every error subtype a named fault) is -tested in the sidecar without a credential. - -Road follow-ups, 2026-09-10, from the first two SDK-backed seeded runs -(`notes/local-live-smoke.md`, "Claude SDK route"): the sidecar's schema -conversion now carries every field `description` through to the advertised -tool schema (it dropped all of them, so the `claude` lane saw bare types); -`due` describes itself as a clock reading and both authoring prompts print -the clock, because the model wrote twelve commitments due at or before a -clock it was never shown; `declare_subject` states the grant rule at the -point of use; `apply_tool_call` logs each raw tool call at debug so a refused -patch is diagnosed from what the model sent. A kernel refusal now continues -the same conversation instead of opening a fresh draft: `Refusal { after_round, -mismatches }` rows on both authoring checkpoints (`controller_work.v12`; -prior rows refused, not migrated), the refusal rendered as the next user turn -after the rounds that earned it, and the draft rebuilt by one `DraftFold` -shared by the evaluator and the oracle from the calls after it. The harness -takes the connector binding only when `GHOSTLIGHT_CONTROLLER_CONNECTOR` is -set, so an all-`claude` run needs no connector. +(The Agent SDK sidecar transport documented here was later removed; `RoutedInferencePort` routes prefix-claimed `local/` and `hosted/` lanes and falls through to the connector.) From run 2: the Interpreter's `speak` and `record_gap` cite the source by quoting it (`source_quote`), and the harness locates the quote and derives @@ -845,9 +710,8 @@ operation count sentence (line 459 still says twenty-nine; it is thirty and stays thirty), and Interpreter paragraph follow. Build budget: crate `ghostlight-dungeon` and `ghostlight-persona-projection` -tests on the Windows workstation as the proving host, sidecar schema -fixtures regenerated if the Interpreter tool set changes the sidecar's -fixture; the Linux release is Idunn's build and is not touched by this cut. +tests on the Windows workstation as the proving host; the Linux release is +Idunn's build and is not touched by this cut. Verification: kernel tests that a display lands `Seen { by }` on the co-located only, never on the actor, never on a subject elsewhere or on a diff --git a/notes/local-live-smoke.md b/notes/local-live-smoke.md index 757d944..c8fea56 100644 --- a/notes/local-live-smoke.md +++ b/notes/local-live-smoke.md @@ -1,4 +1,4 @@ -# Connector And Claude SDK Sidecar Bring-Up +# Connector Bring-Up No automated live smoke exists in this tree. The one real-model test left is the ignored `controllers::tests::real_local_model_cognition_modes_commit_speech` @@ -37,46 +37,3 @@ an output-schema request on haiku and a plain request on sonnet. Ghostlight's port is one shot and returns a typed fault (`InferenceFaultClass`) whose disposition says whether the owning flow may try again. - -## Claude SDK route - -`crates/ghostlight/src/sdk_inference.rs`'s `SdkInferencePort` gives any lane whose configured -model is `claude`-prefixed (matching `GHOSTLIGHT_SDK_MODEL_PREFIX`, default -`claude`) a second transport: a Node sidecar on the Claude Agent SDK instead of -the connector, so a session can run on the Claude subscription with no -connector budget. - -**Operator prerequisites, none of which Ghostlight performs:** - -1. Install the Claude Code CLI. -2. Sign in with `/login`, or mint a token with `claude setup-token`. -3. Verify the login with one plain `claude -p` query. - -The harness never reads, copies, forwards, or logs that credential; the -sidecar inherits it from the ambient environment the same way the CLI does. - -**Build the sidecar**, once the CLI login is verified: - -```bash -npm --prefix sidecar/claude-sdk install -npm run sdk:build -``` - -`npm run sdk:build` is the root `package.json` alias for -`npm --prefix sidecar/claude-sdk run build`, emitting -`sidecar/claude-sdk/dist/main.js`. - -**Environment**, in addition to the connector variables above: - -```bash -GHOSTLIGHT_SDK_SIDECAR='F:\Projects\Ghostlight\sidecar\claude-sdk\dist\main.js' -GHOSTLIGHT_SDK_MODEL_PREFIX=claude # optional; this is already the default -``` - - -`GHOSTLIGHT_SDK_SIDECAR`'s absence means no SDK binding at all: a -`claude`-prefixed lane model then routes to the connector, which serves the -`claude-*-5-5` models itself. With both bound, a model the connector serves -(`claude--5-5`) under the sidecar's prefix is refused at open -(`SidecarClaimsConnectorModel`) rather than stolen by the sidecar; a model -such as `claude-opus-5` still reaches the sidecar. diff --git a/package.json b/package.json index 287051d..8e6110d 100644 --- a/package.json +++ b/package.json @@ -3,10 +3,6 @@ "private": true, "version": "0.0.0", "description": "Ghostlight: the Rust kernel for socially situated agents.", - "scripts": { - "sdk:build": "npm --prefix sidecar/claude-sdk run build", - "sdk:test": "npm --prefix sidecar/claude-sdk test" - }, "devDependencies": { "inkjs": "^2.4.0" } diff --git a/sidecar/claude-sdk/package-lock.json b/sidecar/claude-sdk/package-lock.json deleted file mode 100644 index fd71505..0000000 --- a/sidecar/claude-sdk/package-lock.json +++ /dev/null @@ -1,1558 +0,0 @@ -{ - "name": "ghostlight-claude-sdk-sidecar", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "ghostlight-claude-sdk-sidecar", - "version": "0.1.0", - "dependencies": { - "@anthropic-ai/claude-agent-sdk": "0.3.261", - "@msgpack/msgpack": "3.1.3", - "zod": "4.5.4" - }, - "devDependencies": { - "@types/node": "24.13.3", - "typescript": "5.9.3" - }, - "engines": { - "node": ">=24 <25" - } - }, - "node_modules/@anthropic-ai/claude-agent-sdk": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.261.tgz", - "integrity": "sha512-CDG9z14JVKYRHjpp/g6zJ2k8xM5uSoRgjGdpTiK9woLDZxXtXcxV93ipCh55jQ3REj7M7H3GieMsETGZXB/ydw==", - "license": "SEE LICENSE IN README.md", - "engines": { - "node": ">=18.0.0" - }, - "optionalDependencies": { - "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.261", - "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.261", - "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.261", - "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.261", - "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.261", - "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.261", - "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.261", - "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.261" - }, - "peerDependencies": { - "@anthropic-ai/sdk": ">=0.93.0", - "@modelcontextprotocol/sdk": "^1.29.0", - "zod": "^4.0.0" - } - }, - "node_modules/@anthropic-ai/claude-agent-sdk-darwin-arm64": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.261.tgz", - "integrity": "sha512-oI8SPd6g+xUF6EnEqIInxz5CjSSJXoDlaqefjbSJvTFCawGGBhxlQs0g9jzsYou6Rdu+i2tJBToJZLsKSnN/0Q==", - "cpu": [ - "arm64" - ], - "license": "SEE LICENSE IN LICENSE.md", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@anthropic-ai/claude-agent-sdk-darwin-x64": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.261.tgz", - "integrity": "sha512-PODd45XbrKxwngebFmc60Xd68QDb7xCo+0toYTJKfFumU24b/JT2WpO5sTSfc5+fahd/P11q0uF5v9YeSjWmjg==", - "cpu": [ - "x64" - ], - "license": "SEE LICENSE IN LICENSE.md", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.261.tgz", - "integrity": "sha512-C+y3N3MD2ExrwrbCYcbLdM39VkbJkQKUv23oubvoZr0CtHiH2LESyUUC3JsUbHJ1TRKO8fbzLqvPkjZ9UsBIcw==", - "cpu": [ - "arm64" - ], - "libc": [ - "glibc" - ], - "license": "SEE LICENSE IN LICENSE.md", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.261.tgz", - "integrity": "sha512-BAUG2EremVyy8bA14jKF35VRJjGE2TqREpFerA0CRBWg9/sUJZVWdmIRXUiXCKh0MvenPRUJbEgwcHFllQETOw==", - "cpu": [ - "arm64" - ], - "libc": [ - "musl" - ], - "license": "SEE LICENSE IN LICENSE.md", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.261.tgz", - "integrity": "sha512-MdojjfN0HJHT0JMiZJ6rTj3/ODNi5OdY0py1JZmVVEVTYOdvgH6OG3oy9/BmmJTx0mp/BBCHbOGNpibtnqE+1g==", - "cpu": [ - "x64" - ], - "libc": [ - "glibc" - ], - "license": "SEE LICENSE IN LICENSE.md", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.261.tgz", - "integrity": "sha512-H7sCtM7X9OyQ+ZCEhh6TY/Z1i+5WIn8YyHRVJ2LrZRFOaszPeDbl1SzSxxuOd5ibwJZA9gx+2uQ78dx+bDkQUA==", - "cpu": [ - "x64" - ], - "libc": [ - "musl" - ], - "license": "SEE LICENSE IN LICENSE.md", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@anthropic-ai/claude-agent-sdk-win32-arm64": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.261.tgz", - "integrity": "sha512-zvZfec4+wDooqF/ZOI3lthgq9WfZLIrSserS6tULpBqCLKNRbTIpARDcljY7SrRuMGb3Ex+LFn/yXazgajpwzg==", - "cpu": [ - "arm64" - ], - "license": "SEE LICENSE IN LICENSE.md", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@anthropic-ai/claude-agent-sdk-win32-x64": { - "version": "0.3.261", - "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.261.tgz", - "integrity": "sha512-tepSwNpNsl4tyDdJ1+YcRXeY7VZNirPqpCtKDuh2YVwDkMfzQevCqojURtACAdLwI8BUXeOGaecwRbh3zoSUtA==", - "cpu": [ - "x64" - ], - "license": "SEE LICENSE IN LICENSE.md", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@anthropic-ai/sdk": { - "version": "0.124.0", - "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.124.0.tgz", - "integrity": "sha512-cN5O8i9UVxHeOQAzj/XjshWXG8KiibJDw9OGpH2Z/eR3n/RBxdoLxDJOcfqAJWvjaMDFfHTBADU04hWRJVkDyA==", - "license": "MIT", - "peer": true, - "dependencies": { - "json-schema-to-ts": "^3.1.1", - "standardwebhooks": "^1.0.0" - }, - "bin": { - "anthropic-ai-sdk": "bin/cli" - }, - "peerDependencies": { - "zod": "^3.25.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "zod": { - "optional": true - } - } - }, - "node_modules/@babel/runtime": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", - "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@hono/node-server": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.1.tgz", - "integrity": "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=20" - }, - "peerDependencies": { - "hono": "^4" - } - }, - "node_modules/@modelcontextprotocol/sdk": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz", - "integrity": "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==", - "license": "MIT", - "peer": true, - "dependencies": { - "@hono/node-server": "^1.19.9 || ^2.0.5", - "ajv": "^8.17.1", - "ajv-formats": "^3.0.1", - "content-type": "^1.0.5", - "cors": "^2.8.5", - "cross-spawn": "^7.0.5", - "eventsource": "^3.0.2", - "eventsource-parser": "^3.0.0", - "express": "^5.2.1", - "express-rate-limit": "^8.2.1", - "hono": "^4.11.4", - "jose": "^6.1.3", - "json-schema-typed": "^8.0.2", - "pkce-challenge": "^5.0.0", - "raw-body": "^3.0.0", - "zod": "^3.25 || ^4.0", - "zod-to-json-schema": "^3.25.1" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@cfworker/json-schema": "^4.1.1", - "zod": "^3.25 || ^4.0" - }, - "peerDependenciesMeta": { - "@cfworker/json-schema": { - "optional": true - }, - "zod": { - "optional": false - } - } - }, - "node_modules/@msgpack/msgpack": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz", - "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==", - "license": "ISC", - "engines": { - "node": ">= 18" - } - }, - "node_modules/@stablelib/base64": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", - "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", - "license": "MIT", - "peer": true - }, - "node_modules/@types/node": { - "version": "24.13.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz", - "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~7.18.0" - } - }, - "node_modules/accepts": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", - "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "license": "MIT", - "peer": true, - "dependencies": { - "mime-types": "^3.0.0", - "negotiator": "^1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/ajv": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "license": "MIT", - "peer": true, - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ajv-formats": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", - "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "ajv": "^8.0.0" - }, - "peerDependencies": { - "ajv": "^8.0.0" - }, - "peerDependenciesMeta": { - "ajv": { - "optional": true - } - } - }, - "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", - "license": "MIT", - "peer": true, - "dependencies": { - "bytes": "^3.1.2", - "content-type": "^2.0.0", - "debug": "^4.4.3", - "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", - "on-finished": "^2.4.1", - "qs": "^6.15.2", - "raw-body": "^3.0.2", - "type-is": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/body-parser/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", - "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "license": "MIT", - "peer": true, - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/content-disposition": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", - "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", - "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=6.6.0" - } - }, - "node_modules/cors": { - "version": "2.8.6", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", - "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", - "license": "MIT", - "peer": true, - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "license": "MIT", - "peer": true, - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "peer": true, - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", - "peer": true, - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT", - "peer": true - }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", - "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", - "license": "MIT", - "peer": true, - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT", - "peer": true - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/eventsource": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", - "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", - "license": "MIT", - "peer": true, - "dependencies": { - "eventsource-parser": "^3.0.1" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/eventsource-parser": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", - "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/express": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", - "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", - "license": "MIT", - "peer": true, - "dependencies": { - "accepts": "^2.0.0", - "body-parser": "^2.2.1", - "content-disposition": "^1.0.0", - "content-type": "^1.0.5", - "cookie": "^0.7.1", - "cookie-signature": "^1.2.1", - "debug": "^4.4.0", - "depd": "^2.0.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "finalhandler": "^2.1.0", - "fresh": "^2.0.0", - "http-errors": "^2.0.0", - "merge-descriptors": "^2.0.0", - "mime-types": "^3.0.0", - "on-finished": "^2.4.1", - "once": "^1.4.0", - "parseurl": "^1.3.3", - "proxy-addr": "^2.0.7", - "qs": "^6.14.0", - "range-parser": "^1.2.1", - "router": "^2.2.0", - "send": "^1.1.0", - "serve-static": "^2.2.0", - "statuses": "^2.0.1", - "type-is": "^2.0.1", - "vary": "^1.1.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/express-rate-limit": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.0.tgz", - "integrity": "sha512-hOwV7WOxXfjRpAM1DSJWZDXx3GhplwD8IfwuwvogD8i1Qnkgosw/H45s4ZnFAUHDAhPjlY9hLBvJhKmGMyY26g==", - "license": "MIT", - "peer": true, - "dependencies": { - "debug": "^4.4.3", - "ip-address": "^10.2.0" - }, - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/express-rate-limit" - }, - "peerDependencies": { - "express": ">= 4.11" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "license": "MIT", - "peer": true - }, - "node_modules/fast-sha256": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", - "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", - "license": "Unlicense", - "peer": true - }, - "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause", - "peer": true - }, - "node_modules/finalhandler": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", - "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", - "license": "MIT", - "peer": true, - "dependencies": { - "debug": "^4.4.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "on-finished": "^2.4.1", - "parseurl": "^1.3.3", - "statuses": "^2.0.1" - }, - "engines": { - "node": ">= 18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", - "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "license": "MIT", - "peer": true, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", - "peer": true, - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", - "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", - "license": "MIT", - "peer": true, - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/hono": { - "version": "4.13.7", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz", - "integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=16.9.0" - } - }, - "node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/iconv-lite": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", - "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC", - "peer": true - }, - "node_modules/ip-address": { - "version": "10.7.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.0.tgz", - "integrity": "sha512-BGFsyJd5mpXp3rK6jIdADLNgpJUK1jnjzvYF8lK+VyDab9JAmqN0YOKDdP17HlgKb2+ehPgDc8EtnRLbGCAMhA==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 12" - } - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/is-promise": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", - "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", - "license": "MIT", - "peer": true - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "license": "ISC", - "peer": true - }, - "node_modules/jose": { - "version": "6.2.12", - "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", - "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", - "license": "MIT", - "peer": true, - "funding": { - "url": "https://github.com/sponsors/panva" - } - }, - "node_modules/json-schema-to-ts": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", - "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/runtime": "^7.18.3", - "ts-algebra": "^2.0.0" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "license": "MIT", - "peer": true - }, - "node_modules/json-schema-typed": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", - "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", - "license": "BSD-2-Clause", - "peer": true - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/media-typer": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", - "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/merge-descriptors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", - "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/mime-db": { - "version": "1.54.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", - "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", - "license": "MIT", - "peer": true, - "dependencies": { - "mime-db": "^1.54.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT", - "peer": true - }, - "node_modules/negotiator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", - "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", - "license": "MIT", - "peer": true, - "dependencies": { - "content-type": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/negotiator/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "license": "MIT", - "peer": true, - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "peer": true, - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/path-to-regexp": { - "version": "8.4.2", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", - "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", - "license": "MIT", - "peer": true, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/pkce-challenge": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", - "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=16.20.0" - } - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "license": "MIT", - "peer": true, - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", - "license": "BSD-3-Clause", - "peer": true, - "dependencies": { - "es-define-property": "^1.0.1", - "side-channel": "^1.1.1" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", - "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/raw-body": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", - "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", - "license": "MIT", - "peer": true, - "dependencies": { - "bytes": "~3.1.2", - "http-errors": "~2.0.1", - "iconv-lite": "~0.7.0", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/router": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", - "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "debug": "^4.4.0", - "depd": "^2.0.0", - "is-promise": "^4.0.0", - "parseurl": "^1.3.3", - "path-to-regexp": "^8.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT", - "peer": true - }, - "node_modules/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", - "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "debug": "^4.4.3", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "fresh": "^2.0.0", - "http-errors": "^2.0.1", - "mime-types": "^3.0.2", - "ms": "^2.1.3", - "on-finished": "^2.4.1", - "range-parser": "^1.2.1", - "statuses": "^2.0.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/serve-static": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", - "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", - "license": "MIT", - "peer": true, - "dependencies": { - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "parseurl": "^1.3.3", - "send": "^1.2.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "license": "ISC", - "peer": true - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "license": "MIT", - "peer": true, - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/side-channel": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", - "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.4", - "side-channel-list": "^1.0.1", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", - "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", - "license": "MIT", - "peer": true, - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "license": "MIT", - "peer": true, - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "license": "MIT", - "peer": true, - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/standardwebhooks": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", - "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "@stablelib/base64": "^1.0.0", - "fast-sha256": "^1.3.0" - } - }, - "node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=0.6" - } - }, - "node_modules/ts-algebra": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", - "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", - "license": "MIT", - "peer": true - }, - "node_modules/type-is": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", - "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", - "license": "MIT", - "peer": true, - "dependencies": { - "content-type": "^2.0.0", - "media-typer": "^1.1.0", - "mime-types": "^3.0.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/type-is/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "7.18.2", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", - "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", - "dev": true, - "license": "MIT" - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "license": "ISC", - "peer": true, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC", - "peer": true - }, - "node_modules/zod": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.5.4.tgz", - "integrity": "sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, - "node_modules/zod-to-json-schema": { - "version": "3.25.2", - "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", - "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", - "license": "ISC", - "peer": true, - "peerDependencies": { - "zod": "^3.25.28 || ^4" - } - } - } -} diff --git a/sidecar/claude-sdk/package.json b/sidecar/claude-sdk/package.json deleted file mode 100644 index 4c104bb..0000000 --- a/sidecar/claude-sdk/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "ghostlight-claude-sdk-sidecar", - "version": "0.1.0", - "private": true, - "type": "module", - "description": "Ghostlight's Claude Agent SDK sidecar. Reads length-prefixed MessagePack frames on stdin, runs one SDK query, and answers every tool call by asking Rust. It computes nothing and holds no credential.", - "engines": { "node": ">=24 <25" }, - "scripts": { - "build": "tsc -p .", - "test": "node --experimental-strip-types --test \"test/**/*.test.ts\"" - }, - "dependencies": { - "@anthropic-ai/claude-agent-sdk": "0.3.261", - "@msgpack/msgpack": "3.1.3", - "zod": "4.5.4" - }, - "devDependencies": { "@types/node": "24.13.3", "typescript": "5.9.3" } -} diff --git a/sidecar/claude-sdk/src/frames.ts b/sidecar/claude-sdk/src/frames.ts deleted file mode 100644 index dbe5fa7..0000000 --- a/sidecar/claude-sdk/src/frames.ts +++ /dev/null @@ -1,158 +0,0 @@ -// The wire between Rust and this sidecar: a 4-byte big-endian length prefix -// followed by MessagePack with string keys, matching `rmp_serde::to_vec_named`. -// Rust owns the shapes; this file only encodes and decodes them. - -import { decode, encode } from "@msgpack/msgpack"; - -/** The connector's own frame cap. Rust refuses anything larger on its side too. */ -export const MAX_FRAME_BYTES = 1_052_672; - -export interface SidecarTool { - name: string; - description: string; - parameters_json: string; -} - -export type SidecarEvent = - | { kind: "text"; text: string } - | { - kind: "tool_call"; - call_id: string; - name: string; - arguments: string; - dispatched: boolean; - }; - -export interface SdkModelUsage { - model: string; - input_tokens: number; - output_tokens: number; - cache_read_input_tokens: number; - cache_creation_input_tokens: number; -} - -export interface SdkResultMaterial { - session_id: string; - result_uuid: string; - subtype: string; - stop_reason: string | null; - num_turns: number; - assistant_message_uuids: string[]; - assistant_request_ids: string[]; - usage: SdkModelUsage[]; - total_cost_usd_estimate: string; -} - -/** - * The closed set of failures this sidecar may name. It reports a reason; Rust - * assigns the disposition, so nothing here can quarantine the world. - */ -export type SidecarFaultReason = - | "rate_limited" - | "overloaded" - | "server_error" - | "api_timeout" - | "authentication_failed" - | "org_not_allowed" - | "billing_error" - | "invalid_request" - | "model_not_found" - | "max_output_tokens" - | "max_budget_usd" - | "execution_error" - | "unknown" - | "protocol_violation" - | "tool_registration_failed" - | "turn_cap_refused"; - -export type SidecarFrame = - | { - kind: "query"; - query_id: number; - model: string; - instructions: string; - prompt: string; - transcript: string[]; - tools: SidecarTool[]; - effort: string | null; - max_output_tokens: number | null; - turn_cap: number; - } - | { - kind: "tool_call"; - query_id: number; - call_id: string; - name: string; - arguments: string; - } - | { - kind: "tool_result"; - query_id: number; - call_id: string; - output: string; - } - | { - kind: "output"; - query_id: number; - events: SidecarEvent[]; - receipt: SdkResultMaterial; - } - | { - kind: "fault"; - query_id: number; - reason: SidecarFaultReason; - detail: string; - }; - -export function encodeFrame(frame: SidecarFrame): Uint8Array { - const body = encode(frame, { useBigInt64: false }); - if (body.length > MAX_FRAME_BYTES) { - throw new Error(`frame of ${body.length} bytes exceeds ${MAX_FRAME_BYTES}`); - } - const framed = new Uint8Array(4 + body.length); - new DataView(framed.buffer).setUint32(0, body.length, false); - framed.set(body, 4); - return framed; -} - -export function decodeFrameBody(body: Uint8Array): SidecarFrame { - const value = decode(body); - if (typeof value !== "object" || value === null || !("kind" in value)) { - throw new Error("a sidecar frame decoded to something without a kind"); - } - return value as SidecarFrame; -} - -/** Reassembles frames from an arbitrarily chunked byte stream. */ -export class FrameReader { - #buffer = new Uint8Array(0); - - push(chunk: Uint8Array): void { - const grown = new Uint8Array(this.#buffer.length + chunk.length); - grown.set(this.#buffer, 0); - grown.set(chunk, this.#buffer.length); - this.#buffer = grown; - } - - /** The next whole frame, or null while one is still arriving. */ - next(): SidecarFrame | null { - if (this.#buffer.length < 4) { - return null; - } - const length = new DataView( - this.#buffer.buffer, - this.#buffer.byteOffset, - 4, - ).getUint32(0, false); - if (length === 0 || length > MAX_FRAME_BYTES) { - throw new Error(`frame length ${length} is outside 1..=${MAX_FRAME_BYTES}`); - } - if (this.#buffer.length < 4 + length) { - return null; - } - const body = this.#buffer.subarray(4, 4 + length); - const frame = decodeFrameBody(body); - this.#buffer = this.#buffer.slice(4 + length); - return frame; - } -} diff --git a/sidecar/claude-sdk/src/main.ts b/sidecar/claude-sdk/src/main.ts deleted file mode 100644 index 4c119ad..0000000 --- a/sidecar/claude-sdk/src/main.ts +++ /dev/null @@ -1,517 +0,0 @@ -// Ghostlight's Claude Agent SDK sidecar. -// -// One query at a time, one child process for many queries. Every tool call is -// forwarded to Rust and answered by Rust: this process computes no tool result, -// reads no credential, logs no prompt, argument, or result, and writes nothing -// outside its own stdout. -// -// Operator prerequisites, none of which Ghostlight performs: install the Claude -// Code CLI, sign in with `/login` or mint a token with `claude setup-token`, -// verify with one plain `claude -p` query, then `npm --prefix sidecar/claude-sdk -// install` and `npm run sdk:build`. The SDK finds that login on its own through -// the ambient environment. Nothing in this repository reads, copies, forwards, -// or logs the credential. -// -// Runtime binding: `GHOSTLIGHT_SDK_SIDECAR` is this file's built path -// (`sidecar/claude-sdk/dist/main.js`) and `GHOSTLIGHT_SDK_MODEL_PREFIX` -// (default `claude`) is the model-name prefix that routes a lane here. - -import { - createSdkMcpServer, - query, - tool, - type Options, -} from "@anthropic-ai/claude-agent-sdk"; -import { - FrameReader, - encodeFrame, - type SdkModelUsage, - type SdkResultMaterial, - type SidecarEvent, - type SidecarFaultReason, - type SidecarFrame, - type SidecarTool, -} from "./frames.ts"; -import { toolInputSchema } from "./schema.ts"; -import { resolve } from "node:path"; -import { pathToFileURL } from "node:url"; - -const SERVER_NAME = "ghostlight"; -const QUALIFIED_PREFIX = `mcp__${SERVER_NAME}__`; -/** The header a prior round's rendered transcript is folded under. */ -const TRANSCRIPT_HEADER = - "Earlier turns in this same request, as they happened:"; -/** No deadline tighter than the Rust side's own response timeout. */ -const RENDEZVOUS_TIMEOUT_MS = 900_000; -/** The largest round budget any Ghostlight lane carries. */ -const MAX_TURN_CAP = 24; - -export class SidecarFault extends Error { - readonly reason: SidecarFaultReason; - - constructor(reason: SidecarFaultReason, detail: string) { - super(detail); - this.reason = reason; - } -} - -interface Dispatch { - call_id: string; - name: string; - arguments: string; -} - -/** One in-flight query's rendezvous with Rust. */ -export class QuerySession { - readonly dispatches: Dispatch[] = []; - readonly queryId: number; - readonly #pending = new Map void>(); - readonly #write: (frame: SidecarFrame) => void; - #nextCall = 0; - - constructor(queryId: number, write: (frame: SidecarFrame) => void) { - this.queryId = queryId; - this.#write = write; - } - - /** Sends one call to Rust and resolves when Rust answers it. */ - async ask(name: string, args: unknown): Promise { - const call_id = `c${this.#nextCall++}`; - const argumentsJson = JSON.stringify(args ?? {}); - this.dispatches.push({ call_id, name, arguments: argumentsJson }); - const answer = new Promise((resolve) => { - this.#pending.set(call_id, resolve); - }); - this.#write({ - kind: "tool_call", - query_id: this.queryId, - call_id, - name, - arguments: argumentsJson, - }); - return answer; - } - - answer(call_id: string, output: string): void { - const resolve = this.#pending.get(call_id); - if (!resolve) { - throw new SidecarFault( - "protocol_violation", - `a tool result arrived for the unissued call ${call_id}`, - ); - } - this.#pending.delete(call_id); - resolve(output); - } -} - -export function apiRetryReason(category: unknown): SidecarFaultReason { - switch (category) { - case "rate_limit": - return "rate_limited"; - case "overloaded": - return "overloaded"; - case "server_error": - return "server_error"; - case "authentication_failed": - return "authentication_failed"; - case "oauth_org_not_allowed": - return "org_not_allowed"; - case "billing_error": - return "billing_error"; - case "invalid_request": - return "invalid_request"; - case "model_not_found": - return "model_not_found"; - case "max_output_tokens": - return "max_output_tokens"; - default: - return "unknown"; - } -} - -export function resultReason( - subtype: string, - apiErrorStatus: unknown, -): SidecarFaultReason { - if (typeof apiErrorStatus === "number") { - if (apiErrorStatus === 429) { - return "rate_limited"; - } - if (apiErrorStatus >= 500) { - return "server_error"; - } - } - switch (subtype) { - case "error_max_budget_usd": - return "max_budget_usd"; - case "error_during_execution": - case "error_max_structured_output_retries": - return "execution_error"; - default: - return "unknown"; - } -} - -/** - * One `result` message's verdict: `null` when the round is an ordinary output, - * a fault otherwise. Exported so the whole subtype mapping is testable without - * a credential. - * - * `error_max_turns` is not a fault: the cap is the lane's own remaining round - * budget, so reaching it means the model spent turns the evaluator would also - * have allowed. The lane sees one ordinary round. - */ -export function resultFault(message: Record): SidecarFault | null { - const subtype = String(message.subtype ?? ""); - if (subtype === "success" || subtype === "error_max_turns") { - return null; - } - const errors = Array.isArray(message.errors) - ? (message.errors as unknown[]).map(String).join("; ") - : ""; - const category = Array.isArray(message.errors) ? undefined : message.error; - const reason = - category === undefined - ? resultReason(subtype, message.api_error_status) - : apiRetryReason(category); - return new SidecarFault(reason, `${subtype}: ${errors}`); -} - -function usageRows(modelUsage: unknown): SdkModelUsage[] { - if (typeof modelUsage !== "object" || modelUsage === null) { - return []; - } - return Object.entries(modelUsage as Record>).map( - ([model, row]) => ({ - model, - input_tokens: Number(row?.inputTokens ?? row?.input_tokens ?? 0), - output_tokens: Number(row?.outputTokens ?? row?.output_tokens ?? 0), - cache_read_input_tokens: Number( - row?.cacheReadInputTokens ?? row?.cache_read_input_tokens ?? 0, - ), - cache_creation_input_tokens: Number( - row?.cacheCreationInputTokens ?? row?.cache_creation_input_tokens ?? 0, - ), - }), - ); -} - -/** - * The `query()` options one frame lowers to. Exported so a test can assert the - * hygiene — no CLAUDE.md, no settings, no built-in tools, no persisted session - * — against a stub instead of a live query. - */ -export function lowerQuery( - frame: Extract, - session: QuerySession, -): { prompt: string; options: Options } { - if (frame.turn_cap < 1 || frame.turn_cap > MAX_TURN_CAP) { - throw new SidecarFault( - "turn_cap_refused", - `turn cap ${frame.turn_cap} is outside 1..=${MAX_TURN_CAP}`, - ); - } - const tools = frame.tools.map((entry: SidecarTool) => { - let schema; - try { - schema = toolInputSchema(entry.parameters_json, entry.name); - } catch (error) { - throw new SidecarFault("tool_registration_failed", String(error)); - } - return tool( - entry.name, - entry.description, - // `tool()` names a raw shape and the server it registers with takes a - // whole schema in the same slot. The whole object is what carries the - // looseness the one-validator rule needs: a raw shape is wrapped in a - // stripping `z.object` before the arguments are ever seen. - schema as unknown as Parameters[2], - async (args: unknown) => ({ - content: [ - { type: "text" as const, text: await session.ask(entry.name, args) }, - ], - }), - { alwaysLoad: true }, - ); - }); - const prompt = frame.transcript.length - ? `${frame.prompt}\n\n${TRANSCRIPT_HEADER}\n${frame.transcript.join("\n")}` - : frame.prompt; - const options: Record = { - systemPrompt: { type: "custom", prompt: frame.instructions }, - // No CLAUDE.md, no settings.json, no output styles, no built-in tools. - settingSources: [], - tools: [], - strictMcpConfig: true, - model: frame.model, - maxTurns: frame.turn_cap, - includePartialMessages: false, - persistSession: false, - }; - if (frame.effort) { - options.effort = frame.effort; - } - if (tools.length) { - options.mcpServers = { - [SERVER_NAME]: createSdkMcpServer({ - name: SERVER_NAME, - tools, - alwaysLoad: true, - timeout: RENDEZVOUS_TIMEOUT_MS, - }), - }; - options.allowedTools = [`${QUALIFIED_PREFIX}*`]; - } - return { prompt, options: options as unknown as Options }; -} - -function strip(name: string): string { - return name.startsWith(QUALIFIED_PREFIX) - ? name.slice(QUALIFIED_PREFIX.length) - : name; -} - -/** - * Walks the assistant messages in order and pairs each registered tool_use - * block with the dispatch it caused, so the ids Rust answered and the ids - * reported here are the same ids. - */ -export function assembleEvents( - messages: { content: unknown }[], - registered: Set, - dispatches: Dispatch[], -): SidecarEvent[] { - const events: SidecarEvent[] = []; - let taken = 0; - let undispatched = 0; - for (const message of messages) { - const blocks = Array.isArray(message.content) ? message.content : []; - for (const block of blocks as Record[]) { - if (block.type === "text" && typeof block.text === "string") { - events.push({ kind: "text", text: block.text }); - continue; - } - if (block.type !== "tool_use") { - continue; - } - const name = strip(String(block.name ?? "")); - if (registered.has(name)) { - const dispatch = dispatches[taken++]; - if (!dispatch || dispatch.name !== name) { - // No argument reaches this any more: the registered schema refuses - // nothing, so a call the model emits is a call the handler runs. - // What still reaches it is the call never offered to the handler at - // all — a permission decision or an abort taken above this server, a - // tool the server disabled, or a pairing where the assistant stream - // and the dispatch log disagree about order. - throw new SidecarFault( - "protocol_violation", - `a registered tool_use block for ${name} has no matching dispatch`, - ); - } - events.push({ kind: "tool_call", ...dispatch, dispatched: true }); - continue; - } - events.push({ - kind: "tool_call", - call_id: `u${undispatched++}`, - name, - arguments: JSON.stringify(block.input ?? {}), - dispatched: false, - }); - } - } - if (taken !== dispatches.length) { - throw new SidecarFault( - "protocol_violation", - "more tool calls were dispatched than the assistant messages report", - ); - } - return events; -} - -async function runQuery( - frame: Extract, - write: (frame: SidecarFrame) => void, - session: QuerySession, -): Promise { - const registered = new Set(frame.tools.map((entry) => entry.name)); - const { prompt, options } = lowerQuery(frame, session); - const assistant: { content: unknown }[] = []; - const material: SdkResultMaterial = { - session_id: "", - result_uuid: "", - subtype: "", - stop_reason: null, - num_turns: 0, - assistant_message_uuids: [], - assistant_request_ids: [], - usage: [], - total_cost_usd_estimate: "0", - }; - let sawResult = false; - const stream = query({ prompt, options }); - try { - for await (const message of stream as AsyncIterable>) { - if (message.type === "assistant") { - const inner = message.message as Record | undefined; - assistant.push({ content: inner?.content }); - if (typeof message.uuid === "string") { - material.assistant_message_uuids.push(message.uuid); - } - if (typeof message.request_id === "string") { - material.assistant_request_ids.push(message.request_id); - } - continue; - } - if (message.type === "system" && message.subtype === "api_retry") { - // The harness owns its own retries; only an exhausted one reaches a - // result, so this is recorded and not raised. - continue; - } - if (message.type !== "result") { - continue; - } - sawResult = true; - const subtype = String(message.subtype ?? ""); - material.session_id = String(message.session_id ?? ""); - material.result_uuid = String(message.uuid ?? ""); - material.subtype = subtype; - material.stop_reason = - typeof message.stop_reason === "string" ? message.stop_reason : null; - material.num_turns = Number(message.num_turns ?? 0); - material.usage = usageRows(message.modelUsage); - material.total_cost_usd_estimate = String(message.total_cost_usd ?? 0); - const fault = resultFault(message); - if (fault) { - throw fault; - } - } - } catch (error) { - // The TS SDK throws after yielding an error result. A result already - // collected for `error_max_turns` is the normal path, so only an - // unaccounted throw becomes a fault. - if (error instanceof SidecarFault) { - throw error; - } - if (!sawResult) { - throw new SidecarFault("execution_error", String(error)); - } - } - if (!sawResult) { - throw new SidecarFault("execution_error", "the SDK query produced no result"); - } - write({ - kind: "output", - query_id: frame.query_id, - events: assembleEvents(assistant, registered, session.dispatches), - receipt: material, - }); -} - -async function main(): Promise { - const reader = new FrameReader(); - const write = (frame: SidecarFrame) => { - process.stdout.write(encodeFrame(frame)); - }; - let live: QuerySession | null = null; - let running: Promise = Promise.resolve(); - - for await (const chunk of process.stdin) { - reader.push(chunk as Uint8Array); - for (;;) { - let frame: SidecarFrame | null; - try { - frame = reader.next(); - } catch (error) { - write({ - kind: "fault", - query_id: live?.queryId ?? 0, - reason: "protocol_violation", - detail: String(error), - }); - return; - } - if (!frame) { - break; - } - if (frame.kind === "query") { - if (live) { - write({ - kind: "fault", - query_id: frame.query_id, - reason: "protocol_violation", - detail: "a second query arrived while one was in flight", - }); - continue; - } - const opening = frame; - const session = new QuerySession(opening.query_id, write); - live = session; - running = (async () => { - try { - await runQuery(opening, write, session); - } catch (error) { - const fault = - error instanceof SidecarFault - ? error - : new SidecarFault("execution_error", String(error)); - write({ - kind: "fault", - query_id: opening.query_id, - reason: fault.reason, - detail: fault.message, - }); - } finally { - live = null; - } - })(); - void running; - continue; - } - if (frame.kind === "tool_result") { - if (!live || live.queryId !== frame.query_id) { - write({ - kind: "fault", - query_id: frame.query_id, - reason: "protocol_violation", - detail: "a tool result arrived outside its query", - }); - continue; - } - try { - live.answer(frame.call_id, frame.output); - } catch (error) { - const fault = - error instanceof SidecarFault - ? error - : new SidecarFault("protocol_violation", String(error)); - write({ - kind: "fault", - query_id: frame.query_id, - reason: fault.reason, - detail: fault.message, - }); - } - continue; - } - write({ - kind: "fault", - query_id: 0, - reason: "protocol_violation", - detail: `frame kind ${frame.kind} is not one this sidecar accepts`, - }); - } - } - await running; -} - -// Only run the loop when this file is the entry point, so the tests can import -// its pure halves without starting a stdin reader. -if ( - process.argv[1] && - import.meta.url === pathToFileURL(resolve(process.argv[1])).href -) { - await main(); -} diff --git a/sidecar/claude-sdk/src/schema.ts b/sidecar/claude-sdk/src/schema.ts deleted file mode 100644 index ef99264..0000000 --- a/sidecar/claude-sdk/src/schema.ts +++ /dev/null @@ -1,155 +0,0 @@ -// The JSON Schema grammar Ghostlight's one emitter produces, converted to the -// Zod object the SDK's `tool()` registers. -// -// The conversion exists for one reason: the model must see the same parameter -// schema on both transports, and the in-process MCP server derives the schema -// it advertises from this Zod object. It is not a validator. Rust's decoder is -// the one validator on both transports, so every object here is loose and every -// property catches: an extra key, a missing required property, and a mistyped -// value all reach the handler, travel to Rust unstripped, and become the gap -// the evaluator already records instead of a tool call the SDK answers itself. -// -// A construct outside the emitted grammar still throws. That is a registration -// failure, not an argument judgement: a schema this module cannot convert is a -// tool the model would otherwise be shown blind. - -import { z } from "zod"; - -type Json = Record; - -const FORBIDDEN = ["oneOf", "allOf", "not", "$ref"] as const; - -function isObject(value: unknown): value is Json { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -/** - * Wraps one property so it can never refuse the call. The catch value is - * static because Zod refuses to render a dynamic one as JSON Schema, and the - * advertised schema is the whole point of converting. A value the property's - * type refuses therefore arrives at Rust as an absent field, which its decoder - * reports the same way it reports any other missing field. - */ -function keep(schema: z.ZodTypeAny): z.ZodTypeAny { - return schema.catch(undefined as never); -} - -/** - * The text the emitter put beside a field is the model's only account of what - * the field means; the first SDK road run lost every description here and the - * model filled `due` blind. - */ -function convert(node: unknown, at: string): z.ZodTypeAny { - const converted = convertShape(node, at); - return isObject(node) && typeof node.description === "string" - ? converted.describe(node.description) - : converted; -} - -function convertShape(node: unknown, at: string): z.ZodTypeAny { - if (!isObject(node)) { - throw new Error(`${at}: schema node is not an object`); - } - for (const forbidden of FORBIDDEN) { - if (forbidden in node) { - throw new Error(`${at}: \`${forbidden}\` is outside the emitted grammar`); - } - } - if ("anyOf" in node) { - const branches = node.anyOf; - if (!Array.isArray(branches) || branches.length === 0) { - throw new Error(`${at}: anyOf must be a nonempty array`); - } - // The nullable shape the emitter uses for an optional argument. - if ( - branches.length === 2 && - isObject(branches[1]) && - branches[1].type === "null" - ) { - return convert(branches[0], `${at}/anyOf/0`).nullable(); - } - const converted = branches.map((branch, index) => - convert(branch, `${at}/anyOf/${index}`), - ); - if (converted.length === 1) { - return converted[0]!; - } - return z.union(converted as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]); - } - const kind = node.type; - if (typeof kind !== "string") { - throw new Error(`${at}: schema node names no type`); - } - switch (kind) { - case "object": - return objectSchema(node, at); - case "string": { - if ("const" in node) { - if (typeof node.const !== "string") { - throw new Error(`${at}: a string const must be a string`); - } - return z.literal(node.const); - } - if ("enum" in node) { - const values = node.enum; - if ( - !Array.isArray(values) || - values.length === 0 || - values.some((value) => typeof value !== "string") - ) { - throw new Error(`${at}: enum must be a nonempty array of strings`); - } - return z.enum(values as [string, ...string[]]); - } - return z.string(); - } - case "integer": { - let schema = z.number().int(); - if (typeof node.minimum === "number") { - schema = schema.min(node.minimum); - } - if (typeof node.maximum === "number") { - schema = schema.max(node.maximum); - } - return schema; - } - case "boolean": - return z.boolean(); - case "null": - return z.null(); - case "array": - return z.array(convert(node.items, `${at}/items`)); - default: - throw new Error(`${at}: type \`${kind}\` is outside the emitted grammar`); - } -} - -/** One object node, loose so an unknown key survives to Rust with its value. */ -function objectSchema(node: Json, at: string): z.ZodObject { - const properties = node.properties; - if (!isObject(properties)) { - throw new Error(`${at}: object without properties`); - } - const shape: Record = {}; - for (const name of Object.keys(properties).sort()) { - shape[name] = keep(convert(properties[name], `${at}/${name}`)); - } - return z.looseObject(shape); -} - -/** - * One tool's `parameters_json` as the schema `tool()` registers. Throws on any - * node outside the grammar the emitter produces. - */ -export function toolInputSchema(parametersJson: string, at: string): z.ZodObject { - let parsed: unknown; - try { - parsed = JSON.parse(parametersJson); - } catch (error) { - throw new Error(`${at}: parameters_json is not JSON (${String(error)})`); - } - if (!isObject(parsed) || parsed.type !== "object") { - throw new Error(`${at}: a tool's parameters must be an object schema`); - } - return objectSchema(parsed, at); -} diff --git a/sidecar/claude-sdk/test/frames.test.ts b/sidecar/claude-sdk/test/frames.test.ts deleted file mode 100644 index 884a19f..0000000 --- a/sidecar/claude-sdk/test/frames.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -// Spec test 18: the frame bytes Rust writes decode here, and the bytes this -// side encodes are byte-identical to Rust's. The `.bin` fixtures are written by -// the Rust test `frame_fixtures_match_the_checked_in_sidecar_bytes`. - -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; -import test from "node:test"; -import { - FrameReader, - MAX_FRAME_BYTES, - decodeFrameBody, - encodeFrame, - type SidecarFrame, -} from "../src/frames.ts"; - -function fixture(name: string): Uint8Array { - return new Uint8Array( - readFileSync(fileURLToPath(new URL(`./frames/${name}.bin`, import.meta.url))), - ); -} - -const NAMES = ["query", "tool_call", "tool_result", "output", "fault"]; - -test("every Rust frame fixture decodes and re-encodes to the same bytes", () => { - for (const name of NAMES) { - const bytes = fixture(name); - const frame = decodeFrameBody(bytes.subarray(4)); - assert.equal(frame.kind, name, `${name} decoded to the wrong kind`); - assert.deepEqual( - Array.from(encodeFrame(frame)), - Array.from(bytes), - `${name} did not re-encode to Rust's bytes`, - ); - } -}); - -test("the query fixture carries the fields the lowering reads", () => { - const frame = decodeFrameBody(fixture("query").subarray(4)) as Extract< - SidecarFrame, - { kind: "query" } - >; - assert.equal(frame.query_id, 7); - assert.equal(frame.model, "claude-opus-5"); - assert.equal(frame.turn_cap, 24); - assert.equal(frame.effort, "medium"); - assert.equal(frame.max_output_tokens, 4000); - assert.deepEqual(frame.transcript, ["assistant: thinking", "tool result: ok"]); - assert.equal(frame.tools.length, 1); - assert.equal(frame.tools[0]!.name, "submit"); -}); - -test("the output fixture reports dispatch honestly", () => { - const frame = decodeFrameBody(fixture("output").subarray(4)) as Extract< - SidecarFrame, - { kind: "output" } - >; - assert.deepEqual(frame.events[0], { kind: "text", text: "Done." }); - assert.deepEqual(frame.events[1], { - kind: "tool_call", - call_id: "call-0", - name: "submit", - arguments: "{}", - dispatched: true, - }); - assert.equal(frame.receipt.session_id, "session-one"); - assert.equal(frame.receipt.usage[0]!.output_tokens, 34); -}); - -test("a chunked stream reassembles into whole frames", () => { - const reader = new FrameReader(); - const stream = new Uint8Array([ - ...fixture("tool_call"), - ...fixture("tool_result"), - ]); - const seen: SidecarFrame[] = []; - for (let at = 0; at < stream.length; at += 3) { - reader.push(stream.subarray(at, Math.min(at + 3, stream.length))); - for (;;) { - const frame = reader.next(); - if (!frame) { - break; - } - seen.push(frame); - } - } - assert.deepEqual( - seen.map((frame) => frame.kind), - ["tool_call", "tool_result"], - ); -}); - -test("a length prefix outside the cap is refused", () => { - const reader = new FrameReader(); - const prefix = new Uint8Array(4); - new DataView(prefix.buffer).setUint32(0, MAX_FRAME_BYTES + 1, false); - reader.push(prefix); - assert.throws(() => reader.next()); -}); diff --git a/sidecar/claude-sdk/test/frames/fault.bin b/sidecar/claude-sdk/test/frames/fault.bin deleted file mode 100644 index 0cf3677..0000000 Binary files a/sidecar/claude-sdk/test/frames/fault.bin and /dev/null differ diff --git a/sidecar/claude-sdk/test/frames/output.bin b/sidecar/claude-sdk/test/frames/output.bin deleted file mode 100644 index 40d21ba..0000000 Binary files a/sidecar/claude-sdk/test/frames/output.bin and /dev/null differ diff --git a/sidecar/claude-sdk/test/frames/query.bin b/sidecar/claude-sdk/test/frames/query.bin deleted file mode 100644 index 02385e3..0000000 Binary files a/sidecar/claude-sdk/test/frames/query.bin and /dev/null differ diff --git a/sidecar/claude-sdk/test/frames/tool_call.bin b/sidecar/claude-sdk/test/frames/tool_call.bin deleted file mode 100644 index 631b07b..0000000 Binary files a/sidecar/claude-sdk/test/frames/tool_call.bin and /dev/null differ diff --git a/sidecar/claude-sdk/test/frames/tool_result.bin b/sidecar/claude-sdk/test/frames/tool_result.bin deleted file mode 100644 index 7a29358..0000000 Binary files a/sidecar/claude-sdk/test/frames/tool_result.bin and /dev/null differ diff --git a/sidecar/claude-sdk/test/lowering.test.ts b/sidecar/claude-sdk/test/lowering.test.ts deleted file mode 100644 index 41b3d8d..0000000 --- a/sidecar/claude-sdk/test/lowering.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -// Spec test 16: the hygiene the query options must carry, asserted against the -// same function `main.ts` uses. No credential, no network, no query. - -import assert from "node:assert/strict"; -import test from "node:test"; -import { QuerySession, lowerQuery, SidecarFault } from "../src/main.ts"; -import type { SidecarFrame } from "../src/frames.ts"; - -const EMPTY_SCHEMA = JSON.stringify({ - type: "object", - additionalProperties: false, - required: [], - properties: {}, -}); - -function queryFrame( - overrides: Partial> = {}, -): Extract { - return { - kind: "query", - query_id: 1, - model: "claude-opus-5", - instructions: "Author the shortfall.", - prompt: "Answer the deficit.", - transcript: [], - tools: [ - { name: "submit", description: "Submit the draft.", parameters_json: EMPTY_SCHEMA }, - { name: "record_gap", description: "Record a gap.", parameters_json: EMPTY_SCHEMA }, - ], - effort: "medium", - max_output_tokens: 4000, - turn_cap: 24, - ...overrides, - }; -} - -function session(frame: Extract): QuerySession { - return new QuerySession(frame.query_id, () => {}); -} - -test("lowers a query to SDK options that load nothing ambient", () => { - const frame = queryFrame(); - const { prompt, options } = lowerQuery(frame, session(frame)); - const raw = options as unknown as Record; - - assert.equal(prompt, frame.prompt, "a first round carried a transcript header"); - assert.deepEqual(raw.systemPrompt, { - type: "custom", - prompt: frame.instructions, - }); - assert.deepEqual(raw.settingSources, [], "settings sources were not emptied"); - assert.deepEqual(raw.tools, [], "built-in tools were not stripped"); - assert.equal(raw.strictMcpConfig, true); - assert.equal(raw.persistSession, false, "the caller's conversation would persist"); - assert.equal(raw.includePartialMessages, false); - assert.equal(raw.maxTurns, frame.turn_cap); - assert.equal(raw.model, frame.model); - assert.equal(raw.effort, frame.effort); - assert.deepEqual(raw.allowedTools, ["mcp__ghostlight__*"]); - - const servers = raw.mcpServers as Record>; - assert.ok(servers.ghostlight, "the ghostlight MCP server was not registered"); - const registered = servers.ghostlight.instance ?? servers.ghostlight; - assert.ok(registered, "the in-process server carries no instance"); -}); - -test("a request with no tools registers no MCP server", () => { - const frame = queryFrame({ tools: [], turn_cap: 1 }); - const { options } = lowerQuery(frame, session(frame)); - const raw = options as unknown as Record; - assert.equal(raw.mcpServers, undefined); - assert.equal(raw.allowedTools, undefined); - assert.equal(raw.maxTurns, 1); -}); - -test("a prior round's transcript is folded under one fixed header", () => { - const frame = queryFrame({ - transcript: ["assistant: thinking", "tool result: ok"], - }); - const { prompt } = lowerQuery(frame, session(frame)); - assert.equal( - prompt, - "Answer the deficit.\n\nEarlier turns in this same request, as they happened:\nassistant: thinking\ntool result: ok", - ); -}); - -test("a turn cap outside the lane budgets is refused", () => { - for (const turn_cap of [0, 25]) { - const frame = queryFrame({ turn_cap }); - assert.throws( - () => lowerQuery(frame, session(frame)), - (error: unknown) => - error instanceof SidecarFault && error.reason === "turn_cap_refused", - ); - } -}); - -test("a tool schema outside the emitted grammar refuses registration", () => { - const frame = queryFrame({ - tools: [ - { - name: "submit", - description: "Submit the draft.", - parameters_json: JSON.stringify({ oneOf: [{ type: "string" }] }), - }, - ], - }); - assert.throws( - () => lowerQuery(frame, session(frame)), - (error: unknown) => - error instanceof SidecarFault && error.reason === "tool_registration_failed", - ); -}); diff --git a/sidecar/claude-sdk/test/result.test.ts b/sidecar/claude-sdk/test/result.test.ts deleted file mode 100644 index 9ab4938..0000000 --- a/sidecar/claude-sdk/test/result.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Which `result` message becomes a round and which becomes a named fault. The -// mapping is the sidecar's whole judgement of a finished query, so it is -// asserted directly against the exported decision, with no credential, no -// network, and no `query()`. - -import assert from "node:assert/strict"; -import test from "node:test"; -import { apiRetryReason, resultFault, resultReason, SidecarFault } from "../src/main.ts"; - -function reasonOf(message: Record): string | null { - const fault = resultFault(message); - if (fault === null) { - return null; - } - assert.ok(fault instanceof SidecarFault); - return fault.reason; -} - -test("a spent turn cap is an ordinary output, not a fault", () => { - // The cap is the lane's own remaining round budget, so reaching it means the - // model spent turns the evaluator would also have allowed. - assert.equal(resultFault({ subtype: "error_max_turns", num_turns: 24 }), null); - assert.equal(resultFault({ subtype: "success" }), null); -}); - -test("every other result subtype carries its named fault", () => { - assert.equal(reasonOf({ subtype: "error_max_budget_usd" }), "max_budget_usd"); - assert.equal(reasonOf({ subtype: "error_during_execution" }), "execution_error"); - assert.equal( - reasonOf({ subtype: "error_max_structured_output_retries" }), - "execution_error", - ); - assert.equal(reasonOf({ subtype: "error_nobody_has_named_yet" }), "unknown"); -}); - -test("an API status outranks the subtype it arrived on", () => { - assert.equal( - reasonOf({ subtype: "error_during_execution", api_error_status: 429 }), - "rate_limited", - ); - assert.equal( - reasonOf({ subtype: "error_during_execution", api_error_status: 503 }), - "server_error", - ); - assert.equal( - reasonOf({ subtype: "error_during_execution", api_error_status: 400 }), - "execution_error", - ); - assert.equal(resultReason("error_during_execution", "429"), "execution_error"); -}); - -test("a retry category names the fault when the result carries one", () => { - const categories: [string, string][] = [ - ["rate_limit", "rate_limited"], - ["overloaded", "overloaded"], - ["server_error", "server_error"], - ["authentication_failed", "authentication_failed"], - ["oauth_org_not_allowed", "org_not_allowed"], - ["billing_error", "billing_error"], - ["invalid_request", "invalid_request"], - ["model_not_found", "model_not_found"], - ["max_output_tokens", "max_output_tokens"], - ["something_new", "unknown"], - ]; - for (const [category, reason] of categories) { - assert.equal(apiRetryReason(category), reason, category); - assert.equal( - reasonOf({ subtype: "error_during_execution", error: category }), - reason, - category, - ); - } -}); - -test("a fault's detail carries the subtype and the reported errors", () => { - const fault = resultFault({ - subtype: "error_during_execution", - errors: ["the pipe closed", "and stayed closed"], - }); - assert.ok(fault instanceof SidecarFault); - assert.equal(fault.reason, "execution_error"); - assert.equal(fault.message, "error_during_execution: the pipe closed; and stayed closed"); -}); diff --git a/sidecar/claude-sdk/test/schema.test.ts b/sidecar/claude-sdk/test/schema.test.ts deleted file mode 100644 index 473a58d..0000000 --- a/sidecar/claude-sdk/test/schema.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -// Spec test 17: every schema Ghostlight's one emitter actually produces -// converts, and everything outside that grammar throws. `schemas.json` is -// written by the Rust test `schema_fixtures_match_the_checked_in_sidecar_grammar`, -// so the two halves cannot drift apart. - -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; -import test from "node:test"; -import { z } from "zod"; -import { toolInputSchema } from "../src/schema.ts"; - -const emitted: { name: string; parameters_json: string }[] = JSON.parse( - readFileSync(fileURLToPath(new URL("./schemas.json", import.meta.url)), "utf8"), -); - -test("every emitted tool schema converts", () => { - assert.ok(emitted.length > 0, "the schema fixture is empty"); - for (const entry of emitted) { - const schema = toolInputSchema(entry.parameters_json, entry.name); - const declared = Object.keys( - JSON.parse(entry.parameters_json).properties as Record, - ).sort(); - assert.deepEqual(Object.keys(schema.shape).sort(), declared, entry.name); - } -}); - -test("a property's description reaches the advertised schema", () => { - const schema = toolInputSchema( - JSON.stringify({ - type: "object", - additionalProperties: false, - required: ["due", "kind"], - properties: { - due: { type: "integer", minimum: 0, maximum: 9, description: "a clock reading" }, - kind: { type: "string", enum: ["a"], description: "which shape" }, - }, - }), - "described", - ); - const advertised = z.toJSONSchema(schema, { io: "input" }) as { - properties: Record; - }; - assert.equal(advertised.properties.due?.description, "a clock reading"); - assert.equal(advertised.properties.kind?.description, "which shape"); -}); - -test("a converted schema carries every property's own type", () => { - const schema = toolInputSchema( - JSON.stringify({ - type: "object", - additionalProperties: false, - required: ["detail", "count", "flag", "choice", "maybe", "many"], - properties: { - detail: { type: "string" }, - count: { type: "integer", minimum: 1, maximum: 4 }, - flag: { type: "boolean" }, - choice: { type: "string", enum: ["a", "b"] }, - maybe: { anyOf: [{ type: "string" }, { type: "null" }] }, - many: { type: "array", items: { type: "string" } }, - }, - }), - "sample", - ); - const admitted = schema.parse({ - detail: "ok", - count: 2, - flag: true, - choice: "a", - maybe: null, - many: ["a"], - }) as Record; - assert.deepEqual(admitted, { - detail: "ok", - count: 2, - flag: true, - choice: "a", - maybe: null, - many: ["a"], - }); - - // A value outside a property's own type empties that property and nothing - // else. Rust decides what an absent field means. - const dropped = schema.parse({ detail: "ok", count: 9, choice: "c" }) as Record< - string, - unknown - >; - assert.equal(dropped.detail, "ok"); - assert.equal(dropped.count, undefined); - assert.equal(dropped.choice, undefined); -}); - -test("anything outside the grammar throws", () => { - const refused = [ - { oneOf: [{ type: "string" }] }, - { allOf: [{ type: "string" }] }, - { $ref: "#/definitions/thing" }, - { description: "no type at all" }, - { type: "number" }, - ]; - for (const node of refused) { - assert.throws( - () => - toolInputSchema( - JSON.stringify({ - type: "object", - additionalProperties: false, - required: ["field"], - properties: { field: node }, - }), - "refused", - ), - `${JSON.stringify(node)} was accepted`, - ); - } -}); - -test("an open object and a partly optional one convert and refuse nothing", () => { - // Openness and optionality are Rust's judgements, so neither is a - // registration failure here. - const open = toolInputSchema( - JSON.stringify({ type: "object", required: [], properties: {} }), - "open", - ); - assert.deepEqual(open.parse({ anything: 1 }), { anything: 1 }); - - const partial = toolInputSchema( - JSON.stringify({ - type: "object", - additionalProperties: false, - required: ["a"], - properties: { a: { type: "string" }, b: { type: "string" } }, - }), - "partial", - ); - assert.deepEqual(partial.parse({ b: "set" }), { b: "set" }); -}); diff --git a/sidecar/claude-sdk/test/schemas.json b/sidecar/claude-sdk/test/schemas.json deleted file mode 100644 index 1e90b8e..0000000 --- a/sidecar/claude-sdk/test/schemas.json +++ /dev/null @@ -1,210 +0,0 @@ -[ - { - "name": "acquire_knowledge", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"confidence\":{\"enum\":[\"doubted\",\"believed\",\"certain\"],\"type\":\"string\"},\"fact\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing fact\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"source\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"source\":{\"const\":\"witnessed\",\"type\":\"string\"}},\"required\":[\"source\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"source\":{\"const\":\"evidenced\",\"type\":\"string\"}},\"required\":[\"source\"],\"type\":\"object\"}]},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"fact\",\"source\",\"confidence\"],\"type\":\"object\"}" - }, - { - "name": "adjust_attitude", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"decay\":{\"anyOf\":[{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"},{\"type\":\"null\"}]},\"delta\":{\"maximum\":100,\"minimum\":-100,\"type\":\"integer\"},\"holder\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"toward\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"holder\",\"toward\",\"delta\",\"decay\"],\"type\":\"object\"}" - }, - { - "name": "admit", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"evidence\":{\"description\":\"an exact evidence receipt retrieved for this answer\",\"type\":\"string\"},\"holder\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"qty\":{\"maximum\":18446744073709551615,\"minimum\":1,\"type\":\"integer\"},\"resource\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"holder\",\"resource\",\"qty\",\"evidence\"],\"type\":\"object\"}" - }, - { - "name": "advance_pressure", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"by\":{\"maximum\":4294967295,\"minimum\":1,\"type\":\"integer\"},\"source\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"commitment\",\"type\":\"string\"},\"of\":{\"additionalProperties\":false,\"properties\":{\"key\":{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"the command id that created the commitment\",\"type\":\"string\"},\"index\":{\"maximum\":4294967295,\"minimum\":0,\"type\":\"integer\"}},\"required\":[\"command\",\"index\"],\"type\":\"object\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"key\"],\"type\":\"object\"}},\"required\":[\"from\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"dependency\",\"type\":\"string\"},\"of\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"resource\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"route\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"subject\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"}]}},\"required\":[\"from\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"subject\",\"type\":\"string\"},\"of\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"from\",\"of\"],\"type\":\"object\"}]},\"target\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"source\",\"target\",\"by\"],\"type\":\"object\"}" - }, - { - "name": "alter_cost", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"cost\":{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"},\"route\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"route\",\"cost\"],\"type\":\"object\"}" - }, - { - "name": "bind", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"resource\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"route\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"subject\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"}]}},\"required\":[\"subject\",\"target\"],\"type\":\"object\"}" - }, - { - "name": "c3__finish_without_proposal", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"}" - }, - { - "name": "c3__record_need", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"detail\":{\"description\":\"what the agent would need and does not have\",\"type\":\"string\"}},\"required\":[\"detail\"],\"type\":\"object\"}" - }, - { - "name": "c3__speak", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"text\":{\"description\":\"the utterance this invocation carries\",\"type\":\"string\"}},\"required\":[\"text\"],\"type\":\"object\"}" - }, - { - "name": "close_forum", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"grievance\":{\"description\":\"the grievance kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"}},\"required\":[\"grievance\"],\"type\":\"object\"}" - }, - { - "name": "close_office", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"institution\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"office\":{\"description\":\"the office's name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"}},\"required\":[\"institution\",\"office\"],\"type\":\"object\"}" - }, - { - "name": "close_route", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"route\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"route\"],\"type\":\"object\"}" - }, - { - "name": "communicate", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"fact\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing fact\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"speaker\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"to\":{\"anyOf\":[{\"const\":\"colocated\",\"type\":\"string\"},{\"additionalProperties\":false,\"properties\":{\"channel\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing channel\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"channel\"],\"type\":\"object\"}]}},\"required\":[\"speaker\",\"fact\",\"to\"],\"type\":\"object\"}" - }, - { - "name": "consume", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"holder\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"qty\":{\"maximum\":18446744073709551615,\"minimum\":1,\"type\":\"integer\"},\"resource\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"holder\",\"resource\",\"qty\"],\"type\":\"object\"}" - }, - { - "name": "create_commitment", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"checks\":{\"items\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"at\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"precondition\":{\"const\":\"present\",\"type\":\"string\"}},\"required\":[\"precondition\",\"at\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"precondition\":{\"const\":\"reachable\",\"type\":\"string\"},\"to\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"within\":{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"precondition\",\"to\",\"within\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"at_least\":{\"maximum\":18446744073709551615,\"minimum\":1,\"type\":\"integer\"},\"precondition\":{\"const\":\"holds\",\"type\":\"string\"},\"resource\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"precondition\",\"resource\",\"at_least\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"description\":\"the authority kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"over\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"over\":{\"const\":\"subject\",\"type\":\"string\"},\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"over\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"over\":{\"const\":\"place_subtree\",\"type\":\"string\"},\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"over\",\"ref\"],\"type\":\"object\"}]},\"precondition\":{\"const\":\"authorized\",\"type\":\"string\"}},\"required\":[\"precondition\",\"over\",\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"grievance\":{\"description\":\"the grievance kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"precondition\":{\"const\":\"has_standing\",\"type\":\"string\"}},\"required\":[\"precondition\",\"grievance\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"at_least\":{\"enum\":[\"doubted\",\"believed\",\"certain\"],\"type\":\"string\"},\"fact\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing fact\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"precondition\":{\"const\":\"knows\",\"type\":\"string\"}},\"required\":[\"precondition\",\"fact\",\"at_least\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"precondition\":{\"const\":\"can_broadcast\",\"type\":\"string\"},\"via\":{\"anyOf\":[{\"const\":\"colocated\",\"type\":\"string\"},{\"additionalProperties\":false,\"properties\":{\"channel\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing channel\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"channel\"],\"type\":\"object\"}]}},\"required\":[\"precondition\",\"via\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"precondition\":{\"const\":\"can_reach\",\"type\":\"string\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"via\":{\"anyOf\":[{\"const\":\"colocated\",\"type\":\"string\"},{\"additionalProperties\":false,\"properties\":{\"channel\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing channel\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"channel\"],\"type\":\"object\"}]}},\"required\":[\"precondition\",\"subject\",\"via\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"routine\",\"obligation\",\"goal\"],\"type\":\"string\"},\"precondition\":{\"const\":\"committed\",\"type\":\"string\"},\"to\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"precondition\",\"to\",\"kind\"],\"type\":\"object\"}]},\"type\":\"array\"},\"counterparty\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},{\"type\":\"null\"}]},\"due\":{\"description\":\"a reading of the world clock in fictional minutes; the prompt states the current reading, and a due must be later than it\",\"maximum\":18446744073709551615,\"minimum\":0,\"type\":\"integer\"},\"kind\":{\"enum\":[\"routine\",\"obligation\",\"goal\"],\"type\":\"string\"},\"period\":{\"anyOf\":[{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"},{\"type\":\"null\"}]},\"statement\":{\"description\":\"what is promised, as the promisor would say it in one sentence\",\"type\":\"string\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"counterparty\",\"kind\",\"due\",\"period\",\"checks\",\"statement\"],\"type\":\"object\"}" - }, - { - "name": "declare_affordance", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"carries_speech\":{\"type\":\"boolean\"},\"effect_slots\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"bounds\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"bound\":{\"const\":\"none\",\"type\":\"string\"}},\"required\":[\"bound\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"bound\":{\"const\":\"quantity\",\"type\":\"string\"},\"max\":{\"maximum\":18446744073709551615,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"bound\",\"max\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"bound\":{\"const\":\"cost\",\"type\":\"string\"},\"max\":{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"bound\",\"max\"],\"type\":\"object\"}]},\"op_kind\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"relocate\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"open_route\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"close_route\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"alter_cost\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"transfer\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"transform\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"consume\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"bind\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"release\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"description\":\"the authority kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"op\":{\"const\":\"grant_authority\",\"type\":\"string\"}},\"required\":[\"op\",\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"description\":\"the authority kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"op\":{\"const\":\"revoke_authority\",\"type\":\"string\"}},\"required\":[\"op\",\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"office\":{\"description\":\"the office's name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"op\":{\"const\":\"install_incumbent\",\"type\":\"string\"}},\"required\":[\"op\",\"office\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"office\":{\"description\":\"the office's name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"op\":{\"const\":\"vacate_office\",\"type\":\"string\"}},\"required\":[\"op\",\"office\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"confidence\":{\"enum\":[\"doubted\",\"believed\",\"certain\"],\"type\":\"string\"},\"op\":{\"const\":\"acquire_knowledge\",\"type\":\"string\"}},\"required\":[\"op\",\"confidence\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"forget\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"horizon\":{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"},\"kind\":{\"enum\":[\"routine\",\"obligation\",\"goal\"],\"type\":\"string\"},\"op\":{\"const\":\"create_commitment\",\"type\":\"string\"},\"period\":{\"anyOf\":[{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"},{\"type\":\"null\"}]}},\"required\":[\"op\",\"kind\",\"horizon\",\"period\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"by\":{\"maximum\":4294967295,\"minimum\":1,\"type\":\"integer\"},\"op\":{\"const\":\"advance_pressure\",\"type\":\"string\"}},\"required\":[\"op\",\"by\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"by\":{\"maximum\":4294967295,\"minimum\":1,\"type\":\"integer\"},\"op\":{\"const\":\"reduce_pressure\",\"type\":\"string\"}},\"required\":[\"op\",\"by\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"op\":{\"const\":\"resolve_pressure\",\"type\":\"string\"}},\"required\":[\"op\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"decay\":{\"anyOf\":[{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"},{\"type\":\"null\"}]},\"delta\":{\"maximum\":100,\"minimum\":-100,\"type\":\"integer\"},\"op\":{\"const\":\"adjust_attitude\",\"type\":\"string\"}},\"required\":[\"op\",\"delta\",\"decay\"],\"type\":\"object\"}]},\"roles\":{\"items\":{\"description\":\"a declared role name\",\"type\":\"string\"},\"type\":\"array\"}},\"required\":[\"op_kind\",\"roles\",\"bounds\"],\"type\":\"object\"},\"type\":\"array\"},\"handle\":{\"description\":\"a new draft handle, unique within this patch\",\"type\":\"string\"},\"kind\":{\"description\":\"the affordance's tool name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"outcome_bands\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"effects\":{\"items\":{\"maximum\":4294967295,\"minimum\":0,\"type\":\"integer\"},\"type\":\"array\"},\"weight\":{\"maximum\":4294967295,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"weight\",\"effects\"],\"type\":\"object\"},\"type\":\"array\"},\"preconditions\":{\"items\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"at\":{\"description\":\"a declared role name\",\"type\":\"string\"},\"precondition\":{\"const\":\"present\",\"type\":\"string\"}},\"required\":[\"precondition\",\"at\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"precondition\":{\"const\":\"reachable\",\"type\":\"string\"},\"to\":{\"description\":\"a declared role name\",\"type\":\"string\"},\"within\":{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"precondition\",\"to\",\"within\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"at_least\":{\"maximum\":18446744073709551615,\"minimum\":1,\"type\":\"integer\"},\"precondition\":{\"const\":\"holds\",\"type\":\"string\"},\"resource\":{\"description\":\"a declared role name\",\"type\":\"string\"}},\"required\":[\"precondition\",\"resource\",\"at_least\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"description\":\"the authority kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"over\":{\"description\":\"a declared role name\",\"type\":\"string\"},\"precondition\":{\"const\":\"authorized\",\"type\":\"string\"}},\"required\":[\"precondition\",\"over\",\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"grievance\":{\"description\":\"the grievance kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"precondition\":{\"const\":\"has_standing\",\"type\":\"string\"}},\"required\":[\"precondition\",\"grievance\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"at_least\":{\"enum\":[\"doubted\",\"believed\",\"certain\"],\"type\":\"string\"},\"fact\":{\"description\":\"a declared role name\",\"type\":\"string\"},\"precondition\":{\"const\":\"knows\",\"type\":\"string\"}},\"required\":[\"precondition\",\"fact\",\"at_least\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"precondition\":{\"const\":\"can_broadcast\",\"type\":\"string\"},\"via\":{\"anyOf\":[{\"const\":\"colocated\",\"type\":\"string\"},{\"additionalProperties\":false,\"properties\":{\"channel\":{\"description\":\"a declared role name\",\"type\":\"string\"}},\"required\":[\"channel\"],\"type\":\"object\"}]}},\"required\":[\"precondition\",\"via\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"precondition\":{\"const\":\"can_reach\",\"type\":\"string\"},\"subject\":{\"description\":\"a declared role name\",\"type\":\"string\"},\"via\":{\"anyOf\":[{\"const\":\"colocated\",\"type\":\"string\"},{\"additionalProperties\":false,\"properties\":{\"channel\":{\"description\":\"a declared role name\",\"type\":\"string\"}},\"required\":[\"channel\"],\"type\":\"object\"}]}},\"required\":[\"precondition\",\"subject\",\"via\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"routine\",\"obligation\",\"goal\"],\"type\":\"string\"},\"precondition\":{\"const\":\"committed\",\"type\":\"string\"},\"to\":{\"description\":\"a declared role name\",\"type\":\"string\"}},\"required\":[\"precondition\",\"to\",\"kind\"],\"type\":\"object\"}]},\"type\":\"array\"},\"roles\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"kind\":{\"anyOf\":[{\"enum\":[\"person\",\"institution\",\"population\"],\"type\":\"string\"},{\"type\":\"null\"}]},\"namespace\":{\"const\":\"subject\",\"type\":\"string\"}},\"required\":[\"namespace\",\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"place\",\"resource\",\"fact\",\"channel\"],\"type\":\"string\"},\"namespace\":{\"const\":\"entity\",\"type\":\"string\"}},\"required\":[\"namespace\",\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"route\"],\"type\":\"string\"},\"namespace\":{\"const\":\"edge\",\"type\":\"string\"}},\"required\":[\"namespace\",\"kind\"],\"type\":\"object\"}]},\"role\":{\"description\":\"the slot's parameter name\",\"type\":\"string\"}},\"required\":[\"role\",\"kind\"],\"type\":\"object\"},\"type\":\"array\"}},\"required\":[\"handle\",\"kind\",\"roles\",\"preconditions\",\"effect_slots\",\"outcome_bands\",\"carries_speech\"],\"type\":\"object\"}" - }, - { - "name": "declare_attitude", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"basis\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"basis\":{\"const\":\"prejudice\",\"type\":\"string\"}},\"required\":[\"basis\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"basis\":{\"const\":\"rumour\",\"type\":\"string\"},\"fact\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing fact\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"basis\",\"fact\"],\"type\":\"object\"}]},\"decay\":{\"anyOf\":[{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"},{\"type\":\"null\"}]},\"delta\":{\"maximum\":100,\"minimum\":-100,\"type\":\"integer\"},\"holder\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"toward\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"of\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"toward\":{\"const\":\"subject\",\"type\":\"string\"}},\"required\":[\"toward\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"of\":{\"description\":\"the trait's name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"toward\":{\"const\":\"trait\",\"type\":\"string\"}},\"required\":[\"toward\",\"of\"],\"type\":\"object\"}]}},\"required\":[\"holder\",\"toward\",\"delta\",\"basis\",\"decay\"],\"type\":\"object\"}" - }, - { - "name": "declare_channel", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"controller\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},{\"type\":\"null\"}]},\"handle\":{\"description\":\"a new draft handle, unique within this patch\",\"type\":\"string\"},\"label\":{\"description\":\"a display label\",\"type\":\"string\"},\"reach\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"of\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"type\":\"array\"},\"reach\":{\"const\":\"subjects\",\"type\":\"string\"}},\"required\":[\"reach\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"of\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"reach\":{\"const\":\"place\",\"type\":\"string\"}},\"required\":[\"reach\",\"of\"],\"type\":\"object\"}]}},\"required\":[\"handle\",\"label\",\"reach\",\"controller\"],\"type\":\"object\"}" - }, - { - "name": "declare_fact", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"handle\":{\"description\":\"a new draft handle, unique within this patch\",\"type\":\"string\"},\"label\":{\"description\":\"a display label\",\"type\":\"string\"},\"standing\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"evidence\":{\"description\":\"an exact evidence receipt\",\"type\":\"string\"},\"standing\":{\"const\":\"canonical\",\"type\":\"string\"}},\"required\":[\"standing\",\"evidence\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"by\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"standing\":{\"const\":\"claimed\",\"type\":\"string\"}},\"required\":[\"standing\",\"by\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"standing\":{\"const\":\"ruled\",\"type\":\"string\"}},\"required\":[\"standing\"],\"type\":\"object\"}]},\"statement\":{\"description\":\"the committed world text this fact carries\",\"type\":\"string\"}},\"required\":[\"handle\",\"label\",\"statement\",\"standing\"],\"type\":\"object\"}" - }, - { - "name": "declare_place", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"container\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},{\"type\":\"null\"}]},\"handle\":{\"description\":\"a new draft handle, unique within this patch\",\"type\":\"string\"},\"label\":{\"description\":\"a display label\",\"type\":\"string\"}},\"required\":[\"handle\",\"label\",\"container\"],\"type\":\"object\"}" - }, - { - "name": "declare_resource", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"handle\":{\"description\":\"a new draft handle, unique within this patch\",\"type\":\"string\"},\"label\":{\"description\":\"a display label\",\"type\":\"string\"}},\"required\":[\"handle\",\"label\"],\"type\":\"object\"}" - }, - { - "name": "declare_route", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"access\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"access\":{\"const\":\"public\",\"type\":\"string\"}},\"required\":[\"access\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"access\":{\"const\":\"restricted\",\"type\":\"string\"},\"requires\":{\"description\":\"the authority kind that opens this route: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"}},\"required\":[\"access\",\"requires\"],\"type\":\"object\"}]},\"cost\":{\"maximum\":525600,\"minimum\":1,\"type\":\"integer\"},\"from\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"handle\":{\"description\":\"a new draft handle, unique within this patch\",\"type\":\"string\"},\"label\":{\"description\":\"a display label\",\"type\":\"string\"},\"to\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"handle\",\"label\",\"from\",\"to\",\"access\",\"cost\"],\"type\":\"object\"}" - }, - { - "name": "declare_subject", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"affordances\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing affordance\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"type\":\"array\"},\"controller\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"type\":{\"const\":\"narrative_persona\",\"type\":\"string\"}},\"required\":[\"type\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"type\":{\"const\":\"operational_agent\",\"type\":\"string\"}},\"required\":[\"type\"],\"type\":\"object\"}],\"description\":\"who decides for this subject, as an object with a `type` field: narrative_persona for a person who acts through prose, operational_agent for an institution or organ that acts through typed tools; an empty object is refused and the subject is not declared\"},\"handle\":{\"description\":\"a new draft handle, unique within this patch\",\"type\":\"string\"},\"kind\":{\"enum\":[\"person\",\"institution\",\"population\"],\"type\":\"string\"},\"label\":{\"description\":\"a display label\",\"type\":\"string\"},\"position\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},{\"type\":\"null\"}]}},\"required\":[\"handle\",\"label\",\"kind\",\"controller\",\"affordances\",\"position\"],\"type\":\"object\"}" - }, - { - "name": "declare_trait", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"fact\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing fact\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"name\":{\"description\":\"the trait's name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"name\",\"fact\"],\"type\":\"object\"}" - }, - { - "name": "discharge_commitment", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"key\":{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"the command id that created the commitment\",\"type\":\"string\"},\"index\":{\"maximum\":4294967295,\"minimum\":0,\"type\":\"integer\"}},\"required\":[\"command\",\"index\"],\"type\":\"object\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"key\"],\"type\":\"object\"}" - }, - { - "name": "finish_without_proposal", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{},\"type\":\"object\"}" - }, - { - "name": "forget", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"fact\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing fact\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"fact\"],\"type\":\"object\"}" - }, - { - "name": "grant_affordance", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"affordance\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing affordance\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"affordance\"],\"type\":\"object\"}" - }, - { - "name": "grant_authority", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"grant\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"description\":\"the authority kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"over\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"over\":{\"const\":\"subject\",\"type\":\"string\"},\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"over\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"over\":{\"const\":\"place_subtree\",\"type\":\"string\"},\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"over\",\"ref\"],\"type\":\"object\"}]}},\"required\":[\"kind\",\"over\"],\"type\":\"object\"},\"holder\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"holder\",\"grant\"],\"type\":\"object\"}" - }, - { - "name": "install_incumbent", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"incumbent\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"institution\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"office\":{\"description\":\"the office's name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"}},\"required\":[\"institution\",\"office\",\"incumbent\"],\"type\":\"object\"}" - }, - { - "name": "mint", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"holder\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"qty\":{\"maximum\":18446744073709551615,\"minimum\":1,\"type\":\"integer\"},\"resource\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"holder\",\"resource\",\"qty\"],\"type\":\"object\"}" - }, - { - "name": "open_forum", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"forum\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"grievance\":{\"description\":\"the grievance kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"standing\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"over\":{\"const\":\"subject\",\"type\":\"string\"},\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"over\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"over\":{\"const\":\"place_subtree\",\"type\":\"string\"},\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"over\",\"ref\"],\"type\":\"object\"}]}},\"required\":[\"grievance\",\"forum\",\"standing\"],\"type\":\"object\"}" - }, - { - "name": "open_office", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"delegated\":{\"items\":{\"description\":\"an authority kind the office lends: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"type\":\"array\"},\"institution\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"office\":{\"description\":\"the office's name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"}},\"required\":[\"institution\",\"office\",\"delegated\"],\"type\":\"object\"}" - }, - { - "name": "open_route", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"route\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"route\"],\"type\":\"object\"}" - }, - { - "name": "record_gap", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"detail\":{\"description\":\"what the world needs and this vocabulary cannot express\",\"type\":\"string\"}},\"required\":[\"detail\"],\"type\":\"object\"}" - }, - { - "name": "record_need", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"detail\":{\"description\":\"what the agent would need and does not have\",\"type\":\"string\"}},\"required\":[\"detail\"],\"type\":\"object\"}" - }, - { - "name": "reduce_pressure", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"by\":{\"maximum\":4294967295,\"minimum\":1,\"type\":\"integer\"},\"source\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"commitment\",\"type\":\"string\"},\"of\":{\"additionalProperties\":false,\"properties\":{\"key\":{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"the command id that created the commitment\",\"type\":\"string\"},\"index\":{\"maximum\":4294967295,\"minimum\":0,\"type\":\"integer\"}},\"required\":[\"command\",\"index\"],\"type\":\"object\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"key\"],\"type\":\"object\"}},\"required\":[\"from\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"dependency\",\"type\":\"string\"},\"of\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"resource\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"route\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"subject\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"}]}},\"required\":[\"from\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"subject\",\"type\":\"string\"},\"of\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"from\",\"of\"],\"type\":\"object\"}]},\"target\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"source\",\"target\",\"by\"],\"type\":\"object\"}" - }, - { - "name": "release", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"resource\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"route\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"subject\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"}]}},\"required\":[\"subject\",\"target\"],\"type\":\"object\"}" - }, - { - "name": "relocate", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"via\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"via\"],\"type\":\"object\"}" - }, - { - "name": "resolve_pressure", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"source\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"commitment\",\"type\":\"string\"},\"of\":{\"additionalProperties\":false,\"properties\":{\"key\":{\"additionalProperties\":false,\"properties\":{\"command\":{\"description\":\"the command id that created the commitment\",\"type\":\"string\"},\"index\":{\"maximum\":4294967295,\"minimum\":0,\"type\":\"integer\"}},\"required\":[\"command\",\"index\"],\"type\":\"object\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"key\"],\"type\":\"object\"}},\"required\":[\"from\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"dependency\",\"type\":\"string\"},\"of\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"resource\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing route\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"route\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"target\":{\"const\":\"subject\",\"type\":\"string\"}},\"required\":[\"target\",\"ref\"],\"type\":\"object\"}]}},\"required\":[\"from\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"from\":{\"const\":\"subject\",\"type\":\"string\"},\"of\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"from\",\"of\"],\"type\":\"object\"}]},\"target\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"source\",\"target\"],\"type\":\"object\"}" - }, - { - "name": "retire", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\"],\"type\":\"object\"}" - }, - { - "name": "revoke_affordance", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"affordance\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing affordance\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"affordance\"],\"type\":\"object\"}" - }, - { - "name": "revoke_authority", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"grant\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"description\":\"the authority kind: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"},\"over\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"over\":{\"const\":\"subject\",\"type\":\"string\"},\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"over\",\"ref\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"over\":{\"const\":\"place_subtree\",\"type\":\"string\"},\"ref\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"over\",\"ref\"],\"type\":\"object\"}]}},\"required\":[\"kind\",\"over\"],\"type\":\"object\"},\"holder\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"holder\",\"grant\"],\"type\":\"object\"}" - }, - { - "name": "set_controller", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"channel\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing channel\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"controller\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},{\"type\":\"null\"}]}},\"required\":[\"channel\",\"controller\"],\"type\":\"object\"}" - }, - { - "name": "set_persona_material", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"memories\":{\"items\":{\"description\":\"one thing this subject remembers, as a sentence\",\"type\":\"string\"},\"type\":\"array\"},\"reads\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"statement\":{\"description\":\"how this subject reads that one, in one sentence\",\"type\":\"string\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"subject\",\"statement\"],\"type\":\"object\"},\"type\":\"array\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"values\":{\"items\":{\"description\":\"one value the subject holds, as a sentence\",\"type\":\"string\"},\"type\":\"array\"},\"voice\":{\"description\":\"how this subject speaks, in one sentence\",\"type\":\"string\"}},\"required\":[\"subject\",\"values\",\"voice\",\"memories\",\"reads\"],\"type\":\"object\"}" - }, - { - "name": "set_reach", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"channel\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing channel\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"reach\":{\"anyOf\":[{\"additionalProperties\":false,\"properties\":{\"of\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"type\":\"array\"},\"reach\":{\"const\":\"subjects\",\"type\":\"string\"}},\"required\":[\"reach\",\"of\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"of\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"reach\":{\"const\":\"place\",\"type\":\"string\"}},\"required\":[\"reach\",\"of\"],\"type\":\"object\"}]}},\"required\":[\"channel\",\"reach\"],\"type\":\"object\"}" - }, - { - "name": "speak", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"text\":{\"description\":\"the utterance this invocation carries\",\"type\":\"string\"}},\"required\":[\"text\"],\"type\":\"object\"}" - }, - { - "name": "submit", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{},\"required\":[],\"type\":\"object\"}" - }, - { - "name": "transfer", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"from\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"qty\":{\"maximum\":18446744073709551615,\"minimum\":1,\"type\":\"integer\"},\"resource\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"to\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"from\",\"to\",\"resource\",\"qty\"],\"type\":\"object\"}" - }, - { - "name": "transform", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"from_resource\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"holder\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"into_resource\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing resource\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"qty\":{\"maximum\":18446744073709551615,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"holder\",\"from_resource\",\"into_resource\",\"qty\"],\"type\":\"object\"}" - }, - { - "name": "vacate_office", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"institution\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing subject\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"office\":{\"description\":\"the office's name: lowercase snake_case, starting with a letter, at most 48 characters (e.g. toll_command)\",\"pattern\":\"^[a-z][a-z0-9_]{0,47}$\",\"type\":\"string\"}},\"required\":[\"institution\",\"office\"],\"type\":\"object\"}" - }, - { - "name": "witness", - "parameters_json": "{\"additionalProperties\":false,\"properties\":{\"confidence\":{\"enum\":[\"doubted\",\"believed\",\"certain\"],\"type\":\"string\"},\"fact\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing fact\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"},\"place\":{\"additionalProperties\":false,\"properties\":{\"ref\":{\"enum\":[\"draft\",\"existing\"],\"type\":\"string\"},\"value\":{\"description\":\"a draft handle declared in this same patch, or the canonical id of an existing place\",\"type\":\"string\"}},\"required\":[\"ref\",\"value\"],\"type\":\"object\"}},\"required\":[\"fact\",\"place\",\"confidence\"],\"type\":\"object\"}" - } -] diff --git a/sidecar/claude-sdk/test/soul-dispatcher.test.ts b/sidecar/claude-sdk/test/soul-dispatcher.test.ts deleted file mode 100644 index f05133c..0000000 --- a/sidecar/claude-sdk/test/soul-dispatcher.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -// Soul: the two sidecar gates that live in the stdin dispatcher rather than in -// a pure function, driven against the real built entry point. -// -// Neither case reaches `query()`, so no Claude Code subprocess is spawned, no -// credential is looked for, and no network is touched. The gate that needs a -// live query — a second `query` frame while one is in flight — is deliberately -// not exercised here for that reason. - -import assert from "node:assert/strict"; -import { spawn } from "node:child_process"; -import { existsSync } from "node:fs"; -import { fileURLToPath } from "node:url"; -import test from "node:test"; -import { FrameReader, encodeFrame, type SidecarFrame } from "../src/frames.ts"; -import { QuerySession, SidecarFault } from "../src/main.ts"; -import { encode } from "@msgpack/msgpack"; - -const entry = fileURLToPath(new URL("../dist/main.js", import.meta.url)); - -/** Writes raw bytes to a fresh sidecar child and returns the frames it emits. */ -async function exchange(bytes: Uint8Array): Promise { - const child = spawn(process.execPath, [entry], { - stdio: ["pipe", "pipe", "inherit"], - }); - const reader = new FrameReader(); - const frames: SidecarFrame[] = []; - child.stdout.on("data", (chunk: Buffer) => { - reader.push(new Uint8Array(chunk)); - for (;;) { - const frame = reader.next(); - if (!frame) { - break; - } - frames.push(frame); - } - }); - child.stdin.write(bytes); - child.stdin.end(); - await new Promise((done) => child.on("close", () => done())); - return frames; -} - -function framed(body: Uint8Array): Uint8Array { - const out = new Uint8Array(4 + body.length); - new DataView(out.buffer).setUint32(0, body.length, false); - out.set(body, 4); - return out; -} - -test("a tool result for a call the session never issued is a protocol violation", async () => { - const sent: SidecarFrame[] = []; - const session = new QuerySession(4, (frame) => sent.push(frame)); - const pending = session.ask("record_gap", { detail: "no route" }); - assert.deepEqual(session.dispatches, [ - { call_id: "c0", name: "record_gap", arguments: '{"detail":"no route"}' }, - ]); - assert.throws( - () => session.answer("c9", "gap recorded"), - (error: unknown) => - error instanceof SidecarFault && error.reason === "protocol_violation", - ); - session.answer("c0", "gap recorded"); - assert.equal(await pending, "gap recorded"); - // And a second answer for a call already resolved is refused too, so one - // dispatch can never be answered twice. - assert.throws( - () => session.answer("c0", "gap recorded"), - (error: unknown) => - error instanceof SidecarFault && error.reason === "protocol_violation", - ); - assert.equal(sent.length, 1); -}); - -test("a frame kind the sidecar does not accept is a protocol violation", async (t) => { - if (!existsSync(entry)) { - t.skip("run `npm run build` first"); - return; - } - // A well-formed MessagePack map with a kind that is not on the wire. - const frames = await exchange( - framed(encode({ kind: "hallucination", query_id: 3 }, { useBigInt64: false })), - ); - assert.equal(frames.length, 1); - assert.deepEqual(frames[0], { - kind: "fault", - query_id: 0, - reason: "protocol_violation", - detail: "frame kind hallucination is not one this sidecar accepts", - }); -}); - -test("a tool result outside any query is a protocol violation", async (t) => { - if (!existsSync(entry)) { - t.skip("run `npm run build` first"); - return; - } - const frames = await exchange( - encodeFrame({ - kind: "tool_result", - query_id: 7, - call_id: "c0", - output: "gap recorded", - }), - ); - assert.equal(frames.length, 1); - const [fault] = frames; - assert.ok(fault && fault.kind === "fault"); - assert.equal(fault.reason, "protocol_violation"); - assert.equal(fault.query_id, 7); -}); - -test("a length prefix over the cap ends the sidecar rather than buffering it", async (t) => { - if (!existsSync(entry)) { - t.skip("run `npm run build` first"); - return; - } - const over = new Uint8Array(8); - new DataView(over.buffer).setUint32(0, 1_052_673, false); - const frames = await exchange(over); - assert.equal(frames.length, 1); - const [fault] = frames; - assert.ok(fault && fault.kind === "fault"); - assert.equal(fault.reason, "protocol_violation"); -}); diff --git a/sidecar/claude-sdk/test/soul-zod-liability.test.ts b/sidecar/claude-sdk/test/soul-zod-liability.test.ts deleted file mode 100644 index b890590..0000000 --- a/sidecar/claude-sdk/test/soul-zod-liability.test.ts +++ /dev/null @@ -1,225 +0,0 @@ -// One validator, both transports. These assert that the schema the sidecar -// registers judges nothing: an argument Ghostlight's evaluators would record as -// a gap travels through the real in-process MCP server unstripped and reaches -// the handler, so Rust's decoder is the only thing that can refuse it. -// -// Established end to end against the real SDK, with no credential and no -// network. Also asserts the sidecar names no credential and reads no -// environment. - -import assert from "node:assert/strict"; -import { readFileSync, readdirSync } from "node:fs"; -import { fileURLToPath } from "node:url"; -import test from "node:test"; -import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk"; -import { toolInputSchema } from "../src/schema.ts"; -import { assembleEvents, SidecarFault } from "../src/main.ts"; - -const emitted: { name: string; parameters_json: string }[] = JSON.parse( - readFileSync(fileURLToPath(new URL("./schemas.json", import.meta.url)), "utf8"), -); - -function schemaFor(name: string): string { - const entry = emitted.find((candidate) => candidate.name === name); - assert.ok(entry, `the emitted fixture carries no ${name}`); - return entry.parameters_json; -} - -test("the registered schema keeps an extra property instead of stripping it", () => { - const gap = toolInputSchema(schemaFor("record_gap"), "record_gap"); - const admitted = gap.safeParse({ detail: "no route", extra: true }); - assert.equal(admitted.success, true); - assert.deepEqual( - admitted.success && admitted.data, - { detail: "no route", extra: true }, - "an extra property was stripped before Rust could refuse it", - ); - - // A nested object keeps its own, so the emitter's depth does not matter. - const declare = toolInputSchema(schemaFor("bind"), "bind"); - const deep = declare.safeParse({ - subject: { ref: "draft", value: "x", extra: true }, - }); - assert.equal(deep.success, true); - assert.deepEqual(deep.success && (deep.data as { subject: unknown }).subject, { - ref: "draft", - value: "x", - extra: true, - }); -}); - -test("the registered schema admits a missing or mistyped required property", () => { - const gap = toolInputSchema(schemaFor("record_gap"), "record_gap"); - const absent = gap.safeParse({}); - assert.equal(absent.success, true); - assert.deepEqual(absent.success && absent.data, {}); - - // A mistyped value is the one thing a property's catch cannot carry through: - // it reaches Rust as an absent field, which the decoder reports the way it - // reports any other missing field, rather than as a call the SDK refused. - const mistyped = gap.safeParse({ detail: 5 }); - assert.equal(mistyped.success, true); - assert.equal( - mistyped.success && (mistyped.data as { detail?: unknown }).detail, - undefined, - ); - - const subject = toolInputSchema(schemaFor("declare_subject"), "declare_subject"); - assert.equal( - subject.safeParse({ handle: "smith" }).success, - true, - "a partly filled call was refused here instead of in Rust", - ); -}); - -test("the SDK dispatches a call Rust would refuse and never answers it itself", async () => { - // The middle link, against the real in-process MCP server the sidecar - // registers. No credential, no network, no `query()`. - let mcp: { Client: new (info: { name: string; version: string }) => never }; - let memory: { InMemoryTransport: { createLinkedPair(): [never, never] } }; - try { - mcp = await import("@modelcontextprotocol/sdk/client/index.js"); - memory = await import("@modelcontextprotocol/sdk/inMemory.js"); - } catch { - // The MCP client is the SDK's own transitive dependency, not this - // package's. If a future install stops hoisting it, the assertions either - // side of this test still stand on their own. - return; - } - const seen: unknown[] = []; - const handle = tool( - "record_gap", - "Record a gap.", - toolInputSchema(schemaFor("record_gap"), "record_gap") as unknown as Parameters< - typeof tool - >[2], - async (args: unknown) => { - seen.push(args); - return { content: [{ type: "text" as const, text: "gap recorded" }] }; - }, - { alwaysLoad: true }, - ); - const server = createSdkMcpServer({ name: "ghostlight", tools: [handle], alwaysLoad: true }); - const [clientSide, serverSide] = memory.InMemoryTransport.createLinkedPair(); - const instance = (server as unknown as { instance: { connect(t: unknown): Promise } }) - .instance; - await instance.connect(serverSide); - const client = new mcp.Client({ name: "ghostlight-soul-probe", version: "0" }) as unknown as { - connect(t: unknown): Promise; - listTools(): Promise<{ tools: { inputSchema: Record }[] }>; - callTool(request: { name: string; arguments: unknown }): Promise<{ - isError?: boolean; - content: { text: string }[]; - }>; - close(): Promise; - }; - await client.connect(clientSide); - try { - // The model still sees the emitted parameters. Looseness is what the - // server judges arguments by, not what it advertises. - const advertised = (await client.listTools()).tools[0]!.inputSchema; - assert.equal(advertised.type, "object"); - assert.deepEqual(Object.keys(advertised.properties as object), ["detail"]); - assert.deepEqual(advertised.required, ["detail"]); - - // An extra key reaches the handler with the key present. - const extra = await client.callTool({ - name: "record_gap", - arguments: { detail: "no route", extra: true }, - }); - assert.notEqual(extra.isError, true, "an extra property was refused"); - assert.deepEqual(seen.at(-1), { detail: "no route", extra: true }); - - // A missing required property reaches the handler too. - const missing = await client.callTool({ name: "record_gap", arguments: {} }); - assert.notEqual(missing.isError, true, "a missing property was refused"); - assert.deepEqual(seen.at(-1), {}); - - assert.equal(seen.length, 2, "a call was answered without reaching the handler"); - } finally { - await client.close(); - } -}); - -test("a registered tool_use block with no dispatch is a protocol violation", () => { - // No argument reaches this any more. What still does is a call never offered - // to the handler, or an assistant stream and a dispatch log that disagree. - const registered = new Set(["record_gap"]); - assert.throws( - () => - assembleEvents( - [ - { - content: [ - { type: "tool_use", name: "mcp__ghostlight__record_gap", input: { detail: 5 } }, - ], - }, - ], - registered, - [], - ), - (error: unknown) => - error instanceof SidecarFault && error.reason === "protocol_violation", - "a registered tool_use with no dispatch did not raise protocol_violation", - ); - - // The mirror image: a dispatch the assistant messages never report. - assert.throws( - () => - assembleEvents([{ content: [] }], registered, [ - { call_id: "c0", name: "record_gap", arguments: "{}" }, - ]), - (error: unknown) => - error instanceof SidecarFault && error.reason === "protocol_violation", - ); - - // An unregistered name needs no dispatch and is reported undispatched, which - // is the path the evaluators already own as a gap. - assert.deepEqual( - assembleEvents( - [{ content: [{ type: "tool_use", name: "speek", input: {} }] }], - registered, - [], - ), - [ - { - kind: "tool_call", - call_id: "u0", - name: "speek", - arguments: "{}", - dispatched: false, - }, - ], - ); -}); - -test("no credential name appears anywhere in the sidecar source", () => { - const forbidden = [ - ".credentials.json", - "CLAUDE_CODE_OAUTH_TOKEN", - "ANTHROPIC_API_KEY", - "ANTHROPIC_AUTH_TOKEN", - ".claude.json", - "apiKeyHelper", - "USERPROFILE", - "homedir", - "--bare", - ]; - const source = fileURLToPath(new URL("../src", import.meta.url)); - for (const name of readdirSync(source)) { - const text = readFileSync(`${source}/${name}`, "utf8"); - for (const needle of forbidden) { - assert.equal(text.includes(needle), false, `${name} names ${needle}`); - } - } -}); - -test("the sidecar reads no environment and logs nothing of its own", () => { - const source = fileURLToPath(new URL("../src", import.meta.url)); - for (const name of readdirSync(source)) { - const text = readFileSync(`${source}/${name}`, "utf8"); - assert.equal(text.includes("process.env"), false, `${name} reads the environment`); - assert.equal(text.includes("console."), false, `${name} logs outside the frame protocol`); - assert.equal(text.includes("process.stderr"), false, `${name} writes to stderr`); - } -}); diff --git a/sidecar/claude-sdk/tsconfig.json b/sidecar/claude-sdk/tsconfig.json deleted file mode 100644 index 4d199af..0000000 --- a/sidecar/claude-sdk/tsconfig.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "NodeNext", - "moduleResolution": "NodeNext", - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "outDir": "dist", - "rootDir": "src", - "declaration": false, - "sourceMap": false, - "skipLibCheck": true, - "allowImportingTsExtensions": true, - "rewriteRelativeImportExtensions": true - }, - "include": ["src/**/*.ts"] -}