winx-code-agent 0.2.358

Remote-first Rust MCP runtime with Streamable HTTP, durable PTYs, and guarded agent tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Session-scoped observation tools; they never send terminal input.
use crate::server::usage::lifecycle::{phase, Phase};
pub(super) mod history;
mod observe;
mod wait;

use std::path::Path;
use std::time::Duration;

use rmcp::model::{CallToolResult, ContentBlock};
use rmcp::ErrorData as McpError;
use serde_json::{json, Value};

use super::outcomes::{self, ToolResultEnvelope, ToolResultStatus};
use super::sessions::SessionGuard;
use super::workflow_types::{ExecutionAction, ExecutionRequest};
use super::{SharedBashState, WinxService};
use crate::errors::WinxError;
use crate::state::execution_history::{
    ExecutionProcessStatus, ExecutionRecord, ExecutionScope, HistoryError, HistoryResult,
    DEFAULT_PAGE_BYTES,
};
use crate::types::Modes;

use history::{history_call, now_ms, refresh_record};
pub(super) use wait::WaitTiming;

pub(super) struct WorkflowContext {
    pub slot: SharedBashState,
    pub scope: ExecutionScope,
    pub allow_prompt: bool,
    _session_guard: SessionGuard,
}

pub(super) struct WorkflowReply {
    pub status: ToolResultStatus,
    pub error_code: Option<&'static str>,
    pub message: String,
    pub output: Option<String>,
    pub data: Value,
}

pub(super) fn workflow_result(
    tool: &str,
    reply: WorkflowReply,
) -> Result<CallToolResult, McpError> {
    workflow_envelope(
        tool,
        reply.status,
        &reply.message,
        reply.error_code,
        reply.output,
        reply.data,
    )
}

pub(super) fn workflow_envelope(
    tool: &str,
    status: ToolResultStatus,
    message: &str,
    error_code: Option<&str>,
    output: Option<String>,
    data: Value,
) -> Result<CallToolResult, McpError> {
    let content =
        output.as_ref().map_or_else(Vec::new, |text| vec![ContentBlock::text(text.clone())]);
    let envelope = ToolResultEnvelope {
        effective_wait: None,
        status,
        tool: tool.to_string(),
        message: message.to_string(),
        output,
        error_code: error_code.map(str::to_string),
        retryable: false,
        retry_same_call: false,
        retry_after_ms: None,
        next_action: None,
        required_reads: Vec::new(),
        data: Some(data),
    };
    let mut result = CallToolResult::success(content);
    result.is_error = Some(matches!(
        status,
        ToolResultStatus::InvalidInput
            | ToolResultStatus::NotFound
            | ToolResultStatus::Denied
            | ToolResultStatus::Failed
    ));
    result.structured_content = Some(serde_json::to_value(envelope).map_err(|error| {
        McpError::internal_error(format!("could not serialize workflow result: {error}"), None)
    })?);
    Ok(result)
}

pub(super) fn history_error_details(error: &HistoryError) -> (ToolResultStatus, &'static str) {
    match error {
        HistoryError::NotFound => (ToolResultStatus::NotFound, "execution_not_found"),
        HistoryError::InvalidInput(_) => {
            (ToolResultStatus::InvalidInput, "invalid_workflow_request")
        }
        HistoryError::InvalidCursor => (ToolResultStatus::InvalidInput, "invalid_execution_cursor"),
        HistoryError::IdentityConflict => {
            (ToolResultStatus::Conflict, "execution_identity_conflict")
        }
        HistoryError::Capacity => {
            (ToolResultStatus::CompletedWithIssues, "execution_history_capacity")
        }
        HistoryError::Io(_) | HistoryError::Json(_) => {
            (ToolResultStatus::Failed, "execution_history_unavailable")
        }
    }
}

pub(super) fn history_failure(
    tool: &str,
    error: &HistoryError,
) -> Result<CallToolResult, McpError> {
    let (status, code) = history_error_details(error);
    workflow_envelope(tool, status, &error.to_string(), Some(code), None, json!({}))
}

pub(super) fn bounded_timeout(value: Option<f32>) -> HistoryResult<Duration> {
    bounded_timeout_up_to(value, super::wait_budget::DEFAULT_EXECUTION_WAIT_MAX_SECONDS)
}

/// Validate a workflow timeout against `ceiling`, which only a client-profile
/// wait budget raises above the public 30 s range.
pub(super) fn bounded_timeout_up_to(value: Option<f32>, ceiling: f32) -> HistoryResult<Duration> {
    let seconds = value.unwrap_or(5.0);
    if !seconds.is_finite() || !(0.0..=ceiling).contains(&seconds) {
        return Err(HistoryError::InvalidInput(format!(
            "timeout_seconds must be between 0 and {ceiling}"
        )));
    }
    Ok(Duration::from_secs_f32(seconds))
}

