fix: load default model if no models, only option in headless
This commit is contained in:
parent
2854b139ca
commit
760d370edf
9 changed files with 405 additions and 298 deletions
|
|
@ -353,7 +353,32 @@ describe("remote command", () => {
|
|||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
body: expect.stringContaining(`"agent":"${testConfig}"`),
|
||||
body: expect.stringContaining(`"config":"${testConfig}"`),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should include agent in request body when agent option is provided", async () => {
|
||||
const testAgent = "test-agent";
|
||||
|
||||
await remote("test prompt", { agent: testAgent });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.stringContaining(`"agent":"${testAgent}"`),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
body: expect.stringContaining(`"agent":"${testAgent}"`),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
|
@ -375,11 +400,31 @@ describe("remote command", () => {
|
|||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
prompt: "test prompt",
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
agent: testConfig,
|
||||
config: testConfig,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle proper request body structure with agent field", async () => {
|
||||
const testAgent = "my-agent";
|
||||
const testIdempotencyKey = "test-with-config";
|
||||
|
||||
await remote("test prompt", {
|
||||
agent: testAgent,
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
});
|
||||
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
|
||||
expect(requestBody).toEqual({
|
||||
repoUrl: "https://github.com/user/test-repo.git",
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
prompt: "test prompt",
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
agent: testAgent,
|
||||
});
|
||||
});
|
||||
|
||||
it("should not include config in request body when config option is not provided", async () => {
|
||||
await remote("test prompt", {});
|
||||
|
||||
|
|
|
|||
|
|
@ -35,7 +35,8 @@ export type ConfigSource =
|
|||
| { type: "saved-uri"; uri: string }
|
||||
| { type: "user-assistant"; slug: string }
|
||||
| { type: "default-config-yaml" }
|
||||
| { type: "default-agent" };
|
||||
| { type: "default-agent" }
|
||||
| { type: "no-config" };
|
||||
|
||||
/**
|
||||
* Streamlined configuration loader that implements the specification
|
||||
|
|
@ -46,12 +47,17 @@ export async function loadConfiguration(
|
|||
cliConfigPath: string | undefined,
|
||||
apiClient: DefaultApiInterface,
|
||||
injectBlocks: PackageIdentifier[],
|
||||
isHeadless: boolean | undefined,
|
||||
): Promise<ConfigLoadResult> {
|
||||
const organizationId = getOrganizationId(authConfig);
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
|
||||
// Step 1: Determine config source using precedence rules
|
||||
const configSource = determineConfigSource(authConfig, cliConfigPath);
|
||||
const configSource = determineConfigSource(
|
||||
authConfig,
|
||||
cliConfigPath,
|
||||
isHeadless,
|
||||
);
|
||||
|
||||
// Step 2: Load configuration from the determined source
|
||||
const config = await loadFromSource(
|
||||
|
|
@ -82,12 +88,18 @@ export async function loadConfiguration(
|
|||
function determineConfigSource(
|
||||
authConfig: AuthConfig,
|
||||
cliConfigPath: string | undefined,
|
||||
isHeadless: boolean | undefined,
|
||||
): ConfigSource {
|
||||
// Priority 1: CLI --config flag
|
||||
if (cliConfigPath) {
|
||||
return { type: "cli-flag", path: cliConfigPath };
|
||||
}
|
||||
|
||||
// In headless, config fallback behavior isn't supported
|
||||
if (isHeadless) {
|
||||
return { type: "no-config" };
|
||||
}
|
||||
|
||||
// Priority 2: Saved config URI (only for file-based auth)
|
||||
if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
|
||||
const savedUri = getConfigUri(authConfig);
|
||||
|
|
@ -164,6 +176,12 @@ async function loadFromSource(
|
|||
injectBlocks,
|
||||
);
|
||||
|
||||
case "no-config":
|
||||
return {
|
||||
name: "No Config Specified",
|
||||
version: "1.0.0",
|
||||
};
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown config source type: ${(source as any).type}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -147,6 +147,7 @@ export async function initializeWithOnboarding(
|
|||
configPath,
|
||||
getApiClient(authConfig?.accessToken),
|
||||
[],
|
||||
false,
|
||||
);
|
||||
} catch (errorMessage) {
|
||||
throw new Error(
|
||||
|
|
|
|||
|
|
@ -1,206 +0,0 @@
|
|||
// import {
|
||||
// AuthenticatedConfig,
|
||||
// login as doLogin,
|
||||
// logout as doLogout,
|
||||
// ensureOrganization,
|
||||
// isAuthenticated,
|
||||
// listUserOrganizations,
|
||||
// loadAuthConfig,
|
||||
// saveAuthConfig,
|
||||
// } from "../auth/workos.js";
|
||||
// import { logger } from "../util/logger.js";
|
||||
|
||||
// import { BaseService } from "./BaseService.js";
|
||||
// import { AuthServiceState } from "./types.js";
|
||||
|
||||
// /**
|
||||
// * Service for managing authentication state and operations
|
||||
// * Now extends BaseService for common functionality
|
||||
// */
|
||||
// export class AuthService extends BaseService<AuthServiceState> {
|
||||
// constructor() {
|
||||
// super("AuthService", {
|
||||
// authConfig: null,
|
||||
// isAuthenticated: false,
|
||||
// });
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Initialize the auth service by loading current config
|
||||
// */
|
||||
// async doInitialize(): Promise<AuthServiceState> {
|
||||
// const authConfig = loadAuthConfig();
|
||||
// const authenticated = isAuthenticated();
|
||||
|
||||
// const state: AuthServiceState = {
|
||||
// authConfig,
|
||||
// isAuthenticated: authenticated,
|
||||
// organizationId: authConfig?.organizationId || undefined,
|
||||
// };
|
||||
|
||||
// logger.debug("AuthService initialized", {
|
||||
// authenticated,
|
||||
// hasConfig: !!authConfig,
|
||||
// orgId: state.organizationId,
|
||||
// });
|
||||
|
||||
// return state;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Perform login flow
|
||||
// */
|
||||
// async login(): Promise<AuthServiceState> {
|
||||
// logger.debug("Starting login flow");
|
||||
|
||||
// try {
|
||||
// const newAuthConfig = await doLogin();
|
||||
|
||||
// this.setState({
|
||||
// authConfig: newAuthConfig,
|
||||
// isAuthenticated: true,
|
||||
// organizationId: newAuthConfig?.organizationId || undefined,
|
||||
// });
|
||||
|
||||
// logger.debug("Login successful", {
|
||||
// orgId: this.currentState.organizationId,
|
||||
// });
|
||||
|
||||
// return this.getState();
|
||||
// } catch (error: any) {
|
||||
// logger.error("Login failed:", error);
|
||||
// this.emit("error", error);
|
||||
// throw error;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Perform logout
|
||||
// */
|
||||
// async logout(): Promise<AuthServiceState> {
|
||||
// logger.debug("Logging out");
|
||||
|
||||
// doLogout();
|
||||
|
||||
// this.setState({
|
||||
// authConfig: null,
|
||||
// isAuthenticated: false,
|
||||
// organizationId: undefined,
|
||||
// });
|
||||
|
||||
// logger.debug("Logout complete");
|
||||
// return this.getState();
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Ensure organization is selected, prompting if necessary
|
||||
// */
|
||||
// async ensureOrganization(
|
||||
// isHeadless: boolean = false,
|
||||
// ): Promise<AuthServiceState> {
|
||||
// if (!this.currentState.authConfig) {
|
||||
// throw new Error("Not authenticated - cannot ensure organization");
|
||||
// }
|
||||
|
||||
// logger.debug("Ensuring organization is selected", {
|
||||
// currentOrgId: this.currentState.organizationId,
|
||||
// isHeadless,
|
||||
// });
|
||||
|
||||
// const updatedConfig = await ensureOrganization(
|
||||
// this.currentState.authConfig,
|
||||
// isHeadless,
|
||||
// );
|
||||
|
||||
// this.setState({
|
||||
// authConfig: updatedConfig,
|
||||
// isAuthenticated: true,
|
||||
// organizationId: updatedConfig?.organizationId || undefined,
|
||||
// });
|
||||
|
||||
// logger.debug("Organization ensured", {
|
||||
// orgId: this.currentState.organizationId,
|
||||
// });
|
||||
|
||||
// return this.getState();
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Switch to a different organization
|
||||
// */
|
||||
// async switchOrganization(
|
||||
// organizationId: string | null,
|
||||
// ): Promise<AuthServiceState> {
|
||||
// if (
|
||||
// !this.currentState.authConfig ||
|
||||
// !("userId" in this.currentState.authConfig)
|
||||
// ) {
|
||||
// throw new Error(
|
||||
// "Not authenticated with file-based auth - cannot switch organizations",
|
||||
// );
|
||||
// }
|
||||
|
||||
// logger.debug("Switching organization", {
|
||||
// from: this.currentState.organizationId,
|
||||
// to: organizationId,
|
||||
// });
|
||||
|
||||
// const authenticatedConfig = this.currentState
|
||||
// .authConfig as AuthenticatedConfig;
|
||||
|
||||
// const updatedConfig: AuthenticatedConfig = {
|
||||
// ...authenticatedConfig,
|
||||
// organizationId,
|
||||
// };
|
||||
|
||||
// saveAuthConfig(updatedConfig);
|
||||
|
||||
// this.setState({
|
||||
// authConfig: updatedConfig,
|
||||
// isAuthenticated: true,
|
||||
// organizationId: organizationId || undefined,
|
||||
// });
|
||||
|
||||
// logger.debug("Organization switched", {
|
||||
// newOrgId: this.currentState.organizationId,
|
||||
// });
|
||||
|
||||
// return this.getState();
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Get available organizations for the current user
|
||||
// */
|
||||
// async getAvailableOrganizations(): Promise<
|
||||
// { id: string; name: string }[] | null
|
||||
// > {
|
||||
// if (!this.currentState.isAuthenticated) {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// try {
|
||||
// return await listUserOrganizations();
|
||||
// } catch (error: any) {
|
||||
// logger.error("Failed to list organizations:", error);
|
||||
// this.emit("error", error);
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Check if the current user has multiple organizations available
|
||||
// */
|
||||
// async hasMultipleOrganizations(): Promise<boolean> {
|
||||
// const orgs = await this.getAvailableOrganizations();
|
||||
// return orgs !== null && orgs.length > 0;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Refresh auth state from disk (useful after external changes)
|
||||
// */
|
||||
// async refresh(): Promise<AuthServiceState> {
|
||||
// logger.debug("Refreshing auth state from disk");
|
||||
// return this.reload();
|
||||
// }
|
||||
// }
|
||||
export {};
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import {
|
||||
decodePackageIdentifier,
|
||||
mergeUnrolledAssistants,
|
||||
ModelRole,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
|
|
@ -11,16 +12,33 @@ import { ConfigService } from "./ConfigService.js";
|
|||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import { AgentFileServiceState, SERVICE_NAMES } from "./types.js";
|
||||
vi.mock("../auth/workos.js");
|
||||
vi.mock("../configLoader.js");
|
||||
vi.mock("../configLoader.js", () => ({
|
||||
loadConfiguration: vi.fn(),
|
||||
unrollPackageIdentifiersAsConfigYaml: vi.fn(),
|
||||
}));
|
||||
vi.mock("../util/logger.js");
|
||||
vi.mock("./ServiceContainer.js");
|
||||
vi.mock("@continuedev/config-yaml");
|
||||
|
||||
const defaultModel = {
|
||||
provider: "anthropic",
|
||||
name: "claude-sonnet-4.5",
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
roles: ["chat"] as ModelRole[],
|
||||
};
|
||||
|
||||
describe("ConfigService", () => {
|
||||
let service: ConfigService;
|
||||
const mockConfig = {
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
models: [
|
||||
{
|
||||
name: "existing-model",
|
||||
model: "gpt-4",
|
||||
roles: ["chat"],
|
||||
},
|
||||
],
|
||||
systemMessage: "Test system message",
|
||||
} as any;
|
||||
const mockApiClient = { get: vi.fn(), post: vi.fn() };
|
||||
|
|
@ -45,6 +63,17 @@ describe("ConfigService", () => {
|
|||
versionSlug: "version",
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock the default model loading function
|
||||
vi.mocked(
|
||||
configLoader.unrollPackageIdentifiersAsConfigYaml,
|
||||
).mockResolvedValue({
|
||||
block: {
|
||||
name: "default-chat-model",
|
||||
version: "1.0.0",
|
||||
models: [defaultModel],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("State Management", () => {
|
||||
|
|
@ -270,7 +299,8 @@ describe("ConfigService", () => {
|
|||
} as any);
|
||||
vi.mocked(serviceContainer.get)
|
||||
.mockResolvedValueOnce({ apiClient: mockApiClient })
|
||||
.mockResolvedValueOnce(mockAgentFileState);
|
||||
.mockResolvedValueOnce(mockAgentFileState)
|
||||
.mockResolvedValueOnce({ isHeadless: false });
|
||||
|
||||
// Mock new config load
|
||||
const newConfig = { ...mockConfig, name: "new-assistant" } as any;
|
||||
|
|
@ -472,6 +502,249 @@ describe("ConfigService", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("addDefaultChatModelIfNone()", () => {
|
||||
test("should add default model when no chat models exist", async () => {
|
||||
const config = {
|
||||
name: "test-config",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
name: "non-chat-model",
|
||||
model: "test-model",
|
||||
roles: ["embed", "rerank"], // No "chat" role
|
||||
},
|
||||
],
|
||||
} as any;
|
||||
|
||||
// Mock the default model loading
|
||||
vi.mocked(
|
||||
configLoader.unrollPackageIdentifiersAsConfigYaml,
|
||||
).mockResolvedValue({
|
||||
block: {
|
||||
name: "default",
|
||||
version: "1.0.0",
|
||||
models: [defaultModel],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
);
|
||||
|
||||
expect(
|
||||
vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml),
|
||||
).toHaveBeenCalledWith(
|
||||
[
|
||||
{
|
||||
uriType: "slug",
|
||||
fullSlug: {
|
||||
ownerSlug: "anthropic",
|
||||
packageSlug: "claude-sonnet-4-5",
|
||||
versionSlug: "1.0.0",
|
||||
},
|
||||
},
|
||||
],
|
||||
"token",
|
||||
null,
|
||||
mockApiClient,
|
||||
);
|
||||
|
||||
expect(result.models).toHaveLength(2);
|
||||
expect(result.models![1]).toEqual(defaultModel);
|
||||
});
|
||||
|
||||
test("should not add default model when chat model already exists", async () => {
|
||||
const config = {
|
||||
name: "test-config",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
name: "existing-chat-model",
|
||||
model: "gpt-4",
|
||||
roles: ["chat"],
|
||||
},
|
||||
],
|
||||
} as any;
|
||||
|
||||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
);
|
||||
|
||||
// Should not call the unroll function since chat model exists
|
||||
expect(
|
||||
vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml),
|
||||
).not.toHaveBeenCalled();
|
||||
expect(result).toBe(config); // Should return unchanged config
|
||||
});
|
||||
|
||||
test("should not add default model when model with no roles exists (defaults to chat)", async () => {
|
||||
const config = {
|
||||
name: "test-config",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
name: "model-with-no-roles",
|
||||
model: "gpt-4",
|
||||
// No roles specified, defaults to including chat
|
||||
},
|
||||
],
|
||||
} as any;
|
||||
|
||||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
);
|
||||
|
||||
expect(
|
||||
vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml),
|
||||
).not.toHaveBeenCalled();
|
||||
expect(result).toBe(config);
|
||||
});
|
||||
|
||||
test("should handle empty models array by adding default model", async () => {
|
||||
const config = {
|
||||
name: "test-config",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
} as any;
|
||||
|
||||
vi.mocked(
|
||||
configLoader.unrollPackageIdentifiersAsConfigYaml,
|
||||
).mockResolvedValue({
|
||||
block: {
|
||||
name: "default",
|
||||
version: "1.0.0",
|
||||
models: [defaultModel],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
);
|
||||
|
||||
expect(result.models).toHaveLength(1);
|
||||
expect(result.models![0]).toEqual(defaultModel);
|
||||
});
|
||||
|
||||
test("should handle undefined models by adding default model", async () => {
|
||||
const config = {
|
||||
name: "test-config",
|
||||
version: "1.0.0",
|
||||
// models is undefined
|
||||
} as any;
|
||||
|
||||
vi.mocked(
|
||||
configLoader.unrollPackageIdentifiersAsConfigYaml,
|
||||
).mockResolvedValue({
|
||||
block: {
|
||||
name: "default",
|
||||
version: "1.0.0",
|
||||
models: [defaultModel],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
);
|
||||
|
||||
expect(result.models).toHaveLength(1);
|
||||
expect(result.models![0]).toEqual(defaultModel);
|
||||
});
|
||||
|
||||
test("should throw error when default model fails to load", async () => {
|
||||
const config = {
|
||||
name: "test-config",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
} as any;
|
||||
|
||||
const error = new Error("Failed to load default model");
|
||||
vi.mocked(
|
||||
configLoader.unrollPackageIdentifiersAsConfigYaml,
|
||||
).mockRejectedValue(error);
|
||||
|
||||
await expect(
|
||||
service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
),
|
||||
).rejects.toThrow("No model specified and failed to load default model");
|
||||
});
|
||||
|
||||
test("should throw error when loaded default model is empty", async () => {
|
||||
const config = {
|
||||
name: "test-config",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
} as any;
|
||||
|
||||
// Mock empty model config
|
||||
vi.mocked(
|
||||
configLoader.unrollPackageIdentifiersAsConfigYaml,
|
||||
).mockResolvedValue({
|
||||
block: {
|
||||
name: "default",
|
||||
version: "1.0.0",
|
||||
models: [], // Empty models array
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
{ accessToken: "token" } as any,
|
||||
),
|
||||
).rejects.toThrow("No model specified and failed to load default model");
|
||||
});
|
||||
|
||||
test("should work with null access token", async () => {
|
||||
const config = {
|
||||
name: "test-config",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
} as any;
|
||||
|
||||
vi.mocked(
|
||||
configLoader.unrollPackageIdentifiersAsConfigYaml,
|
||||
).mockResolvedValue({
|
||||
block: {
|
||||
name: "default",
|
||||
version: "1.0.0",
|
||||
models: [defaultModel],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.addDefaultChatModelIfNone(
|
||||
config,
|
||||
mockApiClient as any,
|
||||
undefined, // No auth config
|
||||
);
|
||||
|
||||
expect(
|
||||
vi.mocked(configLoader.unrollPackageIdentifiersAsConfigYaml),
|
||||
).toHaveBeenCalledWith(
|
||||
expect.any(Array),
|
||||
null, // Should pass null for access token
|
||||
null, // Should pass null for organization ID
|
||||
mockApiClient,
|
||||
);
|
||||
|
||||
expect(result.models).toHaveLength(1);
|
||||
expect(result.models![0]).toEqual(defaultModel);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Legacy Compatibility", () => {
|
||||
test("updateConfigPath method exists and has correct signature", () => {
|
||||
// Test that the updateConfigPath method exists and is a function
|
||||
|
|
|
|||
|
|
@ -11,11 +11,15 @@ import { getErrorString } from "src/util/error.js";
|
|||
|
||||
import { AuthConfig, loadAuthConfig } from "../auth/workos.js";
|
||||
import { BaseCommandOptions } from "../commands/BaseCommandOptions.js";
|
||||
import { loadConfiguration } from "../configLoader.js";
|
||||
import {
|
||||
loadConfiguration,
|
||||
unrollPackageIdentifiersAsConfigYaml,
|
||||
} from "../configLoader.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import { ToolPermissionServiceState } from "./ToolPermissionService.js";
|
||||
import {
|
||||
AgentFileServiceState,
|
||||
ApiClientServiceState,
|
||||
|
|
@ -23,12 +27,22 @@ import {
|
|||
SERVICE_NAMES,
|
||||
} from "./types.js";
|
||||
|
||||
const DEFAULT_MODEL_IDENTIFIER: PackageIdentifier = {
|
||||
uriType: "slug",
|
||||
fullSlug: {
|
||||
ownerSlug: "anthropic",
|
||||
packageSlug: "claude-sonnet-4-5",
|
||||
versionSlug: "1.0.0",
|
||||
},
|
||||
};
|
||||
|
||||
interface ConfigServiceInit {
|
||||
authConfig: AuthConfig;
|
||||
configPath: string | undefined;
|
||||
apiClient: DefaultApiInterface;
|
||||
agentFileState: AgentFileServiceState;
|
||||
injectedConfigOptions?: BaseCommandOptions;
|
||||
isHeadless?: boolean;
|
||||
}
|
||||
/**
|
||||
* Service for managing configuration state and operations
|
||||
|
|
@ -197,6 +211,35 @@ export class ConfigService
|
|||
return value.startsWith("http://") || value.startsWith("https://");
|
||||
}
|
||||
|
||||
async addDefaultChatModelIfNone(
|
||||
config: AssistantUnrolled,
|
||||
apiClient: DefaultApiInterface,
|
||||
authConfig: AuthConfig | undefined,
|
||||
): Promise<AssistantUnrolled> {
|
||||
const hasChatModel = !!config.models?.find(
|
||||
(m) => !!m && (!m.roles || m.roles.includes("chat")),
|
||||
);
|
||||
if (!hasChatModel) {
|
||||
try {
|
||||
const modelConfig = await unrollPackageIdentifiersAsConfigYaml(
|
||||
[DEFAULT_MODEL_IDENTIFIER],
|
||||
authConfig?.accessToken ?? null,
|
||||
authConfig?.organizationId ?? null,
|
||||
apiClient,
|
||||
);
|
||||
const defaultModel = modelConfig?.block?.models?.[0];
|
||||
if (!defaultModel) {
|
||||
throw new Error("Loaded default model contained no model block");
|
||||
}
|
||||
config.models = [...(config.models || []), defaultModel];
|
||||
} catch (e) {
|
||||
logger.error("Failed to load default model with no model specified", e);
|
||||
throw new Error("No model specified and failed to load default model");
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private async loadConfig(
|
||||
init: ConfigServiceInit,
|
||||
): Promise<ConfigServiceState> {
|
||||
|
|
@ -217,16 +260,23 @@ export class ConfigService
|
|||
configPath,
|
||||
apiClient,
|
||||
injected,
|
||||
init.isHeadless,
|
||||
);
|
||||
|
||||
const loadedConfig = result.config;
|
||||
const merged = mergeUnrolledAssistants(loadedConfig, additional);
|
||||
|
||||
const withModel = await this.addDefaultChatModelIfNone(
|
||||
merged,
|
||||
apiClient,
|
||||
authConfig,
|
||||
);
|
||||
|
||||
// Config URI persistence is now handled by the streamlined loader
|
||||
logger.debug("ConfigService initialized successfully");
|
||||
|
||||
const state = {
|
||||
config: merged,
|
||||
config: withModel,
|
||||
configPath,
|
||||
};
|
||||
this.setState(state);
|
||||
|
|
@ -312,12 +362,18 @@ export class ConfigService
|
|||
SERVICE_NAMES.AGENT_FILE,
|
||||
);
|
||||
|
||||
const toolPermissionsState =
|
||||
await serviceContainer.get<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
|
||||
const result = await this.loadConfig({
|
||||
agentFileState,
|
||||
apiClient,
|
||||
authConfig,
|
||||
configPath: newConfigPath,
|
||||
injectedConfigOptions: {},
|
||||
isHeadless: toolPermissionsState.isHeadless,
|
||||
});
|
||||
|
||||
// Manually reload dependent services (MODEL, MCP) to pick up the new config
|
||||
|
|
|
|||
|
|
@ -100,45 +100,6 @@ describe("ModelService", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("update()", () => {
|
||||
test("should update model with new assistant config", async () => {
|
||||
// Initialize first
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
// Update with new assistant
|
||||
const newAssistant = {
|
||||
...mockAssistant,
|
||||
models: [
|
||||
{
|
||||
provider: "openai",
|
||||
model: "gpt-4-turbo",
|
||||
name: "GPT-4 Turbo",
|
||||
apiKey: "new-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
],
|
||||
};
|
||||
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
newLlmApi as any,
|
||||
newAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
|
||||
const state = await service.update(newAssistant, mockAuthConfig);
|
||||
|
||||
expect(state).toEqual({
|
||||
llmApi: newLlmApi,
|
||||
model: newAssistant.models![0],
|
||||
assistant: newAssistant,
|
||||
authConfig: mockAuthConfig,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("switchModel()", () => {
|
||||
test("should switch to a different model by index", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ export class ModelService
|
|||
async doInitialize(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig,
|
||||
agentFileServiceState?: AgentFileServiceState,
|
||||
agentFileServiceState: AgentFileServiceState | undefined,
|
||||
): Promise<ModelServiceState> {
|
||||
logger.debug("ModelService.doInitialize called", {
|
||||
hasAssistant: !!assistant,
|
||||
|
|
@ -122,48 +122,6 @@ export class ModelService
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the model based on new config or auth changes
|
||||
*/
|
||||
async update(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig,
|
||||
): Promise<ModelServiceState> {
|
||||
logger.debug("Updating ModelService");
|
||||
|
||||
try {
|
||||
// Update instance properties for backward compatibility
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter(
|
||||
(model) =>
|
||||
model && (model.roles?.includes("chat") || model.roles === undefined),
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
|
||||
// Ensure state has all necessary data
|
||||
this.setState({
|
||||
llmApi,
|
||||
model,
|
||||
assistant,
|
||||
authConfig,
|
||||
});
|
||||
|
||||
logger.debug("ModelService updated successfully", {
|
||||
modelProvider: model.provider,
|
||||
modelName: (model as any).name || "unnamed",
|
||||
availableModels: this.availableModels.length,
|
||||
});
|
||||
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to update ModelService:", error);
|
||||
this.emit("error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Override isReady to check for required state
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -212,13 +212,14 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
|
|||
}
|
||||
}
|
||||
|
||||
return configService.initialize({
|
||||
return await configService.initialize({
|
||||
authConfig: finalAuthState.authConfig,
|
||||
configPath,
|
||||
// organizationId: finalAuthState.organizationId || null,
|
||||
apiClient: apiClientState.apiClient,
|
||||
agentFileState,
|
||||
injectedConfigOptions: commandOptions,
|
||||
isHeadless: initOptions.headless,
|
||||
});
|
||||
},
|
||||
[SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.AGENT_FILE], // Dependencies
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue