Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions .changeset/fix-bb-agent-empty-channel-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@aws-blocks/bb-agent": patch
---

fix(bb-agent): treat empty channelId as unset in stream()

An empty `channelId` now falls back to `conversationId` or a random UUID, preventing all streams from sharing the same channel. Empty strings are treated as unset rather than used literally.
2 changes: 1 addition & 1 deletion packages/bb-agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const agent = new Agent(scope, id, config)
| `getPendingInterrupts(conversationId)` | `Promise<Array<...>>` | Get unanswered interrupts (for reload support). |
| `getChannel(channelId)` | `Promise<RealtimeChannel>` | Get a Realtime channel for subscribing to chunks. |

`stream()` submits the message to AsyncJob and returns immediately — no API Gateway timeout risk. The agent runs asynchronously and publishes chunks to Realtime.
`stream()` submits the message to AsyncJob and returns immediately — no API Gateway timeout risk. The agent runs asynchronously and publishes chunks to Realtime. The channel ID is resolved as `options.channelId || options.conversationId || crypto.randomUUID()` — empty strings are treated as unset and fall through to the next value.

**Important: Subscribe before sending.** The agent starts emitting chunks immediately after `stream()` is called. If you subscribe to the channel after calling `stream()`, early chunks may be dropped. Always subscribe first, await `established`, then send:

Expand Down
2 changes: 1 addition & 1 deletion packages/bb-agent/src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@
import { FileBucket } from '@aws-blocks/bb-file-bucket';
import { Logger } from '@aws-blocks/bb-logger';
import type { ChildLogger } from '@aws-blocks/bb-logger';
import { Agent as StrandsAgent, tool, SessionManager, ModelStreamUpdateEvent, AfterToolCallEvent, BeforeToolCallEvent, AgentResultEvent, InterruptEvent } from '@strands-agents/sdk';

Check warning on line 12 in packages/bb-agent/src/agent.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/correctness/noUnusedImports

Several of these imports are unused.
import type { AgentResult } from '@strands-agents/sdk';

Check warning on line 13 in packages/bb-agent/src/agent.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/correctness/noUnusedImports

This import is unused.
import { InterruptResponseContent } from '@strands-agents/sdk';
import { z } from 'zod';
import { createStrandsModel, checkModelHealth } from './model-factory.js';
import type { SnapshotStorage } from '@strands-agents/sdk';
import { messageSchema, conversationSchema, agentStreamChunkSchema } from './schemas.js';
import type { AgentConfig, AgentStreamChunk, AgentStreamResult, StreamOptions, Message, Conversation, TokenUsage, ConversationManagerConfig, ModelConfig, JSONValue, InterruptResponse, DefaultToolContext, AgentTool, ToolDefinition } from './types.js';

Check warning on line 19 in packages/bb-agent/src/agent.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/correctness/noUnusedImports

Several of these imports are unused.
import { AgentErrors, blocksAgentError, InterruptError } from './errors.js';
import { SlidingWindowConversationManager, SummarizingConversationManager } from '@strands-agents/sdk';
import { BB_NAME, BB_VERSION } from './version.js';
Expand Down Expand Up @@ -67,7 +67,7 @@
* @see https://strandsagents.com/docs/user-guide/concepts/agents/conversation-management/
*/
function createConversationManager(config?: ConversationManagerConfig) {
if (!config || !config.strategy || config.strategy === 'sliding-window') {

Check warning on line 70 in packages/bb-agent/src/agent.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/complexity/useOptionalChain

Change to an optional chain.
const windowSize = config && 'windowSize' in config ? config.windowSize : undefined;
return new SlidingWindowConversationManager({ windowSize });
}
Expand Down Expand Up @@ -313,13 +313,13 @@

const strandsTools = toolDefs.map(t => tool({
// `name` is always set by resolveTools() from the Record key.
name: t.name!,

Check warning on line 316 in packages/bb-agent/src/agent.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/style/noNonNullAssertion

Forbidden non-null assertion.
description: t.description,
inputSchema: t.parameters,
callback: (input, context) => t.handler({
input,
context: readContext(context),
interrupt: (params) => context!.interrupt(params),

Check warning on line 322 in packages/bb-agent/src/agent.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/style/noNonNullAssertion

Forbidden non-null assertion.
}),
}));

Expand Down Expand Up @@ -403,7 +403,7 @@
*/
async stream(message: string, options?: StreamOptions<TContext>): Promise<AgentStreamResult> {
const conversationId = options?.conversationId;
const channelId = options?.channelId ?? conversationId ?? crypto.randomUUID();
const channelId = options?.channelId || conversationId || crypto.randomUUID();
if (!options?.userId && !this.config.inferenceOnly) throw blocksAgentError(AgentErrors.PersistenceRequired, 'userId is required when persistence is enabled. Pass it via options.userId.');
const userId = options?.userId ?? 'anonymous';
const context = this.resolveContext(options?.context);
Expand Down
20 changes: 20 additions & 0 deletions packages/bb-agent/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,26 @@
});
});

// ── stream() empty channelId fallback ────────────────────────────────────────

describe('stream() empty channelId fallback', () => {
test('empty channelId is treated as unset', async () => {
const scope = new Scope('test-empty-ch');
const agent = new Agent(scope, 'ec', { systemPrompt: 'test', model: { deployed: { provider: 'canned' }, local: { provider: 'canned' } } });
const result = await agent.stream('hello', { userId: 'test-user', channelId: '' });
assert.notStrictEqual(result.channelId, '');
assert.ok(result.channelId.length > 0);
});

test('empty conversationId is treated as unset', async () => {
const scope = new Scope('test-empty-conv');
const agent = new Agent(scope, 'ev', { systemPrompt: 'test', model: { deployed: { provider: 'canned' }, local: { provider: 'canned' } } });
const result = await agent.stream('hello', { userId: 'test-user', conversationId: '' });
assert.notStrictEqual(result.channelId, '');
assert.ok(result.channelId.length > 0);
});
});

// ── tool factory enforcement (compile-time) ──────────────────────────────────

describe('tool factory enforcement', () => {
Expand Down Expand Up @@ -727,7 +747,7 @@

await chat.sendMessage('hello');
// Simulate error chunk from server
chunkHandler!({ type: 'error', error: 'model throttled' });

Check warning on line 750 in packages/bb-agent/src/index.test.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/style/noNonNullAssertion

Forbidden non-null assertion.

assert.strictEqual(errorReceived, 'model throttled');
assert.strictEqual(loadingStates.at(-1), false, 'loading should be false after error');
Expand All @@ -753,11 +773,11 @@
});

await chat.sendMessage('hello');
chunkHandler!({ type: 'interrupt', interrupts: [{ id: 'int-1', name: 'approve:deleteRecords', reason: { tool: 'deleteRecords' } }] });

Check warning on line 776 in packages/bb-agent/src/index.test.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/style/noNonNullAssertion

Forbidden non-null assertion.

assert.ok(interruptsReceived, 'onInterrupt should be called');
assert.strictEqual(interruptsReceived!.length, 1);

Check warning on line 779 in packages/bb-agent/src/index.test.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/style/noNonNullAssertion

Forbidden non-null assertion.
assert.strictEqual(interruptsReceived![0].name, 'approve:deleteRecords');

Check warning on line 780 in packages/bb-agent/src/index.test.ts

View workflow job for this annotation

GitHub Actions / Build, Unit Tests, E2E Local

lint/style/noNonNullAssertion

Forbidden non-null assertion.
assert.strictEqual(loadingStates.at(-1), false, 'loading should be false after interrupt');
});

Expand Down
2 changes: 1 addition & 1 deletion packages/bb-agent/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ export interface ToolCallRecord {

export interface StreamOptions<TContext = DefaultToolContext> {
conversationId?: string;
/** Channel ID for Realtime delivery. Defaults to conversationId or a random UUID. */
/** Channel ID for Realtime delivery. Defaults to conversationId or a random UUID. Empty strings are treated as unset. */
channelId?: string;
/** User ID for conversation scoping. Defaults to 'anonymous'. */
userId?: string;
Expand Down
Loading