Skip to content

Comments

feat: add Bedrock AgentCore integration for AI agents#13353

Merged
czubocha merged 35 commits intomainfrom
sc-3770
Feb 19, 2026
Merged

feat: add Bedrock AgentCore integration for AI agents#13353
czubocha merged 35 commits intomainfrom
sc-3770

Conversation

@czubocha
Copy link
Contributor

@czubocha czubocha commented Feb 17, 2026

Summary

  • Add full AWS Bedrock AgentCore integration to the Serverless Framework, enabling deployment and management of AI agents as first-class resources alongside Lambda functions
  • Introduce ai top-level configuration in serverless.yml for defining agents, tools (Lambda gateway, remote MCP), memory, browsers, and code interpreters
  • Compile agent resources to CloudFormation: runtimes, gateways, gateway targets, memory, browser, code interpreter, and all associated IAM roles with least-privilege policies
  • Add Docker image building (auto-build or custom Dockerfile) and ECR upload for agent container artifacts
  • Add sls dev mode for agents with hot-reload, local Docker execution, file watching, and credential forwarding
  • Add sls invoke -a <agent> command with support for both JSON and SSE streaming responses
  • Add sls logs -a <agent> command for viewing agent CloudWatch logs (with --tail, --filter, --startTime support)
  • Add sls info output for deployed agent runtime endpoints
  • Add Python agent support with automatic pip install, requirements.txt / pyproject.toml detection, and code injection for the runtime entry point
  • Add comprehensive configuration schema validation (JSON Schema + semantic validation) for all ai.* properties
  • Include 20+ example agents (JavaScript and Python) covering: basic, streaming, gateway tools, browser, code interpreter, memory, multi-gateway, MCP server, and a comprehensive example combining all features
  • Add 8,100+ lines of unit tests across 23 test files covering compilers, IAM policies, validators, Docker builder, dev credentials, streaming utilities, and CLI commands

Test plan

  • Unit tests: npm run test:unit -w @serverless/framework passes (23 new test files, 8,100+ lines)
  • Deployed and invoked example agents, verifying all tool types
  • Verified sls invoke -a assistant handles both JSON and SSE streaming responses
  • Verified sls logs -a assistant displays agent CloudWatch logs
  • Verified sls info shows agent runtime endpoint URLs
  • Verified schema validation rejects invalid ai.* configurations
  • Verified sls dev mode with hot-reload rebuilds Docker images on file changes

Summary by CodeRabbit

  • New Features

    • Added AWS Bedrock AgentCore deployment and management via Serverless Framework with support for agents, gateways, tools, memory, browsers, and code interpreters.
    • Added agent-specific CLI commands: invoke agent, logs for agents, and local dev mode.
    • Added multiple JavaScript and Python example agents with LangGraph, MCP, custom browsers, and code execution capabilities.
  • Documentation

    • Added comprehensive guides for agent configuration, runtimes, memory management, gateway tools, browser automation, code interpreters, and local development.

Note

High Risk
Introduces a large new deployment surface area (new config schema, CloudFormation generation, IAM roles, and new CLI behaviors) that can affect packaging/deploy/invoke flows and permissions for existing services.

Overview
Adds AWS Bedrock AgentCore integration so Serverless Framework can deploy and manage AI agents via a new top-level ai block in serverless.yml, compiling runtimes, gateways/tools, memory, browsers, and code interpreters (plus outputs/roles) into CloudFormation.

Extends the CLI to treat agents as peers to functions: sls invoke/sls logs now accept --agent (mutually exclusive with --function), sls dev gains agent-specific options, and the framework registers new internal plugins (including bedrock-agentcore, invoke-agent, and logs-agent) and dependencies (notably @aws-sdk/client-bedrock-agentcore). Documentation is updated/added extensively for agent configuration and usage, and .gitignore now excludes an auto-generated Snyk rules file.

Written by Cursor Bugbot for commit 3671f7b. This will update automatically on new commits. Configure here.

# Conflicts:
#	package-lock.json
#	packages/serverless/package.json
# Conflicts:
#	package-lock.json
#	packages/serverless/lib/cli/commands-schema.js
#	packages/serverless/package.json
# Conflicts:
#	package-lock.json
#	packages/serverless/lib/cli/commands-schema.js
#	packages/serverless/lib/plugins/aws/dev/index.js
#	packages/serverless/lib/plugins/aws/invoke-local/runtime-wrappers/java/pom.xml
#	packages/serverless/package.json
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 17, 2026

Important

Review skipped

Too many files!

This PR contains 231 files, which is 81 over the limit of 150.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sc-3770

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Mmarzex
Copy link
Contributor

Mmarzex commented Feb 17, 2026

Snyk checks have passed. No issues have been found so far.

Status Scanner Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues
Licenses 0 0 0 0 0 issues
Code Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 60044e5904

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 19

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🟡 Minor comments (30)
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/test-invoke.py-51-69 (1)

51-69: ⚠️ Potential issue | 🟡 Minor

Inconsistent content-type checking may miss JSON responses with parameters.

Line 51 uses substring matching (in) which correctly handles content types with parameters (e.g., text/event-stream; charset=utf-8), but Line 61 uses exact equality (==) which would fail for application/json; charset=utf-8, causing such responses to fall through to the raw print branch.

Proposed fix for consistent content-type matching
-        elif response.get("contentType") == "application/json":
+        elif "application/json" in response.get("contentType", ""):
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/test-invoke.py`
around lines 51 - 69, The content-type check is inconsistent: the SSE branch
uses substring matching but the JSON branch uses exact equality on
response.get("contentType"), which misses parameterized types like
"application/json; charset=utf-8"; update the JSON branch to mirror the SSE
check (e.g., check if "application/json" in response.get("contentType", ""))
where response.get("contentType") is referenced so JSON responses with
parameters are handled correctly and not dropped to the raw branch.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/index.js-76-86 (1)

76-86: ⚠️ Potential issue | 🟡 Minor

Add error handling for invalid timezone.

If an invalid timezone string is provided, toLocaleString will throw a RangeError. Consider catching this and returning a user-friendly error message.

Proposed fix
     async ({ timezone }) => {
-      const now = new Date()
-      const options = {
-        timeZone: timezone || 'UTC',
-        dateStyle: 'full',
-        timeStyle: 'long',
+      try {
+        const now = new Date()
+        const options = {
+          timeZone: timezone || 'UTC',
+          dateStyle: 'full',
+          timeStyle: 'long',
+        }
+        return {
+          content: [{ type: 'text', text: now.toLocaleString('en-US', options) }],
+        }
+      } catch (error) {
+        return {
+          content: [{ type: 'text', text: `Invalid timezone: ${timezone}` }],
+          isError: true,
+        }
       }
-      return {
-        content: [{ type: 'text', text: now.toLocaleString('en-US', options) }],
-      }
     },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/index.js`
around lines 76 - 86, The current anonymous async handler that builds `options`
and calls `now.toLocaleString('en-US', options)` can throw a RangeError for
invalid `timezone`; wrap the `toLocaleString` call in a try/catch around the
block that builds and returns `{ content: [...] }`, catch RangeError (and
fallback for any error), and return a user-friendly error response (e.g., `{
content:[{ type:'text', text: 'Invalid timezone provided' }] }`) or a fallback
timezone; reference the anonymous async function and the `options`
object/`timezone` variable so you update that function to handle and return a
safe error message instead of throwing.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-code-interpreter-custom/test-invoke.js-47-52 (1)

47-52: ⚠️ Potential issue | 🟡 Minor

Use a streaming TextDecoder to avoid UTF‑8 boundary corruption.

Decoding each chunk with a fresh decoder can corrupt multi-byte characters split across chunk boundaries. Reuse one decoder with { stream: true } and flush at the end.

🛠️ Suggested fix
-    for await (const chunk of body) {
-      chunks.push(
-        typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk),
-      )
-    }
+    const decoder = new TextDecoder()
+    for await (const chunk of body) {
+      chunks.push(
+        typeof chunk === 'string'
+          ? chunk
+          : decoder.decode(chunk, { stream: true }),
+      )
+    }
+    chunks.push(decoder.decode())
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-code-interpreter-custom/test-invoke.js`
around lines 47 - 52, The current loop decodes each chunk with a new
TextDecoder, which can corrupt multi-byte UTF-8 characters split across chunks;
replace per-chunk decoding with a single persistent TextDecoder constructed with
streaming enabled, use decoder.decode(chunk, { stream: true }) inside the
for-await loop over body (for await (const chunk of body)) to append decoded
piece to chunks, and after the loop call decoder.decode() with no input to flush
remaining bytes before pushing the final string.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/package.json-16-24 (1)

16-24: ⚠️ Potential issue | 🟡 Minor

Dependency versions diverge significantly between this example and others.

This example uses @langchain/core: ^0.3.0 and zod: ^3.23.0, while nearly all other examples (11 out of 13) use @langchain/core: ^1.1.19 and zod: ^4.3.6. The langgraph-basic-dockerfile example also uses the older versions. Consider aligning to the newer versions used by most examples unless there is a specific reason to maintain legacy dependencies.

The node: "24.x" requirement is consistent with most examples in this PR (11 out of 13 use it), though the dockerfile variant permits >=20.0.0. If a broader Node version range would work here, consider using it to improve compatibility.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/package.json`
around lines 16 - 24, Update this example's package.json to align dependency
versions with the majority of examples: bump "@langchain/core" from "^0.3.0" to
"^1.1.19" and "zod" from "^3.23.0" to "^4.3.6" (adjust other `@langchain/`*
packages if needed for compatibility with these versions), and relax the "node"
engines constraint if you want broader compatibility (e.g., change "node":
"24.x" to a wider range such as ">=20.0.0" or match the common examples); verify
the project builds/tests after making these changes and update any code that
breaks due to the dependency upgrades.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter/README.md-14-22 (1)

14-22: ⚠️ Potential issue | 🟡 Minor

Add language identifiers to fenced code blocks.

Line 14 and Line 41 open fences without a language, which triggers MD040. Adding language hints (e.g., text, yaml) fixes linting and improves readability.

🧩 Suggested fix
-```
+```text
 langgraph-code-interpreter/
 ├── serverless.yml     # Serverless Framework configuration
 ├── agent.py           # LangGraph agent with code interpreter
 ├── Dockerfile         # Container definition
 ├── pyproject.toml     # Python dependencies
 ├── test-invoke.py     # Validation script
 └── README.md          # This file
 ```
@@
-```
+```yaml
 ai:
   agents:
     codeAgent: https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/.../invocations
 ```

Also applies to: 41-45

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter/README.md`
around lines 14 - 22, Update the two fenced code blocks in README.md to include
language identifiers: change the file-tree block that starts with
"langgraph-code-interpreter/" to open with ```text, and change the YAML-looking
block that starts with "ai:\n  agents:\n    codeAgent:" to open with ```yaml;
keep the closing ``` fences as-is so the Markdown linter (MD040) and syntax
highlighting are satisfied.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/index.js-27-28 (1)

27-28: ⚠️ Potential issue | 🟡 Minor

Avoid unconditionally overriding tool-consent bypass.

Line 27–28 forces BYPASS_TOOL_CONSENT to true even when users explicitly set it. Consider only defaulting when it’s unset so explicit configs are respected.