impl WinxService {
    pub(super) async fn workflow_context(
        &self,
        thread_id: &str,
        workspace_root: &Path,
    ) -> crate::errors::Result<WorkflowContext> {
        if crate::types::normalize_thread_id(thread_id).is_empty() {
            return Err(WinxError::WorkspaceBindingRequired { thread_id: String::new() });
        }
        let (slot, session_guard) = self.tool_session_for(thread_id).await;
        let (scope, allow_prompt) = {
            let guard = slot.lock().await;
            let state = guard.as_ref().ok_or(WinxError::BashStateNotInitialized)?;
            let requested = workspace_root
                .canonicalize()
                .map_err(|error| WinxError::WorkspacePathError(error.to_string()))?;
            if requested != state.workspace_root {
                return Err(WinxError::WorkspaceBindingMismatch {
                    thread_id: thread_id.to_string(),
                    requested_workspace: requested,
                    bound_workspace: state.workspace_root.clone(),
                });
            }
            (
                ExecutionScope {
                    thread_id: state.current_thread_id.clone(),
                    workspace_root: state.workspace_root.clone(),
                },
                matches!(state.mode, Modes::Wcgw),
            )
        };
        Ok(WorkflowContext { slot, scope, allow_prompt, _session_guard: session_guard })
    }

