mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-28 19:25:45 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8055cde9b | ||
|
|
69ed22c076 |
@@ -4577,6 +4577,303 @@ test("keeps the global Paseo-tools gate outside provider policy and MCP injectio
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("voice-only delivery injects internal paseo MCP and native voiceOnly catalog even when Paseo tools are disabled", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const voiceActiveAgents = new Set<string>();
|
||||
|
||||
class VoiceMcpSession extends McpCapableTestAgentSession {
|
||||
override readonly provider: AgentProvider;
|
||||
|
||||
constructor(config: AgentSessionConfig) {
|
||||
super(config);
|
||||
this.provider = config.provider;
|
||||
}
|
||||
|
||||
override describePersistence(): AgentPersistenceHandle {
|
||||
return {
|
||||
provider: this.provider,
|
||||
sessionId: this.id,
|
||||
metadata: { cwd: workdir },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class VoiceMcpClient extends TestAgentClient {
|
||||
override readonly capabilities = {
|
||||
...TEST_CAPABILITIES,
|
||||
supportsMcpServers: true,
|
||||
};
|
||||
readonly configs: AgentSessionConfig[] = [];
|
||||
readonly launchContexts: Array<AgentLaunchContext | undefined> = [];
|
||||
|
||||
override async createSession(
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
): Promise<AgentSession> {
|
||||
this.configs.push(config);
|
||||
this.launchContexts.push(launchContext);
|
||||
return new VoiceMcpSession(config);
|
||||
}
|
||||
|
||||
override async resumeSession(
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
launchContext?: AgentLaunchContext,
|
||||
): Promise<AgentSession> {
|
||||
const config = {
|
||||
provider: handle.provider,
|
||||
cwd: workdir,
|
||||
...overrides,
|
||||
} as AgentSessionConfig;
|
||||
this.configs.push(config);
|
||||
this.launchContexts.push(launchContext);
|
||||
return new VoiceMcpSession(config);
|
||||
}
|
||||
}
|
||||
|
||||
class VoiceNativeClient extends VoiceMcpClient {
|
||||
override readonly capabilities = {
|
||||
...TEST_CAPABILITIES,
|
||||
supportsMcpServers: true,
|
||||
supportsNativePaseoTools: true,
|
||||
};
|
||||
}
|
||||
|
||||
const speakCatalog: PaseoToolCatalog = {
|
||||
tools: new Map([
|
||||
[
|
||||
"speak",
|
||||
{
|
||||
name: "speak",
|
||||
description: "Speak text",
|
||||
handler: async () => ({ content: [], structuredContent: { ok: true } }),
|
||||
},
|
||||
],
|
||||
]),
|
||||
getTool: (name) => (name === "speak" ? speakCatalog.tools.get("speak") : undefined),
|
||||
executeTool: async () => ({ content: [], structuredContent: { ok: true } }),
|
||||
};
|
||||
|
||||
const mcpClient = new VoiceMcpClient("claude");
|
||||
const nativeClient = new VoiceNativeClient("opencode");
|
||||
const catalogCalls: Array<{
|
||||
callerAgentId?: string;
|
||||
paseoToolPolicy?: unknown;
|
||||
voiceOnly?: boolean;
|
||||
}> = [];
|
||||
|
||||
const manager = new AgentManager({
|
||||
clients: { claude: mcpClient, opencode: nativeClient },
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpAuthToken: "voice-token",
|
||||
paseoToolsEnabled: false,
|
||||
hasActiveVoiceTools: (agentId) => voiceActiveAgents.has(agentId),
|
||||
paseoToolCatalogFactory: (context) => {
|
||||
catalogCalls.push(context);
|
||||
return speakCatalog;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const claudeAgent = await manager.createAgent(
|
||||
{ provider: "claude", cwd: workdir },
|
||||
"00000000-0000-4000-8000-000000000201",
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const opencodeAgent = await manager.createAgent(
|
||||
{ provider: "opencode", cwd: workdir },
|
||||
"00000000-0000-4000-8000-000000000202",
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
// Non-voice sessions receive zero Paseo MCP servers and zero native Paseo tools.
|
||||
expect(mcpClient.configs.at(-1)?.mcpServers).toBeUndefined();
|
||||
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBeUndefined();
|
||||
expect(nativeClient.configs.at(-1)?.mcpServers).toBeUndefined();
|
||||
expect(nativeClient.launchContexts.at(-1)?.paseoTools).toBeUndefined();
|
||||
expect(catalogCalls).toEqual([]);
|
||||
|
||||
// Enabling voice mode on MCP provider injects loopback paseo MCP and marks voiceToolsEnabled.
|
||||
voiceActiveAgents.add(claudeAgent.id);
|
||||
await manager.reloadAgentSession(
|
||||
claudeAgent.id,
|
||||
{ systemPrompt: "voice prompt" },
|
||||
{ requireVoiceSpeak: true },
|
||||
);
|
||||
expect(mcpClient.configs.at(-1)?.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${claudeAgent.id}`,
|
||||
headers: { Authorization: "Bearer voice-token" },
|
||||
});
|
||||
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBe(true);
|
||||
|
||||
// Enabling voice mode on native-tools provider builds a voiceOnly catalog with speak only.
|
||||
voiceActiveAgents.add(opencodeAgent.id);
|
||||
await manager.reloadAgentSession(
|
||||
opencodeAgent.id,
|
||||
{ systemPrompt: "voice prompt" },
|
||||
{ requireVoiceSpeak: true },
|
||||
);
|
||||
expect(catalogCalls).toEqual([
|
||||
{
|
||||
callerAgentId: opencodeAgent.id,
|
||||
paseoToolPolicy: { enabled: false },
|
||||
voiceOnly: true,
|
||||
},
|
||||
]);
|
||||
expect(nativeClient.launchContexts.at(-1)?.paseoTools).toBe(speakCatalog);
|
||||
expect(nativeClient.configs.at(-1)?.mcpServers?.paseo).toBeUndefined();
|
||||
|
||||
// Disabling voice mode removes paseo MCP and voiceToolsEnabled again.
|
||||
voiceActiveAgents.delete(claudeAgent.id);
|
||||
await manager.reloadAgentSession(claudeAgent.id, { systemPrompt: "normal prompt" });
|
||||
expect(mcpClient.configs.at(-1)?.mcpServers).toBeUndefined();
|
||||
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBeUndefined();
|
||||
} finally {
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("reloadAgentSession rejects voice mode when the session cannot mount speak and preserves the live session", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
class PiNoMcpSession extends CloseRecordingTestAgentSession {
|
||||
override readonly provider = "pi" as const;
|
||||
|
||||
override describePersistence(): AgentPersistenceHandle {
|
||||
return {
|
||||
provider: "pi",
|
||||
sessionId: this.id,
|
||||
metadata: { cwd: workdir },
|
||||
};
|
||||
}
|
||||
}
|
||||
const original = new PiNoMcpSession({ provider: "pi", cwd: workdir });
|
||||
const reopened = new PiNoMcpSession({ provider: "pi", cwd: workdir });
|
||||
let voiceActive = false;
|
||||
|
||||
class NoMcpPiClient extends TestAgentClient {
|
||||
override readonly capabilities = {
|
||||
...TEST_CAPABILITIES,
|
||||
supportsMcpServers: false,
|
||||
supportsNativePaseoTools: false,
|
||||
};
|
||||
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return original;
|
||||
}
|
||||
|
||||
override async resumeSession(): Promise<AgentSession> {
|
||||
return reopened;
|
||||
}
|
||||
}
|
||||
|
||||
class StdioOnlyAcpSession extends CloseRecordingTestAgentSession {
|
||||
override readonly provider = "acp-stdio" as const;
|
||||
override readonly capabilities = {
|
||||
...TEST_CAPABILITIES,
|
||||
supportsMcpServers: true,
|
||||
supportsHttpMcpServers: false,
|
||||
};
|
||||
|
||||
override describePersistence(): AgentPersistenceHandle {
|
||||
return {
|
||||
provider: "acp-stdio",
|
||||
sessionId: this.id,
|
||||
metadata: { cwd: workdir },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const acpOriginal = new StdioOnlyAcpSession({ provider: "acp-stdio", cwd: workdir });
|
||||
const acpReopened = new StdioOnlyAcpSession({ provider: "acp-stdio", cwd: workdir });
|
||||
|
||||
class StdioOnlyAcpClient extends TestAgentClient {
|
||||
override readonly capabilities = {
|
||||
...TEST_CAPABILITIES,
|
||||
supportsMcpServers: true,
|
||||
};
|
||||
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return acpOriginal;
|
||||
}
|
||||
|
||||
override async resumeSession(): Promise<AgentSession> {
|
||||
return acpReopened;
|
||||
}
|
||||
}
|
||||
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
pi: new NoMcpPiClient("pi"),
|
||||
"acp-stdio": new StdioOnlyAcpClient("acp-stdio"),
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
paseoToolsEnabled: false,
|
||||
hasActiveVoiceTools: () => voiceActive,
|
||||
});
|
||||
|
||||
try {
|
||||
const created = await manager.createAgent(
|
||||
{ provider: "pi", cwd: workdir, systemPrompt: "base prompt" },
|
||||
"00000000-0000-4000-8000-000000000203",
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
voiceActive = true;
|
||||
|
||||
await expect(
|
||||
manager.reloadAgentSession(
|
||||
created.id,
|
||||
{ systemPrompt: "voice prompt" },
|
||||
{ requireVoiceSpeak: true },
|
||||
),
|
||||
).rejects.toThrow(/speak/i);
|
||||
|
||||
expect(original.closed).toBe(false);
|
||||
expect(reopened.closed).toBe(false);
|
||||
expect(manager.getAgent(created.id)?.session).toBe(original);
|
||||
expect(manager.getAgent(created.id)?.lifecycle).toBe("idle");
|
||||
const stored = await storage.get(created.id);
|
||||
expect(stored?.config?.systemPrompt).toBe("base prompt");
|
||||
|
||||
// ACP with mcpCapabilities.http=false still launches with stdio MCP servers,
|
||||
// while rejecting voice mode cleanly without closing the live session.
|
||||
voiceActive = false;
|
||||
const acpAgent = await manager.createAgent(
|
||||
{
|
||||
provider: "acp-stdio",
|
||||
cwd: workdir,
|
||||
mcpServers: {
|
||||
local: { type: "stdio", command: "node", args: ["mcp.js"] },
|
||||
},
|
||||
},
|
||||
"00000000-0000-4000-8000-000000000204",
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
expect(manager.getAgent(acpAgent.id)?.lifecycle).toBe("idle");
|
||||
|
||||
voiceActive = true;
|
||||
await expect(
|
||||
manager.reloadAgentSession(
|
||||
acpAgent.id,
|
||||
{ systemPrompt: "voice prompt" },
|
||||
{ requireVoiceSpeak: true },
|
||||
),
|
||||
).rejects.toThrow(/speak/i);
|
||||
expect(acpOriginal.closed).toBe(false);
|
||||
expect(acpReopened.closed).toBe(false);
|
||||
expect(manager.getAgent(acpAgent.id)?.session).toBe(acpOriginal);
|
||||
expect(manager.getAgent(acpAgent.id)?.lifecycle).toBe("idle");
|
||||
} finally {
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("resumeAgentFromPersistence replaces stored internal paseo MCP with current runtime URL", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
|
||||
@@ -437,6 +437,7 @@ export interface AgentManagerOptions {
|
||||
pluginSessions?: PluginSessionsRuntime;
|
||||
paseoToolsEnabled?: boolean;
|
||||
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
|
||||
hasActiveVoiceTools?: (agentId: string) => boolean;
|
||||
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
|
||||
appendSystemPrompt?: string;
|
||||
agentStreamCoalesceWindowMs?: number;
|
||||
@@ -975,6 +976,7 @@ export class AgentManager {
|
||||
private readonly pluginSessions: PluginSessionsRuntime | undefined;
|
||||
private paseoToolsEnabled = true;
|
||||
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
|
||||
private hasActiveVoiceTools: (agentId: string) => boolean = () => false;
|
||||
private readonly paseoToolPolicies = new Map<string, ProviderPaseoToolsPolicy | undefined>();
|
||||
private readonly resolvePaseoToolPolicy: (
|
||||
provider: AgentProvider,
|
||||
@@ -1027,6 +1029,7 @@ export class AgentManager {
|
||||
private configurePaseoTools(options: AgentManagerOptions): void {
|
||||
this.paseoToolsEnabled = options.paseoToolsEnabled ?? true;
|
||||
this.paseoToolCatalogFactory = options.paseoToolCatalogFactory ?? null;
|
||||
this.hasActiveVoiceTools = options.hasActiveVoiceTools ?? (() => false);
|
||||
}
|
||||
|
||||
registerClient(provider: AgentProvider, client: AgentClient): void {
|
||||
@@ -1091,6 +1094,10 @@ export class AgentManager {
|
||||
this.paseoToolsEnabled = enabled;
|
||||
}
|
||||
|
||||
isPaseoToolsEnabled(): boolean {
|
||||
return this.paseoToolsEnabled;
|
||||
}
|
||||
|
||||
setPaseoToolCatalogFactory(factory: PaseoToolCatalogFactory | null): void {
|
||||
this.paseoToolCatalogFactory = factory;
|
||||
}
|
||||
@@ -2067,7 +2074,7 @@ export class AgentManager {
|
||||
reloadAgentSession(
|
||||
agentId: string,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
options?: { rehydrateFromDisk?: boolean },
|
||||
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
|
||||
): Promise<ManagedAgent> {
|
||||
return this.trackAgentRegistrationOperation(
|
||||
this.runLifecycleMutation(agentId, () =>
|
||||
@@ -2079,7 +2086,7 @@ export class AgentManager {
|
||||
private reloadAgentSessionInternal(
|
||||
agentId: string,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
options?: { rehydrateFromDisk?: boolean },
|
||||
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
|
||||
): Promise<ManagedAgent> {
|
||||
return this.launchAgent(agentId, () => this.reopenAgentSession(agentId, overrides, options));
|
||||
}
|
||||
@@ -2101,7 +2108,7 @@ export class AgentManager {
|
||||
private async reopenAgentSession(
|
||||
agentId: string,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
options?: { rehydrateFromDisk?: boolean },
|
||||
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
|
||||
): Promise<ManagedAgent> {
|
||||
this.assertAcceptingAgentRegistrations();
|
||||
let existing = this.requireSessionAgent(agentId);
|
||||
@@ -2150,6 +2157,7 @@ export class AgentManager {
|
||||
existing,
|
||||
launchConfig,
|
||||
launchContext,
|
||||
options,
|
||||
);
|
||||
|
||||
let session: AgentSession | undefined;
|
||||
@@ -2171,6 +2179,7 @@ export class AgentManager {
|
||||
? await client.resumeSession(handle, providerLaunchConfig, launchContext)
|
||||
: await client.createSession(providerLaunchConfig, launchContext);
|
||||
await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext);
|
||||
this.assertVoiceSpeakSupportIfRequired(session, providerLaunchConfig, launchContext, options);
|
||||
this.assertAcceptingAgentRegistrations();
|
||||
|
||||
if (rehydrateFromDisk) {
|
||||
@@ -2233,6 +2242,7 @@ export class AgentManager {
|
||||
existing: ActiveManagedAgent,
|
||||
launchConfig: AgentSessionConfig,
|
||||
launchContext: AgentLaunchContext,
|
||||
options?: { requireVoiceSpeak?: boolean },
|
||||
): AgentSessionConfig {
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
const mcpServers = stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {};
|
||||
@@ -2242,6 +2252,12 @@ export class AgentManager {
|
||||
) {
|
||||
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
|
||||
}
|
||||
this.assertVoiceSpeakSupportIfRequired(
|
||||
existing.session,
|
||||
providerLaunchConfig,
|
||||
launchContext,
|
||||
options,
|
||||
);
|
||||
return providerLaunchConfig;
|
||||
}
|
||||
|
||||
@@ -4877,6 +4893,29 @@ export class AgentManager {
|
||||
return new Error(`Provider '${config.provider}' does not support MCP servers${source}`);
|
||||
}
|
||||
|
||||
private assertVoiceSpeakSupportIfRequired(
|
||||
session: AgentSession,
|
||||
launchConfig: AgentSessionConfig,
|
||||
launchContext: AgentLaunchContext,
|
||||
options?: { requireVoiceSpeak?: boolean },
|
||||
): void {
|
||||
if (!options?.requireVoiceSpeak) {
|
||||
return;
|
||||
}
|
||||
const hasNativeSpeak = launchContext.paseoTools?.tools.has("speak") === true;
|
||||
const supportsHttpMcp =
|
||||
session.capabilities.supportsMcpServers === true &&
|
||||
session.capabilities.supportsHttpMcpServers !== false;
|
||||
const hasMcpSpeak =
|
||||
Boolean(launchConfig.mcpServers?.[PASEO_MCP_SERVER_NAME]) && supportsHttpMcp;
|
||||
if (hasNativeSpeak || hasMcpSpeak) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`Voice mode is unavailable for provider '${launchConfig.provider}': the session does not expose Paseo's 'speak' tool (requires native Paseo tool support or HTTP MCP server support).`,
|
||||
);
|
||||
}
|
||||
|
||||
private async initializeAgentTimelineForRegister(params: {
|
||||
agentId: string;
|
||||
now: Date;
|
||||
@@ -6644,17 +6683,16 @@ export class AgentManager {
|
||||
purpose: options.purpose,
|
||||
resolveDefaultModel: options.resolveDefaultModel,
|
||||
});
|
||||
const voiceActive = this.hasActiveVoiceTools(agentId);
|
||||
const paseoToolPolicy = this.paseoToolsEnabled
|
||||
? this.resolvePaseoToolPolicy(storedConfig.provider)
|
||||
: { enabled: false };
|
||||
const generalEnabled = this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy);
|
||||
const launchConfig = this.applyDaemonAppendSystemPrompt(
|
||||
withRuntimePaseoMcpServer({
|
||||
config: storedConfig,
|
||||
agentId,
|
||||
mcpBaseUrl:
|
||||
this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy)
|
||||
? this.mcpBaseUrl
|
||||
: null,
|
||||
mcpBaseUrl: generalEnabled || voiceActive ? this.mcpBaseUrl : null,
|
||||
mcpAuthToken: this.mcpAuthToken,
|
||||
}),
|
||||
);
|
||||
@@ -6731,10 +6769,23 @@ export class AgentManager {
|
||||
...agentIdentityEnv({ agentId, cwd, opening }),
|
||||
},
|
||||
};
|
||||
await this.attachLaunchPaseoTools(context, agentId, client, paseoToolPolicy);
|
||||
return context;
|
||||
}
|
||||
|
||||
private async attachLaunchPaseoTools(
|
||||
context: AgentLaunchContext,
|
||||
agentId: string,
|
||||
client: AgentClient,
|
||||
paseoToolPolicy: ProviderPaseoToolsPolicy | undefined,
|
||||
): Promise<void> {
|
||||
const voiceActive = this.hasActiveVoiceTools(agentId);
|
||||
if (voiceActive) {
|
||||
context.voiceToolsEnabled = true;
|
||||
}
|
||||
const generalEnabled = this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy);
|
||||
const useNativeTools =
|
||||
this.paseoToolsEnabled &&
|
||||
isPaseoToolPolicyEnabled(paseoToolPolicy) &&
|
||||
client.capabilities.supportsNativePaseoTools;
|
||||
(generalEnabled || voiceActive) && client.capabilities.supportsNativePaseoTools;
|
||||
if (
|
||||
this.paseoToolCatalogFactory &&
|
||||
(useNativeTools || this.getPluginTools(agentId).length > 0)
|
||||
@@ -6743,10 +6794,10 @@ export class AgentManager {
|
||||
const catalog = await this.paseoToolCatalogFactory({
|
||||
callerAgentId: agentId,
|
||||
paseoToolPolicy,
|
||||
...(useNativeTools && voiceActive && !generalEnabled ? { voiceOnly: true } : {}),
|
||||
});
|
||||
if (useNativeTools) context.paseoTools = catalog;
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
private resolveProviderLaunchConfig(
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import http from "node:http";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { describe, expect, test } from "vitest";
|
||||
@@ -17,6 +19,8 @@ import pino from "pino";
|
||||
import { withTimeout } from "../../utils/promise-timeout.js";
|
||||
import { hashDaemonPassword } from "../auth.js";
|
||||
import { createPaseoDaemon, type PaseoDaemonConfig } from "../bootstrap.js";
|
||||
import type { SpeechService } from "../speech/speech-runtime.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import type {
|
||||
AgentClient,
|
||||
@@ -1188,3 +1192,278 @@ describe("agent MCP protocol negotiation", () => {
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
describe("voice-only speak MCP delivery", () => {
|
||||
function createFakeVoiceSpeechService(spokenTexts: string[]): SpeechService {
|
||||
const ready = {
|
||||
enabled: true,
|
||||
available: true,
|
||||
retryable: false,
|
||||
reasonCode: "ready" as const,
|
||||
message: "Ready",
|
||||
missingModelIds: [],
|
||||
};
|
||||
return {
|
||||
resolveStt: () => ({
|
||||
id: "local",
|
||||
createSession: () => {
|
||||
const session = new EventEmitter();
|
||||
return Object.assign(session, {
|
||||
requiredSampleRate: 16000,
|
||||
async connect() {},
|
||||
appendPcm16() {},
|
||||
commit() {},
|
||||
clear() {},
|
||||
close() {},
|
||||
});
|
||||
},
|
||||
}),
|
||||
resolveSttLanguage: () => "en",
|
||||
resolveTts: () => ({
|
||||
async synthesizeSpeech(text: string) {
|
||||
spokenTexts.push(text);
|
||||
return { stream: Readable.from([Buffer.from("pcm")]), format: "pcm;rate=24000" };
|
||||
},
|
||||
}),
|
||||
resolveTurnDetection: () => ({
|
||||
id: "local",
|
||||
createSession: () => {
|
||||
const session = new EventEmitter();
|
||||
return Object.assign(session, {
|
||||
requiredSampleRate: 16000,
|
||||
async connect() {},
|
||||
appendPcm16() {},
|
||||
flush() {},
|
||||
reset() {},
|
||||
close() {},
|
||||
});
|
||||
},
|
||||
}),
|
||||
resolveDictationStt: () => null,
|
||||
resolveDictationSttLanguage: () => "en",
|
||||
getReadiness: () => ({
|
||||
voiceFeature: ready,
|
||||
realtimeVoice: ready,
|
||||
dictation: ready,
|
||||
localModels: [],
|
||||
}),
|
||||
onReadinessChange: () => () => {},
|
||||
reconfigure: () => {},
|
||||
listLocalModels: async () => [],
|
||||
downloadLocalModel: () => {},
|
||||
deleteLocalModel: async () => {},
|
||||
start: () => {},
|
||||
stop: async () => {},
|
||||
};
|
||||
}
|
||||
|
||||
async function listMcpToolsAndCallSpeak(
|
||||
mcpUrl: string,
|
||||
authToken: string | null,
|
||||
text?: string,
|
||||
): Promise<{ toolNames: string[]; speakResult?: unknown }> {
|
||||
const client = new StandardMcpClient({ name: "voice-mcp-e2e", version: "0.0.0" });
|
||||
await client.connect(
|
||||
new StandardMcpHttpTransport(new URL(mcpUrl), {
|
||||
requestInit: authToken ? { headers: { Authorization: `Bearer ${authToken}` } } : undefined,
|
||||
}),
|
||||
);
|
||||
try {
|
||||
const tools = await client.listTools();
|
||||
const toolNames = tools.tools.map((tool) => tool.name);
|
||||
let speakResult: unknown;
|
||||
if (text !== undefined) {
|
||||
speakResult = await client.callTool({ name: "speak", arguments: { text } });
|
||||
}
|
||||
return { toolNames, speakResult };
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
class VoiceRecordingAgentClient implements AgentClient {
|
||||
readonly provider: AgentClient["provider"];
|
||||
readonly capabilities: AgentClient["capabilities"];
|
||||
|
||||
constructor(
|
||||
private readonly inner: AgentClient,
|
||||
readonly launches: AgentSessionConfig[],
|
||||
supportsMcpServers: boolean,
|
||||
) {
|
||||
this.provider = inner.provider;
|
||||
this.capabilities = {
|
||||
...inner.capabilities,
|
||||
supportsMcpServers,
|
||||
supportsNativePaseoTools: false,
|
||||
};
|
||||
}
|
||||
|
||||
private wrapSession(session: AgentSession): AgentSession {
|
||||
return Object.assign(Object.create(Object.getPrototypeOf(session)), session, {
|
||||
capabilities: this.capabilities,
|
||||
}) as AgentSession;
|
||||
}
|
||||
|
||||
async createSession(
|
||||
...args: Parameters<AgentClient["createSession"]>
|
||||
): ReturnType<AgentClient["createSession"]> {
|
||||
this.launches.push(args[0]);
|
||||
return this.wrapSession(await this.inner.createSession(...args));
|
||||
}
|
||||
|
||||
async resumeSession(
|
||||
...args: Parameters<AgentClient["resumeSession"]>
|
||||
): ReturnType<AgentClient["resumeSession"]> {
|
||||
this.launches.push({
|
||||
provider: this.provider,
|
||||
cwd: args[1]?.cwd ?? String(args[0].metadata?.cwd ?? ""),
|
||||
...args[1],
|
||||
});
|
||||
return this.wrapSession(await this.inner.resumeSession(...args));
|
||||
}
|
||||
|
||||
fetchCatalog(
|
||||
...args: Parameters<AgentClient["fetchCatalog"]>
|
||||
): ReturnType<AgentClient["fetchCatalog"]> {
|
||||
return this.inner.fetchCatalog(...args);
|
||||
}
|
||||
|
||||
isAvailable(): Promise<boolean> {
|
||||
return this.inner.isAvailable();
|
||||
}
|
||||
}
|
||||
|
||||
test.each([
|
||||
{
|
||||
name: "default config (mcp.injectIntoAgents=false, mcp.enabled=true)",
|
||||
mcpEnabled: true,
|
||||
mcpInjectIntoAgents: false,
|
||||
providerOverrides: undefined,
|
||||
},
|
||||
{
|
||||
name: "mcp.enabled=false on loopback",
|
||||
mcpEnabled: false,
|
||||
mcpInjectIntoAgents: false,
|
||||
providerOverrides: undefined,
|
||||
},
|
||||
{
|
||||
name: "per-provider paseoTools.enabled=false",
|
||||
mcpEnabled: true,
|
||||
mcpInjectIntoAgents: true,
|
||||
providerOverrides: { claude: { paseoTools: { enabled: false } } },
|
||||
},
|
||||
])(
|
||||
"delivers only speak on voice enable under $name and rejects unsupported providers",
|
||||
async ({ mcpEnabled, mcpInjectIntoAgents, providerOverrides }) => {
|
||||
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-home-"));
|
||||
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-static-"));
|
||||
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-cwd-"));
|
||||
const port = await getAvailablePort();
|
||||
const spokenTexts: string[] = [];
|
||||
const claudeLaunches: AgentSessionConfig[] = [];
|
||||
const codexLaunches: AgentSessionConfig[] = [];
|
||||
const baseClients = createTestAgentClients();
|
||||
const claudeBase = baseClients.claude!;
|
||||
const codexBase = baseClients.codex!;
|
||||
|
||||
const daemon = await createPaseoDaemon(
|
||||
{
|
||||
listen: `127.0.0.1:${port}`,
|
||||
paseoHome,
|
||||
corsAllowedOrigins: [],
|
||||
hostnames: true,
|
||||
mcpEnabled,
|
||||
mcpInjectIntoAgents,
|
||||
providerOverrides,
|
||||
staticDir,
|
||||
mcpDebug: false,
|
||||
agentClients: {
|
||||
...baseClients,
|
||||
claude: new VoiceRecordingAgentClient(claudeBase, claudeLaunches, true),
|
||||
codex: new VoiceRecordingAgentClient(codexBase, codexLaunches, false),
|
||||
},
|
||||
agentStoragePath: path.join(paseoHome, "agents"),
|
||||
},
|
||||
pino({ level: "silent" }),
|
||||
{ speechService: createFakeVoiceSpeechService(spokenTexts) },
|
||||
);
|
||||
await daemon.start();
|
||||
|
||||
const wsClient = new DaemonClient({ url: `ws://127.0.0.1:${port}/ws` });
|
||||
wsClient.on("audio_output", (msg) => {
|
||||
if (msg.type === "audio_output" && msg.payload.id) {
|
||||
void wsClient.sendSessionMessage({ type: "audio_played", id: msg.payload.id });
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await wsClient.connect();
|
||||
|
||||
// Non-voice agent receives zero Paseo MCP servers.
|
||||
const claudeAgent = await daemon.agentManager.createAgent(
|
||||
{
|
||||
provider: "claude",
|
||||
cwd: agentCwd,
|
||||
model: "claude-test-model",
|
||||
modeId: "bypassPermissions",
|
||||
},
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
expect(claudeLaunches.at(-1)?.mcpServers?.paseo).toBeUndefined();
|
||||
|
||||
// When mcp.enabled=false, non-voice /mcp/agents requests still get 404.
|
||||
if (!mcpEnabled) {
|
||||
const nonVoiceRes = await fetch(
|
||||
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${claudeAgent.id}`,
|
||||
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
|
||||
);
|
||||
expect(nonVoiceRes.status).toBe(404);
|
||||
}
|
||||
|
||||
// Enabling voice mode injects loopback paseo MCP and exposes ONLY speak.
|
||||
await wsClient.setVoiceMode(true, claudeAgent.id);
|
||||
const injected = claudeLaunches.at(-1)?.mcpServers?.paseo;
|
||||
expect(injected).toBeDefined();
|
||||
expect(injected?.type).toBe("http");
|
||||
if (!injected || injected.type !== "http") {
|
||||
throw new Error("Expected HTTP paseo MCP server");
|
||||
}
|
||||
|
||||
const { toolNames } = await listMcpToolsAndCallSpeak(
|
||||
injected.url,
|
||||
daemon.agentManager.getMcpAuthToken(),
|
||||
"Hello from voice mode",
|
||||
);
|
||||
expect(toolNames).toEqual(["speak"]);
|
||||
expect(spokenTexts).toEqual(["Hello from voice mode"]);
|
||||
|
||||
// Disabling voice mode drops paseo MCP on the restored non-voice session.
|
||||
await wsClient.setVoiceMode(false, claudeAgent.id);
|
||||
expect(claudeLaunches.at(-1)?.mcpServers?.paseo).toBeUndefined();
|
||||
|
||||
// Provider without MCP/native tools rejects set_voice_mode cleanly.
|
||||
const unsupportedAgent = await daemon.agentManager.createAgent(
|
||||
{ provider: "codex", cwd: agentCwd },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
await expect(wsClient.setVoiceMode(true, unsupportedAgent.id)).rejects.toThrow(/speak/i);
|
||||
if (!mcpEnabled) {
|
||||
const rejectedRes = await fetch(
|
||||
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${unsupportedAgent.id}`,
|
||||
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
|
||||
);
|
||||
expect(rejectedRes.status).toBe(404);
|
||||
}
|
||||
} finally {
|
||||
await wsClient.close();
|
||||
await daemon.stop();
|
||||
await rm(paseoHome, { recursive: true, force: true });
|
||||
await rm(staticDir, { recursive: true, force: true });
|
||||
await rm(agentCwd, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -185,6 +185,8 @@ export interface AgentCapabilityFlags {
|
||||
supportsSessionListing?: boolean;
|
||||
supportsDynamicModes: boolean;
|
||||
supportsMcpServers: boolean;
|
||||
/** When false, HTTP MCP servers (such as Paseo's loopback endpoint) are not supported even if stdio MCP works. */
|
||||
supportsHttpMcpServers?: boolean;
|
||||
supportsNativePaseoTools?: boolean;
|
||||
supportsReasoningStream: boolean;
|
||||
supportsToolInvocations: boolean;
|
||||
@@ -694,6 +696,8 @@ export interface AgentLaunchContext {
|
||||
* AgentSessionConfig; providers may adapt it to their native tool surface.
|
||||
*/
|
||||
paseoTools?: PaseoToolCatalog;
|
||||
/** True while Paseo voice mode is active for this session launch (never persisted). */
|
||||
voiceToolsEnabled?: boolean;
|
||||
}
|
||||
|
||||
export interface AgentCreateSessionOptions {
|
||||
|
||||
@@ -8,7 +8,11 @@ import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import { AgentManager } from "./agent-manager.js";
|
||||
import { validateProviderOptions } from "./provider-options.js";
|
||||
import { applyClaudeToolPolicy, ClaudeProviderOptionsSchema } from "./providers/claude/options.js";
|
||||
import { applyCodexToolPolicy, CodexProviderOptionsSchema } from "./providers/codex/options.js";
|
||||
import {
|
||||
applyCodexMcpToolApproval,
|
||||
applyCodexToolPolicy,
|
||||
CodexProviderOptionsSchema,
|
||||
} from "./providers/codex/options.js";
|
||||
import {
|
||||
buildOpenCodePermissionRules,
|
||||
OpenCodeProviderOptionsSchema,
|
||||
@@ -196,6 +200,52 @@ describe("exact MCP preapproval mappings", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("Codex speak approval sets tools.speak.approval_mode without restricting enabled_tools", () => {
|
||||
expect(
|
||||
applyCodexMcpToolApproval(
|
||||
{
|
||||
"mcp_servers.paseo": { url: "http://127.0.0.1/mcp/agents?callerAgentId=a1" },
|
||||
"mcp_servers.other": { command: "node" },
|
||||
},
|
||||
"paseo",
|
||||
"speak",
|
||||
),
|
||||
).toEqual({
|
||||
"mcp_servers.paseo": {
|
||||
url: "http://127.0.0.1/mcp/agents?callerAgentId=a1",
|
||||
tools: { speak: { approval_mode: "approve" } },
|
||||
},
|
||||
"mcp_servers.other": { command: "node" },
|
||||
});
|
||||
|
||||
expect(
|
||||
applyCodexMcpToolApproval(
|
||||
{
|
||||
mcp_servers: {
|
||||
paseo: { url: "http://127.0.0.1/mcp/agents?callerAgentId=a1" },
|
||||
"my.dotted": { url: "http://127.0.0.1/other" },
|
||||
},
|
||||
},
|
||||
"paseo",
|
||||
"speak",
|
||||
),
|
||||
).toEqual({
|
||||
mcp_servers: {
|
||||
paseo: {
|
||||
url: "http://127.0.0.1/mcp/agents?callerAgentId=a1",
|
||||
tools: { speak: { approval_mode: "approve" } },
|
||||
},
|
||||
"my.dotted": { url: "http://127.0.0.1/other" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
applyCodexMcpToolApproval({ "mcp_servers.other": { command: "node" } }, "paseo", "speak"),
|
||||
).toEqual({
|
||||
"mcp_servers.other": { command: "node" },
|
||||
});
|
||||
});
|
||||
|
||||
test("Claude adds the exact MCP identity without replacing deny rules", () => {
|
||||
expect(
|
||||
applyClaudeToolPolicy(
|
||||
|
||||
@@ -3561,6 +3561,92 @@ describe("ACPAgentSession", () => {
|
||||
expect(asInternals<ACPSessionInternals>(session).acpMcpServers()).toEqual([]);
|
||||
});
|
||||
|
||||
test("gates HTTP MCP servers and supportsHttpMcpServers on agentCapabilities.mcpCapabilities.http without breaking stdio MCP", async () => {
|
||||
const newSession = vi.fn().mockResolvedValue({
|
||||
sessionId: "acp-http-cap-session",
|
||||
modes: null,
|
||||
models: null,
|
||||
configOptions: [],
|
||||
});
|
||||
|
||||
class CapabilityTestSession extends ACPAgentSession {
|
||||
constructor(
|
||||
private readonly httpCap: boolean | undefined,
|
||||
config: AgentSessionConfig,
|
||||
) {
|
||||
super(config, {
|
||||
provider: "test-acp",
|
||||
logger: createTestLogger(),
|
||||
defaultCommand: ["test-acp", "serve"],
|
||||
defaultModes: [],
|
||||
capabilities: {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: true,
|
||||
supportsMcpServers: true,
|
||||
supportsReasoningStream: true,
|
||||
supportsToolInvocations: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected override async spawnProcess(): Promise<SpawnedACPProcess> {
|
||||
return {
|
||||
child: createProbeChildStub(),
|
||||
connection: {
|
||||
newSession,
|
||||
} as unknown as ClientSideConnection,
|
||||
initialize: {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
agentCapabilities:
|
||||
this.httpCap === undefined ? {} : { mcpCapabilities: { http: this.httpCap } },
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const mcpServers: AgentSessionConfig["mcpServers"] = {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
local: { type: "stdio", command: "node", args: ["mcp.js"] },
|
||||
};
|
||||
|
||||
const unsupported = new CapabilityTestSession(false, {
|
||||
provider: "test-acp",
|
||||
cwd: "/tmp/paseo-acp-test",
|
||||
mcpServers,
|
||||
});
|
||||
await unsupported.initializeNewSession();
|
||||
|
||||
expect(unsupported.capabilities.supportsMcpServers).toBe(true);
|
||||
expect(unsupported.capabilities.supportsHttpMcpServers).toBe(false);
|
||||
expect(newSession).toHaveBeenLastCalledWith({
|
||||
cwd: "/tmp/paseo-acp-test",
|
||||
mcpServers: [{ name: "local", command: "node", args: ["mcp.js"], env: [] }],
|
||||
});
|
||||
|
||||
const supported = new CapabilityTestSession(true, {
|
||||
provider: "test-acp",
|
||||
cwd: "/tmp/paseo-acp-test",
|
||||
mcpServers,
|
||||
});
|
||||
await supported.initializeNewSession();
|
||||
|
||||
expect(supported.capabilities.supportsMcpServers).toBe(true);
|
||||
expect(supported.capabilities.supportsHttpMcpServers).toBe(true);
|
||||
expect(newSession).toHaveBeenLastCalledWith({
|
||||
cwd: "/tmp/paseo-acp-test",
|
||||
mcpServers: [
|
||||
{
|
||||
type: "http",
|
||||
name: "paseo",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
headers: [],
|
||||
},
|
||||
{ name: "local", command: "node", args: ["mcp.js"], env: [] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("summarizes JSON-RPC error details without stringifying objects", () => {
|
||||
const summary = summarizeACPRequestError(
|
||||
new RequestError(-32603, "Internal error", {
|
||||
|
||||
@@ -1998,7 +1998,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
|
||||
export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
readonly provider: string;
|
||||
readonly capabilities: AgentCapabilityFlags;
|
||||
private readonly baseCapabilities: AgentCapabilityFlags;
|
||||
|
||||
private readonly logger: Logger;
|
||||
private readonly runtimeSettings?: ProviderRuntimeSettings;
|
||||
@@ -2083,7 +2083,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
constructor(config: AgentSessionConfig, options: ACPAgentSessionOptions) {
|
||||
this.provider = options.provider;
|
||||
this.terminateProcess = options.terminateProcess ?? terminateWithTreeKill;
|
||||
this.capabilities = options.capabilities;
|
||||
this.baseCapabilities = { ...options.capabilities };
|
||||
this.logger = options.logger.child({ module: "agent", provider: options.provider });
|
||||
this.runtimeSettings = options.runtimeSettings;
|
||||
this.defaultCommand = options.defaultCommand;
|
||||
@@ -2121,6 +2121,15 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
this.extensionCommandsParser = options.extensionCommandsParser;
|
||||
}
|
||||
|
||||
get capabilities(): AgentCapabilityFlags {
|
||||
return {
|
||||
...this.baseCapabilities,
|
||||
supportsHttpMcpServers:
|
||||
this.baseCapabilities.supportsMcpServers &&
|
||||
this.agentCapabilities?.mcpCapabilities?.http !== false,
|
||||
};
|
||||
}
|
||||
|
||||
get id(): string | null {
|
||||
return this.sessionId;
|
||||
}
|
||||
@@ -3387,7 +3396,14 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
}
|
||||
|
||||
private acpMcpServers(): McpServer[] {
|
||||
return this.capabilities.supportsMcpServers ? normalizeMcpServers(this.config.mcpServers) : [];
|
||||
if (!this.baseCapabilities.supportsMcpServers) {
|
||||
return [];
|
||||
}
|
||||
const servers = normalizeMcpServers(this.config.mcpServers);
|
||||
if (this.agentCapabilities?.mcpCapabilities?.http === false) {
|
||||
return servers.filter((server) => !("type" in server && server.type === "http"));
|
||||
}
|
||||
return servers;
|
||||
}
|
||||
|
||||
private applySessionState(response: SessionStateResponse): void {
|
||||
|
||||
@@ -1875,6 +1875,38 @@ describe("Codex app-server provider", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("auto-approves paseo speak tool during active voice sessions without restricting enabled_tools", async () => {
|
||||
const appServer = createFakeCodexAppServer();
|
||||
const session = await createProviderWithFakeAppServer(appServer).createSession(
|
||||
createConfig({
|
||||
modeId: "auto",
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
},
|
||||
}),
|
||||
{ voiceToolsEnabled: true },
|
||||
);
|
||||
try {
|
||||
await session.startTurn("say hello");
|
||||
const threadStart = appServer.requests().find((req) => req.method === "thread/start");
|
||||
const startConfig = (threadStart?.params as { config?: Record<string, unknown> } | undefined)
|
||||
?.config;
|
||||
expect(startConfig).toEqual({
|
||||
"mcp_servers.paseo": {
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
tools: { speak: { approval_mode: "approve" } },
|
||||
},
|
||||
});
|
||||
expect(startConfig).not.toHaveProperty("mcp_servers");
|
||||
expect(startConfig?.["mcp_servers.paseo"]).not.toHaveProperty("enabled_tools");
|
||||
expect(startConfig?.["mcp_servers.paseo"]).not.toHaveProperty("default_tools_approval_mode");
|
||||
appServer.completeTurn();
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("preapproves only granted tools on the injected Codex MCP server", async () => {
|
||||
const session = createSession({
|
||||
modeId: undefined,
|
||||
|
||||
@@ -142,10 +142,12 @@ import {
|
||||
} from "../provider-notices.js";
|
||||
import type { WorkspaceGitService } from "../../workspace-git-service.js";
|
||||
import {
|
||||
applyCodexMcpToolApproval,
|
||||
applyCodexToolPolicy,
|
||||
CodexProviderOptionsSchema,
|
||||
type CodexProviderOptions,
|
||||
} from "./codex/options.js";
|
||||
import { PASEO_MCP_SERVER_NAME } from "../runtime-mcp-config.js";
|
||||
|
||||
function assertChildWithPipes(
|
||||
child: ChildProcess,
|
||||
@@ -350,6 +352,7 @@ interface CodexAppServerAgentDeps {
|
||||
extends: string;
|
||||
};
|
||||
customCodexConfig?: CodexCustomProviderConfig | null;
|
||||
voiceToolsEnabled?: boolean;
|
||||
// The CODEX_HOME the session's app-server runs with; prompts and skills are read from it.
|
||||
codexHome?: string;
|
||||
_createCodexClient?: (
|
||||
@@ -6142,7 +6145,10 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
}
|
||||
const configured = applyCodexToolPolicy(innerConfig, this.config.toolPolicy);
|
||||
let configured = applyCodexToolPolicy(innerConfig, this.config.toolPolicy);
|
||||
if (this.deps.voiceToolsEnabled && this.config.mcpServers?.[PASEO_MCP_SERVER_NAME]) {
|
||||
configured = applyCodexMcpToolApproval(configured, PASEO_MCP_SERVER_NAME, "speak");
|
||||
}
|
||||
return Object.keys(configured).length > 0 ? configured : null;
|
||||
}
|
||||
|
||||
@@ -8363,7 +8369,11 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
null,
|
||||
this.logger,
|
||||
async () => spawn(),
|
||||
{ ...this.sessionDeps(launchContext?.env), environment },
|
||||
{
|
||||
...this.sessionDeps(launchContext?.env),
|
||||
environment,
|
||||
...(launchContext?.voiceToolsEnabled ? { voiceToolsEnabled: true } : {}),
|
||||
},
|
||||
options?.persistSession === false,
|
||||
goalsEnabled,
|
||||
autoReviewEnabled,
|
||||
@@ -8401,7 +8411,11 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
handle,
|
||||
this.logger,
|
||||
async () => spawn(),
|
||||
{ ...this.sessionDeps(launchContext?.env), environment },
|
||||
{
|
||||
...this.sessionDeps(launchContext?.env),
|
||||
environment,
|
||||
...(launchContext?.voiceToolsEnabled ? { voiceToolsEnabled: true } : {}),
|
||||
},
|
||||
false,
|
||||
goalsEnabled,
|
||||
autoReviewEnabled,
|
||||
|
||||
@@ -133,6 +133,49 @@ export function applyCodexToolPolicy(
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-approves a single tool on an already-configured Codex MCP server without
|
||||
* narrowing `enabled_tools` or changing `default_tools_approval_mode`, so other
|
||||
* tools on the same server keep their existing visibility and approval policy.
|
||||
*/
|
||||
export function applyCodexMcpToolApproval(
|
||||
config: Record<string, unknown>,
|
||||
server: string,
|
||||
tool: string,
|
||||
): Record<string, unknown> {
|
||||
const approveServerTool = (serverConfig: Record<string, unknown>): Record<string, unknown> => {
|
||||
const existingTools = readRecord(serverConfig.tools);
|
||||
let enabledTools: unknown[] | undefined;
|
||||
if (Array.isArray(serverConfig.enabled_tools)) {
|
||||
enabledTools = serverConfig.enabled_tools.includes(tool)
|
||||
? serverConfig.enabled_tools
|
||||
: [...serverConfig.enabled_tools, tool];
|
||||
}
|
||||
return {
|
||||
...serverConfig,
|
||||
...(enabledTools ? { enabled_tools: enabledTools } : {}),
|
||||
tools: {
|
||||
...existingTools,
|
||||
[tool]: { approval_mode: "approve" },
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
if ("mcp_servers" in config) {
|
||||
const mcpServers = readRecord(config.mcp_servers);
|
||||
if (!(server in mcpServers)) return config;
|
||||
mcpServers[server] = approveServerTool(readRecord(mcpServers[server]));
|
||||
return { ...config, mcp_servers: mcpServers };
|
||||
}
|
||||
|
||||
const key = `${MCP_SERVERS_PREFIX}${server}`;
|
||||
if (!(key in config)) return config;
|
||||
return {
|
||||
...config,
|
||||
[key]: approveServerTool(readRecord(config[key])),
|
||||
};
|
||||
}
|
||||
|
||||
function readRecord(value: unknown): Record<string, unknown> {
|
||||
return value != null && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ import { formatAttachmentContentDisposition } from "./file-download/content-disp
|
||||
import type { OpenAiSpeechProviderConfig } from "./speech/providers/openai/config.js";
|
||||
import type { LocalSpeechProviderConfig } from "./speech/providers/local/config.js";
|
||||
import type { RequestedSpeechProviders } from "./speech/speech-types.js";
|
||||
import { createSpeechService } from "./speech/speech-runtime.js";
|
||||
import { createSpeechService, type SpeechService } from "./speech/speech-runtime.js";
|
||||
import { createSpeechSettingsOwner } from "./speech/speech-settings.js";
|
||||
import { AgentManager } from "./agent/agent-manager.js";
|
||||
import { AgentStorage } from "./agent/agent-storage.js";
|
||||
@@ -133,7 +133,7 @@ import {
|
||||
type ResolvedDaemonSettings,
|
||||
type CliConfigOverrides,
|
||||
} from "./config.js";
|
||||
import { resolvePaseoToolPolicy } from "./agent/paseo-tool-policy.js";
|
||||
import { isPaseoToolPolicyEnabled, resolvePaseoToolPolicy } from "./agent/paseo-tool-policy.js";
|
||||
import { BrowserToolsBroker } from "./browser-tools/broker.js";
|
||||
import { DaemonConfigBrowserToolsPolicy } from "./browser-tools/policy.js";
|
||||
import { WorkspaceGitServiceImpl } from "./workspace-git-service.js";
|
||||
@@ -439,6 +439,7 @@ export interface PaseoDaemon {
|
||||
export interface PaseoDaemonDependencies {
|
||||
builtinPlugins?: BuiltinPluginLoader;
|
||||
lazyTerminalWorker?: boolean;
|
||||
speechService?: SpeechService;
|
||||
getTailscaleNetwork?: () => TailscaleNetwork;
|
||||
hubRelationshipRemote?: HubRelationshipRemote;
|
||||
hubRelationshipClock?: HubRelationshipClock;
|
||||
@@ -584,11 +585,13 @@ export async function createPaseoDaemon(
|
||||
const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`;
|
||||
const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url);
|
||||
const initialMutableConfig = createInitialMutableDaemonConfig(config);
|
||||
const speechService = createSpeechService({
|
||||
logger,
|
||||
openaiConfig: config.openai,
|
||||
speechConfig: config.speech,
|
||||
});
|
||||
const speechService =
|
||||
dependencies.speechService ??
|
||||
createSpeechService({
|
||||
logger,
|
||||
openaiConfig: config.openai,
|
||||
speechConfig: config.speech,
|
||||
});
|
||||
logger.info({ elapsed: elapsed() }, "Speech service created");
|
||||
const daemonConfigStore = new DaemonConfigStore(config.paseoHome, initialMutableConfig, logger, {
|
||||
relayEnabledMutable: config.relayEnabledMutable ?? true,
|
||||
@@ -988,6 +991,8 @@ export async function createPaseoDaemon(
|
||||
const git = daemonConfigStore.get().git;
|
||||
if (git) configureGitProcessPolicy(git);
|
||||
});
|
||||
const hasActiveVoiceTools = (agentId: string): boolean =>
|
||||
wsServer?.resolveVoiceCallerContext(agentId)?.enableVoiceTools === true;
|
||||
const initialAgentManagerState = providerSnapshotManager.getAgentManagerProviderState();
|
||||
const agentManager = new AgentManager({
|
||||
pluginLifecycle: pluginRuntime,
|
||||
@@ -1000,6 +1005,7 @@ export async function createPaseoDaemon(
|
||||
workspaceGitService.onWorkspaceStateMayHaveChanged(cwd);
|
||||
},
|
||||
mcpAuthToken: agentMcpAuthToken,
|
||||
hasActiveVoiceTools,
|
||||
resolvePaseoToolPolicy: (provider) =>
|
||||
resolvePaseoToolPolicy(provider, daemonConfigStore.get().providers),
|
||||
logger,
|
||||
@@ -1636,7 +1642,6 @@ export async function createPaseoDaemon(
|
||||
setAgentProviderToolsEnabled(config.mcpEnabled !== false && config.mcpInjectIntoAgents !== false);
|
||||
|
||||
let mcpEnabled = config.mcpEnabled ?? true;
|
||||
let agentMcpBaseUrl: string | null = null;
|
||||
{
|
||||
const agentMcpRoute = "/mcp/agents";
|
||||
|
||||
@@ -1645,14 +1650,20 @@ export async function createPaseoDaemon(
|
||||
// 2025-era clients through its stateless legacy fallback. No per-session
|
||||
// state is retained between requests, matching the previous
|
||||
// `sessionIdGenerator: undefined` transport.
|
||||
const createAgentMcpSession = async (callerAgentId?: string) => {
|
||||
if (callerAgentId) await agentManager.refreshPluginTools(callerAgentId);
|
||||
const createAgentMcpSession = async (
|
||||
callerAgentId?: string,
|
||||
options?: { voiceOnly?: boolean },
|
||||
) => {
|
||||
if (callerAgentId && !options?.voiceOnly) {
|
||||
await agentManager.refreshPluginTools(callerAgentId);
|
||||
}
|
||||
const agentMcpServer = await createAgentMcpServer(
|
||||
createAgentToolHostDependencies({
|
||||
callerAgentId,
|
||||
paseoToolPolicy: callerAgentId
|
||||
? agentManager.getPaseoToolPolicy(callerAgentId)
|
||||
: undefined,
|
||||
voiceOnly: options?.voiceOnly,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1669,7 +1680,17 @@ export async function createPaseoDaemon(
|
||||
req: express.Request,
|
||||
res: express.Response,
|
||||
): Promise<void> => {
|
||||
if (!mcpEnabled) {
|
||||
const callerAgentIdRaw = req.query.callerAgentId;
|
||||
let callerAgentId: string | undefined;
|
||||
if (typeof callerAgentIdRaw === "string") {
|
||||
callerAgentId = callerAgentIdRaw;
|
||||
} else if (Array.isArray(callerAgentIdRaw) && typeof callerAgentIdRaw[0] === "string") {
|
||||
callerAgentId = callerAgentIdRaw[0];
|
||||
}
|
||||
const voiceActive = Boolean(callerAgentId && hasActiveVoiceTools(callerAgentId));
|
||||
const isActiveLoopbackVoiceRequest =
|
||||
voiceActive && isLoopbackRemoteAddress(req.socket.remoteAddress);
|
||||
if (!mcpEnabled && !isActiveLoopbackVoiceRequest) {
|
||||
res.status(404).json({ error: "Agent MCP endpoint disabled" });
|
||||
return;
|
||||
}
|
||||
@@ -1714,14 +1735,11 @@ export async function createPaseoDaemon(
|
||||
});
|
||||
return;
|
||||
}
|
||||
const callerAgentIdRaw = req.query.callerAgentId;
|
||||
let callerAgentId: string | undefined;
|
||||
if (typeof callerAgentIdRaw === "string") {
|
||||
callerAgentId = callerAgentIdRaw;
|
||||
} else if (Array.isArray(callerAgentIdRaw) && typeof callerAgentIdRaw[0] === "string") {
|
||||
callerAgentId = callerAgentIdRaw[0];
|
||||
}
|
||||
const { handler } = await createAgentMcpSession(callerAgentId);
|
||||
const policy = callerAgentId ? agentManager.getPaseoToolPolicy(callerAgentId) : undefined;
|
||||
const generalPaseoToolsEnabled =
|
||||
mcpEnabled && agentManager.isPaseoToolsEnabled() && isPaseoToolPolicyEnabled(policy);
|
||||
const voiceOnly = voiceActive && !generalPaseoToolsEnabled;
|
||||
const { handler } = await createAgentMcpSession(callerAgentId, { voiceOnly });
|
||||
try {
|
||||
// express.json() already consumed the stream, so hand the parsed body over.
|
||||
await toNodeHandler(handler)(
|
||||
@@ -1822,21 +1840,18 @@ export async function createPaseoDaemon(
|
||||
);
|
||||
}
|
||||
const mcpBaseUrl = loopbackAgentEndpoint.getMcpBaseUrl();
|
||||
agentMcpBaseUrl =
|
||||
!mcpEnabled || config.mcpInjectIntoAgents === false ? null : mcpBaseUrl;
|
||||
agentManager.setMcpBaseUrl(agentMcpBaseUrl);
|
||||
agentManager.setMcpBaseUrl(mcpBaseUrl);
|
||||
agentManager.setPaseoToolsEnabled(mcpEnabled && config.mcpInjectIntoAgents !== false);
|
||||
daemonConfigStore.onFieldChange("mcp.enabled", (value) => {
|
||||
mcpEnabled = value !== false;
|
||||
const inject = daemonConfigStore.get().mcp.injectIntoAgents !== false;
|
||||
agentManager.setMcpBaseUrl(mcpEnabled && inject ? mcpBaseUrl : null);
|
||||
agentManager.setPaseoToolsEnabled(mcpEnabled && inject);
|
||||
setAgentProviderToolsEnabled(mcpEnabled && inject);
|
||||
});
|
||||
daemonConfigStore.onFieldChange("mcp.injectIntoAgents", (value) => {
|
||||
agentManager.setMcpBaseUrl(mcpEnabled && value ? mcpBaseUrl : null);
|
||||
agentManager.setPaseoToolsEnabled(mcpEnabled && value !== false);
|
||||
setAgentProviderToolsEnabled(mcpEnabled && value !== false);
|
||||
const inject = value !== false;
|
||||
agentManager.setPaseoToolsEnabled(mcpEnabled && inject);
|
||||
setAgentProviderToolsEnabled(mcpEnabled && inject);
|
||||
});
|
||||
daemonConfigStore.onFieldChange("appendSystemPrompt", (value) => {
|
||||
agentManager.setAppendSystemPrompt(typeof value === "string" ? value : "");
|
||||
|
||||
@@ -1424,8 +1424,8 @@ export class Session {
|
||||
agentStorage: this.agentStorage,
|
||||
logger: this.sessionLogger,
|
||||
}),
|
||||
reloadAgentSession: (agentId, overrides) =>
|
||||
this.agentManager.reloadAgentSession(agentId, overrides),
|
||||
reloadAgentSession: (agentId, overrides, reloadOptions) =>
|
||||
this.agentManager.reloadAgentSession(agentId, overrides, reloadOptions),
|
||||
sendSpokenInput: async (agentId, text) => {
|
||||
await this.handleSendAgentMessage(
|
||||
agentId,
|
||||
|
||||
@@ -325,4 +325,94 @@ describe("VoiceSession streaming transcription", () => {
|
||||
|
||||
await voiceSession.cleanup();
|
||||
});
|
||||
|
||||
test("rejects set_voice_mode and cleans up voice bridge when speak capability check fails", async () => {
|
||||
const events: string[] = [];
|
||||
const host = createFakeHost();
|
||||
const reloadOptions: Array<unknown> = [];
|
||||
host.reloadAgentSession = async (_agentId, _overrides, options) => {
|
||||
reloadOptions.push(options);
|
||||
throw new Error(
|
||||
"Voice mode is unavailable for provider 'pi': the session does not expose Paseo's 'speak' tool",
|
||||
);
|
||||
};
|
||||
const voiceSession = new VoiceSession({
|
||||
host,
|
||||
logger: pino({ level: "silent" }),
|
||||
sessionId: "voice-capability-reject-test",
|
||||
sttLanguage: "en",
|
||||
tts: null,
|
||||
stt: { id: "local", createSession: vi.fn(() => new FakeVoiceSttSession()) },
|
||||
voice: {
|
||||
turnDetection: {
|
||||
id: "local",
|
||||
createSession: vi.fn(() => new FakeVoiceTurnDetectionSession()),
|
||||
},
|
||||
},
|
||||
voiceBridge: {
|
||||
registerVoiceSpeakHandler: (id) => events.push(`register-speak:${id}`),
|
||||
unregisterVoiceSpeakHandler: (id) => events.push(`unregister-speak:${id}`),
|
||||
registerVoiceCallerContext: (id) => events.push(`register-ctx:${id}`),
|
||||
unregisterVoiceCallerContext: (id) => events.push(`unregister-ctx:${id}`),
|
||||
},
|
||||
});
|
||||
|
||||
await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "req-voice-1");
|
||||
|
||||
expect(reloadOptions).toEqual([{ requireVoiceSpeak: true }]);
|
||||
expect(events).toEqual([
|
||||
`register-speak:${VOICE_AGENT_ID}`,
|
||||
`register-ctx:${VOICE_AGENT_ID}`,
|
||||
`unregister-speak:${VOICE_AGENT_ID}`,
|
||||
`unregister-ctx:${VOICE_AGENT_ID}`,
|
||||
]);
|
||||
expect(voiceSession.isActiveForAgent(VOICE_AGENT_ID)).toBe(false);
|
||||
expect(host.emitted).toContainEqual({
|
||||
type: "set_voice_mode_response",
|
||||
payload: {
|
||||
requestId: "req-voice-1",
|
||||
enabled: false,
|
||||
agentId: null,
|
||||
accepted: false,
|
||||
error:
|
||||
"Voice mode is unavailable for provider 'pi': the session does not expose Paseo's 'speak' tool",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("unregisters voice bridge before reloading when disabling voice mode", async () => {
|
||||
const order: string[] = [];
|
||||
const host = createFakeHost();
|
||||
host.reloadAgentSession = async (agentId) => {
|
||||
order.push(`reload:${agentId}`);
|
||||
return { id: agentId } as unknown as ManagedAgent;
|
||||
};
|
||||
const voiceSession = new VoiceSession({
|
||||
host,
|
||||
logger: pino({ level: "silent" }),
|
||||
sessionId: "voice-disable-order-test",
|
||||
sttLanguage: "en",
|
||||
tts: null,
|
||||
stt: { id: "local", createSession: vi.fn(() => new FakeVoiceSttSession()) },
|
||||
voice: {
|
||||
turnDetection: {
|
||||
id: "local",
|
||||
createSession: vi.fn(() => new FakeVoiceTurnDetectionSession()),
|
||||
},
|
||||
},
|
||||
voiceBridge: {
|
||||
registerVoiceSpeakHandler: () => order.push("register-speak"),
|
||||
unregisterVoiceSpeakHandler: () => order.push("unregister-speak"),
|
||||
registerVoiceCallerContext: () => order.push("register-ctx"),
|
||||
unregisterVoiceCallerContext: () => order.push("unregister-ctx"),
|
||||
},
|
||||
});
|
||||
|
||||
await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "req-on");
|
||||
order.length = 0;
|
||||
|
||||
await voiceSession.handleSetVoiceMode(false, VOICE_AGENT_ID, "req-off");
|
||||
|
||||
expect(order).toEqual(["unregister-speak", "unregister-ctx", `reload:${VOICE_AGENT_ID}`]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -125,6 +125,7 @@ export interface VoiceSessionHost {
|
||||
reloadAgentSession(
|
||||
agentId: string,
|
||||
overrides: Partial<AgentSessionConfig>,
|
||||
options?: { requireVoiceSpeak?: boolean },
|
||||
): Promise<ManagedAgent>;
|
||||
sendSpokenInput(agentId: string, text: string): Promise<void>;
|
||||
interruptAgentIfRunning(agentId: string): Promise<void>;
|
||||
@@ -513,7 +514,9 @@ export class VoiceSession {
|
||||
{ agentId, elapsedMs: Date.now() - startedAt },
|
||||
"enableVoiceModeForAgent.reloadAgentSession.start",
|
||||
);
|
||||
const refreshed = await this.host.reloadAgentSession(agentId, refreshOverrides);
|
||||
const refreshed = await this.host.reloadAgentSession(agentId, refreshOverrides, {
|
||||
requireVoiceSpeak: true,
|
||||
});
|
||||
this.sessionLogger.info(
|
||||
{ agentId, refreshedAgentId: refreshed.id, elapsedMs: Date.now() - startedAt },
|
||||
"enableVoiceModeForAgent.reloadAgentSession.done",
|
||||
@@ -536,6 +539,9 @@ export class VoiceSession {
|
||||
return;
|
||||
}
|
||||
|
||||
this.unregisterVoiceSpeakHandler?.(agentId);
|
||||
this.unregisterVoiceCallerContext?.(agentId);
|
||||
|
||||
if (restoreAgentConfig && this.voiceModeBaseConfig) {
|
||||
const baseConfig = this.voiceModeBaseConfig;
|
||||
try {
|
||||
@@ -550,8 +556,6 @@ export class VoiceSession {
|
||||
}
|
||||
}
|
||||
|
||||
this.unregisterVoiceSpeakHandler?.(agentId);
|
||||
this.unregisterVoiceCallerContext?.(agentId);
|
||||
this.voiceModeBaseConfig = null;
|
||||
this.voiceModeAgentId = null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user