feat: add session-scoped workflow approval gate commands

This commit is contained in:
William Valentin
2026-02-18 10:35:42 -08:00
parent 1508bcf9cb
commit f34a974210
13 changed files with 369 additions and 6 deletions
+1 -1
View File
@@ -213,7 +213,7 @@ export async function startDaemon(config: Config, options?: StartDaemonOptions):
const messageRouter = createMessageRouter({
sessionManager, modelRouter, systemPrompt, toolRegistry, toolExecutor,
config, memoryStore, agentConfigRegistry, agentRouter, sandboxManager, commandRegistry, intentRegistry, routingPolicy, skillRegistry,
config, memoryStore, agentConfigRegistry, agentRouter, sandboxManager, commandRegistry, hookEngine, intentRegistry, routingPolicy, skillRegistry,
...createConfiguredExternalBackends(config),
});
channelRegistry.setMessageHandler(messageRouter.handler);
+94
View File
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { AgentRouter } from '../agents/router.js';
import { AgentConfigRegistry } from '../agents/registry.js';
import { HookEngine } from '../hooks/index.js';
import type { ModelTier } from '../models/router.js';
import { createMessageRouter } from './routing.js';
import { AgentOrchestrator } from '../backends/index.js';
@@ -817,6 +818,99 @@ describe('daemon command fast-path integration', () => {
const outbound = reply.mock.calls[0]?.[0] as OutboundMessage | undefined;
expect(outbound?.text).toContain('Backend: codex');
});
it('lists and resolves pending approvals for the current session via /approvals + /approve', async () => {
const processSpy = vi.spyOn(AgentOrchestrator.prototype, 'process');
const session = {
id: 'telegram:approvals-user',
addMessage: vi.fn(),
getHistory: vi.fn(() => []),
clear: vi.fn(),
replaceHistory: vi.fn(),
getConfig: vi.fn(() => undefined),
setConfig: vi.fn(),
deleteConfig: vi.fn(),
};
const hookEngine = new HookEngine({ confirm: [], log: [], silent: [] });
const pendingPromise = hookEngine.requestConfirmation(
'shell.exec',
{ command: 'rm -rf /tmp/example' },
{ sessionId: session.id, channel: 'telegram', sender: 'approvals-user' },
);
const pending = hookEngine.getPendingConfirmations({ sessionId: session.id });
const pendingId = pending[0]?.id;
if (!pendingId) {
throw new Error('Expected pending approval id');
}
const commandRegistry = new CommandRegistry();
registerBuiltinCommands(commandRegistry);
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' } },
} as unknown as MessageRouterDeps['config'],
commandRegistry,
hookEngine,
});
const reply = vi.fn(async (_message: OutboundMessage) => {});
await router.handler({
id: 'approvals-1',
channel: 'telegram',
senderId: 'approvals-user',
text: '/approvals',
timestamp: Date.now(),
metadata: { isCommand: true, command: 'approvals' },
} as MessageRouterInput, reply);
const listReply = reply.mock.calls[0]?.[0] as OutboundMessage | undefined;
expect(String(listReply?.text)).toContain('Pending approvals:');
expect(String(listReply?.text)).toContain(pendingId);
await router.handler({
id: 'approvals-2',
channel: 'telegram',
senderId: 'approvals-user',
text: `/approve ${pendingId}`,
timestamp: Date.now(),
metadata: { isCommand: true, command: 'approve', commandArgs: pendingId },
} as MessageRouterInput, reply);
const approveReply = reply.mock.calls[1]?.[0] as OutboundMessage | undefined;
expect(String(approveReply?.text)).toContain('Approved: shell.exec');
await expect(pendingPromise).resolves.toEqual({ approved: true });
expect(processSpy).not.toHaveBeenCalled();
});
});
describe('daemon external backend integration', () => {
+82
View File
@@ -20,6 +20,7 @@ import { AgentConfigRegistry, AgentRouter } from '../agents/index.js';
import type { CommandRegistry } from '../commands/index.js';
import type { ComponentRegistry } from '../intents/index.js';
import type { RoutingPolicy } from '../routing/index.js';
import type { HookEngine } from '../hooks/index.js';
import { createClientFromConfig } from './models.js';
import { matchReactionPrompt } from '../automation/reactions.js';
import type { SkillRegistry } from '../skills/index.js';
@@ -116,6 +117,7 @@ export function createMessageRouter(deps: {
agentRouter?: AgentRouter;
sandboxManager?: SandboxManager;
commandRegistry?: CommandRegistry;
hookEngine?: HookEngine;
intentRegistry?: ComponentRegistry;
routingPolicy?: RoutingPolicy;
skillRegistry?: SkillRegistry;
@@ -936,6 +938,86 @@ export function createMessageRouter(deps: {
deps.sessionManager.transferSession(msg.channel, msg.senderId, toFrontend, toUserId);
return `Session transferred to ${destinationLabel}`;
},
getApprovals: () => {
if (!deps.hookEngine) {
return 'Approval gates are not enabled in this runtime.';
}
const pending = deps.hookEngine.getPendingConfirmations({ sessionId: session.id });
if (pending.length === 0) {
return 'No pending approvals for this session.';
}
const lines = ['Pending approvals:'];
for (const item of pending) {
const ageSec = Math.max(0, Math.round((Date.now() - item.createdAt.getTime()) / 1000));
lines.push(`- ${item.id} | ${item.tool} | ${ageSec}s old`);
}
lines.push('');
lines.push('Use `/approve <id>` or `/deny <id> <reason>` (id optional: latest is used).');
return lines.join('\n');
},
approvePending: (inputRaw: string) => {
if (!deps.hookEngine) {
return 'Approval gates are not enabled in this runtime.';
}
const pending = deps.hookEngine.getPendingConfirmations({ sessionId: session.id });
if (pending.length === 0) {
return 'No pending approvals for this session.';
}
const input = inputRaw.trim();
const selected = input
? pending.find((item) => item.id === input)
: pending[pending.length - 1];
if (!selected) {
return `Approval id not found in this session: ${input}`;
}
const resolved = deps.hookEngine.resolveConfirmation(selected.id, { approved: true });
return resolved
? `Approved: ${selected.tool} (${selected.id})`
: `Approval request is no longer pending: ${selected.id}`;
},
denyPending: (inputRaw: string) => {
if (!deps.hookEngine) {
return 'Approval gates are not enabled in this runtime.';
}
const pending = deps.hookEngine.getPendingConfirmations({ sessionId: session.id });
if (pending.length === 0) {
return 'No pending approvals for this session.';
}
const input = inputRaw.trim();
let targetId: string | undefined;
let reason = 'Denied by user';
if (input) {
const [first, ...rest] = input.split(/\s+/);
const matched = pending.find((item) => item.id === first);
if (matched) {
targetId = matched.id;
reason = rest.join(' ').trim() || reason;
} else {
targetId = pending[pending.length - 1].id;
reason = input;
}
} else {
targetId = pending[pending.length - 1].id;
}
const selected = pending.find((item) => item.id === targetId);
if (!selected) {
return `Approval request is no longer pending: ${targetId}`;
}
const resolved = deps.hookEngine.resolveConfirmation(selected.id, { approved: false, reason });
return resolved
? `Denied: ${selected.tool} (${selected.id}) — ${reason}`
: `Approval request is no longer pending: ${selected.id}`;
},
},
});