🛠️ Suggested fix
-// Bypass tool consent for automated deployments
-process.env.BYPASS_TOOL_CONSENT = 'true'
+// Bypass tool consent for automated deployments (only if not explicitly set)
+if (process.env.BYPASS_TOOL_CONSENT == null) {
+  process.env.BYPASS_TOOL_CONSENT = 'true'
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/index.js`
around lines 27 - 28, The code unconditionally sets
process.env.BYPASS_TOOL_CONSENT = 'true', which overrides any user-provided
value; modify the initialization so it only defaults when unset (e.g., check if
process.env.BYPASS_TOOL_CONSENT is undefined or empty before assigning) so
explicit user configuration is preserved; update the assignment site
(process.env.BYPASS_TOOL_CONSENT) in index.js to perform a
conditional/default-only set.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/README.md-95-104 (1)

95-104: ⚠️ Potential issue | 🟡 Minor

Add a language to the project structure code fence.
Helps markdown tooling and readability.

🛠️ Suggested fix
-```
+```text
 langgraph-streaming/
 ├── serverless.yml    # Serverless Framework configuration
 ├── index.js          # LangGraph JS agent with streaming
 ├── package.json      # npm dependencies
 ├── test-invoke.js    # Test script for streaming invocation
 └── README.md         # This file
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In
@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/README.md
around lines 95 - 104, Update the code fence in the README.md project structure
to include a language identifier for better markdown tooling (e.g., change the
opening totext); locate the block that lists the langgraph-streaming
directory and surrounding triple backticks in the README.md and add the language
token immediately after the first backticks so the fence becomes ```text while
keeping the same inner content (the tree listing and comments).


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/agent.js-139-145 (1)</summary><blockquote>

`139-145`: _⚠️ Potential issue_ | _🟡 Minor_

**Handle empty agent responses defensively.**  
If `result.messages` is empty, this access will throw. A small guard avoids a hard failure.



<details>
<summary>🛠️ Suggested fix</summary>

```diff
-      const finalMessage = result.messages[result.messages.length - 1]
-      const response = finalMessage.content
+      const finalMessage = result.messages?.[result.messages.length - 1]
+      const response =
+        finalMessage?.content ?? 'Error: Agent returned no response'
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/agent.js`
around lines 139 - 145, The code assumes result.messages has at least one
element and directly accesses finalMessage =
result.messages[result.messages.length - 1]; update the handling in the function
that builds and returns response so it defensively checks result.messages (e.g.,
if (!result.messages || result.messages.length === 0) return a sensible default
like an empty string or a fallback message) before computing finalMessage and
response; ensure any downstream use of finalMessage or response (the return path
and console.log) is guarded by that check to avoid runtime exceptions.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/agent.js-28-37 (1)</summary><blockquote>

`28-37`: _⚠️ Potential issue_ | _🟡 Minor_

**Guard invalid timezones to avoid runtime errors.**  
`toLocaleString` throws a `RangeError` for invalid timezones. Since the timezone is user-supplied, return a friendly error instead of crashing the handler.



<details>
<summary>🛠️ Suggested fix</summary>

```diff
 const getCurrentTime = tool(
   async ({ timezone }) => {
     const now = new Date()
     const options = {
       timeZone: timezone || 'UTC',
       dateStyle: 'full',
       timeStyle: 'long',
     }
-    return `Current time: ${now.toLocaleString('en-US', options)}`
+    try {
+      return `Current time: ${now.toLocaleString('en-US', options)}`
+    } catch {
+      return `Error: Invalid timezone "${timezone}"`
+    }
   },
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/agent.js`
around lines 28 - 37, The getCurrentTime tool currently calls toLocaleString
with a user-supplied timezone which can throw a RangeError for invalid
timezones; wrap the timezone handling in validation and error handling inside
the getCurrentTime function (or the tool wrapper) by attempting to construct an
Intl.DateTimeFormat or otherwise validating the timezone before calling
toLocaleString, and if it fails catch the RangeError and return a friendly error
message (e.g., "Invalid timezone: <value>") instead of letting the handler
crash; ensure you reference getCurrentTime and the tool wrapper when making this
change.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtimeEndpoint.js-28-53 (1)</summary><blockquote>

`28-53`: _⚠️ Potential issue_ | _🟡 Minor_

**Default tags parameter to prevent Object.keys crash.**  
The `tags` parameter lacks a default value. If a caller omits it (or passes undefined), `Object.keys(tags)` will throw a TypeError. Defaulting to an empty object is safe and defensive.

<details>
<summary>Suggested fix</summary>

```diff
 export function compileRuntimeEndpoint(
   agentName,
   endpointName,
   config,
   runtimeLogicalId,
   context,
-  tags,
+  tags = {},
 ) {
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtimeEndpoint.js`
around lines 28 - 53, The function compileRuntimeEndpoint currently calls
Object.keys(tags) but tags can be undefined; update the function signature to
default tags to an empty object (e.g., tags = {}) so Object.keys(tags) is safe,
and ensure any callers still work with the default. Locate
compileRuntimeEndpoint and modify its parameter list to set tags = {} (and
adjust any internal use of tags if needed) so the spread
"(Object.keys(tags).length > 0 && { Tags: tags })" no longer risks a TypeError.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/README.md-57-65 (1)</summary><blockquote>

`57-65`: _⚠️ Potential issue_ | _🟡 Minor_

**Update CLI command examples to match actual command syntax.**

The commands shown in the examples are incorrect:
- `sls invoke agent --agent assistant` should be `sls invoke --agent assistant` (no "agent" subcommand)
- `sls agentcore info` does not exist as a CLI command; use `sls info` for stack information instead

Update lines 57-65 in the README to use the correct command syntax.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/README.md`
around lines 57 - 65, Update the README examples to use the correct Serverless
CLI commands: replace the incorrect "sls invoke agent --agent assistant"
invocation with "sls invoke --agent assistant" (remove the extra "agent"
subcommand) and replace the reference to the non-existent "sls agentcore info"
with "sls info" when instructing users to get their runtime/stack URL; ensure
both updated command examples (the sls invoke invocation and the curl example
that references the runtime URL from `sls info`) are used in the README section
that currently shows the two examples.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/test-invoke.js-57-97 (1)</summary><blockquote>

`57-97`: _⚠️ Potential issue_ | _🟡 Minor_

**Buffer SSE lines across chunks to avoid partial event parsing.**

SSE data can be split mid-line; splitting per chunk can drop or corrupt events. Buffering preserves full lines before parsing.  


<details>
<summary>🔧 Suggested fix</summary>

```diff
-    const chunks = []
-    for await (const chunk of body) {
-      const text =
-        typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk)
+    const decoder = new TextDecoder()
+    let buffer = ''
+    const chunks = []
+    for await (const chunk of body) {
+      const text =
+        typeof chunk === 'string'
+          ? chunk
+          : decoder.decode(chunk, { stream: true })
 
-      /**
-       * Parse SSE lines and extract data payloads
-       */
-      const lines = text.split('\n')
+      /**
+       * Parse SSE lines and extract data payloads
+       */
+      buffer += text
+      const lines = buffer.split('\n')
+      buffer = lines.pop() || ''
       for (const line of lines) {
         if (line.startsWith('data: ')) {
           const data = line.slice(6)
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/test-invoke.js`
around lines 57 - 97, The SSE handler that iterates "for await (const chunk of
body)" must buffer partial lines instead of splitting each chunk independently;
add a string "buffer" before the loop, append each decoded chunk to buffer, then
extract only complete SSE lines (or complete "data: ..." entries) from buffer
for parsing and leave any trailing partial line in buffer for the next
iteration; update the parsing block that currently uses "const lines =
text.split('\n')" to consume from buffer and only process complete lines
(checking for "data: " and "[DONE]") while preserving remainder, and at the end
of the stream process any remaining buffered data into chunks.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/agent.py-163-165 (1)</summary><blockquote>

`163-165`: _⚠️ Potential issue_ | _🟡 Minor_

**Potential `IndexError` if agent returns empty messages.**

If `result["messages"]` is empty, accessing `[-1]` will raise an `IndexError`. Consider adding a guard.


<details>
<summary>🛡️ Proposed fix</summary>

```diff
         # Extract the final response
-        final_message = result["messages"][-1].content
-        logger.info(f"Response: {final_message[:200]}...")
+        messages = result.get("messages", [])
+        if not messages:
+            return {"error": "No response from agent"}
+        final_message = messages[-1].content
+        logger.info(f"Response: {final_message[:200] if final_message else ''}...")
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/agent.py`
around lines 163 - 165, The code blindly indexes result["messages"][-1] which
raises IndexError when messages is empty; update the logic in agent.py (the
block that assigns final_message and calls logger.info) to first get messages =
result.get("messages", []) and check if messages is non-empty before accessing
the last element, otherwise set a safe fallback (e.g., empty string or a "no
messages" note) and log that fallback via logger.info so the code won't crash
when the agent returns no messages.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/serverless.yml-37-49 (1)</summary><blockquote>

`37-49`: _⚠️ Potential issue_ | _🟡 Minor_

**Duplicate IAM action.**

`bedrock-agentcore:InvokeCodeInterpreter` is listed twice (lines 39 and 42). While IAM will deduplicate this, it adds unnecessary noise to the configuration.



<details>
<summary>Proposed fix</summary>

```diff
           - Effect: Allow
             Action:
               - bedrock-agentcore:InvokeCodeInterpreter
               - bedrock-agentcore:CreateCodeInterpreter
               - bedrock-agentcore:StartCodeInterpreterSession
-              - bedrock-agentcore:InvokeCodeInterpreter
               - bedrock-agentcore:StopCodeInterpreterSession
               - bedrock-agentcore:DeleteCodeInterpreter
               - bedrock-agentcore:ListCodeInterpreters
               - bedrock-agentcore:GetCodeInterpreter
               - bedrock-agentcore:GetCodeInterpreterSession
               - bedrock-agentcore:ListCodeInterpreterSessions
             Resource: !GetAtt PublicInterpreterCodeInterpreter.CodeInterpreterArn
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/serverless.yml`
around lines 37 - 49, Remove the duplicate IAM action from the policy Actions
list: locate the IAM policy block where the Action array includes multiple
bedrock-agentcore permissions (including bedrock-agentcore:InvokeCodeInterpreter
twice) and delete the redundant bedrock-agentcore:InvokeCodeInterpreter entry so
each action appears only once; ensure the Action list still contains the other
required permissions (CreateCodeInterpreter, StartCodeInterpreterSession,
StopCodeInterpreterSession, DeleteCodeInterpreter, ListCodeInterpreters,
GetCodeInterpreter, GetCodeInterpreterSession, ListCodeInterpreterSessions) and
leave the Resource reference PublicInterpreterCodeInterpreter.CodeInterpreterArn
unchanged.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md-62-68 (1)</summary><blockquote>

`62-68`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language identifier to fenced code block.**

The file structure diagram should have a language specified for the fenced code block, as flagged by markdownlint.


<details>
<summary>📝 Proposed fix</summary>

```diff
-```
+```text
 my-agent/
 ├── handler.py          # Entry point (artifact.entryPoint)
 ├── requirements.txt    # Dependencies
 ├── serverless.yml      # Configuration
 └── venv/              # Virtual environment (strongly recommended)
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md around
lines 62 - 68, Add a language identifier to the fenced code block that contains
the directory tree diagram so markdownlint stops flagging it; specifically
change the opening fence for the block that starts with "my-agent/" to include a
language (e.g., use "```text") so the tree diagram is annotated as plain text.


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md-72-84 (1)</summary><blockquote>

`72-84`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language identifier to fenced code block.**

The architecture diagram should have a language specified for the fenced code block.


<details>
<summary>📝 Proposed fix</summary>

```diff
-```
+```text
 dev/index.js (main)
 ├── Detects mode (Docker vs Code)
 ├── Manages AWS credentials
 ├── Handles file watching
 ├── Provides chat interface
 └── Delegates to:
     ├── Docker mode (inline in index.js)
     │   ├── DockerBuilder (builds image)
     │   └── DockerClient (runs container)
     └── Code mode (code-mode.js)
         └── Spawns Python process directly
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md around
lines 72 - 84, The README's architecture diagram fenced code block is missing a
language identifier; update the triple-backtick fence that contains the
"dev/index.js (main) ... Delegates to: ... code-mode.js" diagram by adding a
language tag (e.g., text) after the opening so the block becomestext;
this targets the fenced block showing dev/index.js, DockerBuilder, DockerClient
and code-mode.js in the README.


</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/runtime.md-1-1 (1)</summary><blockquote>

`1-1`: _⚠️ Potential issue_ | _🟡 Minor_

**Remove leading whitespace from the opening comment.**

The file starts with leading whitespace before the HTML comment, which may cause issues with some markdown parsers or the docs site processing.


<details>
<summary>📝 Proposed fix</summary>

```diff
-  <!--
+<!--
 title: Serverless Framework - AgentCore Runtime Configuration
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/agents/runtime.md` at line 1, The file begins
with leading whitespace before the HTML opening comment "<!--"; remove any
leading spaces or blank lines so the file starts directly with "<!--" (edit
docs/sf/providers/aws/guide/agents/runtime.md and delete the leading
whitespace/newline characters before the "<!--" token).
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/index.js-103-107 (1)</summary><blockquote>

`103-107`: _⚠️ Potential issue_ | _🟡 Minor_

**Minor typo in schema description.**

There's a trailing space before the closing parenthesis in the divisor description.


<details>
<summary>📝 Proposed fix</summary>

```diff
       b: z.number().describe('Divisor (number to divide by )'),
+      b: z.number().describe('Divisor (number to divide by)'),
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/index.js`
around lines 103 - 107, The schema object's field descriptions have a minor
formatting typo: remove the trailing space before the closing parenthesis in the
description for property b inside the schema (the z.object with properties a and
b) so "Divisor (number to divide by )" becomes "Divisor (number to divide by)";
update the description string for b accordingly.
```

</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/code-interpreter.md-219-229 (1)</summary><blockquote>

`219-229`: _⚠️ Potential issue_ | _🟡 Minor_

**Update Zod version to v4 to align with current ecosystem.**

The example specifies `"zod": "^3.23.0"`, but Zod 4 is now the current stable version (released July 2025, currently at v4.3.6). Since `npm i zod` now installs v4.x by default, update the example to `"zod": "^4.0.0"` to prevent version conflicts for users. The code shown uses only basic Zod features compatible with both versions, so no other changes are needed.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/agents/code-interpreter.md` around lines 219 -
229, Update the dependencies JSON to use Zod v4 by changing the "zod" dependency
value from "^3.23.0" to "^4.0.0" in the shown dependencies block (the "zod" key
in the JSON snippet) so the example reflects the current ecosystem and avoids
npm installing v4 by default.
```

</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/dev.md-51-64 (1)</summary><blockquote>

`51-64`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language identifiers to fenced code blocks (MD040).**

markdownlint flagged the untyped fences; adding a language keeps lint clean and improves rendering.


<details>
<summary>📚 Proposed fix</summary>

```diff
-```
+```text
 Dev mode running on http://localhost:8080
@@
-```
+```

-```
+```text
 serverless dev
@@
-```
+```

-```
+```http
 POST http://localhost:<port>/invocations
@@
-```
+```

-```
+```text
 my-agent/
@@
-```
+```
```
</details>


Also applies to: 82-100, 296-304, 363-369

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/sf/providers/aws/guide/agents/dev.md around lines 51 - 64, Add explicit
language identifiers to the untyped fenced code blocks in the referenced
markdown examples: mark the blocks that start with "Dev mode running on
http://localhost:8080" and "serverless dev" and "my-agent/" as text and mark the HTTP request block that begins with "POST http://localhost:<port>/invocations" as http; update all similar untyped
fences (also present around the other ranges mentioned) so markdownlint MD040 is
satisfied and rendering is improved.


</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/dev.md-286-286 (1)</summary><blockquote>

`286-286`: _⚠️ Potential issue_ | _🟡 Minor_

**Remove trailing space inside inline code span (MD038).**


<details>
<summary>✂️ Proposed fix</summary>

```diff
-- **Prompt**: Type messages at the `You: ` prompt
+- **Prompt**: Type messages at the `You:` prompt
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/agents/dev.md` at line 286, The inline code span
contains a trailing space ("`You: `") which violates MD038; edit the markdown so
the inline code has no trailing space by changing the inline code token from
`You: ` to `You:` in the sentence "**Prompt**: Type messages at the `You: `
prompt" to remove the trailing whitespace inside the code span.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/commands/info.js-39-76 (1)</summary><blockquote>

`39-76`: _⚠️ Potential issue_ | _🟡 Minor_

**Show gateway info when gateways exist without shared tools.**

`collectAllTools` exposes `hasGateways`, but `showInfo` only checks `hasTools`. This hides gateway info when users define `ai.gateways` with no shared tools.


<details>
<summary>🛠️ Proposed fix</summary>

```diff
-  const { hasTools } = collectAllTools(aiConfig)
-  if (hasTools) {
+  const { hasTools, hasGateways } = collectAllTools(aiConfig)
+  if (hasTools || hasGateways) {
     log.notice('Gateway:')
-    log.notice('  Auto-created gateway for tools')
+    log.notice(
+      hasTools
+        ? '  Auto-created gateway for tools'
+        : '  Gateway configuration detected',
+    )
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/commands/info.js`
around lines 39 - 76, The showInfo function currently only reads hasTools from
collectAllTools and thus skips printing gateway info when ai.gateways exist
without shared tools; update the destructuring from collectAllTools(aiConfig) to
also get hasGateways and change the condition that prints the gateway block to
check (hasTools || hasGateways) or specifically hasGateways where appropriate so
the gateway URL lookup (provider.request + getGatewayLogicalId()) runs when
gateways are defined even if hasTools is false.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/index.js-85-90 (1)</summary><blockquote>

`85-90`: _⚠️ Potential issue_ | _🟡 Minor_

**Prevent `stopSession` failures from masking the root error.**

If `startSession`/navigation fails, an exception in `stopSession` will hide the original error.


<details>
<summary>🛠️ Proposed fix</summary>

```diff
     } finally {
-      // Stop the session - triggers recording upload to S3
-      await browserClient.stopSession()
-      console.log(
-        'Browser session stopped - recording should be uploaded to S3',
-      )
+      try {
+        // Stop the session - triggers recording upload to S3
+        await browserClient.stopSession()
+        console.log(
+          'Browser session stopped - recording should be uploaded to S3',
+        )
+      } catch (stopErr) {
+        console.warn('Failed to stop browser session cleanly:', stopErr)
+      }
     }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/index.js`
around lines 85 - 90, The finally block currently awaits
browserClient.stopSession() which can throw and mask the original error from
startSession/navigation; wrap the stopSession call in its own try/catch inside
the finally (or capture the original error before finally and rethrow it after
catching stopSession errors) so any exception from browserClient.stopSession()
is logged or handled separately (e.g., processLogger.error or console.error with
context) and does not overwrite or suppress the original exception from
startSession/navigation; locate browserClient.stopSession() in the finally block
and implement the isolated try/catch and rethrow logic around it.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/test-invoke.js-69-94 (1)</summary><blockquote>

`69-94`: _⚠️ Potential issue_ | _🟡 Minor_

**Validate ARN presence for the requested agent type.**

If `AGENT_TYPE` is `public` or `private` but the matching ARN is unset, the script can print “All tests completed” without running any test.


<details>
<summary>🛠️ Proposed fix</summary>

```diff
 async function main() {
   console.log('LangGraph Multi-Gateway Agent Test Suite')
   console.log('='.repeat(50) + '\n')

+  if (AGENT_TYPE === 'public' && !PUBLIC_ARN) {
+    console.error('Error: PUBLIC_RUNTIME_ARN must be set when AGENT_TYPE=public.')
+    process.exit(1)
+  }
+  if (AGENT_TYPE === 'private' && !PRIVATE_ARN) {
+    console.error('Error: PRIVATE_RUNTIME_ARN must be set when AGENT_TYPE=private.')
+    process.exit(1)
+  }
+
   // Test public agent
   if ((AGENT_TYPE === 'both' || AGENT_TYPE === 'public') && PUBLIC_ARN) {
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/test-invoke.js`
around lines 69 - 94, The main function currently may skip running tests if
AGENT_TYPE requests a specific type but the matching ARN is missing; add
explicit validation at the start of main (or before invoking tests) that checks
AGENT_TYPE and the corresponding PUBLIC_ARN/PRIVATE_ARN values and fails fast
with a clear error and process.exit(1) if a required ARN is unset; reference
AGENT_TYPE, PUBLIC_ARN, PRIVATE_ARN, main and invokeAgent to locate where to add
the check and update the existing final conditional so it distinguishes between
"no ARNs at all" and "requested agent type missing its ARN".
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py-41-41 (1)</summary><blockquote>

`41-41`: _⚠️ Potential issue_ | _🟡 Minor_

**Remove unnecessary f-string prefix (Ruff F541).**

Line 41 uses an f-string without any variable interpolations (`{}`). The `f` prefix is unnecessary and should be removed:

```diff
-    print(f"🌐 Invoking LangGraph Browser Agent")
+    print("🌐 Invoking LangGraph Browser Agent")
```

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py`
at line 41, The print statement using an f-string in test-invoke.py (print(f"🌐
Invoking LangGraph Browser Agent")) has no interpolations; remove the
unnecessary f prefix so the statement becomes a regular string literal
(print("🌐 Invoking LangGraph Browser Agent")) to satisfy Ruff F541.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/codeInterpreter.js-55-70 (1)</summary><blockquote>

`55-70`: _⚠️ Potential issue_ | _🟡 Minor_

**Add default parameter `tags = {}` for safer defensive programming.**

The `Object.keys(tags)` call on line 69 should handle the edge case where `tags` is undefined. While the current codebase always provides `tags` via `mergeTags()`, adding a default parameter makes the function more robust to future changes and protects against accidental calls without the parameter.

<details>
<summary>Suggested fix</summary>

```diff
-export function compileCodeInterpreter(name, config, context, tags) {
+export function compileCodeInterpreter(name, config, context, tags = {}) {
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/codeInterpreter.js`
around lines 55 - 70, The function compileCodeInterpreter currently assumes tags
is defined and calls Object.keys(tags); update the function signature in
compileCodeInterpreter to accept a default parameter (tags = {}) so tags is
always an object, and leave the existing usage of Tags and Object.keys(tags)
intact; this change ensures resolveRole(config.role, roleLogicalId) and the
spread of ...(Object.keys(tags).length > 0 && { Tags: tags }) remain safe when
callers omit the tags argument.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/handlers/internal-lookup.js-46-68 (1)</summary><blockquote>

`46-68`: _⚠️ Potential issue_ | _🟡 Minor_

**Guard JSON parsing and normalize `userId` before `.toUpperCase()`.**

Lines 47 and 54: `JSON.parse` can throw on malformed JSON. Line 67: `userId.toUpperCase()` crashes if `userId` is a non-string truthy value (e.g., number). Add try-catch blocks around JSON.parse calls and coerce `userId` to a string before calling `.toUpperCase()`.

<details>
<summary>🛠️ Suggested guardrails</summary>

```diff
   if (typeof event === 'string') {
-    event = JSON.parse(event)
+    try {
+      event = JSON.parse(event)
+    } catch {
+      return {
+        statusCode: 400,
+        body: JSON.stringify({ error: 'Invalid JSON payload' }),
+      }
+    }
   }
 
   let userId = ''
 
   if (event.body) {
     const body =
-      typeof event.body === 'string' ? JSON.parse(event.body) : event.body
-    userId = body.userId || ''
+      typeof event.body === 'string' ? (() => {
+        try {
+          return JSON.parse(event.body)
+        } catch {
+          return {}
+        }
+      })() : event.body
+    userId = String(body.userId || '').trim() || ''
   } else {
     userId = event.userId || ''
   }
 
   if (!userId) {
     return {
       statusCode: 400,
       body: JSON.stringify({ error: 'Missing userId parameter' }),
     }
   }
 
-  const user = USERS[userId.toUpperCase()]
+  const user = USERS[String(userId).toUpperCase()]
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/handlers/internal-lookup.js`
around lines 46 - 68, Wrap both JSON.parse calls (parsing event and parsing
event.body) in try-catch blocks and return a 400 error if parsing fails to avoid
crashing on malformed JSON; ensure you validate event after parse. Normalize and
coerce userId to a string before calling .toUpperCase() (e.g., userId =
String(userId || '') ) and then check emptiness; finally use the coerced value
when looking up in USERS (USERS[userId.toUpperCase()]).
```

</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/browser.md-73-79 (1)</summary><blockquote>

`73-79`: _⚠️ Potential issue_ | _🟡 Minor_

**Add languages to the two fenced code blocks.**

Markdownlint flags both fences; specify a language (e.g., `text`) to fix MD040.

<details>
<summary>✏️ Suggested fixes</summary>

```diff
-```
+```text
 bedrock-agentcore>=0.1.0
 strands-agents>=1.0.0
 strands-agents-tools>=0.1.0
-```
+```
```

```diff
-```
+```text
 Agent → Browser Tool → AWS Browser Service → Website → Response
-```
+```
```
</details>



Also applies to: 92-94

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/sf/providers/aws/guide/agents/browser.md around lines 73 - 79, Add a
language identifier (e.g., "text") to the two fenced code blocks shown in the
diff so Markdownlint MD040 is satisfied: update the dependencies block
containing "bedrock-agentcore>=0.1.0 / strands-agents>=1.0.0 /
strands-agents-tools>=0.1.0" and the flow block containing "Agent → Browser Tool
→ AWS Browser Service → Website → Response" to use triple backticks with a
language (e.g., ```text) instead of plain fences; ensure the same change is
applied to the later identical block at lines 92-94.


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/test-invoke.py-47-49 (1)</summary><blockquote>

`47-49`: _⚠️ Potential issue_ | _🟡 Minor_

**Remove the unnecessary f-string prefix on line 48.**

Line 48 contains an f-string without any placeholders, which violates Ruff rule F541. The string "Invoking Custom Code Interpreter Agent" has no variable substitutions, so the `f` prefix is unnecessary.

<details>
<summary>✏️ Suggested fix</summary>

```diff
-    print(f"Invoking Custom Code Interpreter Agent")
+    print("Invoking Custom Code Interpreter Agent")
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/test-invoke.py`
around lines 47 - 49, The second print statement uses an unnecessary f-string
(print(f"Invoking Custom Code Interpreter Agent")) which triggers Ruff F541;
change that print call to a plain string literal (print("Invoking Custom Code
Interpreter Agent")) so no f-prefix is used while leaving the surrounding prints
(e.g., print(f"\n{'='*60}") and print(f"Runtime ARN: {RUNTIME_ARN}")) unchanged.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/agent.py-33-36 (1)</summary><blockquote>

`33-36`: _⚠️ Potential issue_ | _🟡 Minor_

**Timezone argument isn’t applied**

`get_current_time` returns local time and only appends the timezone string, which can mislead tool users. Either convert using `zoneinfo` or drop the parameter.  


<details>
<summary>🕒 Suggested fix (use zoneinfo)</summary>

```diff
-from datetime import datetime
+from datetime import datetime
+from zoneinfo import ZoneInfo
@@
 `@tool`
 def get_current_time(timezone: str = "UTC") -> str:
-    """Get the current date and time."""
-    return f"Current time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {timezone}"
+    """Get the current date and time."""
+    try:
+        tz = ZoneInfo(timezone)
+    except Exception:
+        tz = ZoneInfo("UTC")
+        timezone = "UTC"
+    return f"Current time: {datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')} {timezone}"
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/agent.py`
around lines 33 - 36, The get_current_time tool currently ignores the timezone
argument and just appends the string; update get_current_time to actually apply
the timezone using zoneinfo: import zoneinfo.ZoneInfo and call
datetime.now(tz=ZoneInfo(timezone)) (or handle invalid timezone by falling back
to UTC or raising a ValueError) so the returned timestamp reflects the requested
timezone; alternatively, if you prefer not to support timezones, remove the
timezone parameter from get_current_time and its docstring to avoid misleading
callers.
```

</details>

</blockquote></details>

</blockquote></details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fbac021178

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🟡 Minor comments (41)
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/serverless.yml-37-49 (1)

37-49: ⚠️ Potential issue | 🟡 Minor

Duplicate IAM action: InvokeCodeInterpreter appears twice.

The action bedrock-agentcore:InvokeCodeInterpreter is listed on both line 39 and line 42. Remove the duplicate entry.

🧹 Proposed fix
         statements:
           - Effect: Allow
             Action:
               - bedrock-agentcore:InvokeCodeInterpreter
               - bedrock-agentcore:CreateCodeInterpreter
               - bedrock-agentcore:StartCodeInterpreterSession
-              - bedrock-agentcore:InvokeCodeInterpreter
               - bedrock-agentcore:StopCodeInterpreterSession
               - bedrock-agentcore:DeleteCodeInterpreter
               - bedrock-agentcore:ListCodeInterpreters
               - bedrock-agentcore:GetCodeInterpreter
               - bedrock-agentcore:GetCodeInterpreterSession
               - bedrock-agentcore:ListCodeInterpreterSessions
             Resource: !GetAtt PublicInterpreterCodeInterpreter.CodeInterpreterArn
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/serverless.yml`
around lines 37 - 49, In the IAM policy actions list for the resource referenced
by PublicInterpreterCodeInterpreter.CodeInterpreterArn, remove the duplicate
"bedrock-agentcore:InvokeCodeInterpreter" entry so each action appears only once
(ensure the Actions array contains a single instance of InvokeCodeInterpreter
alongside the other bedrock-agentcore actions like CreateCodeInterpreter,
StartCodeInterpreterSession, StopCodeInterpreterSession, DeleteCodeInterpreter,
ListCodeInterpreters, GetCodeInterpreter, GetCodeInterpreterSession, and
ListCodeInterpreterSessions).
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/pyproject.toml-8-8 (1)

8-8: ⚠️ Potential issue | 🟡 Minor

Lower requires-python to >=3.10.

The dependencies (bedrock-agentcore>=0.1.0, langchain>=0.3.0, langchain-aws>=0.2.0, langgraph>=0.2.0) require a minimum of Python 3.10, not 3.12. The current requirement unnecessarily excludes Python 3.10 and 3.11 users.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/pyproject.toml`
at line 8, The pyproject.toml currently sets requires-python = ">=3.12" which
unnecessarily excludes Python 3.10/3.11 users; change the requires-python
declaration to ">=3.10" so the project supports the minimum Python version
required by the dependencies (refer to the requires-python entry in the
pyproject.toml).
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/test-invoke.js-76-94 (1)

76-94: ⚠️ Potential issue | 🟡 Minor

Update MCP protocol version to the latest specification.

The protocol version '2025-06-18' is outdated. Update to '2025-11-25', which is the current MCP specification and includes important updates such as OIDC Discovery support, JSON Schema 2020-12 as the default dialect, and experimental tasks support.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/test-invoke.js`
around lines 76 - 94, The testInitialize function sends an outdated MCP
protocolVersion; update the string passed in the invoke call (inside
testInitialize) from '2025-06-18' to the current '2025-11-25' so the
invoke('initialize', { protocolVersion: ... }, 1) uses the latest MCP spec
(retain clientInfo and capabilities as-is).
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/README.md-24-32 (1)

24-32: ⚠️ Potential issue | 🟡 Minor

Add language identifiers to fenced code blocks.

Markdownlint (MD040) will flag the unlabeled fences (e.g., Line 24, Line 65, Line 87). Prefer text for outputs/trees.

📝 Suggested fix
-```
+```text
 langgraph-browser-custom/
 ├── serverless.yml      # Defines custom browser + S3 bucket + runtime
 ├── agent.py            # LangGraph agent using custom browser
 ├── test-invoke.py      # Validation test (checks S3 recordings)
 ├── Dockerfile          # Container with Playwright
 ├── pyproject.toml      # Python dependencies
 └── README.md           # This file

- +text
ai:
agents:
browserAgent: https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/xxx/invocations

browsers:
customBrowser: custom-browser-id-xxx


-```
+```text
LangGraph Custom Browser Agent - Validation Test
Recordings Bucket: langgraph-browser-custom-recordings-dev
Region: us-east-1

============================================================
CUSTOM BROWSER VALIDATION TEST
============================================================

[Step 1] Counting existing recordings in S3...
Initial recording count: 0

[Step 2] Invoking agent to browse example.com...
Agent response:
----------------------------------------
Page Title: Example Domain
Content: Example Domain
This domain is for use in illustrative examples...
----------------------------------------

Browser ID used: custom-browser-id-xxx

[Step 3] Waiting for recording to be uploaded to S3...
  Checking... (5s) - Recording count: 0
  Checking... (10s) - Recording count: 1

[Step 4] Validation Results
========================================
SUCCESS: New recording detected in S3!
  Initial count: 0
  Final count: 1
  New recordings: 1

Latest recordings:
  - browser-sessions/session-xxx/batch_1.ndjson.gz
    Size: 12345 bytes
    Modified: 2025-01-30 12:00:00

============================================================
VALIDATION PASSED
The custom browser with session recording is working correctly!
============================================================

</details>


Also applies to: 65-129

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In
@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/README.md
around lines 24 - 32, The README.md contains unlabeled fenced code blocks that
trigger Markdownlint MD040; update each unlabeled triple-backtick block (the
directory tree block, the ai/browsers YAML snippet, and the validation test
output block) to include a language identifier, e.g., change totext (or

unlabeled fences are annotated so Markdownlint no longer flags them.
docs/sf/providers/aws/guide/agents/gateway.md-78-80 (1)

78-80: ⚠️ Potential issue | 🟡 Minor

Add a language to the diagram code fence.

Markdownlint (MD040) flags the unlabeled fence at Line 78.

📝 Suggested fix
-```
+```text
 Agent → Gateway (MCP) → Target (Lambda / API / MCP Server) → Response

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/sf/providers/aws/guide/agents/gateway.md around lines 78 - 80, The
fenced code block containing "Agent → Gateway (MCP) → Target (Lambda / API / MCP
Server) → Response" is missing a language label which triggers markdownlint
MD040; update the fence in docs/sf/providers/aws/guide/agents/gateway.md to use
a labeled code fence (e.g., add "text" after the opening backticks) so the block
becomes text ... to satisfy the linter while preserving the diagram
content.


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/agent.js-138-140 (1)</summary><blockquote>

`138-140`: _⚠️ Potential issue_ | _🟡 Minor_

**Add defensive check for empty messages array.**

If `agent.invoke()` returns an empty `messages` array, accessing `result.messages[result.messages.length - 1]` will return `undefined`, and then `.content` will throw a TypeError.



<details>
<summary>🛡️ Proposed fix</summary>

```diff
       // Extract the final message from the graph result
       const finalMessage = result.messages[result.messages.length - 1]
-      const response = finalMessage.content
+      const response = finalMessage?.content || 'No response generated'
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/agent.js`
around lines 138 - 140, The code assumes result.messages always has at least one
entry; add a defensive check after agent.invoke() to handle an empty messages
array by verifying result.messages && result.messages.length > 0 before
accessing result.messages[result.messages.length - 1]; if empty, return or throw
a clear error (or set response to a safe default) instead of dereferencing
undefined; update the logic around finalMessage and response to use this guard
so agent.invoke() failures or empty results don't cause a TypeError.
```

</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/dev.md-51-65 (1)</summary><blockquote>

`51-65`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language identifiers to fenced code blocks.**

markdownlint flags these blocks without a language spec. Adding one improves consistency and rendering.  


<details>
<summary>✍️ Suggested updates</summary>

```diff
-```
+```text
 Dev mode running on http://localhost:8080
@@
-```
+```text
 serverless dev
@@
-```
+```http
 POST http://localhost:<port>/invocations
@@
-```
+```text
 my-agent/
 ├── agent.py              # Entry point (handler)
```
</details>


Also applies to: 82-100, 296-303, 363-369

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/agents/dev.md` around lines 51 - 65, Update the
Markdown fenced code blocks in docs/sf/providers/aws/guide/agents/dev.md to
include language identifiers so markdownlint passes and rendering is consistent:
add "text" to runtime/plain output blocks (e.g., the "Dev mode running on
http://localhost:8080" and "serverless dev" snippets and the directory tree that
includes "agent.py"), add "http" to the HTTP request block (the "POST
http://localhost:<port>/invocations" snippet), and similarly annotate the other
untagged fenced blocks mentioned (lines around 82-100, 296-303, 363-369) with
the appropriate language identifiers.
```

</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/dev.md-286-289 (1)</summary><blockquote>

`286-289`: _⚠️ Potential issue_ | _🟡 Minor_

**Remove trailing space inside the inline code span.**

The code span `You: ` contains a trailing space, which markdownlint flags.  


<details>
<summary>✍️ Suggested tweak</summary>

```diff
-- **Prompt**: Type messages at the `You: ` prompt
+- **Prompt**: Type messages at the `You:` prompt
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/agents/dev.md` around lines 286 - 289, The inline
code span `You: ` in the "Prompt" bullet contains a trailing space; edit the
markdown so the code span reads `You:` (remove the trailing space) to satisfy
markdownlint — locate the bullet with "- **Prompt**: Type messages at the `You:
` prompt" and update the backticked content to `You:`.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md-62-84 (1)</summary><blockquote>

`62-84`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language identifiers to fenced code blocks.**

markdownlint flags the file-structure and architecture blocks as missing a language.  


<details>
<summary>✍️ Suggested update</summary>

```diff
-```
+```text
 my-agent/
 ├── handler.py          # Entry point (artifact.entryPoint)
@@
-```
+```text
 dev/index.js (main)
 ├── Detects mode (Docker vs Code)
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md around
lines 62 - 84, Update the README's fenced code blocks to include a language
identifier (e.g., use text) for the file-structure block and the Architecture diagram block so markdownlint stops flagging them; locate the two triple-backtick blocks around the "my-agent/" tree and the "dev/index.js (main)" architecture list and change the opening fences to include the language specifier (e.g., text) while leaving the block contents unchanged.


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/handlers/calculator.js-53-77 (1)</summary><blockquote>

`53-77`: _⚠️ Potential issue_ | _🟡 Minor_

**Tighten numeric parsing to avoid malformed inputs.**

Line 54 currently accepts strings like `1..2` or `.`; `parseFloat` will coerce/truncate, which can yield surprising results. Consider a stricter numeric pattern and a finite check.  


<details>
<summary>✅ Suggested fix (stricter numeric validation)</summary>

```diff
 function safeCalculate(expression) {
-  const match = expression.match(/^\s*([\d.]+)\s*([+\-*/])\s*([\d.]+)\s*$/)
+  const match = expression.match(
+    /^\s*(-?(?:\d+|\d*\.\d+))\s*([+\-*/])\s*(-?(?:\d+|\d*\.\d+))\s*$/,
+  )
   if (!match) {
     throw new Error(
       'Use format: "number operator number" (e.g., "2 + 3", "10 / 5")',
     )
   }

   const [, a, op, b] = match
   const left = parseFloat(a)
   const right = parseFloat(b)
+  if (!Number.isFinite(left) || !Number.isFinite(right)) {
+    throw new Error('Invalid number input')
+  }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/handlers/calculator.js`
around lines 53 - 77, The safeCalculate function currently allows malformed
numeric strings (e.g., "1..2", ".") because parseFloat coerces/truncates; update
the regex used in safeCalculate to a stricter numeric pattern (e.g.,
([+-]?(?:\d+\.?\d*|\.\d+))) for both operands so only well-formed
integers/floats match, then parse with Number (or parseFloat) and validate with
Number.isFinite on left and right (reject by throwing the existing format error
or a new descriptive error) before performing operations; keep the existing
operator switch and division-by-zero check in place.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/README.md-97-104 (1)</summary><blockquote>

`97-104`: _⚠️ Potential issue_ | _🟡 Minor_

**Add a language tag to the fenced block.**

Markdownlint flags the project-structure fence without a language specifier. Consider `text` for clarity.  


<details>
<summary>✏️ Suggested fix</summary>

```diff
-```
+```text
 langgraph-streaming/
 ├── serverless.yml    # Serverless Framework configuration
 ├── index.js          # LangGraph JS agent with streaming
 ├── package.json      # npm dependencies
 ├── test-invoke.js    # Test script for streaming invocation
 └── README.md         # This file
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In
@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/README.md
around lines 97 - 104, Update the fenced code block in README.md that shows the
project structure (the block starting with and the tree listing under "langgraph-streaming/") to include a language tag (e.g., text) after the opening backticks so markdownlint stops flagging it; find the project-structure fence in the README.md and change the opening fence from to ```text to explicitly
mark the block as plain text.


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/test-invoke.py-47-49 (1)</summary><blockquote>

`47-49`: _⚠️ Potential issue_ | _🟡 Minor_

**Remove the unused f-string prefix.**

Line 48 uses an f-string without placeholders.  


<details>
<summary>✏️ Suggested fix</summary>

```diff
-    print(f"Invoking Custom Code Interpreter Agent")
+    print("Invoking Custom Code Interpreter Agent")
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/test-invoke.py`
around lines 47 - 49, The print statement using an unnecessary f-string should
be changed to a regular string: in the example script replace the print call
printing "Invoking Custom Code Interpreter Agent" (currently written as
print(f"Invoking Custom Code Interpreter Agent")) with print("Invoking Custom
Code Interpreter Agent") to remove the unused f-string prefix while leaving the
other prints (e.g., the one referencing RUNTIME_ARN) unchanged.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter/test-invoke.py-45-47 (1)</summary><blockquote>

`45-47`: _⚠️ Potential issue_ | _🟡 Minor_

**Remove the unused f-string prefix.**

Line 46 is an f-string without placeholders.  


<details>
<summary>✏️ Suggested fix</summary>

```diff
-    print(f"Invoking Code Interpreter Agent")
+    print("Invoking Code Interpreter Agent")
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter/test-invoke.py`
around lines 45 - 47, Remove the unnecessary f-string prefix from the plain
string print statement that logs "Invoking Code Interpreter Agent" (the print
call shown between the separators and the Runtime ARN print); change
print(f"Invoking Code Interpreter Agent") to print("Invoking Code Interpreter
Agent") so it no longer uses an f-string with no placeholders.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/README.md-17-27 (1)</summary><blockquote>

`17-27`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language identifiers to fenced code blocks.**  
Keeps markdown lint clean and improves rendering consistency.  

<details>
<summary>✏️ Suggested edit</summary>

```diff
-```
+```text
 User Request → AgentCore Runtime → agent_invocation()
                                       ↓
                                    LangGraph
                                       ↓
                                Claude Sonnet 4.5
                                       ↓
                           (uses built-in tools)
                                       ↓
                                    Response
-```
+```

...

-```
+```text
 START → chatbot → [decide: use tool or respond]
            ↑            ↓
            └─── tools ←┘
-```
+```
```
</details>


Also applies to: 108-112

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In
@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/README.md
around lines 17 - 27, Add language identifiers to the fenced code blocks
containing the ASCII diagrams so markdown lint passes and rendering is
consistent: locate the fenced block that begins with "User Request → AgentCore
Runtime → agent_invocation()" and the block that begins with "START → chatbot →
[decide: use tool or respond]" in the README and change their opening fences
from totext (and ensure any other similar ASCII diagram blocks, e.g.,
the one referenced around lines 108-112, are updated the same way).


</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/runtime.md-301-305 (1)</summary><blockquote>

`301-305`: _⚠️ Potential issue_ | _🟡 Minor_

**Hyphenate the compound adjective.**  
"General-purpose" reads better here.  

<details>
<summary>✏️ Suggested edit</summary>

```diff
-| `HTTP`   | Standard HTTP requests (default) | General purpose agents, REST-like interactions |
+| `HTTP`   | Standard HTTP requests (default) | General-purpose agents, REST-like interactions |
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/agents/runtime.md` around lines 301 - 305, Update
the table row for the `HTTP` protocol in the runtime.md content: change the
Description cell text from "General purpose agents, REST-like interactions" to
"General-purpose agents, REST-like interactions" so the compound adjective is
hyphenated; locate the `HTTP` table row in the markdown containing the
Protocol/Description/Use Case columns and edit the phrase accordingly.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js-913-924 (1)</summary><blockquote>

`913-924`: _⚠️ Potential issue_ | _🟡 Minor_

**Signal handlers registered without removal on stop.**

The `SIGINT` and `SIGTERM` handlers are registered at Lines 923-924 but never removed when `stop()` is called. If `start()` is called again (e.g., in tests or programmatic usage), duplicate handlers will accumulate.


<details>
<summary>🛠️ Proposed fix</summary>

Store the handler reference and remove it in `stop()`:

```javascript
// In constructor or as class field
`#signalHandler` = null

// In `#startChat`()
this.#signalHandler = () => { /* ... */ }
process.on('SIGINT', this.#signalHandler)
process.on('SIGTERM', this.#signalHandler)

// In stop()
if (this.#signalHandler) {
  process.off('SIGINT', this.#signalHandler)
  process.off('SIGTERM', this.#signalHandler)
  this.#signalHandler = null
}
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js` around
lines 913 - 924, The SIGINT/SIGTERM handlers added in the start logic are never
removed, causing duplicate handlers on repeated start() calls; capture the
handler function reference (e.g., store it as this.#signalHandler when creating
the signalHandler in the start code where this.#isShuttingDown and
this.#readline are used) and then remove it inside stop() by calling
process.off('SIGINT', this.#signalHandler) and process.off('SIGTERM',
this.#signalHandler), finally nulling this.#signalHandler to avoid re-use.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/commands/info.js-66-68 (1)</summary><blockquote>

`66-68`: _⚠️ Potential issue_ | _🟡 Minor_

**Gateway lookup may not find the correct output key.**

Line 67 calls `getGatewayLogicalId()` without arguments, which returns `'AgentCoreGateway'` (per the naming.js snippet). However, if the gateway was created with a specific name, the output key would be different (e.g., `AgentCoreGatewayMyGatewayUrl`).

Consider iterating through stack outputs to find any gateway URL outputs, or pass the gateway name if available.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/commands/info.js`
around lines 66 - 68, The lookup for the gateway URL using getGatewayLogicalId()
may miss outputs when a named gateway exists; update the code that sets
urlOutput (which currently calls getGatewayLogicalId() with no args) to either
pass the gateway name into getGatewayLogicalId() when available (so the expected
OutputKey like `${getGatewayLogicalId(gatewayName)}Url` is matched) or, if no
name is provided, scan stack?.Outputs for any OutputKey that matches a gateway
URL pattern (e.g., endsWith('GatewayUrl') or matches /AgentCoreGateway.*Url/)
and pick the first matching output; adjust the logic around urlOutput to use
this fallback search so named gateways are handled.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js-574-584 (1)</summary><blockquote>

`574-584`: _⚠️ Potential issue_ | _🟡 Minor_

**Process log listeners attached without cleanup tracking.**

`#streamProcessLogs()` attaches `data` event listeners to `process.stdout` and `process.stderr`, but these listeners are not removed during `stop()` or when the process restarts during a rebuild (Line 808). This could lead to duplicate listeners if `#streamProcessLogs()` is called multiple times.


<details>
<summary>🛠️ Proposed approach</summary>

Consider storing listener references and removing them before reattaching, or use `once` if appropriate for the use case.
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js` around
lines 574 - 584, `#streamProcessLogs` currently attaches persistent 'data'
listeners to the process returned by `#codeMode.getProcess`() that are never
removed, causing duplicate logs on restart; update this by capturing the
listener functions when attaching (e.g., const stdoutListener = (d) =>
this.#displayLog(d.toString()) and stderrListener similarly) and store them on
the instance, then remove them with process.stdout.off('data', stdoutListener)
and process.stderr.off('data', stderrListener) either at the start of
`#streamProcessLogs` (before reattaching) or in stop(); alternatively if
appropriate use once instead of on; ensure references match the stored listener
properties so `#displayLog` invocations stop when the process is stopped or
rebuilt.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js-248-266 (1)</summary><blockquote>

`248-266`: _⚠️ Potential issue_ | _🟡 Minor_

**Python version check could fail silently on version format mismatch.**

The version check at Line 256 uses `includes()` which may produce false positives. For example, if expected is "3.1" and installed is "Python 3.13.1", it would incorrectly pass. Consider using a more precise version comparison.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`
around lines 248 - 266, The current `#checkPythonVersion` uses includes() which
can falsely match (e.g., "3.1" matching "3.13.1"); update the logic in async
`#checkPythonVersion` to parse numeric versions from stdout and expectedRuntime
and perform a proper numeric comparison: extract the installed version from
stdout (e.g., via regex on installedVersion to capture major.minor[.patch]),
derive expectedVersion similarly from expectedRuntime (remove "PYTHON_" and
convert underscores to dots), split both into numeric segments (major, minor,
optional patch), compare major and minor as integers (and patch if present)
instead of using includes(), and keep the existing logging behavior (use
logger.warning on mismatch and logger.debug on error). Ensure you reference
pythonCmd, execP, installedVersion, expectedVersion, and logger when making the
change.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js-650-653 (1)</summary><blockquote>

`650-653`: _⚠️ Potential issue_ | _🟡 Minor_

**Terminal operations may fail in non-TTY environments.**

Lines 651-652 call `process.stdout.clearLine(0)` and `process.stdout.cursorTo(0)` without checking if stdout is a TTY. These methods may not exist or may throw in non-TTY environments (e.g., CI pipelines, piped output).


<details>
<summary>🛠️ Proposed fix</summary>

```diff
     if (this.#readline) {
+      if (process.stdout.isTTY) {
         process.stdout.clearLine(0)
         process.stdout.cursorTo(0)
+      }
     }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js` around
lines 650 - 653, The terminal-clearing calls inside the block guarded by
this.#readline can throw in non-TTY environments; update the block that contains
process.stdout.clearLine and process.stdout.cursorTo (the section referencing
this.#readline) to first verify stdout is a TTY and that the methods exist
(e.g., check process.stdout && process.stdout.isTTY and typeof
process.stdout.clearLine === 'function' and typeof process.stdout.cursorTo ===
'function') before invoking them, otherwise skip those calls so the code safely
runs in CI/piped/non-TTY environments.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js-72-72 (1)</summary><blockquote>

`72-72`: _⚠️ Potential issue_ | _🟡 Minor_

**Potential error if `tags` is undefined.**

Line 72 calls `Object.keys(tags)` but if `tags` is `undefined` or `null`, this will throw a TypeError. Consider adding a defensive check.


<details>
<summary>🛠️ Proposed fix</summary>

```diff
-      ...(Object.keys(tags).length > 0 && { Tags: tags }),
+      ...(tags && Object.keys(tags).length > 0 && { Tags: tags }),
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js` at
line 72, The spread expression uses Object.keys(tags) which will throw if tags
is null/undefined; update the condition to defensively handle missing tags
(e.g., use tags && Object.keys(tags).length > 0 or Object.keys(tags ||
{}).length > 0) so the spread only adds { Tags: tags } when tags is a defined
non-empty object; modify the expression in memory.js (the object construction
that currently uses ...(Object.keys(tags).length > 0 && { Tags: tags })) to use
the safe check (tags && Object.keys(tags).length > 0 ? { Tags: tags } : {}).
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js-207-216 (1)</summary><blockquote>

`207-216`: _⚠️ Potential issue_ | _🟡 Minor_

**Error handling condition may not correctly identify ServerlessError.**

The condition at Line 211-214 checks `error.code !== 'ENOENT'` but `ServerlessError` uses a custom `code` property (e.g., `'MISSING_LOCKFILE'`), not the Node.js `ENOENT` code. This means the ServerlessError will be re-thrown correctly, but the logic is not immediately clear.

Additionally, checking `error.message.includes('Missing lockfile')` is fragile if the error message changes.


<details>
<summary>🛠️ Proposed fix for clearer error handling</summary>

```diff
       } catch (error) {
         // Ignore if package.json missing (not a Node.js project)
         // Re-throw if it's our validation error
-        if (
-          error.code !== 'ENOENT' ||
-          error.message.includes('Missing lockfile')
-        ) {
+        if (error instanceof ServerlessError || error.code !== 'ENOENT') {
           throw error
         }
       }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js`
around lines 207 - 216, The catch block in builder.js is using error.code !==
'ENOENT' and message.includes('Missing lockfile'), which is fragile and doesn't
clearly detect the ServerlessError for a missing lockfile; update the handler in
the catch to explicitly detect the ServerlessError by checking the
ServerlessError type or its canonical code (e.g., compare error.name or
error.code to the known ServerlessError identifier like 'MISSING_LOCKFILE' or
use instanceof ServerlessError if available) and only re-throw for that case,
while treating genuine ENOENT file-not-found errors as ignored; reference the
existing catch block around the package.json/lockfile read logic and use the
same ServerlessError symbol (or its code) instead of message.includes to make
the intent explicit.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/coordinator.js-99-125 (1)</summary><blockquote>

`99-125`: _⚠️ Potential issue_ | _🟡 Minor_

**String `imageConfig` handling may skip builds unexpectedly.**

At Lines 101-105, if `imageConfig` is a string reference to `provider.ecr.images` but that image wasn't built (not in `builtImages`), the code continues to Line 108-109. However, `{ name: imageConfig }` creates an object without `path`, `repository`, or `file`, so the condition at Line 111 fails and the build is silently skipped.

This could leave users confused when their string-referenced images aren't built.


<details>
<summary>🛠️ Proposed fix to handle missing string references</summary>

```diff
     // Handle string reference to provider.ecr.images
     if (typeof imageConfig === 'string') {
       if (builtImages[imageConfig]) {
         continue // Already built above
       }
+      // String reference not found in builtImages - this is an error
+      log.warning(
+        `Image reference '${imageConfig}' not found in provider.ecr.images or builtImages`,
+      )
+      continue
     }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/coordinator.js`
around lines 99 - 125, The loop over runtimesToBuild currently treats a string
imageConfig as a reference but then silently skips builds because { name:
imageConfig } lacks path/repository/file; update the handling of imageConfig in
the for-loop so that when imageConfig is a string and not already in builtImages
you resolve that string into the real image config (e.g., look up
provider.ecr.images[imageConfig] or similar) and assign that to dockerConfig
before checking dockerConfig.path/repository/file; if the lookup fails, make the
code surface an explicit error/log and throw or skip with a clear message;
adjust references to runtimesToBuild, imageConfig, builtImages, dockerConfig,
builder.buildForRuntime, and buildMetadata accordingly.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js-230-242 (1)</summary><blockquote>

`230-242`: _⚠️ Potential issue_ | _🟡 Minor_

**Global `process.env.PATH` mutation persists beyond this instance.**

`#setupVirtualEnv()` mutates the global `process.env.PATH`, which affects the entire Node.js process and persists even after `stop()` is called. This could cause unintended side effects if multiple `AgentCoreCodeMode` instances are created or if other parts of the application rely on the original PATH.

Consider storing the modified PATH locally and passing it only to the spawned process environment instead of modifying the global state.


<details>
<summary>🛠️ Proposed fix</summary>

```diff
   `#setupVirtualEnv`() {
     if (!process.env.VIRTUAL_ENV) {
       return
     }

     const runtimeDir = os.platform() === 'win32' ? 'Scripts' : 'bin'
     const venvBinPath = path.join(process.env.VIRTUAL_ENV, runtimeDir)

-    // Prepend venv bin to PATH
-    process.env.PATH = [venvBinPath, path.delimiter, process.env.PATH].join('')
+    // Return modified PATH for use in spawned process
+    return [venvBinPath, process.env.PATH].join(path.delimiter)
+  }
+
+  `#getModifiedPath`() {
+    if (!process.env.VIRTUAL_ENV) {
+      return process.env.PATH
+    }
+
+    const runtimeDir = os.platform() === 'win32' ? 'Scripts' : 'bin'
+    const venvBinPath = path.join(process.env.VIRTUAL_ENV, runtimeDir)
+    return [venvBinPath, process.env.PATH].join(path.delimiter)
-
-    logger.debug(`Using virtual environment: ${process.env.VIRTUAL_ENV}`)
   }
```

Then use `this.#getModifiedPath()` when building `pythonEnv.PATH` in `start()`.
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`
around lines 230 - 242, Currently `#setupVirtualEnv` mutates global
process.env.PATH; instead stop changing process.env and keep the modified PATH
on the instance (e.g., store it as this._venvPath or implement a private getter
`#getModifiedPath`() that computes the venv bin path without mutating globals).
Update start() to use the instance-modified value when constructing
pythonEnv.PATH (use this.#getModifiedPath() or this._venvPath) and remove any
assignment to process.env.PATH in `#setupVirtualEnv` so no global state is
changed; reference the AgentCoreCodeMode class, `#setupVirtualEnv`, start(), and
pythonEnv.PATH when making these changes.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter/README.md-14-22 (1)</summary><blockquote>

`14-22`: _⚠️ Potential issue_ | _🟡 Minor_

**Specify languages for the fenced blocks.**

Both code fences are missing language identifiers (markdownlint MD040).
<details>
<summary>✅ Suggested fix</summary>

```diff
-```
+```text
 langgraph-code-interpreter/
 ├── serverless.yml     # Serverless Framework configuration
 ├── agent.py           # LangGraph agent with code interpreter
 ├── Dockerfile         # Container definition
 ├── pyproject.toml     # Python dependencies
 ├── test-invoke.py     # Validation script
 └── README.md          # This file
 ```
@@
-```
+```yaml
 ai:
   agents:
     codeAgent: https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/.../invocations
 ```
```
</details>



Also applies to: 41-45

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In
@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter/README.md
around lines 14 - 22, The README.md has two fenced code blocks missing language
identifiers (markdownlint MD040) — update the first tree listing block in
langgraph-code-interpreter/ to use a text fence (e.g., change totext)
and update the YAML example block (around the ai: agents: codeAgent snippet and
the block at lines ~41-45) to use a yaml fence (change toyaml); edit the
README.md file to add these language tags so the tree and YAML blocks are
explicitly marked as text and yaml respectively.


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/README.md-31-35 (1)</summary><blockquote>

`31-35`: _⚠️ Potential issue_ | _🟡 Minor_

**Align the Node.js prerequisite with the package.json engine constraint.**

README says “Node.js 20+” but `package.json` pins `node: 24.x`. Please align one side to avoid confusion.
<details>
<summary>🛠️ Example (update README to match engines)</summary>

```diff
-- Node.js 20+
+- Node.js 24+
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/README.md`
around lines 31 - 35, The README's prerequisite "Node.js 20+" conflicts with
package.json's engines constraint ("node": "24.x"); update the README in
langgraph-basic/README.md to state the same Node.js requirement as package.json
(Node.js 24.x) so both documents match, or alternatively relax package.json
engines to allow 20+—ensure you reference the README entry and the package.json
engines/node field (node: 24.x) and keep both consistent.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/README.md-63-69 (1)</summary><blockquote>

`63-69`: _⚠️ Potential issue_ | _🟡 Minor_

**Add a language identifier to the project-structure code fence.**

This block is missing a fenced-code language (markdownlint MD040).
<details>
<summary>✅ Suggested fix</summary>

```diff
-```
+```text
 langgraph-basic/
 ├── serverless.yml    # Serverless Framework configuration
 ├── index.js          # LangGraph JS agent with tools
 ├── package.json      # npm dependencies
 └── README.md         # This file
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In
@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/README.md
around lines 63 - 69, The README.md code fence for the project structure is
missing a language identifier; update the triple-backtick fence that surrounds
the "langgraph-basic/ ├── serverless.yml ..." block to include a language
identifier such as "text" (e.g., change totext) so markdownlint MD040 is
satisfied and rendering is explicit; locate the fenced block in README.md that
lists the project structure and add the identifier directly after the opening
backticks.


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/handlers/calculator.js-13-24 (1)</summary><blockquote>

`13-24`: _⚠️ Potential issue_ | _🟡 Minor_

**Guard against NaN from malformed numeric tokens in regex matches.**

The regex pattern `[\d.]+` matches tokens like `.` or `...` which parse to `NaN` and silently propagate through calculations. Add validation after parsing:

<details>
<summary>🧮 Suggested guard against NaN</summary>

```diff
   const [, a, op, b] = match
-  const left = parseFloat(a)
-  const right = parseFloat(b)
+  const left = Number(a)
+  const right = Number(b)
+  if (!Number.isFinite(left) || !Number.isFinite(right)) {
+    throw new Error('Invalid number')
+  }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/handlers/calculator.js`
around lines 13 - 24, In safeCalculate, after parsing the regex captures into
left and right (variables a, b -> left, right), validate that both left and
right are real numbers (use Number.isFinite or !Number.isNaN) and throw the same
user-facing error if either is invalid; keep the original format message ('Use
format: "number operator number" ...') and do not rely solely on the regex (this
prevents tokens like "." or "..." from producing NaN and leaking into
calculations).
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/index.js-28-37 (1)</summary><blockquote>

`28-37`: _⚠️ Potential issue_ | _🟡 Minor_

**Add error handling for invalid timezone inputs in getCurrentTime tool.**

Line 36 calls `toLocaleString` with a user-supplied `timeZone` option. Invalid timezone values (any non-IANA string that doesn't match a valid identifier like `"America/New_York"` or an offset format) throw `RangeError` and fail the invocation. Wrap the call in a try-catch to return a friendly error message instead.

<details>
<summary>Suggested timezone guard</summary>

```diff
   async ({ timezone }) => {
     const now = new Date()
     const options = {
       timeZone: timezone || 'UTC',
       dateStyle: 'full',
       timeStyle: 'long',
     }
-    return `Current time: ${now.toLocaleString('en-US', options)}`
+    try {
+      return `Current time: ${now.toLocaleString('en-US', options)}`
+    } catch {
+      return `Error: Invalid timezone "${timezone}"`
+    }
   },
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/index.js`
around lines 28 - 37, The getCurrentTime tool currently calls
now.toLocaleString('en-US', options) with a user-specified timezone which can
throw a RangeError for invalid timeZone values; wrap the toLocaleString
invocation in a try-catch inside the async function for getCurrentTime, validate
or attempt to use the provided options.timeZone and on RangeError return a
friendly message like "Invalid timezone: <value>" (or fall back to 'UTC'), and
ensure the function still returns the formatted time string on success; modify
the tool function (getCurrentTime) to catch errors from toLocaleString and
handle them gracefully.
```

</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/serverless.yml.md-1599-1710 (1)</summary><blockquote>

`1599-1710`: _⚠️ Potential issue_ | _🟡 Minor_

**Avoid duplicate keys inside the same YAML example.**

The AI Agents example shows alternative forms for `role`, `memory`, `artifact.image`, and `authorizer` in the same map. Copy‑pasting this block produces invalid YAML (later keys override earlier ones). Consider splitting alternatives into separate snippets or commenting out one variant in each block.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/serverless.yml.md` around lines 1599 - 1710, The
example YAML contains duplicate map keys (role, memory, artifact.image,
authorizer) which make the snippet invalid; update the examples by separating
each alternative into distinct snippets or by commenting out alternative forms
so only one key appears per map (e.g., create separate blocks titled "role as
string" vs "role as object", "memory shared reference" vs "memory inline",
"artifact.image as URI" vs "artifact.image build object", and "authorizer: none"
vs "authorizer: custom_jwt") and ensure the symbols role, memory,
artifact.image, and authorizer are not repeated within the same YAML map.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtimeEndpoint.js-28-53 (1)</summary><blockquote>

`28-53`: _⚠️ Potential issue_ | _🟡 Minor_

**Guard against undefined `tags` to avoid a TypeError.**

`Object.keys(tags)` will throw if `tags` is omitted. Defaulting to `{}` keeps compilation resilient when callers skip tags.

<details>
<summary>🛠️ Suggested fix</summary>

```diff
 export function compileRuntimeEndpoint(
   agentName,
   endpointName,
   config,
   runtimeLogicalId,
   context,
-  tags,
+  tags = {},
 ) {
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtimeEndpoint.js`
around lines 28 - 53, The code in compileRuntimeEndpoint uses Object.keys(tags)
which will throw if tags is undefined; to fix, ensure tags defaults to an empty
object before use by either setting a default in the function signature (e.g.,
tags = {}) or normalizing at the top of compileRuntimeEndpoint (e.g., const
safeTags = tags || {}) and then use safeTags when computing Properties; update
the Tags spread to reference the normalized variable so Properties uses a safe
object and avoids TypeError.
```

</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/code-interpreter.md-106-108 (1)</summary><blockquote>

`106-108`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language specifier for diagram block.**

Consider adding a language specifier (e.g., `text` or `plaintext`) to the diagram code block.


<details>
<summary>Proposed fix</summary>

```diff
-```
+```text
 Agent → Code Tool → AWS Sandbox → Results
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/sf/providers/aws/guide/agents/code-interpreter.md around lines 106 -
108, The diagram code block currently uses a plain triple-backtick fence without
a language specifier; update the block that contains the text "Agent → Code Tool
→ AWS Sandbox → Results" to use a language specifier such as "text" or
"plaintext" (i.e., change the opening fence to ```text and keep the closing

docs/sf/providers/aws/guide/agents/code-interpreter.md-86-93 (1)

86-93: ⚠️ Potential issue | 🟡 Minor

Add language specifier to fenced code block.

The requirements.txt code block should have a language specifier for consistent rendering.

Proposed fix
 **Dependencies (`requirements.txt`):**
 
-```
+```txt
 bedrock-agentcore>=0.1.0
 langchain>=0.3.0
 langchain-aws>=0.2.0
 langgraph>=0.2.0
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/sf/providers/aws/guide/agents/code-interpreter.md around lines 86 - 93,
In the "Dependencies (requirements.txt)" fenced code block, add a language
specifier (e.g., txt) to the opening fence so the block becomes txt
followed by the four dependency lines (bedrock-agentcore, langchain,
langchain-aws, langgraph) to ensure consistent rendering.


</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/code-interpreter.md-314-320 (1)</summary><blockquote>

`314-320`: _⚠️ Potential issue_ | _🟡 Minor_

**Add language specifier to fenced code block.**

Similar to line 88, add a language specifier for the requirements.txt block.


<details>
<summary>Proposed fix</summary>

```diff
 **Dependencies (`requirements.txt`):**
 
-```
+```txt
 bedrock-agentcore>=0.1.0
 strands-agents>=1.0.0
 strands-agents-tools>=0.1.0
 ```
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @docs/sf/providers/aws/guide/agents/code-interpreter.md around lines 314 -
320, The fenced code block under "Dependencies (requirements.txt):" is
missing a language specifier; update the triple-backtick fence that wraps the
list of packages (the requirements.txt block) to use a language tag like "txt"
(e.g., ```txt) so syntax/highlight tools treat it as a plain text requirements
file, matching the style used earlier in the doc.


</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/index.js-69-70 (1)</summary><blockquote>

`69-70`: _⚠️ Potential issue_ | _🟡 Minor_

**Add defensive checks for browser context and page.**

`browser.contexts()[0]` and `context.pages()[0]` may be undefined if the browser has no contexts or pages. Consider adding existence checks to avoid runtime errors.


<details>
<summary>🛡️ Proposed fix to add null checks</summary>

```diff
       const context = browser.contexts()[0]
+      if (!context) {
+        throw new Error('No browser context available')
+      }
       const page = context.pages()[0]
+      if (!page) {
+        throw new Error('No page available in browser context')
+      }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/index.js`
around lines 69 - 70, The code assumes browser.contexts()[0] and
context.pages()[0] always exist; add defensive checks around those calls: verify
browser.contexts().length > 0 before assigning context and verify
context.pages().length > 0 before assigning page, and if missing either create a
new context/page (using browser.newContext() / context.newPage()) or handle the
error with a clear log/throw; update the variables context and page assignment
logic (the places using browser.contexts(), context.pages(), and the
context/pages variables) to use these checks so you never dereference undefined.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/agent.py-94-95 (1)</summary><blockquote>

`94-95`: _⚠️ Potential issue_ | _🟡 Minor_

**Add defensive checks for browser context and page.**

Similar to the JavaScript version, `browser.contexts[0]` and `context.pages[0]` may raise an IndexError if empty. Consider adding checks.


<details>
<summary>🛡️ Proposed fix</summary>

```diff
             # Get the page
             context = browser.contexts[0]
+            if not context:
+                raise RuntimeError("No browser context available")
             page = context.pages[0]
+            if not page:
+                raise RuntimeError("No page available in browser context")
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/agent.py`
around lines 94 - 95, The code accesses browser.contexts[0] and context.pages[0]
without checking for emptiness which can raise IndexError; update the logic
around the variables browser, context, and page so you first verify
browser.contexts is non-empty (if empty, create a new context via
browser.new_context() or raise a clear error) and then verify context.pages is
non-empty (if empty, create a new page via context.new_page() or raise a clear
error); ensure any created objects are assigned back to context and page so
downstream code uses the valid objects.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/test-invoke.py-90-91 (1)</summary><blockquote>

`90-91`: _⚠️ Potential issue_ | _🟡 Minor_

**Remove extraneous f-string prefix.**

Line 91 uses an f-string without any placeholders. Remove the `f` prefix.


<details>
<summary>Proposed fix</summary>

```diff
-    print(f"\n{'='*60}")
+    print("\n" + "="*60)
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/test-invoke.py`
around lines 90 - 91, The second print call that reads print(f"Invoking Custom
Browser Agent") uses an unnecessary f-string; change it to a plain string
literal (print("Invoking Custom Browser Agent")) so only the first print
(print(f"\n{'='*60}")) remains an f-string for its expression.
```

</details>

</blockquote></details>
<details>
<summary>docs/sf/providers/aws/guide/agents/code-interpreter.md-217-229 (1)</summary><blockquote>

`217-229`: _⚠️ Potential issue_ | _🟡 Minor_

**Update zod version in package.json example for consistency.**

The documentation shows `"zod": "^3.23.0"`, but the majority of examples across the codebase use `"zod": "^4.3.6"`. Update the documented version to match the most commonly used version in examples for consistency.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/agents/code-interpreter.md` around lines 217 -
229, Update the package.json dependency example so the "zod" version matches the
rest of the codebase; in the Dependencies JSON block change the "zod" entry from
"^3.23.0" to "^4.3.6" (i.e., update the "zod" dependency string in the shown
package.json example).
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/browser.js-44-49 (1)</summary><blockquote>

`44-49`: _⚠️ Potential issue_ | _🟡 Minor_

**Update schema comment and reconsider SecurityGroups default logic.**

The schema comment on line 9 is inaccurate—CloudFormation does not require `SecurityGroups` to be provided; it's optional and accepts empty arrays. However, the functional concern remains: defaulting to an empty array means VPC mode won't provide actual network connectivity. If `mode: VPC` is used, explicitly require `securityGroups` to be provided, or document why an empty default is acceptable for the use case.

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/browser.js`
around lines 44 - 49, Update the inaccurate schema comment to state that
CloudFormation's SecurityGroups is optional and accepts empty arrays, and change
the VPC handling logic in browser.js so that when networkMode === 'VPC' you do
not silently default SecurityGroups to an empty array; instead validate that
network.securityGroups is provided (referencing networkMode, network, and
config.VpcConfig) and either throw/emit a clear error requiring securityGroups
for VPC mode or explicitly document why an empty list is acceptable for this
code path.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js-172-185 (1)</summary><blockquote>

`172-185`: _⚠️ Potential issue_ | _🟡 Minor_

**Avoid emitting empty LifecycleConfiguration objects.**

If `lifecycle` is `{}`, the function returns an empty object, which will be truthy and included. That can yield an invalid CFN fragment. Return `null` when no properties are set.


<details>
<summary>🛠️ Suggested fix</summary>

```diff
 function buildLifecycleConfiguration(lifecycle) {
   if (!lifecycle) {
     return null
   }
 
-  return {
-    ...(lifecycle.idleRuntimeSessionTimeout !== undefined && {
-      IdleRuntimeSessionTimeout: lifecycle.idleRuntimeSessionTimeout,
-    }),
-    ...(lifecycle.maxLifetime !== undefined && {
-      MaxLifetime: lifecycle.maxLifetime,
-    }),
-  }
+  const config = {
+    ...(lifecycle.idleRuntimeSessionTimeout !== undefined && {
+      IdleRuntimeSessionTimeout: lifecycle.idleRuntimeSessionTimeout,
+    }),
+    ...(lifecycle.maxLifetime !== undefined && {
+      MaxLifetime: lifecycle.maxLifetime,
+    }),
+  }
+
+  return Object.keys(config).length > 0 ? config : null
 }
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js`
around lines 172 - 185, The buildLifecycleConfiguration function can return an
empty object when lifecycle is {} which becomes a problematic truthy CFN
fragment; modify buildLifecycleConfiguration to construct the
LifecycleConfiguration object from lifecycle.idleRuntimeSessionTimeout and
lifecycle.maxLifetime into a local object (using the same property keys
IdleRuntimeSessionTimeout and MaxLifetime) and then return null if that object
has no own properties (e.g., Object.keys(...).length === 0), otherwise return
the constructed object.
```

</details>

</blockquote></details>
<details>
<summary>packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js-43-105 (1)</summary><blockquote>

`43-105`: _⚠️ Potential issue_ | _🟡 Minor_

**Guard against missing artifact objects to avoid a TypeError.**

`buildArtifact` dereferences `artifact.image`/`artifact.s3` before any validation; if `config.artifact` is undefined, this throws before the intended error path.


<details>
<summary>🛠️ Suggested fix</summary>

```diff
-function buildArtifact(artifact, options = {}) {
+function buildArtifact(artifact = {}, options = {}) {
```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

```
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js`
around lines 43 - 105, The function buildArtifact currently dereferences
artifact.image and artifact.s3 without validating artifact exists; add an early
guard at the top of buildArtifact (e.g., in the function body of buildArtifact)
that checks if artifact is present and is an object (if not, throw a clear Error
like "Missing or invalid artifact: ensure config.artifact is set and packaged"),
so subsequent references to artifact.image / artifact.s3 / artifact.entryPoint
are safe and the intended error is thrown instead of a TypeError.
```

</details>

</blockquote></details>

</blockquote></details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0e36090a46

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c1ad1efeb8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# Conflicts:
#	packages/serverless/test/unit/lib/plugins/aws/dev.test.js
Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f33183c052

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/sf/providers/aws/cli-reference/logs.md (1)

16-64: ⚠️ Potential issue | 🟡 Minor

Fix two small typos for readability.

✏️ Proposed fix
-Lets you watch the logs of a specific function or agent.
+Let's you watch the logs of a specific function or agent.
@@
-- `--filter` You can specify a filter string to filter the log output. This is useful if you want to to get the `error` logs for example.
+- `--filter` You can specify a filter string to filter the log output. This is useful if you want to get the `error` logs for example.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/cli-reference/logs.md` around lines 16 - 64, In the
docs, fix two typos: in the --startTime description replace "A specific unit in
time to start fetching logs from" with "A specific point in time to start
fetching logs from" (referencing the --startTime option) and in the --filter
line remove the duplicated word "to" so it reads "This is useful if you want to
get the `error` logs for example." (referencing the --filter option).
🧹 Nitpick comments (13)
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/test-invoke.js (1)

62-97: Unused chunks array in SSE handling.

The chunks array (Line 62) is populated but never used after the loop completes. If you intended to aggregate the streamed content for later use, consider returning or logging it. Otherwise, the accumulation can be removed to simplify the code.

♻️ Suggested simplification
   if (contentType.includes('text/event-stream')) {
-    const chunks = []
     for await (const chunk of body) {
       const text =
         typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk)

       const lines = text.split('\n')
       for (const line of lines) {
         if (line.startsWith('data: ')) {
           const data = line.slice(6)
           if (data && data !== '[DONE]') {
             try {
               const parsed = JSON.parse(data)
               if (typeof parsed === 'string') {
                 process.stdout.write(parsed)
-                chunks.push(parsed)
               } else if (parsed.text) {
                 process.stdout.write(parsed.text)
-                chunks.push(parsed.text)
               } else if (parsed.data?.text) {
                 process.stdout.write(parsed.data.text)
-                chunks.push(parsed.data.text)
               }
             } catch {
               process.stdout.write(data)
-              chunks.push(data)
             }
           }
         }
       }
     }
     console.log('\n')
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/test-invoke.js`
around lines 62 - 97, The chunks array is populated inside the SSE parsing
for-await loop but never used afterwards; either remove the chunks accumulation
(delete the chunks declaration and all chunks.push(...) calls) to simplify the
stream handler, or make use of it by returning or otherwise consuming the
aggregated result after the loop (e.g., join into a single string and return or
log it) from the surrounding function that contains the for-await block so the
collected stream is actually used; update references around the for-await (SSE
parsing) block and the chunks variable accordingly.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/index.js (1)

160-166: Replace message._getType() with the public getType() method.

LangChain provides a public getType() method on BaseMessage that returns the same type string. Use it instead of the underscore-prefixed variant:

message.getType() === 'ai'

Alternatively, for greater robustness, import and use the isAIMessage() type guard from @langchain/core/messages:

import { isAIMessage } from '@langchain/core/messages'

if (isAIMessage(message) && typeof message.content === 'string') {
  yield message.content
}

This eliminates reliance on underscore-prefixed methods and aligns with LangChain's recommended patterns.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/index.js`
around lines 160 - 166, Replace the private call message._getType() with the
public API: use message.getType() in the conditional (i.e., change
message._getType() === 'ai' to message.getType() === 'ai') or, even better,
import and use the provided type guard isAIMessage from `@langchain/core/messages`
and check isAIMessage(message) && typeof message.content === 'string' before
yielding content; update the conditional in the generator where
message._getType() is used to reference message.getType() or isAIMessage
instead.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile (2)

26-42: Consider dropping the custom non-root user to keep the example minimal.

AgentCore examples in this repo intentionally keep Dockerfiles simple; the extra user setup adds noise without much practical benefit for these samples.

♻️ Simplify the example Dockerfile
-# Create non-root user for security
-RUN groupadd --gid 1001 nodejs && \
-    useradd --uid 1001 --gid nodejs --shell /bin/bash --create-home agent
-
 # Copy dependencies from deps stage
 COPY --from=deps /app/node_modules ./node_modules
@@
-# Switch to non-root user
-USER agent
Based on learnings: "In the serverless/serverless repository, Dockerfiles for AWS Bedrock AgentCore examples are intentionally simple. AgentCore Runtime manages container execution in sandboxed microVMs, which provide isolation. Therefore, non-root user directives are not necessary in these example Dockerfiles and would only complicate the examples without practical security benefit."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile`
around lines 26 - 42, The Dockerfile includes a custom non-root user setup
(groupadd --gid 1001 nodejs, useradd --uid 1001 --gid nodejs ... agent) and a
USER agent switch which add unnecessary noise for these AgentCore examples;
remove the groupadd/useradd block and the final USER agent line so the example
remains minimal and uses the default image user, keeping other parts (COPY
steps, ENV NODE_ENV/PORT, and dependency COPY) unchanged.

13-17: Remove non-root user directives to keep the example intentionally simple.

AgentCore Runtime manages container execution in sandboxed microVMs, which provide isolation. The non-root user setup (lines 26–28 and 42) is unnecessary complexity for this example. Simplify by removing the groupadd, useradd, and USER directives:

Suggested simplification
-# Create non-root user for security
-RUN groupadd --gid 1001 nodejs && \
-    useradd --uid 1001 --gid nodejs --shell /bin/bash --create-home agent
-
 # Copy dependencies from deps stage
 COPY --from=deps /app/node_modules ./node_modules
 
@@ -39,8 +36,6 @@ COPY package.json ./
 ENV NODE_ENV=production
 ENV PORT=8080
 
-# Switch to non-root user
-USER agent
-
 # Expose the AgentCore runtime port
 EXPOSE 8080
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile`
around lines 13 - 17, Remove the non-root user setup from the Dockerfile by
deleting the groupadd, useradd, and USER directives (the calls that create
"node" group/user and the subsequent USER instruction) so the image runs as root
for this simplified example; ensure any chown/chmod lines referencing that user
are removed or adjusted and keep the COPY/RUN npm ci steps as-is so files remain
owned by root and the build succeeds under the simplified container user model.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py (1)

14-14: Remove unused codecs import.

The codecs module is imported but never used in this file. The response handling uses decode("utf-8") directly on the bytes object.

🧹 Proposed fix
 import boto3
-import codecs
 import json
 import os
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py`
at line 14, Remove the unused import of the codecs module: delete the line
importing "codecs" at the top of the test-invoke.py file since the file decodes
bytes with .decode("utf-8") directly and no codecs functions are used; ensure no
other references to codecs remain and run tests/lint to confirm.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py (1)

163-165: Consider using logging.exception for better stack traces.

When catching exceptions, logging.exception automatically includes the traceback, which aids debugging in production.

🧹 Suggested improvement
     except Exception as e:
-        logger.error(f"Error during agent execution: {e}")
+        logger.exception("Error during agent execution")
         return {"error": str(e)}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py`
around lines 163 - 165, The except block in the agent execution currently logs
errors with logger.error which omits the traceback; update the except in the
agent execution code (the except Exception as e handler in agent.py) to call
logger.exception("Error during agent execution") so the stack trace is included,
and retain the existing return {"error": str(e)}; ensure you don't duplicate the
exception string in the message so logger.exception captures the traceback
cleanly.
packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js (1)

187-209: Duplicate JSDoc comment block.

Lines 187-189 contain a duplicate/empty JSDoc comment before the actual documentation block at lines 190-195.

🧹 Remove duplicate comment
-/**
- * Build protocol configuration for the runtime
- */
 /**
  * Build protocol configuration for the runtime
  * For Runtime, ProtocolConfiguration is just a string enum: HTTP, MCP, or A2A
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js`
around lines 187 - 209, Remove the redundant/empty JSDoc block that appears
immediately before the real documentation for buildProtocolConfiguration so only
the single proper JSDoc remains; update the file by deleting the duplicate
comment lines (the stray /** ... */ just above the real JSDoc) and ensure the
documented function buildProtocolConfiguration retains the correct JSDoc block
describing parameters and return value.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/test-invoke.py (1)

117-123: Heuristic-based validation may produce false positives.

The success indicators check for generic terms like "limit", "github", "api" which could match unrelated content. Consider tightening the validation or accepting that this is a smoke test rather than precise validation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/test-invoke.py`
around lines 117 - 123, The current heuristic in success_indicators (checking
response_text for generic tokens like "limit", "github", "api") is prone to
false positives; update the validation in the test_invoke.py to either narrow
the checks to more specific phrases or regex patterns (e.g., "rate limit
exceeded", "GitHub API", specific numeric patterns like "60 requests/minute" or
HTTP status codes like "429") or explicitly mark this as a smoke test by
replacing the heuristic with a single existence check and a comment stating it’s
non-deterministic; locate and adjust the success_indicators list and any
assertion that consumes it so the test either uses stricter substring/regex
matches against response_text or documents/relaxes the expectation as a
lightweight smoke check.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile (1)

6-22: Consider adding --no-install-recommends to reduce image size.

The explicit dependency list is correct per project conventions for deterministic builds. Adding --no-install-recommends would prevent pulling unnecessary recommended packages, reducing the final image size.

♻️ Proposed fix
-RUN apt-get update && apt-get install -y \
+RUN apt-get update && apt-get install -y --no-install-recommends \
     libnss3 \
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile`
around lines 6 - 22, The RUN apt-get update && apt-get install -y ... line in
the Dockerfile should include the --no-install-recommends flag to avoid
installing unnecessary recommended packages and reduce image size; update the
RUN instruction that installs libnss3, libnspr4, libatk1.0-0, etc. so apt-get
install uses --no-install-recommends (and keep the existing rm -rf
/var/lib/apt/lists/* cleanup).
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile (1)

6-22: Consider adding --no-install-recommends to reduce image size.

Same as the langgraph-browser Dockerfile — adding the flag would reduce image size without affecting functionality.

♻️ Proposed fix
-RUN apt-get update && apt-get install -y \
+RUN apt-get update && apt-get install -y --no-install-recommends \
     libnss3 \
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile`
around lines 6 - 22, Update the Dockerfile RUN that currently uses "apt-get
update && apt-get install -y \ ..." to include the --no-install-recommends flag
in the apt-get install invocation (i.e., change to apt-get install -y
--no-install-recommends ...) while preserving the existing package list and the
trailing "&& rm -rf /var/lib/apt/lists/*" cleanup; this will reduce image size
without changing functionality.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-memory/index.js (1)

172-187: Prefer async/await in chatbot.
Replace the Promise chain to align with project style.

♻️ Suggested refactor
-  function chatbot(state) {
+  async function chatbot(state) {
     const rawMessages = state.messages || []
@@
-    return llmWithTools.invoke(messages).then((response) => ({
-      messages: [...rawMessages, response],
-    }))
+    const response = await llmWithTools.invoke(messages)
+    return { messages: [...rawMessages, response] }
   }

Per coding guidelines: "Use async/await for asynchronous code"

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-memory/index.js`
around lines 172 - 187, The chatbot function currently returns a Promise via
.then; convert it to an async function (async function chatbot(state)) and use
await for llmWithTools.invoke(messages) instead of .then so the code matches
project style. Preserve the existing logic around rawMessages, SystemMessage and
systemMessage (keep nonSystemMessages and messages array), then await const
response = await llmWithTools.invoke(messages) and return { messages:
[...rawMessages, response] } directly from the async function. Ensure any
callers that expect a Promise continue to work since async returns a Promise.
packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js (2)

32-39: Unused agentName parameter in constructor.

The agentName parameter is destructured but never stored or used in the class. Either remove it from the constructor signature or store it if it's needed for future functionality.

♻️ Suggested fix
-  constructor({ projectPath, agentName, agentConfig, region, port }) {
+  constructor({ projectPath, agentConfig, region, port }) {
     this.#projectPath = projectPath
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`
around lines 32 - 39, The constructor currently accepts an unused agentName;
either remove agentName from the parameter list or persist it—preferred: store
it as a private field by assigning this.#agentName = agentName in the
constructor and add the corresponding private field declaration (e.g.,
`#agentName`) to the class so other methods can reference the agent name
consistently; if you intentionally don't need it, remove agentName from the
destructured parameters in the constructor signature instead.

233-245: Global process.env.PATH mutation persists beyond instance lifecycle.

#setupVirtualEnv() modifies process.env.PATH globally (line 242), which persists for the entire Node.js process lifetime. If dev mode stops and restarts, or if multiple agents run sequentially, the PATH will accumulate duplicate venv entries.

Consider building the PATH locally and passing it only to the spawned process environment instead of mutating the global process.env.

♻️ Suggested refactor
-  `#setupVirtualEnv`() {
-    if (!process.env.VIRTUAL_ENV) {
-      return
-    }
-
-    const runtimeDir = os.platform() === 'win32' ? 'Scripts' : 'bin'
-    const venvBinPath = path.join(process.env.VIRTUAL_ENV, runtimeDir)
-
-    // Prepend venv bin to PATH
-    process.env.PATH = [venvBinPath, path.delimiter, process.env.PATH].join('')
-
-    logger.debug(`Using virtual environment: ${process.env.VIRTUAL_ENV}`)
-  }
+  `#getVenvPath`() {
+    if (!process.env.VIRTUAL_ENV) {
+      return process.env.PATH
+    }
+
+    const runtimeDir = os.platform() === 'win32' ? 'Scripts' : 'bin'
+    const venvBinPath = path.join(process.env.VIRTUAL_ENV, runtimeDir)
+
+    logger.debug(`Using virtual environment: ${process.env.VIRTUAL_ENV}`)
+    return `${venvBinPath}${path.delimiter}${process.env.PATH}`
+  }

Then in start(), use it when building pythonEnv:

-    // Setup virtual environment in PATH if available
-    this.#setupVirtualEnv()
     // ...
-    pythonEnv.PATH = process.env.PATH
+    pythonEnv.PATH = this.#getVenvPath()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`
around lines 233 - 245, `#setupVirtualEnv` currently mutates the global
process.env.PATH causing persistent and duplicate venv entries; change it to
compute and return a local PATH string (or the venvBinPath) instead of writing
to process.env, and update start() to use that returned value when building the
pythonEnv passed to the spawned process (e.g., merge returned venv path with
existing env.PATH only for the child), also guard against adding duplicate
entries (check if venvBinPath is already present) so repeated starts don't
accumulate entries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/sf/providers/aws/guide/agents/dev.md`:
- Line 286: The markdown code span contains a trailing space in the inline code
`You: ` which triggers MD038; remove the trailing space so the code span reads
`You:` (or otherwise remove the space inside the backticks) to satisfy
markdownlint and preserve the intended prompt text.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/browser.js`:
- Around line 57-76: The validator currently only checks for
recording.s3Location.bucket but the schema and buildRecordingConfig(recording)
treat prefix as required; update the validator that validates
recording.s3Location (the check in config validator that inspects
recording.s3Location) to assert both bucket and prefix are present when
s3Location is provided, and return/throw a clear validation error referencing
the missing "prefix" (so the compiler producing buildRecordingConfig(recording)
cannot emit a config without Prefix).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/package.json`:
- Around line 5-6: The package.json "main" entry points to a non-existent file
("agent.js"); update the "main" field in package.json to reference the actual
entry file ("index.js") so tooling uses the correct module; locate the
package.json in the langgraph-basic example and change the "main" property value
from "agent.js" to "index.js".

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/README.md`:
- Around line 29-35: The README's Node.js prerequisite ("Node.js 20+") conflicts
with the package.json engines.node constraint (requires 24.x); either update the
README text in langgraph-basic/README.md to state "Node.js 24+" to match
package.json, or relax the engines.node entry in package.json to allow ">=20" if
supporting Node 20+ is intended—make the change so both files consistently
reflect the same Node.js version requirement.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/package.json`:
- Line 23: The project is using Zod 4.x which is incompatible with
`@langchain/core`; to fix, add the LangGraph Zod 4 adapter import at your entry
point by importing "@langchain/langgraph/zod" so LangGraph schemas work with Zod
4, ensure you do not mix imports from "zod/v3" and "zod" in the same schema, and
if you encounter degraded TypeScript inference in APIs like withStructuredOutput
consider downgrading to Zod 3 or adjusting types to maintain compatibility
between bedrock-agentcore (which requires Zod 4) and `@langchain/core`.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/README.md`:
- Around line 57-62: The README prerequisite lists "Node.js 20+" but
package.json's engines field requires "node": "24.x"; update either the README
or package.json so they match: decide the supported Node version (e.g., Node
24), then edit package.json's engines -> "node" value or change the README text
to reflect "Node.js 24+"; locate the package.json engines entry to adjust
("engines": { "node": "24.x" }) or update the README section "Prerequisites" to
the chosen version string so both are consistent.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/README.md`:
- Line 156: The README link to Browser Documentation uses an incorrect relative
path; update the link target in the README.md entry that currently points to
../../../../../../../docs/sf/providers/aws/guide/agents/browser.md to the
corrected path with nine parent traversals:
../../../../../../../../../../../docs/sf/providers/aws/guide/agents/browser.md
so it resolves to docs/sf/providers/aws/guide/agents/browser.md.
- Around line 143-144: Update the broken internal relative link in README.md:
locate the internal browser.md link in
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/README.md
and change the path from
../../../../../../../docs/sf/providers/aws/guide/agents/browser.md (7 levels up)
to ../../../../../../../../../docs/sf/providers/aws/guide/agents/browser.md (9
levels up) so the link correctly resolves.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter/README.md`:
- Around line 99-111: The fenced code block containing example prompts is
missing the language specifier; update the triple-backtick fence in the README
example block (the block with the Data analysis / Calculations / File operations
/ Visualization prompts) to start with ```python so the block is marked as
Python for consistency and markdown linting.
- Around line 62-80: The README's code fence for the langgraph code interpreter
snippet is missing a language specifier; update the opening fence to include
"python" so the block is ```python (ensuring the snippet that shows
create_code_interpreter_toolkit, create_react_agent, agent.ainvoke and
toolkit.cleanup is treated as Python) to fix syntax highlighting and markdown
linting.

---

Outside diff comments:
In `@docs/sf/providers/aws/cli-reference/logs.md`:
- Around line 16-64: In the docs, fix two typos: in the --startTime description
replace "A specific unit in time to start fetching logs from" with "A specific
point in time to start fetching logs from" (referencing the --startTime option)
and in the --filter line remove the duplicated word "to" so it reads "This is
useful if you want to get the `error` logs for example." (referencing the
--filter option).

---

Duplicate comments:
In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/commands/info.js`:
- Around line 66-74: The code currently only logs the gateway URL when urlOutput
exists but doesn't handle the case where describeStacks succeeds but urlOutput
is undefined; update the logic around getGatewayLogicalId() and urlOutput so
that after computing urlOutput (const urlOutput = stack?.Outputs?.find(...)) you
add an else branch that calls log.notice('  URL: (deploy to see URL)') — i.e.,
ensure the block that now logs the URL when urlOutput is truthy also logs the
same fallback message when urlOutput is falsy so the "Gateway:" section always
shows a URL or the deploy hint.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilation/orchestrator.js`:
- Around line 630-663: Before calling shouldGenerateRole(config) and using
resolvedConfig, normalize any legacy roleArn into resolvedConfig.role so the
presence of roleArn prevents generating a new role; specifically, if
resolvedConfig.role is falsy and resolvedConfig.roleArn is present, set
resolvedConfig.role = resolvedConfig.roleArn (or otherwise copy/rename the
value) so the subsequent shouldGenerateRole(resolvedConfig) check and
generateRuntimeRole/name logic respect the provided ARN.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js`:
- Around line 682-722: The watcher’s ignored function (watchOptions.ignored)
compares chokidar filePath strings against forward-slash patterns so Windows
backslashes break exclusions; normalize filePath at the start of ignored (e.g.,
const normalized = filePath.replace(/\\/g, '/')) and use normalized for all
checks including commonExclusions, the this.#mode === 'code' .py check, and
test-file suffix checks to ensure exclusions work cross-platform.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/agents/index.js`:
- Line 438: The module-level PlaywrightBrowser instance reuse is safe due to
sequential invocations, so instead of changing logic, add a clear inline comment
near the const browser = new PlaywrightBrowser({ region: AWS_REGION })
declaration documenting that AgentCore Runtime guarantees sequential invocations
per microVM and that createBrowserTools stops sessions after each request;
reference PlaywrightBrowser and createBrowserTools by name so future readers
know this sharing is intentional and safe.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/handlers/calculator.js`:
- Around line 43-52: The code checks for gateway-wrapped payloads using
event.body after parsing event into body, which misses wrapped inputs when the
incoming event was a JSON string; update the conditional to inspect the parsed
body (use body.body instead of event.body) and parse body.body when it's a
string so expression = (body.body?.expression || body.expression) still works;
reference the variables body, event and the final const expression to locate and
fix the logic.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/Dockerfile.public`:
- Around line 1-10: The Dockerfile shows a conscious decision to keep the
example minimal and intentionally runs as root within the container image (FROM
public.ecr.aws/docker/library/node:24-slim with CMD ["node",
"public-agent.js"]); the static analysis warning about running as non-root
(DS-0002) is a false positive for these AgentCore examples, so no code changes
are required—leave the Dockerfile unchanged and keep the existing FROM, WORKDIR,
COPY, RUN, and CMD entries as they are.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/test-invoke.js`:
- Around line 69-94: The current main() runs test blocks before checking that
PUBLIC_ARN or PRIVATE_ARN are set, so tests may be silently skipped; move or add
the validation of the runtime ARNs (PUBLIC_ARN, PRIVATE_ARN, and AGENT_TYPE) to
the top of main() before any calls to invokeAgent, and if neither ARN is
provided call process.exit(1) with the existing error message; ensure the
condition and error message logic remains identical so tests never run when
required ARNs are missing.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/README.md`:
- Around line 7-11: The table entry for the `multiply` tool repeats "together";
update the description for `multiply` (the table row referencing `multiply`) to
a tighter phrasing such as "Multiply two numbers" to avoid the redundant word
and improve clarity.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/agent.py`:
- Around line 85-88: The entrypoint function agent_invocation decorated with
`@app.entrypoint` currently declares an unused parameter named context which
triggers Ruff ARG001; rename the parameter to _context in the agent_invocation
signature to silence the warning (leave payload and function body unchanged) so
the decorator and call sites remain compatible.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/README.md`:
- Around line 66-81: The example uses client.invoke_agent_runtime and directly
JSON-parses response['response'] but the SDK returns a streaming StreamingBody;
update the README example to read the stream (use
response['response'].iter_lines() or similar) and accumulate/parse events
instead of json.loads on the body object, and include explicit headers/content
type by passing contentType and accept (e.g., "text/event-stream") when calling
invoke_agent_runtime so the snippet demonstrates streaming consumption of the
runtimeSessionId response.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/requirements.txt`:
- Around line 1-5: Add an explicit urllib3 constraint to the requirements to
prevent installation of vulnerable transitive versions: update the
requirements.txt (the dependency block that currently lists bedrock-agentcore,
langgraph, langchain, etc.) by adding a line "urllib3>=2.6.3" so pip will prefer
a safe urllib3 when resolving transitive deps (this ensures bedrock-agentcore's
transitive urllib3 is bumped).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/test-invoke.py`:
- Around line 61-66: The code handling JSON responses iterates
response.get("response") as if it were a list, but InvokeAgentRuntime returns a
StreamingBody; change the branch that checks response.get("contentType") ==
"application/json" to read the full streaming payload (call .read() on
response.get("response")), decode it (e.g., .read().decode('utf-8')), and then
pass that decoded string into json.loads instead of iterating chunks—update the
logic around response.get("response") to use .read().decode() and json.loads
accordingly.
- Around line 41-45: The InvokeAgentRuntime call omits explicit MIME types;
update the client.invoke_agent_runtime invocation to include contentType and
accept parameters (alongside agentRuntimeArn, runtimeSessionId, payload) and set
them to the correct MIME types (e.g., "application/json" or the service-required
types) so the request model receives explicit contentType and accept headers;
change the invocation where client.invoke_agent_runtime(...) is called
(referencing RUNTIME_ARN, SESSION_ID, payload) to pass these two additional
arguments.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/agent.py`:
- Around line 86-88: The function agent_invocation defines an unused parameter
named context which triggers Ruff ARG001; rename the parameter to _context in
the agent_invocation definition (and any internal references, though there are
none) to indicate it is intentionally unused and satisfy the linter (refer to
the decorator `@app.entrypoint` and the function name agent_invocation when
locating the change).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/README.md`:
- Around line 66-81: The example treats response['response'] as a simple bytes
buffer and calls .read() then json.loads; instead, handle the StreamingBody
returned by invoke_agent_runtime by iterating/reading it properly and
decoding/accumulating chunks before parsing JSON. Update the example around the
invoke_agent_runtime call and the result parsing (referencing the response
variable and invoke_agent_runtime API) to stream-read response['response'],
decode bytes to text, concatenate chunks into a full payload string, then call
json.loads on that string to obtain the result.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/test-invoke.py`:
- Around line 41-45: The InvokeAgentRuntime call is missing explicit MIME types;
update the invoke_agent_runtime invocation to include contentType and accept
keys in the request payload (alongside agentRuntimeArn=RUNTIME_ARN,
runtimeSessionId=SESSION_ID, payload=payload) so the SDK sends explicit MIME
types (e.g., "application/json" or the expected MIME) to satisfy the
boto3/Bedrock model; modify the call where invoke_agent_runtime is used to pass
those fields and ensure they match the service expectation.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/README.md`:
- Around line 116-125: The fenced code block currently marked as "```python"
contains plain text prompt examples (the three quoted prompt lines) rather than
executable Python; change the fence language from "python" to "text" so the
block is accurately labeled (update the opening fence for that snippet in the
README to "```text" and leave the contents unchanged).

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/README.md`:
- Around line 570-585: The headings under "IAM Role Customization" use h4 (####)
immediately after an h2 which violates markdown hierarchy; update the
subheadings "Existing Role ARN" and "Role Customization" to h3 (###) so they are
proper children of the h2, and verify any other nearby headings follow the same
h2→h3→h4 progression to satisfy markdownlint; locate the strings "IAM Role
Customization", "Existing Role ARN", and "Role Customization" in the README to
make the change.

---

Nitpick comments:
In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js`:
- Around line 187-209: Remove the redundant/empty JSDoc block that appears
immediately before the real documentation for buildProtocolConfiguration so only
the single proper JSDoc remains; update the file by deleting the duplicate
comment lines (the stray /** ... */ just above the real JSDoc) and ensure the
documented function buildProtocolConfiguration retains the correct JSDoc block
describing parameters and return value.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`:
- Around line 32-39: The constructor currently accepts an unused agentName;
either remove agentName from the parameter list or persist it—preferred: store
it as a private field by assigning this.#agentName = agentName in the
constructor and add the corresponding private field declaration (e.g.,
`#agentName`) to the class so other methods can reference the agent name
consistently; if you intentionally don't need it, remove agentName from the
destructured parameters in the constructor signature instead.
- Around line 233-245: `#setupVirtualEnv` currently mutates the global
process.env.PATH causing persistent and duplicate venv entries; change it to
compute and return a local PATH string (or the venvBinPath) instead of writing
to process.env, and update start() to use that returned value when building the
pythonEnv passed to the spawned process (e.g., merge returned venv path with
existing env.PATH only for the child), also guard against adding duplicate
entries (check if venvBinPath is already present) so repeated starts don't
accumulate entries.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile`:
- Around line 26-42: The Dockerfile includes a custom non-root user setup
(groupadd --gid 1001 nodejs, useradd --uid 1001 --gid nodejs ... agent) and a
USER agent switch which add unnecessary noise for these AgentCore examples;
remove the groupadd/useradd block and the final USER agent line so the example
remains minimal and uses the default image user, keeping other parts (COPY
steps, ENV NODE_ENV/PORT, and dependency COPY) unchanged.
- Around line 13-17: Remove the non-root user setup from the Dockerfile by
deleting the groupadd, useradd, and USER directives (the calls that create
"node" group/user and the subsequent USER instruction) so the image runs as root
for this simplified example; ensure any chown/chmod lines referencing that user
are removed or adjusted and keep the COPY/RUN npm ci steps as-is so files remain
owned by root and the build succeeds under the simplified container user model.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-memory/index.js`:
- Around line 172-187: The chatbot function currently returns a Promise via
.then; convert it to an async function (async function chatbot(state)) and use
await for llmWithTools.invoke(messages) instead of .then so the code matches
project style. Preserve the existing logic around rawMessages, SystemMessage and
systemMessage (keep nonSystemMessages and messages array), then await const
response = await llmWithTools.invoke(messages) and return { messages:
[...rawMessages, response] } directly from the async function. Ensure any
callers that expect a Promise continue to work since async returns a Promise.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/index.js`:
- Around line 160-166: Replace the private call message._getType() with the
public API: use message.getType() in the conditional (i.e., change
message._getType() === 'ai' to message.getType() === 'ai') or, even better,
import and use the provided type guard isAIMessage from `@langchain/core/messages`
and check isAIMessage(message) && typeof message.content === 'string' before
yielding content; update the conditional in the generator where
message._getType() is used to reference message.getType() or isAIMessage
instead.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/test-invoke.js`:
- Around line 62-97: The chunks array is populated inside the SSE parsing
for-await loop but never used afterwards; either remove the chunks accumulation
(delete the chunks declaration and all chunks.push(...) calls) to simplify the
stream handler, or make use of it by returning or otherwise consuming the
aggregated result after the loop (e.g., join into a single string and return or
log it) from the surrounding function that contains the for-await block so the
collected stream is actually used; update references around the for-await (SSE
parsing) block and the chunks variable accordingly.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile`:
- Around line 6-22: Update the Dockerfile RUN that currently uses "apt-get
update && apt-get install -y \ ..." to include the --no-install-recommends flag
in the apt-get install invocation (i.e., change to apt-get install -y
--no-install-recommends ...) while preserving the existing package list and the
trailing "&& rm -rf /var/lib/apt/lists/*" cleanup; this will reduce image size
without changing functionality.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile`:
- Around line 6-22: The RUN apt-get update && apt-get install -y ... line in the
Dockerfile should include the --no-install-recommends flag to avoid installing
unnecessary recommended packages and reduce image size; update the RUN
instruction that installs libnss3, libnspr4, libatk1.0-0, etc. so apt-get
install uses --no-install-recommends (and keep the existing rm -rf
/var/lib/apt/lists/* cleanup).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py`:
- Line 14: Remove the unused import of the codecs module: delete the line
importing "codecs" at the top of the test-invoke.py file since the file decodes
bytes with .decode("utf-8") directly and no codecs functions are used; ensure no
other references to codecs remain and run tests/lint to confirm.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py`:
- Around line 163-165: The except block in the agent execution currently logs
errors with logger.error which omits the traceback; update the except in the
agent execution code (the except Exception as e handler in agent.py) to call
logger.exception("Error during agent execution") so the stack trace is included,
and retain the existing return {"error": str(e)}; ensure you don't duplicate the
exception string in the message so logger.exception captures the traceback
cleanly.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/test-invoke.py`:
- Around line 117-123: The current heuristic in success_indicators (checking
response_text for generic tokens like "limit", "github", "api") is prone to
false positives; update the validation in the test_invoke.py to either narrow
the checks to more specific phrases or regex patterns (e.g., "rate limit
exceeded", "GitHub API", specific numeric patterns like "60 requests/minute" or
HTTP status codes like "429") or explicitly mark this as a smoke test by
replacing the heuristic with a single existence check and a comment stating it’s
non-deterministic; locate and adjust the success_indicators list and any
assertion that consumes it so the test either uses stricter substring/regex
matches against response_text or documents/relaxes the expectation as a
lightweight smoke check.

# Conflicts:
#	package-lock.json
#	packages/serverless/package.json
@chatgpt-codex-connector
Copy link

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector
Copy link

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@czubocha
Copy link
Contributor Author

@cursor review

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

🧹 Nitpick comments (18)
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile (1)

26-42: Simplify the example Dockerfile by dropping custom user creation.
These examples are intentionally minimal; the extra user/group setup adds noise without practical benefit here. Consider removing the non-root user directives for consistency.

🧹 Proposed simplification
-# Create non-root user for security
-RUN groupadd --gid 1001 nodejs && \
-    useradd --uid 1001 --gid nodejs --shell /bin/bash --create-home agent
-
@@
-# Switch to non-root user
-USER agent
Based on learnings: "In the serverless/serverless repository, Dockerfiles for AWS Bedrock AgentCore examples are intentionally simple. AgentCore Runtime manages container execution in sandboxed microVMs, which provide isolation. Therefore, non-root user directives are not necessary in these example Dockerfiles and would only complicate the examples without practical security benefit."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile`
around lines 26 - 42, Remove the custom non-root user/group creation and
switching from this example Dockerfile to keep it minimal: delete the RUN
groupadd/useradd lines that create gid/uid 1001 and the final USER agent
directive (and any related comments about non-root user), leaving the dependency
copy, app copy, and ENV/PORT setup intact; ensure no other instructions
reference "agent" so the container runs as the default image user.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile (1)

6-22: Consider adding --no-install-recommends for smaller image size.

The static analysis tool flagged the missing --no-install-recommends flag. Adding it would reduce the image size by avoiding unnecessary recommended packages.

💡 Proposed fix
 # Install system dependencies for Playwright
-RUN apt-get update && apt-get install -y \
+RUN apt-get update && apt-get install -y --no-install-recommends \
     libnss3 \
     libnspr4 \
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile`
around lines 6 - 22, The Dockerfile's RUN apt-get install command installs
packages with recommended extras; update the RUN line in the Dockerfile (the
apt-get update && apt-get install -y ... && rm -rf /var/lib/apt/lists/* block)
to include --no-install-recommends after apt-get install to avoid pulling
recommended packages and reduce image size, e.g., change "apt-get install -y" to
"apt-get install -y --no-install-recommends" while keeping the same package list
and the rm -rf cleanup.
packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtimeEndpoint.js (1)

52-52: Consider defensive check for tags parameter.

The Object.keys(tags).length > 0 check assumes tags is always an object. If the caller passes undefined or null, this would throw. While validation is centralized upstream per project patterns, a default parameter or defensive check could add resilience.

💡 Option: Use default parameter
 export function compileRuntimeEndpoint(
   agentName,
   endpointName,
   config,
   runtimeLogicalId,
   context,
-  tags,
+  tags = {},
 ) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtimeEndpoint.js`
at line 52, The spread expression that builds the Tags property uses
Object.keys(tags).length which will throw if tags is null/undefined; update the
code to defensively handle tags—either add a default parameter (e.g., tags = {})
where the function that builds the runtime endpoint is declared, or change the
spread condition to check tags exists first (e.g., tags &&
Object.keys(tags).length > 0) before spreading { Tags: tags } so undefined/null
tags are safe; ensure you update the same expression that currently reads like
...(Object.keys(tags).length > 0 && { Tags: tags }).
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/package.json (1)

18-20: Consider using Node.js LTS version.

Same as noted in the multi-gateway example: Node 24.x is a non-LTS release. Consider 22.x or >=20 for broader compatibility unless a specific Node 24 feature is required.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/package.json`
around lines 18 - 20, Update the package.json "engines" entry to target a Node
LTS range instead of "24.x"; modify the "engines" -> "node" value (currently
"24.x") to a broader LTS-compatible spec such as "22.x" or ">=20" to improve
compatibility across environments while retaining the engines field in the same
location.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser/index.js (1)

229-237: Consider guarding against empty messages array.

If agent.invoke returns an empty messages array, accessing result.messages[result.messages.length - 1] would yield undefined, causing subsequent .content access to throw. While unlikely in normal LangGraph operation, adding a guard improves robustness.

🛡️ Optional defensive check
         const result = await agent.invoke({
           messages: [{ role: 'user', content: request.prompt }],
         })

-        const finalMessage = result.messages[result.messages.length - 1]
-        const response = finalMessage.content
+        const finalMessage = result.messages?.[result.messages.length - 1]
+        const response = finalMessage?.content || 'No response generated'
         console.log(`Response: ${String(response).substring(0, 200)}...`)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser/index.js`
around lines 229 - 237, The code assumes result.messages has at least one
element; update the agent.invoke handling to guard against an empty messages
array by checking result.messages && result.messages.length > 0 before computing
finalMessage = result.messages[result.messages.length - 1]; if empty, return or
throw a clear error (or log and return a safe default) instead of dereferencing
undefined, and ensure downstream uses of finalMessage.content (variable
response) only occur after this check.
docs/sf/providers/aws/guide/agents/README.md (1)

159-168: Consider using a specific Node.js LTS version in Dockerfile example.

The Dockerfile example uses node:20-slim which is good (Node 20 is LTS). This is consistent with the recommendation but note it differs from the 24.x engine constraint in the example package.json files. Consider aligning these for consistency.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/sf/providers/aws/guide/agents/README.md` around lines 159 - 168, The
Dockerfile example uses FROM node:20-slim while the example package.json
specifies an engine constraint of 24.x; update one to match the other for
consistency — either change the Dockerfile base image to FROM node:24-slim to
match package.json's "engines": { "node": ">=24.x" } or relax/change the
package.json engine field to ">=20.x" to match the Dockerfile; pick the
preferred LTS and make the same version string in both the Dockerfile and the
package.json engine entries so they stay consistent.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-memory/index.js (1)

173-187: Convert chatbot function to async/await.

The function uses .then() chaining, which violates the repo guideline requiring async/await for asynchronous code in JavaScript files.

♻️ Suggested refactor
-  function chatbot(state) {
+  async function chatbot(state) {
     const rawMessages = state.messages || []
 
     // Remove existing system messages to avoid duplicates
     const nonSystemMessages = rawMessages.filter(
       (msg) => !(msg instanceof SystemMessage),
     )
 
     // Ensure SystemMessage is first
     const messages = [new SystemMessage(systemMessage), ...nonSystemMessages]
 
     // Get response from model with tools bound
-    return llmWithTools.invoke(messages).then((response) => ({
-      messages: [...rawMessages, response],
-    }))
+    const response = await llmWithTools.invoke(messages)
+    return { messages: [...rawMessages, response] }
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-memory/index.js`
around lines 173 - 187, Convert the chatbot function to use async/await: mark
the chatbot function async, keep the SystemMessage filtering and prep (variables
rawMessages, nonSystemMessages, messages) unchanged, then await
llmWithTools.invoke(messages) instead of using .then() and return the same
object shape ({ messages: [...rawMessages, response] }) after awaiting; ensure
any thrown errors propagate normally (no .then usage remains in chatbot).
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py (1)

14-14: Remove unused import.

The codecs module is imported but never used in this file.

📝 Proposed fix
 import boto3
-import codecs
 import json
 import os
 import uuid
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py`
at line 14, Remove the unused import of the codecs module from the top of the
test-invoke.py file; specifically delete the line "import codecs" so the file no
longer contains an unused import and linter warnings disappear.
packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js (2)

180-182: Redundant fs/promises import.

fs/promises is already imported at line 165 within the same function scope. Remove the duplicate import.

♻️ Suggested fix
       // VALIDATION: Buildpacks for Node.js require a lockfile
       // If package.json exists but no lockfile, dependencies won't be installed
       try {
-        const fs = await import('fs/promises')
         const packageJsonPath = path.resolve(contextPath, 'package.json')
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js`
around lines 180 - 182, In the try block of builder.js remove the redundant
dynamic import of 'fs/promises' (the const fs = await import('fs/promises')
line) since fs/promises is already imported earlier in the same function scope;
keep the existing fs/promises binding and just use it when resolving
packageJsonPath and subsequent operations (look for uses around packageJsonPath
and in the surrounding try block to ensure no duplicate import remains).

210-218: ServerlessError thrown at line 204 won't be re-thrown due to incorrect condition.

The condition at line 214-215 checks error.code !== 'ENOENT' OR error.message.includes('Missing lockfile'). However, ServerlessError thrown at line 204 has code === 'MISSING_LOCKFILE' (not 'ENOENT'), so the first condition error.code !== 'ENOENT' will be true, and the error will be re-thrown correctly. But the logic is confusing and the second condition is redundant.

The intent seems to be: re-throw if it's NOT a missing package.json case (ENOENT) OR if it's our validation error. The current logic works but is unnecessarily complex.

♻️ Suggested simplification
       } catch (error) {
-        // Ignore if package.json missing (not a Node.js project)
-        // Re-throw if it's our validation error
-        if (
-          error.code !== 'ENOENT' ||
-          error.message.includes('Missing lockfile')
-        ) {
+        // Re-throw all errors except missing package.json (not a Node.js project)
+        if (error.code !== 'ENOENT') {
           throw error
         }
       }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js`
around lines 210 - 218, The catch condition is confusing and relies on checking
error.message; replace it with an explicit check that ignores only the missing
package.json case (error.code === 'ENOENT') and re-throws all other errors
(including the ServerlessError with code 'MISSING_LOCKFILE'), e.g., change the
current if (error.code !== 'ENOENT' || error.message.includes('Missing
lockfile')) { throw error } logic to a straightforward branch that
returns/ignores when error.code === 'ENOENT' and otherwise throws the error,
using the existing error.code values rather than matching on error.message.
packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/credentials.js (1)

27-30: getRoleNameFromArn may return unexpected results for path-based role ARNs.

Role ARNs can include paths like arn:aws:iam::123456789012:role/path/to/my-role. The current implementation returns my-role (correct), but the function name suggests it extracts the role name, not the full path. This behavior is correct for the use case (getting role name for API calls), but consider documenting this behavior.

📝 Documentation improvement
 /**
  * Extract role name from a role ARN
+ * Note: For path-based role ARNs (e.g., arn:aws:iam::123:role/path/to/my-role),
+ * this returns just the role name (my-role), not the full path.
  *
  * `@param` {string} roleArn - Full IAM role ARN
  * `@returns` {string} Role name
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/credentials.js`
around lines 27 - 30, The function getRoleNameFromArn currently returns only the
final path segment (basename) for ARNs like
arn:aws:iam::123:role/path/to/my-role; add a brief JSDoc comment above
getRoleNameFromArn clarifying that it extracts and returns the role name (final
segment) not the full path, mention that this is intentional for API calls
expecting the role name, and optionally note expected input format and examples
so callers aren't surprised by path-based ARNs.
packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/gateway.js (2)

1-1: Remove 'use strict' directive in ES module.

ES modules are strict by default, making this directive redundant.

Suggested fix
-'use strict'
-
 /**
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/gateway.js`
at line 1, Remove the redundant "'use strict'" directive at the top of the ES
module (gateway.js); ES modules are strict by default so simply delete the "'use
strict'" string literal from the file (no other changes required).

184-186: Redundant optional chaining.

The conditional config.exceptionLevel && already ensures the value is truthy before accessing it, so ?. is unnecessary.

Suggested fix
       ...(config.exceptionLevel && {
-        ExceptionLevel: config.exceptionLevel?.toUpperCase(),
+        ExceptionLevel: config.exceptionLevel.toUpperCase(),
       }),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/gateway.js`
around lines 184 - 186, The conditional spread uses redundant optional chaining
on config.exceptionLevel; update the spread so it still guards with the existing
truthy check but calls toUpperCase() directly (e.g., keep the guard
"...(config.exceptionLevel && { ExceptionLevel:
config.exceptionLevel.toUpperCase(), })") to remove the unnecessary "?.",
referring to the same config.exceptionLevel and ExceptionLevel symbols in the
gateway.js diff.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile (1)

6-22: Consider adding --no-install-recommends to reduce image size.

Adding this flag prevents installation of recommended but non-essential packages, resulting in a smaller image.

Suggested fix
 # Install system dependencies for Playwright
-RUN apt-get update && apt-get install -y \
+RUN apt-get update && apt-get install -y --no-install-recommends \
     libnss3 \
     libnspr4 \
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile`
around lines 6 - 22, The RUN apt-get command in the Dockerfile installs packages
without using --no-install-recommends, inflating the image; modify the RUN line
that invokes apt-get update && apt-get install -y to include
--no-install-recommends (i.e., apt-get install -y --no-install-recommends) while
keeping the existing package list and the trailing && rm -rf
/var/lib/apt/lists/* to ensure reduced image size and cleaned apt caches; no
other changes to package names are required.
packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js (2)

1-1: 'use strict' is unnecessary with ES modules.

ES modules are always in strict mode by default. This directive can be removed.

♻️ Suggested fix
-'use strict'
-
 /**
  * AWS::BedrockAgentCore::Memory CloudFormation Schema
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js` at
line 1, Remove the redundant "'use strict'" directive at the top of the module
(packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js)
because ES modules are strict by default; simply delete that line so the module
remains valid ES module code without the unnecessary directive.

51-51: Unused parameter parentRuntimeName.

The parentRuntimeName parameter is declared but not used in the function body. If this is reserved for future use or API consistency with other compilers, consider adding a comment. Otherwise, it can be removed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js` at
line 51, The function export compileMemory(name, config, context, tags,
parentRuntimeName) declares parentRuntimeName but never uses it; either remove
the parameter from the signature to eliminate the unused variable, or keep it
and add a concise explanatory comment above the function (e.g.,
"parentRuntimeName reserved for API consistency/future use") and mark it
intentionally unused (or prefix with _parentRuntimeName) to satisfy linters;
update any callers if you remove the parameter and ensure compileMemory's
exported signature remains consistent with other compiler functions if that
consistency is required.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/index.js (1)

129-141: Set Content-Type header for JSON response consistency.

The GET handler returns a JSON body but doesn't set the Content-Type header, unlike the POST error handler which uses res.json().

♻️ Suggested fix
 // GET /mcp — method not allowed per MCP spec
 app.get('/mcp', (_req, res) => {
-  res.writeHead(405).end(
-    JSON.stringify({
-      jsonrpc: '2.0',
-      error: {
-        code: -32000,
-        message: 'Method not allowed.',
-      },
-      id: null,
-    }),
-  )
+  res.status(405).json({
+    jsonrpc: '2.0',
+    error: {
+      code: -32000,
+      message: 'Method not allowed.',
+    },
+    id: null,
+  })
 })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/index.js`
around lines 129 - 141, The GET handler for '/mcp' sends a JSON body but doesn't
set Content-Type; update the app.get('/mcp', ...) response to include the JSON
content-type header (e.g., use res.writeHead(405, { 'Content-Type':
'application/json' }) before .end(...) or replace with
res.status(405).json(...)) so the response matches the POST handler's JSON
response behavior.
packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/coordinator.js (1)

99-105: Unreachable code: imageConfig is always an object here.

The check typeof imageConfig === 'string' at line 101 can never be true. Looking at how runtimesToBuild is populated (lines 52-56 and 65-69), imageConfig is always assigned as an object (artifactImage which is already confirmed to be an object at line 50, or { path: '.' } at line 68).

This dead code can be safely removed to improve clarity.

♻️ Suggested cleanup
   // Build images for runtimes with docker config (LOCAL BUILD ONLY)
   for (const { name, imageConfig } of runtimesToBuild) {
-    // Handle string reference to provider.ecr.images
-    if (typeof imageConfig === 'string') {
-      if (builtImages[imageConfig]) {
-        continue // Already built above
-      }
-    }
-
     // Build the image - imageConfig should have path, repository, or file
     const dockerConfig =
       typeof imageConfig === 'string' ? { name: imageConfig } : imageConfig
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/coordinator.js`
around lines 99 - 105, Remove the dead branch that checks typeof imageConfig ===
'string' inside the loop over runtimesToBuild; imageConfig is always an object
when populated, so delete the whole conditional and simply use
builtImages[imageConfig] logic based on object identity or a proper key (refer
to runtimesToBuild, imageConfig, and builtImages) — if you intended to detect
previously built images, replace the string check with a lookup using the actual
identifier used when populating runtimesToBuild (e.g., the image reference key)
or adjust builtImages to use object-derived keys before the continue.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/sf/providers/aws/guide/agents/runtime.md`:
- Around line 1-2: Remove the leading whitespace before the HTML comment opening
tag so the file starts with "<!--" immediately; specifically edit the opening
comment that contains "title: Serverless Framework - AgentCore Runtime
Configuration" so there are no spaces before "<!--" on the first line to prevent
Markdown rendering issues.
- Around line 301-306: Update the table row for the `HTTP` protocol so the
description uses the hyphenated compound adjective "General-purpose agents,
REST-like interactions" instead of "General purpose agents, REST-like
interactions"; locate and edit the table cell under Protocol `HTTP` in
docs/sf/providers/aws/guide/agents/runtime.md (the line containing "General
purpose agents, REST-like interactions") and replace with the hyphenated form.

In `@packages/serverless/lib/cli/commands-schema.js`:
- Around line 253-259: The schema for the 'session-id' option currently includes
an unsupported minLength: 33; either remove the minLength property from the
'session-id' entry in commands-schema.js or add explicit validation in the CLI
validation path (e.g., in ensure-supported-command.js) to enforce string length
for option 'session-id' (check option.name === 'session-id' and validate
value.length >= 33 before accepting). Update tests or error messages accordingly
so invalid session IDs produce a clear validation error.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/browser.js`:
- Around line 44-49: Remove the empty SecurityGroups fallback in the compiler:
in packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/browser.js
delete the "|| []" so config.VpcConfig.SecurityGroups is set only from
network.securityGroups; then add a validator in validators/config.js that
mirrors the subnet check for VPC mode: when networkMode === 'VPC' assert that
network.securityGroups exists and has length > 0 and throw a clear error if
missing/empty (use the same validation style/pattern as the existing subnets
check) so VPC mode cannot be used without at least one security group.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`:
- Around line 240-243: `#setupVirtualEnv`() currently mutates process.env.PATH
causing persistent side effects and duplicate venv entries; instead, stop
changing process.env and compute a local PATH string (prepend venvBinPath to
process.env.PATH, dedup if needed) and assign that local value to pythonEnv.PATH
when building pythonEnv in start(); keep all references to venvBinPath,
`#setupVirtualEnv`(), start(), and pythonEnv to locate and update the code
accordingly.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js`:
- Around line 570-580: The `#streamProcessLogs`() method is attaching duplicate
stdout/stderr listeners to the same process already instrumented by
AgentCoreCodeMode.start() (see code-mode.js start() which calls getProcess()),
so remove the duplication by deleting or disabling `#streamProcessLogs`() and any
calls to it in index.js and rely on the listeners defined in
AgentCoreCodeMode.start(); confirm logging still flows through the existing
getProcess() handlers and that `#displayLog` is not re-registered elsewhere.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md`:
- Around line 92-116: Update the two examples under "Docker Mode Example" and
"Code Mode Example" to match the public config API: nest the examples under
top-level ai.agents (not top-level agents), remove the obsolete type: runtime
key, change the docker artifact form to artifact.image (use image.path and
platform if needed), and for code mode replace entryPoint/list with handler:
handler.py and normalize runtime to lowercase form like python3.13; update the
example blocks titled "Docker Mode Example" and "Code Mode Example" in the
README.md accordingly.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/README.md`:
- Around line 125-137: The README snippet for the Serverless configuration is
out of sync with the actual serverless.yml: either add the missing region key to
the repository's serverless.yml or remove the region line from the README
example to match the file. Update the file named serverless.yml (or the README
snippet in langgraph-basic-dockerfile/README.md) so that the "provider: region:
us-east-1" entry is present in both places or omitted from both, ensuring the
YAML shown under the "ai: agents: assistant" example exactly matches the actual
serverless.yml.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/index.js`:
- Line 105: The description string for the schema field using
z.number().describe contains a trailing space before the closing parenthesis;
update the describe call for the field "b" (the z.number().describe invocation)
to remove the extra space so the text reads "Divisor (number to divide by)"
instead of "Divisor (number to divide by )".

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-code-interpreter/README.md`:
- Line 7: Replace the all-caps term "SANDBOX" in the "Sandboxed Execution"
bullet with a non-all-caps variant or Markdown emphasis to follow documentation
style; locate the string "SANDBOX" (in the "Sandboxed Execution" bullet) and
change it to "sandbox" or "*sandbox*" / "**sandbox**" so the line reads e.g.
"Sandboxed Execution: Run Python, JavaScript, or TypeScript in a sandbox
environment" (or with emphasis).
- Line 45: Update the README entry that references the example directory name
langgraph-code-interpreter-custom to use lowercase "public" instead of "PUBLIC"
for consistency; locate the text "-
[langgraph-code-interpreter-custom](../langgraph-code-interpreter-custom/) -
Custom interpreter with PUBLIC network" and change the word PUBLIC to public so
the line reads "... - Custom interpreter with public network".

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-gateway/handlers/calculator.js`:
- Around line 55-75: The regex and parseFloat allow malformed numerics like "."
or "1.2.3" which lead to NaN/partial parses; in the calculator handler (the
expression.match usage and the subsequent parseFloat into left/right), validate
that both parsed values are finite numbers (e.g., use Number.isFinite(left) and
Number.isFinite(right) or tighten the regex to require a valid numeric literal)
and throw the existing format Error if either is not a finite number; ensure the
division by zero check remains.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/pyproject.toml`:
- Around line 10-17: Add an explicit urllib3 constraint to the pyproject.toml
dependencies to mitigate transitive vulnerabilities: update the dependencies
list (the dependencies = [...] block that currently contains
"bedrock-agentcore>=1.3.0", "langchain>=1.2.10", etc.) to include
"urllib3>=2.6.3" so that the project and any transitive pulls via
bedrock-agentcore use the patched urllib3 version.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py`:
- Around line 78-83: The call to code_interpreter.start(...) always passes
identifier=CUSTOM_INTERPRETER_ID which can be None and prevents the default
interpreter fallback; change the logic in the code that invokes
code_interpreter.start (the call using CUSTOM_INTERPRETER_ID and the subsequent
logger lines referencing code_interpreter.identifier and
code_interpreter.session_id) to only pass identifier when CUSTOM_INTERPRETER_ID
is truthy (e.g., call code_interpreter.start(identifier=CUSTOM_INTERPRETER_ID)
if CUSTOM_INTERPRETER_ID else code_interpreter.start()), preserving the existing
logging of code_interpreter.identifier and code_interpreter.session_id.

---

Duplicate comments:
In `@docs/sf/providers/aws/guide/agents/dev.md`:
- Line 286: Remove the trailing space inside the inline code span in the
markdown line containing "**Prompt**: Type messages at the `You: ` prompt" by
changing the code span from `You: ` to `You:` so it no longer has a space inside
the backticks, satisfying markdownlint MD038.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/commands/info.js`:
- Around line 56-72: The code calls
provider.request('CloudFormation','describeStacks') and looks up urlOutput via
stack?.Outputs?.find((o) => o.OutputKey === `${getGatewayLogicalId()}Url`) but
does nothing when urlOutput is missing; add an else branch after that find to
call log.notice with a clear fallback (e.g., "  URL: (not available)" or "  URL:
not found") so the "Gateway:" section always prints a URL line; update the block
around provider.request / getGatewayLogicalId / urlOutput to include this
fallback path.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilation/orchestrator.js`:
- Around line 520-542: No code change required for resolveContainerImage: the
function correctly handles string artifact.image values by returning
builtImages[artifactImage] when present or the string as a URI otherwise, and it
also handles object and buildpack cases; simply mark the PR approved and remove
the duplicate review comment markers ([approve_code_changes] and
[duplicate_comment]) from the review text to avoid confusion.
- Around line 630-663: shouldGenerateRole(config) is being called before legacy
roleArn is normalized so a provided config.roleArn is ignored and a new role is
generated; update each compile function (compileRuntimeResources,
compileMemoryResources, compileBrowserResources,
compileCodeInterpreterResources) to normalize legacy config.roleArn to
config.role before calling shouldGenerateRole (e.g., if config.role is falsy and
config.roleArn exists, set config.role = config.roleArn), then proceed with the
existing role-generation logic that calls shouldGenerateRole and
generateRuntimeRole; ensure this normalization happens early in each function so
downstream logic (roleLogicalId, roleOptions, template.Outputs) respects the
supplied ARN.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/browser.js`:
- Around line 68-75: The implementation in browser.js currently treats
recording.s3Location.prefix as optional while the JSDoc and schema require
Prefix; inspect validators/config.js to confirm it enforces that when
recording.s3Location is present, prefix must exist, and then simplify the
browser.js block to always set config.S3Location = { Bucket:
recording.s3Location.bucket, Prefix: recording.s3Location.prefix } (remove the
conditional spread). If you find the validator does not enforce prefix, either
add the enforcement there (update validators/config.js to require prefix when
s3Location is provided) or add an explicit runtime check in the browser.js code
path that throws a clear error if recording.s3Location is present but prefix is
missing.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/codeInterpreter.js`:
- Around line 1-72: The changes are fine—no code fixes required: keep
buildCodeInterpreterNetworkConfiguration (which normalizes network.mode and
builds VpcConfig) and compileCodeInterpreter (which uses getResourceName,
resolveRole and includes NetworkConfiguration) as-is since VPC validation is
handled centrally in validators/config.js; no modifications needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`:
- Around line 44-45: Reset the private shutdown flag at the start of start():
inside the async start(credentials) method, set this.#isShuttingDown = false as
the first operational step (before using this.#agentConfig.handler or other
logic) so each start/stop cycle can proceed even if a prior stop() threw;
reference the methods start() and stop() and the field `#isShuttingDown` when
making this change.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js`:
- Around line 679-717: The watcher exclusion checks in the ignored function fail
on Windows because filePath can contain backslashes; normalize filePath early
(e.g., replace backslashes with forward slashes and optionally toLowerCase())
and use the normalized value for all checks (commonExclusions includes, the
this.#mode '.py' check, and the test-file endsWith checks) so patterns like
'/node_modules/' and suffix checks work cross-platform; update references from
filePath to the normalized path inside ignored.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/coordinator.js`:
- Around line 144-148: No change required: the progress parameter is correctly
passed into the DockerBuilder constructor (see DockerBuilder and
buildDockerImages usage), so leave the lines creating mainProgress and new
DockerBuilder(serverless, log, progress) as-is.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/README.md`:
- Line 31: The README's Node.js prerequisite ("Node.js 20+") is inconsistent
with the package.json engines.node value; open the package.json for the example
(check the engines.node field) and either update the README line "Node.js 20+"
to match the exact engines.node value (e.g., "Node.js 24.x") or, if you intend
to support Node 20+, change the package.json engines.node to the desired range;
ensure the README and the package.json engines.node are identical and keep the
version string format consistent.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-code-interpreter-custom/test-invoke.js`:
- Around line 45-63: Keep the simplified streaming handling as-is in
test-invoke.js: when response.response (variable body) implements
Symbol.asyncIterator, iterate with "for await (const chunk of body)", decode
non-string chunks with TextDecoder, collect into chunks array and join into
text, then attempt JSON.parse; do not add production-grade SSE/frame parsing for
this example—retain the current logic around body, TextDecoder, and the JSON
parse/fallback console.log behavior.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/agents/index.js`:
- Around line 438-439: The module-level PlaywrightBrowser instance (const
browser = new PlaywrightBrowser({ region: AWS_REGION })) is safe because
AgentCore guarantees sequential invocations per microVM; keep the shared browser
instance but add a short code comment near the PlaywrightBrowser/browser
declaration stating that AgentCore Runtime enforces sequential execution per
microVM so concurrent access races are not possible, and ensure any future
changes reference PlaywrightBrowser and browser to avoid accidental concurrent
use.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/handlers/calculator.js`:
- Around line 43-52: The code parses event into the local variable body but then
checks event.body instead of the parsed body, which ignores gateway-wrapped
payloads when event was a JSON string; update the nested-payload check to use
body (i.e., check body.body and parse it when it's a string) so that the
assignment before const expression uses the correctly unwrapped payload
(variables: body, event, expression).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/test-invoke.js`:
- Around line 69-98: The current main() runs tests before validating ARNs so
missing ARNs for a requested AGENT_TYPE can silently skip; update main() to
validate PUBLIC_ARN/PRIVATE_ARN against AGENT_TYPE before any invokeAgent calls
(or alternatively, before calling invokeAgent add explicit skip logs when
PUBLIC_ARN or PRIVATE_ARN is undefined) and use AGENT_TYPE, PUBLIC_ARN,
PRIVATE_ARN and invokeAgent in the checks so the script either exits early with
a clear error or logs "Skipping Public/Private agent test: missing ARN" before
skipping.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/package.json`:
- Around line 18-24: Your package lists "zod" 4.x which can break LangGraph/
LangChain unless the LangChain Zod adapter is imported and you don't mix zod
v3/v4; to fix, in the example entrypoint (the example's main JS file, not
package.json) add the LangChain Zod adapter import (referencing the
LangChain/LangGraph Zod adapter symbol) before any schema usage, ensure only
"zod" (v4) is installed (remove any zod/v3 imports), or alternatively
pin/downgrade "zod" in the dependencies in package.json if you must use v3;
verify imports in files using keyValidator/_parse come from the same zod package
to avoid the TypeError.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/README.md`:
- Around line 57-60: Update the "### Prerequisites" section in the README to
match the repo's supported Node version: replace the "- Node.js 20+" bullet with
the correct requirement (e.g., "Node.js 24.x" or the exact range used in
package.json engines), or alternatively update the project's engines to match
this README; locate the "### Prerequisites" heading and the "- Node.js 20+" line
in the README.md and make the versions consistent with the project's engines
field.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/README.md`:
- Around line 9-10: The tool description wording is redundant: update the table
entry for the `multiply` tool (the row with the symbol `multiply`) to remove the
trailing word "together" so it reads "Multiply two numbers" for consistency with
the `add` description; ensure the `add` row (`add`) remains "Add two numbers
together" or adjust both rows to a consistent style if preferred.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/agent.py`:
- Around line 86-87: Rename the unused parameter in the entrypoint function
agent_invocation from context to _context to silence the Ruff ARG001 warning
while preserving the required signature intent; update the function definition
def agent_invocation(payload, context): to use the underscore-prefixed parameter
name (i.e., _context) wherever it's referenced (if at all) so linters treat it
as intentionally unused.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/README.md`:
- Around line 66-82: The README currently uses response =
client.invoke_agent_runtime(...) and parses the StreamingBody via result =
json.loads(response['response'].read()); update the example and/or add a short
note to show proper StreamingBody handling for event-streams: replace or augment
the `.read()` usage with a streaming iteration pattern (e.g., use
response['response'].iter_lines() and decode/process each chunk) and mention
that `.read()` is acceptable for simple examples but production code should
iterate the stream; reference the invoke_agent_runtime call and the
response['response'] StreamingBody in your text so readers know exactly where to
change behavior.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/requirements.txt`:
- Around line 1-5: Add an explicit urllib3 version constraint to requirements to
avoid transitive vulnerabilities: update the requirements.txt used by the
example (where dependencies like bedrock-agentcore, langgraph, langchain,
langchain-aws, langchain-core are listed) to include "urllib3>=2.6.3" so pip
will resolve a safe urllib3 release regardless of versions pulled by
bedrock-agentcore.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/agent.py`:
- Around line 86-88: Rename the unused parameter in the agent_invocation
function from context to _context to silence Ruff ARG001; update the function
signature def agent_invocation(payload, _context): and anywhere that parameter
is referenced (none expected) to use _context if needed, ensuring only the
parameter name is changed in agent_invocation so linters treat it as
intentionally unused.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/README.md`:
- Around line 65-80: The example call to invoke_agent_runtime omits explicit
MIME types, which can cause the runtime to stream and break JSON parsing; update
the client.invoke_agent_runtime invocation (the invoke_agent_runtime call in the
snippet) to include contentType and accept parameters set to a JSON MIME (e.g.,
"application/json" or "application/json; charset=utf-8") so the runtime returns
a JSON payload that can be parsed by json.loads(response['response'].read());
ensure both keys are present in the argument list alongside agentRuntimeArn and
runtimeSessionId.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/test-invoke.py`:
- Around line 41-45: The invoke_agent_runtime call (client.invoke_agent_runtime)
is missing contentType and accept headers, causing streaming/rejection of JSON
responses; update the invocation to include contentType set to
"application/json" (or the appropriate payload type) and accept set to
"application/json" to match the payload/response so the SDK returns JSON instead
of a streaming response and the existing JSON handling path works (use the same
constants around RUNTIME_ARN, SESSION_ID, and payload when adding these
parameters).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/test-invoke.py`:
- Around line 86-113: No change required: the invoke_agent function correctly
encodes the payload for invoke_agent_runtime by using json.dumps({"prompt":
prompt}).encode("utf-8") and the extraneous f-string prefix was already removed;
leave the invoke_agent implementation (including session_id generation and
response handling of stream.read() with JSON fallback) as-is.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/test-invoke.py`:
- Around line 47-52: Replace the unnecessary f-strings that only contain the
expression {'='*60} in the two print statements (the ones printing the separator
before and after the log block) with plain strings using string
multiplication/concatenation instead of f-strings; locate the two print calls
that currently read print(f"\n{'='*60}") and print(f"{'='*60}\n") and change
them to use a non-f-string form (e.g., combine "\n" and "="*60 or use "="*60
with surrounding newlines) so Ruff F541 is avoided.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter/agent.py`:
- Around line 1-110: No changes required; the example agent (symbols: invoke,
create_code_interpreter_toolkit, init_chat_model, create_react_agent,
BedrockAgentCoreApp) is correct and can be approved as-is—no fixes needed in
invoke or the module initialization, so leave the functions and logging/error
handling unchanged.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/README.md`:
- Around line 570-603: The markdown headings "Existing Role ARN" and "Role
Customization" are currently H4 (####) beneath a H2 and should be H3 for correct
hierarchy; update the two headings labeled "Existing Role ARN" and "Role
Customization" to use three hashes (###) instead of four, leaving their
following content and code blocks unchanged so the document structure becomes H2
-> H3 -> content.

---

Nitpick comments:
In `@docs/sf/providers/aws/guide/agents/README.md`:
- Around line 159-168: The Dockerfile example uses FROM node:20-slim while the
example package.json specifies an engine constraint of 24.x; update one to match
the other for consistency — either change the Dockerfile base image to FROM
node:24-slim to match package.json's "engines": { "node": ">=24.x" } or
relax/change the package.json engine field to ">=20.x" to match the Dockerfile;
pick the preferred LTS and make the same version string in both the Dockerfile
and the package.json engine entries so they stay consistent.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/gateway.js`:
- Line 1: Remove the redundant "'use strict'" directive at the top of the ES
module (gateway.js); ES modules are strict by default so simply delete the "'use
strict'" string literal from the file (no other changes required).
- Around line 184-186: The conditional spread uses redundant optional chaining
on config.exceptionLevel; update the spread so it still guards with the existing
truthy check but calls toUpperCase() directly (e.g., keep the guard
"...(config.exceptionLevel && { ExceptionLevel:
config.exceptionLevel.toUpperCase(), })") to remove the unnecessary "?.",
referring to the same config.exceptionLevel and ExceptionLevel symbols in the
gateway.js diff.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js`:
- Line 1: Remove the redundant "'use strict'" directive at the top of the module
(packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js)
because ES modules are strict by default; simply delete that line so the module
remains valid ES module code without the unnecessary directive.
- Line 51: The function export compileMemory(name, config, context, tags,
parentRuntimeName) declares parentRuntimeName but never uses it; either remove
the parameter from the signature to eliminate the unused variable, or keep it
and add a concise explanatory comment above the function (e.g.,
"parentRuntimeName reserved for API consistency/future use") and mark it
intentionally unused (or prefix with _parentRuntimeName) to satisfy linters;
update any callers if you remove the parameter and ensure compileMemory's
exported signature remains consistent with other compiler functions if that
consistency is required.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtimeEndpoint.js`:
- Line 52: The spread expression that builds the Tags property uses
Object.keys(tags).length which will throw if tags is null/undefined; update the
code to defensively handle tags—either add a default parameter (e.g., tags = {})
where the function that builds the runtime endpoint is declared, or change the
spread condition to check tags exists first (e.g., tags &&
Object.keys(tags).length > 0) before spreading { Tags: tags } so undefined/null
tags are safe; ensure you update the same expression that currently reads like
...(Object.keys(tags).length > 0 && { Tags: tags }).

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/credentials.js`:
- Around line 27-30: The function getRoleNameFromArn currently returns only the
final path segment (basename) for ARNs like
arn:aws:iam::123:role/path/to/my-role; add a brief JSDoc comment above
getRoleNameFromArn clarifying that it extracts and returns the role name (final
segment) not the full path, mention that this is intentional for API calls
expecting the role name, and optionally note expected input format and examples
so callers aren't surprised by path-based ARNs.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js`:
- Around line 180-182: In the try block of builder.js remove the redundant
dynamic import of 'fs/promises' (the const fs = await import('fs/promises')
line) since fs/promises is already imported earlier in the same function scope;
keep the existing fs/promises binding and just use it when resolving
packageJsonPath and subsequent operations (look for uses around packageJsonPath
and in the surrounding try block to ensure no duplicate import remains).
- Around line 210-218: The catch condition is confusing and relies on checking
error.message; replace it with an explicit check that ignores only the missing
package.json case (error.code === 'ENOENT') and re-throws all other errors
(including the ServerlessError with code 'MISSING_LOCKFILE'), e.g., change the
current if (error.code !== 'ENOENT' || error.message.includes('Missing
lockfile')) { throw error } logic to a straightforward branch that
returns/ignores when error.code === 'ENOENT' and otherwise throws the error,
using the existing error.code values rather than matching on error.message.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/coordinator.js`:
- Around line 99-105: Remove the dead branch that checks typeof imageConfig ===
'string' inside the loop over runtimesToBuild; imageConfig is always an object
when populated, so delete the whole conditional and simply use
builtImages[imageConfig] logic based on object identity or a proper key (refer
to runtimesToBuild, imageConfig, and builtImages) — if you intended to detect
previously built images, replace the string check with a lookup using the actual
identifier used when populating runtimesToBuild (e.g., the image reference key)
or adjust builtImages to use object-derived keys before the continue.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile`:
- Around line 26-42: Remove the custom non-root user/group creation and
switching from this example Dockerfile to keep it minimal: delete the RUN
groupadd/useradd lines that create gid/uid 1001 and the final USER agent
directive (and any related comments about non-root user), leaving the dependency
copy, app copy, and ENV/PORT setup intact; ensure no other instructions
reference "agent" so the container runs as the default image user.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/package.json`:
- Around line 18-20: Update the package.json "engines" entry to target a Node
LTS range instead of "24.x"; modify the "engines" -> "node" value (currently
"24.x") to a broader LTS-compatible spec such as "22.x" or ">=20" to improve
compatibility across environments while retaining the engines field in the same
location.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser/index.js`:
- Around line 229-237: The code assumes result.messages has at least one
element; update the agent.invoke handling to guard against an empty messages
array by checking result.messages && result.messages.length > 0 before computing
finalMessage = result.messages[result.messages.length - 1]; if empty, return or
throw a clear error (or log and return a safe default) instead of dereferencing
undefined, and ensure downstream uses of finalMessage.content (variable
response) only occur after this check.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-memory/index.js`:
- Around line 173-187: Convert the chatbot function to use async/await: mark the
chatbot function async, keep the SystemMessage filtering and prep (variables
rawMessages, nonSystemMessages, messages) unchanged, then await
llmWithTools.invoke(messages) instead of using .then() and return the same
object shape ({ messages: [...rawMessages, response] }) after awaiting; ensure
any thrown errors propagate normally (no .then usage remains in chatbot).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/index.js`:
- Around line 129-141: The GET handler for '/mcp' sends a JSON body but doesn't
set Content-Type; update the app.get('/mcp', ...) response to include the JSON
content-type header (e.g., use res.writeHead(405, { 'Content-Type':
'application/json' }) before .end(...) or replace with
res.status(405).json(...)) so the response matches the POST handler's JSON
response behavior.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile`:
- Around line 6-22: The RUN apt-get command in the Dockerfile installs packages
without using --no-install-recommends, inflating the image; modify the RUN line
that invokes apt-get update && apt-get install -y to include
--no-install-recommends (i.e., apt-get install -y --no-install-recommends) while
keeping the existing package list and the trailing && rm -rf
/var/lib/apt/lists/* to ensure reduced image size and cleaned apt caches; no
other changes to package names are required.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile`:
- Around line 6-22: The Dockerfile's RUN apt-get install command installs
packages with recommended extras; update the RUN line in the Dockerfile (the
apt-get update && apt-get install -y ... && rm -rf /var/lib/apt/lists/* block)
to include --no-install-recommends after apt-get install to avoid pulling
recommended packages and reduce image size, e.g., change "apt-get install -y" to
"apt-get install -y --no-install-recommends" while keeping the same package list
and the rm -rf cleanup.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py`:
- Line 14: Remove the unused import of the codecs module from the top of the
test-invoke.py file; specifically delete the line "import codecs" so the file no
longer contains an unused import and linter warnings disappear.

@chatgpt-codex-connector
Copy link

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@czubocha
Copy link
Contributor Author

@cursor review

@chatgpt-codex-connector
Copy link

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@czubocha
Copy link
Contributor Author

@cursor review

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (7)
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile (1)

6-22: Add --no-install-recommends to keep the image lean.

This keeps the image smaller and aligns with the static analysis rule without changing behavior.

♻️ Proposed change
-RUN apt-get update && apt-get install -y \
+RUN apt-get update && apt-get install -y --no-install-recommends \
     libnss3 \
     libnspr4 \
     libatk1.0-0 \
     libatk-bridge2.0-0 \
     libcups2 \
     libdrm2 \
     libxkbcommon0 \
     libxcomposite1 \
     libxdamage1 \
     libxfixes3 \
     libxrandr2 \
     libgbm1 \
     libasound2 \
     libpango-1.0-0 \
     libcairo2 \
     && rm -rf /var/lib/apt/lists/*
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile`
around lines 6 - 22, Update the apt package install command in the Dockerfile
RUN step to avoid installing recommended packages: change the apt-get install
invocation in the RUN that includes libnss3, libnspr4, etc. to use apt-get
install -y --no-install-recommends (keeping the apt-get update and the final rm
-rf /var/lib/apt/lists/* as-is) so the image stays lean without changing the
listed packages.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/package.json (1)

1-7: Mark this example package as private to prevent accidental publish.

For example packages, adding "private": true avoids accidental npm publication without affecting usage.

♻️ Suggested change
 {
   "name": "langgraph-browser-custom",
   "version": "1.0.0",
+  "private": true,
   "description": "LangGraph JS agent with custom AgentCore Browser and session recording",
   "type": "module",
   "main": "index.js",
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/package.json`
around lines 1 - 7, Add the "private": true property to the example package.json
for the "langgraph-browser-custom" package to prevent accidental npm
publication; open the package.json (the object containing "name":
"langgraph-browser-custom", "version", "description", etc.) and insert the
top-level "private": true field alongside "type" and "main".
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/test-invoke.js (1)

48-56: Unused chunks array in streaming branch.

The chunks array collects streamed data but is never used. If it's not needed for this example, consider removing it to simplify the code.

♻️ Suggested simplification
   if (contentType.includes('text/event-stream')) {
-    const chunks = []
     for await (const chunk of body) {
       const text =
         typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk)
       process.stdout.write(text)
-      chunks.push(text)
     }
     console.log('\n')
   } else if (body && typeof body[Symbol.asyncIterator] === 'function') {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/test-invoke.js`
around lines 48 - 56, The streaming branch collects chunks into an unused array
named "chunks" when contentType.includes('text/event-stream'); remove the
"chunks" array and any pushes to it inside the for-await loop (the loop over
"body" that decodes with new TextDecoder() and calls process.stdout.write(text))
to simplify the example, leaving only the streaming decoding and output logic.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile (1)

6-22: Consider --no-install-recommends to slim the image.

This keeps the example small while preserving explicit dependency control.

Proposed tweak
-RUN apt-get update && apt-get install -y \
+RUN apt-get update && apt-get install -y --no-install-recommends \
     libnss3 \
     libnspr4 \
     libatk1.0-0 \
     libatk-bridge2.0-0 \
     libcups2 \
     libdrm2 \
     libxkbcommon0 \
     libxcomposite1 \
     libxdamage1 \
     libxfixes3 \
     libxrandr2 \
     libgbm1 \
     libasound2 \
     libpango-1.0-0 \
     libcairo2 \
     && rm -rf /var/lib/apt/lists/*
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile`
around lines 6 - 22, Update the Dockerfile RUN that installs system packages to
add the apt flag --no-install-recommends so only explicit packages are
installed: modify the existing RUN line that starts with "apt-get update &&
apt-get install -y \ libnss3 ..." to use "apt-get install -y
--no-install-recommends \", keep the same package list and the trailing "&& rm
-rf /var/lib/apt/lists/*" cleanup. This ensures the install step uses the
explicit package set without pulling recommended extras.
packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js (1)

32-39: Unused constructor parameter agentName.

The agentName parameter is accepted in the constructor but never stored or used. Either remove it from the signature or store it if needed for future use (e.g., logging).

-  constructor({ projectPath, agentName, agentConfig, region, port }) {
+  constructor({ projectPath, agentConfig, region, port }) {
     this.#projectPath = projectPath
     this.#agentConfig = agentConfig
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`
around lines 32 - 39, The constructor currently accepts an unused agentName
parameter; either remove agentName from the constructor signature or persist it
for later use by assigning it to a private field (e.g., this.#agentName) and
update any related uses (logging or telemetry) to reference that field; locate
the constructor definition and choose one of these two fixes (remove agentName
from the parameter list in the constructor or add this.#agentName = agentName
alongside this.#projectPath / this.#agentConfig assignments) and update any
callers or docs accordingly.
packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js (1)

187-195: Remove duplicate JSDoc comment block.

Lines 187-189 contain an empty JSDoc, followed by the actual documentation at 190-195.

-/**
- * Build protocol configuration for the runtime
- */
 /**
  * Build protocol configuration for the runtime
  * For Runtime, ProtocolConfiguration is just a string enum: HTTP, MCP, or A2A
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js`
around lines 187 - 195, Remove the redundant empty JSDoc block that precedes the
actual documentation for the "Build protocol configuration for the runtime"
comment; keep the full JSDoc that documents the protocol parameter and return
value (the block that explains the string enum HTTP/MCP/A2A and the
param/returns) and delete the earlier empty /** ... */ so there's only a single
JSDoc for this runtime protocol configuration logic.
packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js (1)

180-182: Minor: Redundant dynamic import of fs/promises.

fs/promises was already imported at line 165. Consider reusing the imported module instead of re-importing.

-      try {
-        const fs = await import('fs/promises')
+      try {
         const packageJsonPath = path.resolve(contextPath, 'package.json')
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js`
around lines 180 - 182, The dynamic import of 'fs/promises' inside the try block
is redundant; reuse the module already imported earlier (the existing
fs/promises import symbol) instead of re-importing it. Remove the await
import('fs/promises') from the try block and reference the previously-imported
variable when resolving packageJsonPath and reading package.json (look for the
earlier fs/promises import and the variables packageJsonPath and contextPath in
this file to replace the dynamic import use). Ensure no new variable name
conflict is introduced when swapping to the existing fs/promises symbol.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@docs/sf/providers/aws/guide/agents/dev.md`:
- Line 286: The markdown code span shown as `You: ` has a trailing space that
triggers markdownlint MD038; edit the markdown in
docs/sf/providers/aws/guide/agents/dev.md and change the code span from `You: `
to `You:` (remove the trailing space) so the inline code token `You:` contains
no trailing space and satisfies MD038.

In `@docs/sf/providers/aws/guide/agents/runtime.md`:
- Around line 301-304: Change the unhyphenated compound adjective in the HTTP
protocol table row: update the Description cell text "General purpose agents,
REST-like interactions" to use the hyphenated form "General-purpose agents,
REST-like interactions" so the compound adjective is grammatically correct (look
for the table row containing the `HTTP` Protocol label).

In `@packages/serverless/lib/cli/commands-schema.js`:
- Around line 241-259: The schema's 'session-id' option includes a minLength
property that the CLI parser does not enforce; either remove the unsupported
minLength from the options object or add explicit runtime validation where CLI
args are parsed to enforce session-id length >= 33. Specifically, update the CLI
argument validation path to check options['session-id'] (or the parsed sessionId
value) and return/throw a user-facing error when its length is < 33, or remove
the minLength key from the options definition to avoid misleading documentation;
update any related tests or error messages to reflect the chosen fix.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/commands/info.js`:
- Around line 66-74: The code currently only logs a fallback when describeStacks
throws, but if describeStacks succeeds and urlOutput is undefined the function
prints nothing; update the block that finds urlOutput (the const urlOutput =
stack?.Outputs?.find((o) => o.OutputKey === `${getGatewayLogicalId()}Url`)) to
add an else branch that calls log.notice('  URL: (deploy to see URL)') so you
always emit a fallback when the gateway output is missing; keep the existing
catch fallback as-is.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilation/orchestrator.js`:
- Around line 630-631: Normalize legacy roleArn before calling
shouldGenerateRole by mapping config.roleArn (if present) into config.role so
the generation check uses the provided ARN; update the normalization in the
orchestrator just before the shouldGenerateRole(config) call and apply the same
normalization pattern in the runtime, memory, browser, and codeInterpreter
helpers to avoid silently generating a role when a roleArn was supplied.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/browser.js`:
- Around line 44-48: The VpcConfig builder in the browser compiler currently
forces SecurityGroups to an empty array when network.securityGroups is absent;
update the logic in the browser.js compiler (inside the code that checks
networkMode === 'VPC' and sets config.VpcConfig) to omit the SecurityGroups
property entirely if network.securityGroups is undefined or empty so validation
in validators/config.js can enforce presence; i.e., only add SecurityGroups to
config.VpcConfig when network.securityGroups is truthy (non-empty).
- Around line 68-74: The compiler (compilers/browser.js) currently treats
recording.s3Location.prefix as optional but the RecordingConfig/S3Location
schema requires Prefix; add a validation in validators/config.js that when a
recording object has s3Location, it must include a non-empty prefix (i.e.,
enforce recording.s3Location.prefix presence and type/format), so
compilers/browser.js can safely assume Prefix exists; update the validator to
validate recording.s3Location.bucket and recording.s3Location.prefix together
and return a clear validation error message referencing
RecordingConfig/S3Location/Prefix on failure.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`:
- Around line 44-56: Reset the private shutdown flag at the beginning of start()
to avoid orphaned state: in the start() method of the class, set
this.#isShuttingDown = false before any async operations so subsequent calls to
stop() aren't short-circuited by a leftover true value; ensure you reference the
existing start() method and the `#isShuttingDown` field so the flag is reliably
reinitialized for each start/stop cycle.
- Around line 233-245: The `#setupVirtualEnv`() currently mutates
process.env.PATH; instead compute a local modified PATH string (using
venvBinPath and path.delimiter) without assigning to process.env.PATH, return or
set that value on the python environment object (assign to pythonEnv.PATH) and
keep logger.debug(`Using virtual environment: ${process.env.VIRTUAL_ENV}`) for
visibility; then update start() to call `#setupVirtualEnv`(), capture the returned
PATH and pass it into the python process/env initialization (pythonEnv.PATH)
rather than relying on the global process.env.PATH so repeated restarts don’t
accumulate duplicates.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js`:
- Around line 570-580: The logging listeners are attached twice: remove the
duplication by choosing one location to handle process stdout/stderr; either
delete the listeners inside AgentCoreCodeMode.start (referenced as
AgentCoreCodeMode.start in code-mode.js, lines ~110-121) and keep the single
`#streamProcessLogs`() implementation which uses this.#codeMode.getProcess() and
calls this.#displayLog, or remove `#streamProcessLogs`() entirely and rely on
AgentCoreCodeMode.start to attach the listeners and forward logs to the same
handler; ensure only one of `#streamProcessLogs`() or AgentCoreCodeMode.start
registers process.stdout/stderr 'data' handlers and that the chosen single
handler invokes the same log routine (this.#displayLog or the equivalent) to
avoid duplicate processing.
- Around line 693-697: Watcher paths may contain backslashes on Windows causing
exclusion checks to fail; normalize the incoming filePath to use forward slashes
before performing exclusion logic. Replace uses of filePath in the
commonExclusions loop (and in the subsequent checks around the same block that
reference filePath between lines 700-714) with a normalized variable (e.g.,
normalize via replacing backslashes with '/'), then use that normalized path for
filePath.includes(...) and any other comparisons so exclusions like
commonExclusions and the later checks match consistently across platforms.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md`:
- Around line 94-116: Update the Dev Mode README YAML examples to use the
current ai.agents config shape instead of the legacy agents/type: runtime
structure: replace the Docker example that uses agents → myAgent →
artifact.docker (path/platform) with ai → agents → myAgent → artifact.image
(path/platform), and replace the Code Mode example that uses agents → myAgent →
artifact.entryPoint and runtime: PYTHON_3_13 with ai → agents → myAgent →
handler: <handler.py> and runtime: python3.13; adjust keys exactly where the
README shows artifact.entryPoint, artifact.docker, agents, and runtime so
examples match the public ai.agents shape.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/index.js`:
- Around line 89-106: In the divide tool's input schema (the z.object for
function divide), remove the stray trailing space inside the description for the
b field so it reads "Divisor (number to divide by)" instead of "Divisor (number
to divide by )"; update the z.number().describe(...) call for b to use the
corrected string to eliminate the extra space.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/README.md`:
- Around line 29-35: The README's Node.js prerequisite ("Node.js 20+") is
inconsistent with the project's package.json engines.node setting; update one to
match the other—either change the README.md prereq to "Node.js 24.x" (or the
specific range used) or adjust package.json's "engines.node" value to allow
">=20" so they align; locate README.md (langgraph-basic/README.md) and
package.json (check the engines.node field) and make the values consistent,
keeping the canonical requirement in package.json and reflecting that exact text
in the README.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser/package.json`:
- Around line 19-21: Update the "engines" constraint in package.json (the
"engines" object and its "node" value) to a verified, supported Node.js version
used across examples (or add a fallback range like ">=18" or ">=18 <=20" for
compatibility); confirm the chosen version matches other example package.json
files and documentation, and if Node 24.x is not yet broadly available replace
"24.x" with the verified version or a compatible range so all examples remain
consistent.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-code-interpreter/README.md`:
- Line 45: Update the README entry for the langgraph-code-interpreter-custom
example to use lowercase "public" in the prose; locate the list item that reads
"[langgraph-code-interpreter-custom](../langgraph-code-interpreter-custom/) -
Custom interpreter with PUBLIC network" and change "PUBLIC" to "public" so it
matches the project's prose style.
- Line 7: The phrase "Sandboxed Execution" uses all-caps "SANDBOX" in prose;
update the README heading/line so it reads "Sandboxed Execution: Run Python,
JavaScript, or TypeScript in a sandbox environment" (i.e., replace "SANDBOX"
with lowercase "sandbox") in the README.md entry where the string "Sandboxed
Execution" appears.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/handlers/calculator.js`:
- Around line 43-50: The nested payload unwrap uses event.body instead of the
already-parsed body, so gateway-wrapped payloads are skipped; update the logic
in the handler (the code that sets the local variable body) to check body?.body
and parse that when present (i.e., replace the event.body check with body?.body
and parse body.body if it's a string) so the expression field is correctly
discovered after parsing string events.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-gateway/handlers/calculator.js`:
- Around line 54-75: safeCalculate currently uses parseFloat which accepts
partial/malformed literals like "1.2.3"; tighten numeric validation by ensuring
the captured token strings a and b are valid finite numbers before parsing or by
using a stricter regex. Update the function safeCalculate to either replace the
numeric capture with a stricter pattern (e.g.
/^[+-]?(?:\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/) in the main match, or after
parseFloat check Number.isFinite(left) && Number.isFinite(right) and re-validate
that a and b match a strict numeric pattern; keep the same error thrown on
invalid input and preserve the existing operator handling in safeCalculate.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/test-invoke.js`:
- Around line 69-94: The current main() runs test blocks before validating ARNs,
causing silent skips; move the validation that checks PUBLIC_ARN and PRIVATE_ARN
to the top of main() (or immediately before invoking tests) so missing ARNs are
detected early, and update the test branches that check
AGENT_TYPE/PUBLIC_ARN/PRIVATE_ARN to log explicit skip messages when a specific
ARN is absent (e.g., before calling invokeAgent), referencing AGENT_TYPE,
PUBLIC_ARN, PRIVATE_ARN, main(), and invokeAgent to locate where to add the
pre-check and skip logs.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/README.md`:
- Around line 57-62: The README's Node.js prerequisite ("Node.js 20+") is
inconsistent with the example's package.json engines field; open the example's
package.json in
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming,
check engines.node, and update the README prerequisite to exactly match that
value (e.g., "Node.js 24.x" if engines.node is ">=24" or "24.x" as specified) so
the README and package.json.engines are aligned.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/agent.py`:
- Around line 86-87: The agent_invocation function declares an unused context
parameter causing a linter ARG001; rename the parameter from context to _context
in the def agent_invocation signature (and update any internal references if
present) so it follows Python convention for intentionally unused parameters and
silences Ruff's warning.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/README.md`:
- Around line 71-81: The example calling client.invoke_agent_runtime is missing
required headers (contentType and accept) and may cause validation errors or
unexpected formats; update the invoke_agent_runtime call to include contentType
(e.g., "application/json") and accept (e.g., "application/json") parameters
alongside payload, and ensure payload remains JSON-encoded and response parsing
uses response['response'].read() expecting JSON; modify the example around
client.invoke_agent_runtime and the response parsing to reflect these header
additions so readers get a consistent JSON response.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/requirements.txt`:
- Around line 1-5: Add an explicit urllib3 constraint to requirements.txt to
override the transitive vulnerable version from bedrock-agentcore; update the
file by adding a line like "urllib3>=1.26.16" (or another known patched
>=1.26.x) alongside the existing entries (bedrock-agentcore, langgraph,
langchain, langchain-aws, langchain-core) so pip will install a non-vulnerable
urllib3.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/agent.py`:
- Around line 85-113: The function agent_invocation declares an unused parameter
named context which triggers Ruff ARG001; rename that parameter to _context in
the agent_invocation signature to mark it intentionally unused (leave all other
logic, uses of payload and graph.invoke unchanged) so the linter stops flagging
it and behavior remains identical.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/README.md`:
- Around line 66-81: The example incorrectly treats the invoke_agent_runtime
result as a static bytes buffer by calling response['response'].read(); instead,
handle the returned StreamingBody by iterating over its streaming lines/chunks
(e.g., use response['response'].iter_lines() or iterate the stream) to collect
and decode SSE/streamed JSON events, then aggregate the decoded pieces into a
complete JSON string before calling json.loads(); update the
client.invoke_agent_runtime example to consume the stream incrementally and
parse after reconstructing the full payload.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/test-invoke.py`:
- Around line 40-45: The Python invoke of the agent runtime may rely on SDK
defaults for MIME types; update the client.invoke_agent_runtime call to
explicitly pass contentType and accept headers (e.g., "application/json" or the
same MIME used in JS examples) alongside agentRuntimeArn=RUNTIME_ARN,
runtimeSessionId=SESSION_ID and payload to ensure consistent behavior across
environments; verify the correct MIME values against the Bedrock AgentCore SDK
model/docs before setting and add those parameters to the
client.invoke_agent_runtime invocation.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/agent.py`:
- Around line 71-78: The call to BrowserClient.start currently always passes
identifier=CUSTOM_BROWSER_ID which can be None and may prevent the default
browser fallback; update the logic around browser_client.start so it only
supplies the identifier argument when CUSTOM_BROWSER_ID is truthy (e.g., if
CUSTOM_BROWSER_ID: browser_client.start(identifier=CUSTOM_BROWSER_ID) else:
browser_client.start()), keeping the existing BrowserClient instantiation
(browser_client = BrowserClient(region=AWS_REGION)) and ensuring you reference
BrowserClient.start and CUSTOM_BROWSER_ID when making the change.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/pyproject.toml`:
- Around line 10-16: Add an explicit urllib3 version constraint to the
dependencies list in the pyproject.toml for the langgraph-browser-custom example
so transitive pulls don't bring in a vulnerable urllib3; update the dependencies
array that currently lists "bedrock-agentcore", "langchain", "langchain-aws",
"langgraph", "playwright", "nest_asyncio" to include a pinned or minimum-safe
"urllib3" entry (e.g., "urllib3>=1.xx.y" per your security guidance) and ensure
the chosen version matches any organization-wide urllib3 constraint used
elsewhere.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/README.md`:
- Around line 152-156: Update the "Browser Documentation" link in the README
(the link text "Browser Documentation") so it correctly points to
docs/sf/providers/aws/guide/agents/browser.md from the langgraph-browser example
directory: compute the correct relative path (or use a repo-root absolute path
like /docs/sf/providers/aws/guide/agents/browser.md) and replace the current
overly long ../ chain with that corrected path; ensure the link resolves locally
(e.g., with realpath or relative path calculation) before committing.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py`:
- Around line 77-81: The call to code_interpreter.start currently passes
CUSTOM_INTERPRETER_ID even when it's unset, which can block the default
interpreter; update the try block so you only pass
identifier=CUSTOM_INTERPRETER_ID when CUSTOM_INTERPRETER_ID is truthy (e.g.,
check the variable or os.environ.get value first), otherwise call
code_interpreter.start() with no identifier to allow the default interpreter;
modify the logic around the code_interpreter.start call (referencing
code_interpreter.start and CUSTOM_INTERPRETER_ID) to conditionally include the
identifier argument.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/README.md`:
- Around line 570-603: Under the "IAM Role Customization" section the
subheadings "Existing Role ARN" and "Role Customization" use #### (h4) while the
parent is ## (h2), breaking hierarchy; change those two headings to ### (h3) so
they are direct children of "IAM Role Customization" and maintain proper
markdown structure, leaving the rest of the YAML examples and text untouched.

---

Nitpick comments:
In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/runtime.js`:
- Around line 187-195: Remove the redundant empty JSDoc block that precedes the
actual documentation for the "Build protocol configuration for the runtime"
comment; keep the full JSDoc that documents the protocol parameter and return
value (the block that explains the string enum HTTP/MCP/A2A and the
param/returns) and delete the earlier empty /** ... */ so there's only a single
JSDoc for this runtime protocol configuration logic.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/code-mode.js`:
- Around line 32-39: The constructor currently accepts an unused agentName
parameter; either remove agentName from the constructor signature or persist it
for later use by assigning it to a private field (e.g., this.#agentName) and
update any related uses (logging or telemetry) to reference that field; locate
the constructor definition and choose one of these two fixes (remove agentName
from the parameter list in the constructor or add this.#agentName = agentName
alongside this.#projectPath / this.#agentConfig assignments) and update any
callers or docs accordingly.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js`:
- Around line 180-182: The dynamic import of 'fs/promises' inside the try block
is redundant; reuse the module already imported earlier (the existing
fs/promises import symbol) instead of re-importing it. Remove the await
import('fs/promises') from the try block and reference the previously-imported
variable when resolving packageJsonPath and reading package.json (look for the
earlier fs/promises import and the variables packageJsonPath and contextPath in
this file to replace the dynamic import use). Ensure no new variable name
conflict is introduced when swapping to the existing fs/promises symbol.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-browser-custom/package.json`:
- Around line 1-7: Add the "private": true property to the example package.json
for the "langgraph-browser-custom" package to prevent accidental npm
publication; open the package.json (the object containing "name":
"langgraph-browser-custom", "version", "description", etc.) and insert the
top-level "private": true field alongside "type" and "main".

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/test-invoke.js`:
- Around line 48-56: The streaming branch collects chunks into an unused array
named "chunks" when contentType.includes('text/event-stream'); remove the
"chunks" array and any pushes to it inside the for-await loop (the loop over
"body" that decodes with new TextDecoder() and calls process.stdout.write(text))
to simplify the example, leaving only the streaming decoding and output logic.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile`:
- Around line 6-22: Update the Dockerfile RUN that installs system packages to
add the apt flag --no-install-recommends so only explicit packages are
installed: modify the existing RUN line that starts with "apt-get update &&
apt-get install -y \ libnss3 ..." to use "apt-get install -y
--no-install-recommends \", keep the same package list and the trailing "&& rm
-rf /var/lib/apt/lists/*" cleanup. This ensures the install step uses the
explicit package set without pulling recommended extras.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/Dockerfile`:
- Around line 6-22: Update the apt package install command in the Dockerfile RUN
step to avoid installing recommended packages: change the apt-get install
invocation in the RUN that includes libnss3, libnspr4, etc. to use apt-get
install -y --no-install-recommends (keeping the apt-get update and the final rm
-rf /var/lib/apt/lists/* as-is) so the image stays lean without changing the
listed packages.

@chatgpt-codex-connector
Copy link

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@czubocha
Copy link
Contributor Author

@cursor review

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (12)
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/package.json (1)

1-18: Mark this example package as private to avoid accidental publish.

Since this lives under examples, consider adding "private": true so it can’t be published to npm by mistake.

Suggested change
 {
   "name": "strands-browser",
+  "private": true,
   "version": "1.0.0",
   "description": "Strands Agents SDK with AgentCore Browser for web automation",
   "type": "module",
   "main": "index.js",
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/package.json`
around lines 1 - 18, Add the npm "private": true field to the example
package.json for the "strands-browser" package to prevent accidental publishes;
locate the package.json JSON object containing "name": "strands-browser" and add
the "private": true property at the top-level of that JSON object (alongside
"name", "version", "description", etc.).
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/test-invoke.js (1)

48-55: Unused chunks array in event-stream branch.

The chunks array is populated on line 54 but never used after the loop—the streaming content is already written to stdout on line 53. This dead variable could confuse readers of this example.

Suggested fix
   if (contentType.includes('text/event-stream')) {
-    const chunks = []
     for await (const chunk of body) {
       const text =
         typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk)
       process.stdout.write(text)
-      chunks.push(text)
     }
     console.log('\n')
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/test-invoke.js`
around lines 48 - 55, The example creates a dead variable `chunks` in the SSE
branch — remove the unused `chunks` array and the `chunks.push(text)` call
inside the `for await (const chunk of body)` loop (the branch where
`contentType.includes('text/event-stream')` and `process.stdout.write(text)`
already handles streaming) so the loop only decodes and writes text; ensure no
other code references `chunks`.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile (2)

26-42: Consider removing the non-root user setup to keep the example minimal.
Given the examples aim for clarity and simplicity, the user/group creation and USER switch add complexity without practical benefit in this context.

♻️ Simplify the Dockerfile (example-friendly)
-# Create non-root user for security
-RUN groupadd --gid 1001 nodejs && \
-    useradd --uid 1001 --gid nodejs --shell /bin/bash --create-home agent
-
 ...
-# Switch to non-root user
-USER agent

Based on learnings: “In the serverless/serverless repository, Dockerfiles for AWS Bedrock AgentCore examples are intentionally simple. AgentCore Runtime manages container execution in sandboxed microVMs, which provide isolation. Therefore, non-root user directives are not necessary in these example Dockerfiles and would only complicate the examples without practical security benefit.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile`
around lines 26 - 42, Remove the explicit non-root user setup to simplify the
example Dockerfile: delete the groupadd and useradd commands that create
"nodejs" and "agent" and remove the "USER agent" directive so the image runs as
the default user; keep the dependency COPYs, application COPYs (agent.js and
package.json), and ENV lines (NODE_ENV and PORT) unchanged to preserve
functionality while making the example minimal.

13-17: Simplify Dockerfile by removing non-root user setup.
The example Dockerfile includes non-root user directives (lines 26–28, 42), but per the intended pattern for AgentCore Runtime examples, these are unnecessary. AgentCore manages container execution in sandboxed microVMs with built-in isolation, so omitting the user setup keeps the example simpler and more focused.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile`
around lines 13 - 17, Remove the non-root user setup from the example Dockerfile
by deleting the commands that create/modify a user/group and switch to it (e.g.,
any RUN groupadd/useradd/chown lines and the USER directive); keep the existing
COPY package*.json ./ and RUN npm ci --omit=dev steps and any subsequent
build/runtime commands, so the image runs as the default root user as intended
for AgentCore Runtime examples.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/test-invoke.js (1)

78-81: Use for await...of loop to fully consume the stream instead of single read() call.

A single await body.read() call returns only currently buffered data or null; it doesn't guarantee the complete payload is read. This branch (lines 78-85) should follow the same pattern already used in lines 65-77 for proper stream consumption.

♻️ Suggested fix
  } else if (body && typeof body.read === 'function') {
-   const data = await body.read()
-   const text = new TextDecoder().decode(data)
+   const chunks = []
+   for await (const chunk of body) {
+     chunks.push(
+       typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk),
+     )
+   }
+   const text = chunks.join('')
    try {
      console.log(JSON.stringify(JSON.parse(text), null, 2))
    } catch {
      console.log(text)
    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/test-invoke.js`
around lines 78 - 81, The branch that handles readable streams currently calls
await body.read() once (using body.read and TextDecoder) which can return
partial data; replace this with a for await...of loop over body to fully consume
the stream (same pattern as the earlier branch), accumulate chunks, decode them
with TextDecoder, and then parse/assign to text as before so the complete
payload is read.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/index.js (1)

154-167: Consider removing unused metadata variable.

The metadata variable from the stream destructuring is declared but never used. While this doesn't affect functionality, removing it would slightly clean up the code.

♻️ Optional refactor
-      for await (const [message, metadata] of stream) {
+      for await (const [message] of stream) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/index.js`
around lines 154 - 167, The for-await loop destructures each item as [message,
metadata] but never uses metadata; update the loop to only destructure the used
value by changing the iteration to extract just message (e.g., for await (const
[message] of stream) or restructure to for await (const message of stream)
depending on stream item shape) in the block that contains message._getType()
and yield message.content so the unused metadata variable is removed; edit the
loop around the stream iteration in this file (references: stream, message,
metadata, message._getType).
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile (1)

6-22: Consider adding --no-install-recommends to reduce image size.

Adding this flag prevents installation of suggested packages, resulting in a smaller final image.

Suggested fix
 # Install system dependencies for Playwright
-RUN apt-get update && apt-get install -y \
+RUN apt-get update && apt-get install -y --no-install-recommends \
     libnss3 \
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile`
around lines 6 - 22, The Dockerfile RUN command installs many packages without
suppressing recommended packages; update the RUN in the Dockerfile (the apt-get
update && apt-get install -y ... line) to include --no-install-recommends after
install -y so apt-get install uses minimal dependencies, keeping the final rm
-rf /var/lib/apt/lists/* cleanup unchanged to reduce image size.
packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js (1)

142-236: Avoid mutating caller-provided buildOptions when appending cache-from.
Repeated builds with the same config can accumulate duplicate --cache-from entries.

♻️ Suggested tweak
-    const buildOptions = dockerConfig.buildOptions || []
+    const buildOptions = [...(dockerConfig.buildOptions || [])]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js`
around lines 142 - 236, The buildImage function mutates the caller-provided
dockerConfig.buildOptions when appending cache-from entries, causing duplicate
flags across repeated builds; fix by making a local copy (e.g., const
buildOptions = [...(dockerConfig.buildOptions || [])] or similar) instead of
reusing dockerConfig.buildOptions, then append the --cache-from entries to that
local array and pass the local array to this.dockerClient.buildImage; update
references to buildOptions in buildImage so the original
dockerConfig.buildOptions is never modified.
packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js (2)

51-51: Unused parameter parentRuntimeName.

The parentRuntimeName parameter is declared but never used in the function body. If this is reserved for future use, consider documenting that intent; otherwise, it could be removed to avoid confusion.

♻️ Suggested fix if parameter is not needed
-export function compileMemory(name, config, context, tags, parentRuntimeName) {
+export function compileMemory(name, config, context, tags) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js` at
line 51, The function compileMemory declares an unused parameter
parentRuntimeName; remove parentRuntimeName from the function signature (export
function compileMemory(name, config, context, tags)) and update any callers to
stop passing that argument, or if it must be reserved for future use, add a
short comment above compileMemory documenting that parentRuntimeName is
intentionally unused (e.g., "reserved for future use") and prefix it with an
underscore (parentRuntimeName -> _parentRuntimeName) to indicate intentional
unused status; ensure references to the symbol in this file are updated
accordingly.

1-1: Redundant 'use strict' in ES module.

ES modules are automatically in strict mode, so this directive is unnecessary. This is a minor nit and can be addressed if desired.

♻️ Suggested removal
-'use strict'
-
 /**
  * AWS::BedrockAgentCore::Memory CloudFormation Schema
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js` at
line 1, Remove the redundant "use strict" directive at the top of the ES module
(the top-level 'use strict' string literal) since ES modules are strict by
default; simply delete that literal from the module (memory.js) to clean up the
file without changing any runtime behavior.
packages/serverless/lib/plugins/aws/bedrock-agentcore/compilation/orchestrator.js (1)

669-678: Potential duplicate entries in DependsOn array.

If runtimeResource.DependsOn already exists and contains memoryLogicalId, the push will create a duplicate. While CloudFormation handles this gracefully, it's cleaner to avoid it.

🧹 Optional cleanup
   if (memoryLogicalId) {
     runtimeResource.DependsOn = runtimeResource.DependsOn || []
-    runtimeResource.DependsOn.push(memoryLogicalId)
+    if (!runtimeResource.DependsOn.includes(memoryLogicalId)) {
+      runtimeResource.DependsOn.push(memoryLogicalId)
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilation/orchestrator.js`
around lines 669 - 678, runtimeResource.DependsOn may receive duplicate
memoryLogicalId entries; update the block that initializes
runtimeResource.DependsOn and pushes memoryLogicalId (referencing
memoryLogicalId and runtimeResource.DependsOn) to ensure you only add
memoryLogicalId if it isn't already present — e.g., initialize DependsOn to an
array if falsy and conditionally push only when runtimeResource.DependsOn does
not already include memoryLogicalId; leave the template.Outputs creation
unchanged.
packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py (1)

163-165: Use logging.exception to preserve traceback.

Replace logger.error() with logger.exception() to automatically include the stack trace, which aids debugging.

🔧 Proposed fix
     except Exception as e:
-        logger.error(f"Error during agent execution: {e}")
+        logger.exception("Error during agent execution")
         return {"error": str(e)}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py`
around lines 163 - 165, The except block in the agent execution path currently
calls logger.error with the exception message, losing the traceback; in the
except Exception as e handler inside the function where agent execution occurs
(the block shown in agent.py), replace logger.error(f"Error during agent
execution: {e}") with logger.exception(...) so the stack trace is preserved in
logs while keeping the existing return {"error": str(e)} behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/sf/providers/aws/cli-reference/logs.md`:
- Line 16: Update the user-facing text to fix two typos: change the sentence
"Lets you watch the logs of a specific function or agent." to "Let's you watch
the logs of a specific function or agent." (replace "Lets" with "Let's") and
remove the duplicated word "to to" elsewhere in the same document so it reads
"to" only; edit the markdown in docs/sf/providers/aws/cli-reference/logs.md to
apply these exact word fixes.

In `@docs/sf/providers/aws/guide/serverless.yml.md`:
- Around line 1599-1658: The YAML example currently defines duplicate keys
(role, memory, artifact.image) in the same mapping which causes earlier
alternatives to be overwritten; update the snippet so each alternative is safe
to copy/paste by moving each variant into its own clearly labeled block (e.g.,
"Option A: existing role ARN" and "Option B: customize generated role") or
comment out unused alternatives, and ensure the keys referenced (role, memory,
artifact.image / image.file / image.path, handler, runtime, gateway, statements,
managedPolicies, permissionsBoundary, tags) appear only once per mapping so
users won't accidentally lose values when copying.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/package.json`:
- Around line 23-29: Update the package versions in package.json for the
LangChain and Zod dependencies: bump "@langchain/aws" to "^1.2.0",
"@langchain/core" to "^1.1.0", "@langchain/langgraph" to "^1.1.0", and "zod" to
"^4.3.0"; then reinstall (npm/yarn) and run the example to catch any breaking
changes in imports or types introduced by the 1.x LangChain and Zod 4 upgrade,
adjusting code referencing those libraries (e.g., any usages of `@langchain/core`,
`@langchain/aws`, `@langchain/langgraph`, or zod) if type/signature changes surface.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/package.json`:
- Around line 16-21: Update the package.json dependency versions to published
releases: replace "@langchain/langgraph": "^0.2.0" with an existing pre-release
(for example "^0.2.0-rc.2") or a valid published stable if available, and
replace "zod": "^3.23.0" with a published version (for example "^3.23.0-beta.2"
or a nearby stable like "^3.22.4"); update the dependency strings in the
dependencies block so npm install can resolve them (refer to the
"@langchain/langgraph" and "zod" entries in the dependencies section).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/index.js`:
- Around line 27-28: The code currently unconditionally sets
process.env.BYPASS_TOOL_CONSENT = 'true', overwriting any user-provided value;
change this to only default when unset by checking
process.env.BYPASS_TOOL_CONSENT and assigning 'true' only if it is undefined or
empty so existing values (including 'false') are preserved—locate the assignment
to process.env.BYPASS_TOOL_CONSENT in the file and replace it with a conditional
defaulting pattern around that environment variable.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser/test-invoke.py`:
- Around line 36-51: The invoke_agent function currently passes a JSON string to
client.invoke_agent_runtime (call site: client.invoke_agent_runtime with
parameters agentRuntimeArn, runtimeSessionId, payload), which fails because the
Bedrock AgentCore client expects bytes or a file-like object; fix by encoding
the JSON payload to bytes (e.g., JSON string .encode('utf-8')) before passing it
into the payload argument so invoke_agent_runtime receives bytes instead of a
str.

---

Duplicate comments:
In `@docs/sf/providers/aws/guide/agents/dev.md`:
- Line 286: The markdown code span contains a trailing space: change the inline
code `` `You: ` `` to remove the trailing space so it becomes `` `You:` ``
(update the string in the docs/guide content where the prompt example "Prompt:
Type messages at the `You: ` prompt" appears).

In `@docs/sf/providers/aws/guide/agents/runtime.md`:
- Around line 1-2: Remove the leading whitespace before the opening HTML comment
token so the file begins exactly with "<!--" rather than with spaces; locate the
initial comment block containing "<!--" and the following "title: Serverless
Framework - AgentCore Runtime Configuration" line and delete any
whitespace/newline characters preceding the "<!--" so the comment starts at the
very beginning of the file.
- Around line 301-304: In the protocol table row for `HTTP` update the
description text "General purpose agents, REST-like interactions" to use a
hyphenated adjective: change it to "General-purpose agents, REST-like
interactions" so the phrase is grammatically correct; locate the table row
containing the `HTTP` protocol and modify that string in the markdown.

In `@packages/serverless/lib/cli/commands-schema.js`:
- Around line 253-258: The 'session-id' option currently includes a non-enforced
minLength: 33 property; remove this ineffective constraint or implement
validation in the CLI parser. Update the schema entry for 'session-id' (the
object with type: 'string' and minLength: 33) to delete the minLength field, or
add explicit runtime validation in the CLI option handling code (where option
parsing and validation occur) to check that options['session-id'] is a string
and length >= 33 and emit a clear error if not.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/browser.js`:
- Around line 35-52: The VPC subnets/securityGroups validation in
buildBrowserNetworkConfiguration is redundant; remove the duplicated validation
and delegate to the shared validator (or consolidate into a single helper) so
only one place enforces required VPC fields. Update
buildBrowserNetworkConfiguration to simply set VpcConfig when networkMode ===
'VPC' using already-validated values (network.subnets and
network.securityGroups) and remove any extra validation logic here; reference
the function buildBrowserNetworkConfiguration, the networkMode check and the
VpcConfig assignment to locate the change.
- Around line 57-78: The check for recording.s3Location.prefix is duplicated —
remove the redundant validation from buildRecordingConfig and rely on the
centralized validator; keep buildRecordingConfig (function name
buildRecordingConfig) minimal so it only includes S3Location.Prefix when
recording.s3Location.prefix is present (retain the current conditional spread
behavior) and delete any extra/pre-existing explicit prefix requirement logic
inside buildRecordingConfig so there’s a single source of truth for prefix
validation.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/codeInterpreter.js`:
- Around line 33-49: The check and minimal validation for VPC
subnets/securityGroups inside buildCodeInterpreterNetworkConfiguration is a
duplicate of upstream validation; remove the conditional subnets/securityGroups
validation block (the if (networkMode === 'VPC' && network.subnets) { ... } that
creates VpcConfig) and either (a) simply attach network.VpcConfig directly if
present or (b) leave only NetworkMode here and let the central network validator
handle VpcConfig creation/validation; refer to symbols networkMode,
network.subnets, network.securityGroups, and VpcConfig when making the change.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/index.js`:
- Around line 570-579: The `#streamProcessLogs` method is adding stdout/stderr
'data' listeners on the process returned by this.#codeMode.getProcess(), which
can duplicate listeners if AgentCoreCodeMode.start() already attaches them;
inspect AgentCoreCodeMode.start() for existing stdout/stderr wiring and ensure
only one owner attaches listeners by either removing the duplicate attachments
here or guarding them (e.g., check listenerCount on
process.stdout/process.stderr or use a logsStreamingEnabled flag/property on
AgentCoreCodeMode) and centralize log forwarding to a single method (keep
`#displayLog` as the consumer) so logs are not emitted twice.
- Around line 664-744: The watcher ignore logic in the private async method
`#startWatcher` uses string includes with forward-slash patterns which fails on
Windows where chokidar emits backslashes; update the ignored function inside
watchOptions to normalize filePath (e.g., convert backslashes to forward slashes
via filePath.replace(/\\\\/g, '/') or use path.posix.normalize) before running
the commonExclusions, extension checks, and test-file checks, and also use the
same normalized path when computing relativePath for the logger so logs and
ignores behave consistently.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/dev/README.md`:
- Around line 94-115: Update the README examples to match the public ai.agents
config shape: replace the top-level "agents" and "type: runtime" usage with a
top-level "ai" object containing "agents.myAgent". For the Docker example change
the artifact to use "artifact.image" with "path" and "platform" (refer to
symbols: ai, agents, myAgent, artifact.image, platform) and for the Code example
replace "artifact.entryPoint"/"runtime" with "handler" and normalized "runtime"
(refer to symbols: ai, agents, myAgent, handler, runtime) so the snippets match
the current public schema.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/index.js`:
- Line 105: Fix the minor typo in the schema property b's description: remove
the trailing space before the closing parenthesis in the string passed to
z.number().describe (the describe call on property 'b' in the schema) so it
reads "Divisor (number to divide by)" without the extra space.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic/README.md`:
- Line 31: The README’s Node.js prerequisite ("Node.js 20+") must match the
example's package.json engines constraint; inspect the example's package.json
and the "engines.node" field and either update engines.node to reflect ">=20"
(or the exact range implied by "20+") or change the README text to match the
current engines.node value so both are consistent; look for the README.md entry
"Node.js 20+" and the package.json "engines" -> "node" key to make the change.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-code-interpreter/README.md`:
- Line 7: Replace the all-caps "SANDBOX" in the README entry titled "Sandboxed
Execution" with lowercase "sandbox" for documentation consistency; update the
line that currently reads "**Sandboxed Execution**: Run Python, JavaScript, or
TypeScript in a SANDBOX environment" so it reads "... in a sandbox environment"
to match the project's casing conventions.
- Line 45: Change the all-caps "PUBLIC" to lowercase "public" in the README
entry for [langgraph-code-interpreter-custom] so the line reads "... - Custom
interpreter with public network"; update the text for consistency in the
README.md example referencing langgraph-code-interpreter-custom.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/agents/index.js`:
- Line 438: The module-level browser constant (browser = new
PlaywrightBrowser(...)) can persist stale state across microVM invocations if
stopSession() fails; move the PlaywrightBrowser instantiation into the request
handler (process()) so each invocation creates and uses a fresh
PlaywrightBrowser instance, ensure any existing stopSession()/cleanup still runs
on that instance before returning, and update references to the module-level
browser to use the local browser variable inside process() (and adjust any calls
to stopSession() accordingly).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-comprehensive/handlers/calculator.js`:
- Around line 43-52: The handler parses event into the local variable body but
then checks event.body instead of body.body, so nested payloads in a JSON string
are ignored; change the conditional to inspect body.body (and parse it if it's a
string) before deriving expression (i.e., replace the if (event.body) branch so
it uses body.body and sets body = typeof body.body === 'string' ?
JSON.parse(body.body) : body.body), ensuring expression = body.expression || ''
still reads the parsed payload.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-gateway/handlers/calculator.js`:
- Around line 55-75: The parsing allows malformed numeric strings (e.g., "." or
"1.2.3") so after extracting a and b and computing left = parseFloat(a) and
right = parseFloat(b) (from the match destructuring), validate both are finite
numbers using Number.isFinite (or isFinite) and throw a clear Error (e.g.,
"Invalid number format") if either is not finite before entering the switch;
this ensures deterministic behavior for the calculator logic (including the
division-by-zero check in the '/' case).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-multi-gateway/test-invoke.js`:
- Around line 69-98: The current main function runs invokeAgent calls before
validating ARNs, so when AGENT_TYPE === 'both' and only one of
PUBLIC_ARN/PRIVATE_ARN is set a test is silently skipped; move the ARN
validation to the start of main (before any invokeAgent calls), enforce that if
AGENT_TYPE === 'both' both PUBLIC_ARN and PRIVATE_ARN must be present (otherwise
log a clear error and exit), and for other AGENT_TYPE values log explicit
skip/info messages when the expected ARN (PUBLIC_ARN or PRIVATE_ARN) is missing
instead of silently skipping; reference main, AGENT_TYPE, PUBLIC_ARN,
PRIVATE_ARN, and invokeAgent to locate the changes.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/package.json`:
- Around line 18-23: The package.json pins `@langchain/core`, `@langchain/langgraph`
and zod but may mix incompatible Zod major versions or miss the LangGraph Zod
adapter; verify the three packages' peerDependency requirements and, if
LangGraph expects Zod v4, update the example entrypoint to import the adapter
from "@langchain/langgraph/zod" (instead of raw "zod" or "zod/v3") and ensure
only one Zod major version is installed in dependencies; adjust package.json
versions to mutually compatible releases or add the appropriate adapter import
in the example source that uses LangGraph schemas.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/README.md`:
- Around line 57-62: The README's prerequisites state "Node.js 20+" but
package.json declares engines: { "node": "24.x" }, causing a mismatch; update
one to match the other — either change the README prerequisite to "Node.js 24+"
to reflect package.json's engines field, or relax the package.json engines
setting to ">=20" (or "20.x || 24.x") so it aligns with the README; ensure the
change is applied to the README prereqs text or the package.json engines value
(refer to the engines: "node": "24.x" entry) so both documents match.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/mcp-server/README.md`:
- Around line 7-11: The README table entry for the `multiply` tool uses a
redundant word "together"; update the `multiply` row in README.md (the table row
with the `multiply` tool name) to a concise description such as "Multiply two
numbers" instead of "Multiply two numbers together" so the wording is consistent
with the `add` row.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/agent.py`:
- Around line 86-113: The agent_invocation function currently has an unused
parameter context which triggers Ruff ARG001; silence it by renaming the
parameter to _context (or _ if preferred) in the agent_invocation signature so
the linter ignores it, keeping the rest of the function body the same; update
any internal references to context (none expected) and ensure the function name
agent_invocation and the graph.invoke call remain unchanged.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/README.md`:
- Around line 66-82: The code is incorrectly calling response['response'].read()
on the StreamingBody from invoke_agent_runtime; instead consume the stream
incrementally (e.g., iterate response['response'] with .iter_lines() or
.iter_chunks()) and parse each chunk/line as JSON (or accumulate if the model
emits a final JSON object), so update the snippet around the
invoke_agent_runtime call to iterate the StreamingBody rather than calling
.read() and pass each line/chunk to json.loads() (or assemble then json.loads())
to handle streaming responses correctly.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-code/requirements.txt`:
- Around line 1-5: Add an explicit urllib3 constraint to the requirements list
to prevent vulnerable transitive versions from being selected: update the
requirements.txt entries (alongside bedrock-agentcore, langgraph, langchain,
langchain-aws, langchain-core) to include a pinned safe minimum such as
"urllib3>=2.6.3" so the resolver cannot install older vulnerable urllib3
releases; ensure the new line is added as a separate requirement entry and
commit the change.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/agent.py`:
- Around line 86-88: The parameter `context` in the function definition of
agent_invocation is unused and triggers Ruff ARG001; rename it to `_context` in
the `def agent_invocation(payload, context)` signature (i.e., change to `def
agent_invocation(payload, _context)`) to mark it as intentionally unused—ensure
there are no other references to `context` inside `agent_invocation` before
renaming.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/README.md`:
- Around line 65-80: The example incorrectly treats invoke_agent_runtime's
response as a single JSON blob (response['response'].read()), which will hang
because the body is streamed; update the snippet around invoke_agent_runtime to
consume the streaming body incrementally (e.g., iterate over
response['response'] streaming/iter_lines or read chunks from
response['response'].raw/streaming_body), concatenate and decode the chunks into
a complete string, then call json.loads on that string to parse the final JSON;
ensure you still use runtimeSessionId and agentRuntimeArn as shown and handle
potential partial/empty chunks and decode errors when building the final payload
before printing.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-basic-docker/test-invoke.py`:
- Around line 41-45: The invoke_agent_runtime call is missing explicit MIME type
parameters; update the invocation of invoke_agent_runtime (the call around
variables RUNTIME_ARN, SESSION_ID, payload) to include contentType and accept
with appropriate MIME types (e.g., "application/json" for both or the correct
request/response MIME types you expect) so the request and response formats are
explicit to the AWS API.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/agent.py`:
- Around line 71-78: Before calling BrowserClient.start, guard against passing
None by checking CUSTOM_BROWSER_ID and only supplying the identifier argument
when it is set; update the code around BrowserClient and the start call
(BrowserClient, start, CUSTOM_BROWSER_ID) to conditionally call
start(identifier=...) versus start() so the SDK never receives a None
identifier.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/pyproject.toml`:
- Around line 10-17: Add an explicit urllib3 constraint to the dependencies list
to ensure patched versions are used; update the dependencies array (the list
containing "bedrock-agentcore...","langchain...", etc.) to include a durable
urllib3 constraint such as "urllib3>=1.26.16,<2.0.0" so the example pins a safe
minimum for transitive vulnerabilities while remaining compatible with the other
listed packages.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py`:
- Around line 77-83: The call to code_interpreter.start currently always passes
identifier=CUSTOM_INTERPRETER_ID which can send None and prevent fallback;
update the start invocation in the try block so it only passes the identifier
when CUSTOM_INTERPRETER_ID is not None (e.g., branch or conditional argument
construction) — modify the code around code_interpreter.start(...) to call
code_interpreter.start() when CUSTOM_INTERPRETER_ID is None and
code_interpreter.start(identifier=CUSTOM_INTERPRETER_ID) otherwise, preserving
the subsequent logging of code_interpreter.identifier and
code_interpreter.session_id.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/README.md`:
- Around line 570-583: The subsection headings under "IAM Role Customization"
use h4 instead of h3; update the markdown headings "Existing Role ARN" and "Role
Customization" to be h3 (### Existing Role ARN and ### Role Customization) so
they follow the h2 "IAM Role Customization" correctly and avoid skipping heading
levels.

---

Nitpick comments:
In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilation/orchestrator.js`:
- Around line 669-678: runtimeResource.DependsOn may receive duplicate
memoryLogicalId entries; update the block that initializes
runtimeResource.DependsOn and pushes memoryLogicalId (referencing
memoryLogicalId and runtimeResource.DependsOn) to ensure you only add
memoryLogicalId if it isn't already present — e.g., initialize DependsOn to an
array if falsy and conditionally push only when runtimeResource.DependsOn does
not already include memoryLogicalId; leave the template.Outputs creation
unchanged.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/compilers/memory.js`:
- Line 51: The function compileMemory declares an unused parameter
parentRuntimeName; remove parentRuntimeName from the function signature (export
function compileMemory(name, config, context, tags)) and update any callers to
stop passing that argument, or if it must be reserved for future use, add a
short comment above compileMemory documenting that parentRuntimeName is
intentionally unused (e.g., "reserved for future use") and prefix it with an
underscore (parentRuntimeName -> _parentRuntimeName) to indicate intentional
unused status; ensure references to the symbol in this file are updated
accordingly.
- Line 1: Remove the redundant "use strict" directive at the top of the ES
module (the top-level 'use strict' string literal) since ES modules are strict
by default; simply delete that literal from the module (memory.js) to clean up
the file without changing any runtime behavior.

In `@packages/serverless/lib/plugins/aws/bedrock-agentcore/docker/builder.js`:
- Around line 142-236: The buildImage function mutates the caller-provided
dockerConfig.buildOptions when appending cache-from entries, causing duplicate
flags across repeated builds; fix by making a local copy (e.g., const
buildOptions = [...(dockerConfig.buildOptions || [])] or similar) instead of
reusing dockerConfig.buildOptions, then append the --cache-from entries to that
local array and pass the local array to this.dockerClient.buildImage; update
references to buildOptions in buildImage so the original
dockerConfig.buildOptions is never modified.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/Dockerfile`:
- Around line 26-42: Remove the explicit non-root user setup to simplify the
example Dockerfile: delete the groupadd and useradd commands that create
"nodejs" and "agent" and remove the "USER agent" directive so the image runs as
the default user; keep the dependency COPYs, application COPYs (agent.js and
package.json), and ENV lines (NODE_ENV and PORT) unchanged to preserve
functionality while making the example minimal.
- Around line 13-17: Remove the non-root user setup from the example Dockerfile
by deleting the commands that create/modify a user/group and switch to it (e.g.,
any RUN groupadd/useradd/chown lines and the USER directive); keep the existing
COPY package*.json ./ and RUN npm ci --omit=dev steps and any subsequent
build/runtime commands, so the image runs as the default root user as intended
for AgentCore Runtime examples.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-basic-dockerfile/test-invoke.js`:
- Around line 78-81: The branch that handles readable streams currently calls
await body.read() once (using body.read and TextDecoder) which can return
partial data; replace this with a for await...of loop over body to fully consume
the stream (same pattern as the earlier branch), accumulate chunks, decode them
with TextDecoder, and then parse/assign to text as before so the complete
payload is read.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/langgraph-streaming/index.js`:
- Around line 154-167: The for-await loop destructures each item as [message,
metadata] but never uses metadata; update the loop to only destructure the used
value by changing the iteration to extract just message (e.g., for await (const
[message] of stream) or restructure to for await (const message of stream)
depending on stream item shape) in the block that contains message._getType()
and yield message.content so the unused metadata variable is removed; edit the
loop around the stream iteration in this file (references: stream, message,
metadata, message._getType).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/package.json`:
- Around line 1-18: Add the npm "private": true field to the example
package.json for the "strands-browser" package to prevent accidental publishes;
locate the package.json JSON object containing "name": "strands-browser" and add
the "private": true property at the top-level of that JSON object (alongside
"name", "version", "description", etc.).

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/javascript/strands-browser/test-invoke.js`:
- Around line 48-55: The example creates a dead variable `chunks` in the SSE
branch — remove the unused `chunks` array and the `chunks.push(text)` call
inside the `for await (const chunk of body)` loop (the branch where
`contentType.includes('text/event-stream')` and `process.stdout.write(text)`
already handles streaming) so the loop only decodes and writes text; ensure no
other code references `chunks`.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-browser-custom/Dockerfile`:
- Around line 6-22: The Dockerfile RUN command installs many packages without
suppressing recommended packages; update the RUN in the Dockerfile (the apt-get
update && apt-get install -y ... line) to include --no-install-recommends after
install -y so apt-get install uses minimal dependencies, keeping the final rm
-rf /var/lib/apt/lists/* cleanup unchanged to reduce image size.

In
`@packages/serverless/lib/plugins/aws/bedrock-agentcore/examples/python/langgraph-code-interpreter-custom/agent.py`:
- Around line 163-165: The except block in the agent execution path currently
calls logger.error with the exception message, losing the traceback; in the
except Exception as e handler inside the function where agent execution occurs
(the block shown in agent.py), replace logger.error(f"Error during agent
execution: {e}") with logger.exception(...) so the stack trace is preserved in
logs while keeping the existing return {"error": str(e)} behavior.

@czubocha czubocha merged commit 83677fd into main Feb 19, 2026
14 checks passed
@czubocha czubocha deleted the sc-3770 branch February 19, 2026 20:25
@github-actions github-actions bot locked and limited conversation to collaborators Feb 19, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants