Phase 1 run-control semantics and run_state events
This commit is contained in:
@@ -437,6 +437,90 @@ describe('daemon command fast-path integration', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('preempts active runs when queue mode is interrupt', async () => {
|
||||
const cancelSpy = vi.spyOn(AgentOrchestrator.prototype, 'cancel');
|
||||
vi.spyOn(AgentOrchestrator.prototype, 'isCancellable').mockReturnValue(true);
|
||||
const processSpy = vi.spyOn(AgentOrchestrator.prototype, 'process');
|
||||
let resolveFirst: ((value: string) => void) | undefined;
|
||||
let markStarted: (() => void) | undefined;
|
||||
const started = new Promise<void>((resolve) => { markStarted = resolve; });
|
||||
processSpy
|
||||
.mockImplementationOnce(() => {
|
||||
markStarted?.();
|
||||
return new Promise<string>((resolve) => { resolveFirst = resolve; });
|
||||
})
|
||||
.mockResolvedValueOnce('second');
|
||||
|
||||
const session = {
|
||||
id: 'telegram:user-interrupt',
|
||||
addMessage: vi.fn(),
|
||||
getHistory: vi.fn(() => []),
|
||||
clear: vi.fn(),
|
||||
replaceHistory: vi.fn(),
|
||||
getConfig: vi.fn((key: string) => (key === 'queue.mode' ? 'interrupt' : undefined)),
|
||||
setConfig: vi.fn(),
|
||||
deleteConfig: vi.fn(),
|
||||
};
|
||||
|
||||
const router = createMessageRouter({
|
||||
sessionManager: {
|
||||
getSession: vi.fn(() => session),
|
||||
} as unknown as MessageRouterDeps['sessionManager'],
|
||||
modelRouter: {
|
||||
getAvailableTiers: () => ['fast', 'default', 'complex', 'local'],
|
||||
getAllLabels: () => ({ fast: 'fast', default: 'default', complex: 'complex', local: 'local' }),
|
||||
getLabel: (tier: string) => tier,
|
||||
} as unknown as MessageRouterDeps['modelRouter'],
|
||||
systemPrompt: 'test prompt',
|
||||
toolRegistry: {
|
||||
clone() { return this; },
|
||||
register: vi.fn(),
|
||||
} as unknown as MessageRouterDeps['toolRegistry'],
|
||||
toolExecutor: {} as unknown as MessageRouterDeps['toolExecutor'],
|
||||
config: {
|
||||
agents: {
|
||||
primary_tier: 'default',
|
||||
delegation: {
|
||||
compaction: 'fast',
|
||||
memory_extraction: 'fast',
|
||||
classification: 'fast',
|
||||
tool_summarisation: 'fast',
|
||||
complex_reasoning: 'complex',
|
||||
},
|
||||
max_delegation_depth: 3,
|
||||
max_iterations: 10,
|
||||
},
|
||||
compaction: { enabled: false },
|
||||
models: { default: { provider: 'anthropic', model: 'claude' } },
|
||||
server: { queue: { mode: 'collect' } },
|
||||
} as unknown as MessageRouterDeps['config'],
|
||||
});
|
||||
|
||||
const reply = vi.fn(async (_message: OutboundMessage) => {});
|
||||
const firstRun = router.handler({
|
||||
id: 'm-interrupt-1',
|
||||
channel: 'telegram',
|
||||
senderId: 'user-interrupt',
|
||||
text: 'first',
|
||||
timestamp: Date.now(),
|
||||
} as MessageRouterInput, reply);
|
||||
|
||||
await started;
|
||||
|
||||
await router.handler({
|
||||
id: 'm-interrupt-2',
|
||||
channel: 'telegram',
|
||||
senderId: 'user-interrupt',
|
||||
text: 'second',
|
||||
timestamp: Date.now(),
|
||||
} as MessageRouterInput, reply);
|
||||
|
||||
expect(cancelSpy).toHaveBeenCalled();
|
||||
|
||||
resolveFirst?.('first');
|
||||
await firstRun;
|
||||
});
|
||||
|
||||
it('emits run.state start and complete for non-command channel messages', async () => {
|
||||
const processSpy = vi.spyOn(AgentOrchestrator.prototype, 'process').mockResolvedValue('ok');
|
||||
const mockAuditLogger = {
|
||||
|
||||
+72
-40
@@ -443,6 +443,56 @@ export function createMessageRouter(deps: {
|
||||
});
|
||||
}
|
||||
|
||||
function requestActiveRunCancellation(input: {
|
||||
sessionId: string;
|
||||
channel: string;
|
||||
senderId: string;
|
||||
requestId: string;
|
||||
}): { cancelled: boolean; latencyMs: number } {
|
||||
const cancelStartedAt = Date.now();
|
||||
const run = activeRuns.get(input.sessionId);
|
||||
if (!run || !run.isCancellable()) {
|
||||
const latencyMs = Date.now() - cancelStartedAt;
|
||||
deps.metrics?.recordCancelLatency(latencyMs);
|
||||
auditLogger?.runCancel?.({
|
||||
session_id: input.sessionId,
|
||||
channel: input.channel,
|
||||
sender: input.senderId,
|
||||
source: 'channel',
|
||||
requested: true,
|
||||
acknowledged: false,
|
||||
request_id: input.requestId,
|
||||
latency_ms: latencyMs,
|
||||
});
|
||||
return { cancelled: false, latencyMs };
|
||||
}
|
||||
|
||||
run.cancel();
|
||||
const cancelLatencyMs = Date.now() - cancelStartedAt;
|
||||
deps.metrics?.recordCancelLatency(cancelLatencyMs);
|
||||
auditLogger?.runCancel?.({
|
||||
session_id: input.sessionId,
|
||||
channel: input.channel,
|
||||
sender: input.senderId,
|
||||
source: 'channel',
|
||||
requested: true,
|
||||
acknowledged: true,
|
||||
request_id: input.requestId,
|
||||
latency_ms: cancelLatencyMs,
|
||||
});
|
||||
auditLogger?.runState?.({
|
||||
session_id: input.sessionId,
|
||||
channel: input.channel,
|
||||
sender: input.senderId,
|
||||
source: 'channel',
|
||||
state: 'cancel_requested',
|
||||
request_id: input.requestId,
|
||||
duration_ms: cancelLatencyMs,
|
||||
});
|
||||
deps.metrics?.recordRunState('cancel_requested');
|
||||
return { cancelled: true, latencyMs: cancelLatencyMs };
|
||||
}
|
||||
|
||||
function executeBackendCommand(inputRaw: string, activeTier: string): string {
|
||||
return executeRuntimeBackendModeCommand(inputRaw, {
|
||||
getActiveTier: () => activeTier,
|
||||
@@ -770,6 +820,21 @@ export function createMessageRouter(deps: {
|
||||
}
|
||||
}
|
||||
|
||||
const session = deps.sessionManager.getSession(msg.channel, msg.senderId);
|
||||
const queueMode = session.getConfig('queue.mode') ?? deps.config.server?.queue?.mode ?? 'collect';
|
||||
const rawCommand = msg.metadata?.isCommand
|
||||
? msg.metadata.command
|
||||
: incomingText.trim().startsWith('/') ? incomingText.trim().slice(1).split(/\s+/, 1)[0] : undefined;
|
||||
const isCancelCommand = rawCommand === 'stop' || rawCommand === 'cancel';
|
||||
if (queueMode === 'interrupt' && !isCancelCommand) {
|
||||
requestActiveRunCancellation({
|
||||
sessionId: sessionIdForRun,
|
||||
channel: msg.channel,
|
||||
senderId: msg.senderId,
|
||||
requestId: msg.id,
|
||||
});
|
||||
}
|
||||
|
||||
const automationReactions = deps.config.automation?.reactions ?? [];
|
||||
if (!msg.metadata?.isCommand) {
|
||||
if (automationReactions.length === 0) {
|
||||
@@ -896,7 +961,6 @@ export function createMessageRouter(deps: {
|
||||
});
|
||||
|
||||
if (deps.commandRegistry && deps.commandRegistry.isCommand(commandInput)) {
|
||||
const session = deps.sessionManager.getSession(msg.channel, msg.senderId);
|
||||
const commandResult = await deps.commandRegistry.execute(commandInput, {
|
||||
channel: msg.channel,
|
||||
senderId: msg.senderId,
|
||||
@@ -1066,46 +1130,15 @@ export function createMessageRouter(deps: {
|
||||
return '';
|
||||
},
|
||||
cancelRun: () => {
|
||||
const cancelStartedAt = Date.now();
|
||||
const run = activeRuns.get(session.id);
|
||||
if (!run || !run.isCancellable()) {
|
||||
deps.metrics?.recordCancelLatency(Date.now() - cancelStartedAt);
|
||||
auditLogger?.runCancel?.({
|
||||
session_id: session.id,
|
||||
channel: msg.channel,
|
||||
sender: msg.senderId,
|
||||
source: 'channel',
|
||||
requested: true,
|
||||
acknowledged: false,
|
||||
request_id: msg.id,
|
||||
latency_ms: Date.now() - cancelStartedAt,
|
||||
});
|
||||
return 'No active operation to cancel.';
|
||||
}
|
||||
run.cancel();
|
||||
const cancelLatencyMs = Date.now() - cancelStartedAt;
|
||||
deps.metrics?.recordCancelLatency(cancelLatencyMs);
|
||||
auditLogger?.runCancel?.({
|
||||
session_id: session.id,
|
||||
const result = requestActiveRunCancellation({
|
||||
sessionId: session.id,
|
||||
channel: msg.channel,
|
||||
sender: msg.senderId,
|
||||
source: 'channel',
|
||||
requested: true,
|
||||
acknowledged: true,
|
||||
request_id: msg.id,
|
||||
latency_ms: cancelLatencyMs,
|
||||
senderId: msg.senderId,
|
||||
requestId: msg.id,
|
||||
});
|
||||
auditLogger?.runState?.({
|
||||
session_id: session.id,
|
||||
channel: msg.channel,
|
||||
sender: msg.senderId,
|
||||
source: 'channel',
|
||||
state: 'cancel_requested',
|
||||
request_id: msg.id,
|
||||
duration_ms: cancelLatencyMs,
|
||||
});
|
||||
deps.metrics?.recordRunState('cancel_requested');
|
||||
return 'Cancellation requested. The active operation will stop at the next safe point.';
|
||||
return result.cancelled
|
||||
? 'Cancellation requested. The active operation will stop at the next safe point.'
|
||||
: 'No active operation to cancel.';
|
||||
},
|
||||
|
||||
delegateAgent: async (agentName: string, task: string) => {
|
||||
@@ -1515,7 +1548,6 @@ export function createMessageRouter(deps: {
|
||||
|
||||
// Determine if the active model supports native audio input
|
||||
let effectiveTier: string = deps.config.agents.primary_tier ?? 'default';
|
||||
const session = deps.sessionManager.getSession(msg.channel, msg.senderId);
|
||||
const sessionTierOverride = session.getConfig('modelTier');
|
||||
const tierFromUseCaseMetadata = tierFromUseCase(deps.config, msg.metadata?.modelFor);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user