Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/skills/layerfs-js-sdk/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ and examples.
| [commit](references/methods/commit.md) | `list(project, branch)`, `get(project, branch, commit)`, `diff(project, from_commit, to_commit, { paths_only, … })` |
| [file](references/methods/file.md) | reads `read`, `stat`, `list`, `glob`, `grep`, `blame`, `diff`; writes `write`, `edit`, `rm`, `mkdir`, `mv`, `cp`, `apply` |
| [sandbox](references/methods/sandbox.md) | `create(project, name, machine?, { image })`, `list(project?, { page_size, page_pos })`, `get(name, { page_size, page_pos })`, `close(name, { force })` |
| [workspace](references/methods/workspace.md) | `mount(sandbox, branch, { name })`, `exec(ws, command, { message, stream, stdout, stderr })`, `commit(ws, { message, force })`, `unmount(ws, { discard, force })`, `status(ws)` |
| [workspace](references/methods/workspace.md) | `mount(sandbox, branch, { name })`, `exec(ws, command, { message, stream, stdout, stderr })`, `commit(ws, { message, force })`, `unmount(ws, { discard, force, kill })`, `status(ws)` |
| [machine](references/methods/machine.md) | `list`, `platforms`, `get`, `status`, `start`, `stop`, `create`, `connect`, `remove`, `disconnect`, `update` |
| [store](references/methods/store.md) | `list`, `get`, `status`, `create`, `connect`, `push`, `pull`, `remove`, `disconnect` |
| [backup](references/methods/backup.md) | `connect`, `disconnect`, `list`, `create`, `restore` |
Expand Down
53 changes: 48 additions & 5 deletions .agents/skills/layerfs-js-sdk/references/methods/workspace.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
workspace.mount(sandbox, branch, { name })
workspace.exec(ws, command, { message, stream, stdout, stderr })
workspace.commit(ws, { message, force })
workspace.unmount(ws, { discard, force })
workspace.unmount(ws, { discard, force, kill })
workspace.status(ws)
```

Expand Down Expand Up @@ -157,6 +157,15 @@ const run = await layerfs.workspace.exec(ws, `printf '%s' ${b64} | base64 -d > s
too; mount again elsewhere), `NotMounted`, `Unknown` (the exit code is not
known: the command may or may not have run; stop).

