# Let Diagrid start and stop your agent's AgentCore sessions

With Diagrid-managed sessions, Diagrid runs your agent in an Amazon Bedrock AgentCore session only while the agent has work. Diagrid calls this serverless compute: it's what the `--compute` options of the Diagrid CLI set up. Your clients start runs through Diagrid, not through AgentCore. When the agent has pending work and no worker is connected, Diagrid starts an AgentCore session, whose container connects as the agent's worker. When the agent has had no work for a cooldown period, Diagrid stops the session.

This guide attaches serverless compute to the agent from [AgentCore hosted agents](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/hosted-agents), and runs the agent's front end on your machine.

**Sequence diagram: A run in a Diagrid-managed session.** Diagrid acts in your AWS account as a role that trusts only this agent's ID, the agent's workload identity. It stores no AWS credentials.

Participants: Front end (your machine), Diagrid (the agent's ID), AWS (STS, AgentCore), Worker (AgentCore session).

1. Front end (your machine) → Diagrid (the agent's ID): start run
   - *Note over Diagrid (the agent's ID):* pending work, no worker
2. Diagrid (the agent's ID) → AWS (STS, AgentCore): AssumeRoleWithWebIdentity
3. Diagrid (the agent's ID) → AWS (STS, AgentCore): InvokeAgentRuntime {}
4. AWS (STS, AgentCore) → Worker (AgentCore session): start session
5. Worker (AgentCore session) → Diagrid (the agent's ID): connect as worker
6. Diagrid (the agent's ID) → Worker (AgentCore session): run steps
7. Diagrid (the agent's ID) → Front end (your machine) (reply): result
   - *Note over Diagrid (the agent's ID):* no work for the cooldown
8. Diagrid (the agent's ID) → AWS (STS, AgentCore): StopRuntimeSession

## How it works

- **When a worker starts.** The agent has pending or in-flight work, such as a run a client started, and no worker is connected. Diagrid starts one worker. A worker that crashes is replaced.
- **When a worker stops.** The agent has had no pending and no in-flight work for the cooldown, 300 seconds by default. Work that arrives in bursts keeps the worker.
- **How Diagrid reaches AWS.** Diagrid gets a short-lived token for the agent's ID from the region's OIDC issuer, and exchanges it with AWS STS for credentials of an IAM role in your account. The role trusts only this agent's ID, and may only start and stop sessions of one Runtime. CloudTrail records the agent's SPIFFE ID as the web identity of each call.
- **Which code a worker runs.** By default, Diagrid invokes the Runtime's `DEFAULT` endpoint, so new workers run the Runtime's newest version. You can pin a version with a named endpoint. See [Pin a code version](#pin-a-code-version).

### What the worker must do

Diagrid starts a worker by invoking a new session with an empty JSON body, `{}`. The container must:

- **Not connect to Diagrid when the process starts.** AgentCore runs the process once to take the snapshot it restores every session from. A connection opened then is in every session, already closed.
- **Start the worker on the first `POST /invocations`**, and start nothing on a repeated one.
- **Answer `HealthyBusy` on `GET /ping` while the worker runs**, so AgentCore doesn't end the session at its idle timeout.
- **Never stop the worker on its own.**

`AgentcoreRunner` from the Diagrid package takes care of all of this. See the [reference](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/reference).

## Prerequisites

- [AgentCore hosted agents](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/hosted-agents) completed, with its CloudFormation stack and its secret kept, and its environment variables set in your terminal.
- The [Diagrid CLI](https://docs.diagrid.io/getting-started/local-installation#diagrid-cli), version 1.146.0 or later.
- Permission in the AWS account to create an IAM role, an IAM OIDC identity provider and a CloudFormation stack.

## 1. Keep worker sessions running

Set `AGENT_WORKER_KEEPALIVE` on the Runtime, so that a session answers `HealthyBusy` once its worker runs. The session then runs until Diagrid stops it, or until the Runtime's maximum lifetime, 8 hours by default. Deploy the stack from [step 4 of AgentCore hosted agents](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/hosted-agents#4-deploy-the-agentcore-runtime) again from the `budget-planner` folder, with `KeepAlive` set to `true`. The other parameters keep their values:

**macOS/Linux**

```bash
aws cloudformation deploy --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner \
  --template-file template.yaml --capabilities CAPABILITY_NAMED_IAM \
  --parameter-overrides KeepAlive=true
```

**Windows**

```powershell
aws cloudformation deploy --region $env:AWS_REGION --stack-name agentcore-quickstart-budget-planner --template-file template.yaml --capabilities CAPABILITY_NAMED_IAM --parameter-overrides KeepAlive=true
```

Every worker is replaced when it reaches the Runtime's maximum lifetime. Work it holds goes back to the queue and runs on the next worker, and an activity longer than the maximum lifetime can't complete.

Check that the Runtime is `READY` again, as in [step 4 of AgentCore hosted agents](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/hosted-agents#4-deploy-the-agentcore-runtime).

From now on, a session you start yourself with `invoke-agent-runtime`, as in [step 5 of AgentCore hosted agents](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/hosted-agents#5-invoke-the-hosted-agent), also keeps running. Its worker stays connected to Diagrid and takes the agent's runs, so Diagrid doesn't start a session of its own. If you invoked the Runtime after this step, stop that session, using the session ID of that invocation:

**macOS/Linux**

```bash
aws bedrock-agentcore stop-runtime-session --region "$AWS_REGION" --agent-runtime-arn "$RUNTIME_ARN" --runtime-session-id "$SESSION_ID"
```

**Windows**

```powershell
aws bedrock-agentcore stop-runtime-session --region $env:AWS_REGION --agent-runtime-arn $env:RUNTIME_ARN --runtime-session-id $env:SESSION_ID
```

## 2. Generate the AWS setup

`diagrid agent compute setup` writes the IAM resources that let Diagrid start and stop sessions of the Runtime, as a CloudFormation template or as Terraform:

- An IAM OIDC identity provider for the issuer of each region the project runs in.
- An IAM role, named `diagrid-budget-planner-invoker`, that trusts the agent's ID in each of those regions, and only that ID.
- A policy on the role that allows `bedrock-agentcore:InvokeAgentRuntime` and `bedrock-agentcore:StopRuntimeSession` on the Runtime and its endpoints.

Generate the CloudFormation template:

**macOS/Linux**

```bash
diagrid agent compute setup budget-planner --project agentcore-quickstart \
  --compute aws-agentcore --compute-agentcore-runtime-arn "$RUNTIME_ARN" \
  --output cloudformation > invoker.yaml
```

**Windows**

```powershell
diagrid agent compute setup budget-planner --project agentcore-quickstart --compute aws-agentcore --compute-agentcore-runtime-arn $env:RUNTIME_ARN --output cloudformation | Set-Content -Path invoker.yaml
```

Without `--output`, the command writes Terraform. `--role-name` sets another name for the role.

An AWS account has one IAM OIDC provider per issuer, shared by every agent that uses the account in that region. If the account already has one for the region's issuer, remove it from the template, or import it, before you apply. A project in a region group gets one provider and one trust entry per member region, so trust keeps working when the project fails over.

## 3. Apply the setup

The template names the role, so deploying it needs `CAPABILITY_NAMED_IAM`. Deploy the stack and read the role's ARN from its outputs:

**macOS/Linux**

```bash
aws cloudformation deploy --region "$AWS_REGION" --stack-name diagrid-budget-planner-invoker \
  --template-file invoker.yaml --capabilities CAPABILITY_NAMED_IAM
export INVOKER_ROLE_ARN="$(aws cloudformation describe-stacks --region "$AWS_REGION" \
  --stack-name diagrid-budget-planner-invoker \
  --query "Stacks[0].Outputs[?OutputKey=='RoleArn'].OutputValue" --output text)"
echo "$INVOKER_ROLE_ARN"
```

**Windows**

```powershell
aws cloudformation deploy --region $env:AWS_REGION --stack-name diagrid-budget-planner-invoker --template-file invoker.yaml --capabilities CAPABILITY_NAMED_IAM
$env:INVOKER_ROLE_ARN = aws cloudformation describe-stacks --region $env:AWS_REGION --stack-name diagrid-budget-planner-invoker --query "Stacks[0].Outputs[?OutputKey=='RoleArn'].OutputValue" --output text
$env:INVOKER_ROLE_ARN
```

The ARN ends with `role/diagrid-budget-planner-invoker`.

## 4. Attach the serverless compute

Attach the Runtime and the role to the agent:

**macOS/Linux**

```bash
diagrid agent update budget-planner --project agentcore-quickstart \
  --compute aws-agentcore \
  --compute-agentcore-runtime-arn "$RUNTIME_ARN" \
  --compute-agentcore-role-arn "$INVOKER_ROLE_ARN"
diagrid agent get budget-planner --project agentcore-quickstart -o json | jq '.status.appIds[0].spec.compute'
```

**Windows**

```powershell
diagrid agent update budget-planner --project agentcore-quickstart --compute aws-agentcore --compute-agentcore-runtime-arn $env:RUNTIME_ARN --compute-agentcore-role-arn $env:INVOKER_ROLE_ARN
(diagrid agent get budget-planner --project agentcore-quickstart -o json | Out-String | ConvertFrom-Json).status.appIds[0].spec.compute
```

The compute settings show the provider `awsAgentCore` with the Runtime ARN, the `DEFAULT` endpoint and the role ARN, and the scaling settings.

## 5. Run the front end

The front end starts runs through Diagrid and executes none of them. It is the same `main.py`, with `AGENT_WORKER` set to `false`. In the `budget-planner` folder, with the variables from the quickstart's [steps 5](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/getting-started#5-configure-the-aws-account) and [6](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/getting-started#6-configure-the-diagrid-connection) set:

**macOS/Linux**

```bash
AGENT_WORKER=false uv run python main.py
```

**Windows**

```powershell
$env:AGENT_WORKER = "false"
uv run python main.py
```

The front end and the workers must run the same `main.py`, because the worker reads the agent's prompt, model and tools from it.

## 6. Send a task

From another terminal, create a new session ID and send the quickstart's request with it:

**macOS/Linux**

```bash
export SESSION_ID="serverless-$(uuidgen)"
curl -X POST http://localhost:8080/invocations \
  -H "Content-Type: text/plain" \
  -H "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: $SESSION_ID" \
  -d 'Calculate the budget for a corporate event with venue, catering, and entertainment'
```

**Windows**

```powershell
$env:SESSION_ID = "serverless-$([guid]::NewGuid())"
Invoke-RestMethod -Method Post -Uri 'http://localhost:8080/invocations' -ContentType 'text/plain' -Headers @{ 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id' = $env:SESSION_ID } -Body 'Calculate the budget for a corporate event with venue, catering, and entertainment'
```

The front end starts the run and waits. Diagrid sees the pending run, starts an AgentCore session, and gives the run to its worker once it connects. The answer has the same shape as in the quickstart. The first answer takes longer than a later one, because a session has to start.

## 7. Watch the worker start and stop

Follow the worker's logs in CloudWatch. The log group is named after the Runtime and its endpoint:

**macOS/Linux**

```bash
aws logs tail "/aws/bedrock-agentcore/runtimes/${RUNTIME_ARN##*/}-DEFAULT" --region "$AWS_REGION" --since 30m --follow
```

**Windows**

```powershell
$runtimeId = $env:RUNTIME_ARN.Split('/')[-1]
aws logs tail "/aws/bedrock-agentcore/runtimes/${runtimeId}-DEFAULT" --region $env:AWS_REGION --since 30m --follow
```

When Diagrid starts a worker, the logs show the worker connecting to Diagrid with `Successfully connected to … Waiting for work items...`, followed by Diagrid's start request, `"POST /invocations HTTP/1.1" 200 OK`. When Diagrid stops the worker, the logs end with `Worker shutdown completed` and `Finished server process`.

The run is a workflow under the `budget-planner` ID, as in the quickstart's [inspection step](https://docs.diagrid.io/integrations/aws-bedrock-agentcore/getting-started#10-inspect-the-execution), and its steps ran in the AgentCore session.

Leave the agent idle for longer than the cooldown. Diagrid stops the session. In CloudWatch, the `ActiveSessionCount` metric in the `AWS/Bedrock-AgentCore` namespace drops back, and has no data while no session runs.

## 8. Simulate a crash

Stop the worker's AgentCore session in the middle of a run. Diagrid sees the agent's pending work and no connected worker, starts a new session, and the run continues from its last completed step. The front end's request waits through the crash and gets the answer.

### Make the runs longer

The quickstart's agent finishes a run in a few seconds, too fast to interrupt. Its `main.py` has a slow tool for this, `check_vendor_availability`, which is off unless `LONG_RUN_SECONDS` is set. Deploy the stack again with `LongRunSeconds` set to `30`, so the workers check each item's vendor for 30 seconds. The image doesn't change, and the front end doesn't need the setting:

**macOS/Linux**

```bash
aws cloudformation deploy --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner \
  --template-file template.yaml --capabilities CAPABILITY_NAMED_IAM \
  --parameter-overrides LongRunSeconds=30
```

**Windows**

```powershell
aws cloudformation deploy --region $env:AWS_REGION --stack-name agentcore-quickstart-budget-planner --template-file template.yaml --capabilities CAPABILITY_NAMED_IAM --parameter-overrides LongRunSeconds=30
```

A worker that is already running keeps the settings it started with, and takes the next run. Leave the agent idle for longer than the cooldown, or stop that worker's session as shown below, before you continue.

### Start a long run

Send a task with a new session ID, as in [step 6](#6-send-a-task):

**macOS/Linux**

```bash
export SESSION_ID="crash-demo-$(uuidgen)"
curl -X POST http://localhost:8080/invocations \
  -H "Content-Type: text/plain" \
  -H "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: $SESSION_ID" \
  -d 'Calculate the budget for a corporate event with venue, catering, and entertainment, and check vendor availability'
```

**Windows**

```powershell
$env:SESSION_ID = "crash-demo-$([guid]::NewGuid())"
Invoke-RestMethod -Method Post -Uri 'http://localhost:8080/invocations' -ContentType 'text/plain' -Headers @{ 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id' = $env:SESSION_ID } -Body 'Calculate the budget for a corporate event with venue, catering, and entertainment, and check vendor availability'
```

The run takes about two minutes, and the request waits for its answer. Leave it running.

### Stop the worker's session

Watch the logs from [step 7](#7-watch-the-worker-start-and-stop). When they show `check_vendor_availability(venue): done` and then `check_vendor_availability(catering): started`, stop the worker's session from another terminal, in the `budget-planner` folder with the same variables set.

Diagrid starts worker sessions with session IDs of its own, not the `SESSION_ID` your request sent. Each session writes to a log stream named `runtime-logs-<session ID>`, so the newest such stream names the worker's session:

**macOS/Linux**

```bash
WORKER_SESSION="$(aws logs describe-log-streams --region "$AWS_REGION" \
  --log-group-name "/aws/bedrock-agentcore/runtimes/${RUNTIME_ARN##*/}-DEFAULT" \
  --order-by LastEventTime --descending --limit 5 \
  --query "logStreams[?starts_with(logStreamName,'runtime-logs-')] | [0].logStreamName" \
  --output text | sed 's/^runtime-logs-//')"
echo "$WORKER_SESSION"
aws bedrock-agentcore stop-runtime-session --region "$AWS_REGION" \
  --agent-runtime-arn "$RUNTIME_ARN" --runtime-session-id "$WORKER_SESSION"
```

**Windows**

```powershell
$runtimeId = $env:RUNTIME_ARN.Split('/')[-1]
$stream = aws logs describe-log-streams --region $env:AWS_REGION --log-group-name "/aws/bedrock-agentcore/runtimes/${runtimeId}-DEFAULT" --order-by LastEventTime --descending --limit 5 --query "logStreams[?starts_with(logStreamName,'runtime-logs-')] | [0].logStreamName" --output text
$workerSession = $stream -replace '^runtime-logs-', ''
$workerSession
aws bedrock-agentcore stop-runtime-session --region $env:AWS_REGION --agent-runtime-arn $env:RUNTIME_ARN --runtime-session-id $workerSession
```

### Watch the run recover

- **The old worker disconnects.** Its log stream shows `Disconnected from …` at once. Its container can still finish the tool call it was running before AgentCore ends it. Diagrid discards that result.
- **Diagrid starts a new worker.** The agent still has work and no connected worker, so Diagrid starts a session, within seconds to half a minute. A new `runtime-logs-…` stream shows `Successfully connected to … Waiting for work items...`, then `check_vendor_availability(catering): started` at once. The venue check isn't repeated.
- **The request gets its answer.** The front end's request returns `COMPLETED`, with the budget and the availability of all three vendors. Nothing retried it.

Print the run's history:

**macOS/Linux**

```bash
diagrid workflow get "$SESSION_ID" --id budget-planner --project agentcore-quickstart
```

**Windows**

```powershell
diagrid workflow get $env:SESSION_ID --id budget-planner --project agentcore-quickstart
```

Every step has one `TaskCompleted` event. The steps that completed before the crash, the model calls, `calculate_budget` and the venue check, ran once. Their results came from the run's history. The catering check was interrupted, so it ran again from its start on the new worker: its `TaskScheduled` and `TaskCompleted` events are before and after the crash. Activities run at least once, so a tool with side effects must be safe to run twice. See [Durable execution](https://docs.diagrid.io/concepts/durable-execution).

To turn long runs off again, deploy the stack with `LongRunSeconds=0`.

## Pin a code version

Every update of the Runtime creates a new version, and the `DEFAULT` endpoint moves to it. With `DEFAULT`, every new worker runs the newest version, and workers already running keep the version they started with.

To pin a version, create a named endpoint of the Runtime that points at that version, and set it on the agent:

```bash
diagrid agent update budget-planner --project agentcore-quickstart --compute-agentcore-endpoint-name <endpoint-name>
```

Changing the endpoint name replaces the running workers. Moving a named endpoint to another version doesn't: set the endpoint name again to replace them. `--compute-agentcore-endpoint-name DEFAULT` goes back to the newest version.

## Troubleshooting

| Symptom | Cause and fix |
| --- | --- |
| `diagrid agent update` fails with `Region "<region>" does not support serverless compute` | A region of the project doesn't support serverless compute, for example because it runs an older version or has serverless compute turned off. |
| The worker doesn't start, and the agent's runs stay pending | Diagrid stops starting workers after several consecutive failed starts. After you fix the cause, change any compute setting with [`diagrid agent update`](https://docs.diagrid.io/references/diagrid/cli-reference/agent/update) to start workers again. |
| Starts fail with `AccessDeniedException` on `InvokeAgentRuntime` | The role may not invoke that Runtime. AWS gives the same error when the Runtime ARN names a Runtime that doesn't exist. Compare the Runtime ARN with the `Resource` of the role's policy: `aws iam get-role-policy --role-name diagrid-budget-planner-invoker --policy-name start-stop-agentcore-sessions`. |
| Deploying `invoker.yaml` fails with `AWS::EarlyValidation::ResourceExistenceCheck` | A role named `diagrid-budget-planner-invoker` already exists in the AWS account, created for another agent named `budget-planner`. IAM role names are unique in an account across all regions. Delete that role if nothing uses it, or change `RoleName` in `invoker.yaml`. The next steps read the role's ARN from the stack's outputs. |
| Starts fail with `IDPCommunicationError` | AWS STS can't reach the region's OIDC issuer. |
| Starts fail with `Received error (500) from runtime` | The container's `/invocations` failed. Read the worker's logs in CloudWatch. |

## Clean up

Detach the serverless compute from the agent. Workers already running are stopped:

```bash
diagrid agent update budget-planner --project agentcore-quickstart --remove-compute
```

Delete the stack. This deletes the role, its policy and the OIDC provider:

**macOS/Linux**

```bash
aws cloudformation delete-stack --region "$AWS_REGION" --stack-name diagrid-budget-planner-invoker
aws cloudformation wait stack-delete-complete --region "$AWS_REGION" --stack-name diagrid-budget-planner-invoker
```

**Windows**

```powershell
aws cloudformation delete-stack --region $env:AWS_REGION --stack-name diagrid-budget-planner-invoker
aws cloudformation wait stack-delete-complete --region $env:AWS_REGION --stack-name diagrid-budget-planner-invoker
```

Stop the front end with `Ctrl+C`. Delete the hosted agent's stack, which deletes the Runtime and the execution role, its secret, the image repository and the Diagrid project:

**macOS/Linux**

```bash
aws cloudformation delete-stack --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner
aws cloudformation wait stack-delete-complete --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner
aws secretsmanager delete-secret --region "$AWS_REGION" --secret-id "$AGENT_SECRET_ARN" --force-delete-without-recovery
aws ecr delete-repository --repository-name agentcore-quickstart-budget-planner --region "$AWS_REGION" --force
diagrid project delete agentcore-quickstart
```

**Windows**

```powershell
aws cloudformation delete-stack --region $env:AWS_REGION --stack-name agentcore-quickstart-budget-planner
aws cloudformation wait stack-delete-complete --region $env:AWS_REGION --stack-name agentcore-quickstart-budget-planner
aws secretsmanager delete-secret --region $env:AWS_REGION --secret-id $env:AGENT_SECRET_ARN --force-delete-without-recovery
aws ecr delete-repository --repository-name agentcore-quickstart-budget-planner --region $env:AWS_REGION --force
diagrid project delete agentcore-quickstart
```

## Next steps

- Learn how history and replay let a run move between workers in [Durable execution](https://docs.diagrid.io/concepts/durable-execution).
- Watch runs, token use and failures in [Operate agents](https://docs.diagrid.io/operate/project-operations/agents).
- See every flag of `diagrid agent update` in the [CLI reference](https://docs.diagrid.io/references/diagrid/cli-reference/agent/update).
