

# Upgrade the template

Upgrading moves a deployed stack to the latest template version in place. The stack keeps its name, its parameter values and its gateway ID. Before the stack changes, the upgrade shows which of the stack's resources it adds, modifies or replaces, with the views and modules nested stacks as one row each, and stops if it would replace any resource other than a version of an AI agent or AI prompt, a Lambda permission or a custom resource. An update replaces the versions of the AI agents and AI prompts it changes. To install a new stack, see [Step 3: Deploy the CloudFormation stack](real-time-data-integration-resources.md).

Every update within version 1.x is complete when you run the upgrade script and answer its prompts. The script writes the latest deployer policies to the stack's deployer role, if it has one, asks you to run the update outside contact hours, checks the gateway's audience afterwards, and runs the two AI console steps. For what each version changes, see [Release notes](#real-time-data-integration-release-notes).

An update that changes one of the stack's views or flows writes it from the template, which discards changes made to it in the Connect Customer console, in the UI builder or with the Connect assistant. Any 1.x update can change any of them, so don't keep changes there: customize through your own flow modules and the stack's parameters, or a copy under your own name. See [Extend the guide with flow modules](real-time-data-integration-modules.md).

Copies you made under your own names don't change when the stack upgrades, so they don't get the new version's changes to the views and flows. After an upgrade, copy the stack's upgraded views and flows again, repeat your changes on the new copies, and set the **Default flow for Agent UI** in your inbound flows to the new copy of the guide flow. A copy of a flow with a **Connect assistant** block, such as a copy of the AI self-service flow, names a version of the stack's AI agent, and the upgrade deletes the versions it replaces. Copy that flow again, or in your copy's **Connect assistant** block choose the newest version of the AI agent that the `AgentAssistAgentName` output names, and publish the copy. In your own AI agents, choose the newest versions of the stack's AI prompts and of any stack module they use as a tool. See [Customize the guide](real-time-data-integration-adapt.md).

You can upgrade with the upgrade script or in the CloudFormation console. The script works for every stack. The console works only for a stack that deploys with your own permissions, because a stack that deploys with the deployer policy needs the latest policy on its role first, and the script writes it.

**To find the stack's version and the latest version**

1. In the CloudFormation console, in the Region of the stack, choose **Stacks**, choose the stack, and choose the **Outputs** tab. The `TemplateVersion` output is the version the stack runs. If the outputs include `InboundFlowArn`, the stack runs the template with the account and case guide; otherwise it runs the gateway-only template.

1. The download links in [Template downloads](real-time-data-integration-deployment.md#real-time-data-integration-downloads) always hold the latest version, and the upgrade script prints both versions.

**To prepare for the upgrade**

1. Check the parameters that the newer version adds. The upgrade keeps every current parameter value and gives each new parameter its default. To change a new parameter, upgrade first and change it afterwards: in the CloudFormation console, select the stack, choose **Update** and **Use existing template**, change the field, choose **Next** until the last page, select the acknowledgments, and choose **Submit**. The change is done when the stack shows `UPDATE_COMPLETE`.

1. If the stack's `NestedTemplateBaseUrl` parameter is your own bucket, copy the latest version's views and modules templates there before you upgrade. The latest version is the newest one in [Release notes](#real-time-data-integration-release-notes).

   1. Download `connect-sf-real-time-data-integration-views.template.json`, `connect-sf-real-time-data-integration-modules.template.json` and `SHA256SUMS` from `https://ac-sf-headless360-cfn-template.s3.us-west-2.amazonaws.com/releases/{{template-version}}/`, and check the two templates against `SHA256SUMS`.

   1. Upload both templates to `{{this-URL}}/{{template-version}}/`, where {{this-URL}} is the stack's `NestedTemplateBaseUrl`.

   1. If the stack has a deployer role, give it `s3:GetObject` on the two new files.

   If the files aren't there, the upgrade stops and the stack is unchanged.

1. Plan the upgrade outside contact hours. If contacts already reach the AI self-service flow, the AI agents' tools fail from the update until the two AI console steps are done. The script runs them at its end; after an upgrade in the console, run them yourself.

## Upgrade with the script
<a name="real-time-data-integration-update-script"></a>

The script needs these rights, besides reading the stack:
+ For a stack that deploys with your own permissions: rights to update every resource in the stack, `s3:ListBucket`, `s3:PutObject` and `s3:GetObject` on the staging bucket (and `s3:CreateBucket` if the script creates it), and `bedrock-agentcore:GetGateway`. For the template with the account and case guide, also `connect:ListIntegrationAssociations` on the instance.
+ For a stack that deploys with the deployer policy: the policy's `Stack`, `ValidateTemplate` and `StagedTemplate` statements, `iam:PassRole` on the deployer role to `cloudformation.amazonaws.com`, `iam:ListRolePolicies`, `iam:GetRolePolicy` and `iam:PutRolePolicy` on the deployer role, `s3:ListBucket` on the staging bucket (and `s3:CreateBucket` if the script creates it), and `bedrock-agentcore:GetGateway`. For the template with the account and case guide, also `connect:ListIntegrationAssociations` on the instance, `iam:ListAttachedRolePolicies` and `iam:AttachRolePolicy` on the deployer role, and `iam:CreatePolicy`, `iam:ListPolicyVersions`, `iam:CreatePolicyVersion` and `iam:DeletePolicyVersion` on the policy `cfn-deployer-{{stack-name}}-ai`.

1. Open CloudShell in the Region of the stack, or set that Region on your computer; see [Where to run the AWS commands](real-time-data-integration-setup.md#real-time-data-integration-where-to-run).

1. Expand the following block, copy it, paste it at the prompt and press Enter. It asks for these values, and Enter accepts the default shown in brackets:
   + the Region of the stack;
   + the stack name;
   + if the stack deploys with a deployer role, the role's inline policy that holds the deployer policy (the default when the role has one inline policy);
   + the staging bucket, an Amazon S3 bucket you own in the stack's Region (the deployer policy's `STAGING_BUCKET` when the stack has a deployer role), and whether to create it if it doesn't exist;
   + whether to run the update now.

### The script that upgrades the stack
<a name="real-time-data-integration-code-upgrade-script"></a>

The script does these steps in order:

1. It downloads the template that matches the stack and its deployer policy, and checks both against `SHA256SUMS`. It checks the new version's views and modules templates, as the stack reads them with the default `NestedTemplateBaseUrl`, against the release folder's `SHA256SUMS`.

1. It prints the stack's version and the latest version, and stops if the stack already runs that version.

1. It stages the template in the bucket, creates a change set that keeps every current parameter value, and prints the change set's resource changes.

1. It deletes the change set and stops if any resource shows `True` under `Replacement`, or `Conditional` on a resource other than a Lambda permission, a custom resource, or a version of an AI agent or AI prompt. An update that changes an AI agent or AI prompt publishes a new version of it and deletes the old one, so those rows can show `Conditional`. Until you confirm, neither the stack nor the deployer role changes.

1. After you confirm, it writes the latest deployer policy to the role, if the stack has one. For the template with the account and case guide, it also writes the AI self-service policy `cfn-deployer-{{stack-name}}-ai`.

1. It runs the change set, waits for the update, and checks the gateway's allowed audience, as the `VerifyAudience` output does.

1. For the template with the account and case guide, it runs the two AI console steps: the console steps script with **set**, from your home folder, where it saves the default it replaces. If the assistant has no **Self service** default, or its default names an AI agent or version that no longer exists, the script sets the stack's knowledge agent as the default for every self-service flow on the assistant. Otherwise it keeps the default you chose.

```
(
  set -o pipefail
  W=$(mktemp -d); trap 'rm -rf "$W"' EXIT; cd "$W" || exit 1
  BASE=https://ac-sf-headless360-cfn-template.s3.us-west-2.amazonaws.com
  R=${AWS_REGION:-us-east-1}
  printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R}
  printf 'Stack name [connect-sf-real-time]: '; read -r STACK; STACK=${STACK:-connect-sf-real-time}
  q() { aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" --query "$1" --output text; }
  STATUS=$(q 'Stacks[0].StackStatus') || exit 1
  case "$STATUS" in CREATE_COMPLETE|UPDATE_COMPLETE|UPDATE_ROLLBACK_COMPLETE) ;;
    *) echo "The stack is $STATUS; nothing changed. Upgrade it only when it is CREATE_COMPLETE, UPDATE_COMPLETE or UPDATE_ROLLBACK_COMPLETE."; exit 1 ;; esac
  CUR=$(q "Stacks[0].Outputs[?OutputKey=='TemplateVersion'].OutputValue | [0]")
  GATEWAY=$(q "Stacks[0].Outputs[?OutputKey=='GatewayId'].OutputValue | [0]")
  if [ "$(q "Stacks[0].Outputs[?OutputKey=='InboundFlowArn'].OutputValue | [0]")" = None ]; then
    NAME=connect-sf-real-time-data-integration-gateway; else NAME=connect-sf-real-time-data-integration; fi
  curl -fsSO "$BASE/$NAME.template.json" && curl -fsSO "$BASE/$NAME.deployer-policy.json" && curl -fsSO "$BASE/SHA256SUMS" \
    || { echo "Download failed; nothing changed."; exit 1; }
  FILES="$NAME.template.json $NAME.deployer-policy.json"; AI=
  if [ "$NAME" = connect-sf-real-time-data-integration ]; then
    AI=connect-sf-real-time-data-integration-ai-sample.deployer-policy.json; FILES="$FILES $AI"
    curl -fsSO "$BASE/$AI" || { echo "Download failed; nothing changed."; exit 1; }
  fi
  # sha256sum where it exists (Linux, CloudShell), else shasum (macOS)
  sum_ok() { if command -v sha256sum >/dev/null 2>&1; then sha256sum -c --status; else shasum -a 256 -c --status; fi; }
  for F in $FILES; do
    grep -q " $F\$" SHA256SUMS || { echo "SHA256SUMS has no line for $F; nothing changed."; exit 1; }
    grep " $F\$" SHA256SUMS | sum_ok || { echo "The download doesn't match its checksum; nothing changed."; exit 1; }
  done
  NEW=$(grep -o 'Template version [0-9][0-9.]*[0-9]' "$NAME.template.json" | head -n 1); NEW=${NEW#Template version }
  echo "The stack runs template version $CUR. The latest version is $NEW."
  [ "$CUR" != "$NEW" ] || { echo "The stack already runs the latest version; nothing changed."; exit 0; }
  if [ -n "$AI" ]; then
    # The nested views and modules templates of the new version, checked against the release folder's SHA256SUMS
    NESTED=$(grep -o 'connect-sf-real-time-data-integration-[a-z]*[.]template[.]json' "$NAME.template.json" | sort -u)
    ( mkdir -p rel && cd rel && curl -fsSO "$BASE/releases/$NEW/SHA256SUMS" \
      && for F in $NESTED; do
        curl -fsSO "$BASE/releases/$NEW/$F" && grep " $F\$" SHA256SUMS | sum_ok || exit 1; done ) \
      || { echo "The release $NEW views or modules template doesn't match its checksum; nothing changed."; exit 1; }
  fi
  ACCOUNT=$(aws sts get-caller-identity --region "$REGION" --query Account --output text) || exit 1
  ROLE=$(q 'Stacks[0].RoleARN'); ROLE_ARG=(); POLICY=; DEF_BUCKET=connect-sf-upgrade-$ACCOUNT-$REGION
  if [ "$ROLE" != None ]; then
    ROLE_ARG=(--role-arn "$ROLE"); RN=${ROLE##*/}
    NAMES=$(aws iam list-role-policies --role-name "$RN" --query 'PolicyNames' --output text) || exit 1
    NAMES=$(echo $NAMES)
    [ -n "$NAMES" ] || { echo "The role $RN has no inline policy; attach the deployer policy to it inline. Nothing changed."; exit 1; }
    echo "The stack deploys with the role $RN. Its inline policies: $NAMES"
    if [ "$(echo "$NAMES" | wc -w)" -eq 1 ]; then P0=$NAMES; else P0=; fi
    printf 'Name of the inline policy that holds the deployer policy [%s]: ' "$P0"; read -r POLICY; POLICY=${POLICY:-$P0}
    case " $NAMES " in *" $POLICY "*) ;; *) echo "Enter one of: $NAMES. Nothing changed."; exit 1 ;; esac
    B0=$(aws iam get-role-policy --role-name "$RN" --policy-name "$POLICY" \
      --query "PolicyDocument.Statement[?Sid=='StagedTemplate'].Resource | [0]" --output text) || exit 1
    B0=${B0%%[[:space:]]*}; B0=${B0#arn:aws:s3:::}; B0=${B0%/\*}; [ "$B0" = None ] || [ -z "$B0" ] || DEF_BUCKET=$B0
  fi
  printf 'Staging bucket, an S3 bucket you own in %s [%s]: ' "$REGION" "$DEF_BUCKET"; read -r BUCKET; BUCKET=${BUCKET:-$DEF_BUCKET}
  if ! aws s3api head-bucket --bucket "$BUCKET" --expected-bucket-owner "$ACCOUNT" --region "$REGION" >/dev/null 2>&1; then
    printf 'The bucket %s does not exist or is not yours. Create it in %s? [y]: ' "$BUCKET" "$REGION"; read -r MK
    [ "${MK:-y}" = y ] || { echo "Nothing changed."; exit 1; }
    aws s3 mb "s3://$BUCKET" --region "$REGION" || exit 1
    aws s3api head-bucket --bucket "$BUCKET" --expected-bucket-owner "$ACCOUNT" --region "$REGION" >/dev/null 2>&1 \
      || { echo "The bucket $BUCKET is not in account $ACCOUNT. Nothing changed."; exit 1; }
  fi
  aws s3api put-object --bucket "$BUCKET" --key "$NAME.template.json" --body "$NAME.template.json" \
    --expected-bucket-owner "$ACCOUNT" --region "$REGION" >/dev/null || exit 1
  URL="https://$BUCKET.s3.$REGION.amazonaws.com/$NAME.template.json"
  KEEP=" $(python3 -I -c 'import json, sys; print(" ".join(json.load(open(sys.argv[1]))["Parameters"]))' "$NAME.template.json") " || exit 1
  PARAMS=()
  INSTANCE_ID=$(q "Stacks[0].Parameters[?ParameterKey=='InstanceArn'].ParameterValue | [0]" | sed 's|.*/||')
  for K in $(q 'Stacks[0].Parameters[].ParameterKey'); do
    case "$KEEP" in *" $K "*) ;; *) continue ;; esac
    PARAMS+=("ParameterKey=$K,UsePreviousValue=true")
  done
  CS=update-to-${NEW//./-}-$(date +%H%M%S)
  csq() { aws cloudformation describe-change-set --region "$REGION" --stack-name "$STACK" --change-set-name "$CS" --query "$1" --output "${2:-text}"; }
  csdel() { aws cloudformation delete-change-set --region "$REGION" --stack-name "$STACK" --change-set-name "$CS"; }
  aws cloudformation create-change-set --region "$REGION" --stack-name "$STACK" --change-set-name "$CS" \
    --template-url "$URL" --capabilities CAPABILITY_IAM "${ROLE_ARG[@]}" --parameters "${PARAMS[@]}" >/dev/null || exit 1
  if ! aws cloudformation wait change-set-create-complete --region "$REGION" --stack-name "$STACK" --change-set-name "$CS"; then
    echo "The change set failed: $(csq StatusReason). The stack is unchanged."; csdel; exit 1
  fi
  csq 'Changes[].ResourceChange.{Action:Action,Resource:LogicalResourceId,Type:ResourceType,Replacement:Replacement}' table
  REPLACED=$(csq "Changes[?ResourceChange.Replacement=='True' || (ResourceChange.Replacement=='Conditional' && ResourceChange.ResourceType!='AWS::Lambda::Permission' && ResourceChange.ResourceType!='AWS::CloudFormation::CustomResource' && ResourceChange.ResourceType!='AWS::Wisdom::AIAgentVersion' && ResourceChange.ResourceType!='AWS::Wisdom::AIPromptVersion')].ResourceChange.LogicalResourceId")
  if [ -n "$REPLACED" ]; then
    echo "The update would or might replace: $REPLACED. It was not run; the stack is unchanged."; csdel; exit 1
  fi
  [ -z "$POLICY" ] || echo "Before the update runs, the script writes the latest deployer policy to $POLICY on $RN."
  printf 'Run the update now, outside contact hours? [n]: '; read -r GO
  if [ "${GO:-n}" != y ]; then
    echo "Not run; the stack is unchanged. The change set $CS stays on the stack's Change sets tab until you run or delete it."; exit 0
  fi
  if [ -n "$POLICY" ]; then
    sed -e "s/REGION/$REGION/g; s/ACCOUNT_ID/$ACCOUNT/g; s/STACK_NAME/$STACK/g" \
      -e "s/INSTANCE_ID/$(q "Stacks[0].Parameters[?ParameterKey=='InstanceArn'].ParameterValue | [0]" | sed 's|.*/||')/g" \
      -e "s/STAGING_BUCKET/$BUCKET/g; s/DEPLOYER_ROLE/$RN/g" "$NAME.deployer-policy.json" > policy.json
    aws iam put-role-policy --role-name "$RN" --policy-name "$POLICY" --policy-document file://policy.json || exit 1
    echo "Updated the policy $POLICY on $RN."
    if [ -n "$AI" ]; then
      sed -e "s/REGION/$REGION/g; s/ACCOUNT_ID/$ACCOUNT/g; s/STACK_NAME/$STACK/g; s/INSTANCE_ID/$INSTANCE_ID/g" "$AI" > ai-policy.json
      AI_ARN=$(aws iam list-attached-role-policies --role-name "$RN" \
        --query "AttachedPolicies[?PolicyName=='cfn-deployer-$STACK-ai'].PolicyArn | [0]" --output text) || exit 1
      if [ "$AI_ARN" = None ]; then
        AI_ARN=$(aws iam create-policy --policy-name "cfn-deployer-$STACK-ai" --policy-document file://ai-policy.json \
          --query Policy.Arn --output text) || exit 1
        aws iam attach-role-policy --role-name "$RN" --policy-arn "$AI_ARN" || exit 1
        echo "Created and attached the AI self-service policy cfn-deployer-$STACK-ai."
      else
        OLD=$(aws iam list-policy-versions --policy-arn "$AI_ARN" \
          --query "Versions[?IsDefaultVersion==\`false\`].VersionId" --output text) || exit 1
        [ "$(echo $OLD | wc -w)" -lt 4 ] || aws iam delete-policy-version --policy-arn "$AI_ARN" --version-id "$(echo $OLD | tr ' ' '\n' | sort -V | head -n 1)" || exit 1
        aws iam create-policy-version --policy-arn "$AI_ARN" --policy-document file://ai-policy.json --set-as-default >/dev/null || exit 1
        echo "Updated the AI self-service policy cfn-deployer-$STACK-ai."
      fi
    fi
    echo "Waiting 15 seconds for IAM."; sleep 15
  fi
  aws cloudformation execute-change-set --region "$REGION" --stack-name "$STACK" --change-set-name "$CS" || exit 1
  echo "Updating."
  if ! aws cloudformation wait stack-update-complete --region "$REGION" --stack-name "$STACK"; then
    echo "The update failed and the stack is $(q 'Stacks[0].StackStatus'). Failed resources:"
    aws cloudformation describe-stack-events --region "$REGION" --stack-name "$STACK" --max-items 60 \
      --query "StackEvents[?ends_with(ResourceStatus,'FAILED')].[LogicalResourceId,ResourceStatusReason]" --output text
    exit 1
  fi
  echo "The stack runs template version $(q "Stacks[0].Outputs[?OutputKey=='TemplateVersion'].OutputValue | [0]")."
  AUD=$(aws bedrock-agentcore-control get-gateway --region "$REGION" --gateway-identifier "$GATEWAY" \
    --query authorizerConfiguration.customJWTAuthorizer.allowedAudience --output text) \
    || { echo "Couldn't read the gateway; run the VerifyAudience output's command."; exit 1; }
  if [ "$AUD" = "$GATEWAY" ]; then echo "Gateway audience: $AUD (correct)."
  else echo "Gateway audience: $AUD. It must be $GATEWAY; tool calls fail until it is."; exit 1; fi
  if [ -n "$AI" ]; then
    echo "Running the two AI console steps (set), with the Self service default the script offers."
    cat > "$W/ai-agent-defaults.sh" <<'AI_DEFAULTS_EOF'
set -euo pipefail

ask() {
  local reply
  read -r -p "$1 [$2]: " reply
  printf '%s' "${reply:-$2}"
}

# CloudShell sets AWS_REGION to the console's Region; elsewhere the CLI's configured Region is the default
region=$(ask "Region of the stack" "${AWS_REGION:-$(aws configure get region 2>/dev/null || echo us-east-1)}")
stack=$(ask "Stack name" "connect-sf-real-time")
action=$(ask "set (after a create or update) or remove (before a delete)" "set")
[[ "$action" == set || "$action" == remove ]] || { echo "Type set or remove." >&2; exit 2; }

cfn() { aws cloudformation describe-stacks --region "$region" --stack-name "$stack" --query "Stacks[0].$1" --output text; }
output() { cfn "Outputs[?OutputKey=='$1'].OutputValue | [0]"; }

status=$(output ConnectAssistantStatus 2> /dev/null) || { echo "Can't read stack $stack in $region." >&2; exit 2; }
[[ "$status" == Created\ * || "$status" == Reused\ * ]] || { echo "Stack $stack has no ConnectAssistantStatus output." >&2; exit 2; }
assistant_id=${status##*/}
instance_arn=$(cfn "Parameters[?ParameterKey=='InstanceArn'].ParameterValue | [0]")
instance_id=${instance_arn##*/}
saved="$stack-ai-agent-defaults-before.txt"
use_case=Connect.SelfService

# The latest published version of the AI agent whose output prefix is $1 (Knowledge, Account or AgentAssist).
latest() {
  local agent_arn
  agent_arn=$(output "$1AgentArn")
  aws qconnect list-ai-agent-versions --region "$region" --assistant-id "$assistant_id" --ai-agent-id "${agent_arn##*/}" \
    --query "max(aiAgentVersionSummaries[].versionNumber)" --output text
}

# Associates (set) or disassociates (remove) the AI agent whose output prefix is $1, and its latest version, with the
# security profile its output names. Does nothing if the stack has no such AI agent.
profiles() {
  local agent_arn name profile profile_id version verb arn
  agent_arn=$(output "$1AgentArn")
  [[ "$agent_arn" != None ]] || return 0
  name=$(output "$1AgentName")
  profile=$(output "$1AgentSecurityProfile")
  profile_id=$(aws connect list-security-profiles --region "$region" --instance-id "$instance_id" \
    --query "SecurityProfileSummaryList[?Name=='$profile'].Id | [0]" --output text)
  version=$(latest "$1")
  if [[ "$profile_id" == None ]]; then
    # Nothing to associate or remove; on remove, carry on with the other AI agents and the default.
    echo "No security profile $profile in the instance." >&2
    [[ "$action" == remove ]] && return 0
    exit 1
  fi
  if [[ "$version" == None && "$action" == set ]]; then echo "No published version of $name." >&2; exit 1; fi
  verb=associate-security-profiles
  [[ "$action" == set ]] || verb=disassociate-security-profiles
  local arns=("$agent_arn") v
  if [[ "$version" != None ]]; then
    if [[ "$action" == set ]]; then
      arns+=("$agent_arn:$version")
    else
      # On remove, every version from 1 to the latest, so no older version keeps the profile.
      for ((v = 1; v <= version; v++)); do arns+=("$agent_arn:$v"); done
    fi
  fi
  for arn in "${arns[@]}"; do
    if [[ "$action" == set ]]; then
      aws connect "$verb" --region "$region" --instance-id "$instance_id" --security-profiles "Id=$profile_id" \
        --entity-type AI_AGENT --entity-arn "$arn"
    else
      # Removing an association that isn't there is not an error here.
      aws connect "$verb" --region "$region" --instance-id "$instance_id" --security-profiles "Id=$profile_id" \
        --entity-type AI_AGENT --entity-arn "$arn" 2> /dev/null || true
    fi
  done
  if [[ "$action" == set ]]; then echo "Associated $profile with $name and its version $version."; else echo "Removed $profile from $name."; fi
}

if [[ "$action" == set ]]; then
  current=$(aws qconnect get-assistant --region "$region" --assistant-id "$assistant_id" \
    --query "assistant.orchestratorConfigurationList[?orchestratorUseCase=='$use_case'].aiAgentId | [0]" --output text)
  # Show the default AI agent by name when the assistant still has it
  current_label=$current
  if [[ "${current%%:*}" != None ]]; then
    current_name=$(aws qconnect get-ai-agent --region "$region" --assistant-id "$assistant_id" --ai-agent-id "${current%%:*}" \
      --query aiAgent.name --output text 2> /dev/null || true)
    [[ -z "$current_name" || "$current_name" == None ]] || current_label="$current_name ($current)"
  fi
  echo "The assistant's Self service default is now ${current_label/None/not set}. It applies to every self-service flow on the assistant."
  # Offer a change only when the default is not set or is already one of this stack's AI agents;
  # otherwise the default is an AI agent your own flows may use, so Enter keeps it.
  knowledge_id=$(output KnowledgeAgentArn); knowledge_id=${knowledge_id##*/}
  account_id=$(output AccountAgentArn); account_id=${account_id##*/}
  current_id=${current%%:*}
  current_version=
  [[ "$current" != *:* ]] || current_version=${current##*:}
  case "$current_id" in
    None) offer=knowledge ;;
    "$knowledge_id" | "$account_id")
      # One of this stack's AI agents: the default must name its latest version, which this update published.
      # Offer the same AI agent's latest version, so Enter keeps the admin's choice of agent.
      if [[ "$current_id" == "$knowledge_id" ]]; then mine=Knowledge offer=knowledge; else mine=Account offer=account; fi
      newest=$(latest "$mine")
      if [[ -z "$current_version" || "$newest" == None || "$current_version" != "$newest" ]]; then
        echo "That is $(output "${mine}AgentName") version ${current_version:-none}, but its latest version is ${newest/None/none}:"
        echo "self-service contacts don't get this update's AI agent until the default names the latest version."
      fi ;;
    *) offer=keep
       # Another AI agent: check that it and its version still exist; if not, offer the knowledge agent
       if ! aws qconnect get-ai-agent --region "$region" --assistant-id "$assistant_id" --ai-agent-id "$current_id" \
           > /dev/null 2>&1; then
         echo "That AI agent no longer exists on the assistant."
         offer=knowledge
       elif [[ -n "$current_version" && $(aws qconnect list-ai-agent-versions --region "$region" --assistant-id "$assistant_id" \
           --ai-agent-id "$current_id" --query "length(aiAgentVersionSummaries[?versionNumber==\`$current_version\`])" \
           --output text 2> /dev/null || echo 0) == 0 ]]; then
         echo "That AI agent has no version $current_version on the assistant."
         offer=knowledge
       else
         echo "That AI agent is not one of this stack's. Setting knowledge or account moves every self-service flow"
         echo "on this assistant, your own included, to that AI agent. Type keep to leave it as it is."
       fi ;;
  esac
  if [[ $(output AccountAgentArn) != None ]]; then
    echo "The account agent reads the account in each contact's accountId. Make it the default only if every self-service"
    echo "flow on this assistant sets accountId from verified data, or to -, before its Connect assistant block."
    choice=$(ask "Self service default: knowledge, account, or keep (change nothing)" "$offer")
  else
    [[ "$offer" != account ]] || offer=keep
    choice=$(ask "Self service default: knowledge, or keep (change nothing)" "$offer")
  fi
  case $choice in
    knowledge) prefix=Knowledge ;;
    account) prefix=Account ;;
    keep) prefix= ;;
    *) echo "Type knowledge, account or keep." >&2; exit 2 ;;
  esac
  if [[ -n "$prefix" ]]; then
    agent_arn=$(output "${prefix}AgentArn")
    version=$(latest "$prefix")
    [[ "$version" != None ]] || { echo "No published version of $(output "${prefix}AgentName")." >&2; exit 1; }
    # Never save one of this stack's own AI agents as the default to put back: remove runs before the stack's delete,
    # which deletes them. A set run again, from another folder, would otherwise save the stack's agent there.
    if [[ "$current_id" != None && ( "$current_id" == "$knowledge_id" || "$current_id" == "$account_id" ) ]]; then
      if grep -q "^$use_case=" "$saved" 2>/dev/null; then
        replaced="It replaced this stack's own AI agent; remove puts back the default saved earlier in $saved."
      else
        replaced="It replaced this stack's own AI agent, so remove has nothing to put back."
      fi
    else
      grep -q "^$use_case=" "$saved" 2>/dev/null || echo "$use_case=$current" >> "$saved"
      replaced="The one it replaced is saved in $saved."
    fi
    aws qconnect update-assistant-ai-agent --region "$region" --assistant-id "$assistant_id" --ai-agent-type ORCHESTRATION \
      --orchestrator-use-case "$use_case" --configuration "aiAgentId=${agent_arn##*/}:$version" > /dev/null
    echo "Set $(output "${prefix}AgentName") (version $version) as the Self service default. $replaced"
  fi
  for prefix in Knowledge Account AgentAssist; do profiles "$prefix"; done
else
  for prefix in Knowledge Account AgentAssist; do profiles "$prefix"; done
  previous=$(grep "^$use_case=" "$saved" 2>/dev/null | head -n 1 | cut -d= -f2- || true)
  if [[ -n "$previous" && $(ask "Put back the Self service default saved in $saved ($previous)? yes or no" "yes") == yes ]]; then
    if [[ "$previous" == None ]]; then
      aws qconnect remove-assistant-ai-agent --region "$region" --assistant-id "$assistant_id" \
        --ai-agent-type ORCHESTRATION --orchestrator-use-case "$use_case"
    else
      aws qconnect update-assistant-ai-agent --region "$region" --assistant-id "$assistant_id" --ai-agent-type ORCHESTRATION \
        --orchestrator-use-case "$use_case" --configuration "aiAgentId=$previous" > /dev/null
    fi
    # Forget it, so a later set on a stack of the same name saves the default as it is then.
    rm -f "$saved"
    echo "Put back the Self service default."
  elif [[ -z "$previous" ]]; then
    echo "No saved Self service default: if the assistant's Self service default is one of this stack's AI agents, set another one in the console."
  fi
fi
AI_DEFAULTS_EOF
    (cd ~ && printf '%s\n%s\nset\n\n' "$REGION" "$STACK" | bash "$W/ai-agent-defaults.sh") \
      || { echo "The AI console steps failed; run the console steps script with set."; exit 1; }
  fi
)
```

It prints `Gateway audience:`, the gateway's ID and `(correct)`. For the template with the account and case guide, it then runs the AI console steps and prints an `Associated` line for each AI agent. To choose another **Self service** default, such as the account agent, run the console steps script yourself; see [Finish the AI setup after each create or update](real-time-data-integration-ai-console.md). If it prints anything else, see [Upgrading the template](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-upgrade).

## Upgrade in the CloudFormation console
<a name="real-time-data-integration-update-console"></a>

Use the console only if the stack deploys with your own permissions: if the stack's **Stack info** tab shows an **IAM role**, use the upgrade script.

1. In the CloudFormation console, in the Region of the stack, choose **Stacks** and select the option button next to the stack.

1. Choose **Stack actions**, then **Create a change set**.

1. Leave **Standard change set** selected. Choose **Replace existing template** and **Amazon S3 URL**, and paste the download URL of the template the stack runs from [Template downloads](real-time-data-integration-deployment.md#real-time-data-integration-downloads). Choose **Next**.

1. Keep the change set name the console fills in. Under **Parameters**, each field shows the stack's current value, and each parameter the new version adds shows its default. Keep each new parameter's default. Choose **Next**.

1. On **Configure change set options**, leave every option as it is, with **Express mode** not enabled and **Roll back all resources** selected. Select **I acknowledge that AWS CloudFormation might create IAM resources** and choose **Next**.

1. Choose **Create change set**. The console shows **You have successfully created a standard change set**, and **Change set status** shows `CREATE_COMPLETE`. If it shows `FAILED`, the **Change set status reason** names the cause; choose **Delete change set** and correct it.

1. In **Resource changes**, read the **Replacement** column. If any row shows `True`, or shows `Conditional` on a row whose type isn't in the list after this step, choose **Delete change set** and don't upgrade: a replaced gateway gets a new ID, which changes every tool name your flows call, and a replaced flow or view gets a new ARN. No update within 1.x replaces these, so contact AWS Support. `False`, `-` (a resource the version adds or removes) and `Conditional` on these four types are expected. For the AI agents and AI prompts, the update publishes a new version of each one it changes and deletes the old version; the stack's own flows move to the new version, and the AI console steps after the upgrade move the rest:
   + `AWS::Lambda::Permission`
   + `AWS::CloudFormation::CustomResource`
   + `AWS::Wisdom::AIAgentVersion`
   + `AWS::Wisdom::AIPromptVersion`

1. Outside contact hours, choose **Execute change set**. In the dialog, leave **Roll back all stack resources** and **Use deletion policy** selected, and choose **Execute change set**.

1. Wait for the stack's status to change from `UPDATE_IN_PROGRESS`. `UPDATE_COMPLETE` means the upgrade worked. `UPDATE_ROLLBACK_IN_PROGRESS` or `UPDATE_ROLLBACK_COMPLETE` means it failed: see [If the upgrade fails](#real-time-data-integration-update-fails).

1. On the **Outputs** tab, check that `TemplateVersion` shows the new version. Copy the `VerifyAudience` output's command, paste it at the prompt and press Enter. It prints the `GatewayId` output's value. If it prints anything else, see the `VerifyAudience` entry in [Deploying and updating the stack](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-deploy).

1. For the template with the account and case guide, run the two AI console steps with the console steps script and **set**; see [Finish the AI setup after each create or update](real-time-data-integration-ai-console.md).

## If the upgrade fails
<a name="real-time-data-integration-update-fails"></a>

A failed upgrade rolls back to the previous version and shows `UPDATE_ROLLBACK_COMPLETE`. Run the `VerifyAudience` command: a rollback can leave the audience at its placeholder.

1. On the stack's **Outputs** tab, check that `TemplateVersion` shows the previous version. Copy the `VerifyAudience` output's command, paste it at the prompt and press Enter. It must print the `GatewayId` output's value.

1. On the **Events** tab, find the cause: the first event with a status that ends in `_FAILED` whose reason isn't `Resource update cancelled` or `Resource creation cancelled`.

1. If the reason says that the deployer role `is not authorized to perform` an action, the role's policy is older than the template. Upgrade with the upgrade script; it writes the latest policy before the update runs.

1. For any other reason, look it up as *If the stack fails* in [Step 3: Deploy the CloudFormation stack](real-time-data-integration-resources.md) describes, correct the cause, and upgrade again. A stack in `UPDATE_ROLLBACK_COMPLETE` can be upgraded again.

1. If the stack shows `UPDATE_ROLLBACK_FAILED` and the failed event is the deployment's token refresh, the rollback asked Salesforce for a token with the previous values and was refused, or the External Client App's **Run As** user changed while `SalesforceIntegrationUsername` was set. To finish the rollback without that request, paste the following block at the prompt. It asks for the Region and the stack name. The token secret keeps its value, and the scheduled token refresh keeps running.

   ```
   (
     R=${AWS_REGION:-us-east-1}
     printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R}
     printf 'Stack name [connect-sf-real-time]: '; read -r STACK; STACK=${STACK:-connect-sf-real-time}
     aws cloudformation continue-update-rollback --region "$REGION" --stack-name "$STACK" \
       --resources-to-skip SalesforceInitialTokenRefreshAB1639C6 || exit 1
     echo "Rollback continued. Waiting for it to finish."
     aws cloudformation wait stack-rollback-complete --region "$REGION" --stack-name "$STACK" \
       && echo "The stack is UPDATE_ROLLBACK_COMPLETE."
   )
   ```

   It ends with `The stack is UPDATE_ROLLBACK_COMPLETE.` If the command prints an error, the stack isn't in `UPDATE_ROLLBACK_FAILED` or the resource name doesn't match; check the stack's status and its first failed event. Then fix the **Run As** user or the parameter, and upgrade again.

   For a stack in `UPDATE_ROLLBACK_FAILED` for another cause, fix the cause that the failed event names, then choose **Stack actions**, **Continue update rollback**. If a resource still can't roll back, the same page lets you skip it; see [Continue rolling back an update](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-continueupdaterollback.html).

## Release notes
<a name="real-time-data-integration-release-notes"></a>

These notes list each version's changes. A stack's `TemplateVersion` output shows the version it runs.

**1.3.0, search and flow designer**
+ Search works for a word Salesforce would spell-correct, which showed **The search did not work** before, and finds the words the agent typed. Your own flows that call `searchRecords` should send `spellCorrection` as `false`.
+ The stack's flows and flow modules open laid out in the flow designer, except the account and case guide flow. To get the layout in a copy you made earlier, copy the flow again.
+ If your own flows, or a copy of the AI self-service flow, have a **Connect assistant** block that names the stack's agent assist AI agent, choose its newest version again after you upgrade. If your own AI agents use Find the customer or Create a customer as tools, choose the modules' new versions.

**1.2.0, Edit customer and Edit contact**
+ Agents edit the account's name, phone and billing city, and a contact's name, email and phone, from the account view. The guide saves only if the record hasn't changed since it was read. See [Edit the account and its contacts](real-time-data-integration-agent-experience.md#real-time-data-integration-agent-edit).
+ **Customer information** has **Refresh**, which reads the account from Salesforce again.
+ Each form marks its required boxes \* and isn't sent until they're filled. If your own flows use the Create a case, Create a case with details, Create a customer or Update a record module, the module refuses an empty required input. See [Extend the guide with flow modules](real-time-data-integration-modules.md).
+ Agent assist can update the account or one of its contacts after the agent confirms. To allow it, add `{{stack-name}}-account-360-update-record` to the agents' security profile.
+ Your own flows can use the new Update a record module to update an account or contact. See [Extend the guide with flow modules](real-time-data-integration-modules.md).
+ Your own flows and AI agents can update one account or contact through the gateway, as the integration user, within the access your Salesforce administrator gives that user. See [Updates of an account or a contact](real-time-data-integration-salesforce.md#real-time-data-integration-salesforce-updates).
+ If your own flows read the account the way the 1.0.0 to 1.1.0 guide does, they keep working after you upgrade, through 1.x.
+ If you copied the stack's views, guide flow or AI self-service flow under your own names, copy them again after you upgrade. The copies don't get Edit customer, Edit contact or the required boxes, and a copied AI self-service flow names an AI agent version the upgrade deletes. See [Customize the guide](real-time-data-integration-adapt.md).

**1.1.0, See all cases**
+ Agents see how many cases the account has, and **See all cases** lists them ten at a time, open cases first.
+ Agent assist can list older cases. To allow it, add `{{stack-name}}-account-360-list-cases` to the agents' security profile.
+ Your own flows can list an account's cases ten at a time, with its open and closed case counts. See [Extend the guide with flow modules](real-time-data-integration-modules.md).

**1.0.0, first release**
+ A sample account and case guide, which shows agents the customer's account, recent cases and contacts, and lets them update and create cases and add customers and contacts; see [What agents see in the sample account and case guide](real-time-data-integration-agent-experience.md).
+ A sample AI self-service flow, which gets no contacts until you route them to it; see [Use the Connect assistant with real-time data integration](real-time-data-integration-ai-agents.md).
+ Agent assist, which reads and writes Salesforce for the agent and asks before each write; see [Give agents agent assist in the agent workspace](real-time-data-integration-ai-assist.md).
+ The guide opens the customer's record from the contact's attributes, or through a module of your own; see [How the guide finds the record](real-time-data-integration-start.md#real-time-data-integration-find-record).
+ Eight flow modules your own flows can reuse, six of them also as tools for AI agents; see [Extend the guide with flow modules](real-time-data-integration-modules.md).
+ A gateway-only template, for building your own guides without the sample guide; see [CloudFormation template reference](real-time-data-integration-deployment.md).