A foreground command leaves a private `/tmp/layerfs-exec-<id>.record` in its
Sandbox while it runs, naming its Workspace, its pid and that pid's start
time; the record is removed when the command ends. A second client can use it
([`workspace.unmount`](#workspaceunmount) `kill: "workspace"`) when the first
client died before its unmount, leaving the command as an orphan that holds
the mount. The record is written only where the Sandbox has `/proc` (Docker's
container and Linux namespaces; a macOS host-process Sandbox writes none),
and the image must provide util-linux `setsid --wait` (Debian 12 has it).

## `workspace.commit`

`workspace.commit(ws, { message, force })`
Expand Down Expand Up @@ -190,25 +199,59 @@ leaves their text out.

## `workspace.unmount`

`workspace.unmount(ws, { discard, force })`
`workspace.unmount(ws, { discard, force, kill })`

Ends a Workspace. The Sandbox keeps running with no Workspace until `sandbox.close` (#535 D11).

| Option | Meaning |
| --- | --- |
| `discard` | Drop uncommitted changes instead of refusing |
| `force` | Abort the Workspace's kernel connection; drops uncommitted changes. A normal unmount that stalls ends itself with one abort write; use `force` only for a live connection, never to repeat an attempted abort |
| `force` | Abort the Workspace's kernel connection; drops uncommitted changes. A normal unmount that stalls ends itself with one abort write; use `force` only for a live connection, never to repeat an attempted abort. While a foreground command's record names a live process, `force` is refused `Busy`: cancel that command, then unmount normally, so it cannot create a new `Retained(Detach)` |
| `kill` | `"workspace"` (the only accepted value) to cancel this Workspace's own foreground commands first, then unmount normally: TERM to each process group, a bounded wait, then KILL only if still there. It never stops or deletes the Sandbox, never aborts the Workspace's connection, and never touches another Workspace. Any other value is `InvalidInput`, as is combining it with `force` |

**Returns:** `{ kind: "Unmounted" }`, or with `force`
`{ kind: "ForceUnmounted", abort, detach, cleanup }`.
`{ kind: "ForceUnmounted", abort, detach, cleanup }`. A `kill: "workspace"`
unmount that ends the Workspace answers `{ kind: "Unmounted" }`: it is a
normal unmount after the holders are cancelled, not a forced one.

| Code | Meaning | Do |
| --- | --- | --- |
| `Dirty` | Uncommitted changes; `detail.changed` lists paths, with `pendingMerge` and `truncated` | Commit them so the step is recorded; discard only a Workspace you're abandoning |
| `Busy` | A process still runs there (`detail.processes`) | Wait for it, or end it in a command |
| `Busy` | A foreground command still runs there; `detail.processes` lists the ids | `workspace.unmount(ws, { kill: "workspace" })` cancels only this Workspace's holders and unmounts; a holder that survives makes it `Busy` again with the ids |
| `InvalidInput` | `kill` was not `"workspace"`, or `kill` and `force` were combined | Pass only `kill: "workspace"`, without `force` |
| `NotMounted` | Already unmounted, or the wrong `ws` | Use the Workspace from `mount` |
| `Failed` with `TeardownCustody` in the message | The mount is gone but its drain did not finish | Preserve the message; don't repeat the abort; replace the Sandbox if its connection can't be ended |

**Example**

```js
await layerfs.workspace.unmount(ws); // ws is now invalid
```

After a `Busy` refusal, cancel only this Workspace's holders and unmount again:

```js
try {
await layerfs.workspace.unmount(ws);
} catch (error) {
if (error.code !== "Busy") throw error;
await layerfs.workspace.unmount(ws, { kill: "workspace" });
}
```

`kill: "workspace"` is the recovery for a Workspace whose own foreground
command was orphaned by a killed client. It cancels only the records whose
Workspace path is this one, and a process group with a member whose cwd or
open file is outside the Workspace is left alone: the call answers `Busy`
with `detail.scope_conflict` instead of taking collateral. It is not a
whole-Sandbox stop: `sandbox.close` has no force mode, and a Workspace the
daemon already holds as `Retained(Detach)` needs its custody retry; `kill`
cannot make that Workspace unmountable. A process that daemonized and escaped
the exec's session has no record once the command ends, so it needs a
separate explicit destroy. The cancel runs where the Sandbox's runtime is (its
machine's worker, or this process), so a Sandbox this process reaches only
through a forwarded daemon port is handled the same way.

## `workspace.status`

`workspace.status(ws)`
Expand Down
2 changes: 1 addition & 1 deletion api/crates/layerfs-api/src/workspace/unmount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub(crate) const CALL: Call = call(
"workspace",
"unmount",
&[a("ws", Text)],
&[opt("discard", Bool), opt("force", Bool)],
&[opt("discard", Bool), opt("force", Bool), opt("kill", Text)],
"end a Workspace",
run,
);
Expand Down
9 changes: 7 additions & 2 deletions api/crates/layerfs-api/tests/workspace_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,20 @@ fn home_with_a_named_workspace(tag: &str) -> PathBuf {
&SdkValue::map([("name", t("app")), ("created", SdkValue::Int(1))]),
)
.unwrap();
// the native daemon a call would launch: never started here
// the native daemon a call would launch: never started here, but the
// record must name a file so the call reaches the Sandbox itself
let native = paths::machine_record(&home, "native");
// (a home made without the machine calls has no native record yet)
let record = read_record(&native)
.unwrap()
.unwrap_or_else(|| SdkValue::map([("name", t("native")), ("platform", t("native"))]));
// the recorded daemon must exist for a call to reach the Sandbox; this
// placeholder is never launched, because no daemon keys are recorded
let daemon = home.join("layerfs-daemon");
std::fs::write(&daemon, b"").unwrap();
write_record(
&native,
&home::with_field(record, "daemon", t("/nonexistent")),
&home::with_field(record, "daemon", t(&daemon.display().to_string())),
)
.unwrap();
write_record(
Expand Down
1 change: 1 addition & 0 deletions api/crates/layerfs-control/src/sandbox/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub fn call(op: &str, args: SdkValue) -> Outcome {
"workspace.commit" => workspace::commit(&workspace::by_name(args)?),
"workspace.unmount" => workspace::unmount(&workspace::by_name(args)?),
"workspace.exec" => exec::exec(&workspace::by_name(args)?),
"workspace.holders" => exec::holders(&workspace::by_name(args)?),
_ => Err(refused("UnknownMethod", format!("no operation {op}"))),
}
}
Expand Down
85 changes: 52 additions & 33 deletions api/crates/layerfs-control/src/sandbox/exec.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,33 @@
//! Commands in a mounted Workspace, run by the Sandbox runtime owner.
//!
//! `exec` runs `bash -c <command>` as the Sandbox's command identity in the
//! `exec` runs the command as the Sandbox's command identity in the
//! Workspace directory and returns the exit code and output when it ends; the
//! daemon is not involved. A local Sandbox
//! (`layerfs_sandbox::Sandbox::HostProcess`) runs the same commands as
//! processes of this kernel.
//!
//! A foreground command writes a private record in the Sandbox's `/tmp`
//! naming its Workspace, its pid and that pid's start time before it runs, so
//! a later call can find and stop an orphan whose first client is gone. The
//! executor owns command launch and cancellation (AGENTS.md), so the record
//! is written where the command runs, by the same runtime owner: `bash -c`
//! under util-linux `setsid --wait`, and `/proc` read inside the Sandbox. A
//! backend without `/proc` (the macOS host process) runs the command plainly
//! and leaves no record; nothing else changes.
//!
//! This module is the orchestration: the two entrypoints and the result they
//! shape. [`record`] owns the foreground record and the id it carries,
//! [`holders`] finds and stops the processes a record names, and [`runtime`]
//! adapts this Sandbox's runtime to the run and capture calls they make.
use crate::common::outcome::Outcome;
use crate::sandbox::output::Spool;
use crate::sandbox::registry::{sandbox, text, SandboxState};
use layerfs_bridge::control::{SdkRefusal, SdkValue};
use crate::sandbox::registry::{sandbox, text};
use layerfs_bridge::control::SdkValue;

/// One command to its end: exit code, stdout, stderr. `spool` sends every
/// non-empty stream to its file instead of keeping it inline. Its home is
/// the Sandbox's scratch directory (`/tmp` in a container), since the
/// command identity has no account there.
fn run(
state: &SandboxState,
directory: &str,
arguments: Vec<String>,
spool: bool,
) -> Result<(i32, Spool, Spool), SdkRefusal> {
let runtime = state.runtime()?;
crate::sandbox::runtime::run(
runtime,
state.identity,
arguments,
vec![format!(
"HOME={}",
crate::sandbox::runtime::scratch(runtime)
)],
directory,
spool,
)
}
mod holders;
mod record;
mod runtime;

pub(crate) use holders::busy;

/// `workspace.exec(ws, command, { spool? })`.
///
Expand All @@ -53,12 +48,9 @@ pub(crate) fn exec(args: &SdkValue) -> Outcome {
Some(directory) => directory.to_owned(),
None => state.directory(path)?,
};
let (code, stdout, stderr) = run(
&state,
&directory,
vec!["bash".into(), "-c".into(), command.into()],
args.get_bool("spool"),
)?;
let arguments = record::foreground_arguments(&state, command)?;
let (code, stdout, stderr) =
runtime::run(&state, &directory, arguments, args.get_bool("spool"))?;
let mut streams = crate::sandbox::output::fields(stdout, stderr)?.into_iter();
let mut result = vec![
("kind", SdkValue::Text(format!("exit:{code}"))),
Expand All @@ -75,3 +67,30 @@ pub(crate) fn exec(args: &SdkValue) -> Outcome {
.collect(),
))
}

/// `workspace.holders(ws)`: the foreground execs still running in a
/// Workspace, read, or cancelled first with `kill`. This op runs where the
/// Sandbox's runtime is (its machine's worker, or this process), so a caller
/// that reaches only its daemon's forwarded port can still cancel an orphan.
/// Answers `{ processes }`; with `kill`, each own process group gets TERM and
/// then KILL, and a group that reaches outside the Workspace answers `Busy`.
pub(crate) fn holders(args: &SdkValue) -> Outcome {
let state = sandbox(args)?;
let path = text(args, "path")?;
if args.get_bool("kill") {
holders::cancel(&state, path)?;
}
let records = record::foreground_in(&state, path)?;
Ok(SdkValue::map([
("path", SdkValue::text(path)),
(
"processes",
SdkValue::List(
records
.into_iter()
.map(|record| SdkValue::Text(record.id))
.collect(),
),
),
]))
}
Loading