Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions harness-py/src/strands_harness/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,8 @@ def create_harness(
read-only; a ``MemoryManager`` instance is used verbatim and not forwarded to delegates;
``False``/``None`` disables it. An explicit ``memory_manager`` in ``agent_kwargs`` takes
precedence. Extraction runs asynchronously every few turns on a small model, so a short run
may end before the first extraction fires; run
``if agent.memory_manager: await agent.memory_manager.flush()`` at your shutdown boundary to
may end before the first extraction fires; scope the agent with ``async with agent:`` to
run its shutdown on exit, or call ``await agent.shutdown()`` at your shutdown boundary, to
persist what's pending.
builtin_plugins: Names of the built-in feature plugins to enable. Defaults to
``["todos", "environment"]``: ``todos`` adds a ``todo_write`` tool that tracks
Expand Down
5 changes: 3 additions & 2 deletions harness-py/src/strands_harness/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
session: memory survives across sessions and works with sessions off.

Extraction is background and turn-triggered, so a short run can end with the latest turns unsaved.
The owner of the agent's lifecycle flushes at shutdown (``await agent.memory_manager.flush()``) to
persist what's pending; the harness's CLI does this, and a library consumer should do the same.
Scoping the agent with ``async with agent:`` runs its shutdown on exit, or the owner of the agent's
lifecycle calls ``await agent.shutdown()`` at shutdown; the harness's CLI does the latter, and a
library consumer should do one or the other.

A consumer can swap the backend by passing their own ``stores``; the harness still owns the manager, so its
injection/tool policy (injection on, ``search_memory`` on, ``add_memory`` off) applies either way.
Expand Down
5 changes: 3 additions & 2 deletions harness-ts/src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,9 @@ export interface HarnessAgentOptions extends Omit<
* when an explicit `memoryManager` is passed.
*
* Extraction is background and turn-triggered, so a short run may end before the first extraction
* fires and the latest turns are unsaved when the agent responds. Call
* `await agent.memoryManager?.flush()` at your shutdown boundary to persist what's pending.
* fires and the latest turns are unsaved when the agent responds. Bind the agent with `await using`
* to run its shutdown on scope exit, or call `await agent.shutdown()` at your shutdown boundary,
* to persist what's pending.
*/
memory?: boolean | MemoryConfig | MemoryManager | null
/**
Expand Down
27 changes: 23 additions & 4 deletions site/src/content/docs/user-guide/harness/configure/memory.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -102,18 +102,37 @@ Pass `False`/`null` (or set `memory` off) to disable memory entirely:
## Flush before a short run exits

Extraction is background and turn-triggered, so a short run can end with its latest turns
not yet written. Flush at your shutdown boundary to persist what is pending:
not yet written. The simplest way to persist what is pending is to scope the agent so its
shutdown runs when the block exits — on a normal return and on a thrown error alike:

<Tabs>
<Tab label="Python">
```python
if agent.memory_manager:
await agent.memory_manager.flush()
async with create_harness() as agent:
await agent.invoke_async(task)
# the agent's shutdown runs here as the scope exits, flushing pending memory
```
</Tab>
<Tab label="TypeScript">
```typescript
await agent.memoryManager?.flush()
await using agent = await createHarness()
await agent.invoke(task)
// the agent's shutdown runs here as the scope exits, flushing pending memory
```
</Tab>
</Tabs>

If you manage the agent's lifetime yourself, run its shutdown at your shutdown boundary:

<Tabs>
<Tab label="Python">
```python
await agent.shutdown()
```
</Tab>
<Tab label="TypeScript">
```typescript
await agent.shutdown()
```
</Tab>
</Tabs>
Expand Down
16 changes: 16 additions & 0 deletions site/src/content/docs/user-guide/sdk/memory/managing-memory.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,14 @@ Whether you need to flush manually depends on how you call the agent:
# After driving the agent with invoke_async / stream_async, before the loop closes.
await memory_manager.flush()
```

`await agent.shutdown()` does the same flush through the agent, and scoping the agent with `async with agent:` runs that shutdown when the block exits, including on a thrown error:

```python
async with agent:
await agent.invoke_async("Summarize the conversation so far")
# agent.shutdown() runs here as the scope exits, flushing pending memory
```
</Tab>
<Tab label="TypeScript">

Expand All @@ -318,6 +326,14 @@ The agent loop never flushes for you, on any call path. Await `flush()` as part
```typescript
--8<-- "user-guide/sdk/memory/managing-memory.ts:flush"
```

`await agent.shutdown()` does the same flush through the agent, and binding the agent with `await using` runs that shutdown when the scope exits, including on a thrown error:

```typescript
await using agent = new Agent({ model, memoryManager })
await agent.invoke('Summarize the conversation so far')
// agent.shutdown() runs here as the scope exits, flushing pending memory
```
</Tab>
</Tabs>

Expand Down
24 changes: 24 additions & 0 deletions strands-py/src/strands/agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,30 @@ def concurrent_invocation_mode(self) -> ConcurrentInvocationMode:
"""
return self._concurrency.mode

async def shutdown(self) -> None:
Comment thread
opieter-aws marked this conversation as resolved.
Resolved
"""Run the agent's shutdown procedures at end of life.

Safe to call more than once, and a no-op when there is nothing to release. Call it directly
when you own the agent's lifecycle (e.g. draining on a shutdown signal), or scope the agent
with ``async with`` to run it automatically on exit.
"""
if self.memory_manager is not None:
Comment thread
opieter-aws marked this conversation as resolved.
Resolved
await self.memory_manager.flush()

async def __aenter__(self) -> "Agent":
"""Enter an ``async with`` scope, returning the agent unchanged.

Pairs with ``__aexit__``, which runs :meth:`shutdown` when the scope exits.
"""
return self

async def __aexit__(self, *_: Any) -> None:
"""Run :meth:`shutdown` when leaving an ``async with`` scope.

Runs on normal exit and when the block raises; any exception still propagates.
"""
await self.shutdown()

def __call__(
self,
prompt: AgentInput = None,
Expand Down
57 changes: 57 additions & 0 deletions strands-py/tests/strands/agent/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -3135,6 +3135,63 @@ async def test_agent_async_invoke_does_not_flush_memory_manager():
memory_manager.flush.assert_not_awaited()


@pytest.mark.asyncio
async def test_agent_shutdown_flushes_memory_manager():
memory_manager = MemoryManager(stores=[_SearchOnlyStore()])
memory_manager.flush = unittest.mock.AsyncMock()
agent = Agent(
model=MockedModelProvider([{"role": "assistant", "content": [{"text": "response"}]}]),
memory_manager=memory_manager,
)

await agent.shutdown()

memory_manager.flush.assert_awaited_once()


@pytest.mark.asyncio
async def test_agent_async_context_manager_flushes_memory_manager_on_exit():
memory_manager = MemoryManager(stores=[_SearchOnlyStore()])
memory_manager.flush = unittest.mock.AsyncMock()
agent = Agent(
model=MockedModelProvider([{"role": "assistant", "content": [{"text": "response"}]}]),
memory_manager=memory_manager,
)

async with agent as entered:
assert entered is agent
await agent.invoke_async("test")
memory_manager.flush.assert_not_awaited()

memory_manager.flush.assert_awaited_once()


@pytest.mark.asyncio
async def test_agent_async_context_manager_flushes_and_propagates_on_error():
memory_manager = MemoryManager(stores=[_SearchOnlyStore()])
memory_manager.flush = unittest.mock.AsyncMock()
agent = Agent(
model=MockedModelProvider([{"role": "assistant", "content": [{"text": "response"}]}]),
memory_manager=memory_manager,
)

with pytest.raises(RuntimeError, match="boom"):
async with agent:
raise RuntimeError("boom")

memory_manager.flush.assert_awaited_once()


@pytest.mark.asyncio
async def test_agent_async_context_manager_without_memory_manager_is_noop():
agent = Agent(model=MockedModelProvider([{"role": "assistant", "content": [{"text": "response"}]}]))

async with agent:
pass

assert agent.memory_manager is None


def test_as_tool_returns_agent_tool():
"""Test that as_tool returns an _AgentAsTool wrapping the agent."""
agent = Agent(name="researcher", description="Finds information")
Expand Down
62 changes: 61 additions & 1 deletion strands-ts/src/agent/__tests__/agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ import {
VideoBlock,
DocumentBlock,
} from '../../index.js'
import type { InvokeOptions } from '../../index.js'
import type { InvokeOptions, MemoryStore } from '../../index.js'
import { MemoryManager } from '../../index.js'
import { AgentPrinter } from '../printer.js'
import {
AfterInvocationEvent,
Expand Down Expand Up @@ -2474,4 +2475,63 @@ describe('normalizeToolUseNames', () => {
expect(sessionIds).toEqual(['s1', 's2'])
})
})

describe('shutdown and async disposal', () => {
const searchOnlyStore = (): MemoryStore => ({
name: 'notes',
writable: false,
search: vi.fn().mockResolvedValue([]),
})

it('flushes the memory manager when shutdown is called directly', async () => {
const memoryManager = new MemoryManager({ stores: [searchOnlyStore()] })
const flush = vi.spyOn(memoryManager, 'flush')
const model = new MockMessageModel().addTurn({ type: 'textBlock', text: 'Hello' })
const agent = new Agent({ model, memoryManager })

await agent.shutdown()

expect(flush).toHaveBeenCalledTimes(1)
})

it('flushes the memory manager when an `await using` scope exits', async () => {
const memoryManager = new MemoryManager({ stores: [searchOnlyStore()] })
const flush = vi.spyOn(memoryManager, 'flush')
const model = new MockMessageModel().addTurn({ type: 'textBlock', text: 'Hello' })

{
await using agent = new Agent({ model, memoryManager })
await agent.invoke('Test prompt')
expect(flush).not.toHaveBeenCalled()
}

expect(flush).toHaveBeenCalledTimes(1)
})

it('flushes even when the scope exits via a thrown error', async () => {
const memoryManager = new MemoryManager({ stores: [searchOnlyStore()] })
const flush = vi.spyOn(memoryManager, 'flush')

await expect(
(async () => {
await using agent = new Agent({ model: new MockMessageModel(), memoryManager })
void agent
throw new Error('boom')
})()
).rejects.toThrow('boom')

expect(flush).toHaveBeenCalledTimes(1)
})

it('is a no-op when no memory manager is configured', async () => {
const model = new MockMessageModel().addTurn({ type: 'textBlock', text: 'Hello' })

await expect(
(async () => {
await using agent = new Agent({ model })
await agent.invoke('Test prompt')
})()
).resolves.toBeUndefined()
})
})
})
26 changes: 26 additions & 0 deletions strands-ts/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1083,6 +1083,32 @@ export class Agent implements LocalAgent, InvokableAgent {
return result.value
}

/**
* Runs the agent's shutdown procedures at end of life. Safe to call more
* than once, and a no-op when there is nothing to release.
*
* Call it directly when you own the agent's lifecycle (e.g. draining on a shutdown signal), or bind
* the agent with `await using` to run it automatically on scope exit.
*
* @example
* ```typescript
* await using agent = await createHarness()
* await agent.invoke('summarize the repo')
* // agent.shutdown() runs here as the scope exits
* ```
*/
async shutdown(): Promise<void> {
await this.memoryManager?.flush()
}

/**
* Runs {@link Agent.shutdown} when the agent leaves an `await using` scope, on normal exit and on
* throw, so its shutdown procedures run without a manual `finally`.
*/
async [Symbol.asyncDispose](): Promise<void> {
await this.shutdown()
}

/**
* Streams the agent execution, yielding events and returning the final result.
*
Expand Down
Loading