Delete the Agent SDK sidecar, its Rust port, and the claude-shaped model-name check

Move RoutedInferencePort and its routing tests into routed_inference.rs,
remove open_inference's sdk parameter and SidecarClaimsConnectorModel /
SdkSidecarMissing / names_connector_model checks, and remove sidecar/claude-sdk
and its docs/scripts. (cut-mp-delete-sdk-sidecar r1)
This commit is contained in:
Meta Vens 2026-12-03 21:12:34 +01:00
commit ccf8533c6e
33 changed files with 354 additions and 5949 deletions

1
.gitignore vendored
View file

@ -1,5 +1,4 @@
node_modules/
sidecar/claude-sdk/dist/
target/
# Disposable local scaffolding. These accumulated to ~87MB of untracked debris

View file

@ -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.

View file

@ -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.

View file

@ -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(),

View file

@ -143,7 +143,7 @@ pub(crate) fn open_shared() -> anyhow::Result<Shared> {
let mut all: Vec<&str> = models.each().to_vec();
all.push(&play_model);
let inference: Arc<dyn InferencePort> =
open_inference(Some(connector_binding()?), None, None, None, &all)?;
open_inference(Some(connector_binding()?), None, None, &all)?;
Ok(Shared {
inference,
models,

View file

@ -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",
}
}

View file

@ -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-<tier>-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<ConnectorBinding>,
sdk: Option<SdkBinding>,
local: Option<LocalBinding>,
hosted: Option<HostedBinding>,
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<Arc<dyn InferencePort>> = 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<dyn InferencePort>)> = 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<dyn Fn() -> 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)"
);
}

View file

@ -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,

View file

@ -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<dyn InferencePort>;
let sdk_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc<dyn InferencePort>;
let narrow_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc<dyn InferencePort>;
let connector_port = Arc::new(port("127.0.0.1:1".parse().unwrap())) as Arc<dyn InferencePort>;
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<dyn InferencePort>;
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<dyn InferencePort>;
let routed = RoutedInferencePort::new(
None,
None,
"claude",
vec![
("hosted/".to_owned(), Arc::clone(&hosted_port)),
("hosted/deep/".to_owned(), Arc::clone(&narrow_port)),

View file

@ -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<Arc<dyn InferencePort>>,
/// 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<dyn InferencePort>)>,
}
impl RoutedInferencePort {
pub(super) fn new(
connector: Option<Arc<dyn InferencePort>>,
claims: Vec<(String, Arc<dyn InferencePort>)>,
) -> 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<dyn InferencePort>> {
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<PreparedInference, InferenceFault> {
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<InferenceOutput, InferenceFault> {
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<dyn ToolResultOracle>) {
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, InferenceFault> {
PreparedInference::prepare(TEST_RUNTIME, unix_ms().saturating_add(60_000), request)
}
async fn infer(&self, _request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
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::<ToolDefinition>::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<dyn InferencePort>;
let local_port = Arc::new(StubPort) as Arc<dyn InferencePort>;
let hosted_port = Arc::new(StubPort) as Arc<dyn InferencePort>;
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<dyn InferencePort>;
let connector = Arc::new(StubPort) as Arc<dyn InferencePort>;
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<dyn InferencePort>;
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<dyn InferencePort>)],
);
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:?}"
);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -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")),
];

View file

@ -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<dyn InferencePort>`,
`Arc<dyn ControllerWorkStore>`, 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

View file

@ -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-<tier>-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.

View file

@ -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"
}

File diff suppressed because it is too large Load diff

View file

@ -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" }
}

View file

@ -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;
}
}

View file

@ -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<string, (output: string) => 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<string> {
const call_id = `c${this.#nextCall++}`;
const argumentsJson = JSON.stringify(args ?? {});
this.dispatches.push({ call_id, name, arguments: argumentsJson });
const answer = new Promise<string>((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<string, unknown>): 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<string, Record<string, unknown>>).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<SidecarFrame, { kind: "query" }>,
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<typeof tool>[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<string, unknown> = {
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<string>,
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<string, unknown>[]) {
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<SidecarFrame, { kind: "query" }>,
write: (frame: SidecarFrame) => void,
session: QuerySession,
): Promise<void> {
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<Record<string, unknown>>) {
if (message.type === "assistant") {
const inner = message.message as Record<string, unknown> | 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<void> {
const reader = new FrameReader();
const write = (frame: SidecarFrame) => {
process.stdout.write(encodeFrame(frame));
};
let live: QuerySession | null = null;
let running: Promise<void> = 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();
}

View file

@ -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<string, unknown>;
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<string, z.ZodTypeAny> = {};
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);
}

View file

@ -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());
});

View file

@ -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<SidecarFrame, { kind: "query" }>> = {},
): Extract<SidecarFrame, { kind: "query" }> {
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<SidecarFrame, { kind: "query" }>): 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<string, unknown>;
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<string, Record<string, unknown>>;
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<string, unknown>;
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",
);
});

View file

@ -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, unknown>): 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");
});

View file

@ -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<string, unknown>,
).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<string, { description?: string }>;
};
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<string, unknown>;
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" });
});

File diff suppressed because one or more lines are too long

View file

@ -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<SidecarFrame[]> {
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<void>((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");
});

View file

@ -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<void> } })
.instance;
await instance.connect(serverSide);
const client = new mcp.Client({ name: "ghostlight-soul-probe", version: "0" }) as unknown as {
connect(t: unknown): Promise<void>;
listTools(): Promise<{ tools: { inputSchema: Record<string, unknown> }[] }>;
callTool(request: { name: string; arguments: unknown }): Promise<{
isError?: boolean;
content: { text: string }[];
}>;
close(): Promise<void>;
};
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`);
}
});

View file

@ -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"]
}