返回 CodeWhale
jobs.rs
1 //! `/v1/jobs` — the client-facing shell job surface.
2 //!
3 //! One authority: every job lives on the thread's shared `ShellManager`, the
4 //! same manager the thread's engine uses for model-launched shell work. Jobs
5 //! created here carry an `api:{thread_id}` owner scope so an engine's
6 //! per-session completion drain never claims client-launched work as model
7 //! evidence — and the model's jobs never appear "client-owned" here.
8
9 use std::collections::{BTreeMap, HashMap};
10
11 use axum::Json;
12 use axum::extract::{Path, Query, State};
13 use axum::http::StatusCode;
14 use base64::Engine as _;
15 use serde::{Deserialize, Serialize};
16
17 use codewhale_engine::runtime_threads::RuntimeThreadStore;
18 use codewhale_engine::runtime_threads::job_operations::{
19 JobOperation, JobOperationRecord, JobOperationTransaction, JobOperationsBusy,
20 request_fingerprint, validate_key,
21 };
22 use codewhale_engine::tools::shell::SharedShellManager;
23 use codewhale_engine::tools::shell::{
24 PtyDimensions, ShellHoldError, ShellJobHold, ShellJobSnapshot, ShellLaunchNotStarted,
25 ShellManager, ShellOutputChunk, ShellOutputStream, ShellResult, ShellStatus,
26 };
27
28 use super::{ApiError, RuntimeApiState, map_thread_err};
29
30 /// `owner_session_id` prefix for jobs launched through this API. A real
31 /// engine session id can never carry it, so `*_for_session` drains stay
32 /// model-owned and API listings can tell the two apart.
33 const API_JOB_SCOPE_PREFIX: &str = "api:";
34
35 const COMMAND_MAX_BYTES: usize = 32 * 1024;
36 const ENV_MAX_ENTRIES: usize = 64;
37 const ENV_KEY_MAX_BYTES: usize = 128;
38 const ENV_VALUE_MAX_BYTES: usize = 8 * 1024;
39 const OUTPUT_CHUNK_DEFAULT: usize = 64 * 1024;
40 const OUTPUT_CHUNK_MAX: usize = 512 * 1024;
41 const OUTPUT_WAIT_MAX_MS: u64 = 30_000;
42 const STDIN_MAX_BYTES: usize = 64 * 1024;
43 const JOB_ID_MAX_BYTES: usize = 128;
44 const OWNER_KEEPALIVE_MAX_SECONDS: u64 = 3_600;
45 const JOB_DEADLINE_MAX_SECONDS: i64 = 24 * 3_600;
46 const JOB_HOLD_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
47
48 fn api_job_scope(thread_id: &str) -> String {
49 format!("{API_JOB_SCOPE_PREFIX}{thread_id}")
50 }
51
52 fn job_owner(snapshot: &ShellJobSnapshot) -> &'static str {
53 if snapshot.owner_agent_id.is_some() {
54 "subagent"
55 } else if snapshot.owner_session_id.starts_with(API_JOB_SCOPE_PREFIX) {
56 "client"
57 } else {
58 "agent"
59 }
60 }
61
62 fn map_job_err(error: anyhow::Error) -> ApiError {
63 let message = error.to_string();
64 if message.ends_with("not found") {
65 ApiError::not_found(message)
66 } else {
67 ApiError::internal(message)
68 }
69 }
70
71 #[derive(Debug, Serialize)]
72 pub(super) struct JobView {
73 #[serde(flatten)]
74 snapshot: ShellJobSnapshot,
75 thread_id: String,
76 /// `client` = launched through this API, `agent` = launched by the model's
77 /// shell tool, `subagent` = owned by a delegated agent.
78 owner: &'static str,
79 /// Null for historical records whose original transport is not known.
80 tty: Option<bool>,
81 terminal_size: Option<PtyDimensions>,
82 #[serde(skip_serializing_if = "Option::is_none")]
83 last_progress_at: Option<chrono::DateTime<chrono::Utc>>,
84 #[serde(flatten)]
85 hold: Option<ShellJobHold>,
86 }
87
88 impl JobView {
89 fn new(snapshot: ShellJobSnapshot, thread_id: String, manager: &ShellManager) -> Self {
90 let owner = job_owner(&snapshot);
91 let terminal_size = manager.job_terminal_size(&snapshot.job_id);
92 let tty = (!snapshot.stale).then_some(terminal_size.is_some());
93 let last_progress_at = manager.job_last_progress_at(&snapshot.job_id);
94 let hold = manager.job_hold(&snapshot.job_id);
95 Self {
96 snapshot,
97 thread_id,
98 owner,
99 tty,
100 terminal_size,
101 last_progress_at,
102 hold,
103 }
104 }
105 }
106
107 fn map_hold_err(error: ShellHoldError) -> ApiError {
108 match error {
109 ShellHoldError::NotFound => ApiError::not_found("job not found"),
110 ShellHoldError::NotRunning => {
111 ApiError::conflict(error.to_string()).with_code("job_not_running")
112 }
113 ShellHoldError::NotHeld => ApiError::conflict(error.to_string()).with_code("job_not_held"),
114 ShellHoldError::Expired => {
115 ApiError::conflict(error.to_string()).with_code("job_keepalive_expired")
116 }
117 }
118 }
119
120 fn enforce_hold(manager: std::sync::Weak<std::sync::Mutex<ShellManager>>, job_id: String) {
121 tokio::spawn(async move {
122 loop {
123 tokio::time::sleep(JOB_HOLD_CHECK_INTERVAL).await;
124 let manager = manager.clone();
125 let job_id = job_id.clone();
126 let holding = tokio::task::spawn_blocking(move || {
127 manager.upgrade().is_some_and(|manager| {
128 manager
129 .lock()
130 .unwrap_or_else(|e| e.into_inner())
131 .enforce_job_hold(&job_id)
132 })
133 })
134 .await
135 .unwrap_or(true);
136 if !holding {
137 break;
138 }
139 }
140 });
141 }
142
143 #[derive(Debug, Serialize)]
144 pub(super) struct JobListResponse {
145 jobs: Vec<JobView>,
146 }
147
148 /// `GET /v1/jobs` — every live and known-stale job across all threads.
149 pub(super) async fn list_jobs(
150 State(state): State<RuntimeApiState>,
151 ) -> Result<Json<JobListResponse>, ApiError> {
152 let managers = state.runtime_threads.shell_managers_snapshot().await;
153 let jobs = tokio::task::spawn_blocking(move || {
154 let mut jobs = Vec::new();
155 for (thread_id, manager) in managers {
156 let mut guard = manager.lock().unwrap_or_else(|e| e.into_inner());
157 jobs.extend(
158 guard
159 .list_jobs()
160 .into_iter()
161 .map(|snapshot| JobView::new(snapshot, thread_id.clone(), &guard)),
162 );
163 }
164 jobs
165 })
166 .await
167 .map_err(|_| ApiError::internal("job listing failed"))?;
168 Ok(Json(JobListResponse { jobs }))
169 }
170
171 async fn thread_manager(
172 state: &RuntimeApiState,
173 thread_id: &str,
174 create: bool,
175 ) -> Result<codewhale_engine::tools::shell::SharedShellManager, ApiError> {
176 state
177 .runtime_threads
178 .thread_shell_manager(thread_id, create)
179 .await
180 .map_err(map_thread_err)?
181 .ok_or_else(|| ApiError::not_found(format!("thread {thread_id} has no jobs")))
182 }
183
184 /// `GET /v1/threads/{id}/jobs` — all jobs owned by one thread's manager:
185 /// model-launched, subagent-launched, and client-launched together.
186 pub(super) async fn list_thread_jobs(
187 State(state): State<RuntimeApiState>,
188 Path(thread_id): Path<String>,
189 ) -> Result<Json<JobListResponse>, ApiError> {
190 let Some(manager) = state
191 .runtime_threads
192 .thread_shell_manager(&thread_id, false)
193 .await
194 .map_err(map_thread_err)?
195 else {
196 return Ok(Json(JobListResponse { jobs: Vec::new() }));
197 };
198 let jobs = tokio::task::spawn_blocking(move || {
199 let mut guard = manager.lock().unwrap_or_else(|e| e.into_inner());
200 guard
201 .list_jobs()
202 .into_iter()
203 .map(|snapshot| JobView::new(snapshot, thread_id.clone(), &guard))
204 .collect()
205 })
206 .await
207 .map_err(|_| ApiError::internal("job listing failed"))?;
208 Ok(Json(JobListResponse { jobs }))
209 }
210
211 #[derive(Deserialize)]
212 #[serde(deny_unknown_fields)]
213 pub(super) struct CreateJobRequest {
214 command: String,
215 /// Working directory. Omitted = the thread's workspace.
216 cwd: Option<String>,
217 /// Bounds the foreground-wait contract inside the manager; background
218 /// jobs are never killed at timeout.
219 timeout_ms: Option<u64>,
220 /// Run under a PTY: stderr merges into stdout and the command sees a
221 /// terminal. Required for interactive programs.
222 #[serde(default)]
223 tty: bool,
224 #[serde(default)]
225 env: HashMap<String, String>,
226 operation_key: Option<String>,
227 purpose: Option<String>,
228 expected_store_id: Option<String>,
229 expected_workspace: Option<String>,
230 owner_keepalive_seconds: Option<u64>,
231 deadline_at: Option<String>,
232 }
233
234 #[derive(Debug, Serialize)]
235 pub(super) struct CreateJobResponse {
236 job: Option<JobView>,
237 #[serde(skip_serializing_if = "Option::is_none")]
238 operation: Option<JobOperation>,
239 #[serde(skip_serializing_if = "Option::is_none")]
240 request_fingerprint: Option<String>,
241 }
242
243 pub(super) type JobManagers = Vec<(String, SharedShellManager)>;
244
245 pub(super) fn operation_error(error: anyhow::Error) -> ApiError {
246 if error.downcast_ref::<JobOperationsBusy>().is_some() {
247 ApiError::conflict("job operation admission is busy").with_code("job_operation_pending")
248 } else {
249 ApiError::internal("job operation storage unavailable")
250 }
251 }
252
253 pub(super) fn project_operation(
254 transaction: &JobOperationTransaction<'_>,
255 record: &mut JobOperationRecord,
256 managers: &JobManagers,
257 generation: &str,
258 ) -> Result<(JobOperation, Option<JobView>), ApiError> {
259 let mut operation = record.operation.clone();
260 let mut view = None;
261 if !matches!(operation.status.as_str(), "completed" | "rejected") {
262 operation.status = "unknown".to_string();
263 if record.owner_generation == generation
264 && let Some(job_id) = record.operation.job_id.clone()
265 && let Some((_, manager)) = managers
266 .iter()
267 .find(|(thread, _)| thread == &operation.thread_id)
268 && let Ok(mut manager) = manager.lock()
269 && let Some(witness) = manager.job_receipt_witness(&job_id)
270 && !witness.wait_failed
271 && (witness.status == ShellStatus::Running || witness.terminal_confirmed)
272 && witness.owner_session_id == api_job_scope(&operation.thread_id)
273 && witness.cwd == operation.cwd
274 {
275 operation.status = if witness.status == ShellStatus::Running {
276 "running"
277 } else {
278 "completed"
279 }
280 .to_string();
281 if operation.status == "completed" {
282 operation.job_status = Some(format!("{:?}", witness.status));
283 operation.exit_code = witness.exit_code;
284 operation.stop_reason = witness.stop_reason;
285 operation.updated_at_ms = chrono::Utc::now()
286 .timestamp_millis()
287 .max(operation.created_at_ms);
288 record.operation = operation.clone();
289 transaction.save(record).map_err(operation_error)?;
290 manager.release_job_receipt(&job_id);
291 }
292 if let Ok(detail) = manager.inspect_job(&job_id)
293 && !detail.snapshot.stale
294 {
295 view = Some(JobView::new(
296 detail.snapshot,
297 operation.thread_id.clone(),
298 &manager,
299 ));
300 }
301 }
302 } else if record.owner_generation == generation
303 && let Some(job_id) = operation.job_id.as_deref()
304 && let Some((_, manager)) = managers
305 .iter()
306 .find(|(thread, _)| thread == &operation.thread_id)
307 && let Ok(mut manager) = manager.lock()
308 && let Ok(detail) = manager.inspect_job(job_id)
309 && !detail.snapshot.stale
310 && detail.snapshot.owner_session_id == api_job_scope(&operation.thread_id)
311 && detail.snapshot.cwd == operation.cwd
312 {
313 view = Some(JobView::new(
314 detail.snapshot,
315 operation.thread_id.clone(),
316 &manager,
317 ));
318 }
319 Ok((operation, view))
320 }
321
322 fn observe_operation(
323 store: RuntimeThreadStore,
324 runtime_owner: std::sync::Weak<
325 codewhale_engine::runtime_threads::manager::RuntimeThreadManager,
326 >,
327 manager: std::sync::Weak<std::sync::Mutex<ShellManager>>,
328 thread_id: String,
329 generation: String,
330 id: String,
331 ) {
332 tokio::spawn(async move {
333 let mut delay = std::time::Duration::from_millis(500);
334 loop {
335 tokio::time::sleep(delay).await;
336 let store = store.clone();
337 let runtime_owner = runtime_owner.clone();
338 let manager = manager.clone();
339 let thread_id = thread_id.clone();
340 let generation = generation.clone();
341 let id = id.clone();
342 let result = tokio::task::spawn_blocking(move || {
343 let Some(runtime_owner) = runtime_owner.upgrade() else {
344 return Ok(None);
345 };
346 if runtime_owner.job_operation_generation().ok().as_deref()
347 != Some(generation.as_str())
348 {
349 return Ok(None);
350 }
351 let Some(manager) = manager.upgrade() else {
352 return Ok(None);
353 };
354 let managers = vec![(thread_id, manager)];
355 store.with_job_operations(|transaction| {
356 let Some(mut record) = transaction.get(&id)? else {
357 return Ok(None);
358 };
359 let projected =
360 project_operation(transaction, &mut record, &managers, &generation)
361 .map_err(|_| anyhow::anyhow!("job observation unavailable"))?;
362 match projected.0.status.as_str() {
363 "running" => Ok(Some(true)),
364 "unknown" => {
365 let available =
366 record.operation.job_id.as_deref().is_some_and(|job_id| {
367 managers[0].1.lock().ok().is_some_and(|mut manager| {
368 manager.job_receipt_witness(job_id).is_some()
369 })
370 });
371 Ok(available.then_some(false))
372 }
373 _ => Ok(None),
374 }
375 })
376 })
377 .await;
378 match result {
379 Ok(Ok(Some(true))) => delay = std::time::Duration::from_millis(500),
380 Ok(Ok(Some(false))) => delay = (delay * 2).min(std::time::Duration::from_secs(10)),
381 Ok(Ok(None)) => break,
382 _ => delay = (delay * 2).min(std::time::Duration::from_secs(10)),
383 }
384 }
385 });
386 }
387
388 pub(super) fn overlaps(left: &std::path::Path, right: &std::path::Path) -> bool {
389 left.starts_with(right) || right.starts_with(left)
390 }
391
392 #[derive(Serialize)]
393 pub(super) struct JobOperationsResponse {
394 operations: Vec<JobOperation>,
395 }
396
397 pub(super) async fn list_job_operations(
398 State(state): State<RuntimeApiState>,
399 ) -> Result<Json<JobOperationsResponse>, ApiError> {
400 list_operations(&state, None).await
401 }
402
403 pub(super) async fn list_thread_job_operations(
404 State(state): State<RuntimeApiState>,
405 Path(thread): Path<String>,
406 ) -> Result<Json<JobOperationsResponse>, ApiError> {
407 state
408 .runtime_threads
409 .get_thread(&thread)
410 .await
411 .map_err(map_thread_err)?;
412 list_operations(&state, Some(thread)).await
413 }
414
415 async fn list_operations(
416 state: &RuntimeApiState,
417 thread: Option<String>,
418 ) -> Result<Json<JobOperationsResponse>, ApiError> {
419 let managers = state.runtime_threads.shell_managers_snapshot().await;
420 let generation = state
421 .runtime_threads
422 .job_operation_generation()
423 .map_err(operation_error)?;
424 let store = state.runtime_threads.job_operation_store();
425 let operations = tokio::task::spawn_blocking(move || {
426 store.with_job_operations(|transaction| {
427 let mut operations = Vec::new();
428 for mut record in transaction.list()? {
429 if thread
430 .as_ref()
431 .is_none_or(|thread| thread == &record.operation.thread_id)
432 {
433 let (operation, _) =
434 project_operation(transaction, &mut record, &managers, &generation)
435 .map_err(|_| anyhow::anyhow!("job operation projection failed"))?;
436 operations.push(operation);
437 }
438 }
439 Ok(operations)
440 })
441 })
442 .await
443 .map_err(|_| ApiError::internal("job operation listing failed"))?
444 .map_err(operation_error)?;
445 Ok(Json(JobOperationsResponse { operations }))
446 }
447
448 pub(super) async fn get_job_operation(
449 State(state): State<RuntimeApiState>,
450 Path((thread, key)): Path<(String, String)>,
451 ) -> Result<Json<CreateJobResponse>, ApiError> {
452 validate_key(&key).map_err(|_| ApiError::bad_request("invalid job operation key"))?;
453 state
454 .runtime_threads
455 .get_thread(&thread)
456 .await
457 .map_err(map_thread_err)?;
458 let managers = state.runtime_threads.shell_managers_snapshot().await;
459 let generation = state
460 .runtime_threads
461 .job_operation_generation()
462 .map_err(operation_error)?;
463 let store = state.runtime_threads.job_operation_store();
464 let result = tokio::task::spawn_blocking(move || {
465 store.with_job_operations(|transaction| {
466 let id = transaction.operation_id(&thread, &key)?;
467 let Some(mut record) = transaction.get(&id)? else {
468 return Ok(None);
469 };
470 let result = project_operation(transaction, &mut record, &managers, &generation)
471 .map_err(|_| anyhow::anyhow!("job operation projection failed"))?;
472 Ok(Some((
473 result.0,
474 result.1,
475 record.request_fingerprint.clone(),
476 )))
477 })
478 })
479 .await
480 .map_err(|_| ApiError::internal("job operation lookup failed"))?
481 .map_err(operation_error)?;
482 let (operation, job, fingerprint) =
483 result.ok_or_else(|| ApiError::not_found("job operation not found"))?;
484 Ok(Json(CreateJobResponse {
485 job,
486 operation: Some(operation),
487 request_fingerprint: Some(fingerprint),
488 }))
489 }
490
491 /// Resolve a job `cwd` against the thread workspace, never the server's cwd.
492 /// Outside trust mode the directory must stay inside the workspace once
493 /// symlinks resolve. This is stricter than the shell tool's `resolve_path`:
494 /// the route has no `workspace_follow_symlinks` or `/trust add` roots and no
495 /// `~` expansion, so a symlink leading out of the workspace is refused.
496 ///
497 /// The manager receives the canonical directory that was checked, not the
498 /// caller's spelling: a symlink retargeted between this check and the launch
499 /// cannot move the job elsewhere. The manager takes a `&str`, so a directory
500 /// whose name is not UTF-8 is refused rather than lossily renamed into a
501 /// different one. On Windows the `\\?\` verbatim prefix `canonicalize` adds
502 /// is dropped ([`plain_windows_path`]) because `cmd.exe` refuses it as a
503 /// current directory.
504 fn resolve_job_cwd(
505 workspace: &std::path::Path,
506 raw: &str,
507 trust_mode: bool,
508 ) -> Result<String, ApiError> {
509 let requested = std::path::Path::new(raw);
510 let candidate = if requested.is_absolute() {
511 requested.to_path_buf()
512 } else {
513 workspace.join(requested)
514 };
515 let not_a_directory = || ApiError::bad_request("cwd must be an existing directory");
516 let resolved = std::fs::canonicalize(&candidate).map_err(|_| not_a_directory())?;
517 if !std::fs::metadata(&resolved).is_ok_and(|meta| meta.is_dir()) {
518 return Err(not_a_directory());
519 }
520 if !trust_mode {
521 let root = std::fs::canonicalize(workspace)
522 .map_err(|_| ApiError::internal("thread workspace is unavailable"))?;
523 if !resolved.starts_with(&root) {
524 return Err(ApiError::forbidden(
525 "cwd must stay inside the thread workspace",
526 ));
527 }
528 }
529 let resolved = resolved
530 .into_os_string()
531 .into_string()
532 .map_err(|_| ApiError::bad_request("cwd must resolve to a UTF-8 path"))?;
533 Ok(if cfg!(windows) {
534 plain_windows_path(&resolved)
535 } else {
536 resolved
537 })
538 }
539
540 /// `\\?\C:\dir` -> `C:\dir` and `\\?\UNC\host\share` -> `\\host\share`; any
541 /// other spelling is returned unchanged. A string rule so every host tests it.
542 pub(super) fn plain_windows_path(path: &str) -> String {
543 if let Some(rest) = path.strip_prefix(r"\\?\UNC\") {
544 return format!(r"\\{rest}");
545 }
546 match path.strip_prefix(r"\\?\") {
547 Some(rest)
548 if rest.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
549 && rest.as_bytes().get(1) == Some(&b':') =>
550 {
551 rest.to_string()
552 }
553 _ => path.to_string(),
554 }
555 }
556
557 fn canonical_job_path(path: &std::path::Path) -> Option<std::path::PathBuf> {
558 let path = std::fs::canonicalize(path).ok()?;
559 if cfg!(windows) {
560 path.to_str()
561 .map(|raw| std::path::PathBuf::from(plain_windows_path(raw)))
562 } else {
563 Some(path)
564 }
565 }
566
567 /// `POST /v1/threads/{id}/jobs` — launch a client-owned background job under
568 /// the thread's own sandbox policy. The client asking is the approval; the
569 /// thread's posture still bounds what the job may touch.
570 pub(super) async fn create_thread_job(
571 State(state): State<RuntimeApiState>,
572 Path(thread_id): Path<String>,
573 Json(request): Json<CreateJobRequest>,
574 ) -> Result<(StatusCode, Json<CreateJobResponse>), ApiError> {
575 let command = request.command.trim();
576 if command.is_empty() {
577 return Err(ApiError::bad_request("command is required"));
578 }
579 if command.contains('\0') {
580 return Err(ApiError::bad_request("command contains a NUL byte"));
581 }
582 if command.len() > COMMAND_MAX_BYTES {
583 return Err(ApiError::bad_request(format!(
584 "command must be at most {COMMAND_MAX_BYTES} bytes"
585 )));
586 }
587 if request.env.len() > ENV_MAX_ENTRIES {
588 return Err(ApiError::bad_request(format!(
589 "env may carry at most {ENV_MAX_ENTRIES} entries"
590 )));
591 }
592 for (key, value) in &request.env {
593 if key.is_empty() || key.len() > ENV_KEY_MAX_BYTES || key.contains(['=', '\0']) {
594 return Err(ApiError::bad_request("invalid env key"));
595 }
596 if value.len() > ENV_VALUE_MAX_BYTES || value.contains('\0') {
597 return Err(ApiError::bad_request("invalid env value"));
598 }
599 }
600 #[cfg(target_env = "ohos")]
601 if request.tty {
602 return Err(ApiError::bad_request(
603 "TTY shell mode is not supported on HarmonyOS/OpenHarmony",
604 ));
605 }
606 if request
607 .owner_keepalive_seconds
608 .is_some_and(|seconds| !(1..=OWNER_KEEPALIVE_MAX_SECONDS).contains(&seconds))
609 {
610 return Err(ApiError::bad_request(format!(
611 "owner_keepalive_seconds must be between 1 and {OWNER_KEEPALIVE_MAX_SECONDS}"
612 )));
613 }
614 let deadline_at = request
615 .deadline_at
616 .as_deref()
617 .map(|raw| {
618 let deadline = chrono::DateTime::parse_from_rfc3339(raw)
619 .map_err(|_| ApiError::bad_request("deadline_at must be an RFC 3339 time"))?
620 .with_timezone(&chrono::Utc);
621 let ahead = (deadline - chrono::Utc::now()).num_seconds();
622 if !(1..=JOB_DEADLINE_MAX_SECONDS).contains(&ahead) {
623 return Err(ApiError::bad_request(format!(
624 "deadline_at must be in the future and at most {JOB_DEADLINE_MAX_SECONDS} seconds ahead"
625 )));
626 }
627 Ok(deadline)
628 })
629 .transpose()?;
630 let keepalive = request
631 .owner_keepalive_seconds
632 .map(std::time::Duration::from_secs);
633 let held = keepalive.is_some() || deadline_at.is_some();
634
635 let keyed = match (
636 &request.operation_key,
637 &request.purpose,
638 &request.expected_store_id,
639 &request.expected_workspace,
640 ) {
641 (None, None, None, None) => false,
642 (Some(key), Some(purpose), Some(expected), Some(workspace)) => {
643 if workspace.trim().is_empty() {
644 return Err(ApiError::bad_request("expected_workspace is required"));
645 }
646 validate_key(key).map_err(|_| ApiError::bad_request("invalid job operation key"))?;
647 if !matches!(purpose.as_str(), "setup" | "run" | "archive" | "command") {
648 return Err(ApiError::bad_request("invalid job operation purpose"));
649 }
650 if expected != state.runtime_threads.job_operation_store_id() {
651 return Err(ApiError::conflict("job operation store changed")
652 .with_code("job_operation_store_changed"));
653 }
654 true
655 }
656 _ => {
657 return Err(ApiError::bad_request(
658 "operation_key, purpose, expected_store_id and expected_workspace must be supplied together",
659 ));
660 }
661 };
662 let admission = state.runtime_threads.session_checkpoint_guard().await;
663 let thread = state
664 .runtime_threads
665 .get_thread(&thread_id)
666 .await
667 .map_err(map_thread_err)?;
668 let command = command.to_string();
669 let fingerprint = if let Some(key) = request.operation_key.as_deref() {
670 let env: BTreeMap<_, _> = request.env.iter().collect();
671 let env: Vec<_> = env.into_iter().collect();
672 let payload = if held {
673 serde_json::to_vec(&(
674 3,
675 &thread_id,
676 &request.expected_workspace,
677 &command,
678 &request.cwd,
679 request.timeout_ms.unwrap_or(120_000),
680 request.tty,
681 env,
682 &request.purpose,
683 request.owner_keepalive_seconds,
684 &request.deadline_at,
685 ))
686 } else {
687 serde_json::to_vec(&(
688 2,
689 &thread_id,
690 &request.expected_workspace,
691 &command,
692 &request.cwd,
693 request.timeout_ms.unwrap_or(120_000),
694 request.tty,
695 env,
696 &request.purpose,
697 ))
698 }
699 .map_err(|_| ApiError::internal("job operation validation failed"))?;
700 Some(
701 request_fingerprint(key, &payload)
702 .map_err(|_| ApiError::bad_request("invalid job operation key"))?,
703 )
704 } else {
705 None
706 };
707 let generation = state
708 .runtime_threads
709 .job_operation_generation()
710 .map_err(operation_error)?;
711 let store = state.runtime_threads.job_operation_store();
712 if let Some(key) = request.operation_key.clone() {
713 let lookup_store = store.clone();
714 let lookup_thread = thread_id.clone();
715 let lookup_fingerprint = fingerprint.clone();
716 let lookup_generation = generation.clone();
717 let managers = state.runtime_threads.shell_managers_snapshot().await;
718 let replay = tokio::task::spawn_blocking(move || {
719 lookup_store.with_job_operations(|transaction| {
720 let id = transaction.operation_id(&lookup_thread, &key)?;
721 let Some(mut record) = transaction.get(&id)? else {
722 return Ok(None);
723 };
724 if Some(&record.request_fingerprint) != lookup_fingerprint.as_ref() {
725 return Ok(Some(Err(ApiError::conflict(
726 "job operation key belongs to a different request",
727 )
728 .with_code("job_operation_mismatch"))));
729 }
730 Ok(Some(
731 project_operation(transaction, &mut record, &managers, &lookup_generation).map(
732 |(operation, job)| (operation, job, record.request_fingerprint.clone()),
733 ),
734 ))
735 })
736 })
737 .await
738 .map_err(|_| ApiError::internal("job operation lookup failed"))?
739 .map_err(operation_error)?;
740 if let Some(result) = replay {
741 let (operation, job, fingerprint) = result?;
742 return Ok((
743 StatusCode::OK,
744 Json(CreateJobResponse {
745 job,
746 operation: Some(operation),
747 request_fingerprint: Some(fingerprint),
748 }),
749 ));
750 }
751 }
752 if !thread.allow_shell {
753 return Err(ApiError::forbidden(
754 "this thread does not allow shell commands",
755 ));
756 }
757 let requested_workspace = thread.workspace.clone();
758 let expected_workspace = request.expected_workspace.clone();
759 let workspace = tokio::task::spawn_blocking(move || {
760 let workspace = canonical_job_path(&requested_workspace)
761 .ok_or_else(|| ApiError::internal("thread workspace is unavailable"))?;
762 if expected_workspace.as_deref().is_some_and(|expected| {
763 canonical_job_path(std::path::Path::new(expected)).as_ref() != Some(&workspace)
764 }) {
765 return Err(ApiError::conflict("job operation workspace changed")
766 .with_code("job_operation_workspace_changed"));
767 }
768 Ok(workspace)
769 })
770 .await
771 .map_err(|_| ApiError::internal("thread workspace resolution failed"))??;
772 state
773 .runtime_threads
774 .validate_shell_access_policy(
775 &workspace,
776 state.config_path.as_deref(),
777 state.config_profile.as_deref(),
778 )
779 .await
780 .map_err(|error| ApiError::forbidden(error.to_string()))?;
781 let external_backend = codewhale_sandbox::backend::SandboxKind::parse(
782 state
783 .runtime_threads
784 .read_config()
785 .sandbox_backend
786 .as_deref()
787 .unwrap_or("none"),
788 ) != Some(codewhale_sandbox::backend::SandboxKind::None);
789 if external_backend {
790 return Err(ApiError::forbidden(
791 "this server runs commands in an external sandbox backend, and a thread job starts a local process; run the command through the thread's shell tool instead",
792 ));
793 }
794 let mut policy_thread = thread.clone();
795 policy_thread.workspace = workspace.clone();
796 let policy = state
797 .runtime_threads
798 .thread_job_sandbox_policy(&policy_thread)
799 .await;
800 let manager = thread_manager(&state, &thread_id, true).await?;
801 let managers = state.runtime_threads.shell_managers_snapshot().await;
802 let store_id = state.runtime_threads.job_operation_store_id().to_string();
803 let runtime_owner = state.runtime_threads.clone();
804 let scope = api_job_scope(&thread_id);
805 let result = tokio::task::spawn_blocking(move || {
806 let _admission = admission;
807 store.with_job_operations(|transaction| {
808 Ok((|| -> Result<(StatusCode, CreateJobResponse), ApiError> {
809 let id = request
810 .operation_key
811 .as_deref()
812 .map(|key| transaction.operation_id(&thread_id, key))
813 .transpose()
814 .map_err(operation_error)?;
815 if let Some(id) = &id
816 && let Some(mut existing) = transaction.get(id).map_err(operation_error)?
817 {
818 if Some(&existing.request_fingerprint) != fingerprint.as_ref() {
819 return Err(ApiError::conflict(
820 "job operation key belongs to a different request",
821 )
822 .with_code("job_operation_mismatch"));
823 }
824 let (operation, job) =
825 project_operation(transaction, &mut existing, &managers, &generation)?;
826 return Ok((
827 StatusCode::OK,
828 CreateJobResponse {
829 job,
830 operation: Some(operation),
831 request_fingerprint: Some(existing.request_fingerprint.clone()),
832 },
833 ));
834 }
835 if canonical_job_path(&thread.workspace).as_ref() != Some(&workspace)
836 || request
837 .expected_workspace
838 .as_deref()
839 .is_some_and(|expected| {
840 canonical_job_path(std::path::Path::new(expected)).as_ref()
841 != Some(&workspace)
842 })
843 {
844 return Err(ApiError::conflict("job operation workspace changed")
845 .with_code("job_operation_workspace_changed"));
846 }
847 let raw_cwd = request.cwd.as_deref().unwrap_or(".");
848 let cwd = resolve_job_cwd(&workspace, raw_cwd, thread.trust_mode)?;
849 let cwd_path = std::path::PathBuf::from(&cwd);
850 for mut record in transaction.list().map_err(operation_error)? {
851 let (operation, _) =
852 project_operation(transaction, &mut record, &managers, &generation)?;
853 if overlaps(&workspace, &operation.workspace)
854 || overlaps(&workspace, &operation.cwd)
855 || overlaps(&cwd_path, &operation.workspace)
856 || overlaps(&cwd_path, &operation.cwd)
857 {
858 if operation.status == "unknown" {
859 return Err(ApiError::conflict(
860 "an earlier job operation is unconfirmed",
861 )
862 .with_code("job_operation_unconfirmed"));
863 }
864 if keyed
865 && request.purpose.as_deref() != Some("command")
866 && operation.status == "running"
867 && operation.purpose != "command"
868 {
869 return Err(ApiError::conflict(
870 "a workspace script is already running",
871 )
872 .with_code("job_operation_busy"));
873 }
874 }
875 }
876 runtime_owner
877 .validate_job_operation_thread(&thread)
878 .map_err(|_| {
879 ApiError::conflict("job operation workspace or shell policy changed")
880 .with_code("job_operation_workspace_changed")
881 })?;
882 if runtime_owner.job_operation_generation().ok().as_deref()
883 != Some(generation.as_str())
884 {
885 return Err(ApiError::internal("job operation owner changed"));
886 }
887 let mut guard = manager
888 .lock()
889 .map_err(|_| ApiError::internal("job manager unavailable"))?;
890 guard
891 .validate_background_job(
892 &command,
893 &cwd_path,
894 request.timeout_ms.unwrap_or(120_000),
895 &policy,
896 &request.env,
897 )
898 .map_err(|error| ApiError::forbidden(error.to_string()))?;
899 if canonical_job_path(&thread.workspace).as_ref() != Some(&workspace)
900 || canonical_job_path(&cwd_path).as_ref() != Some(&cwd_path)
901 {
902 return Err(ApiError::conflict("job operation workspace changed")
903 .with_code("job_operation_workspace_changed"));
904 }
905 let mut record = if let Some(id) = id {
906 let now = chrono::Utc::now().timestamp_millis();
907 let record = JobOperationRecord {
908 schema_version: 1,
909 operation: JobOperation {
910 id,
911 store_id,
912 thread_id: thread_id.clone(),
913 workspace,
914 cwd: cwd_path,
915 purpose: request.purpose.clone().expect("keyed purpose"),
916 status: "unknown".to_string(),
917 job_id: None,
918 job_status: None,
919 exit_code: None,
920 stop_reason: None,
921 created_at_ms: now,
922 updated_at_ms: now,
923 },
924 request_fingerprint: fingerprint.expect("keyed fingerprint"),
925 owner_generation: generation.clone(),
926 };
927 transaction.save(&record).map_err(operation_error)?;
928 Some(record)
929 } else {
930 None
931 };
932 if runtime_owner.job_operation_generation().ok().as_deref()
933 != Some(generation.as_str())
934 {
935 return Err(ApiError::internal("job operation owner changed")
936 .with_code("job_operation_unconfirmed"));
937 }
938 runtime_owner
939 .validate_job_operation_thread(&thread)
940 .map_err(|_| {
941 ApiError::internal("job operation thread changed")
942 .with_code("job_operation_unconfirmed")
943 })?;
944 let result = match guard.execute_with_options_env_for_session(
945 &command,
946 Some(&cwd),
947 request.timeout_ms.unwrap_or(120_000),
948 true,
949 None,
950 request.tty,
951 Some(policy),
952 request.env,
953 &scope,
954 ) {
955 Ok(result) => result,
956 Err(error) if error.downcast_ref::<ShellLaunchNotStarted>().is_some() => {
957 if let Some(record) = &mut record {
958 record.operation.status = "rejected".to_string();
959 record.operation.updated_at_ms = chrono::Utc::now()
960 .timestamp_millis()
961 .max(record.operation.created_at_ms);
962 transaction.save(record).map_err(|_| {
963 ApiError::internal("job launch could not be confirmed")
964 .with_code("job_operation_unconfirmed")
965 })?;
966 return Err(ApiError::conflict("job did not start")
967 .with_code("job_operation_rejected"));
968 }
969 return Err(ApiError::internal("job did not start"));
970 }
971 Err(_) => {
972 return Err(ApiError::internal("job launch could not be confirmed")
973 .with_code("job_operation_unconfirmed"));
974 }
975 };
976 let task_id = result.task_id.ok_or_else(|| {
977 ApiError::internal("job launch could not be confirmed")
978 .with_code("job_operation_unconfirmed")
979 })?;
980 if held && guard.hold_job(&task_id, keepalive, deadline_at).is_err() {
981 let _ = guard.kill(&task_id);
982 return Err(ApiError::internal("job launch could not be confirmed")
983 .with_code("job_operation_unconfirmed"));
984 }
985 if record.is_some() {
986 guard.pin_job_receipt(&task_id).map_err(|_| {
987 ApiError::internal("job launch could not be confirmed")
988 .with_code("job_operation_unconfirmed")
989 })?;
990 }
991 let snapshot = guard
992 .inspect_job(&task_id)
993 .map_err(|_| {
994 ApiError::internal("job launch could not be confirmed")
995 .with_code("job_operation_unconfirmed")
996 })?
997 .snapshot;
998 let job = JobView::new(snapshot, thread_id.clone(), &guard);
999 if held {
1000 enforce_hold(std::sync::Arc::downgrade(&manager), task_id.clone());
1001 }
1002 if let Some(record) = &mut record {
1003 record.operation.job_id = Some(task_id);
1004 record.operation.status = "running".to_string();
1005 record.operation.updated_at_ms = chrono::Utc::now()
1006 .timestamp_millis()
1007 .max(record.operation.created_at_ms);
1008 transaction.save(record).map_err(operation_error)?;
1009 observe_operation(
1010 store.clone(),
1011 std::sync::Arc::downgrade(&runtime_owner),
1012 std::sync::Arc::downgrade(&manager),
1013 thread_id,
1014 generation,
1015 record.operation.id.clone(),
1016 );
1017 }
1018 Ok((
1019 StatusCode::CREATED,
1020 CreateJobResponse {
1021 job: Some(job),
1022 request_fingerprint: record
1023 .as_ref()
1024 .map(|record| record.request_fingerprint.clone()),
1025 operation: record.map(|record| record.operation),
1026 },
1027 ))
1028 })())
1029 })
1030 })
1031 .await
1032 .map_err(|_| ApiError::internal("job launch failed"))?
1033 .map_err(operation_error)??;
1034 Ok((result.0, Json(result.1)))
1035 }
1036
1037 #[derive(Debug, Serialize)]
1038 pub(super) struct JobDetailResponse {
1039 job: JobView,
1040 stdout_tail: String,
1041 stderr_tail: String,
1042 }
1043
1044 /// `GET /v1/threads/{id}/jobs/{job_id}` — snapshot plus the retained output
1045 /// tails. For the full stream, follow `output` with a cursor instead.
1046 pub(super) async fn get_thread_job(
1047 State(state): State<RuntimeApiState>,
1048 Path((thread_id, job_id)): Path<(String, String)>,
1049 ) -> Result<Json<JobDetailResponse>, ApiError> {
1050 if job_id.len() > JOB_ID_MAX_BYTES {
1051 return Err(ApiError::not_found("job not found"));
1052 }
1053 let manager = thread_manager(&state, &thread_id, false).await?;
1054 tokio::task::spawn_blocking(move || {
1055 let mut guard = manager.lock().unwrap_or_else(|e| e.into_inner());
1056 let detail = guard.inspect_job(&job_id).map_err(map_job_err)?;
1057 Ok(Json(JobDetailResponse {
1058 job: JobView::new(detail.snapshot, thread_id, &guard),
1059 stdout_tail: detail.stdout,
1060 stderr_tail: detail.stderr,
1061 }))
1062 })
1063 .await
1064 .map_err(|_| ApiError::internal("job inspect failed"))?
1065 }
1066
1067 #[derive(Deserialize)]
1068 #[serde(deny_unknown_fields)]
1069 pub(super) struct JobOutputQuery {
1070 /// `stdout` (default) or `stderr`; PTY jobs merge stderr into stdout.
1071 #[serde(default)]
1072 stream: Option<String>,
1073 /// Absolute byte offset into the stream's lifetime output.
1074 #[serde(default)]
1075 cursor: Option<usize>,
1076 /// Per-request byte ceiling, default 64 KiB, max 512 KiB.
1077 #[serde(default)]
1078 max_bytes: Option<usize>,
1079 /// Long-poll bound for new bytes on a running job, max 30s.
1080 #[serde(default)]
1081 wait_ms: Option<u64>,
1082 /// `base64` (default, exact bytes) or `text` (lossy UTF-8).
1083 #[serde(default)]
1084 format: Option<String>,
1085 }
1086
1087 #[derive(Debug, Serialize)]
1088 pub(super) struct JobOutputResponse {
1089 job_id: String,
1090 stream: &'static str,
1091 /// Absolute offset of `data[0]`; exceeds `cursor` when the bounded buffer
1092 /// already discarded that prefix (`dropped` reports the cutoff).
1093 offset: usize,
1094 /// Next cursor: pass it back to continue the stream.
1095 next_cursor: usize,
1096 /// Total bytes the stream has produced, including discarded bytes.
1097 total: usize,
1098 /// Leading bytes permanently discarded by the in-flight bound.
1099 dropped: usize,
1100 encoding: &'static str,
1101 data: String,
1102 status: ShellStatus,
1103 exit_code: Option<i64>,
1104 /// Terminal status and no bytes remain past `next_cursor`.
1105 done: bool,
1106 }
1107
1108 /// `GET /v1/threads/{id}/jobs/{job_id}/output` — the resumable byte stream.
1109 /// Reads are non-consuming: several clients may hold independent cursors, and
1110 /// polling here never steals output from the engine's own delta consumer.
1111 pub(super) async fn get_thread_job_output(
1112 State(state): State<RuntimeApiState>,
1113 Path((thread_id, job_id)): Path<(String, String)>,
1114 Query(query): Query<JobOutputQuery>,
1115 ) -> Result<Json<JobOutputResponse>, ApiError> {
1116 if job_id.len() > JOB_ID_MAX_BYTES {
1117 return Err(ApiError::not_found("job not found"));
1118 }
1119 let (stream, stream_name) = match query.stream.as_deref().unwrap_or("stdout") {
1120 "stdout" => (ShellOutputStream::Stdout, "stdout"),
1121 "stderr" => (ShellOutputStream::Stderr, "stderr"),
1122 _ => return Err(ApiError::bad_request("stream must be stdout or stderr")),
1123 };
1124 let cursor = query.cursor.unwrap_or(0);
1125 let max_bytes = query.max_bytes.unwrap_or(OUTPUT_CHUNK_DEFAULT);
1126 if !(1..=OUTPUT_CHUNK_MAX).contains(&max_bytes) {
1127 return Err(ApiError::bad_request(format!(
1128 "max_bytes must be between 1 and {OUTPUT_CHUNK_MAX}"
1129 )));
1130 }
1131 let wait_ms = query.wait_ms.unwrap_or(0).min(OUTPUT_WAIT_MAX_MS);
1132 let format = query.format.as_deref().unwrap_or("base64");
1133 if !matches!(format, "base64" | "text") {
1134 return Err(ApiError::bad_request("format must be base64 or text"));
1135 }
1136 let manager = thread_manager(&state, &thread_id, false).await?;
1137 let chunk = tokio::task::spawn_blocking({
1138 let job_id = job_id.clone();
1139 move || -> Result<ShellOutputChunk, ApiError> {
1140 // Wait between non-consuming snapshots, never while owning the
1141 // thread's shared ShellManager. Input, resize, and kill stay live.
1142 let deadline = std::time::Instant::now() + std::time::Duration::from_millis(wait_ms);
1143 loop {
1144 let chunk = {
1145 let mut guard = manager.lock().unwrap_or_else(|e| e.into_inner());
1146 guard
1147 .read_output_chunk(&job_id, stream, cursor, max_bytes, 0)
1148 .map_err(map_job_err)?
1149 };
1150 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
1151 if chunk.total > cursor
1152 || chunk.status != ShellStatus::Running
1153 || remaining.is_zero()
1154 {
1155 break Ok(chunk);
1156 }
1157 std::thread::sleep(remaining.min(std::time::Duration::from_millis(50)));
1158 }
1159 }
1160 })
1161 .await
1162 .map_err(|_| ApiError::internal("job output read failed"))??;
1163 Ok(Json(encode_chunk(&job_id, stream_name, chunk, format)))
1164 }
1165
1166 fn encode_chunk(
1167 job_id: &str,
1168 stream_name: &'static str,
1169 chunk: ShellOutputChunk,
1170 format: &str,
1171 ) -> JobOutputResponse {
1172 let (encoding, data) = match format {
1173 "text" => ("utf-8", String::from_utf8_lossy(&chunk.bytes).into_owned()),
1174 _ => (
1175 "base64",
1176 base64::engine::general_purpose::STANDARD.encode(&chunk.bytes),
1177 ),
1178 };
1179 let done = chunk.status != ShellStatus::Running && chunk.next_offset >= chunk.total;
1180 JobOutputResponse {
1181 job_id: job_id.to_string(),
1182 stream: stream_name,
1183 offset: chunk.offset,
1184 next_cursor: chunk.next_offset,
1185 total: chunk.total,
1186 dropped: chunk.dropped,
1187 encoding,
1188 data,
1189 status: chunk.status,
1190 exit_code: chunk.exit_code,
1191 done,
1192 }
1193 }
1194
1195 #[derive(Deserialize)]
1196 #[serde(deny_unknown_fields)]
1197 pub(super) struct JobStdinRequest {
1198 /// UTF-8 text (default) or base64 for arbitrary bytes.
1199 data: String,
1200 #[serde(default)]
1201 encoding: Option<String>,
1202 /// Close stdin after writing (EOF).
1203 #[serde(default)]
1204 close: bool,
1205 }
1206
1207 /// `POST /v1/threads/{id}/jobs/{job_id}/stdin` — write to a running job's
1208 /// stdin. Works for PTY and piped jobs alike.
1209 pub(super) async fn write_thread_job_stdin(
1210 State(state): State<RuntimeApiState>,
1211 Path((thread_id, job_id)): Path<(String, String)>,
1212 Json(request): Json<JobStdinRequest>,
1213 ) -> Result<StatusCode, ApiError> {
1214 if job_id.len() > JOB_ID_MAX_BYTES {
1215 return Err(ApiError::not_found("job not found"));
1216 }
1217 let input = match request.encoding.as_deref().unwrap_or("utf-8") {
1218 "utf-8" => {
1219 if request.data.len() > STDIN_MAX_BYTES {
1220 return Err(ApiError::bad_request(format!(
1221 "data must be at most {STDIN_MAX_BYTES} bytes"
1222 )));
1223 }
1224 request.data.into_bytes()
1225 }
1226 "base64" => {
1227 if request.data.len() > STDIN_MAX_BYTES * 2 {
1228 return Err(ApiError::bad_request("data exceeds the stdin limit"));
1229 }
1230 let bytes = base64::engine::general_purpose::STANDARD
1231 .decode(&request.data)
1232 .map_err(|_| ApiError::bad_request("data is not valid base64"))?;
1233 if bytes.len() > STDIN_MAX_BYTES {
1234 return Err(ApiError::bad_request(format!(
1235 "data must be at most {STDIN_MAX_BYTES} decoded bytes"
1236 )));
1237 }
1238 bytes
1239 }
1240 _ => return Err(ApiError::bad_request("encoding must be utf-8 or base64")),
1241 };
1242 let close = request.close;
1243 let manager = thread_manager(&state, &thread_id, false).await?;
1244 tokio::task::spawn_blocking(move || {
1245 let mut guard = manager.lock().unwrap_or_else(|e| e.into_inner());
1246 guard
1247 .write_stdin_bytes(&job_id, &input, close)
1248 .map_err(map_job_err)
1249 })
1250 .await
1251 .map_err(|_| ApiError::internal("job stdin write failed"))??;
1252 Ok(StatusCode::NO_CONTENT)
1253 }
1254
1255 #[derive(Debug, Serialize)]
1256 pub(super) struct KillJobResponse {
1257 job: JobView,
1258 result: ShellResult,
1259 }
1260
1261 /// `POST /v1/threads/{id}/jobs/{job_id}/kill` — bounded SIGTERM → SIGKILL
1262 /// escalation on the whole process group; the final snapshot rides along.
1263 pub(super) async fn kill_thread_job(
1264 State(state): State<RuntimeApiState>,
1265 Path((thread_id, job_id)): Path<(String, String)>,
1266 ) -> Result<Json<KillJobResponse>, ApiError> {
1267 if job_id.len() > JOB_ID_MAX_BYTES {
1268 return Err(ApiError::not_found("job not found"));
1269 }
1270 let admission = state.runtime_threads.session_checkpoint_guard().await;
1271 let manager = thread_manager(&state, &thread_id, false).await?;
1272 let store = state.runtime_threads.job_operation_store();
1273 let generation = state
1274 .runtime_threads
1275 .job_operation_generation()
1276 .map_err(operation_error)?;
1277 let runtime_owner = state.runtime_threads.clone();
1278 tokio::task::spawn_blocking(move || {
1279 let _admission = admission;
1280 if runtime_owner.job_operation_generation().ok().as_deref() != Some(generation.as_str()) {
1281 return Err(ApiError::internal("job operation owner changed"));
1282 }
1283 let mut guard = manager.lock().unwrap_or_else(|e| e.into_inner());
1284 let result = guard.kill(&job_id).map_err(map_job_err)?;
1285 guard.mark_cancel_reported(&result);
1286 let snapshot = guard.inspect_job(&job_id).map_err(map_job_err)?.snapshot;
1287 let pinned = guard.job_receipt_witness(&job_id).is_some();
1288 let job = JobView::new(snapshot, thread_id.clone(), &guard);
1289 drop(guard);
1290 if !pinned {
1291 return Ok(Json(KillJobResponse { job, result }));
1292 }
1293 let managers = vec![(thread_id.clone(), manager)];
1294 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
1295 loop {
1296 let settlement = store.with_job_operations(|transaction| {
1297 let mut records: Vec<_> = transaction
1298 .list()?
1299 .into_iter()
1300 .filter(|record| {
1301 record.operation.thread_id == thread_id
1302 && record.operation.job_id.as_deref() == Some(job_id.as_str())
1303 })
1304 .collect();
1305 anyhow::ensure!(records.len() <= 1, "duplicate job operation binding");
1306 let Some(mut record) = records.pop() else {
1307 return Ok(false);
1308 };
1309 let (operation, _) =
1310 project_operation(transaction, &mut record, &managers, &generation)
1311 .map_err(|_| anyhow::anyhow!("job settlement unavailable"))?;
1312 Ok(operation.status == "completed")
1313 });
1314 match settlement {
1315 Ok(true) => return Ok(Json(KillJobResponse { job, result })),
1316 Ok(false) => {}
1317 Err(error) if error.downcast_ref::<JobOperationsBusy>().is_some() => {}
1318 Err(_) => {
1319 return Err(ApiError::internal("job stop could not be confirmed")
1320 .with_code("job_operation_unconfirmed"));
1321 }
1322 }
1323 if std::time::Instant::now() >= deadline {
1324 return Err(ApiError::internal("job stop could not be confirmed")
1325 .with_code("job_operation_unconfirmed"));
1326 }
1327 std::thread::sleep(std::time::Duration::from_millis(50));
1328 }
1329 })
1330 .await
1331 .map_err(|_| ApiError::internal("job kill failed"))?
1332 }
1333
1334 #[derive(Debug, Serialize)]
1335 pub(super) struct KeepaliveJobResponse {
1336 job: JobView,
1337 }
1338
1339 pub(super) async fn keepalive_thread_job(
1340 State(state): State<RuntimeApiState>,
1341 Path((thread_id, job_id)): Path<(String, String)>,
1342 ) -> Result<Json<KeepaliveJobResponse>, ApiError> {
1343 if job_id.len() > JOB_ID_MAX_BYTES {
1344 return Err(ApiError::not_found("job not found"));
1345 }
1346 let manager = thread_manager(&state, &thread_id, false).await?;
1347 tokio::task::spawn_blocking(move || {
1348 let mut guard = manager.lock().unwrap_or_else(|e| e.into_inner());
1349 guard.keep_job_alive(&job_id).map_err(map_hold_err)?;
1350 let snapshot = guard.inspect_job(&job_id).map_err(map_job_err)?.snapshot;
1351 Ok(Json(KeepaliveJobResponse {
1352 job: JobView::new(snapshot, thread_id, &guard),
1353 }))
1354 })
1355 .await
1356 .map_err(|_| ApiError::internal("job keepalive failed"))?
1357 }
1358
1359 /// `POST /v1/threads/{id}/jobs/{job_id}/resize` — resize this existing PTY.
1360 pub(super) async fn resize_thread_job(
1361 State(state): State<RuntimeApiState>,
1362 Path((thread_id, job_id)): Path<(String, String)>,
1363 Json(size): Json<PtyDimensions>,
1364 ) -> Result<Json<JobDetailResponse>, ApiError> {
1365 let size = size
1366 .validate()
1367 .map_err(|error| ApiError::bad_request(error.to_string()))?;
1368 if job_id.len() > JOB_ID_MAX_BYTES {
1369 return Err(ApiError::not_found("job not found"));
1370 }
1371 let manager = thread_manager(&state, &thread_id, false).await?;
1372 tokio::task::spawn_blocking(move || {
1373 let mut guard = manager.lock().unwrap_or_else(|e| e.into_inner());
1374 let detail = guard.inspect_job(&job_id).map_err(map_job_err)?;
1375 if detail.snapshot.stale || detail.snapshot.status != ShellStatus::Running {
1376 return Err(ApiError {
1377 status: StatusCode::CONFLICT,
1378 message: "This job is no longer running".into(),
1379 code: None,
1380 });
1381 }
1382 if guard.job_terminal_size(&job_id).is_none() {
1383 return Err(ApiError::bad_request("This job is not a PTY"));
1384 }
1385 guard.resize_pty(&job_id, size).map_err(map_job_err)?;
1386 let detail = guard.inspect_job(&job_id).map_err(map_job_err)?;
1387 Ok(Json(JobDetailResponse {
1388 job: JobView::new(detail.snapshot, thread_id, &guard),
1389 stdout_tail: detail.stdout,
1390 stderr_tail: detail.stderr,
1391 }))
1392 })
1393 .await
1394 .map_err(|_| ApiError::internal("PTY resize failed"))?
1395 }
1396
1397 #[cfg(test)]
1398 mod tests {
1399 use super::*;
1400
1401 fn canonical(path: &std::path::Path) -> String {
1402 let canonical = path.canonicalize().unwrap().to_string_lossy().into_owned();
1403 if cfg!(windows) {
1404 plain_windows_path(&canonical)
1405 } else {
1406 canonical
1407 }
1408 }
1409
1410 #[test]
1411 fn job_cwd_resolves_against_the_thread_workspace() {
1412 let tmp = tempfile::tempdir().unwrap();
1413 let workspace = tmp.path().join("workspace");
1414 std::fs::create_dir_all(workspace.join("packages/app")).unwrap();
1415 let outside = tmp.path().join("outside");
1416 std::fs::create_dir_all(&outside).unwrap();
1417
1418 // Relative and absolute requests both come back as the canonical
1419 // directory that was checked, never the caller's spelling.
1420 let resolved = resolve_job_cwd(&workspace, "packages/app", false).unwrap();
1421 assert!(std::path::Path::new(&resolved).is_absolute(), "{resolved}");
1422 assert_eq!(resolved, canonical(&workspace.join("packages/app")));
1423 let absolute = workspace.join("packages");
1424 assert_eq!(
1425 resolve_job_cwd(&workspace, &absolute.to_string_lossy(), false).unwrap(),
1426 canonical(&absolute)
1427 );
1428
1429 let missing = resolve_job_cwd(&workspace, "packages/none", false).unwrap_err();
1430 assert_eq!(missing.status, StatusCode::BAD_REQUEST);
1431 let outside_raw = outside.to_string_lossy().into_owned();
1432 for raw in [outside_raw.as_str(), "../outside"] {
1433 let error = resolve_job_cwd(&workspace, raw, false).unwrap_err();
1434 assert_eq!(error.status, StatusCode::FORBIDDEN, "{raw}");
1435 }
1436 #[cfg(unix)]
1437 {
1438 std::os::unix::fs::symlink(&outside, workspace.join("escape")).unwrap();
1439 let error = resolve_job_cwd(&workspace, "escape", false).unwrap_err();
1440 assert_eq!(error.status, StatusCode::FORBIDDEN);
1441 }
1442 assert_eq!(
1443 resolve_job_cwd(&workspace, "../outside", true).unwrap(),
1444 canonical(&outside)
1445 );
1446 }
1447
1448 /// The cwd handed to the launcher is the directory whose containment was
1449 /// checked: retargeting the requested symlink afterwards does not move
1450 /// the child out of the workspace.
1451 #[cfg(unix)]
1452 #[test]
1453 fn job_cwd_launches_in_the_checked_directory_after_a_retarget() {
1454 let tmp = tempfile::tempdir().unwrap();
1455 let workspace = tmp.path().join("workspace");
1456 let inside = workspace.join("inside");
1457 std::fs::create_dir_all(&inside).unwrap();
1458 let outside = tmp.path().join("outside");
1459 std::fs::create_dir_all(&outside).unwrap();
1460 let link = workspace.join("link");
1461 std::os::unix::fs::symlink(&inside, &link).unwrap();
1462
1463 let resolved = resolve_job_cwd(&workspace, "link", false).unwrap();
1464 assert_eq!(resolved, canonical(&inside));
1465
1466 std::fs::remove_file(&link).unwrap();
1467 std::os::unix::fs::symlink(&outside, &link).unwrap();
1468 let output = std::process::Command::new("pwd")
1469 .arg("-P")
1470 .current_dir(&resolved)
1471 .output()
1472 .unwrap();
1473 assert!(output.status.success(), "{output:?}");
1474 assert_eq!(
1475 String::from_utf8_lossy(&output.stdout).trim(),
1476 canonical(&inside)
1477 );
1478 }
1479
1480 /// A directory whose name is not UTF-8 is refused before launch rather
1481 /// than lossily renamed into a `U+FFFD` sibling. Linux only: macOS and
1482 /// Windows filesystems do not store non-UTF-8 names.
1483 #[cfg(target_os = "linux")]
1484 #[test]
1485 fn job_cwd_refuses_a_directory_name_that_is_not_utf8() {
1486 use std::os::unix::ffi::OsStrExt as _;
1487 let tmp = tempfile::tempdir().unwrap();
1488 let workspace = tmp.path().join("workspace");
1489 let raw_name = std::ffi::OsStr::from_bytes(b"dir-\xff");
1490 std::fs::create_dir_all(workspace.join(raw_name)).unwrap();
1491 std::fs::create_dir_all(workspace.join("dir-\u{fffd}")).unwrap();
1492 std::os::unix::fs::symlink(workspace.join(raw_name), workspace.join("alias")).unwrap();
1493
1494 let error = resolve_job_cwd(&workspace, "alias", false).unwrap_err();
1495 assert_eq!(error.status, StatusCode::BAD_REQUEST);
1496 }
1497
1498 #[test]
1499 fn plain_windows_path_drops_only_the_verbatim_prefix() {
1500 assert_eq!(plain_windows_path(r"\\?\C:\ws\app"), r"C:\ws\app");
1501 assert_eq!(
1502 plain_windows_path(r"\\?\UNC\host\share\ws"),
1503 r"\\host\share\ws"
1504 );
1505 for unchanged in [r"C:\ws", r"\\host\share", r"\\?\Volume{0}\ws", "/tmp/ws"] {
1506 assert_eq!(plain_windows_path(unchanged), unchanged);
1507 }
1508 }
1509 }
1510
1510 lines RUST