Deploy on AgentCore Runtime
Run Stash beside your agent in the same Amazon Bedrock AgentCore Runtime session. Add Stash to the image, mount durable storage, and prepare the Stash mount before the agent handles its first turn.
Before you start
Section titled “Before you start”- An AgentCore Runtime application.
- The
@aws/agentcoreCLI, version 0.27.0 or later. - Durable session storage mounted in the Runtime container.
- Credentials and permissions for each configured source.
1. Install Stash
Section titled “1. Install Stash”Install pinned releases of the Stash CLI and the Strands memory manager when you build the agent image:
ARG STASH_CLI_VERSIONARG STASH_MEMORY_MANAGER_VERSIONRUN npm install --global "@strands-agents/stash@${STASH_CLI_VERSION}" \ && python -m pip install \ "strands-stash-memory-manager==${STASH_MEMORY_MANAGER_VERSION}"Pin both versions with the other application dependencies.
2. Configure durable storage
Section titled “2. Configure durable storage”Mount writable session storage into Runtime. Set STASH_STORAGE_PREFIX to a
folder on that mount:
STASH_STORAGE_PREFIX=/mnt/s3files/stashStash creates a separate home and mount for each Runtime session below this prefix. Stash does not provision or mount the storage.
Note: Stash needs directories, file locks, temporary files, in-place updates, and renames. Check the AgentCore Runtime file system configurations before choosing the path for
STASH_STORAGE_PREFIX.
3. Configure the sources
Section titled “3. Configure the sources”Put the source config in the image or generate it during application startup:
version = 1
[sources.incidents]kind = "agentcore-memory"arn = "${memoryArn}"auth = { sigv4 = {} }write.trajectory.actor = "${actorId}"namespaces = ["/actor/${actorId}/*"]Grant the Runtime execution role access to sources that use SigV4. See Endpoint auth for other authentication modes.
The current StrandsStash integration reads mount_point from its config so
that the agent can open projected files. Put a placeholder in the config
template:
mount_point = "__RUNTIME_MOUNT_POINT__"Note: Runtime does not honor an authored
mount_pointwhen it selects the mount location. Stash derives the path fromSTASH_STORAGE_PREFIX, the Runtime session ID, and the mount name. Pass the rendered temporary config, not the authored template, toStrandsStash. Itsmount_pointmust be that resolved absolute path so the manager can validate and directly read the files served by Stash.
Your startup helper first renders the expected Runtime path so stash create
can validate the config. Once the mount is ready, it reads the authoritative
mount_point from stash status and writes that path into the temporary config
before it constructs StrandsStash. The authored value does not configure
Runtime storage.
4. Prepare Stash
Section titled “4. Prepare Stash”The application must:
- Run
stash createwith the Runtime session ID. - Bind each config variable with
stash bind --set. - Poll
stash statuswith a timeout untilstate: ready. - Stop startup if the mount reaches
state: failedor the timeout expires.
Do not treat a successful stash create exit as a ready mount.
Recover after a Runtime restart
Section titled “Recover after a Runtime restart”Stash keeps session data on the configured durable storage. Its active process state is local to the Runtime container and must be re-established after Runtime restores or replaces the container.
Use one idempotent prepare_stash(session_id) operation before constructing or
reusing the agent:
- Run
stash createwith the same mount, config, and Runtime session ID. - Run
stash bindwith the current values. - Poll
stash statusuntil the mount is ready.
Call this operation during application initialization or before you construct
an agent for a request. Call it again if a later readiness check reports
daemon not running or a missing mount. Wait when the state is starting.
If the mount is failed, inspect its status, run stash delete ops --yes as
described in stash delete, and then prepare it
again. Do not restart Stash only because health is degraded: the mount is
serving, and the status output names the source that did not start.
Avoid running this mutation from a high-frequency container liveness endpoint. A liveness endpoint should remain cheap; use application initialization or a bounded readiness-recovery path that has the Runtime session ID.
Runtime supplies the session ID through the request context. This helper binds
only the variables in the config above, waits up to three minutes, and returns
a rendered config path for StrandsStash:
import jsonimport osimport reimport subprocessimport timefrom pathlib import Path
MOUNT_NAME = "ops"RUNTIME_SESSION_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{32,99}$")PREPARATION_TIMEOUT_SECONDS = 180
def run_stash(deadline: float, *arguments: str) -> str: remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError("Stash preparation exceeded three minutes") try: completed = subprocess.run( ["stash", *arguments], check=False, capture_output=True, text=True, timeout=remaining, ) except subprocess.TimeoutExpired as error: raise TimeoutError("Stash preparation exceeded three minutes") from error if completed.returncode: detail = completed.stderr.strip() or completed.stdout.strip() raise RuntimeError(f"stash {' '.join(arguments[:2])}: {detail}") return completed.stdout
def status_field(output: str, name: str) -> str | None: for line in output.splitlines(): key, separator, value = line.strip().partition(":") if separator and key == name: return value.strip() return None
def render_config( template: str, mount_point: Path, bindings: dict[str, str] | None = None,) -> str: rendered = template.replace( '"__RUNTIME_MOUNT_POINT__"', json.dumps(str(mount_point)), ) for name, value in (bindings or {}).items(): rendered = rendered.replace(f"${{{name}}}", json.dumps(value)[1:-1]) return rendered
def prepare_stash(session_id: str) -> Path: if not RUNTIME_SESSION_ID.fullmatch(session_id): raise ValueError("Runtime session ID is not valid for Stash")
deadline = time.monotonic() + PREPARATION_TIMEOUT_SECONDS prefix = Path(os.environ["STASH_STORAGE_PREFIX"]) if not prefix.parent.is_dir(): raise RuntimeError(f"storage parent does not exist: {prefix.parent}") prefix.mkdir(mode=0o700, exist_ok=True) expected_mount = prefix / "sessions" / session_id / "mounts" / MOUNT_NAME bindings = { "memoryArn": os.environ["STASH_MEMORY_ARN"], "actorId": os.environ["STASH_ACTOR_ID"], }
template = Path(os.environ["STASH_CONFIG_TEMPLATE"]).read_text() config_path = Path("/tmp") / f"stash-{session_id}.toml" config_path.write_text(render_config(template, expected_mount)) config_path.chmod(0o600)
run_stash( deadline, "create", MOUNT_NAME, "--session-id", session_id, "--config", str(config_path), ) run_stash( deadline, "bind", MOUNT_NAME, "--set", f"memoryArn={bindings['memoryArn']}", "--set", f"actorId={bindings['actorId']}", )
while time.monotonic() < deadline: status = run_stash(deadline, "status", MOUNT_NAME) state = status_field(status, "state") if state == "ready": resolved = status_field(status, "mount_point") if not resolved: raise RuntimeError("ready mount has no mount_point") config_path.write_text(render_config(template, Path(resolved), bindings)) config_path.chmod(0o600) return config_path if state == "failed": raise RuntimeError(status) time.sleep(min(2, max(0, deadline - time.monotonic()))) raise TimeoutError("Stash mount did not become ready within three minutes")Set STASH_CONFIG_TEMPLATE to the path of the config template. Set
STASH_MEMORY_ARN and STASH_ACTOR_ID to the values that the helper binds.
Construct and close the agent inside the request handler:
import asyncio
from bedrock_agentcore.runtime import BedrockAgentCoreAppfrom stash_strands import StrandsStashfrom strands import Agentfrom strands.vended_tools import read
app = BedrockAgentCoreApp()
def prompt_from(payload: object) -> str: prompt = payload.get("prompt") if isinstance(payload, dict) else None if not isinstance(prompt, str) or not prompt.strip(): raise ValueError("payload.prompt must be a non-empty string") return prompt
@app.entrypointasync def invoke(payload: object, context): session_id = getattr(context, "session_id", "") if not session_id: raise ValueError("AgentCore Runtime did not provide a session ID")
config_path = await asyncio.to_thread(prepare_stash, session_id) memory = StrandsStash( config_path=config_path, session_id=session_id, mount_name=MOUNT_NAME, command="stash", ) agent = await asyncio.to_thread( lambda: Agent( tools=[read], memory_manager=memory, ) )
try: async for event in agent.stream_async(prompt_from(payload)): if isinstance(event, dict) and "event" in event: yield event finally: try: await memory.flush() finally: await asyncio.to_thread(agent.cleanup)
if __name__ == "__main__": app.run()This example creates and closes the agent for each request. An application can cache one agent for a Runtime session. It must flush after each request, and prepare the mount again if the daemon becomes unavailable.
5. Deploy
Section titled “5. Deploy”Add the Stash-enabled image, durable-storage mount, environment variables, and execution role permissions to your AgentCore project. Deploy it through the standard AgentCore workflow:
agentcore deployagentcore status --jsonThe project declaration remains the source of truth for the Runtime. It should
build or reference the image containing Stash, mount the storage used by
STASH_STORAGE_PREFIX, and pass the source configuration required by the
startup code.
6. Invoke the agent
Section titled “6. Invoke the agent”agentcore invoke --runtime agent \ --session-id 00000000-0000-4000-8000-000000000123 \ --prompt "Summarize the known response for INC-4412."Reuse the session ID to reopen the same durable Stash home and mount. Replace
agent with the Runtime name declared by your AgentCore project.
7. Use and verify the context
Section titled “7. Use and verify the context”StrandsStashadds the hydrated context digest and Stash steering to the agent.- It registers Stash search and source tools.
readlets the agent open_sources/and materialized result files.flush()queues the completed turn for source write-back.
From a Runtime shell or application diagnostic, inspect the mount:
stash status opsstash search ops "INC-4412" --path '/agentcore-memory/incidents/*'Complete one agent turn. Confirm that the configured source accepted its write-back event.
Troubleshoot
Section titled “Troubleshoot”| What you see | What to do |
|---|---|
STASH_STORAGE_PREFIX is missing | Mount durable storage and set the variable before stash create |
The mount stays starting or reports health: degraded | Run stash status ops and check the Runtime logs |
StrandsStash rejects mount_point | Render the placeholder to the derived absolute Runtime mount path |
| A SigV4 source cannot start | Add the required source permissions to the Runtime execution role |