interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / src / client.rs

248 lines · 9195 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Local UNIX domain socket client for AienRuntimeSpine
17//! Used by aien-cli to communicate with the in-process runtime daemon.
18
19use crate::control::{
20 ChatTurn, ControlCommand, ControlEnvelope, ControlResponse, LaunchSwarmReq, RuntimeStatusReport,
21};
22use std::path::{Path, PathBuf};
23use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
24use tokio::net::UnixStream;
25
26pub struct AienRuntimeClient {
27 socket_path: PathBuf,
28}
29
30impl AienRuntimeClient {
31 pub fn new(socket_path: impl AsRef<Path>) -> Self {
32 Self {
33 socket_path: socket_path.as_ref().to_path_buf(),
34 }
35 }
36
37 pub fn default_socket_path() -> PathBuf {
38 if let Ok(sock) = std::env::var("AIEN_RUNTIME_SOCK") {
39 if !sock.trim().is_empty() {
40 return PathBuf::from(sock.trim());
41 }
42 }
43 PathBuf::from("/tmp/aien-runtime.sock")
44 }
45
46 pub fn default_client() -> Self {
47 Self::new(Self::default_socket_path())
48 }
49
50 pub async fn is_alive(&self) -> bool {
51 self.get_status().await.is_ok()
52 }
53
54 pub async fn send_command(&self, command: ControlCommand) -> Result<ControlResponse, String> {
55 let stream = UnixStream::connect(&self.socket_path).await.map_err(|e| {
56 format!(
57 "Failed to connect to AIEN runtime socket at {}: {}",
58 self.socket_path.display(),
59 e
60 )
61 })?;
62
63 if !crate::server::peer_is_current_user(&stream) {
64 return Err(format!(
65 "Refusing runtime socket at {}: server runs as a different user",
66 self.socket_path.display()
67 ));
68 }
69
70 let (reader, mut writer) = stream.into_split();
71 let mut buf_reader = BufReader::new(reader);
72
73 let now = std::time::SystemTime::now()
74 .duration_since(std::time::UNIX_EPOCH)
75 .unwrap_or_default();
76
77 let envelope = ControlEnvelope {
78 protocol_version: 1,
79 request_id: now.as_millis() as u64,
80 operation_id: now.as_nanos(),
81 operator_session: 1,
82 command,
83 };
84
85 let mut payload = serde_json::to_string(&envelope)
86 .map_err(|e| format!("Failed to serialize ControlEnvelope: {}", e))?;
87 payload.push('\n');
88
89 writer
90 .write_all(payload.as_bytes())
91 .await
92 .map_err(|e| format!("Failed to send control command: {}", e))?;
93
94 let mut line = String::new();
95 buf_reader
96 .read_line(&mut line)
97 .await
98 .map_err(|e| format!("Failed to read response from runtime socket: {}", e))?;
99
100 serde_json::from_str::<ControlResponse>(line.trim())
101 .map_err(|e| format!("Failed to parse ControlResponse: {}", e))
102 }
103
104 pub async fn get_status(&self) -> Result<RuntimeStatusReport, String> {
105 match self.send_command(ControlCommand::GetRuntimeStatus).await? {
106 ControlResponse::Status(report) => Ok(report),
107 ControlResponse::Error(e) => Err(e),
108 other => Err(format!(
109 "Unexpected response for GetRuntimeStatus: {:?}",
110 other
111 )),
112 }
113 }
114
115 pub async fn launch_swarm(&self, req: LaunchSwarmReq) -> Result<u64, String> {
116 match self.send_command(ControlCommand::LaunchSwarm(req)).await? {
117 ControlResponse::SwarmAccepted { swarm_id, .. } => Ok(swarm_id),
118 ControlResponse::Error(e) => Err(e),
119 other => Err(format!("Unexpected response for LaunchSwarm: {:?}", other)),
120 }
121 }
122
123 pub async fn cancel_swarm(&self, swarm_id: u64) -> Result<(), String> {
124 match self
125 .send_command(ControlCommand::CancelSwarm(swarm_id))
126 .await?
127 {
128 ControlResponse::SwarmCancelled { .. } => Ok(()),
129 ControlResponse::Error(e) => Err(e),
130 other => Err(format!("Unexpected response for CancelSwarm: {:?}", other)),
131 }
132 }
133
134 pub async fn inspect_swarm(&self, swarm_id: u64) -> Result<RuntimeStatusReport, String> {
135 match self
136 .send_command(ControlCommand::InspectSwarm(swarm_id))
137 .await?
138 {
139 ControlResponse::Status(report) => Ok(report),
140 ControlResponse::Error(e) => Err(e),
141 other => Err(format!("Unexpected response for InspectSwarm: {:?}", other)),
142 }
143 }
144
145 /// Streams one chat turn from the in-process runtime. Does not open an HTTP socket.
146 pub async fn stream_turn(
147 &self,
148 messages: Vec<ChatTurn>,
149 max_tokens: usize,
150 temperature: f32,
151 ) -> Result<String, String> {
152 self.stream_turn_recorded(messages, max_tokens, temperature)
153 .await
154 .map(|(text, _)| text)
155 }
156
157 /// [`Self::stream_turn`] plus the compose ledger id of the daemon's
158 /// generation record for the turn (`None` = the daemon wrote no record).
159 /// Only a normal StopToken finish succeeds. Updated servers return Error
160 /// for limited/aborted/preempted turns after recording generation evidence;
161 /// callers needing that evidence must use ComposeRecall, not infer success.
162 pub async fn stream_turn_recorded(
163 &self,
164 messages: Vec<ChatTurn>,
165 max_tokens: usize,
166 temperature: f32,
167 ) -> Result<(String, Option<u64>), String> {
168 let stream = UnixStream::connect(&self.socket_path).await.map_err(|e| {
169 format!(
170 "Failed to connect to AIEN runtime socket at {}: {}",
171 self.socket_path.display(),
172 e
173 )
174 })?;
175 if !crate::server::peer_is_current_user(&stream) {
176 return Err(format!(
177 "Refusing runtime socket at {}: server runs as a different user",
178 self.socket_path.display()
179 ));
180 }
181 let (reader, mut writer) = stream.into_split();
182 let mut buf_reader = BufReader::new(reader);
183 let now = std::time::SystemTime::now()
184 .duration_since(std::time::UNIX_EPOCH)
185 .unwrap_or_default();
186 let envelope = ControlEnvelope {
187 protocol_version: 1,
188 request_id: now.as_millis() as u64,
189 operation_id: now.as_nanos(),
190 operator_session: 1,
191 command: ControlCommand::StreamTurn {
192 messages,
193 max_tokens,
194 temperature,
195 },
196 };
197 let mut payload = serde_json::to_string(&envelope)
198 .map_err(|e| format!("Failed to serialize ControlEnvelope: {}", e))?;
199 payload.push('\n');
200 writer
201 .write_all(payload.as_bytes())
202 .await
203 .map_err(|e| format!("Failed to send control command: {}", e))?;
204
205 let mut finished = String::new();
206 loop {
207 let mut line = String::new();
208 let n = buf_reader
209 .read_line(&mut line)
210 .await
211 .map_err(|e| format!("Failed to read response from runtime socket: {}", e))?;
212 if n == 0 {
213 break;
214 }
215 let response = serde_json::from_str::<ControlResponse>(line.trim())
216 .map_err(|e| format!("Failed to parse ControlResponse: {}", e))?;
217 match response {
218 ControlResponse::TurnDelta { text } => finished.push_str(&text),
219 ControlResponse::TurnFinished {
220 text,
221 generation_record,
222 ..
223 } => {
224 if !text.is_empty() {
225 return Ok((text, generation_record));
226 }
227 return Ok((finished, generation_record));
228 }
229 ControlResponse::Error(error) => return Err(error),
230 other => {
231 return Err(format!(
232 "Unexpected response while streaming a native turn: {:?}",
233 other
234 ))
235 }
236 }
237 }
238 Err("native runtime closed the socket before the turn finished".into())
239 }
240
241 pub async fn shutdown(&self) -> Result<(), String> {
242 match self.send_command(ControlCommand::Shutdown).await? {
243 ControlResponse::ShutdownAck => Ok(()),
244 ControlResponse::Error(e) => Err(e),
245 other => Err(format!("Unexpected response for Shutdown: {:?}", other)),
246 }
247 }
248}