π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(agent-runtime): default extensible agent loop with an explicit stop reason (#19153)
Arvin Xu8631512dded6
diff --git a/packages/agent-runtime/examples/tools-calling.ts b/packages/agent-runtime/examples/tools-calling.tsindex cd513a1d347..a0b4dbebb0c 100644--- a/packages/agent-runtime/examples/tools-calling.ts+++ b/packages/agent-runtime/examples/tools-calling.ts@@ -2,7 +2,7 @@import OpenAI from 'openai';import type { Agent, AgentRuntimeContext, AgentState } from '../src';-import { AgentRuntime } from '../src';+import { AgentRuntime, runAgentLoop } from '../src';// OpenAI model runtimeasync function* openaiRuntime(payload: any) {@@ -248,7 +248,7 @@ async function main() {console.log(`π¬ User: ${testMessage}\n`);// Create initial state- let state = AgentRuntime.createInitialState({+ const state = AgentRuntime.createInitialState({maxSteps: 10,messages: [{ content: testMessage, role: 'user' }],sessionId: 'simple-test',@@ -256,48 +256,49 @@ async function main() {console.log('π€ AI: ');- // Execute conversation loop- let nextContext: AgentRuntimeContext | undefined = undefined;-- while (state.status !== 'done' && state.status !== 'error') {- const result = await runtime.step(state, nextContext);-- // Process events- for (const event of result.events) {- switch (event.type) {- case 'llm_stream': {- if ((event as any).chunk.content) {- process.stdout.write((event as any).chunk.content);+ // Termination is the loop's job; this only says what one step does and how+ // its events are rendered.+ const outcome = await runAgentLoop({+ state,+ step: async ({ context, state: currentState }) => {+ const result = await runtime.step(currentState, context);++ // Process events+ for (const event of result.events) {+ switch (event.type) {+ case 'llm_stream': {+ if ((event as any).chunk.content) {+ process.stdout.write((event as any).chunk.content);+ }+ break;}- break;- }- case 'llm_result': {- if ((event as any).result.tool_calls) {- console.log('\n\nπ§ Calling tools...');+ case 'llm_result': {+ if ((event as any).result.tool_calls) {+ console.log('\n\nπ§ Calling tools...');+ }+ break;+ }+ case 'tool_result': {+ console.log(`\nπ οΈ Tool execution result:`, event.result);+ console.log('\nπ€ AI: ');+ break;+ }+ case 'done': {+ console.log('\n\nβ Conversation complete');+ break;+ }+ case 'error': {+ console.error('\nβ Error:', event.error);+ break;}- break;- }- case 'tool_result': {- console.log(`\nπ οΈ Tool execution result:`, event.result);- console.log('\nπ€ AI: ');- break;- }- case 'done': {- console.log('\n\nβ Conversation complete');- break;- }- case 'error': {- console.error('\nβ Error:', event.error);- break;}}- }- state = result.newState;- nextContext = result.nextContext; // use the returned nextContext- }+ return { nextContext: result.nextContext, state: result.newState };+ },+ });- console.log(`\nπ Total steps executed: ${state.stepCount}`);+ console.log(`\nπ Total steps executed: ${outcome.stepCount} (stopped: ${outcome.reason})`);}main().catch(console.error);diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.tsindex 11a8b968866..43608702d51 100644--- a/packages/agent-runtime/src/index.ts+++ b/packages/agent-runtime/src/index.ts@@ -3,6 +3,7 @@ export * from './audit';export * from './core';export * from './executors';export * from './groupOrchestration';+export * from './loop';export * from './transport';export * from './types';export * from './utils';diff --git a/packages/agent-runtime/src/loop/index.test.ts b/packages/agent-runtime/src/loop/index.test.tsnew file mode 100644index 00000000000..26f68bf35d9--- /dev/null+++ b/packages/agent-runtime/src/loop/index.test.ts@@ -0,0 +1,188 @@+import { describe, expect, it, vi } from 'vitest';++import type { AgentRuntimeContext, AgentState } from '../types';+import { type AgentLoopStep, resolveStopReason, runAgentLoop } from './index';++const createState = (overrides: Partial<AgentState> = {}): AgentState =>+ ({+ cost: { total: 0 },+ maxSteps: 100,+ messages: [],+ operationId: 'op-1',+ status: 'running',+ stepCount: 0,+ ...overrides,+ }) as AgentState;++const context = (phase = 'user_input') => ({ payload: {}, phase }) as AgentRuntimeContext;++/** A step that runs `count` times, then produces no next context. */+const finiteStep = (count: number): AgentLoopStep => {+ let remaining = count;+ return async ({ state }) => {+ remaining -= 1;+ return { nextContext: remaining > 0 ? context('tool_result') : undefined, state };+ };+};++describe('resolveStopReason', () => {+ it.each([+ ['done', 'done'],+ ['error', 'error'],+ ['interrupted', 'interrupted'],+ ['waiting_for_human', 'parked'],+ ['waiting_for_async_tool', 'parked'],+ ] as const)('maps status %s to %s', (status, reason) => {+ expect(resolveStopReason(createState({ status }), context())).toBe(reason);+ });++ it('reports a missing next context rather than looping on nothing', () => {+ expect(resolveStopReason(createState(), undefined)).toBe('no_next_context');+ });++ it('continues while running with a context to feed forward', () => {+ expect(resolveStopReason(createState(), context())).toBeUndefined();+ });++ it('stops on an exhausted cost budget only when configured to stop', () => {+ const exceeded = (onExceeded: 'stop' | 'warn' | 'interrupt') =>+ createState({+ cost: { total: 10 } as never,+ costLimit: { currency: 'USD', maxTotalCost: 5, onExceeded },+ });++ expect(resolveStopReason(exceeded('stop'), context())).toBe('cost_limit');+ // `warn` and `interrupt` settle up elsewhere; the loop keeps going.+ expect(resolveStopReason(exceeded('warn'), context())).toBeUndefined();+ expect(resolveStopReason(exceeded('interrupt'), context())).toBeUndefined();+ });+});++describe('runAgentLoop', () => {+ it('feeds each step the previous stepβs next context', async () => {+ const seen: (string | undefined)[] = [];+ const step: AgentLoopStep = async ({ context: ctx, state, stepIndex }) => {+ seen.push(ctx?.phase);+ return {+ nextContext: stepIndex < 2 ? context(`after-${stepIndex}`) : undefined,+ state,+ };+ };++ const result = await runAgentLoop({ initialContext: context('start'), state: createState(), step });++ expect(seen).toEqual(['start', 'after-0', 'after-1']);+ expect(result.stepCount).toBe(3);+ expect(result.reason).toBe('no_next_context');+ });++ it('does not step a state that is already finished', async () => {+ const step = vi.fn();++ const result = await runAgentLoop({+ initialContext: context(),+ state: createState({ status: 'done' }),+ step,+ });++ // Resuming a parked or finished operation is a different entry point.+ // Stepping it again here would run a turn the host never asked for.+ expect(step).not.toHaveBeenCalled();+ expect(result.reason).toBe('done');+ expect(result.stepCount).toBe(0);+ });++ it('stops as soon as a step parks the run', async () => {+ const step: AgentLoopStep = async ({ state }) => ({+ nextContext: context('tool_result'),+ state: { ...state, status: 'waiting_for_human' },+ });++ const result = await runAgentLoop({ initialContext: context(), state: createState(), step });++ // The browser loop condition (`!== 'done' && !== 'error'`) would have run+ // another step here; it only escaped because its steps happen to return no+ // next context when parked. This makes the rule explicit instead.+ expect(result.reason).toBe('parked');+ expect(result.stepCount).toBe(1);+ });++ it('honours the caller step budget separately from state.maxSteps', async () => {+ const step = vi.fn(async ({ state }: { state: AgentState }) => ({+ nextContext: context('tool_result'),+ state,+ }));++ const result = await runAgentLoop({+ initialContext: context(),+ maxSteps: 3,+ state: createState(),+ step: step as AgentLoopStep,+ });++ expect(step).toHaveBeenCalledTimes(3);+ expect(result.reason).toBe('max_steps');+ // The context the next step would have received survives, so a caller can+ // resume from exactly where the budget ran out.+ expect(result.context?.phase).toBe('tool_result');+ });++ it('runs a turn that opens with no context', async () => {+ const step = vi.fn(async ({ state }: { state: AgentState }) => ({+ state: { ...state, status: 'done' } as AgentState,+ }));++ // "No next context" describes what a step PRODUCED, so it cannot be asked+ // before the first step. A run legitimately opens without one β treating+ // that as a stop would end every loop before it began.+ const result = await runAgentLoop({ state: createState(), step: step as AgentLoopStep });++ expect(step).toHaveBeenCalledTimes(1);+ expect(result.reason).toBe('done');+ });++ it('reports each completed step to the caller', async () => {+ const seen: number[] = [];++ await runAgentLoop({+ initialContext: context(),+ onStepComplete: (stepIndex) => {+ seen.push(stepIndex);+ },+ state: createState(),+ step: finiteStep(3),+ });++ expect(seen).toEqual([1, 2, 3]);+ });++ it('lets a host add a termination rule of its own', async () => {+ const step = vi.fn(async ({ state }: { state: AgentState }) => ({+ nextContext: context('tool_result'),+ state,+ }));++ const result = await runAgentLoop({+ initialContext: context(),+ resolveStop: (state, ctx) => (state.stepCount >= 0 && ctx?.phase === 'tool_result'+ ? 'interrupted'+ : resolveStopReason(state, ctx)),+ state: createState(),+ step: step as AgentLoopStep,+ });++ expect(step).toHaveBeenCalledTimes(1);+ expect(result.reason).toBe('interrupted');+ });++ it('surfaces the final state, not the one it started from', async () => {+ const step: AgentLoopStep = async ({ state }) => ({+ state: { ...state, status: 'done', stepCount: state.stepCount + 1 },+ });++ const result = await runAgentLoop({ initialContext: context(), state: createState(), step });++ expect(result.state.status).toBe('done');+ expect(result.state.stepCount).toBe(1);+ });+});diff --git a/packages/agent-runtime/src/loop/index.ts b/packages/agent-runtime/src/loop/index.tsnew file mode 100644index 00000000000..00a4ab2aed7--- /dev/null+++ b/packages/agent-runtime/src/loop/index.ts@@ -0,0 +1,167 @@+import type { AgentRuntimeContext, AgentState } from '../types';+import { isParkedStatus } from '../utils/status';++/**+ * Why a loop stopped.+ *+ * Every host re-derived this after the fact β the server to decide whether to+ * emit `max_steps` completion signals, the client to choose between a terminal+ * lifecycle event and the parked one. Making it the loop's output is the point+ * of this module: a stop reason that is computed once cannot drift between+ * hosts the way the termination conditions did.+ */+export type AgentLoopStopReason =+ | 'done'+ | 'error'+ | 'interrupted'+ /** Non-terminal pause: human approval, or an async tool / sub-agent result. */+ | 'parked'+ /** Cost budget exhausted and configured to stop. */+ | 'cost_limit'+ /** The caller's step budget, distinct from `state.maxSteps`. */+ | 'max_steps'+ /** The step produced nothing to feed the next one. */+ | 'no_next_context';++export interface AgentLoopStepInput {+ context?: AgentRuntimeContext;+ state: AgentState;+ /** Zero-based index of the step about to run. */+ stepIndex: number;+}++export interface AgentLoopStepResult {+ nextContext?: AgentRuntimeContext;+ state: AgentState;+}++/**+ * One step, supplied by the host.+ *+ * The loop deliberately does NOT call `runtime.step` itself. A step means very+ * different things per host β on the server it claims a distributed lock,+ * persists state, dispatches hooks and records a trace; in the browser and on a+ * device it is a direct `runtime.step`. Collapsing those into one function is+ * how a shared loop turns into something every host has to work around.+ */+export type AgentLoopStep = (input: AgentLoopStepInput) => Promise<AgentLoopStepResult>;++export interface RunAgentLoopOptions {+ initialContext?: AgentRuntimeContext;+ /**+ * Caller-imposed step budget. Separate from `state.maxSteps`, which+ * `runtime.step` enforces by forcing the state to `done`.+ */+ maxSteps?: number;+ onStepComplete?: (stepIndex: number, state: AgentState) => Promise<void> | void;+ /**+ * Replaces the built-in stop check. Return a reason to stop, or `undefined`+ * to continue β for a host with an extra termination condition of its own.+ */+ resolveStop?: (+ state: AgentState,+ context?: AgentRuntimeContext,+ ) => AgentLoopStopReason | undefined;+ state: AgentState;+ step: AgentLoopStep;+}++export interface AgentLoopResult {+ context?: AgentRuntimeContext;+ reason: AgentLoopStopReason;+ state: AgentState;+ /** Steps actually executed by this loop. */+ stepCount: number;+}++/**+ * Stop conditions that depend only on the state itself.+ *+ * Separate from {@link resolveStopReason} because "no next context" is a+ * statement about what a step PRODUCED, and so cannot be asked before the+ * first step has run. A run legitimately starts with no context β the caller+ * either supplies one or lets the agent open the turn β and treating that as a+ * stop would end every loop before it began.+ */+export const resolveTerminalReason = (state: AgentState): AgentLoopStopReason | undefined => {+ if (state.status === 'done') return 'done';+ if (state.status === 'error') return 'error';+ if (state.status === 'interrupted') return 'interrupted';+ if (isParkedStatus(state.status)) return 'parked';++ // Exceeding the budget only stops a run that asked to be stopped; other+ // policies let it continue and settle up elsewhere.+ const costLimit = state.costLimit;+ if (+ costLimit &&+ (state.cost?.total ?? 0) >= costLimit.maxTotalCost &&+ costLimit.onExceeded === 'stop'+ )+ return 'cost_limit';++ return undefined;+};++/**+ * Decide whether a loop should stop after a step, and why.+ *+ * Extracted from the server's `shouldContinueExecution`, which was the only+ * complete statement of these rules; the browser approximated the same thing+ * with a `done`/`error` while-condition plus "no next context", and the two+ * agreed only by coincidence.+ *+ * `context` is the context the NEXT step would receive β absent means the+ * previous step produced nothing to continue from.+ */+export const resolveStopReason = (+ state: AgentState,+ context?: AgentRuntimeContext,+): AgentLoopStopReason | undefined =>+ resolveTerminalReason(state) ?? (context ? undefined : 'no_next_context');++/**+ * Drive an agent to a stopping point, one host-supplied step at a time.+ *+ * Owns exactly two things: when to stop, and what context the next step gets.+ * Everything inside a step β persistence, hooks, streaming, quota β stays with+ * the host, because those are what differ between the server, the browser and+ * a device.+ */+export const runAgentLoop = async (options: RunAgentLoopOptions): Promise<AgentLoopResult> => {+ const { initialContext, maxSteps, onStepComplete, resolveStop, state, step } = options;+ const stopCheck = resolveStop ?? resolveStopReason;++ let currentState = state;+ let currentContext = initialContext;+ let stepCount = 0;++ // Checked before the first step too β a state handed in already `done`,+ // `interrupted` or parked must not be stepped again, since resuming a parked+ // operation is a separate entry point rather than another turn of this loop.+ // Status only: a run may legitimately open with no context.+ let reason = resolveTerminalReason(currentState);++ while (!reason) {+ if (maxSteps !== undefined && stepCount >= maxSteps) return finish('max_steps');++ const result = await step({+ context: currentContext,+ state: currentState,+ stepIndex: stepCount,+ });++ currentState = result.state;+ currentContext = result.nextContext;+ stepCount += 1;++ await onStepComplete?.(stepCount, currentState);++ reason = stopCheck(currentState, currentContext);+ }++ return finish(reason);++ function finish(stopReason: AgentLoopStopReason): AgentLoopResult {+ return { context: currentContext, reason: stopReason, state: currentState, stepCount };+ }+};