Merge branch 'main' of https://github.com/continuedev/cli into pe/readable-help-text
This commit is contained in:
commit
38eb5d8960
211 changed files with 10083 additions and 5666 deletions
2
.github/workflows/pr_checks.yml
vendored
2
.github/workflows/pr_checks.yml
vendored
|
|
@ -41,7 +41,7 @@ jobs:
|
|||
- name: Run tests (excluding e2e on Windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: bash
|
||||
run: npm test -- --testPathIgnorePatterns='.*e2e.*'
|
||||
run: npm test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**'
|
||||
|
||||
- name: Run linting
|
||||
run: npm run lint
|
||||
|
|
|
|||
8
.github/workflows/release.yml
vendored
8
.github/workflows/release.yml
vendored
|
|
@ -1,9 +1,9 @@
|
|||
name: Release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Run every day at 9am UTC
|
||||
- cron: "0 9 * * *"
|
||||
# schedule:
|
||||
# # Run every day at 9am UTC
|
||||
# - cron: "0 9 * * *"
|
||||
workflow_dispatch:
|
||||
# Allow manual triggering
|
||||
|
||||
|
|
@ -46,4 +46,4 @@ jobs:
|
|||
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npx semantic-release
|
||||
run: npx semantic-release
|
||||
|
|
|
|||
3
.vscode/launch.json
vendored
3
.vscode/launch.json
vendored
|
|
@ -21,7 +21,8 @@
|
|||
"resolveSourceMapLocations": [
|
||||
"${workspaceFolder}/**",
|
||||
"!**/node_modules/**"
|
||||
]
|
||||
],
|
||||
"preLaunchTask": "watch-logs"
|
||||
},
|
||||
|
||||
{
|
||||
|
|
|
|||
26
.vscode/tasks.json
vendored
26
.vscode/tasks.json
vendored
|
|
@ -27,6 +27,30 @@
|
|||
"showReuseMessage": true,
|
||||
"clear": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "watch-logs",
|
||||
"type": "shell",
|
||||
"command": "npm run watch:logs",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"pattern": {
|
||||
"regexp": "^$",
|
||||
"file": 1,
|
||||
"location": 2,
|
||||
"message": 3
|
||||
},
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": "^.*$",
|
||||
"endsPattern": "^.*$"
|
||||
}
|
||||
},
|
||||
"presentation": {
|
||||
"reveal": "always",
|
||||
"panel": "new",
|
||||
"focus": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
112
eslint.config.js
Normal file
112
eslint.config.js
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import tsParser from "@typescript-eslint/parser";
|
||||
import tsPlugin from "@typescript-eslint/eslint-plugin";
|
||||
import importPlugin from "eslint-plugin-import";
|
||||
import unusedImports from "eslint-plugin-unused-imports";
|
||||
|
||||
export default [
|
||||
{
|
||||
files: ["**/*.ts", "**/*.tsx"],
|
||||
plugins: {
|
||||
"@typescript-eslint": tsPlugin,
|
||||
import: importPlugin,
|
||||
"unused-imports": unusedImports,
|
||||
},
|
||||
languageOptions: {
|
||||
parser: tsParser,
|
||||
parserOptions: {
|
||||
project: "./tsconfig.json",
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
// Core rules - all as errors
|
||||
"max-classes-per-file": ["error", 1],
|
||||
"prefer-const": "error",
|
||||
|
||||
// TypeScript specific rules
|
||||
"@typescript-eslint/no-floating-promises": "off",
|
||||
|
||||
// Import rules
|
||||
"import/order": [
|
||||
"error",
|
||||
{
|
||||
groups: [
|
||||
"builtin",
|
||||
"external",
|
||||
"internal",
|
||||
"parent",
|
||||
"sibling",
|
||||
"index",
|
||||
],
|
||||
"newlines-between": "always",
|
||||
alphabetize: {
|
||||
order: "asc",
|
||||
caseInsensitive: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
"import/no-default-export": "error",
|
||||
|
||||
// Unused code detection
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"unused-imports/no-unused-imports": "error",
|
||||
"unused-imports/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
vars: "all",
|
||||
varsIgnorePattern: "^_",
|
||||
args: "after-used",
|
||||
argsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
|
||||
// Turn off rules that might be too strict
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/explicit-function-return-type": "off",
|
||||
"@typescript-eslint/explicit-module-boundary-types": "off",
|
||||
"@typescript-eslint/no-non-null-assertion": "off",
|
||||
|
||||
// Allow console for CLI tool
|
||||
"no-console": "off",
|
||||
},
|
||||
settings: {
|
||||
"import/resolver": {
|
||||
typescript: {
|
||||
project: "./tsconfig.json",
|
||||
},
|
||||
node: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
// Allow default exports in specific files
|
||||
files: ["src/index.ts", "*.config.js", "*.config.ts"],
|
||||
rules: {
|
||||
"import/no-default-export": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
// Test files can have different rules
|
||||
files: ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"],
|
||||
rules: {
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"unused-imports/no-unused-vars": "off",
|
||||
"max-classes-per-file": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
ignores: [
|
||||
"dist/**",
|
||||
"node_modules/**",
|
||||
"coverage/**",
|
||||
"*.d.ts",
|
||||
"src/__mocks__/**",
|
||||
"jest.setup.ts",
|
||||
"vitest.config.ts",
|
||||
"*.config.js",
|
||||
"*.config.ts",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
|
@ -15,6 +15,12 @@ jest.mock("./src/auth/workos.js");
|
|||
jest.mock("./src/commands/commands.js");
|
||||
jest.mock("./src/services/index.js");
|
||||
jest.mock("./src/services/ServiceContainerContext.js");
|
||||
jest.mock("./src/config.js");
|
||||
jest.mock("./src/configLoader.js");
|
||||
jest.mock("./src/args.js");
|
||||
jest.mock("./src/services/ServiceContainer.js");
|
||||
jest.mock("./src/permissions/permissionsYamlLoader.js");
|
||||
jest.mock("./src/permissions/precedenceResolver.js");
|
||||
|
||||
// Set up global afterEach hook to clear all timers and reset console
|
||||
afterEach(() => {
|
||||
|
|
|
|||
6828
package-lock.json
generated
6828
package-lock.json
generated
File diff suppressed because it is too large
Load diff
25
package.json
25
package.json
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "@continuedev/cli",
|
||||
"version": "0.0.0-dev",
|
||||
"description": "",
|
||||
"description": "Continue CLI",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"type": "module",
|
||||
|
|
@ -9,15 +9,18 @@
|
|||
"cn": "dist/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "npm run lint && cross-env NODE_OPTIONS=--experimental-vm-modules jest",
|
||||
"vitest": "vitest run",
|
||||
"vitest:watch": "vitest watch",
|
||||
"test": "npm run lint && vitest run",
|
||||
"test:watch": "vitest watch",
|
||||
"test:ui": "vitest --ui",
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx src/index.ts",
|
||||
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
|
||||
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
|
||||
"lint": "tsc --noEmit",
|
||||
"lint": "tsc --noEmit && eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"watch:logs": "tail -f ~/.continue/logs/cn.log",
|
||||
"prepare": "npm run build",
|
||||
"semantic-release": "semantic-release",
|
||||
"semantic-release:dry-run": "semantic-release --dry-run"
|
||||
|
|
@ -55,6 +58,7 @@
|
|||
"dotenv": "^16.5.0",
|
||||
"express": "^5.1.0",
|
||||
"glob": "^11.0.3",
|
||||
"gpt-tokenizer": "^3.0.1",
|
||||
"ignore-walk": "^7.0.0",
|
||||
"ink": "^6.0.1",
|
||||
"jszip": "^3.10.1",
|
||||
|
|
@ -81,21 +85,26 @@
|
|||
"@types/glob": "^8.1.0",
|
||||
"@types/ignore-walk": "^4.0.3",
|
||||
"@types/ink-testing-library": "^1.0.4",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/nock": "^10.0.3",
|
||||
"@types/readline-sync": "^1.4.8",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"@typescript-eslint/eslint-plugin": "^8.39.0",
|
||||
"@typescript-eslint/parser": "^8.39.0",
|
||||
"@vitest/ui": "^3.2.4",
|
||||
"conventional-changelog-conventionalcommits": "^9.1.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"eslint": "^9.32.0",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-unused-imports": "^4.1.4",
|
||||
"execa": "^9.6.0",
|
||||
"express": "^5.1.0",
|
||||
"happy-dom": "^18.0.1",
|
||||
"ink-testing-library": "^4.0.0",
|
||||
"jest": "^29.7.0",
|
||||
"nock": "^14.0.5",
|
||||
"semantic-release": "^24.2.7",
|
||||
"supertest": "^7.1.3",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsx": "^4.20.3",
|
||||
"vitest": "^3.2.4"
|
||||
|
|
|
|||
49
spec/index.md
Normal file
49
spec/index.md
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
# `cn`
|
||||
|
||||
## Overall development goals
|
||||
|
||||
Fight to keep `cn` simple. This is an active process. The default is that `cn` will become disastrously complicated.
|
||||
|
||||
### Maintainability
|
||||
|
||||
Maintain minimal code (avoid new features unless there is overwhelming demand or they remove a clear blocker for many users). If someone offers up a feature you should seek to understand what they actually want and then decide as a maintainer of `cn` whether this can fit into some larger concept in a simple way. If someone asks to make something configurable, you should probably consider just changing the default.
|
||||
|
||||
### Don't write code by hand
|
||||
|
||||
Use `cn` for everything. You should very rarely need to write code by hand. If you find yourself doing this outside of small tweaks, you should ask what about the codebase is causing `cn` to be unable to make the change.
|
||||
|
||||
If we build a system that allows us to entrust all changes to `cn` then it will be more reliable than us writing the code. Not because we can't write better code, but because `cn` is consistently thorough + it will force us to build the right systems around the code.
|
||||
|
||||
### Do not test by hand
|
||||
|
||||
If you find yourself using `npm run start` to test that existing functionality is still working, this means that you are missing a test. A green check mark from `npm test` should be full proof that the code can be shipped. See our testing strategies [here](./testing-strategies.md).
|
||||
|
||||
For new features you obviously need to run them yourself to apply your taste. `cn` can't match that right now.
|
||||
|
||||
### Minimize the number of concepts
|
||||
|
||||
The spec for `cn` (if it were to be fully written out) should be relatively short. This helps keep the code / spec consistent. It also allows us to keep the docs short and makes it easier for users to understand.
|
||||
|
||||
### Low tolerance
|
||||
|
||||
Tolerance for the following should be very close to zero:
|
||||
|
||||
- Un-addressed code reviews
|
||||
- Failing tests
|
||||
- Flaky tests
|
||||
- Sentry issues
|
||||
|
||||
If we are inundated then we should build a system to solve that. For example, if it is tiresome to address all AI code reviews, then set up a trigger to have `cn` automatically address them.
|
||||
|
||||
### Start with a spec
|
||||
|
||||
High level concepts / features should have a spec when possible. Good examples of this are [modes](./modes.md), [permissions](./permissions.md), [OTLP metrics](./otlp-metrics.md), and [wire format](./wire-format.md). Like code, the spec can and should be largely auto-generated.
|
||||
|
||||
## Codebase Design
|
||||
|
||||
- We intentionally write different implementations of the "loop" instead of trying to build a single engine that can be used across TUI, headless mode, `cn serve`, and more. So far, it would be more work than it is worth to add this abstraction.
|
||||
- "Everything is a service." Nobody (human or AI) should need to re-invent a polling mechanism or way to store / update state. This decision has been made already so we can focus on the business logic. The service setup lets us easily keep reactive state and avoid React anti-patterns like `useEffect`.
|
||||
- We use `ink` for UI, following the same usual React principles that we do elsewhere. Keep [components](../src/ui/components/) small, avoid `useEffect`, group logic into [hooks](../src/hooks).
|
||||
- Always use the [logger](../src/util/logger.ts) instead of `console.log`.
|
||||
- Use commander to define [commands](../src/commands/BaseCommandOptions.ts)
|
||||
- `cn remote` is intended to act the same as `cn`'s TUI in almost every way. There is a test helper that allows us to run any e2e test in _both_ remote and normal modes to ensure this is true.
|
||||
|
|
@ -1,3 +1,7 @@
|
|||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
FQSN,
|
||||
PlatformClient,
|
||||
|
|
@ -6,9 +10,6 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api";
|
||||
import * as dotenv from "dotenv";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
export class CLIPlatformClient implements PlatformClient {
|
||||
constructor(
|
||||
|
|
|
|||
57
src/MCPConnection.ts
Normal file
57
src/MCPConnection.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
export class MCPConnection {
|
||||
prompts: Awaited<ReturnType<Client["listPrompts"]>>["prompts"] = [];
|
||||
tools: Awaited<ReturnType<Client["listTools"]>>["tools"] = [];
|
||||
|
||||
private constructor(public readonly client: Client) {}
|
||||
|
||||
public static async create(
|
||||
config: NonNullable<AssistantConfig["mcpServers"]>[number]
|
||||
) {
|
||||
const client = new Client(
|
||||
{
|
||||
name: "continue-cli-client",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{ capabilities: {} }
|
||||
);
|
||||
|
||||
// Construct transport
|
||||
const env: Record<string, string> = config?.env || {};
|
||||
if (process.env.PATH !== undefined) {
|
||||
env.PATH = process.env.PATH;
|
||||
}
|
||||
|
||||
if (!config?.command) {
|
||||
throw new Error("MCP server command is not specified");
|
||||
}
|
||||
|
||||
const transport = new StdioClientTransport({
|
||||
command: config.command,
|
||||
args: config?.args,
|
||||
env,
|
||||
});
|
||||
|
||||
// Connect and get all prompts and tools
|
||||
const connection = new MCPConnection(client);
|
||||
logger.debug('Connecting to MCP server', { command: config.command });
|
||||
await client.connect(transport);
|
||||
const capabilities = client.getServerCapabilities();
|
||||
logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools });
|
||||
|
||||
if (capabilities?.prompts) {
|
||||
connection.prompts = (await client.listPrompts()).prompts;
|
||||
}
|
||||
|
||||
if (capabilities?.tools) {
|
||||
connection.tools = (await client.listTools()).tools;
|
||||
}
|
||||
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
3
src/__mocks__/args.ts
Normal file
3
src/__mocks__/args.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { vi } from 'vitest';
|
||||
|
||||
export const processRule = vi.fn<(rule: string) => Promise<string>>();
|
||||
|
|
@ -1,5 +1,28 @@
|
|||
import { jest } from '@jest/globals';
|
||||
import { vi } from 'vitest';
|
||||
import type { AuthConfig } from '../../auth/workos.js';
|
||||
|
||||
export const isAuthenticated = jest.fn(() => false);
|
||||
export const isAuthenticatedConfig = jest.fn(() => false);
|
||||
export const loadAuthConfig = jest.fn(() => Promise.resolve(null));
|
||||
export const isAuthenticated = vi.fn(() => false);
|
||||
export const isAuthenticatedConfig = vi.fn(() => false);
|
||||
export const isEnvironmentAuthConfig = vi.fn(() => false);
|
||||
export const loadAuthConfig = vi.fn(() => null);
|
||||
export const login = vi.fn();
|
||||
export const logout = vi.fn();
|
||||
export const ensureOrganization = vi.fn();
|
||||
export const getOrganizationId = vi.fn(() => null);
|
||||
export const saveAuthConfig = vi.fn();
|
||||
export const listUserOrganizations = vi.fn();
|
||||
export const hasMultipleOrganizations = vi.fn();
|
||||
export const initWorkOS = vi.fn();
|
||||
export const getModelName = vi.fn(() => null);
|
||||
export const getAccessToken = vi.fn(() => null);
|
||||
export const getConfigUri = vi.fn(() => null);
|
||||
export const getAssistantSlug = vi.fn(() => null);
|
||||
export const getLocalConfigPath = vi.fn(() => null);
|
||||
export const pathToUri = vi.fn((path: string) => path);
|
||||
export const slugToUri = vi.fn((slug: string) => slug);
|
||||
export const uriToPath = vi.fn(() => null);
|
||||
export const uriToSlug = vi.fn(() => null);
|
||||
export const updateConfigUri = vi.fn();
|
||||
export const updateModelName = vi.fn();
|
||||
export const updateAssistantSlug = vi.fn();
|
||||
export const updateLocalConfigPath = vi.fn();
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { jest } from '@jest/globals';
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const getAllSlashCommands = jest.fn(() => [
|
||||
export const getAllSlashCommands = vi.fn(() => [
|
||||
{ name: "help", description: "Show help", category: "system" },
|
||||
{ name: "login", description: "Login to Continue", category: "system" },
|
||||
]);
|
||||
]);
|
||||
|
|
|
|||
6
src/__mocks__/config.ts
Normal file
6
src/__mocks__/config.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import { vi } from 'vitest';
|
||||
|
||||
export const getApiClient = vi.fn<(accessToken: string | null) => any>(() => null);
|
||||
export const getLlmApi = vi.fn<(config: any, authConfig: any, modelConfig?: any, orgScopeId?: string) => [any, any]>();
|
||||
export const getModel = vi.fn<(config: any, modelName: string) => any>();
|
||||
export const createLlmApi = vi.fn<(modelConfig: any, authConfig: any, orgScopeId?: string) => any>();
|
||||
3
src/__mocks__/configLoader.ts
Normal file
3
src/__mocks__/configLoader.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { vi } from 'vitest';
|
||||
|
||||
export const loadConfiguration = vi.fn<(options: any) => Promise<any>>();
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const useService = jest.fn(() => ({
|
||||
export const useService = vi.fn(() => ({
|
||||
value: null,
|
||||
state: "idle",
|
||||
error: null,
|
||||
reload: jest.fn(() => Promise.resolve()),
|
||||
reload: vi.fn(() => Promise.resolve()),
|
||||
}));
|
||||
|
||||
export const useServices = jest.fn(() => ({
|
||||
export const useServices = vi.fn(() => ({
|
||||
services: {
|
||||
auth: { isAuthenticated: true },
|
||||
config: { config: { name: "test-assistant" } },
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
export const log = jest.fn();
|
||||
export const error = jest.fn();
|
||||
export const info = jest.fn();
|
||||
export const warn = jest.fn();
|
||||
import { vi } from 'vitest';
|
||||
|
||||
export const log = vi.fn();
|
||||
export const error = vi.fn();
|
||||
export const info = vi.fn();
|
||||
export const warn = vi.fn();
|
||||
export const loggers = {
|
||||
blue: jest.fn(),
|
||||
green: jest.fn(),
|
||||
yellow: jest.fn(),
|
||||
red: jest.fn(),
|
||||
magenta: jest.fn(),
|
||||
cyan: jest.fn(),
|
||||
white: jest.fn(),
|
||||
gray: jest.fn(),
|
||||
blue: vi.fn(),
|
||||
green: vi.fn(),
|
||||
yellow: vi.fn(),
|
||||
red: vi.fn(),
|
||||
magenta: vi.fn(),
|
||||
cyan: vi.fn(),
|
||||
white: vi.fn(),
|
||||
gray: vi.fn(),
|
||||
};
|
||||
3
src/__mocks__/permissions/permissionsYamlLoader.ts
Normal file
3
src/__mocks__/permissions/permissionsYamlLoader.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { vi } from 'vitest';
|
||||
|
||||
export const loadPermissionsFromYamlSync = vi.fn<() => any>(() => null);
|
||||
3
src/__mocks__/permissions/precedenceResolver.ts
Normal file
3
src/__mocks__/permissions/precedenceResolver.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { vi } from 'vitest';
|
||||
|
||||
export const resolvePermissionPrecedence = vi.fn<(options: any) => any[]>(() => []);
|
||||
9
src/__mocks__/services/ServiceContainer.ts
Normal file
9
src/__mocks__/services/ServiceContainer.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { vi } from 'vitest';
|
||||
|
||||
export const serviceContainer = {
|
||||
get: vi.fn<(name: string) => any>(),
|
||||
set: vi.fn<(name: string, state: any) => void>(),
|
||||
has: vi.fn<(name: string) => boolean>(),
|
||||
reset: vi.fn<() => void>(),
|
||||
reload: vi.fn<(name: string) => Promise<void>>(),
|
||||
};
|
||||
|
|
@ -1,25 +1,25 @@
|
|||
import React from 'react';
|
||||
import { jest } from "@jest/globals";
|
||||
import { vi } from "vitest";
|
||||
import { ServiceContainer } from '../../services/ServiceContainer.js';
|
||||
|
||||
// Create a mock service container
|
||||
const mockServiceContainer = {
|
||||
getSync: jest.fn((serviceName: string) => ({
|
||||
getSync: vi.fn((serviceName: string) => ({
|
||||
state: "ready",
|
||||
value: {},
|
||||
error: null,
|
||||
})),
|
||||
isReady: jest.fn(() => true),
|
||||
on: jest.fn(),
|
||||
off: jest.fn(),
|
||||
load: jest.fn(() => Promise.resolve()),
|
||||
reload: jest.fn(() => Promise.resolve()),
|
||||
emit: jest.fn(),
|
||||
setMaxListeners: jest.fn(),
|
||||
isReady: vi.fn(() => true),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
load: vi.fn(() => Promise.resolve()),
|
||||
reload: vi.fn(() => Promise.resolve()),
|
||||
emit: vi.fn(),
|
||||
setMaxListeners: vi.fn(),
|
||||
} as unknown as ServiceContainer;
|
||||
|
||||
export const ServiceContainerProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
return React.createElement(React.Fragment, null, children);
|
||||
};
|
||||
|
||||
export const useServiceContainer = jest.fn(() => mockServiceContainer);
|
||||
export const useServiceContainer = vi.fn(() => mockServiceContainer);
|
||||
|
|
@ -1,15 +1,15 @@
|
|||
import { jest } from '@jest/globals';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
export const services = {
|
||||
auth: {
|
||||
login: jest.fn(() => Promise.resolve({})),
|
||||
logout: jest.fn(() => Promise.resolve({})),
|
||||
switchOrganization: jest.fn(() => Promise.resolve({})),
|
||||
getAvailableOrganizations: jest.fn(() => Promise.resolve([])),
|
||||
login: vi.fn(() => Promise.resolve({})),
|
||||
logout: vi.fn(() => Promise.resolve({})),
|
||||
switchOrganization: vi.fn(() => Promise.resolve({})),
|
||||
getAvailableOrganizations: vi.fn(() => Promise.resolve([])),
|
||||
},
|
||||
};
|
||||
|
||||
export const reloadService = jest.fn(() => Promise.resolve(undefined));
|
||||
export const reloadService = vi.fn(() => Promise.resolve(undefined));
|
||||
|
||||
export const SERVICE_NAMES = {
|
||||
AUTH: 'auth',
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import { vi } from 'vitest';
|
||||
|
||||
const mockLogger: any = {
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
child: jest.fn((): any => mockLogger),
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
child: vi.fn((): any => mockLogger),
|
||||
};
|
||||
|
||||
export default mockLogger;
|
||||
export const getLogPath = jest.fn(() => "/mock/log/path");
|
||||
export const getSessionId = jest.fn(() => "mock-session-id");
|
||||
export const getLogPath = vi.fn(() => "/mock/log/path");
|
||||
export const getSessionId = vi.fn(() => "mock-session-id");
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { jest } from '@jest/globals';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
import { parseArgs, processRule } from "./args.js";
|
||||
|
||||
describe("parseArgs", () => {
|
||||
|
|
@ -16,22 +17,9 @@ describe("parseArgs", () => {
|
|||
|
||||
it("should return default values when no arguments provided", () => {
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: false,
|
||||
});
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it("should set isHeadless to true when --print flag is present", () => {
|
||||
process.argv = ["node", "script.js", "--print"];
|
||||
const result = parseArgs();
|
||||
expect(result.isHeadless).toBe(true);
|
||||
});
|
||||
|
||||
it("should set isHeadless to true when -p flag is present", () => {
|
||||
process.argv = ["node", "script.js", "-p"];
|
||||
const result = parseArgs();
|
||||
expect(result.isHeadless).toBe(true);
|
||||
});
|
||||
|
||||
it("should set resume to true when --resume flag is present", () => {
|
||||
process.argv = ["node", "script.js", "--resume"];
|
||||
|
|
@ -74,7 +62,6 @@ describe("parseArgs", () => {
|
|||
process.argv = ["node", "script.js", "--print", "--readonly", "--resume"];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: true,
|
||||
readonly: true,
|
||||
resume: true,
|
||||
});
|
||||
|
|
@ -84,7 +71,6 @@ describe("parseArgs", () => {
|
|||
process.argv = ["node", "script.js", "--config", "config.yaml", "--print"];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: true,
|
||||
configPath: "config.yaml",
|
||||
});
|
||||
});
|
||||
|
|
@ -93,7 +79,6 @@ describe("parseArgs", () => {
|
|||
process.argv = ["node", "script.js", "--rule", "my-rule", "--print"];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: true,
|
||||
rules: ["my-rule"],
|
||||
});
|
||||
});
|
||||
|
|
@ -102,7 +87,6 @@ describe("parseArgs", () => {
|
|||
process.argv = ["node", "script.js", "--print", "What is the weather?"];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: true,
|
||||
prompt: "What is the weather?",
|
||||
});
|
||||
});
|
||||
|
|
@ -117,7 +101,6 @@ describe("parseArgs", () => {
|
|||
];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: false,
|
||||
configPath: "config.yaml",
|
||||
prompt: "Test prompt",
|
||||
});
|
||||
|
|
@ -127,7 +110,6 @@ describe("parseArgs", () => {
|
|||
process.argv = ["node", "script.js", "--rule", "my-rule", "Test prompt"];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: false,
|
||||
rules: ["my-rule"],
|
||||
prompt: "Test prompt",
|
||||
});
|
||||
|
|
@ -172,7 +154,6 @@ describe("parseArgs", () => {
|
|||
];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: true,
|
||||
configPath: "my-config.yaml",
|
||||
rules: ["rule1", "rule2"],
|
||||
readonly: true,
|
||||
|
|
@ -196,14 +177,12 @@ describe("parseArgs", () => {
|
|||
it("should handle config flag at the end without value", () => {
|
||||
process.argv = ["node", "script.js", "--print", "--config"];
|
||||
const result = parseArgs();
|
||||
expect(result.isHeadless).toBe(true);
|
||||
expect(result.configPath).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle rule flag at the end without value", () => {
|
||||
process.argv = ["node", "script.js", "--print", "--rule"];
|
||||
const result = parseArgs();
|
||||
expect(result.isHeadless).toBe(true);
|
||||
expect(result.rules).toEqual([]);
|
||||
});
|
||||
|
||||
|
|
@ -211,7 +190,6 @@ describe("parseArgs", () => {
|
|||
process.argv = ["node", "script.js"];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
isHeadless: false,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -245,7 +223,7 @@ describe("parseArgs", () => {
|
|||
describe("processRule (loadRuleFromHub integration)", () => {
|
||||
// Mock fetch for hub tests
|
||||
const originalFetch = global.fetch;
|
||||
const mockFetch = jest.fn() as jest.MockedFunction<typeof fetch>;
|
||||
const mockFetch = vi.fn() as any;
|
||||
|
||||
beforeAll(() => {
|
||||
global.fetch = mockFetch;
|
||||
|
|
|
|||
17
src/args.ts
17
src/args.ts
|
|
@ -1,10 +1,11 @@
|
|||
import * as fs from "fs";
|
||||
import JSZip from "jszip";
|
||||
import * as path from "path";
|
||||
|
||||
import JSZip from "jszip";
|
||||
|
||||
import { env } from "./env.js";
|
||||
|
||||
export interface CommandLineArgs {
|
||||
isHeadless: boolean;
|
||||
configPath?: string;
|
||||
prompt?: string; // Optional prompt argument
|
||||
resume?: boolean; // Resume from last session
|
||||
|
|
@ -108,21 +109,15 @@ export async function processRule(ruleSpec: string): Promise<string> {
|
|||
}
|
||||
|
||||
/**
|
||||
* Parse command line arguments
|
||||
* Parse command line arguments for non-permission related flags
|
||||
* @deprecated Most functionality has been moved to services. This is only kept for backward compatibility.
|
||||
* @returns Parsed command line arguments
|
||||
*/
|
||||
export function parseArgs(): CommandLineArgs {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
// Default values
|
||||
const result: CommandLineArgs = {
|
||||
isHeadless: false,
|
||||
};
|
||||
|
||||
// Parse flags
|
||||
if (args.includes("--print") || args.includes("-p")) {
|
||||
result.isHeadless = true;
|
||||
}
|
||||
const result: CommandLineArgs = {};
|
||||
|
||||
if (args.includes("--resume")) {
|
||||
result.resume = true;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import chalk from "chalk";
|
||||
|
||||
import { getVersion } from "./version.js";
|
||||
|
||||
const b = chalk.bold.magenta;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import chalk from "chalk";
|
||||
|
||||
import { isAuthenticated, login } from "./workos.js";
|
||||
|
||||
/**
|
||||
|
|
@ -22,7 +23,7 @@ export async function ensureAuthenticated(
|
|||
await login();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(chalk.red("Failed to authenticate."));
|
||||
console.error(chalk.red("Failed to authenticate."), error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
import chalk from "chalk";
|
||||
import * as fs from "fs";
|
||||
import open from "open";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import { createInterface } from "readline";
|
||||
import { env } from "../env.js";
|
||||
|
||||
import chalk from "chalk";
|
||||
// Polyfill fetch for Node < 18
|
||||
import nodeFetch from "node-fetch";
|
||||
import open from "open";
|
||||
|
||||
import { getApiClient } from "../config.js";
|
||||
import { env } from "../env.js";
|
||||
if (!globalThis.fetch) {
|
||||
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
|
||||
}
|
||||
|
|
@ -271,23 +271,6 @@ export function isAuthenticated(): boolean {
|
|||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt the user for input
|
||||
*/
|
||||
function prompt(question: string): Promise<string> {
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
|
||||
return new Promise((resolve) => {
|
||||
rl.question(question, (answer) => {
|
||||
rl.close();
|
||||
resolve(answer);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Device authorization response from WorkOS
|
||||
*/
|
||||
|
|
@ -524,7 +507,7 @@ export async function login(): Promise<AuthConfig> {
|
|||
// Try to open the complete verification URL in browser
|
||||
try {
|
||||
await open(deviceAuth.verification_uri_complete);
|
||||
} catch (error) {
|
||||
} catch {
|
||||
console.info(chalk.yellow("Unable to open browser automatically"));
|
||||
}
|
||||
|
||||
|
|
@ -665,7 +648,7 @@ export async function listUserOrganizations(): Promise<
|
|||
try {
|
||||
const resp = await apiClient.listOrganizations();
|
||||
return resp.organizations || [];
|
||||
} catch (error) {
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,15 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import chalk from "chalk";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import * as readlineSync from "readline-sync";
|
||||
|
||||
import { CONTINUE_ASCII_ART } from "../asciiArt.js";
|
||||
import { loadAuthConfig } from "../auth/workos.js";
|
||||
import {
|
||||
compactChatHistory,
|
||||
findCompactionIndex,
|
||||
getHistoryForLLM,
|
||||
} from "../compaction.js";
|
||||
import { configureLogger } from "../logger.js";
|
||||
import * as logging from "../logging.js";
|
||||
import { initializeWithOnboarding } from "../onboarding.js";
|
||||
|
|
@ -13,11 +20,17 @@ import { loadSession, saveSession } from "../session.js";
|
|||
import { streamChatResponse } from "../streamChatResponse.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import { posthogService } from "../telemetry/posthogService.js";
|
||||
import telemetryService from "../telemetry/telemetryService.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { startTUIChat } from "../ui/index.js";
|
||||
import { safeStdout } from "../util/consoleOverride.js";
|
||||
import { formatError } from "../util/formatError.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
import {
|
||||
calculateContextUsagePercentage,
|
||||
countChatHistoryTokens,
|
||||
shouldAutoCompact,
|
||||
} from "../util/tokenizer.js";
|
||||
|
||||
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
|
||||
|
||||
/**
|
||||
|
|
@ -33,7 +46,7 @@ function processJsonOutput(response: string): string {
|
|||
JSON.parse(trimmedResponse);
|
||||
// If it parses successfully, return as-is
|
||||
return trimmedResponse;
|
||||
} catch (error) {
|
||||
} catch {
|
||||
// If it's not valid JSON, wrap it in a JSON object
|
||||
return JSON.stringify({
|
||||
response: trimmedResponse,
|
||||
|
|
@ -43,11 +56,30 @@ function processJsonOutput(response: string): string {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips <think></think> tags and excess whitespace from response
|
||||
* @param response - The raw response from the LLM
|
||||
* @returns Cleaned response
|
||||
*/
|
||||
function stripThinkTags(response: string): string {
|
||||
// Remove <think></think> tags and their content
|
||||
let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, "");
|
||||
|
||||
// Remove excess whitespace: multiple consecutive newlines become single newlines
|
||||
cleaned = cleaned.replace(/\n\s*\n\s*\n/g, "\n\n");
|
||||
|
||||
// Trim leading and trailing whitespace
|
||||
cleaned = cleaned.trim();
|
||||
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
export interface ChatOptions extends ExtendedCommandOptions {
|
||||
headless?: boolean;
|
||||
resume?: boolean;
|
||||
rule?: string[]; // Array of rule specifications
|
||||
format?: "json"; // Output format for headless mode
|
||||
silent?: boolean; // Strip <think></think> tags and excess whitespace
|
||||
}
|
||||
|
||||
export async function initializeChatHistory(
|
||||
|
|
@ -86,15 +118,130 @@ export async function initializeChatHistory(
|
|||
async function processMessage(
|
||||
userInput: string,
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
model: any,
|
||||
model: ModelConfig,
|
||||
llmApi: any,
|
||||
isHeadless: boolean,
|
||||
format?: "json"
|
||||
): Promise<void> {
|
||||
format?: "json",
|
||||
silent?: boolean,
|
||||
compactionIndex?: number | null
|
||||
): Promise<{ compactionIndex?: number | null } | void> {
|
||||
// Check for slash commands in headless mode
|
||||
if (userInput.trim() === "/compact") {
|
||||
if (!isHeadless) {
|
||||
console.info(chalk.yellow("Compacting chat history..."));
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await compactChatHistory(chatHistory, model, llmApi);
|
||||
|
||||
// Replace chat history with compacted version
|
||||
chatHistory.length = 0;
|
||||
chatHistory.push(...result.compactedHistory);
|
||||
|
||||
// Save the compacted session
|
||||
saveSession(chatHistory);
|
||||
|
||||
if (!isHeadless) {
|
||||
console.info(chalk.green("Chat history compacted successfully."));
|
||||
} else {
|
||||
safeStdout(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
message: "Chat history compacted",
|
||||
historyLength: chatHistory.length,
|
||||
}) + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
return { compactionIndex: result.compactionIndex };
|
||||
} catch (error) {
|
||||
const errorMsg = `Compaction error: ${formatError(error)}`;
|
||||
if (!isHeadless) {
|
||||
console.error(chalk.red(errorMsg));
|
||||
} else {
|
||||
safeStdout(
|
||||
JSON.stringify({ status: "error", message: errorMsg }) + "\n"
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Track user prompt
|
||||
telemetryService.logUserPrompt(userInput.length, userInput);
|
||||
|
||||
// Add user message to history
|
||||
// Check if auto-compacting is needed BEFORE adding user message
|
||||
if (shouldAutoCompact(chatHistory, model)) {
|
||||
logger.info("Auto-compacting triggered due to context limit");
|
||||
|
||||
if (!isHeadless) {
|
||||
console.info(
|
||||
chalk.yellow(
|
||||
"\nApproaching context limit. Auto-compacting chat history..."
|
||||
)
|
||||
);
|
||||
} else if (format === "json") {
|
||||
safeStdout(
|
||||
JSON.stringify({
|
||||
status: "info",
|
||||
message: "Auto-compacting triggered",
|
||||
contextUsage:
|
||||
calculateContextUsagePercentage(
|
||||
countChatHistoryTokens(chatHistory),
|
||||
model
|
||||
) + "%",
|
||||
}) + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// Compact the history WITHOUT the current user message
|
||||
const result = await compactChatHistory(chatHistory, model, llmApi);
|
||||
|
||||
// Replace chat history with compacted version
|
||||
chatHistory.length = 0;
|
||||
chatHistory.push(...result.compactedHistory);
|
||||
|
||||
// Save the compacted session
|
||||
saveSession(chatHistory);
|
||||
|
||||
if (!isHeadless) {
|
||||
console.info(
|
||||
chalk.green("✓ Chat history auto-compacted successfully.")
|
||||
);
|
||||
} else if (format === "json") {
|
||||
safeStdout(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
message: "Auto-compacted successfully",
|
||||
historyLength: chatHistory.length,
|
||||
}) + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
// Update compaction index
|
||||
compactionIndex = result.compactionIndex;
|
||||
} catch (error) {
|
||||
const errorMsg = `Auto-compaction error: ${formatError(error)}`;
|
||||
logger.error(errorMsg);
|
||||
|
||||
if (!isHeadless) {
|
||||
console.error(chalk.red(`Warning: ${errorMsg}`));
|
||||
console.info(chalk.yellow("Continuing without compaction..."));
|
||||
} else if (format === "json") {
|
||||
safeStdout(
|
||||
JSON.stringify({
|
||||
status: "warning",
|
||||
message: "Auto-compaction failed, continuing without compaction",
|
||||
}) + "\n"
|
||||
);
|
||||
}
|
||||
|
||||
// Continue without compaction on error
|
||||
}
|
||||
}
|
||||
|
||||
// Add user message to history AFTER potential compaction
|
||||
chatHistory.push({ role: "user", content: userInput });
|
||||
|
||||
// Get AI response with potential tool usage
|
||||
|
|
@ -104,18 +251,48 @@ async function processMessage(
|
|||
|
||||
try {
|
||||
const abortController = new AbortController();
|
||||
const finalResponse = await streamChatResponse(
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
abortController
|
||||
);
|
||||
|
||||
// Handle compaction properly - streamChatResponse modifies the array in place
|
||||
let finalResponse;
|
||||
if (compactionIndex !== null && compactionIndex !== undefined) {
|
||||
// When using compaction, we need to send a subset but capture the full history
|
||||
const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex);
|
||||
const originalLength = historyForLLM.length;
|
||||
|
||||
finalResponse = await streamChatResponse(
|
||||
historyForLLM,
|
||||
model,
|
||||
llmApi,
|
||||
abortController
|
||||
);
|
||||
|
||||
// Append any new messages (assistant/tool) that were added by streamChatResponse
|
||||
const newMessages = historyForLLM.slice(originalLength);
|
||||
chatHistory.push(...newMessages);
|
||||
} else {
|
||||
// No compaction - just pass the full history directly
|
||||
finalResponse = await streamChatResponse(
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
abortController
|
||||
);
|
||||
}
|
||||
|
||||
// In headless mode, only print the final response using safe stdout
|
||||
if (isHeadless && finalResponse && finalResponse.trim()) {
|
||||
let processedResponse = finalResponse;
|
||||
|
||||
// Strip think tags if --silent flag is enabled
|
||||
if (silent) {
|
||||
processedResponse = stripThinkTags(processedResponse);
|
||||
}
|
||||
|
||||
// Process output based on format
|
||||
const outputResponse =
|
||||
format === "json" ? processJsonOutput(finalResponse) : finalResponse;
|
||||
format === "json"
|
||||
? processJsonOutput(processedResponse)
|
||||
: processedResponse;
|
||||
|
||||
safeStdout(outputResponse + "\n");
|
||||
}
|
||||
|
|
@ -163,9 +340,19 @@ async function runHeadlessMode(
|
|||
);
|
||||
const { llmApi, model } = modelState;
|
||||
|
||||
if (!model) {
|
||||
throw new Error("No models were found.");
|
||||
}
|
||||
|
||||
// Initialize chat history
|
||||
const chatHistory = await initializeChatHistory(options);
|
||||
|
||||
// Track compaction index if resuming with compacted history
|
||||
let compactionIndex: number | null = null;
|
||||
if (options.resume) {
|
||||
compactionIndex = findCompactionIndex(chatHistory);
|
||||
}
|
||||
|
||||
let isFirstMessage = true;
|
||||
while (true) {
|
||||
// When in headless mode, don't ask for user input
|
||||
|
|
@ -181,14 +368,21 @@ async function runHeadlessMode(
|
|||
|
||||
isFirstMessage = false;
|
||||
|
||||
await processMessage(
|
||||
const result = await processMessage(
|
||||
userInput,
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
true,
|
||||
options.format
|
||||
options.format,
|
||||
options.silent,
|
||||
compactionIndex
|
||||
);
|
||||
|
||||
// Update compaction index if compaction occurred
|
||||
if (result && result.compactionIndex !== undefined) {
|
||||
compactionIndex = result.compactionIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { beforeEach, describe, expect, it } from '@jest/globals';
|
||||
import type { AssistantConfig } from '@continuedev/sdk';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { getAllSlashCommands } from './commands.js';
|
||||
|
||||
describe('Slash Commands Integration', () => {
|
||||
|
|
|
|||
|
|
@ -22,11 +22,6 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
|
|||
description: "Clear the chat history",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "exit",
|
||||
description: "Exit the chat",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "login",
|
||||
description: "Authenticate with your account",
|
||||
|
|
@ -42,11 +37,6 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
|
|||
description: "Check who you're currently logged in as",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "org",
|
||||
description: "Switch organization",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "model",
|
||||
description: "Switch between available chat models",
|
||||
|
|
@ -57,6 +47,21 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
|
|||
description: "Switch configuration",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "org",
|
||||
description: "Switch organization",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "compact",
|
||||
description: "Summarize chat history into a compact form",
|
||||
category: "system",
|
||||
},
|
||||
{
|
||||
name: "exit",
|
||||
description: "Exit the chat",
|
||||
category: "system",
|
||||
},
|
||||
];
|
||||
|
||||
// Remote mode specific commands
|
||||
|
|
@ -109,4 +114,4 @@ export function getAssistantSlashCommands(
|
|||
category: "assistant" as const,
|
||||
})) || []
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import chalk from "chalk";
|
||||
|
||||
import { login as workosLogin } from "../auth/workos.js";
|
||||
|
||||
export async function login() {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import chalk from "chalk";
|
||||
import telemetryService from "../telemetry/telemetryService.js";
|
||||
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { startRemoteTUIChat } from "../ui/index.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
export async function remoteTest(
|
||||
prompt?: string,
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
import chalk from "chalk";
|
||||
|
||||
import {
|
||||
getAccessToken,
|
||||
isAuthenticatedConfig,
|
||||
loadAuthConfig,
|
||||
} from "../auth/workos.js";
|
||||
import { env } from "../env.js";
|
||||
import telemetryService from "../telemetry/telemetryService.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { startRemoteTUIChat } from "../ui/index.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
export async function remote(
|
||||
prompt: string | undefined,
|
||||
|
|
|
|||
|
|
@ -1,18 +1,19 @@
|
|||
import type { Server } from "http";
|
||||
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
jest,
|
||||
} from "@jest/globals";
|
||||
import type { Server } from "http";
|
||||
vi,
|
||||
} from "vitest";
|
||||
|
||||
import { createMinimalTestContext } from "../test-helpers/ui-test-context.js";
|
||||
|
||||
describe("serve command", () => {
|
||||
let context: any;
|
||||
let originalProcessExit: typeof process.exit;
|
||||
let serverPromise: Promise<void>;
|
||||
let serverRef: Server | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -20,66 +21,66 @@ describe("serve command", () => {
|
|||
|
||||
// Mock process.exit to prevent actual exit during tests
|
||||
originalProcessExit = process.exit;
|
||||
process.exit = jest.fn() as any;
|
||||
process.exit = vi.fn() as any;
|
||||
|
||||
// Mock console.log to prevent output during tests
|
||||
jest.spyOn(console, "log").mockImplementation(() => {});
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
// Mock all required modules at test level with correct relative paths
|
||||
jest.mock("fs", () => ({
|
||||
...(jest.requireActual("fs") as any),
|
||||
existsSync: jest.fn(() => false),
|
||||
vi.mock("fs", () => ({
|
||||
...(vi.importActual("fs") as any),
|
||||
existsSync: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
jest.mock("../auth/workos.js", () => ({
|
||||
loadAuthConfig: jest.fn(() => null),
|
||||
ensureOrganization: jest.fn(),
|
||||
getOrganizationId: jest.fn(),
|
||||
isAuthenticated: jest.fn(() => false),
|
||||
vi.mock("../auth/workos.js", () => ({
|
||||
loadAuthConfig: vi.fn(() => null),
|
||||
ensureOrganization: vi.fn(),
|
||||
getOrganizationId: vi.fn(),
|
||||
isAuthenticated: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
jest.mock("../onboarding.js", () => ({
|
||||
runNormalFlow: jest.fn(() =>
|
||||
vi.mock("../onboarding.js", () => ({
|
||||
runNormalFlow: vi.fn(() =>
|
||||
Promise.resolve({
|
||||
config: { models: [] },
|
||||
llmApi: { chat: jest.fn() },
|
||||
llmApi: { chat: vi.fn() },
|
||||
model: { name: "test-model" },
|
||||
})
|
||||
),
|
||||
runOnboardingFlow: jest.fn(() =>
|
||||
runOnboardingFlow: vi.fn(() =>
|
||||
Promise.resolve({
|
||||
config: { models: [] },
|
||||
llmApi: { chat: jest.fn() },
|
||||
llmApi: { chat: vi.fn() },
|
||||
model: { name: "test-model" },
|
||||
})
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock("../session.js", () => ({
|
||||
saveSession: jest.fn(),
|
||||
vi.mock("../session.js", () => ({
|
||||
saveSession: vi.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("../systemMessage.js", () => ({
|
||||
constructSystemMessage: jest.fn(() => Promise.resolve("System message")),
|
||||
vi.mock("../systemMessage.js", () => ({
|
||||
constructSystemMessage: vi.fn(() => Promise.resolve("System message")),
|
||||
}));
|
||||
|
||||
jest.mock("../telemetry/telemetryService.js", () => ({
|
||||
vi.mock("../telemetry/telemetryService.js", () => ({
|
||||
default: {
|
||||
recordSessionStart: jest.fn(),
|
||||
startActiveTime: jest.fn(),
|
||||
stopActiveTime: jest.fn(),
|
||||
updateOrganization: jest.fn(),
|
||||
recordSessionStart: vi.fn(),
|
||||
startActiveTime: vi.fn(),
|
||||
stopActiveTime: vi.fn(),
|
||||
updateOrganization: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock("../util/logger.js", () => ({
|
||||
vi.mock("../util/logger.js", () => ({
|
||||
default: {
|
||||
error: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock("chalk", () => ({
|
||||
vi.mock("chalk", () => ({
|
||||
default: {
|
||||
green: (str: string) => str,
|
||||
dim: (str: string) => str,
|
||||
|
|
@ -96,7 +97,7 @@ describe("serve command", () => {
|
|||
process.exit = originalProcessExit;
|
||||
|
||||
// Restore console.log
|
||||
jest.restoreAllMocks();
|
||||
vi.restoreAllMocks();
|
||||
|
||||
// Clean up server if it's still running
|
||||
if (serverRef) {
|
||||
|
|
@ -106,7 +107,7 @@ describe("serve command", () => {
|
|||
serverRef = null;
|
||||
}
|
||||
|
||||
jest.clearAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it.skip("should have /exit endpoint that returns success response", async () => {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import chalk from "chalk";
|
||||
import { exec } from "child_process";
|
||||
import express, { Request, Response } from "express";
|
||||
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import path from "path";
|
||||
import { promisify } from "util";
|
||||
|
||||
import chalk from "chalk";
|
||||
import express, { Request, Response } from "express";
|
||||
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
|
||||
|
||||
import { getAssistantSlug } from "../auth/workos.js";
|
||||
import { toolPermissionManager } from "../permissions/permissionManager.js";
|
||||
import { saveSession } from "../session.js";
|
||||
import {
|
||||
getService,
|
||||
initializeServices,
|
||||
|
|
@ -17,17 +19,19 @@ import {
|
|||
ConfigServiceState,
|
||||
ModelServiceState,
|
||||
} from "../services/types.js";
|
||||
import { saveSession } from "../session.js";
|
||||
import {
|
||||
streamChatResponse,
|
||||
type StreamCallbacks,
|
||||
} from "../streamChatResponse.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import telemetryService from "../telemetry/telemetryService.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { getToolDisplayName } from "../tools/index.js";
|
||||
import { DisplayMessage } from "../ui/types.js";
|
||||
import { formatError } from "../util/formatError.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
|
||||
import { getToolDisplayName } from "../tools/index.js";
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
|
|
@ -125,7 +129,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
}
|
||||
|
||||
// Initialize chat history
|
||||
let chatHistory: ChatCompletionMessageParam[] = [];
|
||||
const chatHistory: ChatCompletionMessageParam[] = [];
|
||||
const systemMessage = await constructSystemMessage("", options.rule, undefined, true);
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
|
|
|
|||
160
src/commands/stripThinkTags.test.ts
Normal file
160
src/commands/stripThinkTags.test.ts
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
// Unit tests for the stripThinkTags function
|
||||
|
||||
// Since stripThinkTags is currently a private function in chat.ts,
|
||||
// we'll extract it for testing purposes. This follows the same pattern
|
||||
// as other utility functions in the codebase.
|
||||
|
||||
/**
|
||||
* Strips <think></think> tags and excess whitespace from response
|
||||
* @param response - The raw response from the LLM
|
||||
* @returns Cleaned response
|
||||
*/
|
||||
function stripThinkTags(response: string): string {
|
||||
// Remove <think></think> tags and their content
|
||||
let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, '');
|
||||
|
||||
// Remove excess whitespace: multiple consecutive newlines become single newlines
|
||||
cleaned = cleaned.replace(/\n\s*\n\s*\n/g, '\n\n');
|
||||
|
||||
// Trim leading and trailing whitespace
|
||||
cleaned = cleaned.trim();
|
||||
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
describe("stripThinkTags", () => {
|
||||
it("should remove simple think tags", () => {
|
||||
const input = `<think>
|
||||
This is a thought
|
||||
</think>
|
||||
|
||||
This is the actual content`;
|
||||
|
||||
const expected = "This is the actual content";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should remove multiple think tag blocks", () => {
|
||||
const input = `<think>First thought</think>
|
||||
|
||||
Content 1
|
||||
|
||||
<think>Second thought</think>
|
||||
|
||||
Content 2`;
|
||||
|
||||
const expected = "Content 1\n\nContent 2";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle think tags with nested content", () => {
|
||||
const input = `<think>
|
||||
I need to think about:
|
||||
1. Step one
|
||||
2. Step two
|
||||
- Sub step
|
||||
</think>
|
||||
|
||||
Final result`;
|
||||
|
||||
const expected = "Final result";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should reduce excess whitespace", () => {
|
||||
const input = `<think>Remove this</think>
|
||||
|
||||
|
||||
|
||||
Content with lots of space
|
||||
|
||||
|
||||
|
||||
More content`;
|
||||
|
||||
const expected = "Content with lots of space\n\nMore content";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle content without think tags", () => {
|
||||
const input = `#!/bin/bash
|
||||
echo "Hello World"
|
||||
|
||||
This has no think tags.`;
|
||||
|
||||
// Should return the same content (trimmed)
|
||||
expect(stripThinkTags(input)).toBe(input.trim());
|
||||
});
|
||||
|
||||
it("should handle empty think tags", () => {
|
||||
const input = `<think></think>
|
||||
|
||||
Content after empty think tag`;
|
||||
|
||||
const expected = "Content after empty think tag";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle think tags at the end", () => {
|
||||
const input = `Content at the beginning
|
||||
|
||||
<think>
|
||||
This thought is at the end
|
||||
</think>`;
|
||||
|
||||
const expected = "Content at the beginning";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle complex whitespace patterns", () => {
|
||||
const input = `<think>Remove</think>
|
||||
|
||||
|
||||
Content with indented whitespace
|
||||
|
||||
|
||||
More content`;
|
||||
|
||||
const result = stripThinkTags(input);
|
||||
// Should reduce triple+ newlines to double newlines
|
||||
expect(result).not.toMatch(/\n\s*\n\s*\n/);
|
||||
expect(result).toContain("Content with indented whitespace");
|
||||
expect(result).toContain("More content");
|
||||
});
|
||||
|
||||
it("should handle think tags with special characters", () => {
|
||||
const input = `<think>
|
||||
Special chars: !@#$%^&*()
|
||||
Code: const x = () => { return "test"; }
|
||||
</think>
|
||||
|
||||
Actual content`;
|
||||
|
||||
const expected = "Actual content";
|
||||
expect(stripThinkTags(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should be case sensitive for think tags", () => {
|
||||
const input = `<THINK>This should not be removed</THINK>
|
||||
<Think>This should not be removed</Think>
|
||||
<think>This should be removed</think>
|
||||
|
||||
Content`;
|
||||
|
||||
const result = stripThinkTags(input);
|
||||
expect(result).toContain("<THINK>This should not be removed</THINK>");
|
||||
expect(result).toContain("<Think>This should not be removed</Think>");
|
||||
expect(result).not.toContain("<think>This should be removed</think>");
|
||||
expect(result).toContain("Content");
|
||||
});
|
||||
|
||||
it("should handle malformed think tags gracefully", () => {
|
||||
const input = `<think>Unclosed think tag
|
||||
|
||||
Content should remain`;
|
||||
|
||||
// Should not remove unclosed tags
|
||||
expect(stripThinkTags(input)).toContain("<think>Unclosed think tag");
|
||||
expect(stripThinkTags(input)).toContain("Content should remain");
|
||||
});
|
||||
});
|
||||
616
src/compaction.test.ts
Normal file
616
src/compaction.test.ts
Normal file
|
|
@ -0,0 +1,616 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import { compactChatHistory, findCompactionIndex, getHistoryForLLM, COMPACTION_MARKER } from "./compaction.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
|
||||
|
||||
// Mock the streamChatResponse function
|
||||
vi.mock("./streamChatResponse.js", () => ({
|
||||
streamChatResponse: vi.fn()
|
||||
}));
|
||||
|
||||
describe("compaction", () => {
|
||||
const mockModel: ModelConfig = {
|
||||
name: "test-model",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
} as ModelConfig;
|
||||
|
||||
const mockLlmApi = {} as BaseLlmApi;
|
||||
|
||||
describe("findCompactionIndex", () => {
|
||||
it("should find compaction marker in chat history", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(3);
|
||||
});
|
||||
|
||||
it("should return null if no compaction marker found", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
||||
it("should return first compaction marker when multiple exist", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nFirst summary` },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSecond summary` },
|
||||
];
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(1);
|
||||
});
|
||||
|
||||
it("should return null for empty chat history", () => {
|
||||
const history: ChatCompletionMessageParam[] = [];
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
||||
it("should not match marker in middle of content", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: `Some text ${COMPACTION_MARKER} in the middle` },
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle non-string content", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: null as any },
|
||||
{ role: "assistant", content: undefined as any },
|
||||
{ role: "assistant", content: 123 as any },
|
||||
];
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
||||
it("should only match assistant role messages", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: `${COMPACTION_MARKER}\nSystem compaction?` },
|
||||
{ role: "user", content: `${COMPACTION_MARKER}\nUser compaction?` },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nReal compaction` },
|
||||
];
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getHistoryForLLM", () => {
|
||||
it("should return full history when no compaction index", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, null);
|
||||
expect(result).toEqual(history);
|
||||
});
|
||||
|
||||
it("should return compacted history with system message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, 3);
|
||||
expect(result).toEqual([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
|
||||
{ role: "user", content: "Another message" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should return compacted history without system message when compaction is at index 0", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, 0);
|
||||
expect(result).toEqual(history);
|
||||
});
|
||||
|
||||
it("should return full history when compactionIndex is out of bounds", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, 10);
|
||||
expect(result).toEqual(history);
|
||||
});
|
||||
|
||||
it("should handle negative compactionIndex", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, -1);
|
||||
// Negative index with slice means "from the end", so -1 gives us only the last message
|
||||
// Since compactionIndex is not > 0, system message is not included
|
||||
expect(result).toEqual([
|
||||
{ role: "user", content: "Hello" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle empty history", () => {
|
||||
const history: ChatCompletionMessageParam[] = [];
|
||||
const result = getHistoryForLLM(history, 0);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should handle history with only system message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, 0);
|
||||
expect(result).toEqual(history);
|
||||
});
|
||||
|
||||
it("should handle history without system message but with compaction", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "First message" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "user", content: "New message" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, 1);
|
||||
expect(result).toEqual([
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "user", content: "New message" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should include system message when first message is not system", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "First user message" },
|
||||
{ role: "system", content: "System message in wrong position" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "user", content: "New message" },
|
||||
];
|
||||
|
||||
// Since system message is not at index 0, it's not included
|
||||
const result = getHistoryForLLM(history, 2);
|
||||
expect(result).toEqual([
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "user", content: "New message" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should preserve message order from compaction point", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Old 1" },
|
||||
{ role: "assistant", content: "Old 2" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "user", content: "New 1" },
|
||||
{ role: "assistant", content: "New 2" },
|
||||
{ role: "user", content: "New 3" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, 3);
|
||||
expect(result).toEqual([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "user", content: "New 1" },
|
||||
{ role: "assistant", content: "New 2" },
|
||||
{ role: "user", content: "New 3" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("compactChatHistory", () => {
|
||||
it("should compact chat history successfully", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "This is a summary of the conversation";
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2);
|
||||
expect(result.compactedHistory[0]).toEqual({ role: "system", content: "System message" });
|
||||
expect(result.compactedHistory[1]).toEqual({
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\n${mockContent}`
|
||||
});
|
||||
expect(result.compactionIndex).toBe(1);
|
||||
expect(result.compactionContent).toBe(mockContent);
|
||||
});
|
||||
|
||||
it("should handle callbacks correctly", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "Summary content";
|
||||
const onStreamContent = vi.fn();
|
||||
const onStreamComplete = vi.fn();
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary ");
|
||||
callbacks?.onContent?.("content");
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
|
||||
await compactChatHistory(history, mockModel, mockLlmApi, {
|
||||
onStreamContent,
|
||||
onStreamComplete
|
||||
});
|
||||
|
||||
expect(onStreamContent).toHaveBeenCalledWith("Summary ");
|
||||
expect(onStreamContent).toHaveBeenCalledWith("content");
|
||||
expect(onStreamComplete).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle errors correctly", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockError = new Error("Stream failed");
|
||||
const onError = vi.fn();
|
||||
|
||||
mockStreamResponse.mockRejectedValue(mockError);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
|
||||
await expect(
|
||||
compactChatHistory(history, mockModel, mockLlmApi, { onError })
|
||||
).rejects.toThrow("Stream failed");
|
||||
|
||||
expect(onError).toHaveBeenCalledWith(mockError);
|
||||
});
|
||||
|
||||
it("should handle history with only system message", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "Summary of system setup";
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "You are a helpful assistant" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2);
|
||||
expect(result.compactedHistory[0]).toEqual({ role: "system", content: "You are a helpful assistant" });
|
||||
expect(result.compactedHistory[1].content).toContain(COMPACTION_MARKER);
|
||||
});
|
||||
|
||||
it("should handle empty content from stream", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("");
|
||||
callbacks?.onContentComplete?.("");
|
||||
return "";
|
||||
});
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactionContent).toBe("");
|
||||
expect(result.compactedHistory[0].content).toBe(`${COMPACTION_MARKER}\n`);
|
||||
});
|
||||
|
||||
it("should correctly construct prompt for compaction", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
let capturedHistory: ChatCompletionMessageParam[] = [];
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
capturedHistory = [...history];
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
});
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
];
|
||||
|
||||
await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
// Should have original history plus the compaction prompt
|
||||
expect(capturedHistory).toHaveLength(4);
|
||||
expect(capturedHistory[3]).toEqual({
|
||||
role: "user",
|
||||
content: expect.stringContaining("provide a concise summary")
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle history with tool calls and mixed message types", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "Summary including tool usage";
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Do something" },
|
||||
{ role: "assistant", content: "I'll help", tool_calls: [{} as any] },
|
||||
{ role: "tool", content: "Tool result", tool_call_id: "123" },
|
||||
{ role: "assistant", content: "Done" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2);
|
||||
expect(result.compactionContent).toBe(mockContent);
|
||||
});
|
||||
|
||||
it("should handle very long chat histories", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Long summary");
|
||||
callbacks?.onContentComplete?.("Long summary");
|
||||
return "Long summary";
|
||||
});
|
||||
|
||||
// Create a very long history
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System" },
|
||||
];
|
||||
|
||||
for (let i = 0; i < 100; i++) {
|
||||
history.push({ role: "user", content: `User message ${i}` });
|
||||
history.push({ role: "assistant", content: `Assistant response ${i}` });
|
||||
}
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2); // System + compaction
|
||||
expect(result.compactionIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("should handle history without system message", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "Summary without system";
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(1); // Only compaction
|
||||
expect(result.compactedHistory[0].role).toBe("assistant");
|
||||
expect(result.compactionIndex).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("property-based tests", () => {
|
||||
it("getHistoryForLLM should always return a subset of the original history", () => {
|
||||
const testCases: Array<{ history: ChatCompletionMessageParam[], compactionIndex: number | null }> = [
|
||||
{
|
||||
history: [
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
],
|
||||
compactionIndex: 1
|
||||
},
|
||||
{
|
||||
history: [
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
{ role: "user", content: "User 2" },
|
||||
],
|
||||
compactionIndex: 2
|
||||
},
|
||||
{
|
||||
history: [],
|
||||
compactionIndex: null
|
||||
}
|
||||
];
|
||||
|
||||
testCases.forEach(({ history, compactionIndex }) => {
|
||||
const result = getHistoryForLLM(history, compactionIndex);
|
||||
|
||||
// Every message in result should exist in original history
|
||||
result.forEach(msg => {
|
||||
expect(history).toContainEqual(msg);
|
||||
});
|
||||
|
||||
// Result length should be <= original length
|
||||
expect(result.length).toBeLessThanOrEqual(history.length);
|
||||
});
|
||||
});
|
||||
|
||||
it("getHistoryForLLM should always include system message if it exists at index 0", () => {
|
||||
const systemMessage: ChatCompletionMessageParam = { role: "system", content: "System" };
|
||||
const testCases: Array<{ history: ChatCompletionMessageParam[], compactionIndex: number | null }> = [
|
||||
{
|
||||
history: [
|
||||
systemMessage,
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
],
|
||||
compactionIndex: 2
|
||||
},
|
||||
{
|
||||
history: [
|
||||
systemMessage,
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
],
|
||||
compactionIndex: 1
|
||||
}
|
||||
];
|
||||
|
||||
testCases.forEach(({ history, compactionIndex }) => {
|
||||
const result = getHistoryForLLM(history, compactionIndex);
|
||||
|
||||
if (history[0]?.role === "system" && compactionIndex !== null && compactionIndex > 0) {
|
||||
expect(result[0]).toEqual(systemMessage);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("compaction should always reduce message count for non-trivial histories", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
});
|
||||
|
||||
const testHistories: ChatCompletionMessageParam[][] = [
|
||||
[
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
{ role: "user", content: "User 2" },
|
||||
{ role: "assistant", content: "Assistant 2" },
|
||||
],
|
||||
[
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
{ role: "user", content: "User 2" },
|
||||
]
|
||||
];
|
||||
|
||||
for (const history of testHistories) {
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
// Compacted history should be shorter than original
|
||||
// (system + compaction) or just compaction
|
||||
expect(result.compactedHistory.length).toBeLessThanOrEqual(2);
|
||||
expect(result.compactedHistory.length).toBeLessThan(history.length);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("invariant tests", () => {
|
||||
it("compactionIndex should always point to a message with COMPACTION_MARKER", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary content");
|
||||
callbacks?.onContentComplete?.("Summary content");
|
||||
return "Summary content";
|
||||
});
|
||||
|
||||
const histories: ChatCompletionMessageParam[][] = [
|
||||
[{ role: "system", content: "System" }, { role: "user", content: "Hello" }],
|
||||
[{ role: "user", content: "Hello" }, { role: "assistant", content: "Hi" }],
|
||||
[{ role: "system", content: "System" }],
|
||||
];
|
||||
|
||||
for (const history of histories) {
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
// The message at compactionIndex should contain the marker
|
||||
const compactionMessage = result.compactedHistory[result.compactionIndex];
|
||||
expect(compactionMessage.role).toBe("assistant");
|
||||
expect(typeof compactionMessage.content === "string" && compactionMessage.content.startsWith(COMPACTION_MARKER)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("system message should always be preserved in the same position", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
});
|
||||
|
||||
const systemMessage: ChatCompletionMessageParam = { role: "system", content: "You are helpful" };
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
systemMessage,
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
// System message should still be at index 0
|
||||
expect(result.compactedHistory[0]).toEqual(systemMessage);
|
||||
});
|
||||
|
||||
it("findCompactionIndex should be consistent with compactChatHistory result", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
});
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
// findCompactionIndex should find the same index
|
||||
const foundIndex = findCompactionIndex(result.compactedHistory);
|
||||
expect(foundIndex).toBe(result.compactionIndex);
|
||||
});
|
||||
});
|
||||
});
|
||||
139
src/compaction.ts
Normal file
139
src/compaction.ts
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
|
||||
import { StreamCallbacks, streamChatResponse } from "./streamChatResponse.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
export const COMPACTION_MARKER = "[COMPACTED HISTORY]";
|
||||
|
||||
export interface CompactionResult {
|
||||
compactedHistory: ChatCompletionMessageParam[];
|
||||
compactionIndex: number;
|
||||
compactionContent: string;
|
||||
}
|
||||
|
||||
export interface CompactionCallbacks {
|
||||
onStreamContent?: (content: string) => void;
|
||||
onStreamComplete?: () => void;
|
||||
onError?: (error: Error) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compacts a chat history into a summarized form
|
||||
* @param chatHistory The current chat history to compact
|
||||
* @param model The model configuration
|
||||
* @param llmApi The LLM API instance
|
||||
* @param callbacks Optional callbacks for streaming updates
|
||||
* @returns The compacted history with compaction index
|
||||
*/
|
||||
export async function compactChatHistory(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
model: ModelConfig,
|
||||
llmApi: BaseLlmApi,
|
||||
callbacks?: CompactionCallbacks
|
||||
): Promise<CompactionResult> {
|
||||
// Create a prompt to summarize the conversation
|
||||
const compactionPrompt: ChatCompletionMessageParam = {
|
||||
role: "user",
|
||||
content:
|
||||
"Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.",
|
||||
};
|
||||
|
||||
// Get the current history for compaction
|
||||
const historyForCompaction = [...chatHistory, compactionPrompt];
|
||||
|
||||
// Stream the compaction response
|
||||
const controller = new AbortController();
|
||||
|
||||
let compactionContent = "";
|
||||
const streamCallbacks: StreamCallbacks = {
|
||||
onContent: (content: string) => {
|
||||
compactionContent += content;
|
||||
callbacks?.onStreamContent?.(content);
|
||||
},
|
||||
onContentComplete: () => {
|
||||
callbacks?.onStreamComplete?.();
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
await streamChatResponse(
|
||||
historyForCompaction,
|
||||
model,
|
||||
llmApi,
|
||||
controller,
|
||||
streamCallbacks
|
||||
);
|
||||
|
||||
// Create the compacted history with a special marker
|
||||
const systemMessage = chatHistory.find((msg) => msg.role === "system");
|
||||
const compactedMessage: ChatCompletionMessageParam = {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\n${compactionContent}`,
|
||||
};
|
||||
|
||||
// Set new chat history with only system message and compaction
|
||||
const compactedHistory = systemMessage
|
||||
? [systemMessage, compactedMessage]
|
||||
: [compactedMessage];
|
||||
const compactionIndex = compactedHistory.length - 1;
|
||||
|
||||
logger.debug("Chat history compacted", {
|
||||
originalLength: chatHistory.length,
|
||||
compactedLength: compactedHistory.length,
|
||||
compactionIndex,
|
||||
});
|
||||
|
||||
return {
|
||||
compactedHistory,
|
||||
compactionIndex,
|
||||
compactionContent,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error("Compaction failed", error);
|
||||
callbacks?.onError?.(error as Error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the compaction index in a chat history
|
||||
* @param chatHistory The chat history to search
|
||||
* @returns The index of the compaction message, or null if not found
|
||||
*/
|
||||
export function findCompactionIndex(
|
||||
chatHistory: ChatCompletionMessageParam[]
|
||||
): number | null {
|
||||
const compactedIndex = chatHistory.findIndex(
|
||||
(msg) =>
|
||||
msg.role === "assistant" &&
|
||||
typeof msg.content === "string" &&
|
||||
msg.content.startsWith(COMPACTION_MARKER)
|
||||
);
|
||||
return compactedIndex !== -1 ? compactedIndex : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the history to send to the LLM, taking compaction into account
|
||||
* @param fullHistory The complete chat history
|
||||
* @param compactionIndex The index of the compaction message, if any
|
||||
* @returns The history to send to the LLM
|
||||
*/
|
||||
export function getHistoryForLLM(
|
||||
fullHistory: ChatCompletionMessageParam[],
|
||||
compactionIndex: number | null
|
||||
): ChatCompletionMessageParam[] {
|
||||
if (compactionIndex === null || compactionIndex >= fullHistory.length) {
|
||||
return fullHistory;
|
||||
}
|
||||
|
||||
// Include system message (if at index 0) and everything from compaction index forward
|
||||
const systemMessage =
|
||||
fullHistory[0]?.role === "system" ? fullHistory[0] : null;
|
||||
const messagesFromCompaction = fullHistory.slice(compactionIndex);
|
||||
|
||||
return systemMessage && compactionIndex > 0
|
||||
? [systemMessage, ...messagesFromCompaction]
|
||||
: messagesFromCompaction;
|
||||
}
|
||||
|
|
@ -1,8 +1,7 @@
|
|||
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
ModelConfig,
|
||||
RegistryClient,
|
||||
unrollAssistant,
|
||||
} from "@continuedev/config-yaml";
|
||||
import {
|
||||
BaseLlmApi,
|
||||
|
|
@ -14,14 +13,12 @@ import {
|
|||
DefaultApi,
|
||||
DefaultApiInterface,
|
||||
} from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
import chalk from "chalk";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
AuthConfig,
|
||||
getAccessToken,
|
||||
getOrganizationId,
|
||||
} from "./auth/workos.js";
|
||||
import { CLIPlatformClient } from "./CLIPlatformClient.js";
|
||||
import { loadConfiguration } from "./configLoader.js";
|
||||
import { env } from "./env.js";
|
||||
import { MCPService } from "./mcp.js";
|
||||
|
|
@ -77,43 +74,6 @@ export function getLlmApi(
|
|||
return [llmApi, model];
|
||||
}
|
||||
|
||||
async function loadConfigYaml(
|
||||
accessToken: string | null,
|
||||
filePath: string,
|
||||
organizationId: string | null,
|
||||
apiClient: DefaultApiInterface
|
||||
): Promise<AssistantUnrolled> {
|
||||
const unrollResult = await unrollAssistant(
|
||||
{ filePath, uriType: "file" },
|
||||
new RegistryClient({
|
||||
accessToken: accessToken ?? undefined,
|
||||
apiBase: env.apiBase,
|
||||
rootPath: dirname(filePath),
|
||||
}),
|
||||
{
|
||||
currentUserSlug: "",
|
||||
alwaysUseProxy: false,
|
||||
orgScopeId: organizationId,
|
||||
renderSecrets: true,
|
||||
platformClient: new CLIPlatformClient(organizationId, apiClient),
|
||||
onPremProxyUrl: null,
|
||||
}
|
||||
);
|
||||
|
||||
const errorDetails = unrollResult.errors;
|
||||
if (!unrollResult.config) {
|
||||
throw new Error(`Failed to load config file:\n${errorDetails}`);
|
||||
} else if (errorDetails?.length) {
|
||||
const warnings =
|
||||
errorDetails?.length > 1
|
||||
? errorDetails.map((d) => `\n- ${d.message}`)
|
||||
: errorDetails[0].message;
|
||||
console.warn(chalk.dim(`Warning: ${warnings}`));
|
||||
}
|
||||
|
||||
return unrollResult.config;
|
||||
}
|
||||
|
||||
export function getApiClient(
|
||||
accessToken: string | undefined | null
|
||||
): DefaultApi {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
import * as fs from "fs";
|
||||
import { dirname } from "node:path";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
RegistryClient,
|
||||
|
|
@ -5,10 +10,7 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
import chalk from "chalk";
|
||||
import * as fs from "fs";
|
||||
import { dirname } from "node:path";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import {
|
||||
AuthConfig,
|
||||
getAccessToken,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { Continue, ContinueClient } from "@continuedev/sdk";
|
||||
import { env } from "./env.js";
|
||||
import chalk from "chalk";
|
||||
|
||||
import { env } from "./env.js";
|
||||
|
||||
/**
|
||||
* Initialize the Continue SDK with the given parameters
|
||||
* @param apiKey - API key to use for authentication
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
|
||||
import {
|
||||
cleanupTestContext,
|
||||
createTestContext,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { describe, expect, test } from '@jest/globals';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
describe('Config Switching Implementation Test', () => {
|
||||
test('ConfigService updateConfigPath method exists with correct signature', async () => {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
import * as fs from "fs/promises";
|
||||
import * as path from "path";
|
||||
|
||||
import {
|
||||
cleanupTestContext,
|
||||
createTestContext,
|
||||
|
|
@ -10,8 +13,6 @@ import {
|
|||
createMockLLMConfig,
|
||||
type MockLLMServer,
|
||||
} from "../test-helpers/mock-llm-server.js";
|
||||
import * as fs from "fs/promises";
|
||||
import * as path from "path";
|
||||
|
||||
describe("E2E: Headless Mode with Dynamic Responses", () => {
|
||||
let context: any;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
|
||||
import {
|
||||
cleanupTestContext,
|
||||
createTestContext,
|
||||
|
|
|
|||
217
src/e2e/headless-silent-flag.test.ts
Normal file
217
src/e2e/headless-silent-flag.test.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
import {
|
||||
cleanupTestContext,
|
||||
createTestContext,
|
||||
runCLI,
|
||||
} from "../test-helpers/cli-helpers.js";
|
||||
import {
|
||||
setupMockLLMTest,
|
||||
cleanupMockLLMServer,
|
||||
type MockLLMServer,
|
||||
} from "../test-helpers/mock-llm-server.js";
|
||||
|
||||
describe("E2E: Headless Mode with --silent Flag", () => {
|
||||
let context: any;
|
||||
let mockServer: MockLLMServer;
|
||||
|
||||
beforeEach(async () => {
|
||||
context = await createTestContext();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (mockServer) {
|
||||
await cleanupMockLLMServer(mockServer);
|
||||
}
|
||||
await cleanupTestContext(context);
|
||||
});
|
||||
|
||||
it("should strip <think></think> tags from response with --silent flag", async () => {
|
||||
const responseWithThinkTags = `<think>
|
||||
I need to write a shell script. Let me think about this.
|
||||
The user wants a simple Hello World script.
|
||||
</think>
|
||||
|
||||
#!/bin/bash
|
||||
echo "Hello World"`;
|
||||
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
response: responseWithThinkTags,
|
||||
streaming: false,
|
||||
});
|
||||
|
||||
const result = await runCLI(context, {
|
||||
args: ["-p", "--silent", "--config", context.configPath, "Write a shell script"],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Verify think tags are stripped
|
||||
expect(result.stdout).not.toContain("<think>");
|
||||
expect(result.stdout).not.toContain("</think>");
|
||||
expect(result.stdout).not.toContain("I need to write a shell script");
|
||||
|
||||
// Verify the actual content remains
|
||||
expect(result.stdout).toContain("#!/bin/bash");
|
||||
expect(result.stdout).toContain('echo "Hello World"');
|
||||
expect(result.exitCode).toBe(0);
|
||||
}, 20000);
|
||||
|
||||
it("should strip multiple <think></think> blocks with --silent flag", async () => {
|
||||
const responseWithMultipleThinkTags = `<think>
|
||||
First thought block
|
||||
</think>
|
||||
|
||||
Some content here
|
||||
|
||||
<think>
|
||||
Second thought block
|
||||
More thinking...
|
||||
</think>
|
||||
|
||||
Final content`;
|
||||
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
response: responseWithMultipleThinkTags,
|
||||
streaming: false,
|
||||
});
|
||||
|
||||
const result = await runCLI(context, {
|
||||
args: ["-p", "--silent", "--config", context.configPath, "Test prompt"],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Verify all think tags are stripped
|
||||
expect(result.stdout).not.toContain("<think>");
|
||||
expect(result.stdout).not.toContain("</think>");
|
||||
expect(result.stdout).not.toContain("First thought block");
|
||||
expect(result.stdout).not.toContain("Second thought block");
|
||||
expect(result.stdout).not.toContain("More thinking...");
|
||||
|
||||
// Verify the actual content remains
|
||||
expect(result.stdout).toContain("Some content here");
|
||||
expect(result.stdout).toContain("Final content");
|
||||
expect(result.exitCode).toBe(0);
|
||||
}, 20000);
|
||||
|
||||
it("should reduce excess whitespace with --silent flag", async () => {
|
||||
const responseWithExcessWhitespace = `<think>
|
||||
This will be removed
|
||||
</think>
|
||||
|
||||
|
||||
|
||||
Content with lots of whitespace
|
||||
|
||||
|
||||
|
||||
More content`;
|
||||
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
response: responseWithExcessWhitespace,
|
||||
streaming: false,
|
||||
});
|
||||
|
||||
const result = await runCLI(context, {
|
||||
args: ["-p", "--silent", "--config", context.configPath, "Test prompt"],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Verify think tags are stripped and excess whitespace is reduced
|
||||
expect(result.stdout).not.toContain("<think>");
|
||||
expect(result.stdout).not.toContain("This will be removed");
|
||||
expect(result.stdout).toContain("Content with lots of whitespace");
|
||||
expect(result.stdout).toContain("More content");
|
||||
|
||||
// Verify no triple newlines exist (excess whitespace reduced)
|
||||
expect(result.stdout).not.toMatch(/\n\s*\n\s*\n/);
|
||||
expect(result.exitCode).toBe(0);
|
||||
}, 20000);
|
||||
|
||||
it("should work normally without --silent flag (baseline test)", async () => {
|
||||
const responseWithThinkTags = `<think>
|
||||
I need to write a shell script. Let me think about this.
|
||||
</think>
|
||||
|
||||
#!/bin/bash
|
||||
echo "Hello World"`;
|
||||
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
response: responseWithThinkTags,
|
||||
streaming: false,
|
||||
});
|
||||
|
||||
const result = await runCLI(context, {
|
||||
args: ["-p", "--config", context.configPath, "Write a shell script"],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Verify think tags are NOT stripped without --silent flag
|
||||
expect(result.stdout).toContain("<think>");
|
||||
expect(result.stdout).toContain("</think>");
|
||||
expect(result.stdout).toContain("I need to write a shell script");
|
||||
expect(result.stdout).toContain("#!/bin/bash");
|
||||
expect(result.stdout).toContain('echo "Hello World"');
|
||||
expect(result.exitCode).toBe(0);
|
||||
}, 20000);
|
||||
|
||||
it("should handle response with no think tags using --silent flag", async () => {
|
||||
const responseWithoutThinkTags = `#!/bin/bash
|
||||
echo "Hello World"
|
||||
|
||||
This is a simple script.`;
|
||||
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
response: responseWithoutThinkTags,
|
||||
streaming: false,
|
||||
});
|
||||
|
||||
const result = await runCLI(context, {
|
||||
args: ["-p", "--silent", "--config", context.configPath, "Write a shell script"],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Verify content is preserved when no think tags exist
|
||||
expect(result.stdout).toContain("#!/bin/bash");
|
||||
expect(result.stdout).toContain('echo "Hello World"');
|
||||
expect(result.stdout).toContain("This is a simple script.");
|
||||
expect(result.exitCode).toBe(0);
|
||||
}, 20000);
|
||||
|
||||
it("should fail validation when --silent is used without -p flag", async () => {
|
||||
const result = await runCLI(context, {
|
||||
args: ["--silent", "Test prompt"],
|
||||
timeout: 5000,
|
||||
expectError: true,
|
||||
});
|
||||
|
||||
expect(result.stderr).toContain("--silent flag can only be used with -p/--print flag");
|
||||
expect(result.exitCode).toBe(1);
|
||||
}, 10000);
|
||||
|
||||
it("should work with both --silent and --format json flags", async () => {
|
||||
const responseWithThinkTags = `<think>
|
||||
I should respond with JSON
|
||||
</think>
|
||||
|
||||
{"message": "Hello World", "status": "success"}`;
|
||||
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
response: responseWithThinkTags,
|
||||
streaming: false,
|
||||
});
|
||||
|
||||
const result = await runCLI(context, {
|
||||
args: ["-p", "--silent", "--format", "json", "--config", context.configPath, "Test prompt"],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Verify think tags are stripped and JSON is valid
|
||||
expect(result.stdout).not.toContain("<think>");
|
||||
expect(result.stdout).not.toContain("I should respond with JSON");
|
||||
|
||||
// Verify the output is valid JSON
|
||||
expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
|
||||
const parsedOutput = JSON.parse(result.stdout.trim());
|
||||
expect(parsedOutput.message).toBe("Hello World");
|
||||
expect(parsedOutput.status).toBe("success");
|
||||
expect(result.exitCode).toBe(0);
|
||||
}, 20000);
|
||||
});
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import * as http from "http";
|
||||
|
||||
import {
|
||||
cleanupTestContext,
|
||||
createTestContext,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { describe, expect, test } from '@jest/globals';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
describe('Local Config Switching Investigation', () => {
|
||||
test('understands local vs remote config paths', () => {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
import * as fs from "fs/promises";
|
||||
import * as path from "path";
|
||||
|
||||
import {
|
||||
cleanupTestContext,
|
||||
createTestContext,
|
||||
|
|
@ -8,8 +11,6 @@ import {
|
|||
cleanupMockLLMServer,
|
||||
type MockLLMServer,
|
||||
} from "../test-helpers/mock-llm-server.js";
|
||||
import * as fs from "fs/promises";
|
||||
import * as path from "path";
|
||||
|
||||
describe("E2E: Resume Flag", () => {
|
||||
let context: any;
|
||||
|
|
@ -130,7 +131,7 @@ describe("E2E: Resume Flag", () => {
|
|||
expect(firstResult.stdout).toContain("First response");
|
||||
|
||||
// Verify the first session was saved correctly
|
||||
let sessionDir = path.join(context.testDir, ".continue-cli", "sessions");
|
||||
const sessionDir = path.join(context.testDir, ".continue-cli", "sessions");
|
||||
let sessionFiles = await fs.readdir(sessionDir);
|
||||
expect(sessionFiles).toHaveLength(1);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,15 @@
|
|||
import chalk from "chalk";
|
||||
import { spawn } from "child_process";
|
||||
import * as fs from "fs";
|
||||
import open from "open";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import chalk from "chalk";
|
||||
import open from "open";
|
||||
import * as readlineSync from "readline-sync";
|
||||
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
|
||||
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
|
||||
|
||||
import { env } from "./env.js";
|
||||
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
|
||||
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
|
||||
|
||||
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
|
||||
|
||||
|
|
@ -63,7 +65,7 @@ export async function handleMaxedOutFreeTrial(onReload?: () => Promise<void>): P
|
|||
"After setting up your models subscription, restart the CLI to continue."
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
} catch {
|
||||
console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
|
||||
console.log(chalk.white(`Please visit: ${modelsUrl}`));
|
||||
console.log(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { useServiceContainer } from '../services/ServiceContainerContext.js';
|
||||
import { ServiceResult } from '../services/types.js';
|
||||
|
||||
|
|
@ -104,25 +105,20 @@ export function useServices<T extends Record<string, any>>(
|
|||
const newServices: Partial<T> = {};
|
||||
let hasLoading = false;
|
||||
let hasError: Error | null = null;
|
||||
let allReady = true;
|
||||
|
||||
for (const serviceName of serviceNames) {
|
||||
const result = container.getSync(serviceName as string);
|
||||
|
||||
if (result.state === 'loading') {
|
||||
hasLoading = true;
|
||||
allReady = false;
|
||||
} else if (result.state === 'error') {
|
||||
hasError = result.error;
|
||||
allReady = false;
|
||||
} else if (result.state === 'idle') {
|
||||
allReady = false;
|
||||
// Auto-load idle services
|
||||
container.load(serviceName as string).catch(() => {});
|
||||
} else if (result.state === 'ready' && result.value !== null) {
|
||||
newServices[serviceName] = result.value as T[keyof T];
|
||||
} else {
|
||||
allReady = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
17
src/index.ts
17
src/index.ts
|
|
@ -1,6 +1,7 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { Command } from "commander";
|
||||
|
||||
import { chat } from "./commands/chat.js";
|
||||
import { login } from "./commands/login.js";
|
||||
import { logout } from "./commands/logout.js";
|
||||
|
|
@ -9,7 +10,7 @@ import { remote } from "./commands/remote.js";
|
|||
import { serve } from "./commands/serve.js";
|
||||
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
|
||||
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
|
||||
import logger from "./util/logger.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
import { readStdinSync } from "./util/stdin.js";
|
||||
import { getVersion } from "./version.js";
|
||||
|
||||
|
|
@ -42,11 +43,16 @@ addCommonOptions(program)
|
|||
"--format <format>",
|
||||
"Output format for headless mode (json). Only works with -p/--print flag."
|
||||
)
|
||||
.option(
|
||||
"--silent",
|
||||
"Strip <think></think> tags and excess whitespace from output. Only works with -p/--print flag."
|
||||
)
|
||||
.option("--resume", "Resume from last session")
|
||||
.action(async (prompt, options) => {
|
||||
// Configure console overrides FIRST, before any other logging
|
||||
const isHeadless = options.print;
|
||||
configureConsoleForHeadless(isHeadless);
|
||||
logger.configureHeadlessMode(isHeadless);
|
||||
|
||||
// Validate --format flag only works with -p/--print
|
||||
if (options.format && !options.print) {
|
||||
|
|
@ -56,6 +62,15 @@ addCommonOptions(program)
|
|||
process.exit(1);
|
||||
}
|
||||
|
||||
// Validate --silent flag only works with -p/--print
|
||||
if (options.silent && !options.print) {
|
||||
console.error(
|
||||
"Error: --silent flag can only be used with -p/--print flag"
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
// Validate format value
|
||||
if (options.format && options.format !== "json") {
|
||||
console.error("Error: --format currently only supports 'json'");
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
import chalk from 'chalk';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
import {
|
||||
configureLogger,
|
||||
isLoggingEnabled,
|
||||
|
|
@ -7,26 +10,24 @@ import {
|
|||
warn,
|
||||
loggers
|
||||
} from './logging.js';
|
||||
import { jest } from '@jest/globals';
|
||||
import chalk from 'chalk';
|
||||
|
||||
describe('logging utilities', () => {
|
||||
let consoleInfoSpy: jest.SpiedFunction<typeof console.info>;
|
||||
let consoleErrorSpy: jest.SpiedFunction<typeof console.error>;
|
||||
let consoleWarnSpy: jest.SpiedFunction<typeof console.warn>;
|
||||
let consoleInfoSpy: ReturnType<typeof vi.spyOn>;
|
||||
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
|
||||
let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset logger state
|
||||
configureLogger({ headless: false });
|
||||
|
||||
// Mock console methods
|
||||
consoleInfoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
|
||||
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation(() => {});
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('configureLogger', () => {
|
||||
|
|
|
|||
58
src/mcp.ts
58
src/mcp.ts
|
|
@ -1,7 +1,7 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import logger from "./util/logger.js";
|
||||
|
||||
import { MCPConnection } from "./MCPConnection.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
export class MCPService {
|
||||
private readonly connections: MCPConnection[] = [];
|
||||
|
|
@ -60,55 +60,3 @@ export class MCPService {
|
|||
throw new Error(`Tool ${name} not found`);
|
||||
}
|
||||
}
|
||||
|
||||
export class MCPConnection {
|
||||
prompts: Awaited<ReturnType<Client["listPrompts"]>>["prompts"] = [];
|
||||
tools: Awaited<ReturnType<Client["listTools"]>>["tools"] = [];
|
||||
|
||||
private constructor(public readonly client: Client) {}
|
||||
|
||||
public static async create(
|
||||
config: NonNullable<AssistantConfig["mcpServers"]>[number]
|
||||
) {
|
||||
const client = new Client(
|
||||
{
|
||||
name: "continue-cli-client",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{ capabilities: {} }
|
||||
);
|
||||
|
||||
// Construct transport
|
||||
const env: Record<string, string> = config?.env || {};
|
||||
if (process.env.PATH !== undefined) {
|
||||
env.PATH = process.env.PATH;
|
||||
}
|
||||
|
||||
if (!config?.command) {
|
||||
throw new Error("MCP server command is not specified");
|
||||
}
|
||||
|
||||
const transport = new StdioClientTransport({
|
||||
command: config.command,
|
||||
args: config?.args,
|
||||
env,
|
||||
});
|
||||
|
||||
// Connect and get all prompts and tools
|
||||
const connection = new MCPConnection(client);
|
||||
logger.debug('Connecting to MCP server', { command: config.command });
|
||||
await client.connect(transport);
|
||||
const capabilities = client.getServerCapabilities();
|
||||
logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools });
|
||||
|
||||
if (capabilities?.prompts) {
|
||||
connection.prompts = (await client.listPrompts()).prompts;
|
||||
}
|
||||
|
||||
if (capabilities?.tools) {
|
||||
connection.tools = (await client.listTools()).tools;
|
||||
}
|
||||
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,19 @@
|
|||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
import chalk from "chalk";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import * as readlineSync from "readline-sync";
|
||||
|
||||
import { processRule } from "./args.js";
|
||||
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
|
||||
import { initialize } from "./config.js";
|
||||
import { MCPService } from "./mcp.js";
|
||||
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
|
||||
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
|
||||
|
||||
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
|
||||
|
||||
|
|
@ -33,13 +36,11 @@ export async function checkHasAcceptableModel(
|
|||
|
||||
const content = fs.readFileSync(configPath, "utf8");
|
||||
return content.includes("claude");
|
||||
} catch (error) {
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
|
||||
|
||||
export async function createOrUpdateConfig(apiKey: string): Promise<void> {
|
||||
const configDir = path.dirname(CONFIG_PATH);
|
||||
|
||||
|
|
@ -111,7 +112,7 @@ export async function runNormalFlow(
|
|||
): Promise<OnboardingResult> {
|
||||
// Step 1: Check if --config flag is provided
|
||||
if (configPath) {
|
||||
let result = await initialize(authConfig, configPath);
|
||||
const result = await initialize(authConfig, configPath);
|
||||
// Inject rules into the config if provided
|
||||
if (rules && rules.length > 0) {
|
||||
result.config = await injectRulesIntoConfig(result.config, rules);
|
||||
|
|
@ -122,25 +123,27 @@ export async function runNormalFlow(
|
|||
// Step 2: If user is logged in, look for first assistant in selected org
|
||||
if (isAuthenticated()) {
|
||||
try {
|
||||
let result = await initialize(authConfig, undefined);
|
||||
const result = await initialize(authConfig, undefined);
|
||||
// Inject rules into the config if provided
|
||||
if (rules && rules.length > 0) {
|
||||
result.config = await injectRulesIntoConfig(result.config, rules);
|
||||
}
|
||||
return { ...result, wasOnboarded: false };
|
||||
} catch (error) {}
|
||||
} catch {
|
||||
// Silently ignore errors when loading default assistant
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: Look for local ~/.continue/config.yaml
|
||||
if (fs.existsSync(CONFIG_PATH)) {
|
||||
try {
|
||||
let result = await initialize(authConfig, CONFIG_PATH);
|
||||
const result = await initialize(authConfig, CONFIG_PATH);
|
||||
// Inject rules into the config if provided
|
||||
if (rules && rules.length > 0) {
|
||||
result.config = await injectRulesIntoConfig(result.config, rules);
|
||||
}
|
||||
return { ...result, wasOnboarded: false };
|
||||
} catch (error) {
|
||||
} catch {
|
||||
console.log(chalk.yellow("⚠ Invalid config file found"));
|
||||
}
|
||||
}
|
||||
|
|
@ -150,7 +153,7 @@ export async function runNormalFlow(
|
|||
console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment"));
|
||||
await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY);
|
||||
console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`));
|
||||
let result = await initialize(authConfig, CONFIG_PATH);
|
||||
const result = await initialize(authConfig, CONFIG_PATH);
|
||||
// Inject rules into the config if provided
|
||||
if (rules && rules.length > 0) {
|
||||
result.config = await injectRulesIntoConfig(result.config, rules);
|
||||
|
|
@ -193,7 +196,7 @@ async function injectRulesIntoConfig(
|
|||
return config;
|
||||
}
|
||||
|
||||
let processedRules: string[] = [];
|
||||
const processedRules: string[] = [];
|
||||
for (const ruleSpec of rules) {
|
||||
try {
|
||||
const processedRule = await processRule(ruleSpec);
|
||||
|
|
|
|||
|
|
@ -6,26 +6,26 @@ import { ToolPermissionPolicy } from "./types.js";
|
|||
*/
|
||||
export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [
|
||||
// Read-only tools are generally safe to allow
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "list_files", permission: "allow" },
|
||||
{ tool: "search_code", permission: "allow" },
|
||||
{ tool: "fetch", permission: "allow" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "List", permission: "allow" },
|
||||
{ tool: "Search", permission: "allow" },
|
||||
{ tool: "Fetch", permission: "allow" },
|
||||
|
||||
// Write operations should require confirmation
|
||||
{ tool: "write_file", permission: "ask" },
|
||||
{ tool: "edit_file", permission: "ask" },
|
||||
{ tool: "Write", permission: "ask" },
|
||||
{ tool: "Edit", permission: "ask" },
|
||||
|
||||
// Write to a checklist
|
||||
{ tool: "write_checklist", permission: "allow" },
|
||||
{ tool: "Checklist", permission: "allow" },
|
||||
|
||||
// Terminal commands should require confirmation by default
|
||||
{ tool: "run_terminal_command", permission: "ask" },
|
||||
{ tool: "Bash", permission: "ask" },
|
||||
|
||||
// Exit tool is generally safe (headless mode only)
|
||||
{ tool: "exit", permission: "allow" },
|
||||
{ tool: "Exit", permission: "allow" },
|
||||
|
||||
// View diff is read-only
|
||||
{ tool: "view_diff", permission: "allow" },
|
||||
{ tool: "Diff", permission: "allow" },
|
||||
|
||||
// Default fallback - ask for any unmatched tools
|
||||
{ tool: "*", permission: "ask" },
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
|
||||
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
||||
import { checkToolPermission } from "./permissionChecker.js";
|
||||
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
|
||||
|
||||
describe("Headless Permissions Integration", () => {
|
||||
describe("precedence resolution", () => {
|
||||
|
|
@ -34,13 +34,13 @@ describe("Headless Permissions Integration", () => {
|
|||
const permissions = { policies: DEFAULT_TOOL_POLICIES };
|
||||
|
||||
// Read-only tools should be allowed
|
||||
expect(checkToolPermission({ name: "read_file", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "list_files", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "search_code", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "List", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Search", arguments: {} }, permissions).permission).toBe("allow");
|
||||
|
||||
// Write operations should require permission
|
||||
expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("ask");
|
||||
expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("ask");
|
||||
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("ask");
|
||||
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("ask");
|
||||
|
||||
// Unknown tools should default to ask
|
||||
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask");
|
||||
|
|
@ -61,8 +61,8 @@ describe("Headless Permissions Integration", () => {
|
|||
expect(excludedResult.permission).toBe("exclude");
|
||||
|
||||
// Default tools should follow their normal rules
|
||||
expect(checkToolPermission({ name: "read_file", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("ask");
|
||||
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("ask");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -74,7 +74,7 @@ describe("Headless Permissions Integration", () => {
|
|||
// Still exclude truly dangerous operations
|
||||
exclude: ["rm", "sudo"],
|
||||
// Allow specific tools that would normally require confirmation
|
||||
allow: ["write_file", "run_terminal_command"],
|
||||
allow: ["Write", "Bash"],
|
||||
},
|
||||
useDefaults: true,
|
||||
personalSettings: false,
|
||||
|
|
@ -87,11 +87,11 @@ describe("Headless Permissions Integration", () => {
|
|||
expect(checkToolPermission({ name: "sudo", arguments: {} }, permissions).permission).toBe("exclude");
|
||||
|
||||
// Explicitly allowed tools should be allowed
|
||||
expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("allow");
|
||||
|
||||
// Read-only tools should still be allowed by default
|
||||
expect(checkToolPermission({ name: "read_file", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
|
||||
|
||||
// Unknown tools should default to ask (since no wildcard allow override was provided)
|
||||
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask");
|
||||
|
|
@ -109,8 +109,8 @@ describe("Headless Permissions Integration", () => {
|
|||
const permissions = { policies };
|
||||
|
||||
// All tools should be allowed due to wildcard override
|
||||
expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("allow");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
114
src/permissions/permissionChecker.integration.test.ts
Normal file
114
src/permissions/permissionChecker.integration.test.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
|
||||
import { ToolPermissionService } from '../services/ToolPermissionService.js';
|
||||
|
||||
import { checkToolPermission } from './permissionChecker.js';
|
||||
|
||||
describe('Permission Integration Tests', () => {
|
||||
let service: ToolPermissionService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new ToolPermissionService();
|
||||
});
|
||||
|
||||
describe('Headless mode with --allow flags', () => {
|
||||
it('should allow Edit tool when --allow Edit is specified in headless mode', () => {
|
||||
// Initialize service with headless mode and --allow Edit
|
||||
service.initializeSync({
|
||||
allow: ['Edit'],
|
||||
isHeadless: true
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
|
||||
// Check that the service is in headless mode
|
||||
expect(state.isHeadless).toBe(true);
|
||||
|
||||
// Check permission for Edit tool
|
||||
const result = checkToolPermission(
|
||||
{ name: 'Edit', arguments: {} },
|
||||
state.permissions
|
||||
);
|
||||
|
||||
// Should be allowed because --allow Edit is specified
|
||||
expect(result.permission).toBe('allow');
|
||||
});
|
||||
|
||||
it('should allow multiple tools with --allow in headless mode', () => {
|
||||
// Initialize service with headless mode and multiple --allow flags
|
||||
service.initializeSync({
|
||||
allow: ['Edit', 'Write', 'Bash'],
|
||||
isHeadless: true
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
|
||||
// Check Edit
|
||||
const editResult = checkToolPermission(
|
||||
{ name: 'Edit', arguments: {} },
|
||||
state.permissions
|
||||
);
|
||||
expect(editResult.permission).toBe('allow');
|
||||
|
||||
// Check Write
|
||||
const writeResult = checkToolPermission(
|
||||
{ name: 'Write', arguments: {} },
|
||||
state.permissions
|
||||
);
|
||||
expect(writeResult.permission).toBe('allow');
|
||||
|
||||
// Check Bash
|
||||
const bashResult = checkToolPermission(
|
||||
{ name: 'Bash', arguments: {} },
|
||||
state.permissions
|
||||
);
|
||||
expect(bashResult.permission).toBe('allow');
|
||||
});
|
||||
|
||||
it('should respect --exclude in headless mode', () => {
|
||||
service.initializeSync({
|
||||
allow: ['Read'],
|
||||
exclude: ['Edit'],
|
||||
isHeadless: true
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
|
||||
// Check that Read is allowed
|
||||
const readResult = checkToolPermission(
|
||||
{ name: 'Read', arguments: {} },
|
||||
state.permissions
|
||||
);
|
||||
expect(readResult.permission).toBe('allow');
|
||||
|
||||
// Check that Edit is excluded
|
||||
const editResult = checkToolPermission(
|
||||
{ name: 'Edit', arguments: {} },
|
||||
state.permissions
|
||||
);
|
||||
expect(editResult.permission).toBe('exclude');
|
||||
});
|
||||
|
||||
it('should work with plan mode and --allow overrides', () => {
|
||||
// Plan mode normally excludes write operations
|
||||
service.initializeSync({
|
||||
mode: 'plan',
|
||||
allow: ['Edit'], // But we explicitly allow Edit
|
||||
isHeadless: true
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
|
||||
// In plan mode with --allow Edit override
|
||||
const editResult = checkToolPermission(
|
||||
{ name: 'Edit', arguments: {} },
|
||||
state.permissions
|
||||
);
|
||||
|
||||
// Currently this fails because plan mode ignores --allow flags
|
||||
// After fix, this should be 'allow'
|
||||
expect(editResult.permission).toBe('exclude'); // Current behavior
|
||||
// TODO: After fix, change to: expect(editResult.permission).toBe('allow');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import {
|
||||
checkToolPermission,
|
||||
filterExcludedTools,
|
||||
matchesToolPattern,
|
||||
matchesArguments,
|
||||
matchesToolPattern,
|
||||
} from "./permissionChecker.js";
|
||||
import { ToolPermissions } from "./types.js";
|
||||
|
||||
|
|
@ -20,7 +20,9 @@ describe("Permission Checker", () => {
|
|||
});
|
||||
|
||||
it("should match prefix wildcards", () => {
|
||||
expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(true);
|
||||
expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(
|
||||
true
|
||||
);
|
||||
expect(matchesToolPattern("mcp__filesystem__read", "mcp__*")).toBe(true);
|
||||
expect(matchesToolPattern("builtin__readFile", "mcp__*")).toBe(false);
|
||||
});
|
||||
|
|
@ -55,7 +57,9 @@ describe("Permission Checker", () => {
|
|||
expect(matchesToolPattern("test$dollar", "test$dollar")).toBe(true);
|
||||
expect(matchesToolPattern("test{brace}", "test{brace}")).toBe(true);
|
||||
expect(matchesToolPattern("test|pipe", "test|pipe")).toBe(true);
|
||||
expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(true);
|
||||
expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle wildcard patterns with special regex characters", () => {
|
||||
|
|
@ -68,37 +72,67 @@ describe("Permission Checker", () => {
|
|||
});
|
||||
|
||||
describe("Bash command patterns", () => {
|
||||
it("should match Bash command patterns with run_terminal_command", () => {
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "ls" })).toBe(true);
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "ls -la" })).toBe(true);
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "pwd" })).toBe(false);
|
||||
it("should match Bash command patterns with Bash tool", () => {
|
||||
expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls" })).toBe(
|
||||
true
|
||||
);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" })
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should match Bash command patterns with Bash display name", () => {
|
||||
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })).toBe(true);
|
||||
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })).toBe(true);
|
||||
expect(matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })).toBe(false);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should match exact Bash commands", () => {
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(ls)", { command: "ls" })).toBe(true);
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(ls)", { command: "ls -la" })).toBe(false);
|
||||
expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls" })).toBe(
|
||||
true
|
||||
);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should not match Bash patterns for non-bash tools", () => {
|
||||
expect(matchesToolPattern("read_file", "Bash(ls*)", { command: "ls" })).toBe(false);
|
||||
expect(matchesToolPattern("write_file", "Bash(git*)", { command: "git status" })).toBe(false);
|
||||
expect(matchesToolPattern("Read", "Bash(ls*)", { command: "ls" })).toBe(
|
||||
false
|
||||
);
|
||||
expect(
|
||||
matchesToolPattern("Write", "Bash(git*)", { command: "git status" })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should not match Bash patterns without command argument", () => {
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", {})).toBe(false);
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { other: "value" })).toBe(false);
|
||||
expect(matchesToolPattern("Bash", "Bash(ls*)", {})).toBe(false);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { other: "value" })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle complex Bash command patterns", () => {
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(npm*)", { command: "npm install" })).toBe(true);
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(npm*)", { command: "npm run build" })).toBe(true);
|
||||
expect(matchesToolPattern("run_terminal_command", "Bash(git*commit*)", { command: "git commit -m 'test'" })).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" })
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm run build" })
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(git*commit*)", {
|
||||
command: "git commit -m 'test'",
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -114,7 +148,7 @@ describe("Permission Checker", () => {
|
|||
const args = { path: "/test.txt", mode: "read" };
|
||||
const patterns = { path: "/test.txt" };
|
||||
expect(matchesArguments(args, patterns)).toBe(true);
|
||||
|
||||
|
||||
const nonMatchingPatterns = { path: "/other.txt" };
|
||||
expect(matchesArguments(args, nonMatchingPatterns)).toBe(false);
|
||||
});
|
||||
|
|
@ -123,7 +157,7 @@ describe("Permission Checker", () => {
|
|||
const args = { path: "/any/file.txt", mode: "write" };
|
||||
const patterns = { path: "*", mode: "write" };
|
||||
expect(matchesArguments(args, patterns)).toBe(true);
|
||||
|
||||
|
||||
const wildcardOnlyPatterns = { path: "*" };
|
||||
expect(matchesArguments(args, wildcardOnlyPatterns)).toBe(true);
|
||||
});
|
||||
|
|
@ -132,7 +166,7 @@ describe("Permission Checker", () => {
|
|||
const args = { path: "/test.txt", mode: "read", format: "json" };
|
||||
const allMatchingPatterns = { path: "/test.txt", mode: "read" };
|
||||
expect(matchesArguments(args, allMatchingPatterns)).toBe(true);
|
||||
|
||||
|
||||
const partialMatchingPatterns = { path: "/test.txt", mode: "write" };
|
||||
expect(matchesArguments(args, partialMatchingPatterns)).toBe(false);
|
||||
});
|
||||
|
|
@ -147,7 +181,7 @@ describe("Permission Checker", () => {
|
|||
const args = { count: 42, enabled: true, data: null, list: [1, 2, 3] };
|
||||
const patterns = { count: 42, enabled: true };
|
||||
expect(matchesArguments(args, patterns)).toBe(true);
|
||||
|
||||
|
||||
const mismatchedPatterns = { count: "42" }; // string vs number
|
||||
expect(matchesArguments(args, mismatchedPatterns)).toBe(false);
|
||||
});
|
||||
|
|
@ -155,38 +189,43 @@ describe("Permission Checker", () => {
|
|||
it("should handle complex object arguments with reference equality", () => {
|
||||
const configObj = { host: "localhost", port: 3000 };
|
||||
const optionsArray = ["verbose", "debug"];
|
||||
|
||||
const args = {
|
||||
|
||||
const args = {
|
||||
config: configObj,
|
||||
options: optionsArray
|
||||
options: optionsArray,
|
||||
};
|
||||
const patterns = {
|
||||
const patterns = {
|
||||
config: configObj, // Same reference
|
||||
options: optionsArray // Same reference
|
||||
options: optionsArray, // Same reference
|
||||
};
|
||||
expect(matchesArguments(args, patterns)).toBe(true);
|
||||
|
||||
const differentObjectPatterns = {
|
||||
config: { host: "localhost", port: 8080 } // Different object
|
||||
|
||||
const differentObjectPatterns = {
|
||||
config: { host: "localhost", port: 8080 }, // Different object
|
||||
};
|
||||
expect(matchesArguments(args, differentObjectPatterns)).toBe(false);
|
||||
|
||||
const differentButEqualObjectPatterns = {
|
||||
config: { host: "localhost", port: 3000 } // Different reference, same content
|
||||
|
||||
const differentButEqualObjectPatterns = {
|
||||
config: { host: "localhost", port: 3000 }, // Different reference, same content
|
||||
};
|
||||
expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(false);
|
||||
expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
describe("glob pattern matching", () => {
|
||||
it("should match glob patterns with asterisk wildcards", () => {
|
||||
const args = { command: "cd ../projects && ls", file_path: "/src/file.ts" };
|
||||
|
||||
const args = {
|
||||
command: "cd ../projects && ls",
|
||||
file_path: "/src/file.ts",
|
||||
};
|
||||
|
||||
// Test command patterns
|
||||
expect(matchesArguments(args, { command: "cd*" })).toBe(true);
|
||||
expect(matchesArguments(args, { command: "*ls" })).toBe(true);
|
||||
expect(matchesArguments(args, { command: "*&&*" })).toBe(true);
|
||||
expect(matchesArguments(args, { command: "pwd*" })).toBe(false);
|
||||
|
||||
|
||||
// Test file path patterns
|
||||
expect(matchesArguments(args, { file_path: "*.ts" })).toBe(true);
|
||||
expect(matchesArguments(args, { file_path: "/src/*" })).toBe(true);
|
||||
|
|
@ -196,7 +235,7 @@ describe("Permission Checker", () => {
|
|||
|
||||
it("should match glob patterns with question mark wildcards", () => {
|
||||
const args = { command: "git add", file: "test1.js" };
|
||||
|
||||
|
||||
expect(matchesArguments(args, { command: "git a?d" })).toBe(true);
|
||||
expect(matchesArguments(args, { command: "git a??d" })).toBe(false);
|
||||
expect(matchesArguments(args, { file: "test?.js" })).toBe(true);
|
||||
|
|
@ -204,87 +243,99 @@ describe("Permission Checker", () => {
|
|||
});
|
||||
|
||||
it("should match complex glob patterns", () => {
|
||||
const args = {
|
||||
const args = {
|
||||
command: "npm run test:unit",
|
||||
path: "/home/user/projects/myapp/src/utils/helper.ts"
|
||||
path: "/home/user/projects/myapp/src/utils/helper.ts",
|
||||
};
|
||||
|
||||
|
||||
expect(matchesArguments(args, { command: "npm * test:*" })).toBe(true);
|
||||
expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(true);
|
||||
expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(
|
||||
true
|
||||
);
|
||||
expect(matchesArguments(args, { path: "**/src/**/*.ts" })).toBe(true);
|
||||
expect(matchesArguments(args, { path: "/home/*/projects/*/src/**" })).toBe(true);
|
||||
expect(
|
||||
matchesArguments(args, { path: "/home/*/projects/*/src/**" })
|
||||
).toBe(true);
|
||||
expect(matchesArguments(args, { command: "yarn *" })).toBe(false);
|
||||
});
|
||||
|
||||
it("should escape special regex characters in glob patterns", () => {
|
||||
const args = {
|
||||
const args = {
|
||||
command: "echo 'test.pattern'",
|
||||
regex: "test[0-9]+",
|
||||
special: "file(1).txt"
|
||||
special: "file(1).txt",
|
||||
};
|
||||
|
||||
|
||||
// Literal dots, brackets, parentheses should match exactly
|
||||
expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(true);
|
||||
expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(
|
||||
true
|
||||
);
|
||||
expect(matchesArguments(args, { regex: "test[0-9]+" })).toBe(true);
|
||||
expect(matchesArguments(args, { special: "file(1).txt" })).toBe(true);
|
||||
expect(matchesArguments(args, { special: "file(*).txt" })).toBe(true);
|
||||
|
||||
|
||||
// These should not match due to regex escaping
|
||||
expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(false);
|
||||
expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(
|
||||
false
|
||||
);
|
||||
expect(matchesArguments(args, { regex: "test*" })).toBe(true); // * is wildcard, + is literal
|
||||
});
|
||||
|
||||
it("should handle mixed exact and glob patterns", () => {
|
||||
const args = {
|
||||
tool: "bash",
|
||||
const args = {
|
||||
tool: "bash",
|
||||
command: "cd projects && npm install",
|
||||
flag: "--verbose"
|
||||
flag: "--verbose",
|
||||
};
|
||||
|
||||
|
||||
// Mix of exact and glob matching
|
||||
expect(matchesArguments(args, {
|
||||
tool: "bash", // exact match
|
||||
command: "cd*install", // glob match
|
||||
flag: "--verbose" // exact match
|
||||
})).toBe(true);
|
||||
|
||||
expect(matchesArguments(args, {
|
||||
tool: "bash", // exact match
|
||||
command: "cd*test", // glob no match
|
||||
flag: "--verbose" // exact match
|
||||
})).toBe(false);
|
||||
expect(
|
||||
matchesArguments(args, {
|
||||
tool: "bash", // exact match
|
||||
command: "cd*install", // glob match
|
||||
flag: "--verbose", // exact match
|
||||
})
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
matchesArguments(args, {
|
||||
tool: "bash", // exact match
|
||||
command: "cd*test", // glob no match
|
||||
flag: "--verbose", // exact match
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should convert non-string values to strings for pattern matching", () => {
|
||||
const args = {
|
||||
const args = {
|
||||
port: 3000,
|
||||
enabled: true,
|
||||
count: null,
|
||||
items: [1, 2, 3]
|
||||
items: [1, 2, 3],
|
||||
};
|
||||
|
||||
|
||||
expect(matchesArguments(args, { port: "30*" })).toBe(true);
|
||||
expect(matchesArguments(args, { enabled: "tr*" })).toBe(true);
|
||||
expect(matchesArguments(args, { count: "*" })).toBe(true); // null -> ""
|
||||
expect(matchesArguments(args, { items: "*,*,*" })).toBe(true); // array toString
|
||||
|
||||
|
||||
expect(matchesArguments(args, { port: "40*" })).toBe(false);
|
||||
expect(matchesArguments(args, { enabled: "fa*" })).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle empty and undefined argument values", () => {
|
||||
const args = {
|
||||
const args = {
|
||||
empty: "",
|
||||
undef: undefined,
|
||||
zero: 0,
|
||||
false_val: false
|
||||
false_val: false,
|
||||
};
|
||||
|
||||
|
||||
expect(matchesArguments(args, { empty: "*" })).toBe(true);
|
||||
expect(matchesArguments(args, { undef: "*" })).toBe(true); // undefined -> ""
|
||||
expect(matchesArguments(args, { zero: "*" })).toBe(true); // 0 -> "0"
|
||||
expect(matchesArguments(args, { zero: "*" })).toBe(true); // 0 -> "0"
|
||||
expect(matchesArguments(args, { false_val: "*" })).toBe(true); // false -> "false"
|
||||
|
||||
|
||||
expect(matchesArguments(args, { empty: "nonempty*" })).toBe(false);
|
||||
expect(matchesArguments(args, { zero: "1*" })).toBe(false);
|
||||
});
|
||||
|
|
@ -393,11 +444,11 @@ describe("Permission Checker", () => {
|
|||
|
||||
it("should use default policies when no custom permissions provided", () => {
|
||||
const result = checkToolPermission({
|
||||
name: "read_file",
|
||||
name: "Read",
|
||||
arguments: { path: "/test.txt" },
|
||||
});
|
||||
|
||||
// Should match the default policies (read_file should be "allow")
|
||||
// Should match the default policies (Read should be "allow")
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
|
||||
|
|
@ -419,13 +470,13 @@ describe("Permission Checker", () => {
|
|||
policies: [
|
||||
{ tool: "Bash(ls*)", permission: "allow" },
|
||||
{ tool: "Bash(git*)", permission: "ask" },
|
||||
{ tool: "run_terminal_command", permission: "ask" }, // Fallback for other commands
|
||||
{ tool: "Bash", permission: "ask" }, // Fallback for other commands
|
||||
],
|
||||
};
|
||||
|
||||
// Should match "Bash(ls*)" pattern and allow
|
||||
const lsResult = checkToolPermission(
|
||||
{ name: "run_terminal_command", arguments: { command: "ls -la" } },
|
||||
{ name: "Bash", arguments: { command: "ls -la" } },
|
||||
permissions
|
||||
);
|
||||
expect(lsResult.permission).toBe("allow");
|
||||
|
|
@ -433,7 +484,7 @@ describe("Permission Checker", () => {
|
|||
|
||||
// Should match "Bash(git*)" pattern and ask
|
||||
const gitResult = checkToolPermission(
|
||||
{ name: "run_terminal_command", arguments: { command: "git status" } },
|
||||
{ name: "Bash", arguments: { command: "git status" } },
|
||||
permissions
|
||||
);
|
||||
expect(gitResult.permission).toBe("ask");
|
||||
|
|
@ -441,36 +492,36 @@ describe("Permission Checker", () => {
|
|||
|
||||
// Should match general fallback for other commands
|
||||
const npmResult = checkToolPermission(
|
||||
{ name: "run_terminal_command", arguments: { command: "npm install" } },
|
||||
{ name: "Bash", arguments: { command: "npm install" } },
|
||||
permissions
|
||||
);
|
||||
expect(npmResult.permission).toBe("ask");
|
||||
expect(npmResult.matchedPolicy?.tool).toBe("run_terminal_command");
|
||||
expect(npmResult.matchedPolicy?.tool).toBe("Bash");
|
||||
});
|
||||
|
||||
it("should match argument patterns with glob patterns", () => {
|
||||
const permissions: ToolPermissions = {
|
||||
policies: [
|
||||
{
|
||||
tool: "run_terminal_command",
|
||||
permission: "exclude",
|
||||
argumentMatches: { command: "rm*" }
|
||||
tool: "Bash",
|
||||
permission: "exclude",
|
||||
argumentMatches: { command: "rm*" },
|
||||
},
|
||||
{
|
||||
tool: "write_file",
|
||||
tool: "Write",
|
||||
permission: "ask",
|
||||
argumentMatches: { file_path: "**/*.ts" }
|
||||
argumentMatches: { file_path: "**/*.ts" },
|
||||
},
|
||||
{
|
||||
tool: "write_file",
|
||||
permission: "allow"
|
||||
}
|
||||
tool: "Write",
|
||||
permission: "allow",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Should exclude dangerous rm commands
|
||||
const rmResult = checkToolPermission(
|
||||
{ name: "run_terminal_command", arguments: { command: "rm -rf /" } },
|
||||
{ name: "Bash", arguments: { command: "rm -rf /" } },
|
||||
permissions
|
||||
);
|
||||
expect(rmResult.permission).toBe("exclude");
|
||||
|
|
@ -478,15 +529,20 @@ describe("Permission Checker", () => {
|
|||
|
||||
// Should ask for TypeScript files
|
||||
const tsResult = checkToolPermission(
|
||||
{ name: "write_file", arguments: { file_path: "/src/components/Button.ts" } },
|
||||
{
|
||||
name: "Write",
|
||||
arguments: { file_path: "/src/components/Button.ts" },
|
||||
},
|
||||
permissions
|
||||
);
|
||||
expect(tsResult.permission).toBe("ask");
|
||||
expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe("**/*.ts");
|
||||
expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe(
|
||||
"**/*.ts"
|
||||
);
|
||||
|
||||
// Should allow other file writes
|
||||
const jsResult = checkToolPermission(
|
||||
{ name: "write_file", arguments: { file_path: "/src/utils/helper.js" } },
|
||||
{ name: "Write", arguments: { file_path: "/src/utils/helper.js" } },
|
||||
permissions
|
||||
);
|
||||
expect(jsResult.permission).toBe("allow");
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { getServiceSync } from "../services/index.js";
|
||||
import { SERVICE_NAMES } from "../services/types.js";
|
||||
import type { ToolPermissionServiceState } from "../services/types.js";
|
||||
import { SERVICE_NAMES } from "../services/types.js";
|
||||
|
||||
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
||||
import {
|
||||
PermissionCheckResult,
|
||||
|
|
@ -14,8 +15,8 @@ import {
|
|||
* Also handles special Bash command patterns like "Bash(ls*)"
|
||||
*/
|
||||
export function matchesToolPattern(
|
||||
toolName: string,
|
||||
pattern: string,
|
||||
toolName: string,
|
||||
pattern: string,
|
||||
toolArguments?: Record<string, any>
|
||||
): boolean {
|
||||
if (pattern === "*") return true;
|
||||
|
|
@ -24,12 +25,12 @@ export function matchesToolPattern(
|
|||
// Handle special Bash command patterns like "Bash(ls*)"
|
||||
const bashCommandMatch = pattern.match(/^Bash\((.+)\)$/);
|
||||
if (bashCommandMatch) {
|
||||
// Check if this is a bash/terminal tool (either normalized name or display name)
|
||||
const isBashTool = toolName === "run_terminal_command" || toolName === "Bash";
|
||||
// Check if this is a bash/terminal tool
|
||||
const isBashTool = toolName === "Bash";
|
||||
if (isBashTool && toolArguments?.command) {
|
||||
const commandPattern = bashCommandMatch[1];
|
||||
const command = toolArguments.command;
|
||||
|
||||
|
||||
// Handle command patterns with wildcards
|
||||
if (commandPattern.includes("*") || commandPattern.includes("?")) {
|
||||
// Escape all regex metacharacters except * and ?
|
||||
|
|
@ -39,7 +40,7 @@ export function matchesToolPattern(
|
|||
const regex = new RegExp(`^${regexPattern}$`);
|
||||
return regex.test(command);
|
||||
}
|
||||
|
||||
|
||||
// Exact command match
|
||||
return command === commandPattern;
|
||||
}
|
||||
|
|
@ -75,16 +76,19 @@ export function matchesArguments(
|
|||
if (pattern === "*") continue; // Wildcard matches anything
|
||||
|
||||
// Handle glob patterns with wildcards (only for string patterns)
|
||||
if (typeof pattern === "string" && (pattern.includes("*") || pattern.includes("?"))) {
|
||||
if (
|
||||
typeof pattern === "string" &&
|
||||
(pattern.includes("*") || pattern.includes("?"))
|
||||
) {
|
||||
// Convert argValue to string for pattern matching
|
||||
const stringValue = String(argValue ?? "");
|
||||
|
||||
|
||||
// Escape all regex metacharacters except * and ?
|
||||
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
||||
// Convert * and ? to their regex equivalents
|
||||
const regexPattern = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
|
||||
const regex = new RegExp(`^${regexPattern}$`);
|
||||
|
||||
|
||||
if (!regex.test(stringValue)) {
|
||||
return false;
|
||||
}
|
||||
|
|
@ -109,18 +113,19 @@ export function checkToolPermission(
|
|||
): PermissionCheckResult {
|
||||
// Get permissions from service if not provided
|
||||
let policies = permissions?.policies;
|
||||
|
||||
|
||||
if (!policies) {
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS
|
||||
);
|
||||
|
||||
|
||||
// Only use defaults if service is not ready, not registered, or has no value
|
||||
// This allows critical runtime errors to propagate properly
|
||||
if (serviceResult.state !== 'ready' || !serviceResult.value) {
|
||||
if (serviceResult.state !== "ready" || !serviceResult.value) {
|
||||
policies = DEFAULT_TOOL_POLICIES;
|
||||
} else {
|
||||
policies = serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES;
|
||||
policies =
|
||||
serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,8 +15,14 @@ describe("ToolPermissionManager", () => {
|
|||
|
||||
describe("Request Management", () => {
|
||||
it("should generate unique request IDs", async () => {
|
||||
const toolCall1: ToolCallRequest = { name: "readFile", arguments: { path: "/test1.txt" } };
|
||||
const toolCall2: ToolCallRequest = { name: "readFile", arguments: { path: "/test2.txt" } };
|
||||
const toolCall1: ToolCallRequest = {
|
||||
name: "readFile",
|
||||
arguments: { path: "/test1.txt" },
|
||||
};
|
||||
const toolCall2: ToolCallRequest = {
|
||||
name: "readFile",
|
||||
arguments: { path: "/test2.txt" },
|
||||
};
|
||||
|
||||
// Start requests but don't await them
|
||||
const promise1 = manager.requestPermission(toolCall1);
|
||||
|
|
@ -33,13 +39,16 @@ describe("ToolPermissionManager", () => {
|
|||
});
|
||||
|
||||
it("should store pending request details correctly", async () => {
|
||||
const toolCall: ToolCallRequest = { name: "writeFile", arguments: { path: "/test.txt", content: "data" } };
|
||||
|
||||
const toolCall: ToolCallRequest = {
|
||||
name: "writeFile",
|
||||
arguments: { path: "/test.txt", content: "data" },
|
||||
};
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const pendingIds = manager.getPendingRequestIds();
|
||||
|
||||
|
||||
expect(pendingIds).toHaveLength(1);
|
||||
|
||||
|
||||
const requestDetails = manager.getPendingRequest(pendingIds[0]);
|
||||
expect(requestDetails).toBeDefined();
|
||||
expect(requestDetails?.toolCall).toEqual(toolCall);
|
||||
|
|
@ -50,17 +59,20 @@ describe("ToolPermissionManager", () => {
|
|||
});
|
||||
|
||||
it("should remove request after approval", async () => {
|
||||
const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } };
|
||||
|
||||
const toolCall: ToolCallRequest = {
|
||||
name: "readFile",
|
||||
arguments: { path: "/test.txt" },
|
||||
};
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const pendingIds = manager.getPendingRequestIds();
|
||||
const requestId = pendingIds[0];
|
||||
|
||||
|
||||
expect(manager.getPendingRequest(requestId)).toBeDefined();
|
||||
|
||||
|
||||
const approved = manager.approveRequest(requestId);
|
||||
expect(approved).toBe(true);
|
||||
|
||||
|
||||
const result = await promise;
|
||||
expect(result.approved).toBe(true);
|
||||
expect(manager.getPendingRequest(requestId)).toBeUndefined();
|
||||
|
|
@ -68,15 +80,18 @@ describe("ToolPermissionManager", () => {
|
|||
});
|
||||
|
||||
it("should remove request after rejection", async () => {
|
||||
const toolCall: ToolCallRequest = { name: "runTerminalCommand", arguments: { command: "rm -rf /" } };
|
||||
|
||||
const toolCall: ToolCallRequest = {
|
||||
name: "runTerminalCommand",
|
||||
arguments: { command: "rm -rf /" },
|
||||
};
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const pendingIds = manager.getPendingRequestIds();
|
||||
const requestId = pendingIds[0];
|
||||
|
||||
|
||||
const rejected = manager.rejectRequest(requestId);
|
||||
expect(rejected).toBe(true);
|
||||
|
||||
|
||||
const result = await promise;
|
||||
expect(result.approved).toBe(false);
|
||||
expect(manager.getPendingRequest(requestId)).toBeUndefined();
|
||||
|
|
@ -93,13 +108,16 @@ describe("ToolPermissionManager", () => {
|
|||
});
|
||||
|
||||
it("should support remember option for approval", async () => {
|
||||
const toolCall: ToolCallRequest = { name: "writeFile", arguments: { path: "/test.txt" } };
|
||||
|
||||
const toolCall: ToolCallRequest = {
|
||||
name: "writeFile",
|
||||
arguments: { path: "/test.txt" },
|
||||
};
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const requestId = manager.getPendingRequestIds()[0];
|
||||
|
||||
|
||||
manager.approveRequest(requestId, true); // Remember = true
|
||||
|
||||
|
||||
const result = await promise;
|
||||
expect(result.approved).toBe(true);
|
||||
expect(result.remember).toBe(true);
|
||||
|
|
@ -107,54 +125,71 @@ describe("ToolPermissionManager", () => {
|
|||
});
|
||||
|
||||
describe("Event Emission", () => {
|
||||
it("should emit permissionRequested event", (done) => {
|
||||
const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } };
|
||||
|
||||
manager.on("permissionRequested", (event) => {
|
||||
expect(event.requestId).toBeDefined();
|
||||
expect(event.toolCall).toEqual(toolCall);
|
||||
done();
|
||||
it("should emit permissionRequested event", () => {
|
||||
const toolCall: ToolCallRequest = {
|
||||
name: "readFile",
|
||||
arguments: { path: "/test.txt" },
|
||||
};
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
manager.on("permissionRequested", (event) => {
|
||||
expect(event.requestId).toBeDefined();
|
||||
expect(event.toolCall).toEqual(toolCall);
|
||||
resolve();
|
||||
});
|
||||
|
||||
manager.requestPermission(toolCall);
|
||||
});
|
||||
|
||||
manager.requestPermission(toolCall);
|
||||
});
|
||||
|
||||
it("should emit permissionResponse event on approval", (done) => {
|
||||
const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } };
|
||||
|
||||
manager.on("permissionResponse", (event) => {
|
||||
expect(event.approved).toBe(true);
|
||||
expect(event.requestId).toBeDefined();
|
||||
done();
|
||||
it("should emit permissionResponse event on approval", () => {
|
||||
const toolCall: ToolCallRequest = {
|
||||
name: "readFile",
|
||||
arguments: { path: "/test.txt" },
|
||||
};
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
manager.on("permissionResponse", (event) => {
|
||||
expect(event.approved).toBe(true);
|
||||
expect(event.requestId).toBeDefined();
|
||||
resolve();
|
||||
});
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const requestId = manager.getPendingRequestIds()[0];
|
||||
manager.approveRequest(requestId);
|
||||
});
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const requestId = manager.getPendingRequestIds()[0];
|
||||
manager.approveRequest(requestId);
|
||||
});
|
||||
|
||||
it("should emit permissionResponse event on rejection", (done) => {
|
||||
const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } };
|
||||
|
||||
manager.on("permissionResponse", (event) => {
|
||||
expect(event.approved).toBe(false);
|
||||
expect(event.requestId).toBeDefined();
|
||||
done();
|
||||
it("should emit permissionResponse event on rejection", () => {
|
||||
const toolCall: ToolCallRequest = {
|
||||
name: "readFile",
|
||||
arguments: { path: "/test.txt" },
|
||||
};
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
manager.on("permissionResponse", (event) => {
|
||||
expect(event.approved).toBe(false);
|
||||
expect(event.requestId).toBeDefined();
|
||||
resolve();
|
||||
});
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const requestId = manager.getPendingRequestIds()[0];
|
||||
manager.rejectRequest(requestId);
|
||||
});
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const requestId = manager.getPendingRequestIds()[0];
|
||||
manager.rejectRequest(requestId);
|
||||
});
|
||||
|
||||
it("should emit permissionResponse even for non-existent requests", (done) => {
|
||||
manager.on("permissionResponse", (event) => {
|
||||
expect(event.approved).toBe(true);
|
||||
expect(event.requestId).toBe("fake-id");
|
||||
done();
|
||||
it("should emit permissionResponse even for non-existent requests", () => {
|
||||
return new Promise<void>((resolve) => {
|
||||
manager.on("permissionResponse", (event) => {
|
||||
expect(event.approved).toBe(true);
|
||||
expect(event.requestId).toBe("fake-id");
|
||||
resolve();
|
||||
});
|
||||
|
||||
manager.approveRequest("fake-id");
|
||||
});
|
||||
|
||||
manager.approveRequest("fake-id");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -162,13 +197,18 @@ describe("ToolPermissionManager", () => {
|
|||
it("should handle multiple concurrent requests", async () => {
|
||||
const toolCalls = [
|
||||
{ name: "readFile", arguments: { path: "/file1.txt" } },
|
||||
{ name: "writeFile", arguments: { path: "/file2.txt", content: "data1" } },
|
||||
{
|
||||
name: "writeFile",
|
||||
arguments: { path: "/file2.txt", content: "data1" },
|
||||
},
|
||||
{ name: "runTerminalCommand", arguments: { command: "ls" } },
|
||||
];
|
||||
|
||||
// Start all requests
|
||||
const promises = toolCalls.map(toolCall => manager.requestPermission(toolCall));
|
||||
|
||||
const promises = toolCalls.map((toolCall) =>
|
||||
manager.requestPermission(toolCall)
|
||||
);
|
||||
|
||||
// Get all pending request IDs
|
||||
const pendingIds = manager.getPendingRequestIds();
|
||||
expect(pendingIds).toHaveLength(3);
|
||||
|
|
@ -180,11 +220,11 @@ describe("ToolPermissionManager", () => {
|
|||
|
||||
// Wait for all to complete
|
||||
const results = await Promise.all(promises);
|
||||
|
||||
|
||||
expect(results[0].approved).toBe(true);
|
||||
expect(results[1].approved).toBe(false);
|
||||
expect(results[2].approved).toBe(true);
|
||||
|
||||
|
||||
// All requests should be cleared
|
||||
expect(manager.getPendingRequestIds()).toHaveLength(0);
|
||||
});
|
||||
|
|
@ -193,13 +233,13 @@ describe("ToolPermissionManager", () => {
|
|||
describe("Edge Cases", () => {
|
||||
it("should handle empty tool call arguments", async () => {
|
||||
const toolCall: ToolCallRequest = { name: "exit", arguments: {} };
|
||||
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const requestId = manager.getPendingRequestIds()[0];
|
||||
|
||||
|
||||
manager.approveRequest(requestId);
|
||||
const result = await promise;
|
||||
|
||||
|
||||
expect(result.approved).toBe(true);
|
||||
});
|
||||
|
||||
|
|
@ -209,17 +249,19 @@ describe("ToolPermissionManager", () => {
|
|||
arguments: {
|
||||
config: { host: "localhost", port: 3000 },
|
||||
options: ["verbose", "debug"],
|
||||
metadata: { created: new Date(), version: "1.0.0" }
|
||||
}
|
||||
metadata: { created: new Date(), version: "1.0.0" },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const requestDetails = manager.getPendingRequest(manager.getPendingRequestIds()[0]);
|
||||
|
||||
const requestDetails = manager.getPendingRequest(
|
||||
manager.getPendingRequestIds()[0]
|
||||
);
|
||||
|
||||
expect(requestDetails?.toolCall.arguments).toEqual(toolCall.arguments);
|
||||
|
||||
|
||||
manager.approveRequest(manager.getPendingRequestIds()[0]);
|
||||
await promise;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { EventEmitter } from "events";
|
||||
|
||||
import { ToolCallRequest } from "./types.js";
|
||||
|
||||
export interface PermissionRequestResult {
|
||||
|
|
|
|||
|
|
@ -12,24 +12,24 @@ describe("permissionsYamlLoader", () => {
|
|||
const policies = yamlConfigToPolicies(config);
|
||||
|
||||
expect(policies).toEqual([
|
||||
{ tool: "run_terminal_command", permission: "exclude" },
|
||||
{ tool: "write_file", permission: "ask" },
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "list_files", permission: "allow" },
|
||||
{ tool: "Bash", permission: "exclude" },
|
||||
{ tool: "Write", permission: "ask" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "List", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should normalize tool names", () => {
|
||||
const config = {
|
||||
allow: ["read", "READ", "read_file"],
|
||||
allow: ["read", "READ", "Read"],
|
||||
};
|
||||
|
||||
const policies = yamlConfigToPolicies(config);
|
||||
|
||||
expect(policies).toEqual([
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
|
||||
|
|
@ -63,7 +63,7 @@ describe("permissionsYamlLoader", () => {
|
|||
|
||||
const policies = yamlConfigToPolicies(config);
|
||||
|
||||
expect(policies).toEqual([{ tool: "read_file", permission: "allow" }]);
|
||||
expect(policies).toEqual([{ tool: "Read", permission: "allow" }]);
|
||||
});
|
||||
|
||||
it("should handle all permission types", () => {
|
||||
|
|
@ -76,12 +76,12 @@ describe("permissionsYamlLoader", () => {
|
|||
const policies = yamlConfigToPolicies(config);
|
||||
|
||||
expect(policies).toEqual([
|
||||
{ tool: "fetch", permission: "exclude" },
|
||||
{ tool: "exit", permission: "exclude" },
|
||||
{ tool: "write_file", permission: "ask" },
|
||||
{ tool: "run_terminal_command", permission: "ask" },
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "list_files", permission: "allow" },
|
||||
{ tool: "Fetch", permission: "exclude" },
|
||||
{ tool: "Exit", permission: "exclude" },
|
||||
{ tool: "Write", permission: "ask" },
|
||||
{ tool: "Bash", permission: "ask" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "List", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
@ -91,7 +91,7 @@ describe("permissionsYamlLoader", () => {
|
|||
const policy = parseToolPattern("Write", "allow");
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "write_file",
|
||||
tool: "Write",
|
||||
permission: "allow"
|
||||
});
|
||||
});
|
||||
|
|
@ -100,7 +100,7 @@ describe("permissionsYamlLoader", () => {
|
|||
const policy = parseToolPattern("Write(**/*.ts)", "exclude");
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "write_file",
|
||||
tool: "Write",
|
||||
permission: "exclude",
|
||||
argumentMatches: {
|
||||
file_path: "**/*.ts"
|
||||
|
|
@ -112,7 +112,7 @@ describe("permissionsYamlLoader", () => {
|
|||
const policy = parseToolPattern("Bash(npm install)", "ask");
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "run_terminal_command",
|
||||
tool: "Bash",
|
||||
permission: "ask",
|
||||
argumentMatches: {
|
||||
command: "npm install"
|
||||
|
|
@ -124,19 +124,19 @@ describe("permissionsYamlLoader", () => {
|
|||
const testCases = [
|
||||
{
|
||||
pattern: "Read(src/**/*.js)",
|
||||
expected: { tool: "read_file", permission: "allow", argumentMatches: { file_path: "src/**/*.js" } }
|
||||
expected: { tool: "Read", permission: "allow", argumentMatches: { file_path: "src/**/*.js" } }
|
||||
},
|
||||
{
|
||||
pattern: "List(/home/user)",
|
||||
expected: { tool: "list_files", permission: "allow", argumentMatches: { path: "/home/user" } }
|
||||
expected: { tool: "List", permission: "allow", argumentMatches: { path: "/home/user" } }
|
||||
},
|
||||
{
|
||||
pattern: "Search(TODO)",
|
||||
expected: { tool: "search_code", permission: "allow", argumentMatches: { query: "TODO" } }
|
||||
expected: { tool: "Search", permission: "allow", argumentMatches: { query: "TODO" } }
|
||||
},
|
||||
{
|
||||
pattern: "Fetch(https://api.example.com)",
|
||||
expected: { tool: "fetch", permission: "allow", argumentMatches: { url: "https://api.example.com" } }
|
||||
expected: { tool: "Fetch", permission: "allow", argumentMatches: { url: "https://api.example.com" } }
|
||||
}
|
||||
];
|
||||
|
||||
|
|
@ -150,7 +150,7 @@ describe("permissionsYamlLoader", () => {
|
|||
const policy = parseToolPattern("Write()", "allow");
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "write_file",
|
||||
tool: "Write",
|
||||
permission: "allow"
|
||||
});
|
||||
});
|
||||
|
|
@ -159,7 +159,7 @@ describe("permissionsYamlLoader", () => {
|
|||
const policy = parseToolPattern("Bash( npm run test )", "ask");
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "run_terminal_command",
|
||||
tool: "Bash",
|
||||
permission: "ask",
|
||||
argumentMatches: {
|
||||
command: "npm run test"
|
||||
|
|
@ -187,7 +187,7 @@ describe("permissionsYamlLoader", () => {
|
|||
const policy = parseToolPattern("write(**/*.ts)", "allow");
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "write_file",
|
||||
tool: "Write",
|
||||
permission: "allow",
|
||||
argumentMatches: {
|
||||
file_path: "**/*.ts"
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import * as yaml from "yaml";
|
||||
import logger from "../util/logger.js";
|
||||
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { normalizeToolName } from "./toolNameMapping.js";
|
||||
import { PermissionPolicy, ToolPermissionPolicy } from "./types.js";
|
||||
|
||||
|
|
@ -70,9 +73,9 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null {
|
|||
/**
|
||||
* Parses a pattern string into a ToolPermissionPolicy
|
||||
* Supports formats like:
|
||||
* - "Write" -> { tool: "write_file", permission }
|
||||
* - "Write(pattern)" -> { tool: "write_file", permission, argumentMatches: { file_path: "pattern" } }
|
||||
* - "Bash(npm install)" -> { tool: "run_terminal_command", permission, argumentMatches: { command: "npm install" } }
|
||||
* - "Write" -> { tool: "Write", permission }
|
||||
* - "Write(pattern)" -> { tool: "Write", permission, argumentMatches: { file_path: "pattern" } }
|
||||
* - "Bash(npm install)" -> { tool: "Bash", permission, argumentMatches: { command: "npm install" } }
|
||||
*/
|
||||
export function parseToolPattern(
|
||||
pattern: string,
|
||||
|
|
@ -96,14 +99,14 @@ export function parseToolPattern(
|
|||
if (trimmedArgs) {
|
||||
// Map tool names to their primary argument parameter
|
||||
const toolArgMappings: Record<string, string> = {
|
||||
write_file: "file_path",
|
||||
edit_file: "file_path",
|
||||
read_file: "file_path",
|
||||
list_files: "path",
|
||||
search_code: "query",
|
||||
run_terminal_command: "command",
|
||||
fetch: "url",
|
||||
view_diff: "file_path",
|
||||
Write: "file_path",
|
||||
Edit: "file_path",
|
||||
Read: "file_path",
|
||||
List: "path",
|
||||
Search: "query",
|
||||
Bash: "command",
|
||||
Fetch: "url",
|
||||
Diff: "file_path",
|
||||
};
|
||||
|
||||
const argKey = toolArgMappings[normalizedName] || "pattern";
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import * as yaml from "yaml";
|
||||
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { PERMISSIONS_YAML_PATH, PermissionsYamlConfig, loadPermissionsYaml } from "./permissionsYamlLoader.js";
|
||||
import { normalizeToolName, getDisplayName } from "./toolNameMapping.js";
|
||||
import logger from "../util/logger.js";
|
||||
|
||||
/**
|
||||
* Generates a policy rule for a given tool call
|
||||
|
|
@ -12,8 +15,8 @@ import logger from "../util/logger.js";
|
|||
export function generatePolicyRule(toolName: string, toolArgs: any): string {
|
||||
const normalizedName = normalizeToolName(toolName);
|
||||
|
||||
// For Bash tool (run_terminal_command), create command-specific policies
|
||||
if (normalizedName === "run_terminal_command" && toolArgs?.command) {
|
||||
// For Bash tool, create command-specific policies
|
||||
if (normalizedName === "Bash" && toolArgs?.command) {
|
||||
const command = toolArgs.command.trim();
|
||||
// Extract the first command (before pipes, &&, ||, etc.)
|
||||
const firstCommand = command.split(/[;&|]|&&|\|\|/)[0]?.trim();
|
||||
|
|
@ -34,7 +37,7 @@ export function generatePolicyRule(toolName: string, toolArgs: any): string {
|
|||
export async function addPolicyToYaml(policyRule: string): Promise<void> {
|
||||
try {
|
||||
// Load existing config or create empty one
|
||||
let config: PermissionsYamlConfig = loadPermissionsYaml() || {};
|
||||
const config: PermissionsYamlConfig = loadPermissionsYaml() || {};
|
||||
|
||||
// Ensure allow array exists
|
||||
if (!config.allow) {
|
||||
|
|
|
|||
23
src/permissions/policyWriter.verify.test.ts
Normal file
23
src/permissions/policyWriter.verify.test.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { generatePolicyRule } from "./policyWriter.js";
|
||||
|
||||
describe("policyWriter verification", () => {
|
||||
it("should return display names for all tools", () => {
|
||||
// Test Edit tool
|
||||
expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit");
|
||||
|
||||
// Test Write tool
|
||||
expect(generatePolicyRule("Write", { filepath: "test.txt" })).toBe("Write");
|
||||
|
||||
// Test Read tool
|
||||
expect(generatePolicyRule("Read", { filepath: "test.txt" })).toBe("Read");
|
||||
|
||||
// Test Bash tool with commands
|
||||
expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe("Bash(ls*)");
|
||||
});
|
||||
|
||||
it("should handle mixed case tool names", () => {
|
||||
expect(generatePolicyRule("edit", { filepath: "test.txt" })).toBe("Edit");
|
||||
expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("Edit");
|
||||
expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit");
|
||||
});
|
||||
});
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
||||
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
|
||||
import { ToolPermissionPolicy } from "./types.js";
|
||||
|
|
@ -17,16 +16,16 @@ describe("precedenceResolver", () => {
|
|||
it("should prioritize command line flags over defaults", () => {
|
||||
const policies = resolvePermissionPrecedence({
|
||||
commandLineFlags: {
|
||||
exclude: ["read_file"],
|
||||
allow: ["write_file"],
|
||||
exclude: ["Read"],
|
||||
allow: ["Write"],
|
||||
},
|
||||
personalSettings: false,
|
||||
useDefaults: true,
|
||||
});
|
||||
|
||||
// Command line flags should come first
|
||||
expect(policies[0]).toEqual({ tool: "read_file", permission: "exclude" });
|
||||
expect(policies[1]).toEqual({ tool: "write_file", permission: "allow" });
|
||||
expect(policies[0]).toEqual({ tool: "Read", permission: "exclude" });
|
||||
expect(policies[1]).toEqual({ tool: "Write", permission: "allow" });
|
||||
});
|
||||
|
||||
it("should handle wildcard patterns", () => {
|
||||
|
|
@ -55,9 +54,9 @@ describe("precedenceResolver", () => {
|
|||
});
|
||||
|
||||
expect(policies).toEqual([
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "write_file", permission: "allow" },
|
||||
{ tool: "run_terminal_command", permission: "allow" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "Write", permission: "allow" },
|
||||
{ tool: "Bash", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
|
||||
|
|
@ -84,24 +83,24 @@ describe("precedenceResolver", () => {
|
|||
|
||||
// Order should be: exclude, ask, allow (as specified in the function)
|
||||
expect(policies).toEqual([
|
||||
{ tool: "write_file", permission: "exclude" },
|
||||
{ tool: "run_terminal_command", permission: "exclude" },
|
||||
{ tool: "list_files", permission: "ask" },
|
||||
{ tool: "search_code", permission: "ask" },
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "fetch", permission: "allow" },
|
||||
{ tool: "Write", permission: "exclude" },
|
||||
{ tool: "Bash", permission: "exclude" },
|
||||
{ tool: "List", permission: "ask" },
|
||||
{ tool: "Search", permission: "ask" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "Fetch", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should apply config permissions with proper precedence", () => {
|
||||
const configPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: "write_file", permission: "allow" },
|
||||
{ tool: "read_file", permission: "ask" },
|
||||
{ tool: "Write", permission: "allow" },
|
||||
{ tool: "Read", permission: "ask" },
|
||||
];
|
||||
|
||||
const policies = resolvePermissionPrecedence({
|
||||
commandLineFlags: {
|
||||
exclude: ["read_file"], // Should override config
|
||||
exclude: ["Read"], // Should override config
|
||||
},
|
||||
configPermissions: configPolicies,
|
||||
personalSettings: false,
|
||||
|
|
@ -109,14 +108,14 @@ describe("precedenceResolver", () => {
|
|||
});
|
||||
|
||||
// CLI flag should override config
|
||||
expect(policies[0]).toEqual({ tool: "read_file", permission: "exclude" });
|
||||
expect(policies[0]).toEqual({ tool: "Read", permission: "exclude" });
|
||||
// Config policy should be present
|
||||
expect(policies[1]).toEqual({ tool: "write_file", permission: "allow" });
|
||||
expect(policies[1]).toEqual({ tool: "Write", permission: "allow" });
|
||||
});
|
||||
|
||||
it("should handle all layers with proper precedence", () => {
|
||||
const configPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: "search_code", permission: "ask" },
|
||||
{ tool: "Search", permission: "ask" },
|
||||
];
|
||||
|
||||
const policies = resolvePermissionPrecedence({
|
||||
|
|
@ -128,16 +127,16 @@ describe("precedenceResolver", () => {
|
|||
useDefaults: true,
|
||||
});
|
||||
|
||||
// Find the write_file policy - should be from CLI (allow)
|
||||
const writePolicy = policies.find(p => p.tool === "write_file");
|
||||
// Find the Write policy - should be from CLI (allow)
|
||||
const writePolicy = policies.find(p => p.tool === "Write");
|
||||
expect(writePolicy?.permission).toBe("allow");
|
||||
|
||||
// Find the search_code policy - should be from config
|
||||
const searchPolicy = policies.find(p => p.tool === "search_code");
|
||||
// Find the Search policy - should be from config
|
||||
const searchPolicy = policies.find(p => p.tool === "Search");
|
||||
expect(searchPolicy?.permission).toBe("ask");
|
||||
|
||||
// Should still have default policies
|
||||
const readPolicy = policies.find(p => p.tool === "read_file");
|
||||
const readPolicy = policies.find(p => p.tool === "Read");
|
||||
expect(readPolicy).toBeDefined();
|
||||
});
|
||||
|
||||
|
|
@ -154,21 +153,21 @@ describe("precedenceResolver", () => {
|
|||
it("should allow CLI flags to override default policies", () => {
|
||||
const policies = resolvePermissionPrecedence({
|
||||
commandLineFlags: {
|
||||
exclude: ["write_file"],
|
||||
exclude: ["Write"],
|
||||
},
|
||||
useDefaults: true,
|
||||
personalSettings: false,
|
||||
});
|
||||
|
||||
// CLI exclusion should come first
|
||||
expect(policies[0]).toEqual({ tool: "write_file", permission: "exclude" });
|
||||
expect(policies[0]).toEqual({ tool: "Write", permission: "exclude" });
|
||||
// Default policies should follow
|
||||
expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
|
||||
it("should allow config policies to override defaults", () => {
|
||||
const configPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: "run_terminal_command", permission: "allow" },
|
||||
{ tool: "Bash", permission: "allow" },
|
||||
];
|
||||
|
||||
const policies = resolvePermissionPrecedence({
|
||||
|
|
@ -178,7 +177,7 @@ describe("precedenceResolver", () => {
|
|||
});
|
||||
|
||||
// Config policy should override default
|
||||
expect(policies[0]).toEqual({ tool: "run_terminal_command", permission: "allow" });
|
||||
expect(policies[0]).toEqual({ tool: "Bash", permission: "allow" });
|
||||
// Default policies should follow
|
||||
expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
||||
import { loadPermissionsYaml, yamlConfigToPolicies } from "./permissionsYamlLoader.js";
|
||||
import { normalizeToolName } from "./toolNameMapping.js";
|
||||
import { ToolPermissionPolicy } from "./types.js";
|
||||
import logger from "../util/logger.js";
|
||||
|
||||
export interface PermissionSources {
|
||||
/** Command line flags - highest precedence */
|
||||
|
|
|
|||
|
|
@ -1,48 +1,38 @@
|
|||
/**
|
||||
* Maps common display names and variations to actual tool names
|
||||
* Maps common variations to standardized tool names
|
||||
*/
|
||||
const TOOL_NAME_MAPPINGS: Record<string, string> = {
|
||||
// Display name mappings
|
||||
Read: "read_file",
|
||||
Write: "write_file",
|
||||
List: "list_files",
|
||||
Search: "search_code",
|
||||
Bash: "run_terminal_command",
|
||||
Terminal: "run_terminal_command",
|
||||
Fetch: "fetch",
|
||||
Exit: "exit",
|
||||
Diff: "view_diff",
|
||||
Edit: "edit_file",
|
||||
Checklist: "write_checklist",
|
||||
// Standard tool names (passthrough)
|
||||
Read: "Read",
|
||||
Write: "Write",
|
||||
List: "List",
|
||||
Search: "Search",
|
||||
Bash: "Bash",
|
||||
Fetch: "Fetch",
|
||||
Exit: "Exit",
|
||||
Diff: "Diff",
|
||||
Edit: "Edit",
|
||||
Checklist: "Checklist",
|
||||
|
||||
// Common variations (case insensitive)
|
||||
read: "read_file",
|
||||
write: "write_file",
|
||||
list: "list_files",
|
||||
search: "search_code",
|
||||
bash: "run_terminal_command",
|
||||
terminal: "run_terminal_command",
|
||||
cmd: "run_terminal_command",
|
||||
command: "run_terminal_command",
|
||||
fetch: "fetch",
|
||||
exit: "exit",
|
||||
diff: "view_diff",
|
||||
edit: "edit_file",
|
||||
checklist: "write_checklist",
|
||||
|
||||
// Actual tool names (passthrough)
|
||||
read_file: "read_file",
|
||||
write_file: "write_file",
|
||||
list_files: "list_files",
|
||||
search_code: "search_code",
|
||||
run_terminal_command: "run_terminal_command",
|
||||
view_diff: "view_diff",
|
||||
edit_file: "edit_file",
|
||||
write_checklist: "write_checklist",
|
||||
read: "Read",
|
||||
write: "Write",
|
||||
list: "List",
|
||||
search: "Search",
|
||||
bash: "Bash",
|
||||
terminal: "Bash",
|
||||
Terminal: "Bash",
|
||||
cmd: "Bash",
|
||||
command: "Bash",
|
||||
fetch: "Fetch",
|
||||
exit: "Exit",
|
||||
diff: "Diff",
|
||||
edit: "Edit",
|
||||
checklist: "Checklist",
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes a tool name from various formats (display name, variations) to the actual tool name
|
||||
* Normalizes a tool name from various formats (variations, legacy names) to the standardized tool name
|
||||
*/
|
||||
export function normalizeToolName(input: string): string {
|
||||
// First try exact match (case sensitive)
|
||||
|
|
@ -63,22 +53,11 @@ export function normalizeToolName(input: string): string {
|
|||
}
|
||||
|
||||
/**
|
||||
* Gets the display name for a normalized tool name
|
||||
* Returns the preferred display name (e.g., "read_file" -> "Read")
|
||||
* Gets the display name for a tool name
|
||||
* Since we now use display names as the primary names, this mostly returns the input
|
||||
* but handles any remaining edge cases
|
||||
*/
|
||||
export function getDisplayName(normalizedName: string): string {
|
||||
// Create a reverse mapping from normalized names to display names
|
||||
const reverseMapping: Record<string, string> = {
|
||||
read_file: "Read",
|
||||
write_file: "Write",
|
||||
list_files: "List",
|
||||
search_code: "Search",
|
||||
run_terminal_command: "Bash",
|
||||
fetch: "Fetch",
|
||||
exit: "Exit",
|
||||
view_diff: "Diff",
|
||||
write_checklist: "Checklist",
|
||||
};
|
||||
|
||||
return reverseMapping[normalizedName] || normalizedName;
|
||||
export function getDisplayName(toolName: string): string {
|
||||
// Simply normalize and return - the tool name is already the display name
|
||||
return normalizeToolName(toolName);
|
||||
}
|
||||
|
|
|
|||
81
src/permissions/yamlPermissions.test.ts
Normal file
81
src/permissions/yamlPermissions.test.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
|
||||
import { checkToolPermission } from './permissionChecker.js';
|
||||
import { yamlConfigToPolicies } from './permissionsYamlLoader.js';
|
||||
|
||||
// Mock fs module
|
||||
vi.mock('fs');
|
||||
|
||||
describe('YAML Permissions - Edit Tool Bug', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should allow Edit tool when it is in the allow list', () => {
|
||||
// Test the exact YAML content from the user
|
||||
const yamlContent = `allow:
|
||||
- Edit
|
||||
ask: []
|
||||
exclude: []`;
|
||||
|
||||
// Parse the YAML config
|
||||
const config = {
|
||||
allow: ['Edit'],
|
||||
ask: [],
|
||||
exclude: []
|
||||
};
|
||||
|
||||
// Convert to policies
|
||||
const policies = yamlConfigToPolicies(config);
|
||||
console.log('Converted policies:', policies);
|
||||
|
||||
// The policies should have Edit as allowed
|
||||
expect(policies).toEqual([
|
||||
{ tool: 'Edit', permission: 'allow' }
|
||||
]);
|
||||
|
||||
// Test permission check with tool call named "Edit"
|
||||
const toolCall1 = {
|
||||
name: 'Edit',
|
||||
arguments: { filepath: 'test.txt' }
|
||||
};
|
||||
const result1 = checkToolPermission(toolCall1, { policies });
|
||||
console.log('Permission check for "Edit":', result1);
|
||||
expect(result1.permission).toBe('allow');
|
||||
|
||||
// Legacy names should NOT work anymore
|
||||
const toolCall2 = {
|
||||
name: 'search_and_replace_in_file',
|
||||
arguments: { filepath: 'test.txt' }
|
||||
};
|
||||
const result2 = checkToolPermission(toolCall2, { policies });
|
||||
console.log('Permission check for "search_and_replace_in_file":', result2);
|
||||
expect(result2.permission).toBe('ask'); // Should not match, falls back to ask
|
||||
|
||||
// Legacy names should NOT work anymore
|
||||
const toolCall3 = {
|
||||
name: 'edit_file',
|
||||
arguments: { filepath: 'test.txt' }
|
||||
};
|
||||
const result3 = checkToolPermission(toolCall3, { policies });
|
||||
console.log('Permission check for "edit_file":', result3);
|
||||
expect(result3.permission).toBe('ask'); // Should not match, falls back to ask
|
||||
});
|
||||
|
||||
it('should check what normalizeToolName returns for Edit variations', async () => {
|
||||
const { normalizeToolName } = await import('./toolNameMapping.js');
|
||||
|
||||
console.log('normalizeToolName("Edit"):', normalizeToolName("Edit"));
|
||||
console.log('normalizeToolName("edit"):', normalizeToolName("edit"));
|
||||
console.log('normalizeToolName("edit_file"):', normalizeToolName("edit_file"));
|
||||
console.log('normalizeToolName("search_and_replace_in_file"):', normalizeToolName("search_and_replace_in_file"));
|
||||
|
||||
// Only proper names and case variations should normalize
|
||||
expect(normalizeToolName("Edit")).toBe("Edit");
|
||||
expect(normalizeToolName("edit")).toBe("Edit");
|
||||
|
||||
// Legacy snake_case names should not normalize anymore
|
||||
expect(normalizeToolName("edit_file")).toBe("edit_file");
|
||||
expect(normalizeToolName("search_and_replace_in_file")).toBe("search_and_replace_in_file");
|
||||
});
|
||||
});
|
||||
133
src/services/ApiClientService.test.ts
Normal file
133
src/services/ApiClientService.test.ts
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
|
||||
// Mock the config module
|
||||
vi.mock('../config.js');
|
||||
import * as config from '../config.js';
|
||||
|
||||
import { ApiClientService } from './ApiClientService.js';
|
||||
|
||||
describe('ApiClientService', () => {
|
||||
let service: ApiClientService;
|
||||
const mockApiClient = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
service = new ApiClientService();
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
test('should initialize with null api client', async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
|
||||
const state = await service.initialize({ accessToken: null } as any);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: null
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with api client when token provided', async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
|
||||
const state = await service.initialize({ accessToken: 'test-token' } as any);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: mockApiClient
|
||||
});
|
||||
expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith('test-token');
|
||||
});
|
||||
});
|
||||
|
||||
describe('update()', () => {
|
||||
test('should update api client with new auth config', async () => {
|
||||
// Initialize first
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
// Update with new token
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
const state = await service.update({ accessToken: 'new-token' } as any);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: mockApiClient
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
||||
test('should handle update errors', async () => {
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
vi.mocked(config.getApiClient).mockImplementation(() => {
|
||||
throw new Error('Failed to create client');
|
||||
});
|
||||
|
||||
await expect(service.update({ accessToken: 'bad-token' } as any)).rejects.toThrow(
|
||||
'Failed to create client'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isReady()', () => {
|
||||
test('should return false when not initialized', () => {
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test('should return false when api client is null', async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test('should return true when api client exists', async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.initialize({ accessToken: 'token' } as any);
|
||||
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDependencies()', () => {
|
||||
test('should declare auth dependency', () => {
|
||||
expect(service.getDependencies()).toEqual(['auth']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
test('should emit stateChanged on update', async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.update({ accessToken: 'new-token' } as any);
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ apiClient: mockApiClient }),
|
||||
expect.objectContaining({ apiClient: null })
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit error on update failure', async () => {
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
const errorListener = vi.fn();
|
||||
service.on('error', errorListener);
|
||||
|
||||
const error = new Error('Update failed');
|
||||
vi.mocked(config.getApiClient).mockImplementation(() => {
|
||||
throw error;
|
||||
});
|
||||
|
||||
await expect(service.update({ accessToken: 'bad' } as any)).rejects.toThrow();
|
||||
expect(errorListener).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,43 +1,37 @@
|
|||
import { AuthConfig } from "../auth/workos.js";
|
||||
import { getApiClient } from "../config.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
import { ApiClientServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Service for managing API client state
|
||||
* Provides access to the Continue SDK API client
|
||||
*/
|
||||
export class ApiClientService {
|
||||
private currentState: ApiClientServiceState = {
|
||||
apiClient: null,
|
||||
};
|
||||
export class ApiClientService extends BaseService<ApiClientServiceState> implements ServiceWithDependencies {
|
||||
constructor() {
|
||||
super('ApiClientService', {
|
||||
apiClient: null,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare dependencies on other services
|
||||
*/
|
||||
getDependencies(): string[] {
|
||||
return ['auth'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the API client service
|
||||
*/
|
||||
async initialize(authConfig: AuthConfig): Promise<ApiClientServiceState> {
|
||||
logger.debug("Initializing ApiClientService");
|
||||
async doInitialize(authConfig: AuthConfig): Promise<ApiClientServiceState> {
|
||||
const apiClient = getApiClient(authConfig?.accessToken);
|
||||
|
||||
try {
|
||||
const apiClient = getApiClient(authConfig?.accessToken);
|
||||
|
||||
this.currentState = {
|
||||
apiClient,
|
||||
};
|
||||
|
||||
logger.debug("ApiClientService initialized successfully");
|
||||
return this.currentState;
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to initialize ApiClientService:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current API client state
|
||||
*/
|
||||
getState(): ApiClientServiceState {
|
||||
return { ...this.currentState };
|
||||
return {
|
||||
apiClient,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -49,22 +43,23 @@ export class ApiClientService {
|
|||
try {
|
||||
const apiClient = getApiClient(authConfig?.accessToken);
|
||||
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
apiClient,
|
||||
};
|
||||
});
|
||||
|
||||
logger.debug("ApiClientService updated successfully");
|
||||
return this.currentState;
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to update ApiClientService:", error);
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the API client is ready
|
||||
* Override isReady to check for API client
|
||||
*/
|
||||
isReady(): boolean {
|
||||
return this.currentState.apiClient !== null;
|
||||
override isReady(): boolean {
|
||||
return super.isReady() && this.currentState.apiClient !== null;
|
||||
}
|
||||
}
|
||||
}
|
||||
205
src/services/AuthService.refactored.ts
Normal file
205
src/services/AuthService.refactored.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
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();
|
||||
}
|
||||
}
|
||||
315
src/services/AuthService.test.ts
Normal file
315
src/services/AuthService.test.ts
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
|
||||
// Mock the workos module
|
||||
vi.mock('../auth/workos.js');
|
||||
|
||||
// Import the workos functions we need to mock
|
||||
import {
|
||||
loadAuthConfig,
|
||||
isAuthenticated,
|
||||
login,
|
||||
logout,
|
||||
ensureOrganization,
|
||||
saveAuthConfig,
|
||||
listUserOrganizations
|
||||
} from '../auth/workos.js';
|
||||
|
||||
import { AuthService } from './AuthService.js';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
const mockAuthConfig = {
|
||||
accessToken: 'test-token',
|
||||
organizationId: 'org-123',
|
||||
userId: 'user-123',
|
||||
userEmail: 'test@example.com',
|
||||
refreshToken: 'refresh-token',
|
||||
expiresAt: Date.now() + 3600000
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new AuthService();
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
test('should initialize with unauthenticated state', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
|
||||
const state = await service.initialize();
|
||||
|
||||
expect(state).toEqual({
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
organizationId: undefined
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with authenticated state', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
|
||||
const state = await service.initialize();
|
||||
|
||||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('login()', () => {
|
||||
test('should update state after successful login', async () => {
|
||||
// Initialize first
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
||||
// Mock successful login
|
||||
vi.mocked(login).mockResolvedValue(mockAuthConfig);
|
||||
|
||||
const state = await service.login();
|
||||
|
||||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
||||
test('should handle login failure', async () => {
|
||||
await service.initialize();
|
||||
const loginError = new Error('Login failed');
|
||||
vi.mocked(login).mockRejectedValue(loginError);
|
||||
|
||||
await expect(service.login()).rejects.toThrow('Login failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('logout()', () => {
|
||||
test('should clear state after logout', async () => {
|
||||
// Initialize with authenticated state
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const state = await service.logout();
|
||||
|
||||
expect(state).toEqual({
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
organizationId: undefined
|
||||
});
|
||||
expect(logout).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ensureOrganization()', () => {
|
||||
test('should update organization after ensuring', async () => {
|
||||
// Initialize with auth but no org
|
||||
const authWithoutOrg = { ...mockAuthConfig, organizationId: null };
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(authWithoutOrg);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
// Mock ensure organization
|
||||
vi.mocked(ensureOrganization).mockResolvedValue(mockAuthConfig);
|
||||
|
||||
const state = await service.ensureOrganization();
|
||||
|
||||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
});
|
||||
});
|
||||
|
||||
test('should throw error if not authenticated', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
||||
await expect(service.ensureOrganization()).rejects.toThrow(
|
||||
'Not authenticated - cannot ensure organization'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchOrganization()', () => {
|
||||
test('should update state with new organization', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const state = await service.switchOrganization('org-456');
|
||||
|
||||
expect(state).toEqual({
|
||||
authConfig: {
|
||||
...mockAuthConfig,
|
||||
organizationId: 'org-456'
|
||||
},
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-456'
|
||||
});
|
||||
expect(saveAuthConfig).toHaveBeenCalledWith({
|
||||
...mockAuthConfig,
|
||||
organizationId: 'org-456'
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle null organization', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const state = await service.switchOrganization(null);
|
||||
|
||||
expect(state.organizationId).toBeUndefined();
|
||||
});
|
||||
|
||||
test('should throw error if not file-based auth', async () => {
|
||||
const tokenOnlyAuth = { accessToken: 'token' } as any;
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(tokenOnlyAuth);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
await expect(service.switchOrganization('org-456')).rejects.toThrow(
|
||||
'Not authenticated with file-based auth'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableOrganizations()', () => {
|
||||
test('should return organizations when authenticated', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const mockOrgs = [
|
||||
{ id: 'org-1', name: 'Org 1' },
|
||||
{ id: 'org-2', name: 'Org 2' }
|
||||
];
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue(mockOrgs);
|
||||
|
||||
const orgs = await service.getAvailableOrganizations();
|
||||
expect(orgs).toEqual(mockOrgs);
|
||||
});
|
||||
|
||||
test('should return null when not authenticated', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
||||
const orgs = await service.getAvailableOrganizations();
|
||||
expect(orgs).toBeNull();
|
||||
});
|
||||
|
||||
test('should handle errors gracefully', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockRejectedValue(new Error('API error'));
|
||||
|
||||
// Add error event listener to prevent unhandled rejection
|
||||
const errorHandler = vi.fn();
|
||||
service.on('error', errorHandler);
|
||||
|
||||
const orgs = await service.getAvailableOrganizations();
|
||||
expect(orgs).toBeNull();
|
||||
expect(errorHandler).toHaveBeenCalledWith(expect.any(Error));
|
||||
|
||||
// Clean up
|
||||
service.off('error', errorHandler);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasMultipleOrganizations()', () => {
|
||||
test('should return true when multiple orgs available', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue([
|
||||
{ id: 'org-1', name: 'Org 1' },
|
||||
{ id: 'org-2', name: 'Org 2' }
|
||||
]);
|
||||
|
||||
const hasMultiple = await service.hasMultipleOrganizations();
|
||||
expect(hasMultiple).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false when no orgs available', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue([]);
|
||||
|
||||
const hasMultiple = await service.hasMultipleOrganizations();
|
||||
expect(hasMultiple).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('refresh()', () => {
|
||||
test('should reload auth state from disk', async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
||||
// Update mock to return authenticated state
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
|
||||
const state = await service.refresh();
|
||||
|
||||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
test('should emit stateChanged on login', async () => {
|
||||
// Initialize with no auth config to simulate logged out state
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
|
||||
vi.mocked(login).mockResolvedValue(mockAuthConfig);
|
||||
await service.login();
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
isAuthenticated: true,
|
||||
authConfig: mockAuthConfig,
|
||||
organizationId: 'org-123'
|
||||
}),
|
||||
expect.objectContaining({
|
||||
isAuthenticated: false,
|
||||
authConfig: null
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit error on login failure', async () => {
|
||||
await service.initialize();
|
||||
const errorListener = vi.fn();
|
||||
service.on('error', errorListener);
|
||||
|
||||
const error = new Error('Login failed');
|
||||
vi.mocked(login).mockRejectedValue(error);
|
||||
|
||||
await expect(service.login()).rejects.toThrow();
|
||||
expect(errorListener).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -8,29 +8,31 @@ import {
|
|||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
} from "../auth/workos.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService } from "./BaseService.js";
|
||||
import { AuthServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Service for managing authentication state and operations
|
||||
* Encapsulates all auth logic and provides reactive updates
|
||||
*/
|
||||
export class AuthService {
|
||||
private currentState: AuthServiceState = {
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
};
|
||||
export class AuthService extends BaseService<AuthServiceState> {
|
||||
constructor() {
|
||||
super('AuthService', {
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the auth service by loading current config
|
||||
*/
|
||||
async initialize(): Promise<AuthServiceState> {
|
||||
logger.debug("Initializing AuthService");
|
||||
|
||||
async doInitialize(): Promise<AuthServiceState> {
|
||||
const authConfig = loadAuthConfig();
|
||||
const authenticated = isAuthenticated();
|
||||
|
||||
this.currentState = {
|
||||
const state: AuthServiceState = {
|
||||
authConfig,
|
||||
isAuthenticated: authenticated,
|
||||
organizationId: authConfig?.organizationId || undefined,
|
||||
|
|
@ -39,17 +41,10 @@ export class AuthService {
|
|||
logger.debug("AuthService initialized", {
|
||||
authenticated,
|
||||
hasConfig: !!authConfig,
|
||||
orgId: this.currentState.organizationId,
|
||||
orgId: state.organizationId,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current auth state
|
||||
*/
|
||||
getState(): AuthServiceState {
|
||||
return { ...this.currentState };
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -61,19 +56,20 @@ export class AuthService {
|
|||
try {
|
||||
const newAuthConfig = await doLogin();
|
||||
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
authConfig: newAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: newAuthConfig?.organizationId || undefined,
|
||||
};
|
||||
});
|
||||
|
||||
logger.debug("Login successful", {
|
||||
orgId: this.currentState.organizationId,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Login failed:", error);
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -86,14 +82,14 @@ export class AuthService {
|
|||
|
||||
doLogout();
|
||||
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
organizationId: undefined,
|
||||
};
|
||||
});
|
||||
|
||||
logger.debug("Logout complete");
|
||||
return this.currentState;
|
||||
return this.getState();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -116,17 +112,17 @@ export class AuthService {
|
|||
isHeadless
|
||||
);
|
||||
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
authConfig: updatedConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: updatedConfig?.organizationId || undefined,
|
||||
};
|
||||
});
|
||||
|
||||
logger.debug("Organization ensured", {
|
||||
orgId: this.currentState.organizationId,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
return this.getState();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -159,17 +155,17 @@ export class AuthService {
|
|||
|
||||
saveAuthConfig(updatedConfig);
|
||||
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
authConfig: updatedConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: organizationId || undefined,
|
||||
};
|
||||
});
|
||||
|
||||
logger.debug("Organization switched", {
|
||||
newOrgId: this.currentState.organizationId,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
return this.getState();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -186,6 +182,7 @@ export class AuthService {
|
|||
return await listUserOrganizations();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to list organizations:", error);
|
||||
this.emit('error', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -203,6 +200,6 @@ export class AuthService {
|
|||
*/
|
||||
async refresh(): Promise<AuthServiceState> {
|
||||
logger.debug("Refreshing auth state from disk");
|
||||
return this.initialize();
|
||||
return this.reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
386
src/services/BaseService.test.ts
Normal file
386
src/services/BaseService.test.ts
Normal file
|
|
@ -0,0 +1,386 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
|
||||
import { BaseService, hasDependencies, ServiceWithDependencies } from './BaseService.js';
|
||||
|
||||
// Test implementation of BaseService
|
||||
interface TestState {
|
||||
value: number;
|
||||
message: string;
|
||||
data?: any[];
|
||||
}
|
||||
|
||||
class TestService extends BaseService<TestState> {
|
||||
constructor() {
|
||||
super('TestService', {
|
||||
value: 0,
|
||||
message: 'initial'
|
||||
});
|
||||
}
|
||||
|
||||
async doInitialize(value: number, message: string): Promise<TestState> {
|
||||
return {
|
||||
value,
|
||||
message
|
||||
};
|
||||
}
|
||||
|
||||
// Expose setState for testing
|
||||
updateState(newState: Partial<TestState>) {
|
||||
this.setState(newState);
|
||||
}
|
||||
}
|
||||
|
||||
// Test service with dependencies
|
||||
class DependentTestService extends TestService implements ServiceWithDependencies {
|
||||
getDependencies(): string[] {
|
||||
return ['auth', 'config'];
|
||||
}
|
||||
}
|
||||
|
||||
// Test service that throws during initialization
|
||||
class FailingTestService extends BaseService<TestState> {
|
||||
constructor() {
|
||||
super('FailingService', {
|
||||
value: 0,
|
||||
message: 'initial'
|
||||
});
|
||||
}
|
||||
|
||||
async doInitialize(): Promise<TestState> {
|
||||
throw new Error('Initialization failed');
|
||||
}
|
||||
}
|
||||
|
||||
describe('BaseService', () => {
|
||||
describe('Basic Functionality', () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should have correct initial state', () => {
|
||||
const state = service.getState();
|
||||
expect(state).toEqual({
|
||||
value: 0,
|
||||
message: 'initial'
|
||||
});
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test('should initialize successfully', async () => {
|
||||
const state = await service.initialize(42, 'initialized');
|
||||
|
||||
expect(state).toEqual({
|
||||
value: 42,
|
||||
message: 'initialized'
|
||||
});
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
test('should emit initialization events', async () => {
|
||||
const initializingListener = vi.fn();
|
||||
const initializedListener = vi.fn();
|
||||
|
||||
service.on('initializing', initializingListener);
|
||||
service.on('initialized', initializedListener);
|
||||
|
||||
await service.initialize(42, 'initialized');
|
||||
|
||||
expect(initializingListener).toHaveBeenCalledTimes(1);
|
||||
expect(initializedListener).toHaveBeenCalledTimes(1);
|
||||
expect(initializedListener).toHaveBeenCalledWith({
|
||||
value: 42,
|
||||
message: 'initialized'
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle initialization failure', async () => {
|
||||
const failingService = new FailingTestService();
|
||||
const errorListener = vi.fn();
|
||||
|
||||
failingService.on('error', errorListener);
|
||||
|
||||
await expect(failingService.initialize()).rejects.toThrow('Initialization failed');
|
||||
expect(errorListener).toHaveBeenCalledTimes(1);
|
||||
expect(failingService.isReady()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should return immutable state copy', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
const state1 = service.getState();
|
||||
const state2 = service.getState();
|
||||
|
||||
expect(state1).toEqual(state2);
|
||||
expect(state1).not.toBe(state2); // Different object references
|
||||
});
|
||||
|
||||
test('should return shallow copy of state', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
service.updateState({ data: [{ id: 1 }, { id: 2 }] });
|
||||
|
||||
const state = service.getState();
|
||||
const originalData = state.data;
|
||||
|
||||
// Modify the returned state's nested object
|
||||
if (state.data) {
|
||||
state.data[0].id = 999;
|
||||
}
|
||||
|
||||
// With shallow copy, nested objects are shared
|
||||
const newState = service.getState();
|
||||
expect(newState.data).toEqual([{ id: 999 }, { id: 2 }]);
|
||||
expect(newState.data).toBe(originalData); // Same reference for nested objects
|
||||
});
|
||||
|
||||
test('should emit state change events', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
const stateChangeListener = vi.fn();
|
||||
service.on('stateChanged', stateChangeListener);
|
||||
|
||||
service.updateState({ value: 100 });
|
||||
|
||||
expect(stateChangeListener).toHaveBeenCalledTimes(1);
|
||||
expect(stateChangeListener).toHaveBeenCalledWith(
|
||||
{ value: 100, message: 'test' }, // new state
|
||||
{ value: 42, message: 'test' } // previous state
|
||||
);
|
||||
});
|
||||
|
||||
test('should merge partial state updates', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
service.updateState({ value: 100 });
|
||||
expect(service.getState()).toEqual({
|
||||
value: 100,
|
||||
message: 'test'
|
||||
});
|
||||
|
||||
service.updateState({ message: 'updated' });
|
||||
expect(service.getState()).toEqual({
|
||||
value: 100,
|
||||
message: 'updated'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Reload Functionality', () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should reload service with new parameters', async () => {
|
||||
await service.initialize(42, 'first');
|
||||
expect(service.getState()).toEqual({
|
||||
value: 42,
|
||||
message: 'first'
|
||||
});
|
||||
|
||||
await service.reload(100, 'second');
|
||||
expect(service.getState()).toEqual({
|
||||
value: 100,
|
||||
message: 'second'
|
||||
});
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
test('should reset isInitialized during reload', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
expect(service.isReady()).toBe(true);
|
||||
|
||||
// Create a promise to check intermediate state
|
||||
let wasNotReady = false;
|
||||
const originalInit = service.initialize.bind(service);
|
||||
service.initialize = vi.fn(async (value: number, message: string) => {
|
||||
wasNotReady = !service.isReady();
|
||||
return originalInit(value, message);
|
||||
}) as any;
|
||||
|
||||
await service.reload(100, 'reloaded');
|
||||
|
||||
expect(wasNotReady).toBe(true);
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Cleanup', () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should cleanup resources', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('test-event', listener);
|
||||
|
||||
await service.cleanup();
|
||||
|
||||
expect(service.isReady()).toBe(false);
|
||||
|
||||
// Verify listeners are removed
|
||||
service.emit('test-event');
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ServiceWithDependencies', () => {
|
||||
test('should correctly identify services with dependencies', () => {
|
||||
const regularService = new TestService();
|
||||
const dependentService = new DependentTestService();
|
||||
|
||||
expect(hasDependencies(regularService)).toBe(false);
|
||||
expect(hasDependencies(dependentService)).toBe(true);
|
||||
|
||||
if (hasDependencies(dependentService)) {
|
||||
expect(dependentService.getDependencies()).toEqual(['auth', 'config']);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Shallow Copy Functionality', () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should handle null and undefined values', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
service.updateState({
|
||||
data: [null, undefined, 'string', 123] as any
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
expect(state.data).toEqual([null, undefined, 'string', 123]);
|
||||
});
|
||||
|
||||
test('should handle Date objects', async () => {
|
||||
const date = new Date('2024-01-01');
|
||||
await service.initialize(42, 'test');
|
||||
service.updateState({
|
||||
data: [date] as any
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
expect(state.data?.[0]).toEqual(date);
|
||||
expect(state.data?.[0]).toBe(date); // Same instance with shallow copy
|
||||
expect(state.data?.[0]).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
test('should handle complex nested structures', async () => {
|
||||
const complexData = {
|
||||
nested: {
|
||||
array: [1, 2, { deep: 'value' }],
|
||||
date: new Date(),
|
||||
bool: true,
|
||||
null: null
|
||||
}
|
||||
};
|
||||
|
||||
await service.initialize(42, 'test');
|
||||
service.updateState({ data: complexData as any });
|
||||
|
||||
const state = service.getState();
|
||||
expect(state.data).toEqual(complexData);
|
||||
expect(state.data).toBe(complexData); // Same reference with shallow copy
|
||||
|
||||
// Verify nested objects are shared (not deep copied)
|
||||
if (state.data && typeof state.data === 'object' && 'nested' in state.data) {
|
||||
const data = state.data as any;
|
||||
expect(data.nested.array).toBe(complexData.nested.array);
|
||||
expect(data.nested.array[2]).toBe(complexData.nested.array[2]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
test('should emit error events on setState failures', () => {
|
||||
const service = new TestService();
|
||||
|
||||
// Override setState to throw
|
||||
const originalSetState = Object.getOwnPropertyDescriptor(
|
||||
Object.getPrototypeOf(service),
|
||||
'setState'
|
||||
);
|
||||
|
||||
Object.defineProperty(service, 'setState', {
|
||||
value: function() {
|
||||
throw new Error('setState failed');
|
||||
}
|
||||
});
|
||||
|
||||
expect(() => service.updateState({ value: 100 })).toThrow('setState failed');
|
||||
|
||||
// Restore original
|
||||
if (originalSetState) {
|
||||
Object.defineProperty(
|
||||
Object.getPrototypeOf(service),
|
||||
'setState',
|
||||
originalSetState
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emitter Integration', () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should support multiple listeners', async () => {
|
||||
const listener1 = vi.fn();
|
||||
const listener2 = vi.fn();
|
||||
|
||||
service.on('initialized', listener1);
|
||||
service.on('initialized', listener2);
|
||||
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
expect(listener1).toHaveBeenCalledTimes(1);
|
||||
expect(listener2).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('should support once listeners', async () => {
|
||||
const listener = vi.fn();
|
||||
|
||||
service.once('stateChanged', listener);
|
||||
|
||||
await service.initialize(42, 'test');
|
||||
service.updateState({ value: 100 });
|
||||
service.updateState({ value: 200 });
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('should allow removing specific listeners', async () => {
|
||||
const listener = vi.fn();
|
||||
|
||||
service.on('stateChanged', listener);
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
service.updateState({ value: 100 });
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
|
||||
service.off('stateChanged', listener);
|
||||
service.updateState({ value: 200 });
|
||||
expect(listener).toHaveBeenCalledTimes(1); // Not called again
|
||||
});
|
||||
});
|
||||
});
|
||||
109
src/services/BaseService.ts
Normal file
109
src/services/BaseService.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import { EventEmitter } from "events";
|
||||
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
/**
|
||||
* Base abstract class for all services
|
||||
* Provides common lifecycle methods and state management
|
||||
*/
|
||||
export abstract class BaseService<TState> extends EventEmitter {
|
||||
protected serviceName: string;
|
||||
protected currentState: TState;
|
||||
private isInitialized: boolean = false;
|
||||
|
||||
constructor(serviceName: string, initialState: TState) {
|
||||
super();
|
||||
this.serviceName = serviceName;
|
||||
this.currentState = initialState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the service (must be implemented by subclasses)
|
||||
* This is automatically wrapped with initialization logic
|
||||
*/
|
||||
abstract doInitialize(...args: any[]): Promise<TState>;
|
||||
|
||||
/**
|
||||
* Public initialization method that wraps the implementation
|
||||
*/
|
||||
async initialize(...args: any[]): Promise<TState> {
|
||||
logger.debug(`Initializing ${this.serviceName}`);
|
||||
this.emit("initializing");
|
||||
|
||||
try {
|
||||
const state = await this.doInitialize(...args);
|
||||
this.currentState = state;
|
||||
this.isInitialized = true;
|
||||
logger.debug(`${this.serviceName} initialized successfully`);
|
||||
this.emit("initialized", state);
|
||||
return state;
|
||||
} catch (error: any) {
|
||||
logger.error(`Failed to initialize ${this.serviceName}:`, error);
|
||||
if (this.listenerCount("error") > 0) {
|
||||
this.emit("error", error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current service state (shallow copy for immutability)
|
||||
*/
|
||||
getState(): TState {
|
||||
return { ...this.currentState };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update service state and emit change event
|
||||
*/
|
||||
protected setState(newState: Partial<TState>): void {
|
||||
const previousState = this.currentState;
|
||||
this.currentState = { ...this.currentState, ...newState };
|
||||
// Only log state updates if not in production to avoid circular reference issues
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
logger.debug(`${this.serviceName} state updated`);
|
||||
}
|
||||
this.emit("stateChanged", this.currentState, previousState);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if service is ready for use
|
||||
*/
|
||||
isReady(): boolean {
|
||||
return this.isInitialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload/refresh the service
|
||||
*/
|
||||
async reload(...args: any[]): Promise<TState> {
|
||||
logger.debug(`Reloading ${this.serviceName}`);
|
||||
this.isInitialized = false;
|
||||
return this.initialize(...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup resources (can be overridden by subclasses)
|
||||
*/
|
||||
async cleanup(): Promise<void> {
|
||||
logger.debug(`Cleaning up ${this.serviceName}`);
|
||||
this.removeAllListeners();
|
||||
this.isInitialized = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for services with dependencies
|
||||
*/
|
||||
export interface ServiceWithDependencies {
|
||||
getDependencies(): string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to check if a service has dependencies
|
||||
*/
|
||||
export function hasDependencies(
|
||||
service: any
|
||||
): service is ServiceWithDependencies {
|
||||
return !!service && typeof service.getDependencies === "function";
|
||||
}
|
||||
|
|
@ -1,31 +1,370 @@
|
|||
import { describe, expect, test, beforeEach } from '@jest/globals';
|
||||
import { ConfigService } from './ConfigService.js';
|
||||
import { beforeEach, describe, expect, vi, test } from "vitest";
|
||||
|
||||
describe('ConfigService', () => {
|
||||
let configService: ConfigService;
|
||||
// Mock modules
|
||||
vi.mock("../auth/workos.js");
|
||||
vi.mock("../configLoader.js");
|
||||
vi.mock("../args.js");
|
||||
vi.mock("./ServiceContainer.js");
|
||||
|
||||
import * as args from "../args.js";
|
||||
import * as workos from "../auth/workos.js";
|
||||
import * as configLoader from "../configLoader.js";
|
||||
|
||||
import { ConfigService } from "./ConfigService.js";
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import { SERVICE_NAMES } from "./types.js";
|
||||
|
||||
describe("ConfigService", () => {
|
||||
let service: ConfigService;
|
||||
const mockConfig = {
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
systemMessage: "Test system message",
|
||||
} as any;
|
||||
const mockApiClient = { get: vi.fn(), post: vi.fn() };
|
||||
|
||||
beforeEach(() => {
|
||||
configService = new ConfigService();
|
||||
vi.clearAllMocks();
|
||||
service = new ConfigService();
|
||||
});
|
||||
|
||||
test('updateConfigPath method exists and has correct signature', () => {
|
||||
// Test that the updateConfigPath method exists and is a function
|
||||
expect(typeof configService.updateConfigPath).toBe('function');
|
||||
|
||||
// Test that it accepts the correct parameter types
|
||||
const method = configService.updateConfigPath;
|
||||
expect(method).toBeInstanceOf(Function);
|
||||
expect(method.length).toBe(1); // Should accept 1 parameter
|
||||
describe("State Management", () => {
|
||||
test("should initialize with config from path", async () => {
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/path/to/config.yaml" } as any,
|
||||
});
|
||||
|
||||
const state = await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/path/to/config.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
config: mockConfig as any,
|
||||
configPath: "/path/to/config.yaml",
|
||||
});
|
||||
});
|
||||
|
||||
test("should initialize with undefined config path", async () => {
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "default-agent" } as any,
|
||||
});
|
||||
|
||||
const state = await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
undefined,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
config: mockConfig as any,
|
||||
configPath: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
test("should inject rules into config", async () => {
|
||||
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/config.yaml" } as any,
|
||||
});
|
||||
vi.mocked(args.processRule)
|
||||
.mockImplementation(async (rule) => `Processed: ${rule}`);
|
||||
|
||||
const state = await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/config.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any,
|
||||
["rule1", "rule2"]
|
||||
);
|
||||
|
||||
expect(state.config).toEqual({
|
||||
...mockConfig,
|
||||
systemMessage:
|
||||
"Test system message\n\nProcessed: rule1\n\nProcessed: rule2",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('ConfigService has reactive pattern implementation', () => {
|
||||
// Verify that ConfigService has the updateConfigPath method
|
||||
// which is the key method for reactive config switching
|
||||
expect(configService).toHaveProperty('updateConfigPath');
|
||||
expect(typeof configService.updateConfigPath).toBe('function');
|
||||
|
||||
// The method signature should accept string | undefined
|
||||
// This confirms the reactive pattern is implemented
|
||||
expect(configService.updateConfigPath.length).toBe(1);
|
||||
describe("switchConfig()", () => {
|
||||
test("should switch to new configuration", async () => {
|
||||
|
||||
// Initialize first
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/old.yaml" } as any,
|
||||
});
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
// Switch to new config
|
||||
const newConfig = { ...mockConfig, name: "new-assistant" } as any;
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: newConfig,
|
||||
source: { type: "cli-flag", path: "/new.yaml" } as any,
|
||||
});
|
||||
|
||||
const state = await service.switchConfig(
|
||||
"/new.yaml",
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
config: newConfig,
|
||||
configPath: "/new.yaml",
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
||||
test("should handle switch config errors", async () => {
|
||||
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
vi.mocked(configLoader.loadConfiguration)
|
||||
.mockRejectedValue(new Error("Config not found"));
|
||||
|
||||
await expect(
|
||||
service.switchConfig(
|
||||
"/bad.yaml",
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
)
|
||||
).rejects.toThrow("Config not found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reload()", () => {
|
||||
test("should reload current configuration", async () => {
|
||||
|
||||
// Initialize with a config
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/config.yaml" } as any,
|
||||
});
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/config.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
// Modify mock to return updated config
|
||||
const updatedConfig = { ...mockConfig, name: "updated-assistant" } as any;
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: updatedConfig,
|
||||
source: { type: "cli-flag", path: "/config.yaml" } as any,
|
||||
});
|
||||
|
||||
const state = await service.reload(
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
config: updatedConfig,
|
||||
configPath: "/config.yaml",
|
||||
});
|
||||
});
|
||||
|
||||
test("should throw error if no config path available", async () => {
|
||||
// Initialize without config path
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "default-agent" } as any,
|
||||
});
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
undefined,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.reload(
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
)
|
||||
).rejects.toThrow("No configuration path available for reload");
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateConfigPath()", () => {
|
||||
test("should update config path and reload dependent services", async () => {
|
||||
|
||||
// Initialize service first
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/old.yaml" } as any,
|
||||
});
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
// Mock service container
|
||||
vi.mocked(workos.loadAuthConfig)
|
||||
.mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any);
|
||||
vi.mocked(serviceContainer.get).mockResolvedValue({
|
||||
apiClient: mockApiClient,
|
||||
});
|
||||
|
||||
// Mock new config load
|
||||
const newConfig = { ...mockConfig, name: "new-assistant" } as any;
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: newConfig,
|
||||
source: { type: "cli-flag", path: "/new.yaml" } as any,
|
||||
});
|
||||
|
||||
await service.updateConfigPath("/new.yaml");
|
||||
|
||||
expect(service.getState()).toEqual({
|
||||
config: newConfig,
|
||||
configPath: "/new.yaml",
|
||||
});
|
||||
expect(vi.mocked(serviceContainer.set)).toHaveBeenCalledWith(
|
||||
SERVICE_NAMES.CONFIG,
|
||||
expect.objectContaining({ config: newConfig })
|
||||
);
|
||||
expect(vi.mocked(serviceContainer.reload)).toHaveBeenCalledWith(
|
||||
SERVICE_NAMES.MODEL
|
||||
);
|
||||
expect(vi.mocked(serviceContainer.reload)).toHaveBeenCalledWith(
|
||||
SERVICE_NAMES.MCP
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle missing API client", async () => {
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
vi.mocked(workos.loadAuthConfig)
|
||||
.mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any);
|
||||
vi.mocked(serviceContainer.get).mockResolvedValue({
|
||||
apiClient: null,
|
||||
});
|
||||
|
||||
await expect(service.updateConfigPath("/new.yaml")).rejects.toThrow(
|
||||
"API client not available"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDependencies()", () => {
|
||||
test("should declare auth and apiClient dependencies", () => {
|
||||
expect(service.getDependencies()).toEqual(["auth", "apiClient"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Event Emission", () => {
|
||||
test("should emit stateChanged when switching config", async () => {
|
||||
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/old.yaml" } as any,
|
||||
});
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on("stateChanged", listener);
|
||||
|
||||
const newConfig = { ...mockConfig, name: "new-assistant" } as any;
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: newConfig,
|
||||
source: { type: "cli-flag", path: "/new.yaml" } as any,
|
||||
});
|
||||
|
||||
await service.switchConfig(
|
||||
"/new.yaml",
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ config: newConfig, configPath: "/new.yaml" }),
|
||||
expect.objectContaining({ config: mockConfig, configPath: "/old.yaml" })
|
||||
);
|
||||
});
|
||||
|
||||
test("should emit error on switch failure", async () => {
|
||||
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
);
|
||||
|
||||
const errorListener = vi.fn();
|
||||
service.on("error", errorListener);
|
||||
|
||||
const error = new Error("Config load failed");
|
||||
vi.mocked(configLoader.loadConfiguration).mockRejectedValue(error);
|
||||
|
||||
await expect(
|
||||
service.switchConfig(
|
||||
"/bad.yaml",
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
)
|
||||
).rejects.toThrow();
|
||||
expect(errorListener).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Legacy Compatibility", () => {
|
||||
test("updateConfigPath method exists and has correct signature", () => {
|
||||
// Test that the updateConfigPath method exists and is a function
|
||||
expect(typeof service.updateConfigPath).toBe("function");
|
||||
|
||||
// Test that it accepts the correct parameter types
|
||||
const method = service.updateConfigPath;
|
||||
expect(method).toBeInstanceOf(Function);
|
||||
expect(method.length).toBe(1); // Should accept 1 parameter
|
||||
});
|
||||
|
||||
test("ConfigService has reactive pattern implementation", () => {
|
||||
// Verify that ConfigService has the updateConfigPath method
|
||||
// which is the key method for reactive config switching
|
||||
expect(service).toHaveProperty("updateConfigPath");
|
||||
expect(typeof service.updateConfigPath).toBe("function");
|
||||
|
||||
// The method signature should accept string | undefined
|
||||
// This confirms the reactive pattern is implemented
|
||||
expect(service.updateConfigPath.length).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,15 +1,17 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
|
||||
|
||||
import { processRule } from "../args.js";
|
||||
import {
|
||||
AuthConfig,
|
||||
loadAuthConfig,
|
||||
} from "../auth/workos.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import {
|
||||
ApiClientServiceState,
|
||||
AuthServiceState,
|
||||
ConfigServiceState,
|
||||
SERVICE_NAMES,
|
||||
} from "./types.js";
|
||||
|
|
@ -18,54 +20,50 @@ import {
|
|||
* Service for managing configuration state and operations
|
||||
* Handles loading configs from files or assistant slugs
|
||||
*/
|
||||
export class ConfigService {
|
||||
private currentState: ConfigServiceState = {
|
||||
config: null,
|
||||
configPath: undefined,
|
||||
};
|
||||
export class ConfigService extends BaseService<ConfigServiceState> implements ServiceWithDependencies {
|
||||
constructor() {
|
||||
super('ConfigService', {
|
||||
config: null,
|
||||
configPath: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare dependencies on other services
|
||||
*/
|
||||
getDependencies(): string[] {
|
||||
return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT];
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the config service
|
||||
*/
|
||||
async initialize(
|
||||
async doInitialize(
|
||||
authConfig: AuthConfig,
|
||||
configPath: string | undefined,
|
||||
organizationId: string | null,
|
||||
apiClient: DefaultApiInterface,
|
||||
rules?: string[]
|
||||
): Promise<ConfigServiceState> {
|
||||
try {
|
||||
// Use the new streamlined config loader
|
||||
const { loadConfiguration } = await import("../configLoader.js");
|
||||
const result = await loadConfiguration(authConfig, configPath, apiClient);
|
||||
|
||||
let config = result.config;
|
||||
// Use the new streamlined config loader
|
||||
const { loadConfiguration } = await import("../configLoader.js");
|
||||
const result = await loadConfiguration(authConfig, configPath, apiClient);
|
||||
|
||||
let config = result.config;
|
||||
|
||||
// Inject rules if provided
|
||||
if (rules && rules.length > 0) {
|
||||
config = await this.injectRulesIntoConfig(config, rules);
|
||||
}
|
||||
|
||||
this.currentState = {
|
||||
config,
|
||||
configPath,
|
||||
};
|
||||
|
||||
// Config URI persistence is now handled by the streamlined loader
|
||||
|
||||
logger.debug("ConfigService initialized successfully");
|
||||
return this.currentState;
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to initialize ConfigService:", error);
|
||||
throw error;
|
||||
// Inject rules if provided
|
||||
if (rules && rules.length > 0) {
|
||||
config = await this.injectRulesIntoConfig(config, rules);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current config state
|
||||
*/
|
||||
getState(): ConfigServiceState {
|
||||
return { ...this.currentState };
|
||||
// Config URI persistence is now handled by the streamlined loader
|
||||
|
||||
logger.debug("ConfigService initialized successfully");
|
||||
|
||||
return {
|
||||
config,
|
||||
configPath,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -95,10 +93,10 @@ export class ConfigService {
|
|||
config = await this.injectRulesIntoConfig(config, rules);
|
||||
}
|
||||
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
config,
|
||||
configPath: newConfigPath,
|
||||
};
|
||||
});
|
||||
|
||||
// Config URI persistence is now handled by the streamlined loader
|
||||
|
||||
|
|
@ -106,9 +104,10 @@ export class ConfigService {
|
|||
newConfigPath,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to switch configuration:", error);
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -148,7 +147,7 @@ export class ConfigService {
|
|||
return config;
|
||||
}
|
||||
|
||||
let processedRules: string[] = [];
|
||||
const processedRules: string[] = [];
|
||||
|
||||
for (const ruleSpec of rules) {
|
||||
try {
|
||||
|
|
@ -194,9 +193,6 @@ export class ConfigService {
|
|||
try {
|
||||
// Get current auth and API client state needed for config loading
|
||||
const authConfig = loadAuthConfig();
|
||||
const authState = await serviceContainer.get<AuthServiceState>(
|
||||
SERVICE_NAMES.AUTH
|
||||
);
|
||||
const apiClientState = await serviceContainer.get<ApiClientServiceState>(
|
||||
SERVICE_NAMES.API_CLIENT
|
||||
);
|
||||
|
|
@ -214,15 +210,15 @@ export class ConfigService {
|
|||
);
|
||||
|
||||
// Update internal state
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
config: result.config,
|
||||
configPath: newConfigPath,
|
||||
};
|
||||
});
|
||||
|
||||
// Config URI persistence is now handled by the streamlined loader
|
||||
|
||||
// Update the CONFIG service in the container
|
||||
serviceContainer.set(SERVICE_NAMES.CONFIG, this.currentState);
|
||||
serviceContainer.set(SERVICE_NAMES.CONFIG, this.getState());
|
||||
|
||||
// Manually reload dependent services (MODEL, MCP) to pick up the new config
|
||||
await serviceContainer.reload(SERVICE_NAMES.MODEL);
|
||||
|
|
@ -234,8 +230,9 @@ export class ConfigService {
|
|||
});
|
||||
} catch (error: any) {
|
||||
logger.error("Failed to update configuration path:", error);
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
|
||||
import { MCPService } from '../mcp.js';
|
||||
import logger from '../util/logger.js';
|
||||
import { logger } from '../util/logger.js';
|
||||
|
||||
import { MCPServiceState } from './types.js';
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { beforeEach, afterEach, describe, expect, it, jest } from '@jest/globals';
|
||||
import { beforeEach, afterEach, describe, expect, vi, test } from 'vitest';
|
||||
|
||||
import { ModeService } from './ModeService.js';
|
||||
import { PermissionMode } from '../permissions/types.js';
|
||||
|
||||
describe('ModeService', () => {
|
||||
let modeService: ModeService;
|
||||
|
|
@ -16,61 +16,77 @@ describe('ModeService', () => {
|
|||
(ModeService as any).instance = undefined;
|
||||
});
|
||||
|
||||
describe('initialization', () => {
|
||||
it('should initialize with normal mode by default', () => {
|
||||
modeService.initialize({});
|
||||
describe('State Management', () => {
|
||||
test('should initialize with normal mode by default', async () => {
|
||||
const state = await modeService.initialize({});
|
||||
|
||||
expect(state).toEqual({
|
||||
mode: 'normal',
|
||||
toolPermissionService: expect.any(Object)
|
||||
});
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
});
|
||||
|
||||
it('should convert readonly flag to plan mode', () => {
|
||||
modeService.initialize({ readonly: true });
|
||||
test('should convert readonly flag to plan mode', async () => {
|
||||
const state = await modeService.initialize({ readonly: true });
|
||||
|
||||
expect(state.mode).toBe('plan');
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
});
|
||||
|
||||
it('should convert auto flag to auto mode', () => {
|
||||
modeService.initialize({ auto: true });
|
||||
test('should convert auto flag to auto mode', async () => {
|
||||
const state = await modeService.initialize({ auto: true });
|
||||
|
||||
expect(state.mode).toBe('auto');
|
||||
expect(modeService.getCurrentMode()).toBe('auto');
|
||||
});
|
||||
|
||||
|
||||
it('should initialize tool permission service', () => {
|
||||
modeService.initialize({ allow: ['testTool'], exclude: ['badTool'] });
|
||||
const toolPermissionService = modeService.getToolPermissionService();
|
||||
test('should initialize tool permission service with flags', async () => {
|
||||
const state = await modeService.initialize({
|
||||
allow: ['testTool'],
|
||||
exclude: ['badTool']
|
||||
});
|
||||
|
||||
const toolPermissionService = state.toolPermissionService;
|
||||
expect(toolPermissionService).toBeDefined();
|
||||
expect(toolPermissionService.getState()).toBeDefined();
|
||||
expect(toolPermissionService.getCurrentMode()).toBe('normal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('mode switching', () => {
|
||||
beforeEach(() => {
|
||||
modeService.initialize({});
|
||||
describe('switchMode()', () => {
|
||||
beforeEach(async () => {
|
||||
await modeService.initialize({});
|
||||
});
|
||||
|
||||
it('should switch from normal to plan mode', () => {
|
||||
test('should switch from normal to plan mode', () => {
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
|
||||
modeService.switchMode('plan');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
expect(modeService.getState().mode).toBe('plan');
|
||||
});
|
||||
|
||||
test('should switch from plan to auto mode', () => {
|
||||
modeService.switchMode('plan');
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
});
|
||||
|
||||
it('should switch from plan to auto mode', () => {
|
||||
modeService.switchMode('plan');
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
|
||||
modeService.switchMode('auto');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe('auto');
|
||||
expect(modeService.getState().mode).toBe('auto');
|
||||
});
|
||||
|
||||
it('should switch to auto mode', () => {
|
||||
modeService.switchMode('auto');
|
||||
expect(modeService.getCurrentMode()).toBe('auto');
|
||||
});
|
||||
|
||||
it('should switch back to normal mode', () => {
|
||||
test('should switch back to normal mode', () => {
|
||||
modeService.switchMode('plan');
|
||||
modeService.switchMode('normal');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
expect(modeService.getState().mode).toBe('normal');
|
||||
});
|
||||
|
||||
it('should update tool permission service when switching modes', () => {
|
||||
test('should update tool permission service when switching modes', () => {
|
||||
const toolPermissionService = modeService.getToolPermissionService();
|
||||
const initialState = toolPermissionService.getState();
|
||||
|
||||
|
|
@ -84,14 +100,41 @@ describe('ModeService', () => {
|
|||
permission: 'allow'
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle multiple mode switches correctly', () => {
|
||||
// Start in normal
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
|
||||
// Switch to plan
|
||||
modeService.switchMode('plan');
|
||||
const planState = modeService.getToolPermissionService().getState();
|
||||
expect(planState.permissions.policies).toContainEqual({
|
||||
tool: 'Write',
|
||||
permission: 'exclude'
|
||||
});
|
||||
|
||||
// Switch to auto
|
||||
modeService.switchMode('auto');
|
||||
const autoState = modeService.getToolPermissionService().getState();
|
||||
expect(autoState.permissions.policies).toHaveLength(1);
|
||||
expect(autoState.permissions.policies[0]).toEqual({
|
||||
tool: '*',
|
||||
permission: 'allow'
|
||||
});
|
||||
|
||||
// Back to normal
|
||||
modeService.switchMode('normal');
|
||||
const normalState = modeService.getToolPermissionService().getState();
|
||||
expect(normalState.currentMode).toBe('normal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('available modes', () => {
|
||||
beforeEach(() => {
|
||||
modeService.initialize({});
|
||||
describe('getAvailableModes()', () => {
|
||||
beforeEach(async () => {
|
||||
await modeService.initialize({});
|
||||
});
|
||||
|
||||
it('should return all available modes with descriptions', () => {
|
||||
test('should return all available modes with descriptions', () => {
|
||||
const modes = modeService.getAvailableModes();
|
||||
expect(modes).toHaveLength(3);
|
||||
|
||||
|
|
@ -108,16 +151,16 @@ describe('ModeService', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('singleton behavior', () => {
|
||||
it('should return the same instance', () => {
|
||||
describe('Singleton Behavior', () => {
|
||||
test('should return the same instance', () => {
|
||||
const instance1 = ModeService.getInstance();
|
||||
const instance2 = ModeService.getInstance();
|
||||
expect(instance1).toBe(instance2);
|
||||
});
|
||||
|
||||
it('should maintain state across getInstance calls', () => {
|
||||
test('should maintain state across getInstance calls', async () => {
|
||||
const instance1 = ModeService.getInstance();
|
||||
instance1.initialize({});
|
||||
await instance1.initialize({});
|
||||
instance1.switchMode('plan');
|
||||
|
||||
const instance2 = ModeService.getInstance();
|
||||
|
|
@ -125,43 +168,92 @@ describe('ModeService', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('event emission', () => {
|
||||
let modeChangeListener: jest.Mock;
|
||||
describe('isReady()', () => {
|
||||
test('should always return true for ModeService', () => {
|
||||
// ModeService is always ready since it's a singleton
|
||||
expect(modeService.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
modeService.initialize({});
|
||||
modeChangeListener = jest.fn();
|
||||
describe('Event Emission', () => {
|
||||
let modeChangeListener: ReturnType<typeof vi.fn>;
|
||||
let stateChangeListener: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await modeService.initialize({});
|
||||
modeChangeListener = vi.fn();
|
||||
stateChangeListener = vi.fn();
|
||||
modeService.on('modeChanged', modeChangeListener);
|
||||
modeService.on('stateChanged', stateChangeListener);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
modeService.off('modeChanged', modeChangeListener);
|
||||
modeService.off('stateChanged', stateChangeListener);
|
||||
});
|
||||
|
||||
it('should emit modeChanged event when mode switches', () => {
|
||||
test('should emit modeChanged event when mode switches', () => {
|
||||
modeService.switchMode('plan');
|
||||
|
||||
expect(modeChangeListener).toHaveBeenCalledWith('plan', 'normal');
|
||||
expect(modeChangeListener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should emit event with correct previous and new modes', () => {
|
||||
test('should emit stateChanged event when mode switches', () => {
|
||||
modeService.switchMode('plan');
|
||||
|
||||
expect(stateChangeListener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ mode: 'plan' }),
|
||||
expect.objectContaining({ mode: 'normal' })
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit event with correct previous and new modes', () => {
|
||||
modeService.switchMode('plan');
|
||||
modeChangeListener.mockClear();
|
||||
stateChangeListener.mockClear();
|
||||
|
||||
modeService.switchMode('auto');
|
||||
|
||||
expect(modeChangeListener).toHaveBeenCalledWith('auto', 'plan');
|
||||
expect(modeChangeListener).toHaveBeenCalledTimes(1);
|
||||
expect(stateChangeListener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not emit event when switching to same mode', () => {
|
||||
test('should not emit event when switching to same mode', () => {
|
||||
modeService.switchMode('plan');
|
||||
modeChangeListener.mockClear();
|
||||
stateChangeListener.mockClear();
|
||||
|
||||
modeService.switchMode('plan');
|
||||
|
||||
expect(modeChangeListener).not.toHaveBeenCalled();
|
||||
// stateChanged might still be called due to setState, but modeChanged should not
|
||||
});
|
||||
});
|
||||
|
||||
describe('Integration with ToolPermissionService', () => {
|
||||
beforeEach(async () => {
|
||||
await modeService.initialize({
|
||||
allow: ['Read'],
|
||||
exclude: ['dangerous_tool']
|
||||
});
|
||||
});
|
||||
|
||||
test('should pass initialization args to ToolPermissionService', () => {
|
||||
const toolService = modeService.getToolPermissionService();
|
||||
const state = toolService.getState();
|
||||
|
||||
// The state should have processed the allow/exclude rules
|
||||
expect(state.permissions.policies).toBeDefined();
|
||||
expect(state.currentMode).toBe('normal');
|
||||
});
|
||||
|
||||
test('should maintain ToolPermissionService reference', () => {
|
||||
const toolService1 = modeService.getToolPermissionService();
|
||||
const toolService2 = modeService.getToolPermissionService();
|
||||
|
||||
expect(toolService1).toBe(toolService2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,19 +1,27 @@
|
|||
import { EventEmitter } from "events";
|
||||
import { PermissionMode } from "../permissions/types.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService } from "./BaseService.js";
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
export interface ModeServiceState {
|
||||
mode: PermissionMode;
|
||||
toolPermissionService: ToolPermissionService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Global service for managing permission modes
|
||||
* Provides a singleton interface for mode switching
|
||||
*/
|
||||
export class ModeService extends EventEmitter {
|
||||
export class ModeService extends BaseService<ModeServiceState> {
|
||||
private static instance: ModeService;
|
||||
private toolPermissionService: ToolPermissionService;
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
this.toolPermissionService = new ToolPermissionService();
|
||||
const toolPermissionService = new ToolPermissionService();
|
||||
super('ModeService', {
|
||||
mode: "normal",
|
||||
toolPermissionService
|
||||
});
|
||||
}
|
||||
|
||||
public static getInstance(): ModeService {
|
||||
|
|
@ -26,13 +34,14 @@ export class ModeService extends EventEmitter {
|
|||
/**
|
||||
* Initialize the mode service with command line arguments
|
||||
*/
|
||||
public initialize(args: {
|
||||
async doInitialize(args: {
|
||||
readonly?: boolean;
|
||||
auto?: boolean;
|
||||
allow?: string[];
|
||||
ask?: string[];
|
||||
exclude?: string[];
|
||||
}) {
|
||||
isHeadless?: boolean;
|
||||
}): Promise<ModeServiceState> {
|
||||
// Convert legacy flags to mode
|
||||
let mode: PermissionMode = "normal";
|
||||
if (args.readonly) {
|
||||
|
|
@ -41,22 +50,31 @@ export class ModeService extends EventEmitter {
|
|||
mode = "auto"; // Auto flag maps to auto mode
|
||||
}
|
||||
|
||||
this.toolPermissionService.initializeSync({
|
||||
this.currentState.toolPermissionService.initializeSync({
|
||||
allow: args.allow,
|
||||
ask: args.ask,
|
||||
exclude: args.exclude,
|
||||
mode
|
||||
mode,
|
||||
isHeadless: args.isHeadless
|
||||
});
|
||||
|
||||
logger.debug(`ModeService initialized with mode: ${mode}`);
|
||||
|
||||
return {
|
||||
mode,
|
||||
toolPermissionService: this.currentState.toolPermissionService
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch to a different mode
|
||||
*/
|
||||
public switchMode(mode: PermissionMode): void {
|
||||
const previousMode = this.toolPermissionService.getCurrentMode();
|
||||
const newState = this.toolPermissionService.switchMode(mode);
|
||||
const previousMode = this.currentState.mode;
|
||||
this.currentState.toolPermissionService.switchMode(mode);
|
||||
|
||||
this.setState({ mode });
|
||||
|
||||
logger.info(`Switched to ${mode} mode`);
|
||||
|
||||
// Emit mode change event for immediate UI updates
|
||||
|
|
@ -69,14 +87,14 @@ export class ModeService extends EventEmitter {
|
|||
* Get the current mode
|
||||
*/
|
||||
public getCurrentMode(): PermissionMode {
|
||||
return this.toolPermissionService.getCurrentMode();
|
||||
return this.currentState.mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tool permission service instance
|
||||
*/
|
||||
public getToolPermissionService(): ToolPermissionService {
|
||||
return this.toolPermissionService;
|
||||
return this.currentState.toolPermissionService;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -89,6 +107,13 @@ export class ModeService extends EventEmitter {
|
|||
{ mode: "auto", description: "Automatically allow all tools without asking" }
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Override isReady since this is a singleton with immediate availability
|
||||
*/
|
||||
override isReady(): boolean {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
|
|
|
|||
241
src/services/ModelService.refactored.ts
Normal file
241
src/services/ModelService.refactored.ts
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
|
||||
|
||||
import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js';
|
||||
import { getLlmApi } from '../config.js';
|
||||
import { logger } from '../util/logger.js';
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from './BaseService.js';
|
||||
import { ModelServiceState } from './types.js';
|
||||
|
||||
/**
|
||||
* Service for managing LLM and model state
|
||||
* Extends BaseService and implements ServiceWithDependencies
|
||||
*/
|
||||
export class ModelService extends BaseService<ModelServiceState> implements ServiceWithDependencies {
|
||||
private availableModels: ModelConfig[] = [];
|
||||
private assistant: AssistantUnrolled | null = null;
|
||||
private authConfig: AuthConfig | null = null;
|
||||
|
||||
constructor() {
|
||||
super('ModelService', {
|
||||
llmApi: null,
|
||||
model: null
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare dependencies on other services
|
||||
*/
|
||||
getDependencies(): string[] {
|
||||
return ['auth', 'config'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the model service
|
||||
*/
|
||||
async doInitialize(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig
|
||||
): Promise<ModelServiceState> {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter((model) =>
|
||||
model && model.roles?.includes("chat")
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
// Check if we have a persisted model name and use it if valid
|
||||
const persistedModelName = getModelName(authConfig);
|
||||
if (persistedModelName) {
|
||||
const modelIndex = this.getModelIndexByName(persistedModelName);
|
||||
if (modelIndex !== -1) {
|
||||
// Use the persisted model
|
||||
const state = await this.switchModel(modelIndex);
|
||||
return state;
|
||||
} else {
|
||||
// Model name not found, use default model selection
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// Use default model selection
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the model based on new config or auth changes
|
||||
*/
|
||||
async update(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig
|
||||
): Promise<ModelServiceState> {
|
||||
logger.debug('Updating ModelService');
|
||||
|
||||
try {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter((model) =>
|
||||
model && model.roles?.includes("chat")
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
|
||||
this.setState({
|
||||
llmApi,
|
||||
model
|
||||
});
|
||||
|
||||
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
|
||||
*/
|
||||
override isReady(): boolean {
|
||||
return super.isReady() &&
|
||||
this.currentState.llmApi !== null &&
|
||||
this.currentState.model !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get model information for display
|
||||
*/
|
||||
getModelInfo(): { provider: string; name: string } | null {
|
||||
if (!this.currentState.model) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
provider: this.currentState.model.provider,
|
||||
name: (this.currentState.model as any).name || 'unnamed'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of available chat models
|
||||
*/
|
||||
getAvailableChatModels(): Array<{ provider: string; name: string; index: number }> {
|
||||
return this.availableModels.map((model, index) => ({
|
||||
provider: model.provider,
|
||||
name: (model as any).name || (model as any).model || 'unnamed',
|
||||
index
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch to a different chat model by index
|
||||
*/
|
||||
async switchModel(modelIndex: number): Promise<ModelServiceState> {
|
||||
if (!this.assistant || !this.authConfig) {
|
||||
throw new Error('ModelService not initialized');
|
||||
}
|
||||
|
||||
if (modelIndex < 0 || modelIndex >= this.availableModels.length) {
|
||||
throw new Error(`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`);
|
||||
}
|
||||
|
||||
const selectedModel = this.availableModels[modelIndex];
|
||||
logger.debug('Switching to model', {
|
||||
modelIndex,
|
||||
provider: selectedModel.provider,
|
||||
name: (selectedModel as any).name || 'unnamed'
|
||||
});
|
||||
|
||||
try {
|
||||
const accessToken = getAccessToken(this.authConfig);
|
||||
const organizationId = getOrganizationId(this.authConfig);
|
||||
|
||||
const config: LLMConfig =
|
||||
selectedModel.provider === "continue-proxy"
|
||||
? {
|
||||
provider: selectedModel.provider,
|
||||
requestOptions: selectedModel.requestOptions,
|
||||
apiBase: selectedModel.apiBase,
|
||||
apiKey: accessToken ?? undefined,
|
||||
env: {
|
||||
apiKeyLocation: (selectedModel as any).apiKeyLocation,
|
||||
orgScopeId: organizationId,
|
||||
proxyUrl: undefined,
|
||||
},
|
||||
}
|
||||
: {
|
||||
provider: selectedModel.provider as any,
|
||||
apiKey: selectedModel.apiKey,
|
||||
apiBase: selectedModel.apiBase,
|
||||
requestOptions: selectedModel.requestOptions,
|
||||
env: selectedModel.env,
|
||||
};
|
||||
|
||||
const llmApi = constructLlmApi(config);
|
||||
|
||||
if (!llmApi) {
|
||||
throw new Error('Failed to initialize LLM with selected model');
|
||||
}
|
||||
|
||||
this.setState({
|
||||
llmApi,
|
||||
model: selectedModel
|
||||
});
|
||||
|
||||
logger.debug('Model switched successfully', {
|
||||
modelProvider: selectedModel.provider,
|
||||
modelName: (selectedModel as any).name || 'unnamed'
|
||||
});
|
||||
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to switch model:', error);
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current model index
|
||||
*/
|
||||
getCurrentModelIndex(): number {
|
||||
if (!this.currentState.model) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return this.availableModels.findIndex(model =>
|
||||
model.provider === this.currentState.model?.provider &&
|
||||
(model as any).name === (this.currentState.model as any).name
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get model index by name and provider
|
||||
*/
|
||||
getModelIndexByName(modelName: string, provider?: string): number {
|
||||
return this.availableModels.findIndex(model => {
|
||||
const name = (model as any).name || (model as any).model;
|
||||
const nameMatches = name === modelName;
|
||||
|
||||
if (provider) {
|
||||
return nameMatches && model.provider === provider;
|
||||
}
|
||||
|
||||
return nameMatches;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,15 +1,27 @@
|
|||
import { describe, it, expect, beforeEach } from '@jest/globals';
|
||||
import { ModelService } from './ModelService.js';
|
||||
import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml';
|
||||
import * as openaiAdapters from '@continuedev/openai-adapters';
|
||||
import { describe, expect, beforeEach, vi, test } from 'vitest';
|
||||
|
||||
// Mock dependencies before imports
|
||||
vi.mock('@continuedev/openai-adapters');
|
||||
vi.mock('../config.js');
|
||||
vi.mock('../auth/workos.js');
|
||||
|
||||
import { AuthConfig } from '../auth/workos.js';
|
||||
import * as workos from '../auth/workos.js';
|
||||
import * as config from '../config.js';
|
||||
|
||||
import { ModelService } from './ModelService.js';
|
||||
|
||||
describe('ModelService', () => {
|
||||
let modelService: ModelService;
|
||||
let service: ModelService;
|
||||
let mockAssistant: AssistantUnrolled;
|
||||
let mockAuthConfig: AuthConfig;
|
||||
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
|
||||
beforeEach(() => {
|
||||
modelService = new ModelService();
|
||||
vi.clearAllMocks();
|
||||
service = new ModelService();
|
||||
|
||||
mockAssistant = {
|
||||
name: 'test-assistant',
|
||||
|
|
@ -49,11 +61,155 @@ describe('ModelService', () => {
|
|||
};
|
||||
});
|
||||
|
||||
describe('getAvailableChatModels', () => {
|
||||
it('should return only models with chat role', async () => {
|
||||
await modelService.initialize(mockAssistant, mockAuthConfig);
|
||||
describe('State Management', () => {
|
||||
test('should initialize with default model', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
vi.mocked(workos.getModelName).mockReturnValue(null);
|
||||
|
||||
const state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(state).toEqual({
|
||||
llmApi: mockLlmApi,
|
||||
model: mockAssistant.models![0]
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with persisted model if valid', async () => {
|
||||
vi.mocked(workos.getModelName).mockReturnValue('Claude 3');
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
|
||||
const state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(state.model?.name).toBe('Claude 3');
|
||||
expect(state.llmApi).toStrictEqual(mockLlmApi);
|
||||
});
|
||||
|
||||
test('should fall back to default if persisted model not found', async () => {
|
||||
vi.mocked(workos.getModelName).mockReturnValue('Non-existent Model');
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
|
||||
const state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(state.model).toBe(mockAssistant.models![0]);
|
||||
});
|
||||
|
||||
test('should throw error when no chat models available', async () => {
|
||||
mockAssistant.models = [
|
||||
{
|
||||
provider: 'openai',
|
||||
model: 'text-embedding-ada-002',
|
||||
name: 'Ada Embeddings',
|
||||
roles: ['embed'],
|
||||
} as ModelConfig,
|
||||
];
|
||||
|
||||
const models = modelService.getAvailableChatModels();
|
||||
vi.mocked(config.getLlmApi).mockImplementation(() => {
|
||||
throw new Error('No models with the chat role found in the configured assistant');
|
||||
});
|
||||
|
||||
await expect(service.initialize(mockAssistant, mockAuthConfig))
|
||||
.rejects.toThrow('No models with the chat role found in the configured assistant');
|
||||
});
|
||||
});
|
||||
|
||||
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]
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchModel()', () => {
|
||||
test('should switch to a different model by index', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(newLlmApi as any);
|
||||
|
||||
const state = await service.switchModel(1);
|
||||
|
||||
expect(state).toEqual({
|
||||
llmApi: newLlmApi,
|
||||
model: mockAssistant.models![1]
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
||||
test('should throw error for invalid model index', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
await expect(service.switchModel(5)).rejects.toThrow('Invalid model index: 5. Available models: 0-1');
|
||||
await expect(service.switchModel(-1)).rejects.toThrow('Invalid model index: -1. Available models: 0-1');
|
||||
});
|
||||
|
||||
test('should throw error when service not initialized', async () => {
|
||||
await expect(service.switchModel(0)).rejects.toThrow('ModelService not initialized');
|
||||
});
|
||||
|
||||
test('should handle continue-proxy provider specially', async () => {
|
||||
const proxyModel = {
|
||||
provider: 'continue-proxy',
|
||||
name: 'Proxy Model',
|
||||
apiBase: 'https://proxy.continue.dev',
|
||||
apiKeyLocation: 'env.PROXY_KEY',
|
||||
roles: ['chat'],
|
||||
} as ModelConfig;
|
||||
|
||||
mockAssistant.models = [proxyModel];
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, proxyModel]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
vi.mocked(workos.getAccessToken).mockReturnValue('proxy-token');
|
||||
vi.mocked(workos.getOrganizationId).mockReturnValue('org-123');
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
|
||||
await service.switchModel(0);
|
||||
|
||||
expect(vi.mocked(openaiAdapters.constructLlmApi)).toHaveBeenCalledWith({
|
||||
provider: 'continue-proxy',
|
||||
apiBase: 'https://proxy.continue.dev',
|
||||
apiKey: 'proxy-token',
|
||||
env: {
|
||||
apiKeyLocation: 'env.PROXY_KEY',
|
||||
orgScopeId: 'org-123',
|
||||
proxyUrl: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableChatModels()', () => {
|
||||
test('should return only models with chat role', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const models = service.getAvailableChatModels();
|
||||
|
||||
expect(models).toHaveLength(2);
|
||||
expect(models[0]).toEqual({
|
||||
|
|
@ -67,59 +223,121 @@ describe('ModelService', () => {
|
|||
index: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw error when no chat models available during initialization', async () => {
|
||||
mockAssistant.models = [
|
||||
{
|
||||
provider: 'openai',
|
||||
model: 'text-embedding-ada-002',
|
||||
name: 'Ada Embeddings',
|
||||
roles: ['embed'],
|
||||
} as ModelConfig,
|
||||
];
|
||||
describe('getCurrentModelIndex()', () => {
|
||||
test('should return correct index of current model', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
await expect(modelService.initialize(mockAssistant, mockAuthConfig))
|
||||
.rejects.toThrow('No models with the chat role found in the configured assistant');
|
||||
expect(service.getCurrentModelIndex()).toBe(0);
|
||||
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
await service.switchModel(1);
|
||||
expect(service.getCurrentModelIndex()).toBe(1);
|
||||
});
|
||||
|
||||
test('should return -1 when no model is set', () => {
|
||||
expect(service.getCurrentModelIndex()).toBe(-1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchModel', () => {
|
||||
it('should switch to a different model by index', async () => {
|
||||
await modelService.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const initialModel = modelService.getModelInfo();
|
||||
expect(initialModel?.name).toBe('GPT-4');
|
||||
|
||||
await modelService.switchModel(1);
|
||||
|
||||
const newModel = modelService.getModelInfo();
|
||||
expect(newModel?.name).toBe('Claude 3');
|
||||
describe('getModelIndexByName()', () => {
|
||||
test('should find model by name', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.getModelIndexByName('GPT-4')).toBe(0);
|
||||
expect(service.getModelIndexByName('Claude 3')).toBe(1);
|
||||
expect(service.getModelIndexByName('Non-existent')).toBe(-1);
|
||||
});
|
||||
|
||||
it('should throw error for invalid model index', async () => {
|
||||
await modelService.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
await expect(modelService.switchModel(5)).rejects.toThrow('Invalid model index: 5');
|
||||
await expect(modelService.switchModel(-1)).rejects.toThrow('Invalid model index: -1');
|
||||
});
|
||||
test('should find model by name and provider', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
it('should throw error when service not initialized', async () => {
|
||||
await expect(modelService.switchModel(0)).rejects.toThrow('ModelService not initialized');
|
||||
expect(service.getModelIndexByName('GPT-4', 'openai')).toBe(0);
|
||||
expect(service.getModelIndexByName('GPT-4', 'anthropic')).toBe(-1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCurrentModelIndex', () => {
|
||||
it('should return correct index of current model', async () => {
|
||||
await modelService.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(modelService.getCurrentModelIndex()).toBe(0);
|
||||
|
||||
await modelService.switchModel(1);
|
||||
expect(modelService.getCurrentModelIndex()).toBe(1);
|
||||
describe('getModelInfo()', () => {
|
||||
test('should return current model info', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.getModelInfo()).toEqual({
|
||||
provider: 'openai',
|
||||
name: 'GPT-4'
|
||||
});
|
||||
});
|
||||
|
||||
it('should return -1 when no model is set', () => {
|
||||
expect(modelService.getCurrentModelIndex()).toBe(-1);
|
||||
test('should return null when no model set', () => {
|
||||
expect(service.getModelInfo()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isReady()', () => {
|
||||
test('should return false when not initialized', () => {
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test('should return true when initialized with model and llmApi', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false if llmApi is null', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([null as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDependencies()', () => {
|
||||
test('should declare auth and config dependencies', () => {
|
||||
expect(service.getDependencies()).toEqual(['auth', 'config']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
test('should emit stateChanged on model switch', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
|
||||
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(newLlmApi as any);
|
||||
await service.switchModel(1);
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
model: mockAssistant.models![1],
|
||||
llmApi: newLlmApi
|
||||
}),
|
||||
expect.objectContaining({
|
||||
model: mockAssistant.models![0],
|
||||
llmApi: mockLlmApi
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit error on switch failure', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const errorListener = vi.fn();
|
||||
service.on('error', errorListener);
|
||||
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(null as any);
|
||||
|
||||
await expect(service.switchModel(1)).rejects.toThrow('Failed to initialize LLM');
|
||||
expect(errorListener).toHaveBeenCalledWith(expect.any(Error));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,84 +1,75 @@
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi, constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
|
||||
import { getLlmApi } from '../config.js';
|
||||
import { constructLlmApi, LLMConfig } from "@continuedev/openai-adapters";
|
||||
|
||||
import { AuthConfig, getAccessToken, getOrganizationId, getModelName } from '../auth/workos.js';
|
||||
import logger from '../util/logger.js';
|
||||
import { getLlmApi } from '../config.js';
|
||||
import { logger } from '../util/logger.js';
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from './BaseService.js';
|
||||
import { ModelServiceState } from './types.js';
|
||||
|
||||
/**
|
||||
* Service for managing LLM and model state
|
||||
* Depends on auth config and assistant config
|
||||
*/
|
||||
export class ModelService {
|
||||
private currentState: ModelServiceState = {
|
||||
llmApi: null,
|
||||
model: null
|
||||
};
|
||||
export class ModelService extends BaseService<ModelServiceState> implements ServiceWithDependencies {
|
||||
private availableModels: ModelConfig[] = [];
|
||||
private assistant: AssistantUnrolled | null = null;
|
||||
private authConfig: AuthConfig | null = null;
|
||||
|
||||
constructor() {
|
||||
super('ModelService', {
|
||||
llmApi: null,
|
||||
model: null
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare dependencies on other services
|
||||
*/
|
||||
getDependencies(): string[] {
|
||||
return ['auth', 'config'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the model service
|
||||
*/
|
||||
async initialize(
|
||||
async doInitialize(
|
||||
assistant: AssistantUnrolled,
|
||||
authConfig: AuthConfig
|
||||
): Promise<ModelServiceState> {
|
||||
logger.debug('Initializing ModelService');
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter((model) =>
|
||||
model && model.roles?.includes("chat")
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
try {
|
||||
this.assistant = assistant;
|
||||
this.authConfig = authConfig;
|
||||
this.availableModels = (assistant.models?.filter((model) =>
|
||||
model && model.roles?.includes("chat")
|
||||
) || []) as ModelConfig[];
|
||||
|
||||
// Check if we have a persisted model name and use it if valid
|
||||
const persistedModelName = getModelName(authConfig);
|
||||
if (persistedModelName) {
|
||||
const modelIndex = this.getModelIndexByName(persistedModelName);
|
||||
if (modelIndex !== -1) {
|
||||
// Use the persisted model
|
||||
const state = await this.switchModel(modelIndex);
|
||||
this.currentState = state;
|
||||
} else {
|
||||
// Model name not found, use default model selection
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
this.currentState = {
|
||||
llmApi,
|
||||
model
|
||||
};
|
||||
}
|
||||
// Check if we have a persisted model name and use it if valid
|
||||
const persistedModelName = getModelName(authConfig);
|
||||
if (persistedModelName) {
|
||||
const modelIndex = this.getModelIndexByName(persistedModelName);
|
||||
if (modelIndex !== -1) {
|
||||
// Use the persisted model
|
||||
const state = await this.switchModel(modelIndex);
|
||||
return state;
|
||||
} else {
|
||||
// Use default model selection
|
||||
// Model name not found, use default model selection
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
this.currentState = {
|
||||
return {
|
||||
llmApi,
|
||||
model
|
||||
};
|
||||
}
|
||||
|
||||
logger.debug('ModelService initialized successfully', {
|
||||
modelProvider: this.currentState.model?.provider,
|
||||
modelName: (this.currentState.model as any)?.name || 'unnamed',
|
||||
availableModels: this.availableModels.length
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to initialize ModelService:', error);
|
||||
throw error;
|
||||
} else {
|
||||
// Use default model selection
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
return {
|
||||
llmApi,
|
||||
model
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current model state
|
||||
*/
|
||||
getState(): ModelServiceState {
|
||||
return { ...this.currentState };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the model based on new config or auth changes
|
||||
*/
|
||||
|
|
@ -97,10 +88,10 @@ export class ModelService {
|
|||
|
||||
const [llmApi, model] = getLlmApi(assistant, authConfig);
|
||||
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
llmApi,
|
||||
model
|
||||
};
|
||||
});
|
||||
|
||||
logger.debug('ModelService updated successfully', {
|
||||
modelProvider: model.provider,
|
||||
|
|
@ -108,18 +99,21 @@ export class ModelService {
|
|||
availableModels: this.availableModels.length
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to update ModelService:', error);
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current model is ready for use
|
||||
* Override isReady to check for required state
|
||||
*/
|
||||
isReady(): boolean {
|
||||
return this.currentState.llmApi !== null && this.currentState.model !== null;
|
||||
override isReady(): boolean {
|
||||
return super.isReady() &&
|
||||
this.currentState.llmApi !== null &&
|
||||
this.currentState.model !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -197,19 +191,20 @@ export class ModelService {
|
|||
throw new Error('Failed to initialize LLM with selected model');
|
||||
}
|
||||
|
||||
this.currentState = {
|
||||
this.setState({
|
||||
llmApi,
|
||||
model: selectedModel
|
||||
};
|
||||
});
|
||||
|
||||
logger.debug('Model switched successfully', {
|
||||
modelProvider: selectedModel.provider,
|
||||
modelName: (selectedModel as any).name || 'unnamed'
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
return this.getState();
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to switch model:', error);
|
||||
this.emit('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { describe, expect, test, beforeEach, jest } from '@jest/globals';
|
||||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
|
||||
import { ServiceContainer } from './ServiceContainer.js';
|
||||
|
||||
describe('ServiceContainer', () => {
|
||||
|
|
@ -6,7 +7,7 @@ describe('ServiceContainer', () => {
|
|||
|
||||
beforeEach(() => {
|
||||
container = new ServiceContainer();
|
||||
jest.clearAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Dependency Cascade Reloading', () => {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import logger from '../util/logger.js';
|
||||
import { ServiceResult, ServiceState, ServiceEvents } from './types.js';
|
||||
|
||||
import { logger } from '../util/logger.js';
|
||||
|
||||
import { ServiceResult, ServiceState } from './types.js';
|
||||
|
||||
/**
|
||||
* Central service container that manages service lifecycle and dependencies
|
||||
|
|
@ -28,12 +30,15 @@ export class ServiceContainer extends EventEmitter {
|
|||
this.factories.set(serviceName, factory);
|
||||
this.dependencies.set(serviceName, deps);
|
||||
|
||||
// Initialize with idle state
|
||||
this.services.set(serviceName, {
|
||||
value: null,
|
||||
state: 'idle',
|
||||
error: null
|
||||
});
|
||||
// Only initialize with idle state if the service doesn't already exist
|
||||
// This prevents overwriting services that were registered with registerValue
|
||||
if (!this.services.has(serviceName)) {
|
||||
this.services.set(serviceName, {
|
||||
value: null,
|
||||
state: 'idle',
|
||||
error: null
|
||||
});
|
||||
}
|
||||
|
||||
logger.debug(`Registered service: ${serviceName}`, { dependencies: deps });
|
||||
}
|
||||
|
|
@ -57,7 +62,11 @@ export class ServiceContainer extends EventEmitter {
|
|||
// Emit ready event
|
||||
this.emit(`${serviceName}:ready`, value);
|
||||
|
||||
logger.debug(`Registered service with immediate value: ${serviceName}`);
|
||||
logger.debug(`Registered service with immediate value: ${serviceName}`, {
|
||||
state: 'ready',
|
||||
hasValue: value !== null,
|
||||
serviceMapSize: this.services.size
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -230,6 +239,29 @@ export class ServiceContainer extends EventEmitter {
|
|||
return result?.state === 'loading';
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all registered services
|
||||
* This eagerly loads all services rather than waiting for them to be requested
|
||||
*/
|
||||
async initializeAll(): Promise<void> {
|
||||
logger.debug('Initializing all registered services');
|
||||
|
||||
// Get all registered service names
|
||||
const serviceNames = Array.from(this.factories.keys());
|
||||
|
||||
// Load all services in parallel (dependencies will be handled by load())
|
||||
await Promise.all(
|
||||
serviceNames.map(name =>
|
||||
this.load(name).catch(error => {
|
||||
logger.error(`Failed to initialize service ${name}:`, error);
|
||||
// Don't throw - let individual services fail without breaking others
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
logger.debug('All services initialization complete', this.getServiceStates());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all service states (for debugging)
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import React, { createContext, useContext } from 'react';
|
||||
|
||||
import { ServiceContainer } from './ServiceContainer.js';
|
||||
|
||||
import { serviceContainer as defaultContainer } from './index.js';
|
||||
|
||||
const ServiceContainerContext = createContext<ServiceContainer>(defaultContainer);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { PermissionMode } from "../permissions/types.js";
|
||||
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
describe("ToolPermissionService - Debug Tool Permissions", () => {
|
||||
|
|
@ -24,14 +26,13 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
// console.log(`${index + 1}. tool: "${policy.tool}", permission: "${policy.permission}"`);
|
||||
// });
|
||||
|
||||
const writeFilePolicy = policies.find((p) => p.tool === "write_file");
|
||||
const writePolicy = policies.find((p) => p.tool === "Write");
|
||||
const wildcardPolicy = policies.find((p) => p.tool === "*");
|
||||
|
||||
if (mode === "plan") {
|
||||
// Plan mode should explicitly exclude write_file
|
||||
expect(writeFilePolicy?.permission).toBe("exclude");
|
||||
console.log(`✓ write_file tool correctly excluded in plan mode`);
|
||||
// Plan mode should explicitly exclude Write
|
||||
expect(writePolicy?.permission).toBe("exclude");
|
||||
console.log(`✓ Write tool correctly excluded in plan mode`);
|
||||
} else if (mode === "auto") {
|
||||
// Auto mode should allow everything
|
||||
expect(wildcardPolicy?.permission).toBe("allow");
|
||||
|
|
@ -39,8 +40,8 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
} else {
|
||||
// Normal mode behavior depends on user config
|
||||
console.log(
|
||||
`Normal mode - write_file policy: ${
|
||||
writeFilePolicy?.permission || "none"
|
||||
`Normal mode - Write policy: ${
|
||||
writePolicy?.permission || "none"
|
||||
}`
|
||||
);
|
||||
}
|
||||
|
|
@ -49,9 +50,9 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
it(`should check tool resolution order in ${mode} mode`, () => {
|
||||
const policies = service.getPermissions().policies;
|
||||
|
||||
// Find all policies that could affect write_file tool
|
||||
// Find all policies that could affect Write tool
|
||||
const writeRelevantPolicies = policies.filter(
|
||||
(p) => p.tool === "write_file" || p.tool === "Write" || p.tool === "*"
|
||||
(p) => p.tool === "Write" || p.tool === "*"
|
||||
);
|
||||
|
||||
console.log(
|
||||
|
|
@ -66,8 +67,8 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
});
|
||||
|
||||
if (mode === "plan") {
|
||||
// Should have write_file exclude policy BEFORE any wildcard
|
||||
const writeIndex = policies.findIndex((p) => p.tool === "write_file");
|
||||
// Should have Write exclude policy BEFORE any wildcard
|
||||
const writeIndex = policies.findIndex((p) => p.tool === "Write");
|
||||
const wildcardIndex = policies.findIndex((p) => p.tool === "*");
|
||||
|
||||
expect(writeIndex).toBeGreaterThanOrEqual(0);
|
||||
|
|
@ -110,7 +111,7 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
);
|
||||
});
|
||||
|
||||
const writeFilePolicy = policies.find((p) => p.tool === "write_file");
|
||||
expect(writeFilePolicy?.permission).toBe("exclude");
|
||||
const writePolicy = policies.find((p) => p.tool === "Write");
|
||||
expect(writePolicy?.permission).toBe("exclude");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { DEFAULT_TOOL_POLICIES } from "../permissions/defaultPolicies.js";
|
||||
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
describe("ToolPermissionService E2E", () => {
|
||||
|
|
@ -80,7 +80,9 @@ describe("ToolPermissionService E2E", () => {
|
|||
const state = service.getState();
|
||||
const permissions = service.getPermissions();
|
||||
|
||||
expect(state.permissions).toBe(permissions);
|
||||
// getState() returns a shallow copy, so nested objects are the same reference
|
||||
expect(state.permissions).toEqual(permissions);
|
||||
expect(state.permissions).toBe(permissions); // Same reference for nested objects
|
||||
expect(state.permissions.policies[0]).toEqual({ tool: "test_tool", permission: "exclude" });
|
||||
});
|
||||
|
||||
|
|
@ -95,10 +97,10 @@ describe("ToolPermissionService E2E", () => {
|
|||
|
||||
const results = await Promise.all(promises);
|
||||
|
||||
// All should return the same reference
|
||||
// All should return the same value
|
||||
const firstResult = results[0];
|
||||
results.forEach(result => {
|
||||
expect(result).toBe(firstResult);
|
||||
expect(result).toStrictEqual(firstResult);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { beforeEach, describe, expect, it } from '@jest/globals';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { ToolPermissionService } from './ToolPermissionService.js';
|
||||
import { PermissionMode } from '../permissions/types.js';
|
||||
|
||||
describe('ToolPermissionService - Mode Functionality', () => {
|
||||
let service: ToolPermissionService;
|
||||
|
|
@ -63,8 +63,8 @@ describe('ToolPermissionService - Mode Functionality', () => {
|
|||
|
||||
// Plan mode should have write exclusions and read allowances
|
||||
const planPolicies = planState.permissions.policies;
|
||||
expect(planPolicies.some(p => p.tool === 'write_file' && p.permission === 'exclude')).toBe(true);
|
||||
expect(planPolicies.some(p => p.tool === 'read_file' && p.permission === 'allow')).toBe(true);
|
||||
expect(planPolicies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
|
||||
expect(planPolicies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -90,7 +90,7 @@ describe('ToolPermissionService - Mode Functionality', () => {
|
|||
const planPolicies = service.getPermissions().policies;
|
||||
|
||||
expect(planPolicies).not.toEqual(normalPolicies);
|
||||
expect(planPolicies.some(p => p.tool === 'write_file' && p.permission === 'exclude')).toBe(true);
|
||||
expect(planPolicies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
|
||||
});
|
||||
|
||||
it('should use absolute override for plan mode (ignore non-mode policies)', () => {
|
||||
|
|
@ -107,9 +107,9 @@ describe('ToolPermissionService - Mode Functionality', () => {
|
|||
const newPolicies = service.getPermissions().policies;
|
||||
|
||||
// Plan mode should use ONLY mode policies (absolute override)
|
||||
// Should contain write_file exclude policy for plan mode
|
||||
const writeFilePolicy = newPolicies.find(p => p.tool === 'write_file');
|
||||
expect(writeFilePolicy?.permission).toBe('exclude');
|
||||
// Should contain Write exclude policy for plan mode
|
||||
const writePolicy = newPolicies.find(p => p.tool === 'Write');
|
||||
expect(writePolicy?.permission).toBe('exclude');
|
||||
|
||||
// Should not contain any user-defined policies from the initial setup
|
||||
const userAllowPolicy = newPolicies.find(p => p.tool === 'allowedTool');
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { describe, it, expect, beforeEach } from '@jest/globals';
|
||||
import { ToolPermissionService } from './ToolPermissionService.js';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
|
||||
import { checkToolPermission } from '../permissions/permissionChecker.js';
|
||||
|
||||
import { ToolPermissionService } from './ToolPermissionService.js';
|
||||
|
||||
describe('ToolPermissionService - Real Tool Permission Test', () => {
|
||||
let service: ToolPermissionService;
|
||||
|
||||
|
|
@ -14,63 +16,63 @@ describe('ToolPermissionService - Real Tool Permission Test', () => {
|
|||
service.initializeSync({ mode: 'plan' });
|
||||
});
|
||||
|
||||
it('should deny write_file tool in plan mode', () => {
|
||||
it('should deny Write tool in plan mode', () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'write_file',
|
||||
name: 'Write',
|
||||
arguments: { path: 'test.txt', content: 'test' }
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
console.log(`write_file permission check result:`, result);
|
||||
console.log(`Write permission check result:`, result);
|
||||
expect(result.permission).toBe('exclude');
|
||||
});
|
||||
|
||||
it('should deny search_and_replace_in_file tool in plan mode', () => {
|
||||
it('should deny Edit tool in plan mode', () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'search_and_replace_in_file',
|
||||
name: 'Edit',
|
||||
arguments: { path: 'test.txt', old_str: 'old', new_str: 'new' }
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
console.log(`search_and_replace_in_file permission check result:`, result);
|
||||
console.log(`Edit permission check result:`, result);
|
||||
expect(result.permission).toBe('exclude');
|
||||
});
|
||||
|
||||
it('should deny run_terminal_command tool in plan mode', () => {
|
||||
it('should deny Bash tool in plan mode', () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'run_terminal_command',
|
||||
name: 'Bash',
|
||||
arguments: { command: 'ls' }
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
console.log(`run_terminal_command permission check result:`, result);
|
||||
console.log(`Bash permission check result:`, result);
|
||||
expect(result.permission).toBe('exclude');
|
||||
});
|
||||
|
||||
it('should allow read_file tool in plan mode', () => {
|
||||
it('should allow Read tool in plan mode', () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'read_file',
|
||||
name: 'Read',
|
||||
arguments: { path: 'test.txt' }
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
console.log(`read_file permission check result:`, result);
|
||||
console.log(`Read permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
});
|
||||
|
||||
it('should allow list_files tool in plan mode', () => {
|
||||
it('should allow List tool in plan mode', () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'list_files',
|
||||
name: 'List',
|
||||
arguments: { path: '.' }
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
console.log(`list_files permission check result:`, result);
|
||||
console.log(`List permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
});
|
||||
|
||||
|
|
@ -92,27 +94,27 @@ describe('ToolPermissionService - Real Tool Permission Test', () => {
|
|||
service.initializeSync({ mode: 'auto' });
|
||||
});
|
||||
|
||||
it('should allow write_file tool in auto mode', () => {
|
||||
it('should allow Write tool in auto mode', () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'write_file',
|
||||
name: 'Write',
|
||||
arguments: { path: 'test.txt', content: 'test' }
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
console.log(`Auto mode write_file permission check result:`, result);
|
||||
console.log(`Auto mode Write permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
});
|
||||
|
||||
it('should allow run_terminal_command tool in auto mode', () => {
|
||||
it('should allow Bash tool in auto mode', () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'run_terminal_command',
|
||||
name: 'Bash',
|
||||
arguments: { command: 'ls' }
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
console.log(`Auto mode run_terminal_command permission check result:`, result);
|
||||
console.log(`Auto mode Bash permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
});
|
||||
|
||||
|
|
@ -131,20 +133,20 @@ describe('ToolPermissionService - Real Tool Permission Test', () => {
|
|||
|
||||
describe('Mode Override Test', () => {
|
||||
it('should override user permissions when switching to plan mode', () => {
|
||||
// Start with user explicitly allowing write_file
|
||||
// Start with user explicitly allowing Write
|
||||
service.initializeSync({
|
||||
allow: ['write_file'],
|
||||
allow: ['Write'],
|
||||
mode: 'normal'
|
||||
});
|
||||
|
||||
// Verify write_file is allowed in normal mode
|
||||
// Verify Write is allowed in normal mode
|
||||
let permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'write_file',
|
||||
name: 'Write',
|
||||
arguments: { path: 'test.txt', content: 'test' }
|
||||
};
|
||||
let result = checkToolPermission(toolCall, permissions);
|
||||
console.log(`Normal mode with user allow - write_file result:`, result);
|
||||
console.log(`Normal mode with user allow - Write result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
|
||||
// Switch to plan mode - should OVERRIDE user config completely
|
||||
|
|
|
|||
346
src/services/ToolPermissionService.test.ts
Normal file
346
src/services/ToolPermissionService.test.ts
Normal file
|
|
@ -0,0 +1,346 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
|
||||
// Mock modules
|
||||
vi.mock('../permissions/permissionsYamlLoader.js');
|
||||
vi.mock('../permissions/precedenceResolver.js');
|
||||
|
||||
import * as precedenceResolver from '../permissions/precedenceResolver.js';
|
||||
import { ToolPermissionPolicy } from '../permissions/types.js';
|
||||
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
describe("ToolPermissionService", () => {
|
||||
let service: ToolPermissionService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new ToolPermissionService();
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
test('should initialize with default state', async () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([]);
|
||||
|
||||
const state = await service.initialize();
|
||||
|
||||
expect(state).toEqual({
|
||||
permissions: { policies: [] },
|
||||
currentMode: 'normal',
|
||||
isHeadless: false,
|
||||
modePolicyCount: 0
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with runtime overrides', async () => {
|
||||
const mockPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: 'TestTool3', permission: 'exclude' },
|
||||
{ tool: 'TestTool2', permission: 'ask' },
|
||||
{ tool: 'TestTool1', permission: 'allow' }
|
||||
];
|
||||
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(mockPolicies);
|
||||
|
||||
const overrides = {
|
||||
allow: ["TestTool1"],
|
||||
ask: ["TestTool2"],
|
||||
exclude: ["TestTool3"],
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
|
||||
expect(state.permissions.policies).toEqual(mockPolicies);
|
||||
expect(precedenceResolver.resolvePermissionPrecedence).toHaveBeenCalledWith({
|
||||
commandLineFlags: overrides,
|
||||
personalSettings: true,
|
||||
useDefaults: true
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with specific mode', async () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([]);
|
||||
|
||||
const state = await service.initialize({ mode: 'plan' });
|
||||
|
||||
expect(state.currentMode).toBe('plan');
|
||||
// Plan mode should have mode-specific policies
|
||||
expect(state.permissions.policies.length).toBeGreaterThan(0);
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Write',
|
||||
permission: 'exclude'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('initializeSync()', () => {
|
||||
test('should work synchronously for immediate availability', () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: 'Tool1', permission: 'allow' }
|
||||
]);
|
||||
|
||||
const state = service.initializeSync({ allow: ['Tool1'] });
|
||||
|
||||
expect(state).toBeDefined();
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Tool1',
|
||||
permission: 'allow'
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle empty overrides', () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: '*', permission: 'ask' }
|
||||
]);
|
||||
|
||||
const state = service.initializeSync({
|
||||
allow: [],
|
||||
ask: [],
|
||||
exclude: [],
|
||||
});
|
||||
|
||||
expect(state.permissions.policies).toEqual([
|
||||
{ tool: '*', permission: 'ask' }
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Mode-specific policies', () => {
|
||||
test('should generate plan mode policies', () => {
|
||||
const state = service.initializeSync({ mode: 'plan' });
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
// Should exclude write tools
|
||||
expect(policies).toContainEqual({ tool: 'Write', permission: 'exclude' });
|
||||
expect(policies).toContainEqual({ tool: 'Edit', permission: 'exclude' });
|
||||
expect(policies).toContainEqual({ tool: 'Bash', permission: 'exclude' });
|
||||
|
||||
// Should allow read tools
|
||||
expect(policies).toContainEqual({ tool: 'Read', permission: 'allow' });
|
||||
expect(policies).toContainEqual({ tool: 'Grep', permission: 'allow' });
|
||||
expect(policies).toContainEqual({ tool: 'LS', permission: 'allow' });
|
||||
|
||||
// Should have wildcard exclusion at the end
|
||||
expect(policies[policies.length - 1]).toEqual({ tool: '*', permission: 'exclude' });
|
||||
});
|
||||
|
||||
test('should generate auto mode policies', () => {
|
||||
const state = service.initializeSync({ mode: 'auto' });
|
||||
|
||||
expect(state.permissions.policies).toEqual([
|
||||
{ tool: '*', permission: 'allow' }
|
||||
]);
|
||||
});
|
||||
|
||||
test('should generate normal mode policies', () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: 'Tool1', permission: 'allow' },
|
||||
{ tool: 'Tool2', permission: 'ask' }
|
||||
]);
|
||||
|
||||
const state = service.initializeSync({ mode: 'normal' });
|
||||
|
||||
// Normal mode should use user configuration
|
||||
expect(state.permissions.policies).toEqual([
|
||||
{ tool: 'Tool1', permission: 'allow' },
|
||||
{ tool: 'Tool2', permission: 'ask' }
|
||||
]);
|
||||
expect(state.modePolicyCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchMode()', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: 'UserTool1', permission: 'allow' },
|
||||
{ tool: 'UserTool2', permission: 'exclude' }
|
||||
]);
|
||||
});
|
||||
|
||||
test('should switch from normal to plan mode', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
|
||||
const state = service.switchMode('plan');
|
||||
|
||||
expect(state.currentMode).toBe('plan');
|
||||
// Should only have plan mode policies
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Write',
|
||||
permission: 'exclude'
|
||||
});
|
||||
// Should not have user policies
|
||||
expect(state.permissions.policies).not.toContainEqual({
|
||||
tool: 'UserTool1',
|
||||
permission: 'allow'
|
||||
});
|
||||
});
|
||||
|
||||
test('should store original policies when leaving normal mode', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
const originalState = service.getState();
|
||||
|
||||
service.switchMode('plan');
|
||||
const planState = service.getState();
|
||||
|
||||
// Should have stored original policies
|
||||
expect(planState.originalPolicies).toEqual({
|
||||
policies: originalState.permissions.policies
|
||||
});
|
||||
});
|
||||
|
||||
test('should restore original policies when switching back to normal', () => {
|
||||
// Start in normal with user policies
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
const originalPolicies = service.getState().permissions.policies;
|
||||
|
||||
// Switch to plan
|
||||
service.switchMode('plan');
|
||||
|
||||
// Switch back to normal
|
||||
const state = service.switchMode('normal');
|
||||
|
||||
// Should restore original user policies
|
||||
expect(state.permissions.policies).toEqual(originalPolicies);
|
||||
});
|
||||
|
||||
test('should handle multiple mode switches', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
|
||||
// Switch through all modes
|
||||
service.switchMode('plan');
|
||||
expect(service.getCurrentMode()).toBe('plan');
|
||||
|
||||
service.switchMode('auto');
|
||||
expect(service.getCurrentMode()).toBe('auto');
|
||||
expect(service.getState().permissions.policies).toEqual([
|
||||
{ tool: '*', permission: 'allow' }
|
||||
]);
|
||||
|
||||
service.switchMode('normal');
|
||||
expect(service.getCurrentMode()).toBe('normal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updatePermissions()', () => {
|
||||
test('should replace all policies', () => {
|
||||
service.initializeSync();
|
||||
|
||||
const newPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: "NewTool1", permission: "allow" },
|
||||
{ tool: "NewTool2", permission: "ask" },
|
||||
];
|
||||
|
||||
service.updatePermissions(newPolicies);
|
||||
const state = service.getState();
|
||||
|
||||
expect(state.permissions.policies).toEqual(newPolicies);
|
||||
expect(state.modePolicyCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPermissions()', () => {
|
||||
test('should return current permissions', () => {
|
||||
service.initializeSync({ allow: ["TestTool"] });
|
||||
|
||||
const permissions = service.getPermissions();
|
||||
const state = service.getState();
|
||||
|
||||
// getState() returns a deep copy, so references won't match
|
||||
expect(permissions).toEqual(state.permissions);
|
||||
expect(permissions.policies).toEqual(state.permissions.policies);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCurrentMode()', () => {
|
||||
test('should return current mode', () => {
|
||||
service.initializeSync({ mode: 'plan' });
|
||||
expect(service.getCurrentMode()).toBe('plan');
|
||||
|
||||
service.switchMode('auto');
|
||||
expect(service.getCurrentMode()).toBe('auto');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isReady()', () => {
|
||||
test('should always return true (service is always ready)', () => {
|
||||
// ToolPermissionService is designed to be always ready since it uses synchronous initialization
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
test('should return true after initialization', async () => {
|
||||
await service.initialize();
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
test('should emit stateChanged when switching modes', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
|
||||
service.switchMode('plan');
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ currentMode: 'plan' }),
|
||||
expect.objectContaining({ currentMode: 'normal' })
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit stateChanged when updating permissions', () => {
|
||||
service.initializeSync();
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
|
||||
const newPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: 'NewTool', permission: 'allow' }
|
||||
];
|
||||
service.updatePermissions(newPolicies);
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
permissions: { policies: newPolicies }
|
||||
}),
|
||||
expect.any(Object)
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Mode Override Behavior', () => {
|
||||
test('plan mode should completely override user policies', () => {
|
||||
// Initialize with user policies that would allow writes
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: 'Write', permission: 'allow' },
|
||||
{ tool: 'Edit', permission: 'allow' }
|
||||
]);
|
||||
|
||||
const state = service.initializeSync({
|
||||
mode: 'plan',
|
||||
allow: ['Write', 'Edit']
|
||||
});
|
||||
|
||||
// Plan mode should override and exclude these tools
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Write',
|
||||
permission: 'exclude'
|
||||
});
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Edit',
|
||||
permission: 'exclude'
|
||||
});
|
||||
});
|
||||
|
||||
test('auto mode should completely override user policies', () => {
|
||||
// Initialize with user policies that would exclude tools
|
||||
const state = service.initializeSync({
|
||||
mode: 'auto',
|
||||
exclude: ['DangerousTool']
|
||||
});
|
||||
|
||||
// Auto mode should override and allow everything
|
||||
expect(state.permissions.policies).toEqual([
|
||||
{ tool: '*', permission: 'allow' }
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -5,11 +5,14 @@ import {
|
|||
ToolPermissionPolicy,
|
||||
ToolPermissions,
|
||||
} from "../permissions/types.js";
|
||||
import logger from "../util/logger.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService } from "./BaseService.js";
|
||||
|
||||
export interface ToolPermissionServiceState {
|
||||
permissions: ToolPermissions;
|
||||
currentMode: PermissionMode;
|
||||
isHeadless: boolean;
|
||||
modePolicyCount?: number; // Track how many policies are from mode vs other sources
|
||||
originalPolicies?: ToolPermissions; // Store original policies when switching modes
|
||||
}
|
||||
|
|
@ -17,41 +20,36 @@ export interface ToolPermissionServiceState {
|
|||
/**
|
||||
* Service for managing tool permissions with a single source of truth
|
||||
*/
|
||||
export class ToolPermissionService {
|
||||
private state: ToolPermissionServiceState = {
|
||||
permissions: { policies: [] },
|
||||
currentMode: "normal",
|
||||
modePolicyCount: 0,
|
||||
};
|
||||
export class ToolPermissionService extends BaseService<ToolPermissionServiceState> {
|
||||
constructor() {
|
||||
super("ToolPermissionService", {
|
||||
permissions: { policies: [] },
|
||||
currentMode: "normal",
|
||||
isHeadless: false,
|
||||
modePolicyCount: 0,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate mode-specific policies based on the current mode
|
||||
*/
|
||||
private generateModePolicies(): ToolPermissionPolicy[] {
|
||||
switch (this.state.currentMode) {
|
||||
switch (this.currentState.currentMode) {
|
||||
case "plan":
|
||||
// Plan mode: Complete override - exclude all write operations, allow only reads
|
||||
return [
|
||||
// Exclude all write tools with absolute priority (using actual tool names)
|
||||
{ tool: "write_file", permission: "exclude" },
|
||||
{ tool: "edit_file", permission: "exclude" },
|
||||
{ tool: "write_checklist", permission: "allow" },
|
||||
{ tool: "search_and_replace_in_file", permission: "exclude" },
|
||||
{ tool: "run_terminal_command", permission: "exclude" },
|
||||
// Also exclude capitalized versions in case they exist
|
||||
// Exclude all write tools with absolute priority
|
||||
{ tool: "Write", permission: "exclude" },
|
||||
{ tool: "Edit", permission: "exclude" },
|
||||
{ tool: "MultiEdit", permission: "exclude" },
|
||||
{ tool: "NotebookEdit", permission: "exclude" },
|
||||
{ tool: "Bash", permission: "exclude" },
|
||||
// Allow all read tools (using actual tool names)
|
||||
{ tool: "read_file", permission: "allow" },
|
||||
{ tool: "list_files", permission: "allow" },
|
||||
{ tool: "search_code", permission: "allow" },
|
||||
{ tool: "fetch", permission: "allow" },
|
||||
{ tool: "view_diff", permission: "allow" },
|
||||
// Also allow capitalized versions in case they exist
|
||||
// Allow all read tools
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "List", permission: "allow" },
|
||||
{ tool: "Search", permission: "allow" },
|
||||
{ tool: "Fetch", permission: "allow" },
|
||||
{ tool: "Diff", permission: "allow" },
|
||||
{ tool: "Checklist", permission: "allow" },
|
||||
{ tool: "NotebookRead", permission: "allow" },
|
||||
{ tool: "LS", permission: "allow" },
|
||||
|
|
@ -85,15 +83,18 @@ export class ToolPermissionService {
|
|||
ask?: string[];
|
||||
exclude?: string[];
|
||||
mode?: PermissionMode;
|
||||
isHeadless?: boolean;
|
||||
}): ToolPermissionServiceState {
|
||||
logger.debug("Synchronously initializing ToolPermissionService", {
|
||||
hasOverrides: !!runtimeOverrides,
|
||||
mode: runtimeOverrides?.mode,
|
||||
});
|
||||
logger.debug("Synchronously initializing ToolPermissionService");
|
||||
|
||||
// Set mode from overrides or default
|
||||
if (runtimeOverrides?.mode) {
|
||||
this.state.currentMode = runtimeOverrides.mode;
|
||||
this.setState({ currentMode: runtimeOverrides.mode });
|
||||
}
|
||||
|
||||
// Set headless flag from overrides
|
||||
if (runtimeOverrides?.isHeadless !== undefined) {
|
||||
this.setState({ isHeadless: runtimeOverrides.isHeadless });
|
||||
}
|
||||
|
||||
// Generate mode-specific policies first (highest priority)
|
||||
|
|
@ -103,8 +104,8 @@ export class ToolPermissionService {
|
|||
// For normal mode, combine with user configuration
|
||||
let allPolicies: ToolPermissionPolicy[];
|
||||
if (
|
||||
this.state.currentMode === "plan" ||
|
||||
this.state.currentMode === "auto"
|
||||
this.currentState.currentMode === "plan" ||
|
||||
this.currentState.currentMode === "auto"
|
||||
) {
|
||||
// Absolute override: ignore all user configuration
|
||||
allPolicies = modePolicies;
|
||||
|
|
@ -118,23 +119,28 @@ export class ToolPermissionService {
|
|||
allPolicies = [...modePolicies, ...compiledPolicies];
|
||||
}
|
||||
|
||||
this.state = {
|
||||
this.setState({
|
||||
permissions: { policies: allPolicies },
|
||||
currentMode: this.state.currentMode,
|
||||
currentMode: this.currentState.currentMode,
|
||||
isHeadless: this.currentState.isHeadless,
|
||||
modePolicyCount: modePolicies.length,
|
||||
};
|
||||
});
|
||||
|
||||
return this.state;
|
||||
// Mark as initialized since we're bypassing the async initialize flow
|
||||
(this as any).isInitialized = true;
|
||||
|
||||
return this.getState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the tool permission service with runtime overrides (async version)
|
||||
*/
|
||||
async initialize(runtimeOverrides?: {
|
||||
async doInitialize(runtimeOverrides?: {
|
||||
allow?: string[];
|
||||
ask?: string[];
|
||||
exclude?: string[];
|
||||
mode?: PermissionMode;
|
||||
isHeadless?: boolean;
|
||||
}): Promise<ToolPermissionServiceState> {
|
||||
// Ensure permissions.yaml exists before loading
|
||||
await ensurePermissionsYamlExists();
|
||||
|
|
@ -143,29 +149,21 @@ export class ToolPermissionService {
|
|||
return this.initializeSync(runtimeOverrides);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current permission state
|
||||
*/
|
||||
getState(): ToolPermissionServiceState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the compiled permissions
|
||||
*/
|
||||
getPermissions(): ToolPermissions {
|
||||
return this.state.permissions;
|
||||
return this.getState().permissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update permissions (e.g., when config changes)
|
||||
*/
|
||||
updatePermissions(newPolicies: ToolPermissionPolicy[]) {
|
||||
this.state = {
|
||||
this.setState({
|
||||
permissions: { policies: newPolicies },
|
||||
currentMode: this.state.currentMode,
|
||||
modePolicyCount: 0, // Reset since we're replacing all policies
|
||||
};
|
||||
});
|
||||
logger.debug(
|
||||
`Updated tool permissions with ${newPolicies.length} policies`
|
||||
);
|
||||
|
|
@ -176,25 +174,27 @@ export class ToolPermissionService {
|
|||
*/
|
||||
switchMode(newMode: PermissionMode): ToolPermissionServiceState {
|
||||
logger.debug(
|
||||
`Switching from mode '${this.state.currentMode}' to '${newMode}'`
|
||||
`Switching from mode '${this.currentState.currentMode}' to '${newMode}'`
|
||||
);
|
||||
|
||||
// Store original policies when leaving normal mode for the first time
|
||||
if (
|
||||
this.state.currentMode === "normal" &&
|
||||
this.currentState.currentMode === "normal" &&
|
||||
newMode !== "normal" &&
|
||||
!this.state.originalPolicies
|
||||
!this.currentState.originalPolicies
|
||||
) {
|
||||
// Deep copy the policies array to preserve the original state
|
||||
this.state.originalPolicies = {
|
||||
policies: [...this.state.permissions.policies],
|
||||
};
|
||||
this.setState({
|
||||
originalPolicies: {
|
||||
policies: [...this.currentState.permissions.policies],
|
||||
},
|
||||
});
|
||||
logger.debug(
|
||||
`Stored ${this.state.permissions.policies.length} original policies`
|
||||
`Stored ${this.currentState.permissions.policies.length} original policies`
|
||||
);
|
||||
}
|
||||
|
||||
this.state.currentMode = newMode;
|
||||
this.currentState.currentMode = newMode;
|
||||
|
||||
// Regenerate policies with the new mode
|
||||
const modePolicies = this.generateModePolicies();
|
||||
|
|
@ -207,21 +207,23 @@ export class ToolPermissionService {
|
|||
allPolicies = modePolicies;
|
||||
} else {
|
||||
// Normal mode: restore original policies if we have them
|
||||
if (this.state.originalPolicies) {
|
||||
if (this.currentState.originalPolicies) {
|
||||
// Restore the original user policies
|
||||
// When original policies were stored in normal mode, they had 0 mode policies
|
||||
// So we need to slice from the number of mode policies that were active when stored
|
||||
const originalModePolicyCount = 0; // Normal mode has no mode policies
|
||||
const originalNonModePolicies =
|
||||
this.state.originalPolicies.policies.slice(originalModePolicyCount);
|
||||
this.currentState.originalPolicies.policies.slice(
|
||||
originalModePolicyCount
|
||||
);
|
||||
allPolicies = [...modePolicies, ...originalNonModePolicies];
|
||||
logger.debug(
|
||||
`Restored ${originalNonModePolicies.length} original user policies`
|
||||
);
|
||||
} else {
|
||||
// Fallback to existing behavior if no original policies stored
|
||||
const existingPolicies = this.state.permissions.policies;
|
||||
const previousModePolicyCount = this.state.modePolicyCount || 0;
|
||||
const existingPolicies = this.currentState.permissions.policies;
|
||||
const previousModePolicyCount = this.currentState.modePolicyCount || 0;
|
||||
const nonModePolicies =
|
||||
existingPolicies.length > previousModePolicyCount
|
||||
? existingPolicies.slice(previousModePolicyCount)
|
||||
|
|
@ -230,23 +232,36 @@ export class ToolPermissionService {
|
|||
}
|
||||
}
|
||||
|
||||
this.state = {
|
||||
...this.state,
|
||||
this.setState({
|
||||
permissions: { policies: allPolicies },
|
||||
currentMode: newMode,
|
||||
modePolicyCount: modePolicies.length,
|
||||
};
|
||||
});
|
||||
|
||||
logger.debug(
|
||||
`Mode switched to '${newMode}' with ${allPolicies.length} total policies`
|
||||
);
|
||||
return this.state;
|
||||
return this.getState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current permission mode
|
||||
*/
|
||||
getCurrentMode(): PermissionMode {
|
||||
return this.state.currentMode;
|
||||
return this.currentState.currentMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the headless state
|
||||
*/
|
||||
isHeadless(): boolean {
|
||||
return this.currentState.isHeadless;
|
||||
}
|
||||
|
||||
/**
|
||||
* Override isReady to always return true since we initialize synchronously
|
||||
*/
|
||||
override isReady(): boolean {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,8 +53,14 @@ describe("ToolPermissionService unit tests", () => {
|
|||
const state = service.getState();
|
||||
const permissions = service.getPermissions();
|
||||
|
||||
expect(state.permissions).toBe(permissions);
|
||||
expect(state.permissions.policies).toBe(permissions.policies);
|
||||
// getState() returns a shallow copy, getPermissions() returns the same permissions object
|
||||
expect(state.permissions).toEqual(permissions);
|
||||
expect(state.permissions).toBe(permissions); // Same reference with shallow copy
|
||||
|
||||
// Multiple calls to getPermissions() should return the same reference
|
||||
const permissions2 = service.getPermissions();
|
||||
expect(permissions).toEqual(permissions2);
|
||||
expect(permissions).toBe(permissions2); // Same reference
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { ServiceContainer } from './ServiceContainer.js';
|
||||
|
||||
import { initializeServices } from './index.js';
|
||||
import { SERVICE_NAMES } from './types.js';
|
||||
|
||||
describe('Service Circular Dependencies', () => {
|
||||
it('should not have circular dependencies in service setup', async () => {
|
||||
|
|
@ -80,7 +80,7 @@ describe('Service Circular Dependencies', () => {
|
|||
const circularDeps = detectCircularDependencies(serviceDependencies);
|
||||
|
||||
if (circularDeps.length > 0) {
|
||||
fail(`Circular dependency detected: ${circularDeps.join(' -> ')}`);
|
||||
throw new Error(`Circular dependency detected: ${circularDeps.join(' -> ')}`);
|
||||
}
|
||||
|
||||
// Also verify that all services can be theoretically loaded without circular issues
|
||||
|
|
|
|||
61
src/services/index.initialization.test.ts
Normal file
61
src/services/index.initialization.test.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { serviceContainer } from './ServiceContainer.js';
|
||||
import type { ToolPermissionServiceState } from './ToolPermissionService.js';
|
||||
|
||||
import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js';
|
||||
|
||||
describe('Service Initialization', () => {
|
||||
beforeEach(() => {
|
||||
// Clean up service container state
|
||||
const services = [
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
SERVICE_NAMES.AUTH,
|
||||
SERVICE_NAMES.API_CLIENT,
|
||||
SERVICE_NAMES.CONFIG,
|
||||
SERVICE_NAMES.MODEL,
|
||||
SERVICE_NAMES.MCP
|
||||
];
|
||||
|
||||
services.forEach(service => {
|
||||
// Reset service state
|
||||
(serviceContainer as any).services.delete(service);
|
||||
(serviceContainer as any).factories.delete(service);
|
||||
(serviceContainer as any).dependencies.delete(service);
|
||||
});
|
||||
});
|
||||
|
||||
it('should have TOOL_PERMISSIONS service ready after initialization', async () => {
|
||||
// Before initialization, service should not be ready
|
||||
const beforeInit = getServiceSync(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
expect(beforeInit.state).toBe('error'); // Not registered yet
|
||||
|
||||
// Initialize services
|
||||
await initializeServices({
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
mode: 'normal'
|
||||
}
|
||||
});
|
||||
|
||||
// After initialization, service should be ready
|
||||
const afterInit = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
expect(afterInit.state).toBe('ready');
|
||||
expect(afterInit.value).toBeDefined();
|
||||
expect(afterInit.value?.currentMode).toBe('normal');
|
||||
expect(afterInit.value?.isHeadless).toBe(true);
|
||||
});
|
||||
|
||||
it('should have TOOL_PERMISSIONS service ready immediately when accessed early', async () => {
|
||||
await initializeServices({
|
||||
headless: true
|
||||
});
|
||||
|
||||
// Simulate early access like in streamChatResponse
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
|
||||
// Service should be ready, not idle
|
||||
expect(serviceResult.state).toBe('ready');
|
||||
expect(serviceResult.value).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,108 +1,111 @@
|
|||
import { jest } from '@jest/globals';
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { initializeServices } from './index.js';
|
||||
import { modeService } from './ModeService.js';
|
||||
import { modeService } from "./ModeService.js";
|
||||
|
||||
describe('initializeServices', () => {
|
||||
import { initializeServices } from "./index.js";
|
||||
|
||||
describe("initializeServices", () => {
|
||||
let mockModeService: any;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset all mocks
|
||||
jest.clearAllMocks();
|
||||
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Create mock mode service
|
||||
mockModeService = {
|
||||
initialize: jest.fn(),
|
||||
getCurrentMode: jest.fn()
|
||||
initialize: vi.fn(),
|
||||
getCurrentMode: vi.fn(),
|
||||
};
|
||||
|
||||
|
||||
// Set up modeService mock
|
||||
(modeService as any).initialize = mockModeService.initialize;
|
||||
(modeService as any).getCurrentMode = mockModeService.getCurrentMode;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('mode conversion', () => {
|
||||
it('should pass only readonly flag for plan mode', async () => {
|
||||
describe("mode conversion", () => {
|
||||
it("should pass only readonly flag for plan mode", async () => {
|
||||
await initializeServices({
|
||||
toolPermissionOverrides: {
|
||||
mode: 'plan',
|
||||
allow: ['tool1'],
|
||||
ask: ['tool2'],
|
||||
exclude: ['tool3']
|
||||
}
|
||||
mode: "plan",
|
||||
allow: ["tool1"],
|
||||
ask: ["tool2"],
|
||||
exclude: ["tool3"],
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockModeService.initialize).toHaveBeenCalledWith({
|
||||
allow: ['tool1'],
|
||||
ask: ['tool2'],
|
||||
exclude: ['tool3'],
|
||||
readonly: true
|
||||
allow: ["tool1"],
|
||||
ask: ["tool2"],
|
||||
exclude: ["tool3"],
|
||||
readonly: true,
|
||||
// auto should NOT be set
|
||||
});
|
||||
});
|
||||
|
||||
it('should pass only auto flag for auto mode', async () => {
|
||||
it("should pass only auto flag for auto mode", async () => {
|
||||
await initializeServices({
|
||||
toolPermissionOverrides: {
|
||||
mode: 'auto',
|
||||
allow: ['tool1'],
|
||||
ask: ['tool2'],
|
||||
exclude: ['tool3']
|
||||
}
|
||||
mode: "auto",
|
||||
allow: ["tool1"],
|
||||
ask: ["tool2"],
|
||||
exclude: ["tool3"],
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockModeService.initialize).toHaveBeenCalledWith({
|
||||
allow: ['tool1'],
|
||||
ask: ['tool2'],
|
||||
exclude: ['tool3'],
|
||||
auto: true
|
||||
allow: ["tool1"],
|
||||
ask: ["tool2"],
|
||||
exclude: ["tool3"],
|
||||
auto: true,
|
||||
// readonly should NOT be set
|
||||
});
|
||||
});
|
||||
|
||||
it('should pass no mode flags for normal mode', async () => {
|
||||
it("should pass no mode flags for normal mode", async () => {
|
||||
await initializeServices({
|
||||
toolPermissionOverrides: {
|
||||
mode: 'normal',
|
||||
allow: ['tool1'],
|
||||
ask: ['tool2'],
|
||||
exclude: ['tool3']
|
||||
}
|
||||
mode: "normal",
|
||||
allow: ["tool1"],
|
||||
ask: ["tool2"],
|
||||
exclude: ["tool3"],
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockModeService.initialize).toHaveBeenCalledWith({
|
||||
allow: ['tool1'],
|
||||
ask: ['tool2'],
|
||||
exclude: ['tool3']
|
||||
allow: ["tool1"],
|
||||
ask: ["tool2"],
|
||||
exclude: ["tool3"],
|
||||
// Neither readonly nor auto should be set
|
||||
});
|
||||
});
|
||||
|
||||
it('should pass no mode flags when mode is undefined', async () => {
|
||||
it("should pass no mode flags when mode is undefined", async () => {
|
||||
await initializeServices({
|
||||
toolPermissionOverrides: {
|
||||
allow: ['tool1'],
|
||||
ask: ['tool2'],
|
||||
exclude: ['tool3']
|
||||
}
|
||||
allow: ["tool1"],
|
||||
ask: ["tool2"],
|
||||
exclude: ["tool3"],
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockModeService.initialize).toHaveBeenCalledWith({
|
||||
allow: ['tool1'],
|
||||
ask: ['tool2'],
|
||||
exclude: ['tool3']
|
||||
allow: ["tool1"],
|
||||
ask: ["tool2"],
|
||||
exclude: ["tool3"],
|
||||
// Neither readonly nor auto should be set
|
||||
});
|
||||
});
|
||||
|
||||
it('should not call initialize when no toolPermissionOverrides provided', async () => {
|
||||
it("should call initialize with defaults when no toolPermissionOverrides provided", async () => {
|
||||
await initializeServices({});
|
||||
|
||||
expect(mockModeService.initialize).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockModeService.initialize).toHaveBeenCalledWith({
|
||||
isHeadless: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue