feat(agent): add invocationState support for per-request state #455
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Enables passing arbitrary state through the agent invocation lifecycle, accessible in hooks and tool contexts. Not persisted between invocations.
Description
This PR implements
invocationStatesupport for the Agentinvokeandstreammethods, achieving feature parity with the Python SDK. This allows developers to pass transient, per-request context (such asuserId,requestId, orsessionId) through the agent's lifecycle hooks and tool executions without modifying the agent's persistent state.Key Implementation Details:
Agent API (
src/agent/agent.ts)InvokeOptionsinterface:type InvokeOptions = { invocationState?: Record<string, unknown> }invoke()andstream()to acceptoptions?: InvokeOptions.invocationStatethrough the internal_streamloop to hooks and tool executors.Lifecycle Hooks (
src/hooks/events.ts)invocationStatetoBeforeInvocationEventfor request-level context.invocationStateto granular events (BeforeModelCallEvent,BeforeToolCallEvent, etc.) to enable precise tracing and logging deep in the execution stack.Tool Context (
src/tools/tool.ts)ToolContextto includeinvocationState, allowing tools to access request-specific data.Type Safety
Record<string, unknown>to ensure strict type safety (avoidingany) while allowing flexible user data.Usage Example:
Related Issues
Fixes #427
Documentation PR
(N/A - Documentation updates included in this PR via README usage examples)
Type of Change
New feature
Testing
How have you tested the change?
npm run checksrc/agent/__tests__/agent.test.tsverifyinginvocationStatepropagation to hooks and tool contexts.test/integ/agent.test.tsverifying the full flow from invocation to tool execution.Checklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.