    /// Keep session admission inside the same deadline as the lifecycle wait.
    pub(super) async fn workflow_context_for_wait(
        &self,
        thread_id: &str,
        workspace_root: &Path,
        timing: Option<WaitTiming>,
    ) -> HistoryResult<crate::errors::Result<WorkflowContext>> {
        let guard = phase(Phase::SessionAdmission);
        let operation = self.workflow_context(thread_id, workspace_root);
        let result = if let Some(timing) = timing {
            tokio::time::timeout_at(timing.deadline(), operation).await.map_err(|_| {
                HistoryError::Io(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "execution workflow deadline elapsed before the session context could be acquired",
                ))
            })
        } else {
            Ok(operation.await)
        };
        guard.finish(matches!(&result, Ok(Ok(_))));
        result
    }

    pub(super) async fn handle_execution(
        &self,
        args: Option<Value>,
    ) -> Result<CallToolResult, McpError> {
        let args = args.ok_or_else(|| McpError::invalid_request("Missing arguments", None))?;
        let request: ExecutionRequest = serde_json::from_value(args.clone()).map_err(|error| {
            McpError::invalid_request(format!("Invalid Execution parameters: {error}"), None)
        })?;
        if let ExecutionAction::Observe { items, .. } = &request.action {
            if let Err(error) =
                crate::state::execution_history::validate_observation_requests(items)
            {
                return history_failure("Execution", &error);
            }
        }
        let wait_timing = match &request.action {
            // Only a lifecycle wait may use a client-profile budget above 30 s;
            // an observation is a single bounded pass.
            ExecutionAction::Wait { timeout_seconds, .. } => {
                match WaitTiming::up_to(
                    *timeout_seconds,
                    super::wait_budget::execution_wait_ceiling(),
                ) {
                    Ok(timing) => Some(timing),
                    Err(error) => return history_failure("Execution", &error),
                }
            }
            ExecutionAction::Observe { timeout_seconds, .. } => {
                match WaitTiming::new(*timeout_seconds) {
                    Ok(timing) => Some(timing),
                    Err(error) => return history_failure("Execution", &error),
                }
            }
            _ => None,
        };
        let context = match self
            .workflow_context_for_wait(&request.thread_id, &request.workspace_root, wait_timing)
            .await
        {
            Ok(Ok(context)) => context,
            Ok(Err(error)) => return outcomes::tool_failure("Execution", &error, Some(&args)),
            Err(error) => return history_failure("Execution", &error),
        };
        match self.execution_action(&context, request.action, wait_timing).await {
            Ok(reply) => workflow_result("Execution", reply),
            Err(error) => history_failure("Execution", &error),
        }
    }

    pub(super) async fn execution_action(
        &self,
        context: &WorkflowContext,
        action: ExecutionAction,
        wait_timing: Option<WaitTiming>,
    ) -> HistoryResult<WorkflowReply> {
        match action {
            ExecutionAction::List { limit } => self.execution_list(context, limit).await,
            ExecutionAction::Get { execution_id } => {
                let record = self.execution_record(context, &execution_id, None).await?;
                Ok(WorkflowReply {
                    status: ToolResultStatus::Completed,
                    error_code: None,
                    message: "Retained execution metadata.".into(),
                    output: None,
                    data: json!({ "execution": record }),
                })
            }
            ExecutionAction::Explain { execution_id, recognizer } => {
                let record = self.execution_record(context, &execution_id, recognizer).await?;
                Ok(WorkflowReply {
                    status: ToolResultStatus::Completed,
                    error_code: None,
                    message: "Runtime state and the recognition evidence captured with it.".into(),
                    output: None,
                    data: json!({
                        "execution": record,
                        "historical": record.process_status != ExecutionProcessStatus::Running,
                        "explanation": record.explanation,
                    }),
                })
            }
            ExecutionAction::Read { execution_id, source, cursor, page_bytes } => {
                let record = self.execution_record(context, &execution_id, None).await?;
                let scope = context.scope.clone();
                let catalog = self.execution_history.catalog()?;
                let page = history_call(catalog, move |catalog| {
                    catalog.read(
                        &scope,
                        &execution_id,
                        source,
                        cursor.as_deref(),
                        page_bytes.unwrap_or(DEFAULT_PAGE_BYTES),
                        now_ms(),
                    )
                })
                .await?;
                Ok(WorkflowReply {
                    status: ToolResultStatus::Completed,
                    error_code: None,
                    message: if page.resync_required {
                        "Output retention changed; continue with next_cursor to resynchronize."
                    } else {
                        "One bounded page of retained execution output."
                    }
                    .into(),
                    output: Some(page.text.clone()),
                    data: json!({
                        "page": page,
                        "output_pending": record.output_pending,
                        "output_activity_seq": record.output_activity_seq,
                    }),
                })
            }
            ExecutionAction::Observe { items, timeout_seconds } => {
                self.observe_executions(context, items, timeout_seconds, wait_timing).await
            }
            ExecutionAction::Wait { execution_ids, after, events, timeout_seconds } => {
                self.wait_for_executions(
                    context,
                    execution_ids,
                    after,
                    events,
                    timeout_seconds,
                    wait_timing,
                )
                .await
            }
        }
    }

    async fn execution_list(
        &self,
        context: &WorkflowContext,
        limit: Option<usize>,
    ) -> HistoryResult<WorkflowReply> {
        let limit = limit.unwrap_or(128);
        if !(1..=128).contains(&limit) {
            return Err(HistoryError::InvalidInput("list limit must be between 1 and 128".into()));
        }
        self.refresh_workflow_history(context, None).await?;
        let catalog = self.execution_history.catalog()?;
        let scope = context.scope.clone();
        let mut snapshot =
            history_call(catalog, move |catalog| catalog.list(&scope, now_ms())).await?;
        let omitted = snapshot.executions.len().saturating_sub(limit);
        snapshot.executions.truncate(limit);
        Ok(WorkflowReply {
            status: ToolResultStatus::Completed,
            error_code: None,
            message: "Executions retained for this principal, thread and workspace.".into(),
            output: None,
            data: json!({ "catalog": snapshot, "omitted": omitted }),
        })
    }

    pub(super) async fn execution_record(
        &self,
        context: &WorkflowContext,
        execution_id: &str,
        recognizer: Option<String>,
    ) -> HistoryResult<ExecutionRecord> {
        let catalog = self.execution_history.catalog()?;
        let scope = context.scope.clone();
        let id = execution_id.to_string();
        let record = history_call(catalog.clone(), move |catalog| {
            catalog.get(&scope, &id, now_ms())?.ok_or(HistoryError::NotFound)
        })
        .await?;
        if (record.process_status == ExecutionProcessStatus::Exited && !record.output_pending)
            || !self
                .shell_runtime
                .supports_agent_workflows_for(&context.slot)
                .await
                .unwrap_or(false)
        {
            return Ok(record);
        }
        refresh_record(
            self.shell_runtime.as_ref(),
            &context.slot,
            &catalog,
            &context.scope,
            &record,
            recognizer,
        )
        .await
    }

    pub(super) async fn refresh_workflow_history(
        &self,
        context: &WorkflowContext,
        execution_ids: Option<&[String]>,
    ) -> HistoryResult<bool> {
        let supported =
            self.shell_runtime.supports_agent_workflows_for(&context.slot).await.unwrap_or(false);
        if !supported {
            return Ok(false);
        }
        let catalog = self.execution_history.catalog()?;
        let scope = context.scope.clone();
        let snapshot =
            history_call(catalog.clone(), move |catalog| catalog.list(&scope, now_ms())).await?;
        for record in snapshot.executions.iter().filter(|record| {
            (record.process_status != ExecutionProcessStatus::Exited || record.output_pending)
                && execution_ids.is_none_or(|ids| ids.contains(&record.execution_id))
        }) {
            refresh_record(
                self.shell_runtime.as_ref(),
                &context.slot,
                &catalog,
                &context.scope,
                record,
                None,
            )
            .await?;
        }
        Ok(true)
    }
}