Skip to content
Merged
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 packages/sdk/src/plugins/limits-guard/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { llmEvents } from '~/core/llm/state.js'
import { definePlugin } from '~/core/plugins/plugin-builder.js'
import { selectPluginState } from '~/core/sessions/reducer.js'
import type { SessionState } from '~/core/sessions/state.js'
import type { ToolCallId } from '~/core/tools/schema.js'
import { toolEvents } from '~/core/tools/state.js'
import { responseFingerprint, toolCallFingerprint } from '~/lib/utils/hash.js'
import { mailboxEvents } from '~/plugins/mailbox/state.js'
Expand All @@ -25,6 +26,8 @@ import {
export interface AgentCounters {
inferenceCount: number
toolCallCount: number
/** Agents execute tools serially; recovery can start the same unfinished call again. */
countedToolCallId?: ToolCallId
spawnedAgentCount: number
messagesSentCount: number
/** Consecutive outbound-only turns with no newly consumed inbound work. */
Expand Down Expand Up @@ -259,12 +262,14 @@ export const limitsGuardPlugin = definePlugin('limits-guard')
case 'tool_started': {
const counters = limits.get(event.agentId)
if (!counters) return limits
if (counters.countedToolCallId === event.toolCallId) return limits

const fingerprint = toolCallFingerprint(event.toolName, event.input)
const newLimits = new Map(limits)
newLimits.set(event.agentId, {
...counters,
toolCallCount: counters.toolCallCount + 1,
countedToolCallId: event.toolCallId,
recentToolCallHashes: [...counters.recentToolCallHashes, fingerprint].slice(-20),
})
return newLimits
Expand All @@ -282,6 +287,7 @@ export const limitsGuardPlugin = definePlugin('limits-guard')
newLimits.set(event.agentId, {
...counters,
consecutiveToolFailures: restFailures,
countedToolCallId: undefined,
})
return newLimits
}
Expand All @@ -301,6 +307,7 @@ export const limitsGuardPlugin = definePlugin('limits-guard')
...counters.consecutiveToolFailures,
[toolName]: { count: (currentEntry?.count ?? 0) + 1, lastError: event.error },
},
countedToolCallId: undefined,
})
return newLimits
}
Expand Down
96 changes: 96 additions & 0 deletions packages/sdk/src/plugins/limits-guard/recovery.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { describe, expect, it } from 'bun:test'
import { AgentId } from '~/core/agents/schema.js'
import { agentEvents } from '~/core/agents/state.js'
import { withSessionId } from '~/core/events/test-helpers.js'
import type { DomainEvent } from '~/core/events/types.js'
import { createApplyEvent } from '~/core/sessions/apply-event.js'
import { SessionId } from '~/core/sessions/schema.js'
import { createSessionState, sessionEvents } from '~/core/sessions/state.js'
import { ToolCallId } from '~/core/tools/schema.js'
import { toolEvents } from '~/core/tools/state.js'
import { limitsGuardPlugin, selectAgentCounters } from './plugin.js'
import { checkLimits, resolveAgentLimits } from './limit-guard.js'

const sessionId = SessionId('limits-recovery')
const agentId = AgentId('worker')
const applyEvent = createApplyEvent([limitsGuardPlugin.create({})])
const spawn = withSessionId(
sessionId,
agentEvents.create('agent_spawned', {
agentId,
definitionName: 'worker',
parentId: null,
}),
)
const start = (id: string) =>
withSessionId(
sessionId,
toolEvents.create('tool_started', {
agentId,
toolCallId: ToolCallId(id),
toolName: 'run_command',
input: { command: 'sleep 60' },
}),
)
const restart = withSessionId(
sessionId,
sessionEvents.create('session_restarted', {
resetAgentIds: [],
clearedToolAgentIds: [agentId],
}),
)
const counters = (events: DomainEvent[]) => selectAgentCounters(events.reduce(applyEvent, createSessionState(sessionId, 'test', 0)), agentId)

describe('limits during tool recovery', () => {
it('counts one in-flight call once across repeated restart events and replay', () => {
const events = [spawn, start('call-1'), restart, start('call-1'), restart, start('call-1'), restart, start('call-1')]
const result = counters(events)
expect(result.toolCallCount).toBe(1)
expect(result.recentToolCallHashes).toHaveLength(1)
expect(checkLimits(result, resolveAgentLimits()).status).toBe('ok')
expect(counters(events)).toEqual(result)
})

it('still counts completed identical calls as separate work', () => {
const events: DomainEvent[] = [spawn]
for (let i = 0; i < 4; i++) {
const id = ToolCallId(`call-${i}`)
events.push(
start(id),
withSessionId(
sessionId,
toolEvents.create('tool_completed', {
agentId,
toolCallId: id,
result: 'done',
}),
),
)
}
const result = counters(events)
expect(result.toolCallCount).toBe(4)
expect(result.recentToolCallHashes).toHaveLength(4)
expect(new Set(result.recentToolCallHashes).size).toBe(1)
expect(checkLimits(result, resolveAgentLimits())).toMatchObject({ status: 'hard_limit', limitName: 'maxRepeatedToolCalls' })
})

it('clears the unfinished-call marker on failure without losing failure accounting', () => {
const result = counters([
spawn,
start('call-1'),
restart,
start('call-1'),
withSessionId(
sessionId,
toolEvents.create('tool_failed', {
agentId,
toolCallId: ToolCallId('call-1'),
error: 'command failed',
}),
),
])
expect(result.toolCallCount).toBe(1)
expect(result.countedToolCallId).toBeUndefined()
expect(Object.values(result.consecutiveToolFailures)).toEqual([{ count: 1, lastError: 'command failed' }])
})
})
Loading