Factory members can now add environment variables for every sandbox in a
Factory, under Settings › Manage Factory › Environment variables. Each
variable is marked Build, Runtime, or Both.
Runtime variables reach every command in the Factory's sandboxes.
Adding, editing or deleting one takes effect on the next command in a
sandbox that's already running, with no restart (processes already
running keep their old env). Build variables reach template builds and
Factory's setup commands, never runtime commands, and editing one makes
the next build rebuild the template.
Values are encrypted at rest, never returned by the API or shown in the
UI after saving, and never put into template names, identity, or images.
Saving is blocked when sign-in is on but no credential encryption key is
configured.
To make builds work, `FactorySandboxContext` gets two optional fields.
Providers pass `buildEnv` only to a build-only mechanism and put
`buildEnvRevision` (a random id, never derived from values) in template
identity:
```ts
const { buildEnv, buildEnvRevision, ...rest } = ctx;
return createRepoTemplate({ ...rest, buildEnvRevision });
```
The platform and E2B workspace packages pass Build variables to template
builds. Docker keeps them out of the image and its identity, and doesn't
apply them to template builds yet. The routes are also available from
the CLI as `mastra api factory project environment variables
list|set|update|delete`.
Tested with unit tests on a real local sandbox, route tests that check
no response ever contains a value, and UI tests. I also ran it end to
end against a Platform sandbox: a Runtime variable's new value showed up
after an edit and was gone after a delete, and a Build variable was seen
by setup but not at runtime, with an edit producing a new build.
Part of FACT-554
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
Factory admins can save environment variables for a project and choose
whether each one is used to build sandboxes, run commands, or both.
Factory protects the values and applies changes to later commands or
relevant builds.
## Summary
- Added encrypted, project-scoped storage and authenticated API routes
to list, set, update, and delete sandbox environment variables.
Responses include metadata, not values. When sign-in is enabled without
a credential encryption key, writes are blocked.
- Added a Factory settings interface and CLI commands to manage
variables with Build, Runtime, or Both scopes.
- Runtime variable changes refresh the environment before later
commands. Build variables are available to build contexts and setup
commands. Build-variable changes update a revision used by supported
providers for template identity.
- Reads are served from memory per server: the revision and decrypted
values are reused until a variable changes. A write clears this server's
entry and is announced on Factory's event bus so other servers drop
theirs; a cached read is re-checked after a minute with a cross-process
bus, or after a second without one.
- Added optional `buildEnv` and `buildEnvRevision` fields to
`FactorySandboxContext`. Platform and E2B pass Build variables to
template builds. Docker excludes these fields from template input and
identity; Docker template builds do not receive the variables.
- Added documentation and tests for storage, API routes, settings, CLI,
sandbox behavior, and provider handling.
**Diff size:** 54 files changed; 3,241 lines added and 50 removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
> Opened by @DSchau
## Summary
Today the env a factory deployment passes to its sandboxes reaches every
factory's sessions. A deployment hosting several factories (Shipyard
runs mastra, platform and website) can't give a credential to just one
of them.
This PR adds two fields to `FactorySandboxContext`:
- `factoryId`: the session's factory project id. Environment builds get
it from the project.
- `factoryName`: the factory's display name, for logs and readable
config.
Every factory sandbox provider (`LocalFactorySandbox`,
`PlatformFactorySandbox`, `E2BFactorySandbox`, `DockerFactorySandbox`)
now accepts `env` as either a record (unchanged) or a function of the
context:
```ts
new PlatformFactorySandbox({
env: ctx => (ctx.factoryId === PLATFORM_FACTORY_ID ? { PLATFORM_TOKEN } : {}),
});
```
Names can be edited and aren't unique, so the docs say to scope secrets
by `factoryId`, never by name. Sessions created before factories existed
carry neither field.
The change is non-breaking. The record form behaves exactly as before,
and both context fields are optional, so third-party `FactorySandbox`
implementations keep compiling.
## Proof
- Every provider gets a new test where an env function gives the
credential to the matching factory and nothing to another factory (or to
a legacy session with no factory). The existing record-form `env` tests
still pass unchanged.
- `workspace.test.ts`: the session sandbox context now includes
`factoryId`/`factoryName` for a factory session and neither for a
session without a factory. `build.test.ts`: the environment build
context carries both.
- `tsc --noEmit` is clean for `@mastra/factory`, `@mastra/e2b`,
`@mastra/docker` and `@mastra/platform-workspace` against freshly built
core.
## Unverified
- I haven't run it end to end on a deployed Factory. Shipyard's own
config change (gating the token to the platform factory) is a follow-up
once this is released.
Risk: low
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## ELI5
A factory can choose which environment variables each session receives.
This helps keep one factory’s credentials away from sessions that belong
to other factories.
## What changed
- Added optional `factoryId` and `factoryName` fields to
`FactorySandboxContext`. Sessions created before factories existed do
not have these fields.
- Added the factory ID and name to sandbox contexts for sessions
associated with a factory.
- Updated the Local, Platform, E2B, and Docker sandbox providers to
accept `env` as a fixed record or a function of the session context.
- Documented how to use `factoryId` to scope secrets. Factory names can
change and are not unique.
- Documented that Platform and Docker sandboxes keep their initial
environment when resumed. Recreate a running sandbox to remove a
credential.
## Testing
The PR description reports provider tests for factory-specific
credentials, context tests in `workspace.test.ts` and `build.test.ts`,
and clean `tsc --noEmit` checks for the affected packages. The author
reports that the change was not tested end to end on a deployed Factory.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Lint now requires `import type` for imports used only as types, as
`oxlint.config.ts` always intended. The two rules have matched no files
since mastra-ai/mastra#20173 broke their override's glob, so the repo
drifted into mixing `import { type X }`, `import { X }` for types, and
`import type`. This turns them back on and fixes the existing imports.
No runtime behavior changes.
## What changed
- `import/consistent-type-specifier-style` and
`typescript/consistent-type-imports` go from `off` to `error`.
- 186 files: type-only imports become `import type { … }`, split from
value imports where a statement had both. Done with `oxlint --fix` plus
6 files the fixer left with inline `type` specifiers, then `oxfmt`.
- `disallowTypeAnnotations` is now `false`: `typeof import('x')` is
already type-only, and 97 of its 112 uses are the
`vi.importActual<typeof import('./x')>()` pattern in tests.
## Could this change behavior?
Only where a package keeps imports at runtime (`verbatimModuleSyntax`,
via `tsconfig.node.json`) and a statement became fully `import type`,
since that drops the module load. That happens in 18 places: 11 in
tests, and in source `GithubAppIdentity` (factory), `Workspace`,
`SpanType`, `Knowledge` and `WORKSPACE_TOOLS` (core), `Observable` from
`rxjs` (nestjs), and `zod` / `@mastra/mcp` in the server adapter test
suite. None of those modules run code at load time.
## Scope
The other rules the broken glob turned off (`no-unused-vars`,
`no-console`/`no-debugger`, `ban-ts-comment`, `no-require-imports`, the
test-file import ban) stay off for their own PRs.
## Testing
1. `pnpm lint`: passes (the 13 `only-export-components` warnings are
already on `main`).
2. `pnpm turbo build` for the 34 changed packages and `typecheck` for
the ones that have it: pass.
3. The test files that lost a runtime import: pass (core, server,
observability, factory, voice).
## Why
Factory keeps growing features that need something from the sandbox
provider: per-project settings (CPU, memory, idle timeout), a template
built ahead of a session, build history, and later builds on a schedule
or on push. Until now the only hook a host had was a bare callback that
returned a sandbox, so every new feature meant another callback on
`MastraFactory` and provider-specific knowledge leaking into factory.
`FactorySandbox` adds one object per provider with a stable contract
between factory and the provider. Factory asks the object what it can do
and renders accordingly; providers add features by implementing an
optional method, not by changing factory. The change is backwards
compatible: a host that passes the `sandbox` callback today keeps
working unchanged. Factory wraps it as a `custom` provider, so sessions
boot exactly as before; the host just does not get the new features
(per-project settings, template builds, or any later capability) until
it moves to a `FactorySandbox`.
## What
A host configures where Factory sessions run with one object:
```ts
new MastraFactory({
sandbox: new PlatformFactorySandbox({ defaults: { cpuCount: 4, memoryMb: 8192 } }),
})
```
`FactorySandbox` (in `@mastra/core/workspace`) owns:
- **The session sandbox.** `create(ctx, settings)` constructs the
sandbox for a session, with the environment's working directory handed
through so the session finds the template's checkouts where the template
cloned them.
- **The template.** `template(ctx, settings)` describes the repository
template a session boots from, so the same definition drives a session
and an ahead-of-time build.
- **Settings.** Each provider declares the settings a user can tune per
project as a schema (`PublicSchema`, any flavor). Factory validates
against it on write and exposes the input-side JSON Schema on the wire,
which is what the Environment settings page renders: one row per
property, typed by the schema (integer, enum, boolean), with provider
defaults as placeholders. A provider with no settings renders nothing.
Adding a setting is a one-line change in the provider.
- **Optional capabilities.** `builds` (start, get, list) is the first
one. Factory describes what is present through
`MastraFactory.sandboxDescription` (`provider`, `settingsSchema`,
`capabilities`) and the UI shows a Builds section only when the provider
has it. A provider that does not build simply omits the method.
Factory detects the object by a `Symbol.for('mastra.factory.sandbox')`
brand, so no instanceof across package boundaries.
Providers:
- `@mastra/platform-workspace`: `PlatformFactorySandbox` (`cpuCount`,
`memoryMb`, `idleTimeoutMinutes`, provider-side `defaults`). The `start
complete` log line gains a `templateHash` of the serialized template.
- `@mastra/e2b`: `E2BFactorySandbox` (`cpuCount`, `memoryMb`,
`idleTimeoutMinutes`) with `builds` (`start` via
`Template.buildInBackground`, `get` with logs, `list` from the
template's build history).
- `@mastra/docker`: `DockerFactorySandbox` (`baseImage`, `owner`).
- `@mastra/factory`: `sandbox` accepts a `FactorySandbox` or the
existing callback. The callback keeps working, wrapped as `provider:
'custom'` with no settings and no capabilities; `LocalFactorySandbox({
root, env })` replaces hand-rolled local fallbacks.
- The web host constructs the class with the same
local/platform/E2B/local precedence it had.
- Docs: `reference/workspace/factory-sandbox` plus the E2B per-session
example.
The single-repo `createRepoTemplate` functions are unchanged; a unit
test pins that the class produces the same template definition and build
envs as the callback form for the web and shipyard hosts.
## Test plan
- `packages/core`: `vitest run src/workspace/factory-sandbox.test.ts`
(9), `src/workspace/factory-sandbox.test-d.ts` (2), `pnpm check`
- `workspaces/platform-workspace`: `vitest run` 268 passed, `tsc
--noEmit`
- `workspaces/e2b`: `vitest run` 265 passed (mocked SDK covers
`start`/`get`/`list`), `tsc --noEmit`
- `workspaces/docker`: `vitest run` 336 passed, `tsc --noEmit`
- `mastracode/factory`: `vitest run` 3589 passed, `tsc --noEmit`, `pnpm
lint`
- `mastracode/web`: `pnpm check`
- `docs`: `pnpm format:check`
Closes FACT-384
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## ELI5
This PR gives Factory one consistent way to create a sandbox for each
session. It also lets sandbox providers describe their settings and
whether they can prepare repository templates or report build status.
## Changes
- Added the branded `FactorySandbox` contract to
`@mastra/core/workspace`. `MastraFactory` exposes the provider, settings
schema, and available capabilities through `sandboxDescription`.
- Updated `MastraFactory` to accept a `FactorySandbox` instance or the
existing callback. Factory wraps callbacks as `custom` providers without
settings or capabilities.
- Added `PlatformFactorySandbox`, `E2BFactorySandbox`,
`DockerFactorySandbox`, and `LocalFactorySandbox`.
- Updated Factory workspace and integration types to use
`FactorySandbox`. Updated the web host to select a provider using its
existing local, platform, and E2B configuration precedence.
- Added tests, exports, changesets, and documentation. Platform sandbox
start logs include a template hash when a template is used.
## Validation and review
The PR objectives report package tests, type checks, lint, and
documentation formatting checks. These results were not independently
verified. The PR objectives report the label `tests: green ✅`. The
supplied comments contain no review findings. Review severity counts are
unavailable.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
## Summary
A repo template can now hold several repositories. `createRepoTemplate`
in `@mastra/platform-workspace` and `@mastra/e2b`, and
`createDockerRepoTemplate` in `@mastra/docker`, accept `repos` instead
of `getRepositoryAccess`:
```ts
createRepoTemplate({
repos: [
{ getRepositoryAccess: getMastraAccess, setupCommand: 'pnpm install --frozen-lockfile' },
{ getRepositoryAccess: getDocsAccess, setupCommand: 'npm install' },
],
workspaceSetupCommand: 'touch .workspace-ready',
continueOnSetupFailure: true,
workingDirectory: '/home/user/repos',
})
```
Each entry resolves its own access and head, is cloned to
`<workingDirectory>/<repo>`, pinned, and runs its `setupCommand` inside
its clone. `workspaceSetupCommand` runs once at the working directory
after every repository. `continueOnSetupFailure` records a failing
per-repository setup in `.mastra-sandbox/setup-failed` and lets the
build continue instead of failing it.
The single-repository form is unchanged: same op order, template names,
tags, identities and `.mastra-sandbox/setup` marker.
## How it works
- Public repositories (access without `authorization`) are built before
private ones, caller order within each group.
- Credentials never enter the image or the template identity. Platform:
`MASTRA_REPOSITORY_ACCESS_TOKEN_<n>` ephemeral build envs. E2B:
`GH_TOKEN_<n>` build envs. Docker: `GH_TOKEN_<n>` build secrets mounted
only in that repository's clone stage.
- Markers under the working directory: `.mastra-sandbox/repos/<repo>`
per repository once every step ran, `.mastra-sandbox/workspace-setup`
after the workspace command, `.mastra-sandbox/setup-failed` (one line
per failing repository) when `continueOnSetupFailure` is on.
- Identity: platform family key `repos:<hash>` over the working
directory and ordered clone URLs. E2B template name hashes working
directory, clone URLs and setup commands; the tag is `sha-<hash>` over
every pinned sha. Changing the repository list starts a new template;
changing setup commands or credentials does not change the family.
- Failure: platform and E2B clone a repository unpinned when its head
cannot be resolved and fall back to the default template when access
cannot be resolved. Docker rejects the whole resolution in either case
(it clones full history and pins by checkout, so there is no unpinned
mode).
- Shared helpers (`guardedSetupCommand`, `repoSetupMarkerPath`, marker
constants) live in `@internal/workspace` so all three packages write the
same layout. `guardedSetupCommand` validates the repository directory
name and runs the setup command through `sh -c` so a stray quote or
comment cannot swallow the failure guard.
- `repos` with `getRepositoryAccess`, or `workspaceSetupCommand` /
`continueOnSetupFailure` without `repos`, throw a `TypeError`. Duplicate
checkout directory names are rejected. Docker rejects a setup command
containing a bare newline.
## Test plan
- [x] `@internal/workspace`, `@mastra/platform-workspace`,
`@mastra/e2b`, `@mastra/docker` vitest suites, tsc, lint, oxfmt
- [x] Serialization tests pin the full op list / Dockerfile for one
single-form and one list-form fixture per package
- [x] Real build through the platform proxy on E2B (two public repos,
one failing setup under `continueOnSetupFailure`): both clones present,
per-repo markers, `setup-failed` lists the failing repo once,
`.workspace-ready` present, `rev-parse HEAD` equals the pin
- [x] Real local Docker build with the same shape; a second `build()`
returns the cached tag
- [x] Docs: `integrations/sandboxes/docker.mdx`,
`integrations/sandboxes/e2b.mdx`,
`reference/workspace/platform-sandbox.mdx`
- [x] Changesets: `@mastra/platform-workspace`, `@mastra/e2b`,
`@mastra/docker` (minor)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## ELI5
This change lets one sandbox or Docker image contain several
repositories instead of just one. It can set up each repository and, if
configured, keep the build going when a repository’s setup command
fails.
## Summary
- Add `repos` support to `createRepoTemplate` in
`@mastra/platform-workspace` and `@mastra/e2b`, and to
`createDockerRepoTemplate` in `@mastra/docker`.
- Configure each repository with its own access resolver, optional ref,
and setup command. Clone public repositories before private
repositories, preserving order within each group.
- Add per-repository setup markers and an optional workspace setup
command. When `continueOnSetupFailure` is enabled, record repository
setup failures and continue. Other build failures still fail the build.
- Preserve the existing single-repository behavior. Validate
incompatible options, invalid entries, and duplicate checkout
directories.
- Document the new options and export the repository configuration
types.
## Validation
The PR description reports passing Vitest suites, typechecking, lint,
and formatting for the affected packages. It also reports serialization
tests, a platform-proxy build on E2B, and local Docker builds. These
results were not independently verified.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: CalebBarnes <CalebBarnes@users.noreply.github.com>
> Opened by @wardpeet
## Summary
Fixes#25959.
`DockerProcessManager.spawn()` demultiplexes Docker's exec stream
(8-byte header frames) and decoded each frame's payload with
`.toString('utf-8')` on its own. Docker frame boundaries don't line up
with UTF-8 character boundaries, so a multibyte character (emoji, CJK,
accented text) split across two frames turned into `�` on both sides.
This affected streamed `onStdout`/`onStderr` callbacks,
`handle.stdout`/`handle.stderr`, and `wait()` / `executeCommand`
results.
## Changes
- `workspaces/docker/src/sandbox/process-manager.ts`: each `spawn()` now
decodes stdout and stderr with its own `StringDecoder`. They need to be
separate because stdout and stderr frames interleave. Both decoders are
flushed at the top of `settle()`, which every exit path goes through
(end, close, error, kill/timeout), before the result reads the output.
Empty decoder output isn't emitted. This is the same approach
`@mastra/apple-container` already uses.
- Unit tests in `index.test.ts`:
- interleaved split `€` (stdout) and `😀` (stderr) frames, including one
frame split across two chunks;
- an incomplete sequence at the end of the stream is flushed (to
`\uFFFD`) instead of being dropped.
- Patch changeset for `@mastra/docker`.
## Test plan
- [x] `pnpm test:unit` in `workspaces/docker`: 210 passed, 6 skipped
- [x] The new split-frame test fails on the old code (`Expected "€",
Received "���"`) and passes with the fix
- [x] `tsc --noEmit`, `pnpm lint`, `pnpm build` all clean
- [x] The issue's mocked-stream repro against the built `dist/index.js`
now prints `{"stdout":"€","stderr":"😀","exitCode":0}`
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## ELI5
Docker can split a text character between pieces of output. This change
keeps those pieces together so the output shows the correct character.
## Changes
- `DockerProcessManager.spawn()` now uses a separate UTF-8
`StringDecoder` for stdout and stderr. It flushes both decoders before
settling the result, including when the stream errors.
- Added tests for characters split across interleaved stdout and stderr
frames, a Docker frame split across stream chunks, and incomplete
trailing characters.
- Added a patch changeset for `@mastra/docker`.
## Validation
The PR reports 210 unit tests passed and 6 skipped in
`workspaces/docker`. It also reports clean TypeScript, lint, and build
checks.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
> Opened by @abhiaiyer91
## Summary
When a `DockerTemplate` build without secrets failed, Docker's classic
builder kept the stopped container of the failing step (`forcerm`
defaults to false). `dispose()` only removes the image tag, so these
containers accumulated with every failed build.
This passes `forcerm: true` to `docker.buildImage`, so Docker removes
that container itself. Layer cache is unaffected, and the secrets path
(BuildKit) doesn't create these containers.
Fixes#25255
## Test plan
- Unit: `template.test.ts` asserts `forcerm: true` is sent (39/39 pass).
- Integration (real Docker daemon): new test builds `runCmd('exit 23 #
<uuid>')`, calls `dispose()`, and asserts no container with the marker
remains. It fails without the fix and passes with it.
- `tsc --noEmit` clean for `@mastra/docker`.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## ELI5
When a regular Docker build step fails, Docker can leave a stopped
container behind. This change asks Docker to remove that container, so
failed `DockerTemplate` builds leave less cleanup behind.
## Changes
- Set `forcerm: true` for non-secret `DockerTemplate` builds.
- Updated unit tests to check that Docker receives this option for
regular and forced builds.
- Added a Docker integration test that checks the failed step caused the
build failure, calls `dispose()`, and verifies that no listed container
command contains the step’s unique marker.
- Added a patch changeset for `@mastra/docker`.
## Verification
The supplied context reports a clean `tsc --noEmit` run for
`@mastra/docker`. It does not provide results for the unit or Docker
integration tests.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Abhi Aiyer <abhiaiyer91@gmail.com>
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
> Opened by @user_01KNA8J74D4RF84RXSDRX26BS9
## What this fixes
Terminating a long-running Docker-backed command could be reported as a
natural, successful exit.
`DockerProcessManager` settles `wait()` from the process's exec stream
events (`end`, `close`, `error`). Killing a process tears its own exec
stream down, so Docker can deliver `end` — or surface the teardown as an
`error` (`ECONNRESET`) — while `kill()` is still confirming the process
group is gone. Those events resolved first without `killed`/`timedOut`
and recorded an exit code, which then disarmed `close` — the only path
that attached that metadata. The result was a `CommandResult`
indistinguishable from a command that had exited on its own:
```ts
const result = await handle.wait();
result.success; // true — even though kill() returned true
result.killed; // undefined
```
Reproduced with `sleep 60 & wait`: `kill()` returned `true` while
`wait()` omitted `killed`, in both stdin modes.
## What changed
`end`, `close`, and `error` now settle through a single guarded path, so
the first event to arrive publishes the result and later ones are
no-ops. All three wait for an in-flight kill confirmation before
settling, so termination metadata survives the race regardless of which
event the teardown produces. Once termination is confirmed, settlement
reports exit code 137 with `killed: true` and the handle's `timedOut`,
matching what the `close` path previously produced.
A `kill()` that arrives while a confirmation is already in flight
returns that same confirmation instead of starting a second helper.
Previously the second helper replaced `_terminationPromise` and cleared
it as soon as it settled, so an `end` arriving while the first helper
was still running found nothing to await and settled as a natural exit —
the false-success this path exists to prevent.
The `close` handler also settles on its own now: it awaits any in-flight
confirmation before deciding, and if the stream closes with no `end`, no
kill, and no timeout it polls `exec.inspect()` until the exec has
actually stopped, so a still-running process is never reported as exited
and `wait()` cannot hang on a stream that never emits `end`. Before
settling from that poll it re-checks for a termination that landed while
it was running, so a kill that confirmed mid-poll cannot be overwritten
by a bare exit code.
The whole close-only path shares a single 10s deadline — the
confirmation wait and the inspection poll draw on the same budget rather
than each starting their own — and every `exec.inspect()` call,
including the first, is bounded by the time left on it, so a daemon that
stops answering cannot hold `wait()` open past the bound.
The timeout path records the termination before `kill()` confirms it, so
the event handlers wait unconditionally rather than trusting that flag —
a settlement taken while the helper is still running could not be
corrected afterwards.
Natural exits are unaffected: no metadata is attached and the exit code
still comes from `exec.inspect()`.
## Test plan
- `pnpm test:unit` in `workspaces/docker` — 5 files, 207 passed, 6
skipped
- `npx tsc --noEmit` in `workspaces/docker` — clean
- `oxlint` + `eslint` on the changed files — clean
- Twelve race tests cover the event orderings and fail against the
pre-fix code they pin (including: a terminated process reported
`success: true`, an errored stream reported exit 1 instead of 137,
`close` settled before the kill was confirmed, a stream closed without
`end` left `wait()` pending, a stream closed while the exec was still
running settled early, a kill arriving during the close-only poll lost
its metadata, an unresponsive `inspect()` held `wait()` open, the
confirmation and inspection waits stacked past one deadline, and two
concurrent `kill()` calls shared one confirmation instead of the second
clearing the first).
- The confirmation-deadline test pins the exact 10,000ms bound (pending
at 9,999ms, settled at 10,000ms); shrinking the constant to 5,000 fails
the assertion.
Fixes#24406
---------
Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com>
Co-authored-by: NikAiyer <nick.aiyer@gmail.com>
A sandbox command that reads stdin and gets nothing to read would block
until its timeout fired. The local sandbox handed every child a stdin
socketpair that never reached EOF, so `rg`/`grep` with no path argument,
a bare `cat`, or `read` would sit there forever. One session stalled for
48 minutes on `rg -n "signal-messages" --files-with-matches` — the `|
head` on the end was a bystander, not the cause.
`processes.spawn()` keeps its writable stdin, since the documented
`sendStdin`/`writer` contract and the LSP client rely on it. The
run-to-completion paths — `executeCommand()` and the background spawn
behind the `execute_command` tool — now close stdin, so the child sees
EOF immediately. No caller opts in:
```ts
// before: hung until the timeout whenever the command read stdin
// after: exits right away
await sandbox.executeCommand('/bin/sh', ['-c', 'rg -n "pattern" --files-with-matches | head']);
```
Docker and E2B had the same defect — both attached stdin on every exec —
and now honor the same option. Verified against a live daemon: `cat`
through `DockerSandbox` went from an 8s timeout to 38ms.
The other providers (modal, daytona, blaxel, vercel, railway, platform)
use remote SDK transports I couldn't run here, so one of them may still
keep stdin open.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## ELI5
Commands that wait for input now receive an immediate end-of-input
signal when no input is provided. Interactive processes keep their
existing input support.
## Changes
- Added `stdinMode: 'pipe' | 'ignore'` to `SpawnProcessOptions`.
- Set `stdinMode: 'ignore'` for `executeCommand()` and background
`execute_command` processes.
- Preserved writable stdin for `processes.spawn()`.
- Applied the behavior to local, Docker, and E2B process managers.
- Rejected `sendStdin` for processes created with `stdinMode: 'ignore'`.
- Added regression tests for EOF handling and rejected stdin writes.
- Added changesets for core, Docker, and E2B.
Commands such as `cat`, `read`, and pathless `rg` or `grep` no longer
block while waiting for input. Other remote providers were not verified.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: remy-builder[bot] <324360501+remy-builder[bot]@users.noreply.github.com>