Elffuss BraidHub

kikocis/continue public

merge main
Changesetf039cbc5d7e386a971656154f8ad3e2b972231fd24b5fa48ea1d7d304e10b4d3
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-18 17:25 +02:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-07-18 17:25 +02:00
Parentsfd84b2d5fd91, ad83f3cc5301

Browse the files at this changeset

156 files changed

deleted .continue/mcpServers/continue-docs-mcp.yaml +0 −11
@@ -1,11 +0,0 @@
1-name: Continue Documentation MCP
2-version: 0.0.1
3-schema: v1
4-mcpServers:
5- - name: Continue Docs Search
6- type: stdio
7- command: npx
8- args:
9- - mint-mcp
10- - add
11- - continue-docs
modified .github/workflows/pr_checks.yaml +41 −0
@@ -572,6 +572,43 @@
572572 cd packages/config-yaml
573573 npm test
574574
575+ openai-adapters-tests:
576+ needs: install-openai-adapters
577+ runs-on: ubuntu-latest
578+ steps:
579+ - uses: actions/checkout@v4
580+
581+ - uses: actions/setup-node@v4
582+ with:
583+ node-version-file: ".nvmrc"
584+
585+ - uses: actions/cache@v4
586+ with:
587+ path: node_modules
588+ key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
589+
590+ - uses: actions/cache@v4
591+ id: openai-adapters-cache
592+ with:
593+ path: packages/openai-adapters/node_modules
594+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
595+
596+ - name: Run openai-adapters tests
597+ run: |
598+ cd packages/openai-adapters
599+ npm test
600+ env:
601+ IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
602+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
603+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
604+ GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
605+ MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
606+ AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
607+ AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
608+ AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
609+ AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
610+ VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
611+
575612 vscode-get-test-file-matrix:
576613 runs-on: ubuntu-latest
577614 needs: [install-root, install-vscode, install-config-yaml]
@@ -613,6 +650,9 @@
613650 echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
614651 echo "$FILES" >> $GITHUB_OUTPUT
615652 echo "EOF" >> $GITHUB_OUTPUT
653+ env:
654+ # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
655+ GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
616656
617657 - name: Debug Outputs
618658 run: |
@@ -1068,6 +1108,7 @@
10681108 - config-yaml-checks
10691109 - install-config-yaml
10701110 - install-openai-adapters
1111+ - openai-adapters-tests
10711112
10721113 steps:
10731114 - name: Decide whether the needed jobs succeeded or failed
modified .github/workflows/release-config-yaml.yml +16 −0
@@ -6,6 +6,13 @@
66 - main
77 paths:
88 - "packages/config-yaml/**"
9+ - ".github/workflows/release-config-yaml.yml"
10+ - ".github/workflows/reusable-release.yml"
11+
12+permissions:
13+ contents: write
14+ issues: write
15+ pull-requests: write
916
1017 jobs:
1118 release:
@@ -16,3 +23,12 @@
1623 secrets:
1724 SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
1825 SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
26+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
27+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
28+ GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
29+ MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
30+ AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
31+ AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
32+ AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
33+ AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
34+ VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
modified .github/workflows/release-fetch.yml +16 −0
@@ -6,6 +6,13 @@
66 - main
77 paths:
88 - "packages/fetch/**"
9+ - ".github/workflows/release-fetch.yml"
10+ - ".github/workflows/reusable-release.yml"
11+
12+permissions:
13+ contents: write
14+ issues: write
15+ pull-requests: write
916
1017 jobs:
1118 release:
@@ -16,3 +23,12 @@
1623 secrets:
1724 SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
1825 SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
26+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
27+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
28+ GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
29+ MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
30+ AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
31+ AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
32+ AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
33+ AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
34+ VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
modified .github/workflows/release-llm-info.yml +8 −0
@@ -16,3 +16,11 @@
1616 secrets:
1717 SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
1818 SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
19+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
20+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
21+ GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
22+ MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
23+ AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
24+ AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
25+ AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
26+ AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
No newline at the end of the file
modified .github/workflows/release-openai-adapters.yml +16 −0
@@ -6,6 +6,13 @@
66 - main
77 paths:
88 - "packages/openai-adapters/**"
9+ - ".github/workflows/release-openai-adapters.yml"
10+ - ".github/workflows/reusable-release.yml"
11+
12+permissions:
13+ contents: write
14+ issues: write
15+ pull-requests: write
916
1017 jobs:
1118 release:
@@ -16,3 +23,12 @@
1623 secrets:
1724 SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
1825 SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
26+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
27+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
28+ GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
29+ MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
30+ AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
31+ AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
32+ AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
33+ AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
34+ VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
modified .github/workflows/reusable-release.yml +29 −1
@@ -14,6 +14,24 @@
1414 required: true
1515 SEMANTIC_RELEASE_NPM_TOKEN:
1616 required: true
17+ OPENAI_API_KEY:
18+ required: false
19+ ANTHROPIC_API_KEY:
20+ required: false
21+ GEMINI_API_KEY:
22+ required: false
23+ MISTRAL_API_KEY:
24+ required: false
25+ AZURE_OPENAI_API_KEY:
26+ required: false
27+ AZURE_FOUNDRY_CODESTRAL_API_KEY:
28+ required: false
29+ AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY:
30+ required: false
31+ AZURE_OPENAI_GPT41_API_KEY:
32+ required: false
33+ VOYAGE_API_KEY:
34+ required: false
1735
1836 permissions:
1937 contents: write
@@ -46,10 +64,20 @@
4664
4765 - name: Run tests
4866 run: npm test
67+ env:
68+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
69+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
70+ GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
71+ MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
72+ AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
73+ AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
74+ AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
75+ AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
76+ VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
4977
5078 - name: Release
5179 env:
5280 GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
5381 NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
5482 NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
55- run: npx semantic-release
No newline at the end of the file
83+ run: npx semantic-release
modified core/.eslintrc.json +9 −1
@@ -19,5 +19,13 @@
1919 "max-depth": ["error", { "max": 6 }],
2020 "max-nested-callbacks": ["error", { "max": 4 }],
2121 "max-params": ["error", { "max": 8 }]
22- }
22+ },
23+ "overrides": [
24+ {
25+ "files": ["**/*.vitest.ts"],
26+ "rules": {
27+ "max-lines-per-function": "off"
28+ }
29+ }
30+ ]
2331 }
modified core/config/ConfigHandler.ts +99 −44
@@ -11,12 +11,14 @@
1111 } from "../index.js";
1212 import { GlobalContext } from "../util/GlobalContext.js";
1313
14+import EventEmitter from "node:events";
1415 import {
1516 AuthType,
1617 ControlPlaneSessionInfo,
1718 } from "../control-plane/AuthTypes.js";
1819 import { getControlPlaneEnv } from "../control-plane/env.js";
1920 import { logger } from "../util/logger.js";
21+import { Telemetry } from "../util/posthog.js";
2022 import {
2123 ASSISTANTS,
2224 getAllDotContinueDefinitionFiles,
@@ -44,6 +46,16 @@
4446 private organizations: OrgWithProfiles[] = [];
4547 currentProfile: ProfileLifecycleManager | null;
4648 currentOrg: OrgWithProfiles;
49+ totalConfigLoads: number = 0;
50+
51+ public isInitialized: Promise<void>;
52+ private initter: EventEmitter;
53+
54+ cascadeAbortController: AbortController;
55+ private abortCascade() {
56+ this.cascadeAbortController.abort();
57+ this.cascadeAbortController = new AbortController();
58+ }
4759
4860 constructor(
4961 private readonly ide: IDE,
@@ -53,9 +65,11 @@
5365 ) {
5466 this.ide = ide;
5567 this.ideSettingsPromise = ideSettingsPromise;
68+
5669 this.controlPlaneClient = new ControlPlaneClient(
5770 sessionInfoPromise,
5871 ideSettingsPromise,
72+ this.ide.getIdeInfo(),
5973 );
6074
6175 // This profile manager will always be available
@@ -80,7 +94,13 @@
8094 this.currentOrg = personalOrg;
8195 this.organizations = [personalOrg];
8296
83- void this.cascadeInit();
97+ this.initter = new EventEmitter();
98+ this.isInitialized = new Promise((resolve) => {
99+ this.initter.on("init", resolve);
100+ });
101+
102+ this.cascadeAbortController = new AbortController();
103+ void this.cascadeInit("Config handler initialization");
84104 }
85105
86106 private workspaceDirs: string[] | null = null;
@@ -96,54 +116,71 @@
96116 return `${workspaceId}:::${orgId}`;
97117 }
98118
99- private async cascadeInit() {
119+ private async cascadeInit(reason: string) {
120+ const signal = this.cascadeAbortController.signal;
100121 this.workspaceDirs = null; // forces workspace dirs reload
101122
102- const orgs = await this.getOrgs();
103-
104- // Figure out selected org
105- const workspaceId = await this.getWorkspaceId();
106- const selectedOrgs =
107- this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
108- const currentSelection = selectedOrgs[workspaceId];
123+ try {
124+ const orgs = await this.getOrgs();
109125
110- const firstNonPersonal = orgs.find(
111- (org) => org.id !== this.PERSONAL_ORG_DESC.id,
112- );
113- const fallback = firstNonPersonal ?? orgs[0];
114- // note, ignoring case of zero orgs since should never happen
126+ // Figure out selected org
127+ const workspaceId = await this.getWorkspaceId();
128+ const selectedOrgs =
129+ this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
130+ const currentSelection = selectedOrgs[workspaceId];
115131
116- let selectedOrg: OrgWithProfiles;
117- if (!currentSelection) {
118- selectedOrg = fallback;
119- } else {
120- const match = orgs.find((org) => org.id === currentSelection);
121- if (match) {
122- selectedOrg = match;
123- } else {
132+ const firstNonPersonal = orgs.find(
133+ (org) => org.id !== this.PERSONAL_ORG_DESC.id,
134+ );
135+ const fallback = firstNonPersonal ?? orgs[0];
136+ // note, ignoring case of zero orgs since should never happen
137+
138+ let selectedOrg: OrgWithProfiles;
139+ if (!currentSelection) {
124140 selectedOrg = fallback;
141+ } else {
142+ const match = orgs.find((org) => org.id === currentSelection);
143+ if (match) {
144+ selectedOrg = match;
145+ } else {
146+ selectedOrg = fallback;
147+ }
125148 }
126- }
127149
128- this.globalContext.update("lastSelectedOrgIdForWorkspace", {
129- ...selectedOrgs,
130- [workspaceId]: selectedOrg.id,
131- });
150+ if (signal.aborted) {
151+ return; // local only case, no`fetch to throw abort error
152+ }
153+ this.initter.emit("init");
154+
155+ this.globalContext.update("lastSelectedOrgIdForWorkspace", {
156+ ...selectedOrgs,
157+ [workspaceId]: selectedOrg.id,
158+ });
132159
133- this.organizations = orgs;
134- this.currentOrg = selectedOrg;
135- this.currentProfile = selectedOrg.currentProfile;
136- await this.reloadConfig();
160+ this.organizations = orgs;
161+ this.currentOrg = selectedOrg;
162+ this.currentProfile = selectedOrg.currentProfile;
163+
164+ await this.reloadConfig(reason);
165+ } catch (e) {
166+ if (e instanceof Error && e.message.includes("AbortError")) {
167+ return;
168+ } else {
169+ this.initter.emit("init"); // Error case counts for initialization
170+ throw e;
171+ }
172+ }
137173 }
138174
139175 private async getOrgs(): Promise<OrgWithProfiles[]> {
140- if (await this.controlPlaneClient.isSignedIn()) {
176+ const isSignedIn = await this.controlPlaneClient.isSignedIn();
177+ if (isSignedIn) {
141178 const orgDescs = await this.controlPlaneClient.listOrganizations();
142- const personalHubOrg = await this.getPersonalHubOrg();
143- const hubOrgs = await Promise.all(
144- orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
145- );
146- return [...hubOrgs, personalHubOrg];
179+ const orgs = await Promise.all([
180+ this.getPersonalHubOrg(),
181+ ...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
182+ ]);
183+ return orgs;
147184 } else {
148185 return [await this.getLocalOrg()];
149186 }
@@ -312,13 +349,14 @@
312349 // Should not be used internally
313350 //////////////////
314351 async refreshAll() {
315- await this.cascadeInit();
352+ await this.cascadeInit("External refresh all");
316353 }
317354
318355 // Ide settings change: refresh session and cascade refresh from the top
319356 async updateIdeSettings(ideSettings: IdeSettings) {
320357 this.ideSettingsPromise = Promise.resolve(ideSettings);
321- await this.cascadeInit();
358+ this.abortCascade();
359+ await this.cascadeInit("IDE settings update");
322360 }
323361
324362 // Session change: refresh session and cascade refresh from the top
@@ -328,8 +366,10 @@
328366 this.controlPlaneClient = new ControlPlaneClient(
329367 Promise.resolve(sessionInfo),
330368 this.ideSettingsPromise,
369+ this.ide.getIdeInfo(),
331370 );
332- await this.cascadeInit();
371+ this.abortCascade();
372+ await this.cascadeInit("Control plane session info update");
333373 }
334374
335375 // Org id: check id validity, save selection, switch and reload
@@ -356,7 +396,7 @@
356396 await this.setSelectedProfileId(profileId);
357397 } else {
358398 this.currentProfile = org.currentProfile;
359- await this.reloadConfig();
399+ await this.reloadConfig("Selected org changed");
360400 }
361401 }
362402
@@ -384,14 +424,17 @@
384424 });
385425
386426 this.currentProfile = profile;
387- await this.reloadConfig();
427+ await this.reloadConfig("Selected profile changed");
388428 }
389429
390430 // Bottom level of cascade: refresh the current profile
391431 // IMPORTANT - must always refresh when switching profiles
392432 // Because of e.g. MCP singleton and docs service using things from config
393433 // Could improve this
394- async reloadConfig() {
434+ async reloadConfig(reason: string) {
435+ const startTime = performance.now();
436+ this.totalConfigLoads += 1;
437+ // console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
395438 if (!this.currentProfile) {
396439 return {
397440 config: undefined,
@@ -415,6 +458,17 @@
415458 await this.currentProfile.reloadConfig(this.additionalContextProviders);
416459
417460 this.notifyConfigListeners({ config, errors, configLoadInterrupted });
461+
462+ // Track config loading telemetry
463+ const endTime = performance.now();
464+ const duration = endTime - startTime;
465+ void Telemetry.capture("config_reload", {
466+ duration,
467+ reason,
468+ totalConfigLoads: this.totalConfigLoads,
469+ configLoadInterrupted,
470+ });
471+
418472 return { config, errors, configLoadInterrupted };
419473 }
420474
@@ -457,6 +511,7 @@
457511 configLoadInterrupted: true,
458512 };
459513 }
514+ await this.isInitialized;
460515 const config = await this.currentProfile.loadConfig(
461516 this.additionalContextProviders,
462517 );
@@ -487,7 +542,7 @@
487542 private additionalContextProviders: IContextProvider[] = [];
488543 registerCustomContextProvider(contextProvider: IContextProvider) {
489544 this.additionalContextProviders.push(contextProvider);
490- void this.reloadConfig();
545+ void this.reloadConfig("Custom context provider registered");
491546 }
492547 /**
493548 * Retrieves the titles of additional context providers that are of type "submenu".
modified core/config/ConfigHandler.vitest.ts +2 −2
@@ -32,7 +32,7 @@
3232 }`;
3333 fs.writeFileSync(getConfigTsPath(), configTs);
3434 await new Promise((resolve) => setTimeout(resolve, 1000));
35- const config = await testConfigHandler.reloadConfig();
35+ const config = await testConfigHandler.reloadConfig("test");
3636 /**
3737 * @ts-ignore is applied because this test is skipped
3838 */
@@ -45,7 +45,7 @@
4545 path.join(TEST_DIR, ".continuerc.json"),
4646 JSON.stringify({ systemMessage: "SYSTEM2" }),
4747 );
48- const config = await testConfigHandler.reloadConfig();
48+ const config = await testConfigHandler.reloadConfig("test");
4949 /**
5050 * @ts-ignore is applied because this test is skipped
5151 */
modified core/config/markdown/loadCodebaseRules.ts +42 −1
@@ -7,6 +7,43 @@
77 import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
88 import { getUriPathBasename } from "../../util/uri";
99
10+export class CodebaseRulesCache {
11+ private static instance: CodebaseRulesCache | null = null;
12+ private constructor() {}
13+
14+ public static getInstance(): CodebaseRulesCache {
15+ if (CodebaseRulesCache.instance === null) {
16+ CodebaseRulesCache.instance = new CodebaseRulesCache();
17+ }
18+ return CodebaseRulesCache.instance;
19+ }
20+ rules: RuleWithSource[] = [];
21+ errors: ConfigValidationError[] = [];
22+ async refresh(ide: IDE) {
23+ const { rules, errors } = await loadCodebaseRules(ide);
24+ this.rules = rules;
25+ this.errors = errors;
26+ }
27+ async update(ide: IDE, uri: string) {
28+ const content = await ide.readFile(uri);
29+ const rule = markdownToRule(content, { uriType: "file", filePath: uri });
30+ const ruleWithSource: RuleWithSource = {
31+ ...rule,
32+ source: "colocated-markdown",
33+ ruleFile: uri,
34+ };
35+ const matchIdx = this.rules.findIndex((r) => r.ruleFile === uri);
36+ if (matchIdx === -1) {
37+ this.rules.push(ruleWithSource);
38+ } else {
39+ this.rules[matchIdx] = ruleWithSource;
40+ }
41+ }
42+ remove(uri: string) {
43+ this.rules = this.rules.filter((r) => r.ruleFile !== uri);
44+ }
45+}
46+
1047 /**
1148 * Loads rules from rules.md files colocated in the codebase
1249 */
@@ -33,7 +70,11 @@
3370 const content = await ide.readFile(filePath);
3471 const rule = markdownToRule(content, { uriType: "file", filePath });
3572
36- rules.push({ ...rule, source: "rules-block", ruleFile: filePath });
73+ rules.push({
74+ ...rule,
75+ source: "colocated-markdown",
76+ ruleFile: filePath,
77+ });
3778 } catch (e) {
3879 errors.push({
3980 fatal: false,
modified core/config/markdown/loadCodebaseRules.vitest.ts +4 −4
@@ -45,27 +45,27 @@
4545 "src/rules.md": {
4646 name: "General Rules",
4747 rule: "Follow coding standards",
48- source: "rules-block",
48+ source: "colocated-markdown",
4949 ruleFile: "src/rules.md",
5050 },
5151 "src/redux/rules.md": {
5252 name: "Redux Rules",
5353 rule: "Use Redux Toolkit",
5454 globs: "**/*.{ts,tsx}",
55- source: "rules-block",
55+ source: "colocated-markdown",
5656 ruleFile: "src/redux/rules.md",
5757 },
5858 "src/components/rules.md": {
5959 name: "Component Rules",
6060 rule: "Use functional components",
6161 globs: ["**/*.tsx", "**/*.jsx"],
62- source: "rules-block",
62+ source: "colocated-markdown",
6363 ruleFile: "src/components/rules.md",
6464 },
6565 ".continue/rules.md": {
6666 name: "Global Rules",
6767 rule: "Follow project guidelines",
68- source: "rules-block",
68+ source: "colocated-markdown",
6969 ruleFile: ".continue/rules.md",
7070 },
7171 };
modified core/config/markdown/ruleCollocationApplication.vitest.ts +9 −9
@@ -16,7 +16,7 @@
1616 {
1717 name: "Root Rule",
1818 rule: "Follow project standards",
19- source: "rules-block",
19+ source: "colocated-markdown",
2020 ruleFile: ".continue/rules.md",
2121 },
2222
@@ -24,7 +24,7 @@
2424 {
2525 name: "React Components Rule",
2626 rule: "Use functional components with hooks",
27- source: "rules-block",
27+ source: "colocated-markdown",
2828 ruleFile: "src/components/rules.md",
2929 // No explicit globs - should implicitly only apply to files in that directory
3030 },
@@ -34,7 +34,7 @@
3434 name: "Redux Rule",
3535 rule: "Use Redux Toolkit for state management",
3636 globs: "src/redux/**/*.{ts,tsx}",
37- source: "rules-block",
37+ source: "colocated-markdown",
3838 ruleFile: "src/redux/rules.md",
3939 },
4040
@@ -43,7 +43,7 @@
4343 name: "TypeScript Components Rule",
4444 rule: "Use TypeScript with React components",
4545 globs: "**/*.tsx", // Only apply to .tsx files
46- source: "rules-block",
46+ source: "colocated-markdown",
4747 ruleFile: "src/components/rules.md",
4848 },
4949
@@ -52,7 +52,7 @@
5252 name: "API Utils Rule",
5353 rule: "Follow API utility conventions",
5454 globs: "**/*.ts", // Only TypeScript files in this directory
55- source: "rules-block",
55+ source: "colocated-markdown",
5656 ruleFile: "src/utils/api/rules.md",
5757 },
5858 ];
@@ -183,7 +183,7 @@
183183 const impliedComponentRule: RuleWithSource = {
184184 name: "Implied Components Rule",
185185 rule: "Use React component best practices",
186- source: "rules-block",
186+ source: "colocated-markdown",
187187 ruleFile: "src/components/rules.md",
188188 // No explicit globs - should infer from directory
189189 };
@@ -233,7 +233,7 @@
233233 name: "TypeScript Component Rule",
234234 rule: "Use TypeScript with React components",
235235 globs: "**/*.tsx", // Only apply to .tsx files
236- source: "rules-block",
236+ source: "colocated-markdown",
237237 ruleFile: "src/components/rules.md",
238238 };
239239
@@ -280,7 +280,7 @@
280280 name: "API Utils Rule",
281281 rule: "Follow API utility conventions",
282282 globs: "**/*.ts", // Only TypeScript files in this directory
283- source: "rules-block",
283+ source: "colocated-markdown",
284284 ruleFile: "src/utils/api/rules.md",
285285 };
286286
@@ -323,7 +323,7 @@
323323 return {
324324 name: `Inferred Rule for ${directory}`,
325325 rule: `Follow standards for ${directory}`,
326- source: "rules-block",
326+ source: "colocated-markdown",
327327 ruleFile: ruleFilePath,
328328 // In a fixed implementation, these globs would be automatically inferred
329329 // globs: expectedGlob,
modified core/config/profile/doLoadConfig.ts +4 −5
@@ -37,7 +37,7 @@
3737 import { TTS } from "../../util/tts";
3838 import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
3939 import { loadContinueConfigFromJson } from "../load";
40-import { loadCodebaseRules } from "../markdown/loadCodebaseRules";
40+import { CodebaseRulesCache } from "../markdown/loadCodebaseRules";
4141 import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
4242 import { migrateJsonSharedConfig } from "../migrateSharedConfig";
4343 import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
@@ -165,10 +165,9 @@
165165 }
166166
167167 // Add rules from colocated rules.md files in the codebase
168- const { rules: codebaseRules, errors: codebaseRulesErrors } =
169- await loadCodebaseRules(ide);
170- newConfig.rules.unshift(...codebaseRules);
171- errors.push(...codebaseRulesErrors);
168+ const codebaseRulesCache = CodebaseRulesCache.getInstance();
169+ newConfig.rules.unshift(...codebaseRulesCache.rules);
170+ errors.push(...codebaseRulesCache.errors);
172171
173172 // Rectify model selections for each role
174173 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
modified core/config/sharedConfig.ts +0 −4
@@ -19,7 +19,6 @@
1919 readResponseTTS: z.boolean(),
2020 promptPath: z.string(),
2121 useCurrentFileAsContext: z.boolean(),
22- logEditingData: z.boolean(),
2322 optInNextEditFeature: z.boolean(),
2423 enableExperimentalTools: z.boolean(),
2524 codebaseToolCallingOnly: z.boolean(),
@@ -181,9 +180,6 @@
181180 configCopy.experimental.useCurrentFileAsContext =
182181 sharedConfig.useCurrentFileAsContext;
183182 }
184- if (sharedConfig.logEditingData !== undefined) {
185- configCopy.experimental.logEditingData = sharedConfig.logEditingData;
186- }
187183 if (sharedConfig.optInNextEditFeature !== undefined) {
188184 configCopy.experimental.optInNextEditFeature =
189185 sharedConfig.optInNextEditFeature;
modified core/config/yaml/loadYaml.ts +2 −0
@@ -235,6 +235,8 @@
235235 startUrl: doc.startUrl,
236236 rootUrl: doc.rootUrl,
237237 faviconUrl: doc.faviconUrl,
238+ maxDepth: doc.maxDepth,
239+ useLocalCrawling: doc.useLocalCrawling,
238240 }));
239241
240242 config.mcpServers?.forEach((mcpServer) => {
modified core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +22 −2
@@ -60,12 +60,13 @@
6060 export default class BaseRetrievalPipeline implements IRetrievalPipeline {
6161 private ftsIndex = new FullTextSearchCodebaseIndex();
6262 private lanceDbIndex: LanceDbIndex | null = null;
63+ private lanceDbInitPromise: Promise<void> | null = null;
6364
6465 constructor(protected readonly options: RetrievalPipelineOptions) {
6566 void this.initLanceDb();
6667 }
6768
68- private async initLanceDb() {
69+ protected async initLanceDb() {
6970 const embedModel = this.options.config.selectedModelByRole.embed;
7071
7172 if (!embedModel) {
@@ -77,6 +78,23 @@
7778 );
7879 }
7980
81+ protected async ensureLanceDbInitialized(): Promise<boolean> {
82+ if (this.lanceDbIndex) {
83+ return true;
84+ }
85+
86+ if (this.lanceDbInitPromise) {
87+ await this.lanceDbInitPromise;
88+ return this.lanceDbIndex !== null;
89+ }
90+
91+ this.lanceDbInitPromise = this.initLanceDb();
92+ await this.lanceDbInitPromise;
93+ this.lanceDbInitPromise = null; // clear after init
94+
95+ return this.lanceDbIndex !== null;
96+ }
97+
8098 private getCleanedTrigrams(
8199 query: RetrievalPipelineRunArguments["query"],
82100 ): string[] {
@@ -163,7 +181,9 @@
163181 input: string,
164182 n: number,
165183 ): Promise<Chunk[]> {
166- if (!this.lanceDbIndex) {
184+ const initialized = await this.ensureLanceDbInitialized();
185+
186+ if (!initialized || !this.lanceDbIndex) {
167187 console.warn(
168188 "LanceDB index not available, skipping embeddings retrieval",
169189 );
modified core/control-plane/client.ts +8 −1
@@ -10,7 +10,7 @@
1010 import fetch, { RequestInit, Response } from "node-fetch";
1111
1212 import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
13-import { IdeSettings, ModelDescription } from "../index.js";
13+import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
1414
1515 import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
1616 import { getControlPlaneEnv } from "./env.js";
@@ -40,6 +40,7 @@
4040 ControlPlaneSessionInfo | undefined
4141 >,
4242 private readonly ideSettingsPromise: Promise<IdeSettings>,
43+ private readonly ideInfoPromise: Promise<IdeInfo>,
4344 ) {}
4445
4546 async resolveFQSNs(
@@ -86,11 +87,17 @@
8687
8788 const env = await getControlPlaneEnv(this.ideSettingsPromise);
8889 const url = new URL(path, env.CONTROL_PLANE_URL).toString();
90+ const ideInfo = await this.ideInfoPromise;
91+
8992 const resp = await fetch(url, {
9093 ...init,
9194 headers: {
9295 ...init.headers,
9396 Authorization: `Bearer ${accessToken}`,
97+ ...{
98+ "x-extension-version": ideInfo.extensionVersion,
99+ "x-is-prerelease": String(ideInfo.isPrerelease),
100+ },
94101 },
95102 });
96103
modified core/control-plane/mdm/mdm.ts +8 −2
@@ -132,7 +132,10 @@
132132 try {
133133 // Use REG QUERY command to read registry values
134134 const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
135- const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
135+ const licenseKeyOutput = execSync(licenseKeyCmd, {
136+ encoding: "utf8",
137+ stdio: ["pipe", "pipe", "pipe"],
138+ });
136139 // Extract values from command output
137140 const licenseKey = extractRegValue(licenseKeyOutput);
138141 if (licenseKey) {
@@ -145,7 +148,10 @@
145148 // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
146149 try {
147150 const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
148- const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
151+ const licenseKeyOutput = execSync(licenseKeyCmd, {
152+ encoding: "utf8",
153+ stdio: ["pipe", "pipe", "pipe"],
154+ });
149155 // Extract values from command output
150156 const licenseKey = extractRegValue(licenseKeyOutput);
151157 if (licenseKey) {
modified core/core.ts +113 −22
@@ -24,6 +24,7 @@
2424 import { callTool } from "./tools/callTool";
2525 import { ChatDescriber } from "./util/chatDescriber";
2626 import { clipboardCache } from "./util/clipboardCache";
27+import { compactConversation } from "./util/conversationCompaction";
2728 import { GlobalContext } from "./util/GlobalContext";
2829 import historyManager from "./util/history";
2930 import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
@@ -52,6 +53,7 @@
5253 import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
5354 import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
5455 import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
56+import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
5557 import {
5658 setupLocalConfig,
5759 setupProviderConfig,
@@ -69,6 +71,7 @@
6971 import { llmStreamChat } from "./llm/streamChat";
7072 import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
7173 import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
74+import { NextEditProvider } from "./nextEdit/NextEditProvider";
7275 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
7376 import { OnboardingModes } from "./protocol/core";
7477 import type { IMessenger, Message } from "./protocol/messenger";
@@ -88,6 +91,7 @@
8891 configHandler: ConfigHandler;
8992 codeBaseIndexer: CodebaseIndexer;
9093 completionProvider: CompletionProvider;
94+ nextEditProvider: NextEditProvider;
9195 private docsService: DocsService;
9296 private globalContext = new GlobalContext();
9397 llmLogger = new LLMLogger();
@@ -150,7 +154,7 @@
150154 );
151155
152156 MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
153- void this.configHandler.reloadConfig();
157+ void this.configHandler.reloadConfig("MCP Connections refreshed");
154158
155159 // Refresh @mention dropdown submenu items for MCP providers
156160 const mcpManager = MCPManagerSingleton.getInstance();
@@ -233,6 +237,24 @@
233237 (..._) => Promise.resolve([]),
234238 );
235239
240+ const codebaseRulesCache = CodebaseRulesCache.getInstance();
241+ void codebaseRulesCache
242+ .refresh(ide)
243+ .catch((e) => console.error("Failed to initialize colocated rules cache"))
244+ .then(() => {
245+ void this.configHandler.reloadConfig(
246+ "Initial codebase rules post-walkdir/load reload",
247+ );
248+ });
249+ this.nextEditProvider = NextEditProvider.initialize(
250+ this.configHandler,
251+ ide,
252+ getLlm,
253+ (e) => {},
254+ (..._) => Promise.resolve([]),
255+ "fineTuned",
256+ );
257+
236258 this.registerMessageHandlers(ideSettingsPromise);
237259 }
238260
@@ -299,23 +321,31 @@
299321 on("config/addModel", (msg) => {
300322 const model = msg.data.model;
301323 addModel(model, msg.data.role);
302- void this.configHandler.reloadConfig();
324+ void this.configHandler.reloadConfig(
325+ "Model added (config/addModel message)",
326+ );
303327 });
304328
305329 on("config/deleteModel", (msg) => {
306330 deleteModel(msg.data.title);
307- void this.configHandler.reloadConfig();
331+ void this.configHandler.reloadConfig(
332+ "Model removed (config/deleteModel message)",
333+ );
308334 });
309335
310336 on("config/newPromptFile", async (msg) => {
311337 const { config } = await this.configHandler.loadConfig();
312338 await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
313- await this.configHandler.reloadConfig();
339+ await this.configHandler.reloadConfig(
340+ "Prompt file created (config/newPromptFile message)",
341+ );
314342 });
315343
316344 on("config/addLocalWorkspaceBlock", async (msg) => {
317345 await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
318- await this.configHandler.reloadConfig();
346+ await this.configHandler.reloadConfig(
347+ "Local block created (config/addLocalWorkspaceBlock message)",
348+ );
319349 });
320350
321351 on("config/openProfile", async (msg) => {
@@ -323,8 +353,12 @@
323353 });
324354
325355 on("config/reload", async (msg) => {
326- void this.configHandler.reloadConfig();
327- return await this.configHandler.getSerializedConfig();
356+ // User force reloading will retrigger colocated rules
357+ const codebaseRulesCache = CodebaseRulesCache.getInstance();
358+ await codebaseRulesCache.refresh(this.ide);
359+ void this.configHandler.reloadConfig(
360+ "Force reloaded (config/reload message)",
361+ );
328362 });
329363
330364 on("config/ideSettingsUpdate", async (msg) => {
@@ -343,7 +377,9 @@
343377
344378 on("config/updateSharedConfig", async (msg) => {
345379 const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
346- await this.configHandler.reloadConfig();
380+ await this.configHandler.reloadConfig(
381+ "Shared config update (config/updateSharedConfig message)",
382+ );
347383 return newSharedConfig;
348384 });
349385
@@ -353,7 +389,9 @@
353389 msg.data.role,
354390 msg.data.title,
355391 );
356- await this.configHandler.reloadConfig();
392+ await this.configHandler.reloadConfig(
393+ "Selected model update (config/updateSelectedModel message)",
394+ );
357395 return newSelectedModels;
358396 });
359397
@@ -512,6 +550,28 @@
512550 return await ChatDescriber.describe(currentModel, {}, msg.data.text);
513551 });
514552
553+ on("conversation/compact", async (msg) => {
554+ const currentModel = (await this.configHandler.loadConfig()).config
555+ ?.selectedModelByRole.chat;
556+
557+ if (!currentModel) {
558+ throw new Error("No chat model selected");
559+ }
560+
561+ try {
562+ await compactConversation({
563+ sessionId: msg.data.sessionId,
564+ index: msg.data.index,
565+ historyManager,
566+ currentModel,
567+ });
568+ return undefined;
569+ } catch (error) {
570+ console.error("Error compacting conversation:", error);
571+ return undefined;
572+ }
573+ });
574+
515575 // Autocomplete
516576 on("autocomplete/complete", async (msg) => {
517577 const outcome =
@@ -528,6 +588,21 @@
528588 this.completionProvider.cancel();
529589 });
530590
591+ // Next Edit
592+ on("nextEdit/predict", async (msg) => {
593+ const outcome = await this.nextEditProvider.provideInlineCompletionItems(
594+ msg.data,
595+ undefined,
596+ );
597+ return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
598+ });
599+ on("nextEdit/accept", async (msg) => {
600+ this.nextEditProvider.accept(msg.data.completionId);
601+ });
602+ on("nextEdit/reject", async (msg) => {
603+ this.nextEditProvider.reject(msg.data.completionId);
604+ });
605+
531606 on("streamDiffLines", async (msg) => {
532607 const { config } = await this.configHandler.loadConfig();
533608 if (!config) {
@@ -642,9 +717,12 @@
642717 void refreshIfNotIgnored(data.uris);
643718
644719 if (hasRulesFiles(data.uris)) {
645- await this.configHandler.reloadConfig();
720+ const rulesCache = CodebaseRulesCache.getInstance();
721+ await Promise.all(
722+ data.uris.map((uri) => rulesCache.update(this.ide, uri)),
723+ );
724+ await this.configHandler.reloadConfig("Rules file created");
646725 }
647-
648726 // If it's a local assistant being created, we want to reload all assistants so it shows up in the list
649727 let localAssistantCreated = false;
650728 for (const uri of data.uris) {
@@ -664,7 +742,9 @@
664742 void refreshIfNotIgnored(data.uris);
665743
666744 if (hasRulesFiles(data.uris)) {
667- await this.configHandler.reloadConfig();
745+ const rulesCache = CodebaseRulesCache.getInstance();
746+ data.uris.forEach((uri) => rulesCache.remove(uri));
747+ await this.configHandler.reloadConfig("Codebase rule file deleted");
668748 }
669749 }
670750 });
@@ -940,7 +1020,7 @@
9401020 ],
9411021 }),
9421022 );
943- void this.configHandler.reloadConfig();
1023+ void this.configHandler.reloadConfig("Autocomplete model added");
9441024 }
9451025
9461026 private async handleFilesChanged({
@@ -970,7 +1050,9 @@
9701050 this.globalContext.update("showConfigUpdateToast", false);
9711051 }
9721052 }
973- await this.configHandler.reloadConfig();
1053+ await this.configHandler.reloadConfig(
1054+ "Current profile config file updated",
1055+ );
9741056 continue;
9751057 }
9761058
@@ -978,15 +1060,24 @@
9781060 uri.endsWith(".continuerc.json") ||
9791061 uri.endsWith(".prompt") ||
9801062 uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
981- (uri.includes(".continue") && uri.endsWith(".yaml")) ||
982- uri.endsWith(RULES_MARKDOWN_FILENAME) ||
983- BLOCK_TYPES.some(
984- (blockType) =>
985- uri.includes(`.continue/${blockType}`) ||
986- uri.includes(`.continue\\${blockType}`),
1063+ (uri.includes(".continue") &&
1064+ (uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
1065+ BLOCK_TYPES.some((blockType) =>
1066+ uri.includes(`.continue/${blockType}`),
9871067 )
9881068 ) {
989- await this.configHandler.reloadConfig();
1069+ await this.configHandler.reloadConfig(
1070+ "Config-related file updated: continuerc, prompt, local block, etc",
1071+ );
1072+ } else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) {
1073+ try {
1074+ const codebaseRulesCache = CodebaseRulesCache.getInstance();
1075+ void codebaseRulesCache.update(this.ide, uri).then(() => {
1076+ void this.configHandler.reloadConfig("Codebase rule update");
1077+ });
1078+ } catch (e) {
1079+ console.error("Failed to update codebase rule", e);
1080+ }
9901081 } else if (
9911082 uri.endsWith(".continueignore") ||
9921083 uri.endsWith(".gitignore")
@@ -1068,7 +1159,7 @@
10681159
10691160 editConfigFile((c) => c, editConfigYamlCallback);
10701161
1071- void this.configHandler.reloadConfig();
1162+ void this.configHandler.reloadConfig("Onboarding completed");
10721163 }
10731164
10741165 private getContextItems = async (
modified core/index.d.ts +29 −6
@@ -369,10 +369,32 @@
369369 toolCalls?: ToolCallDelta[];
370370 }
371371
372+/**
373+ * This is meant to be equivalent to the OpenAI [usage object](https://platform.openai.com/docs/api-reference/chat/object#chat/object-usage)
374+ * but potentially with additional information that is needed for other providers.
375+ */
376+export interface Usage {
377+ completionTokens: number;
378+ promptTokens: number;
379+ promptTokensDetails?: {
380+ cachedTokens?: number;
381+ /** This an Anthropic-specific property */
382+ cacheWriteTokens?: number;
383+ audioTokens?: number;
384+ };
385+ completionTokensDetails?: {
386+ acceptedPredictionTokens?: number;
387+ reasoningTokens?: number;
388+ rejectedPredictionTokens?: number;
389+ audioTokens?: number;
390+ };
391+}
392+
372393 export interface AssistantChatMessage {
373394 role: "assistant";
374395 content: MessageContent;
375396 toolCalls?: ToolCallDelta[];
397+ usage?: Usage;
376398 }
377399
378400 export interface SystemChatMessage {
@@ -472,6 +494,7 @@
472494 isGatheringContext?: boolean;
473495 reasoning?: Reasoning;
474496 appliedRules?: RuleWithSource[];
497+ conversationSummary?: string;
475498 }
476499
477500 export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@@ -490,12 +513,14 @@
490513 kind: "startChat";
491514 messages: ChatMessage[];
492515 options: CompletionOptions;
516+ provider: string;
493517 }
494518
495519 export interface LLMInteractionStartComplete extends LLMInteractionBase {
496520 kind: "startComplete";
497521 prompt: string;
498522 options: CompletionOptions;
523+ provider: string;
499524 }
500525
501526 export interface LLMInteractionStartFim extends LLMInteractionBase {
@@ -503,6 +528,7 @@
503528 prefix: string;
504529 suffix: string;
505530 options: CompletionOptions;
531+ provider: string;
506532 }
507533
508534 export interface LLMInteractionChunk extends LLMInteractionBase {
@@ -519,6 +545,7 @@
519545 promptTokens: number;
520546 generatedTokens: number;
521547 thinkingTokens: number;
548+ usage: Usage | undefined;
522549 }
523550
524551 export interface LLMInteractionSuccess extends LLMInteractionEnd {
@@ -711,6 +738,7 @@
711738 version: string;
712739 remoteName: string;
713740 extensionVersion: string;
741+ isPrerelease: boolean;
714742 }
715743
716744 export interface BranchAndDir {
@@ -1288,7 +1316,6 @@
12881316 codeWrap?: boolean;
12891317 showSessionTabs?: boolean;
12901318 autoAcceptEditToolDiffs?: boolean;
1291- logEditingData?: boolean;
12921319 }
12931320
12941321 export interface ContextMenuConfig {
@@ -1441,11 +1468,6 @@
14411468 */
14421469 useCurrentFileAsContext?: boolean;
14431470
1444- /**
1445- * If enabled, will save data on the user's editing processes
1446- */
1447- logEditingData?: boolean;
1448-
14491471 /**
14501472 * If enabled, will enable next edit in place of autocomplete
14511473 */
@@ -1669,6 +1691,7 @@
16691691 | "model-options-plan"
16701692 | "model-options-agent"
16711693 | "rules-block"
1694+ | "colocated-markdown"
16721695 | "json-systemMessage"
16731696 | ".continuerules";
16741697
modified core/indexing/CodebaseIndexer.test.ts +295 −10
@@ -1,3 +1,5 @@
1+/* eslint-disable max-lines-per-function */
2+/* lint is not useful for test classes */
13 import { jest } from "@jest/globals";
24 import { execSync } from "node:child_process";
35 import fs from "node:fs";
@@ -14,8 +16,11 @@
1416 } from "../test/testDir.js";
1517 import { getIndexSqlitePath } from "../util/paths.js";
1618
19+import { ConfigResult } from "@continuedev/config-yaml";
20+import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
21+import { ContinueConfig } from "../index.js";
1722 import { localPathToUri } from "../util/pathToUri.js";
18-import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
23+import { CodebaseIndexer } from "./CodebaseIndexer.js";
1924 import { getComputeDeleteAddRemove } from "./refreshIndex.js";
2025 import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
2126 import { CodebaseIndex } from "./types.js";
@@ -57,6 +62,17 @@
5762 protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
5863 return [new TestCodebaseIndex()];
5964 }
65+
66+ // Add public methods to test private methods
67+ public testHasCodebaseContextProvider() {
68+ return (this as any).hasCodebaseContextProvider();
69+ }
70+
71+ public async testHandleConfigUpdate(
72+ configResult: ConfigResult<ContinueConfig>,
73+ ) {
74+ return (this as any).handleConfigUpdate({ config: configResult.config });
75+ }
6076 }
6177
6278 // Create a mock messenger type that doesn't require actual protocol imports
@@ -71,8 +87,6 @@
7187 // These are more like integration tests, whereas we should separately test
7288 // the individual CodebaseIndex classes
7389 describe("CodebaseIndexer", () => {
74- const pauseToken = new PauseToken(false);
75-
7690 // Replace mockProgressReporter with mockMessenger
7791 const mockMessenger: MockMessengerType = {
7892 send: jest.fn(),
@@ -82,13 +96,8 @@
8296 onError: jest.fn(),
8397 };
8498
85- const codebaseIndexer = new TestCodebaseIndexer(
86- testConfigHandler,
87- testIde,
88- mockMessenger as any,
89- false,
90- );
91- const testIndex = new TestCodebaseIndex();
99+ let codebaseIndexer: TestCodebaseIndexer;
100+ let testIndex: TestCodebaseIndex;
92101
93102 beforeAll(async () => {
94103 tearDownTestDir();
@@ -99,6 +108,15 @@
99108 cwd: TEST_DIR_PATH,
100109 });
101110 execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH });
111+
112+ codebaseIndexer = new TestCodebaseIndexer(
113+ testConfigHandler,
114+ testIde,
115+ mockMessenger as any,
116+ false,
117+ );
118+ await codebaseIndexer.initPromise;
119+ testIndex = new TestCodebaseIndex();
102120 });
103121
104122 afterAll(async () => {
@@ -161,6 +179,7 @@
161179 }
162180
163181 test("should index test folder without problem", async () => {
182+ walkDirCache.invalidate();
164183 addToTestDir([
165184 ["test.ts", TEST_TS],
166185 ["py/main.py", TEST_PY],
@@ -403,4 +422,270 @@
403422 expect(codebaseIndexer.currentIndexingState).toEqual(testState);
404423 });
405424 });
425+
426+ // New describe block for testing handleConfigUpdate functionality
427+ describe("handleConfigUpdate functionality", () => {
428+ let testIndexer: TestCodebaseIndexer;
429+ let mockRefreshCodebaseIndex: jest.MockedFunction<any>;
430+ let mockGetWorkspaceDirs: jest.MockedFunction<any>;
431+
432+ beforeEach(() => {
433+ testIndexer = new TestCodebaseIndexer(
434+ testConfigHandler,
435+ testIde,
436+ mockMessenger as any,
437+ false,
438+ );
439+
440+ // Mock the refreshCodebaseIndex method to avoid actual indexing
441+ mockRefreshCodebaseIndex = jest
442+ .spyOn(testIndexer, "refreshCodebaseIndex")
443+ .mockImplementation(async () => {});
444+
445+ // Mock getWorkspaceDirs to return test directories
446+ mockGetWorkspaceDirs = jest
447+ .spyOn(testIde, "getWorkspaceDirs")
448+ .mockResolvedValue(["/test/workspace"]);
449+ });
450+
451+ afterEach(() => {
452+ jest.clearAllMocks();
453+ });
454+
455+ describe("hasCodebaseContextProvider", () => {
456+ test("should return true when codebase context provider is present", () => {
457+ // Set up config with codebase context provider
458+ (testIndexer as any).config = {
459+ contextProviders: [
460+ {
461+ description: {
462+ title: CodebaseContextProvider.description.title,
463+ },
464+ },
465+ ],
466+ };
467+
468+ const result = testIndexer.testHasCodebaseContextProvider();
469+ expect(result).toBe(true);
470+ });
471+
472+ test("should return false when no context providers are configured", () => {
473+ (testIndexer as any).config = {
474+ contextProviders: undefined,
475+ };
476+
477+ const result = testIndexer.testHasCodebaseContextProvider();
478+ expect(result).toBe(false);
479+ });
480+
481+ test("should return false when context providers exist but no codebase provider", () => {
482+ (testIndexer as any).config = {
483+ contextProviders: [
484+ {
485+ description: {
486+ title: "SomeOtherProvider",
487+ },
488+ },
489+ ],
490+ };
491+
492+ const result = testIndexer.testHasCodebaseContextProvider();
493+ expect(result).toBe(false);
494+ });
495+
496+ test("should return false when context providers is empty array", () => {
497+ (testIndexer as any).config = {
498+ contextProviders: [],
499+ };
500+
501+ const result = testIndexer.testHasCodebaseContextProvider();
502+ expect(result).toBe(false);
503+ });
504+ });
505+
506+ describe("handleConfigUpdate", () => {
507+ test("should return early when newConfig is null", async () => {
508+ const configResult: ConfigResult<ContinueConfig> = {
509+ config: null as any,
510+ errors: [],
511+ configLoadInterrupted: false,
512+ };
513+
514+ await testIndexer.testHandleConfigUpdate(configResult);
515+
516+ // These get called once on init, so we want them to not get called again
517+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
518+ expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
519+ });
520+
521+ test("should return early when newConfig is undefined", async () => {
522+ const configResult: ConfigResult<ContinueConfig> = {
523+ config: undefined as any,
524+ errors: [],
525+ configLoadInterrupted: false,
526+ };
527+
528+ await testIndexer.testHandleConfigUpdate(configResult);
529+
530+ // These get called once on init, so we want them to not get called again
531+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
532+ expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
533+ });
534+
535+ test("should return early when no codebase context provider is present", async () => {
536+ const configResult: ConfigResult<ContinueConfig> = {
537+ config: {
538+ contextProviders: [
539+ {
540+ description: {
541+ title: "SomeOtherProvider",
542+ },
543+ },
544+ ],
545+ selectedModelByRole: {
546+ embed: {
547+ model: "test-model",
548+ provider: "test-provider",
549+ },
550+ },
551+ } as unknown as ContinueConfig,
552+ errors: [],
553+ configLoadInterrupted: false,
554+ };
555+
556+ await testIndexer.testHandleConfigUpdate(configResult);
557+
558+ // These get called once on init, so we want them to not get called again
559+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
560+ expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
561+ });
562+
563+ test("should return early when no embed model is configured", async () => {
564+ const configResult: ConfigResult<ContinueConfig> = {
565+ config: {
566+ contextProviders: [
567+ {
568+ description: {
569+ title: CodebaseContextProvider.description.title,
570+ },
571+ },
572+ ],
573+ selectedModelByRole: {
574+ embed: undefined,
575+ },
576+ } as unknown as ContinueConfig,
577+ errors: [],
578+ configLoadInterrupted: false,
579+ };
580+
581+ await testIndexer.testHandleConfigUpdate(configResult);
582+
583+ // These get called once on init, so we want them to not get called again
584+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
585+ expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
586+ });
587+
588+ test("should call refreshCodebaseIndex when all conditions are met", async () => {
589+ const configResult: ConfigResult<ContinueConfig> = {
590+ config: {
591+ contextProviders: [
592+ {
593+ description: {
594+ title: CodebaseContextProvider.description.title,
595+ },
596+ },
597+ ],
598+ selectedModelByRole: {
599+ embed: {
600+ model: "test-model",
601+ provider: "test-provider",
602+ },
603+ },
604+ } as unknown as ContinueConfig,
605+ errors: [],
606+ configLoadInterrupted: false,
607+ };
608+
609+ await testIndexer.testHandleConfigUpdate(configResult);
610+
611+ // These get called once on init, and we want them to get called again
612+ expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2);
613+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
614+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
615+ "/test/workspace",
616+ ]);
617+ });
618+
619+ test("should set config property before checking conditions", async () => {
620+ const testConfig = {
621+ contextProviders: [
622+ {
623+ description: {
624+ title: CodebaseContextProvider.description.title,
625+ },
626+ },
627+ ],
628+ selectedModelByRole: {
629+ embed: {
630+ model: "test-model",
631+ provider: "test-provider",
632+ },
633+ },
634+ } as unknown as ContinueConfig;
635+
636+ const configResult: ConfigResult<ContinueConfig> = {
637+ config: testConfig,
638+ errors: [],
639+ configLoadInterrupted: false,
640+ };
641+
642+ await testIndexer.testHandleConfigUpdate(configResult);
643+
644+ // Verify that the config was set
645+ expect((testIndexer as any).config).toBe(testConfig);
646+ // These get called once on init, and we want them to get called again
647+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
648+ });
649+
650+ test("should handle multiple context providers correctly", async () => {
651+ const configResult: ConfigResult<ContinueConfig> = {
652+ config: {
653+ contextProviders: [
654+ {
655+ description: {
656+ title: "SomeOtherProvider",
657+ },
658+ },
659+ {
660+ description: {
661+ title: CodebaseContextProvider.description.title,
662+ },
663+ },
664+ {
665+ description: {
666+ title: "AnotherProvider",
667+ },
668+ },
669+ ],
670+ selectedModelByRole: {
671+ embed: {
672+ model: "test-model",
673+ provider: "test-provider",
674+ },
675+ },
676+ } as unknown as ContinueConfig,
677+ errors: [],
678+ configLoadInterrupted: false,
679+ };
680+
681+ await testIndexer.testHandleConfigUpdate(configResult);
682+
683+ // These get called once on init, and we want them to get called again
684+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
685+ expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
686+ "/test/workspace",
687+ ]);
688+ });
689+ });
690+ });
406691 });
modified core/indexing/CodebaseIndexer.ts +70 −2
@@ -1,7 +1,12 @@
11 import * as fs from "fs/promises";
22
33 import { ConfigHandler } from "../config/ConfigHandler.js";
4-import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
4+import {
5+ ContinueConfig,
6+ IDE,
7+ IndexingProgressUpdate,
8+ IndexTag,
9+} from "../index.js";
510 import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
611 import type { IMessenger } from "../protocol/messenger";
712 import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
@@ -9,11 +14,14 @@
914 import { Telemetry } from "../util/posthog.js";
1015 import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
1116
17+import { ConfigResult } from "@continuedev/config-yaml";
18+import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
1219 import { ContinueServerClient } from "../continueServer/stubs/client";
1320 import { LLMError } from "../llm/index.js";
1421 import { getRootCause } from "../util/errors.js";
1522 import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
1623 import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
24+import { embedModelsAreEqual } from "./docs/DocsService.js";
1725 import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
1826 import { LanceDbIndex } from "./LanceDbIndex.js";
1927 import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js";
@@ -44,6 +52,10 @@
4452 * - To make as few requests as possible to the embeddings providers
4553 */
4654 filesPerBatch = 200;
55+ // We normally allow this to run in the background,
56+ // and only need to `await` it for tests.
57+ public initPromise: Promise<void>;
58+ private config!: ContinueConfig;
4759 private indexingCancellationController: AbortController | undefined;
4860 private codebaseIndexingState: IndexingProgressUpdate;
4961 private readonly pauseToken: PauseToken;
@@ -83,6 +95,17 @@
8395
8496 // Initialize pause token
8597 this.pauseToken = new PauseToken(initialPaused);
98+
99+ this.initPromise = this.init(configHandler);
100+ }
101+
102+ // Initialization - load config and attach config listener
103+ private async init(configHandler: ConfigHandler) {
104+ const result = await configHandler.loadConfig();
105+ await this.handleConfigUpdate(result);
106+ configHandler.onConfigUpdate(
107+ this.handleConfigUpdate.bind(this) as (arg: any) => void,
108+ );
86109 }
87110
88111 set paused(value: boolean) {
@@ -192,7 +215,7 @@
192215 workspaceDirs: string[],
193216 ): Promise<void> {
194217 if (this.pauseToken.paused) {
195- // NOTE: by returning here, there is a chance that while paused a file is modified and
218+ // FIXME: by returning here, there is a chance that while paused a file is modified and
196219 // then after unpausing the file is not reindexed
197220 return;
198221 }
@@ -763,4 +786,49 @@
763786 public get currentIndexingState(): IndexingProgressUpdate {
764787 return this.codebaseIndexingState;
765788 }
789+
790+ private hasCodebaseContextProvider() {
791+ return !!this.config.contextProviders?.some(
792+ (provider) =>
793+ provider.description.title ===
794+ CodebaseContextProvider.description.title,
795+ );
796+ }
797+
798+ private isIndexingConfigSame(
799+ config1: ContinueConfig | undefined,
800+ config2: ContinueConfig,
801+ ) {
802+ return embedModelsAreEqual(
803+ config1?.selectedModelByRole.embed,
804+ config2.selectedModelByRole.embed,
805+ );
806+ }
807+
808+ private async handleConfigUpdate({
809+ config: newConfig,
810+ }: ConfigResult<ContinueConfig>) {
811+ if (newConfig) {
812+ const needsReindex = !this.isIndexingConfigSame(this.config, newConfig);
813+
814+ this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
815+
816+ // No point in indexing if no codebase context provider
817+ const hasCodebaseContextProvider = this.hasCodebaseContextProvider();
818+ if (!hasCodebaseContextProvider) {
819+ return;
820+ }
821+
822+ // Skip codebase indexing if not supported
823+ // No warning message here because would show on ANY config update
824+ if (!this.config.selectedModelByRole.embed) {
825+ return;
826+ }
827+
828+ if (needsReindex) {
829+ const dirs = await this.ide.getWorkspaceDirs();
830+ await this.refreshCodebaseIndex(dirs);
831+ }
832+ }
833+ }
766834 }
modified core/indexing/docs/DocsCache.ts +11 −1
@@ -7,6 +7,15 @@
77 title: string;
88 }
99
10+/**
11+ * Strip off the trailing forward slash from the given URL
12+ * @param url The URL of the document
13+ * @returns A sanitized URL without trailing forward slash
14+ */
15+const stripTrailingSlash = (url: string): string => {
16+ return url.replace(/\/+$/, "");
17+};
18+
1019 export class DocsCache {
1120 static readonly AWS_REGION: string = "us-west-1";
1221 static readonly BUCKET_NAME: string = "continue-preindexed-docs";
@@ -33,7 +42,8 @@
3342 url: string,
3443 ): string {
3544 const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
36- const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_"));
45+ const sanitizedUrl = stripTrailingSlash(url);
46+ const normalizedUrl = encodeURIComponent(sanitizedUrl.replace(/\//g, "_"));
3747 return normalizedEmbeddingId + "/" + normalizedUrl;
3848 }
3949
modified core/indexing/docs/DocsService.ts +65 −18
@@ -69,7 +69,7 @@
6969 const globalContext = new GlobalContext();
7070 const failedDocs = globalContext.get("failedDocs") ?? [];
7171 const newFailedDocs = failedDocs.filter(
72- (d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
72+ (d) => !docConfigsAreEqual(siteIndexingConfig, d),
7373 );
7474 newFailedDocs.push(siteIndexingConfig);
7575 globalContext.update("failedDocs", newFailedDocs);
@@ -81,7 +81,7 @@
8181 const globalContext = new GlobalContext();
8282 const failedDocs = globalContext.get("failedDocs") ?? [];
8383 const newFailedDocs = failedDocs.filter(
84- (d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
84+ (d) => !docConfigsAreEqual(siteIndexingConfig, d),
8585 );
8686 globalContext.update("failedDocs", newFailedDocs);
8787 };
@@ -89,32 +89,69 @@
8989 const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => {
9090 const globalContext = new GlobalContext();
9191 const failedDocs = globalContext.get("failedDocs") ?? [];
92- return failedDocs.find((d) =>
93- siteIndexingConfigsAreEqual(siteIndexingConfig, d),
92+ return failedDocs.find((d) => docConfigsAreEqual(siteIndexingConfig, d));
93+};
94+
95+export function embedModelsAreEqual(
96+ llm1: ILLM | null | undefined,
97+ llm2: ILLM | null | undefined,
98+): boolean {
99+ return (
100+ llm1?.underlyingProviderName === llm2?.underlyingProviderName &&
101+ llm1?.title === llm2?.title &&
102+ llm1?.maxEmbeddingChunkSize === llm2?.maxEmbeddingChunkSize
103+ );
104+}
105+
106+const docConfigsAreEqual = (
107+ siteConfig1: SiteIndexingConfig,
108+ siteConfig2: SiteIndexingConfig,
109+) => {
110+ return (
111+ siteConfig1.faviconUrl === siteConfig2.faviconUrl &&
112+ siteConfig1.title === siteConfig2.title &&
113+ docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2)
114+ );
115+};
116+
117+const docConfigsAreEqualExceptTitleAndFavicon = (
118+ siteConfig1: SiteIndexingConfig,
119+ siteConfig2: SiteIndexingConfig,
120+) => {
121+ return (
122+ siteConfig1.startUrl === siteConfig2.startUrl &&
123+ siteConfig1.maxDepth === siteConfig2.maxDepth &&
124+ siteConfig1.useLocalCrawling === siteConfig2.useLocalCrawling
94125 );
95126 };
96127
97128 const siteIndexingConfigsAreEqual = (
98- config1: SiteIndexingConfig,
99- config2: SiteIndexingConfig,
129+ siteConfig1: SiteIndexingConfig,
130+ siteConfig2: SiteIndexingConfig,
131+ contConfig1: ContinueConfig | undefined,
132+ contConfig2: ContinueConfig,
100133 ) => {
101134 return (
102- config1.startUrl === config2.startUrl &&
103- config1.faviconUrl === config2.faviconUrl &&
104- config1.title === config2.title &&
105- config1.maxDepth === config2.maxDepth &&
106- config1.useLocalCrawling === config2.useLocalCrawling
135+ docConfigsAreEqual(siteConfig1, siteConfig2) &&
136+ embedModelsAreEqual(
137+ contConfig1?.selectedModelByRole.embed,
138+ contConfig2.selectedModelByRole.embed,
139+ )
107140 );
108141 };
109142
110143 const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
111- config1: SiteIndexingConfig,
112- config2: SiteIndexingConfig,
144+ siteConfig1: SiteIndexingConfig,
145+ siteConfig2: SiteIndexingConfig,
146+ contConfig1: ContinueConfig | undefined,
147+ contConfig2: ContinueConfig,
113148 ) => {
114149 return (
115- config1.startUrl === config2.startUrl &&
116- config1.maxDepth === config2.maxDepth &&
117- config1.useLocalCrawling === config2.useLocalCrawling
150+ docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) &&
151+ embedModelsAreEqual(
152+ contConfig1?.selectedModelByRole.embed,
153+ contConfig2.selectedModelByRole.embed,
154+ )
118155 );
119156 };
120157
@@ -1037,12 +1074,22 @@
10371074 );
10381075
10391076 // TODO: Changes to the docs config made while Continue isn't running won't be caught
1040- if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
1077+ if (
1078+ oldConfigDoc &&
1079+ !siteIndexingConfigsAreEqual(
1080+ oldConfigDoc,
1081+ doc,
1082+ oldConfig,
1083+ newConfig,
1084+ )
1085+ ) {
10411086 // When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
10421087 if (
10431088 siteIndexingConfigsAreEqualExceptTitleAndFavicon(
10441089 oldConfigDoc,
10451090 doc,
1091+ oldConfig,
1092+ newConfig,
10461093 )
10471094 ) {
10481095 await this.updateMetadataInSqlite(doc);
@@ -1262,7 +1309,7 @@
12621309 // Handles the case where a user has manually added the doc to config.json
12631310 // so it already exists in the file
12641311 const doesEquivalentDocExist = this.config.docs?.some((doc) =>
1265- siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
1312+ docConfigsAreEqual(doc, siteIndexingConfig),
12661313 );
12671314
12681315 if (!doesEquivalentDocExist) {
modified core/indexing/docs/crawlers/DocsCrawler.test.ts +1 −1
@@ -53,7 +53,7 @@
5353 };
5454 }
5555
56- describe("GitHub Crawler", () => {
56+ describe.skip("GitHub Crawler", () => {
5757 const repoUrl =
5858 "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
5959
modified core/jest.config.js +11 −1
@@ -3,7 +3,17 @@
33
44 export default {
55 transform: {
6- "^.+\\.(ts|js)$": ["ts-jest", { useESM: true, useIsolatedModules: true }],
6+ "^.+\\.(ts|js)$": [
7+ "ts-jest",
8+ {
9+ useESM: true,
10+ useIsolatedModules: true,
11+ tsconfig: {
12+ experimentalDecorators: true,
13+ emitDecoratorMetadata: true,
14+ },
15+ },
16+ ],
717 },
818 moduleNameMapper: {
919 "^(\\.{1,2}/.*)\\.js$": "$1",
modified core/llm/index.ts +27 −0
@@ -28,6 +28,7 @@
2828 RequestOptions,
2929 TabAutocompleteOptions,
3030 TemplateType,
31+ Usage,
3132 } from "../index.js";
3233 import mergeJson from "../util/merge.js";
3334 import { renderChatMessage } from "../util/messageContent.js";
@@ -327,6 +328,7 @@
327328 completion: string,
328329 thinking: string | undefined,
329330 interaction: ILLMInteractionLog | undefined,
331+ usage: Usage | undefined,
330332 error?: any,
331333 ): InteractionStatus {
332334 let promptTokens = this.countTokens(prompt);
@@ -368,6 +370,7 @@
368370 promptTokens,
369371 generatedTokens,
370372 thinkingTokens,
373+ usage,
371374 });
372375 return "cancelled";
373376 } else {
@@ -379,6 +382,7 @@
379382 promptTokens,
380383 generatedTokens,
381384 thinkingTokens,
385+ usage,
382386 });
383387 return "error";
384388 }
@@ -388,6 +392,7 @@
388392 promptTokens,
389393 generatedTokens,
390394 thinkingTokens,
395+ usage,
391396 });
392397 return "success";
393398 }
@@ -574,6 +579,7 @@
574579 prefix,
575580 suffix,
576581 options: completionOptions,
582+ provider: this.providerName,
577583 });
578584 if (this.llmRequestHook) {
579585 this.llmRequestHook(completionOptions.model, fimLog);
@@ -622,6 +628,7 @@
622628 completion,
623629 undefined,
624630 interaction,
631+ undefined,
625632 );
626633 } catch (e) {
627634 status = this._logEnd(
@@ -630,6 +637,7 @@
630637 completion,
631638 undefined,
632639 interaction,
640+ undefined,
633641 e,
634642 );
635643 throw e;
@@ -641,6 +649,7 @@
641649 completion,
642650 undefined,
643651 interaction,
652+ undefined,
644653 "cancel",
645654 );
646655 }
@@ -681,6 +690,7 @@
681690 kind: "startComplete",
682691 prompt,
683692 options: completionOptions,
693+ provider: this.providerName,
684694 });
685695 if (this.llmRequestHook) {
686696 this.llmRequestHook(completionOptions.model, prompt);
@@ -736,6 +746,7 @@
736746 completion,
737747 undefined,
738748 interaction,
749+ undefined,
739750 );
740751 } catch (e) {
741752 status = this._logEnd(
@@ -744,6 +755,7 @@
744755 completion,
745756 undefined,
746757 interaction,
758+ undefined,
747759 e,
748760 );
749761 throw e;
@@ -755,6 +767,7 @@
755767 completion,
756768 undefined,
757769 interaction,
770+ undefined,
758771 "cancel",
759772 );
760773 }
@@ -796,6 +809,7 @@
796809 kind: "startComplete",
797810 prompt: prompt,
798811 options: completionOptions,
812+ provider: this.providerName,
799813 });
800814 if (this.llmRequestHook) {
801815 this.llmRequestHook(completionOptions.model, prompt);
@@ -829,6 +843,7 @@
829843 completion,
830844 undefined,
831845 interaction,
846+ undefined,
832847 );
833848 } catch (e) {
834849 status = this._logEnd(
@@ -837,6 +852,7 @@
837852 completion,
838853 undefined,
839854 interaction,
855+ undefined,
840856 e,
841857 );
842858 throw e;
@@ -848,6 +864,7 @@
848864 completion,
849865 undefined,
850866 interaction,
867+ undefined,
851868 "cancel",
852869 );
853870 }
@@ -944,6 +961,7 @@
944961 kind: "startChat",
945962 messages,
946963 options: completionOptions,
964+ provider: this.providerName,
947965 });
948966 if (this.llmRequestHook) {
949967 this.llmRequestHook(completionOptions.model, prompt);
@@ -952,6 +970,7 @@
952970
953971 let thinking = "";
954972 let completion = "";
973+ let usage: Usage | undefined = undefined;
955974
956975 try {
957976 if (this.templateMessages) {
@@ -1018,6 +1037,11 @@
10181037 kind: "message",
10191038 message: chunk,
10201039 });
1040+
1041+ if (chunk.role === "assistant" && chunk.usage) {
1042+ usage = chunk.usage;
1043+ }
1044+
10211045 yield chunk;
10221046 }
10231047 }
@@ -1028,6 +1052,7 @@
10281052 completion,
10291053 thinking,
10301054 interaction,
1055+ usage,
10311056 );
10321057 } catch (e) {
10331058 status = this._logEnd(
@@ -1036,6 +1061,7 @@
10361061 completion,
10371062 thinking,
10381063 interaction,
1064+ usage,
10391065 e,
10401066 );
10411067 throw e;
@@ -1047,6 +1073,7 @@
10471073 completion,
10481074 undefined,
10491075 interaction,
1076+ usage,
10501077 "cancel",
10511078 );
10521079 }
modified core/llm/llms/Anthropic.ts +47 −3
@@ -1,5 +1,10 @@
11 import { streamSse } from "@continuedev/fetch";
2-import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
2+import {
3+ ChatMessage,
4+ CompletionOptions,
5+ LLMOptions,
6+ Usage,
7+} from "../../index.js";
38 import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
49 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
510 import { BaseLLM } from "../index.js";
@@ -234,15 +239,49 @@
234239
235240 if (options.stream === false) {
236241 const data = await response.json();
237- yield { role: "assistant", content: data.content[0].text };
242+ const cost = data.usage
243+ ? {
244+ inputTokens: data.usage.input_tokens,
245+ outputTokens: data.usage.output_tokens,
246+ totalTokens: data.usage.input_tokens + data.usage.output_tokens,
247+ }
248+ : {};
249+ yield {
250+ role: "assistant",
251+ content: data.content[0].text,
252+ ...(Object.keys(cost).length > 0 ? { cost } : {}),
253+ };
238254 return;
239255 }
240256
241257 let lastToolUseId: string | undefined;
242258 let lastToolUseName: string | undefined;
259+ let usage: Usage = {
260+ promptTokens: 0,
261+ completionTokens: 0,
262+ promptTokensDetails: {
263+ cachedTokens: 0,
264+ cacheWriteTokens: 0,
265+ },
266+ };
267+
243268 for await (const value of streamSse(response)) {
244269 // https://docs.anthropic.com/en/api/messages-streaming#event-types
245270 switch (value.type) {
271+ case "message_start":
272+ // Capture initial usage information
273+ usage.promptTokens = value.message.usage.input_tokens;
274+ usage.promptTokensDetails!.cachedTokens =
275+ value.message.usage.cache_read_input_tokens;
276+ usage.promptTokensDetails!.cacheWriteTokens =
277+ value.message.usage.cache_creation_input_tokens;
278+ break;
279+ case "message_delta":
280+ // Update usage information during streaming
281+ if (value.usage) {
282+ usage.completionTokens = value.usage.output_tokens;
283+ }
284+ break;
246285 case "content_block_start":
247286 if (value.content_block.type === "tool_use") {
248287 lastToolUseId = value.content_block.id;
@@ -250,7 +289,6 @@
250289 }
251290 // handle redacted thinking
252291 if (value.content_block.type === "redacted_thinking") {
253- console.log("redacted thinking", value.content_block.data);
254292 yield {
255293 role: "thinking",
256294 content: "",
@@ -303,6 +341,12 @@
303341 break;
304342 }
305343 }
344+
345+ yield {
346+ role: "assistant",
347+ content: "",
348+ usage,
349+ };
306350 }
307351 }
308352
added core/llm/llms/Anthropic.vitest.ts +495 −0
@@ -0,0 +1,495 @@
1+import { afterEach, describe, expect, test, vi } from "vitest";
2+import { ILLM } from "../../index.js";
3+import Anthropic from "./Anthropic.js";
4+
5+interface LlmTestCase {
6+ llm: ILLM;
7+ methodToTest: keyof ILLM;
8+ params: any[];
9+ expectedRequest: {
10+ url: string;
11+ method: string;
12+ headers?: Record<string, string>;
13+ body?: Record<string, any>;
14+ };
15+ mockResponse?: any;
16+ mockStream?: any[];
17+}
18+
19+function createMockStream(mockStream: any[]) {
20+ const encoder = new TextEncoder();
21+ return new ReadableStream({
22+ start(controller) {
23+ for (const chunk of mockStream) {
24+ controller.enqueue(
25+ encoder.encode(
26+ `data: ${
27+ typeof chunk === "string" ? chunk : JSON.stringify(chunk)
28+ }\n\n`,
29+ ),
30+ );
31+ }
32+ controller.close();
33+ },
34+ });
35+}
36+
37+function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
38+ const mockFetch = vi.fn();
39+
40+ if (mockStream) {
41+ const stream = createMockStream(mockStream);
42+ mockFetch.mockResolvedValue(
43+ new Response(stream, {
44+ headers: {
45+ "Content-Type": "text/event-stream",
46+ },
47+ }),
48+ );
49+ } else {
50+ mockFetch.mockResolvedValue(
51+ new Response(JSON.stringify(mockResponse), {
52+ headers: { "Content-Type": "application/json" },
53+ }),
54+ );
55+ }
56+
57+ return mockFetch;
58+}
59+
60+function setupReadableStreamPolyfill() {
61+ // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
62+ // @ts-ignore
63+ const originalFrom = ReadableStream.from;
64+ // @ts-ignore
65+ ReadableStream.from = (body) => {
66+ if (body?.source) {
67+ return body;
68+ }
69+ return originalFrom(body);
70+ };
71+}
72+
73+async function executeLlmMethod(
74+ llm: ILLM,
75+ methodToTest: keyof ILLM,
76+ params: any[],
77+) {
78+ if (typeof (llm as any)[methodToTest] !== "function") {
79+ throw new Error(
80+ `Method ${String(methodToTest)} does not exist on the LLM instance.`,
81+ );
82+ }
83+
84+ const result = await (llm as any)[methodToTest](...params);
85+ if (result?.next) {
86+ for await (const _ of result) {
87+ }
88+ }
89+}
90+
91+function assertFetchCall(mockFetch: any, expectedRequest: any) {
92+ expect(mockFetch).toHaveBeenCalledTimes(1);
93+ const [url, options] = mockFetch.mock.calls[0];
94+
95+ expect(url.toString()).toBe(expectedRequest.url);
96+ expect(options.method).toBe(expectedRequest.method);
97+
98+ if (expectedRequest.headers) {
99+ expect(options.headers).toEqual(
100+ expect.objectContaining(expectedRequest.headers),
101+ );
102+ }
103+
104+ if (expectedRequest.body) {
105+ const actualBody = JSON.parse(options.body as string);
106+ expect(actualBody).toEqual(expectedRequest.body);
107+ }
108+}
109+
110+async function runLlmTest(testCase: LlmTestCase) {
111+ const {
112+ llm,
113+ methodToTest,
114+ params,
115+ expectedRequest,
116+ mockResponse,
117+ mockStream,
118+ } = testCase;
119+
120+ const mockFetch = setupMockFetch(mockResponse, mockStream);
121+ setupReadableStreamPolyfill();
122+
123+ (llm as any).fetch = mockFetch;
124+
125+ await executeLlmMethod(llm, methodToTest, params);
126+ assertFetchCall(mockFetch, expectedRequest);
127+}
128+
129+describe("Anthropic", () => {
130+ afterEach(() => {
131+ vi.clearAllMocks();
132+ });
133+
134+ test("streamChat should send a valid request", async () => {
135+ const anthropic = new Anthropic({
136+ apiKey: "test-api-key",
137+ model: "claude-3-5-sonnet-latest",
138+ apiBase: "https://api.anthropic.com/v1/",
139+ });
140+
141+ await runLlmTest({
142+ llm: anthropic,
143+ methodToTest: "streamChat",
144+ params: [
145+ [{ role: "user", content: "hello" }],
146+ new AbortController().signal,
147+ ],
148+ expectedRequest: {
149+ url: "https://api.anthropic.com/v1/messages",
150+ method: "POST",
151+ headers: {
152+ "Content-Type": "application/json",
153+ Accept: "application/json",
154+ "anthropic-version": "2023-06-01",
155+ "x-api-key": "test-api-key",
156+ },
157+ body: {
158+ model: "claude-3-5-sonnet-latest",
159+ max_tokens: 8192,
160+ stream: true,
161+ messages: [
162+ {
163+ role: "user",
164+ content: [{ type: "text", text: "hello" }],
165+ },
166+ ],
167+ system: "",
168+ },
169+ },
170+ mockStream: [
171+ '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
172+ '{"type": "content_block_stop"}',
173+ ],
174+ });
175+ });
176+
177+ test("chat should send a valid request", async () => {
178+ const anthropic = new Anthropic({
179+ apiKey: "test-api-key",
180+ model: "claude-3-5-sonnet-latest",
181+ apiBase: "https://api.anthropic.com/v1/",
182+ });
183+
184+ await runLlmTest({
185+ llm: anthropic,
186+ methodToTest: "chat",
187+ params: [
188+ [{ role: "user", content: "hello" }],
189+ new AbortController().signal,
190+ ],
191+ expectedRequest: {
192+ url: "https://api.anthropic.com/v1/messages",
193+ method: "POST",
194+ headers: {
195+ "Content-Type": "application/json",
196+ Accept: "application/json",
197+ "anthropic-version": "2023-06-01",
198+ "x-api-key": "test-api-key",
199+ },
200+ body: {
201+ model: "claude-3-5-sonnet-latest",
202+ max_tokens: 8192,
203+ stream: true,
204+ messages: [
205+ {
206+ role: "user",
207+ content: [{ type: "text", text: "hello" }],
208+ },
209+ ],
210+ system: "",
211+ },
212+ },
213+ mockStream: [
214+ '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
215+ '{"type": "content_block_stop"}',
216+ ],
217+ });
218+ });
219+
220+ test("streamComplete should send a valid request", async () => {
221+ const anthropic = new Anthropic({
222+ apiKey: "test-api-key",
223+ model: "claude-3-5-sonnet-latest",
224+ apiBase: "https://api.anthropic.com/v1/",
225+ });
226+
227+ await runLlmTest({
228+ llm: anthropic,
229+ methodToTest: "streamComplete",
230+ params: ["Complete this: Hello", new AbortController().signal],
231+ expectedRequest: {
232+ url: "https://api.anthropic.com/v1/messages",
233+ method: "POST",
234+ headers: {
235+ "Content-Type": "application/json",
236+ Accept: "application/json",
237+ "anthropic-version": "2023-06-01",
238+ "x-api-key": "test-api-key",
239+ },
240+ body: {
241+ model: "claude-3-5-sonnet-latest",
242+ max_tokens: 8192,
243+ stream: true,
244+ messages: [
245+ {
246+ role: "user",
247+ content: [{ type: "text", text: "Complete this: Hello" }],
248+ },
249+ ],
250+ system: "",
251+ },
252+ },
253+ mockStream: [
254+ '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
255+ '{"type": "content_block_stop"}',
256+ ],
257+ });
258+ });
259+
260+ test("complete should send a valid request", async () => {
261+ const anthropic = new Anthropic({
262+ apiKey: "test-api-key",
263+ model: "claude-3-5-sonnet-latest",
264+ apiBase: "https://api.anthropic.com/v1/",
265+ });
266+
267+ await runLlmTest({
268+ llm: anthropic,
269+ methodToTest: "complete",
270+ params: ["Complete this: Hello", new AbortController().signal],
271+ expectedRequest: {
272+ url: "https://api.anthropic.com/v1/messages",
273+ method: "POST",
274+ headers: {
275+ "Content-Type": "application/json",
276+ Accept: "application/json",
277+ "anthropic-version": "2023-06-01",
278+ "x-api-key": "test-api-key",
279+ },
280+ body: {
281+ model: "claude-3-5-sonnet-latest",
282+ max_tokens: 8192,
283+ stream: true,
284+ messages: [
285+ {
286+ role: "user",
287+ content: [{ type: "text", text: "Complete this: Hello" }],
288+ },
289+ ],
290+ system: "",
291+ },
292+ },
293+ mockStream: [
294+ '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
295+ '{"type": "content_block_stop"}',
296+ ],
297+ });
298+ });
299+
300+ describe("Different configurations", () => {
301+ test("should handle system message", async () => {
302+ const anthropic = new Anthropic({
303+ apiKey: "test-api-key",
304+ model: "claude-3-5-sonnet-latest",
305+ apiBase: "https://api.anthropic.com/v1/",
306+ });
307+
308+ await runLlmTest({
309+ llm: anthropic,
310+ methodToTest: "streamChat",
311+ params: [
312+ [
313+ { role: "system", content: "You are a helpful assistant." },
314+ { role: "user", content: "Hello!" },
315+ ],
316+ new AbortController().signal,
317+ ],
318+ expectedRequest: {
319+ url: "https://api.anthropic.com/v1/messages",
320+ method: "POST",
321+ headers: {
322+ "Content-Type": "application/json",
323+ Accept: "application/json",
324+ "anthropic-version": "2023-06-01",
325+ "x-api-key": "test-api-key",
326+ },
327+ body: {
328+ model: "claude-3-5-sonnet-latest",
329+ max_tokens: 8192,
330+ stream: true,
331+ messages: [
332+ {
333+ role: "user",
334+ content: [{ type: "text", text: "Hello!" }],
335+ },
336+ ],
337+ system: "You are a helpful assistant.",
338+ },
339+ },
340+ mockStream: [
341+ '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
342+ '{"type": "content_block_stop"}',
343+ ],
344+ });
345+ });
346+
347+ test("should handle tool calls", async () => {
348+ const anthropic = new Anthropic({
349+ apiKey: "test-api-key",
350+ model: "claude-3-5-sonnet-latest",
351+ apiBase: "https://api.anthropic.com/v1/",
352+ });
353+
354+ const tools = [
355+ {
356+ type: "function" as const,
357+ function: {
358+ name: "get_weather",
359+ description: "Get the current weather",
360+ parameters: {
361+ type: "object",
362+ properties: {
363+ location: { type: "string" },
364+ },
365+ required: ["location"],
366+ },
367+ },
368+ },
369+ ];
370+
371+ await runLlmTest({
372+ llm: anthropic,
373+ methodToTest: "streamChat",
374+ params: [
375+ [{ role: "user", content: "What's the weather in New York?" }],
376+ new AbortController().signal,
377+ { tools },
378+ ],
379+ expectedRequest: {
380+ url: "https://api.anthropic.com/v1/messages",
381+ method: "POST",
382+ headers: {
383+ "Content-Type": "application/json",
384+ Accept: "application/json",
385+ "anthropic-version": "2023-06-01",
386+ "x-api-key": "test-api-key",
387+ },
388+ body: {
389+ model: "claude-3-5-sonnet-latest",
390+ max_tokens: 8192,
391+ stream: true,
392+ messages: [
393+ {
394+ role: "user",
395+ content: [
396+ { type: "text", text: "What's the weather in New York?" },
397+ ],
398+ },
399+ ],
400+ tools: [
401+ {
402+ name: "get_weather",
403+ description: "Get the current weather",
404+ input_schema: {
405+ type: "object",
406+ properties: {
407+ location: { type: "string" },
408+ },
409+ required: ["location"],
410+ },
411+ },
412+ ],
413+ system: "",
414+ },
415+ },
416+ mockStream: [
417+ '{"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "get_weather"}}',
418+ '{"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\\"location\\": \\"New York\\""}}',
419+ '{"type": "content_block_stop"}',
420+ ],
421+ });
422+ });
423+
424+ test("should handle custom max tokens", async () => {
425+ const anthropic = new Anthropic({
426+ apiKey: "test-api-key",
427+ model: "claude-3-5-sonnet-latest",
428+ apiBase: "https://api.anthropic.com/v1/",
429+ });
430+
431+ await runLlmTest({
432+ llm: anthropic,
433+ methodToTest: "streamChat",
434+ params: [
435+ [{ role: "user", content: "hello" }],
436+ new AbortController().signal,
437+ { maxTokens: 1000 },
438+ ],
439+ expectedRequest: {
440+ url: "https://api.anthropic.com/v1/messages",
441+ method: "POST",
442+ headers: {
443+ "Content-Type": "application/json",
444+ Accept: "application/json",
445+ "anthropic-version": "2023-06-01",
446+ "x-api-key": "test-api-key",
447+ },
448+ body: {
449+ model: "claude-3-5-sonnet-latest",
450+ max_tokens: 1000,
451+ stream: true,
452+ messages: [
453+ {
454+ role: "user",
455+ content: [{ type: "text", text: "hello" }],
456+ },
457+ ],
458+ system: "",
459+ },
460+ },
461+ mockStream: [
462+ '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello!"}}',
463+ '{"type": "content_block_stop"}',
464+ ],
465+ });
466+ });
467+ });
468+
469+ describe("Error handling", () => {
470+ test("should throw error when API key is missing", async () => {
471+ const anthropic = new Anthropic({
472+ apiKey: "",
473+ model: "claude-3-5-sonnet-latest",
474+ apiBase: "https://api.anthropic.com/v1/",
475+ });
476+
477+ await expect(
478+ runLlmTest({
479+ llm: anthropic,
480+ methodToTest: "streamChat",
481+ params: [
482+ [{ role: "user", content: "hello" }],
483+ new AbortController().signal,
484+ ],
485+ expectedRequest: {
486+ url: "https://api.anthropic.com/v1/messages",
487+ method: "POST",
488+ },
489+ }),
490+ ).rejects.toThrow(
491+ "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
492+ );
493+ });
494+ });
495+});
modified core/llm/llms/Bedrock.ts +9 −29
@@ -11,18 +11,14 @@
1111 } from "@aws-sdk/client-bedrock-runtime";
1212 import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
1313
14-import {
15- ChatMessage,
16- Chunk,
17- CompletionOptions,
18- LLMOptions,
19- MessageContent,
20-} from "../../index.js";
14+import type { CompletionOptions } from "../../index.js";
15+import { ChatMessage, Chunk, LLMOptions, MessageContent } from "../../index.js";
2116 import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
2217 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
2318 import { BaseLLM } from "../index.js";
2419 import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
2520 import { getSecureID } from "../utils/getSecureID.js";
21+import { withLLMRetry } from "../utils/retry.js";
2622
2723 interface ModelConfig {
2824 formatPayload: (text: string) => any;
@@ -89,6 +85,7 @@
8985 }
9086 }
9187
88+ @withLLMRetry()
9289 protected async *_streamChat(
9390 messages: ChatMessage[],
9491 signal: AbortSignal,
@@ -132,16 +129,9 @@
132129 });
133130 const command = new ConverseStreamCommand(input);
134131
135- let response: ConverseStreamCommandOutput;
136- try {
137- response = (await client.send(command, {
138- abortSignal: signal,
139- })) as ConverseStreamCommandOutput;
140- } catch (error: unknown) {
141- console.error(error);
142- const message = error instanceof Error ? error.message : "Unknown error";
143- throw new Error(`Failed to communicate with Bedrock API: ${message}`);
144- }
132+ const response = (await client.send(command, {
133+ abortSignal: signal,
134+ })) as ConverseStreamCommandOutput;
145135
146136 if (!response?.stream) {
147137 throw new Error("No stream received from Bedrock API");
@@ -259,19 +249,9 @@
259249 }
260250 }
261251 } catch (error: unknown) {
252+ // Clean up state and let the original error bubble up to the retry decorator
262253 this._currentToolResponse = null;
263- if (error instanceof Error) {
264- if ("code" in error) {
265- // AWS SDK specific errors
266- throw new Error(
267- `AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
268- );
269- }
270- throw new Error(`Error processing Bedrock stream: ${error.message}`);
271- }
272- throw new Error(
273- "Error processing Bedrock stream: Unknown error occurred",
274- );
254+ throw error;
275255 }
276256 }
277257
modified core/llm/llms/Docker.ts +1 −1
@@ -17,7 +17,7 @@
1717 class Docker extends OpenAI implements ModelInstaller {
1818 static providerName = "docker";
1919 static defaultOptions: Partial<LLMOptions> = {
20- apiBase: "http://localhost:12434/engines/v1",
20+ apiBase: "http://localhost:12434/engines/v1/",
2121 model: "gemma3-4B-F4", // Default model
2222 };
2323
modified core/llm/llms/Fireworks.ts +1 −1
@@ -5,7 +5,7 @@
55 class Fireworks extends OpenAI {
66 static providerName = "fireworks";
77 static defaultOptions: Partial<LLMOptions> = {
8- apiBase: "https://api.fireworks.ai/inference/v1",
8+ apiBase: "https://api.fireworks.ai/inference/v1/",
99 };
1010
1111 private static modelConversion: { [key: string]: string } = {
added core/llm/llms/Fireworks.vitest.ts +12 −0
@@ -0,0 +1,12 @@
1+import Fireworks from "./Fireworks.js";
2+import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
3+
4+createOpenAISubclassTests(Fireworks, {
5+ providerName: "fireworks",
6+ defaultApiBase: "https://api.fireworks.ai/inference/v1/",
7+ modelConversions: {
8+ "starcoder-7b": "accounts/fireworks/models/starcoder-7b",
9+ },
10+ modelConversionContent:
11+ "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
12+});
added core/llm/llms/Groq.vitest.ts +12 −0
@@ -0,0 +1,12 @@
1+import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
2+import Groq from "./Groq.js";
3+
4+createOpenAISubclassTests(Groq, {
5+ providerName: "groq",
6+ defaultApiBase: "https://api.groq.com/openai/v1/",
7+ modelConversions: {
8+ "mistral-8x7b": "mixtral-8x7b-32768",
9+ "llama3-8b": "llama3-8b-8192",
10+ "llama3-70b": "llama3-70b-8192",
11+ },
12+});
modified core/llm/llms/Kindo.ts +1 −1
@@ -5,7 +5,7 @@
55 class Kindo extends OpenAI {
66 static providerName = "kindo";
77 static defaultOptions: Partial<LLMOptions> = {
8- apiBase: "https://llm.kindo.ai/v1",
8+ apiBase: "https://llm.kindo.ai/v1/",
99 requestOptions: {
1010 headers: {
1111 "kindo-token-transaction-type": "CONTINUE",
modified core/llm/llms/NCompass.ts +2 −2
@@ -6,9 +6,9 @@
66 class NCompass extends OpenAI {
77 static providerName = "ncompass";
88 static defaultOptions: Partial<LLMOptions> = {
9- apiBase: "https://api.ncompass.tech/v1",
9+ apiBase: "https://api.ncompass.tech/v1/",
1010 };
11- static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings";
11+ static embeddingsApiEndpoint = "https://api.gcp.ncompass.tech/v1/embeddings";
1212
1313 private static modelConversion: { [key: string]: string } = {
1414 "qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
added core/llm/llms/OpenAI-compatible-core.vitest.ts +294 −0
@@ -0,0 +1,294 @@
1+import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
2+
3+// Import core OpenAI-compatible providers
4+import OpenAI from "./OpenAI.js";
5+import Groq from "./Groq.js";
6+import Fireworks from "./Fireworks.js";
7+import Together from "./Together.js";
8+import Deepseek from "./Deepseek.js";
9+import OpenRouter from "./OpenRouter.js";
10+import xAI from "./xAI.js";
11+import Mistral from "./Mistral.js";
12+import LMStudio from "./LMStudio.js";
13+import Cerebras from "./Cerebras.js";
14+import DeepInfra from "./DeepInfra.js";
15+import Nvidia from "./Nvidia.js";
16+
17+// Base OpenAI tests
18+import { afterEach, describe, expect, test, vi } from "vitest";
19+import { ILLM } from "../../index.js";
20+
21+interface LlmTestCase {
22+ llm: ILLM;
23+ methodToTest: keyof ILLM;
24+ params: any[];
25+ expectedRequest: {
26+ url: string;
27+ method: string;
28+ headers?: Record<string, string>;
29+ body?: Record<string, any>;
30+ };
31+ mockResponse?: any;
32+ mockStream?: any[];
33+}
34+
35+function createMockStream(mockStream: any[]) {
36+ const encoder = new TextEncoder();
37+ return new ReadableStream({
38+ start(controller) {
39+ for (const chunk of mockStream) {
40+ controller.enqueue(
41+ encoder.encode(
42+ `data: ${
43+ typeof chunk === "string" ? chunk : JSON.stringify(chunk)
44+ }\n\n`,
45+ ),
46+ );
47+ }
48+ controller.close();
49+ },
50+ });
51+}
52+
53+function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
54+ const mockFetch = vi.fn();
55+
56+ if (mockStream) {
57+ const stream = createMockStream(mockStream);
58+ mockFetch.mockResolvedValue(
59+ new Response(stream, {
60+ headers: {
61+ "Content-Type": "text/event-stream",
62+ },
63+ }),
64+ );
65+ } else {
66+ mockFetch.mockResolvedValue(
67+ new Response(JSON.stringify(mockResponse), {
68+ headers: { "Content-Type": "application/json" },
69+ }),
70+ );
71+ }
72+
73+ return mockFetch;
74+}
75+
76+function setupReadableStreamPolyfill() {
77+ // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
78+ // @ts-ignore
79+ const originalFrom = ReadableStream.from;
80+ // @ts-ignore
81+ ReadableStream.from = (body) => {
82+ if (body?.source) {
83+ return body;
84+ }
85+ return originalFrom(body);
86+ };
87+}
88+
89+async function executeLlmMethod(
90+ llm: ILLM,
91+ methodToTest: keyof ILLM,
92+ params: any[],
93+) {
94+ if (typeof (llm as any)[methodToTest] !== "function") {
95+ throw new Error(
96+ `Method ${String(methodToTest)} does not exist on the LLM instance.`,
97+ );
98+ }
99+
100+ const result = await (llm as any)[methodToTest](...params);
101+ if (result?.next) {
102+ for await (const _ of result) {
103+ }
104+ }
105+}
106+
107+function assertFetchCall(mockFetch: any, expectedRequest: any) {
108+ expect(mockFetch).toHaveBeenCalledTimes(1);
109+ const [url, options] = mockFetch.mock.calls[0];
110+
111+ expect(url.toString()).toBe(expectedRequest.url);
112+ expect(options.method).toBe(expectedRequest.method);
113+
114+ if (expectedRequest.headers) {
115+ expect(options.headers).toEqual(
116+ expect.objectContaining(expectedRequest.headers),
117+ );
118+ }
119+
120+ if (expectedRequest.body) {
121+ const actualBody = JSON.parse(options.body as string);
122+ expect(actualBody).toEqual(expectedRequest.body);
123+ }
124+}
125+
126+async function runLlmTest(testCase: LlmTestCase) {
127+ const {
128+ llm,
129+ methodToTest,
130+ params,
131+ expectedRequest,
132+ mockResponse,
133+ mockStream,
134+ } = testCase;
135+
136+ const mockFetch = setupMockFetch(mockResponse, mockStream);
137+ setupReadableStreamPolyfill();
138+
139+ (llm as any).fetch = mockFetch;
140+
141+ // Disable OpenAI adapter to use our custom fetch mock
142+ (llm as any).useOpenAIAdapterFor = [];
143+
144+ await executeLlmMethod(llm, methodToTest, params);
145+ assertFetchCall(mockFetch, expectedRequest);
146+}
147+
148+describe("OpenAI", () => {
149+ afterEach(() => {
150+ vi.clearAllMocks();
151+ });
152+
153+ test("streamChat should send a valid request", async () => {
154+ const openai = new OpenAI({
155+ apiKey: "test-api-key",
156+ model: "gpt-4",
157+ apiBase: "https://api.openai.com/v1/",
158+ });
159+
160+ await runLlmTest({
161+ llm: openai,
162+ methodToTest: "streamChat",
163+ params: [
164+ [{ role: "user", content: "hello" }],
165+ new AbortController().signal,
166+ ],
167+ expectedRequest: {
168+ url: "https://api.openai.com/v1/chat/completions",
169+ method: "POST",
170+ headers: {
171+ "Content-Type": "application/json",
172+ Authorization: "Bearer test-api-key",
173+ "api-key": "test-api-key",
174+ },
175+ body: {
176+ model: "gpt-4",
177+ messages: [{ role: "user", content: "hello" }],
178+ stream: true,
179+ max_tokens: 2048,
180+ },
181+ },
182+ mockStream: [
183+ { choices: [{ delta: { content: "Hello" } }] },
184+ { choices: [{ delta: { content: " world" } }] },
185+ ],
186+ });
187+ });
188+});
189+
190+// Core OpenAI-compatible providers
191+createOpenAISubclassTests(Groq, {
192+ providerName: "groq",
193+ defaultApiBase: "https://api.groq.com/openai/v1/",
194+ modelConversions: {
195+ "mistral-8x7b": "mistral-8x7b",
196+ "llama3-8b": "llama3-8b-8192",
197+ },
198+ modelConversionContent: "[INST] hello [/INST]",
199+ modelConversionMaxTokens: 4096,
200+});
201+
202+createOpenAISubclassTests(Fireworks, {
203+ providerName: "fireworks",
204+ defaultApiBase: "https://api.fireworks.ai/inference/v1/",
205+ modelConversions: {
206+ "starcoder-7b": "starcoder-7b",
207+ },
208+ modelConversionContent:
209+ "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
210+});
211+
212+createOpenAISubclassTests(Together, {
213+ providerName: "together",
214+ defaultApiBase: "https://api.together.xyz/v1/",
215+ modelConversions: {
216+ "codellama-7b": "codellama-7b",
217+ "llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
218+ },
219+ modelConversionContent: "hello",
220+ customStreamCompleteEndpoint: "completions",
221+});
222+
223+createOpenAISubclassTests(Deepseek, {
224+ providerName: "deepseek",
225+ defaultApiBase: "https://api.deepseek.com/",
226+});
227+
228+createOpenAISubclassTests(OpenRouter, {
229+ providerName: "openrouter",
230+ defaultApiBase: "https://openrouter.ai/api/v1/",
231+});
232+
233+createOpenAISubclassTests(xAI, {
234+ providerName: "xAI",
235+ defaultApiBase: "https://api.x.ai/v1/",
236+ modelConversions: {
237+ "grok-beta": "grok-beta",
238+ },
239+ modelConversionContent: "hello",
240+});
241+
242+createOpenAISubclassTests(Mistral, {
243+ providerName: "mistral",
244+ defaultApiBase: "https://api.mistral.ai/v1/",
245+ modelConversions: {
246+ "mistral-7b": "mistral-7b",
247+ "mistral-8x7b": "open-mixtral-8x7b",
248+ },
249+ modelConversionContent: "hello",
250+});
251+
252+createOpenAISubclassTests(LMStudio, {
253+ providerName: "lmstudio",
254+ defaultApiBase: "http://localhost:1234/v1/",
255+});
256+
257+createOpenAISubclassTests(Cerebras, {
258+ providerName: "cerebras",
259+ defaultApiBase: "https://api.cerebras.ai/v1/",
260+ modelConversions: {
261+ "llama3.1-8b": "llama3.1-8b",
262+ "llama3.1-70b": "llama3.1-70b",
263+ },
264+ modelConversionContent:
265+ "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
266+});
267+
268+createOpenAISubclassTests(DeepInfra, {
269+ providerName: "deepinfra",
270+ defaultApiBase: "https://api.deepinfra.com/v1/openai/",
271+ customEmbeddingsUrl:
272+ "https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
273+ customEmbeddingsHeaders: {
274+ Authorization: "bearer test-api-key",
275+ },
276+ customEmbeddingsBody: {
277+ inputs: ["Hello", "World"],
278+ },
279+});
280+
281+createOpenAISubclassTests(Nvidia, {
282+ providerName: "nvidia",
283+ defaultApiBase: "https://integrate.api.nvidia.com/v1/",
284+ customEmbeddingsHeaders: {
285+ Authorization: "Bearer test-api-key",
286+ "Content-Type": "application/json",
287+ },
288+ customEmbeddingsBody: {
289+ input: ["Hello", "World"],
290+ model: "text-embedding-ada-002",
291+ input_type: "passage",
292+ truncate: "END",
293+ },
294+});
added core/llm/llms/OpenAI-compatible.vitest.ts +453 −0
@@ -0,0 +1,453 @@
1+import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
2+
3+// Import all OpenAI-compatible providers
4+import OpenAI from "./OpenAI.js";
5+import Groq from "./Groq.js";
6+import Fireworks from "./Fireworks.js";
7+import Together from "./Together.js";
8+import Deepseek from "./Deepseek.js";
9+import OpenRouter from "./OpenRouter.js";
10+import xAI from "./xAI.js";
11+import Mistral from "./Mistral.js";
12+import LMStudio from "./LMStudio.js";
13+import Cerebras from "./Cerebras.js";
14+import DeepInfra from "./DeepInfra.js";
15+import Nvidia from "./Nvidia.js";
16+import SambaNova from "./SambaNova.js";
17+import Scaleway from "./Scaleway.js";
18+import Venice from "./Venice.js";
19+import Moonshot from "./Moonshot.js";
20+import Novita from "./Novita.js";
21+import SiliconFlow from "./SiliconFlow.js";
22+import Kindo from "./Kindo.js";
23+import Azure from "./Azure.js";
24+import Inception from "./Inception.js";
25+import Docker from "./Docker.js";
26+import Voyage from "./Voyage.js";
27+import Vllm from "./Vllm.js";
28+import TextGenWebUI from "./TextGenWebUI.js";
29+// import Relace from "./Relace.js"; // Skip - causing import issues
30+import FunctionNetwork from "./FunctionNetwork.js";
31+import NCompass from "./NCompass.js";
32+import LlamaStack from "./LlamaStack.js";
33+import Nebius from "./Nebius.js";
34+import OVHcloud from "./OVHcloud.js";
35+
36+// Base OpenAI tests
37+import { afterEach, describe, expect, test, vi } from "vitest";
38+import { ILLM } from "../../index.js";
39+
40+interface LlmTestCase {
41+ llm: ILLM;
42+ methodToTest: keyof ILLM;
43+ params: any[];
44+ expectedRequest: {
45+ url: string;
46+ method: string;
47+ headers?: Record<string, string>;
48+ body?: Record<string, any>;
49+ };
50+ mockResponse?: any;
51+ mockStream?: any[];
52+}
53+
54+function createMockStream(mockStream: any[]) {
55+ const encoder = new TextEncoder();
56+ return new ReadableStream({
57+ start(controller) {
58+ for (const chunk of mockStream) {
59+ controller.enqueue(
60+ encoder.encode(
61+ `data: ${
62+ typeof chunk === "string" ? chunk : JSON.stringify(chunk)
63+ }\n\n`,
64+ ),
65+ );
66+ }
67+ controller.close();
68+ },
69+ });
70+}
71+
72+function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
73+ const mockFetch = vi.fn();
74+
75+ if (mockStream) {
76+ const stream = createMockStream(mockStream);
77+ mockFetch.mockResolvedValue(
78+ new Response(stream, {
79+ headers: {
80+ "Content-Type": "text/event-stream",
81+ },
82+ }),
83+ );
84+ } else {
85+ mockFetch.mockResolvedValue(
86+ new Response(JSON.stringify(mockResponse), {
87+ headers: { "Content-Type": "application/json" },
88+ }),
89+ );
90+ }
91+
92+ return mockFetch;
93+}
94+
95+function setupReadableStreamPolyfill() {
96+ // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
97+ // @ts-ignore
98+ const originalFrom = ReadableStream.from;
99+ // @ts-ignore
100+ ReadableStream.from = (body) => {
101+ if (body?.source) {
102+ return body;
103+ }
104+ return originalFrom(body);
105+ };
106+}
107+
108+async function executeLlmMethod(
109+ llm: ILLM,
110+ methodToTest: keyof ILLM,
111+ params: any[],
112+) {
113+ if (typeof (llm as any)[methodToTest] !== "function") {
114+ throw new Error(
115+ `Method ${String(methodToTest)} does not exist on the LLM instance.`,
116+ );
117+ }
118+
119+ const result = await (llm as any)[methodToTest](...params);
120+ if (result?.next) {
121+ for await (const _ of result) {
122+ }
123+ }
124+}
125+
126+function assertFetchCall(mockFetch: any, expectedRequest: any) {
127+ expect(mockFetch).toHaveBeenCalledTimes(1);
128+ const [url, options] = mockFetch.mock.calls[0];
129+
130+ expect(url.toString()).toBe(expectedRequest.url);
131+ expect(options.method).toBe(expectedRequest.method);
132+
133+ if (expectedRequest.headers) {
134+ expect(options.headers).toEqual(
135+ expect.objectContaining(expectedRequest.headers),
136+ );
137+ }
138+
139+ if (expectedRequest.body) {
140+ const actualBody = JSON.parse(options.body as string);
141+ expect(actualBody).toEqual(expectedRequest.body);
142+ }
143+}
144+
145+async function runLlmTest(testCase: LlmTestCase) {
146+ const {
147+ llm,
148+ methodToTest,
149+ params,
150+ expectedRequest,
151+ mockResponse,
152+ mockStream,
153+ } = testCase;
154+
155+ const mockFetch = setupMockFetch(mockResponse, mockStream);
156+ setupReadableStreamPolyfill();
157+
158+ (llm as any).fetch = mockFetch;
159+
160+ // Disable OpenAI adapter to use our custom fetch mock
161+ (llm as any).useOpenAIAdapterFor = [];
162+
163+ await executeLlmMethod(llm, methodToTest, params);
164+ assertFetchCall(mockFetch, expectedRequest);
165+}
166+
167+describe("OpenAI", () => {
168+ afterEach(() => {
169+ vi.clearAllMocks();
170+ });
171+
172+ test("streamChat should send a valid request", async () => {
173+ const openai = new OpenAI({
174+ apiKey: "test-api-key",
175+ model: "gpt-4",
176+ apiBase: "https://api.openai.com/v1/",
177+ });
178+
179+ await runLlmTest({
180+ llm: openai,
181+ methodToTest: "streamChat",
182+ params: [
183+ [{ role: "user", content: "hello" }],
184+ new AbortController().signal,
185+ ],
186+ expectedRequest: {
187+ url: "https://api.openai.com/v1/chat/completions",
188+ method: "POST",
189+ headers: {
190+ "Content-Type": "application/json",
191+ Authorization: "Bearer test-api-key",
192+ "api-key": "test-api-key",
193+ },
194+ body: {
195+ model: "gpt-4",
196+ messages: [{ role: "user", content: "hello" }],
197+ stream: true,
198+ max_tokens: 2048,
199+ },
200+ },
201+ mockStream: [
202+ { choices: [{ delta: { content: "Hello" } }] },
203+ { choices: [{ delta: { content: " world" } }] },
204+ ],
205+ });
206+ });
207+
208+ test("should handle embeddings", async () => {
209+ const openai = new OpenAI({
210+ apiKey: "test-api-key",
211+ model: "text-embedding-ada-002",
212+ apiBase: "https://api.openai.com/v1/",
213+ });
214+
215+ await runLlmTest({
216+ llm: openai,
217+ methodToTest: "embed",
218+ params: [["Hello", "World"]],
219+ expectedRequest: {
220+ url: "https://api.openai.com/v1/embeddings",
221+ method: "POST",
222+ headers: {
223+ Authorization: "Bearer test-api-key",
224+ "Content-Type": "application/json",
225+ "api-key": "test-api-key",
226+ },
227+ body: {
228+ input: ["Hello", "World"],
229+ model: "text-embedding-ada-002",
230+ },
231+ },
232+ mockResponse: {
233+ data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
234+ },
235+ });
236+ });
237+});
238+
239+// OpenAI-compatible providers
240+createOpenAISubclassTests(Groq, {
241+ providerName: "groq",
242+ defaultApiBase: "https://api.groq.com/openai/v1/",
243+ modelConversions: {
244+ "mistral-8x7b": "mixtral-8x7b-32768",
245+ "llama3-8b": "llama3-8b-8192",
246+ "llama3-70b": "llama3-70b-8192",
247+ },
248+ modelConversionContent: "[INST] hello [/INST]",
249+ modelConversionMaxTokens: 4096,
250+});
251+
252+createOpenAISubclassTests(Fireworks, {
253+ providerName: "fireworks",
254+ defaultApiBase: "https://api.fireworks.ai/inference/v1/",
255+ modelConversions: {
256+ "starcoder-7b": "accounts/fireworks/models/starcoder-7b",
257+ },
258+ modelConversionContent:
259+ "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
260+});
261+
262+createOpenAISubclassTests(Together, {
263+ providerName: "together",
264+ defaultApiBase: "https://api.together.xyz/v1/",
265+ modelConversions: {
266+ "codellama-7b": "codellama-7b",
267+ "llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
268+ "mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
269+ },
270+ modelConversionContent: "hello",
271+ customStreamCompleteEndpoint: "completions",
272+});
273+
274+createOpenAISubclassTests(Deepseek, {
275+ providerName: "deepseek",
276+ defaultApiBase: "https://api.deepseek.com/",
277+});
278+
279+createOpenAISubclassTests(OpenRouter, {
280+ providerName: "openrouter",
281+ defaultApiBase: "https://openrouter.ai/api/v1/",
282+});
283+
284+createOpenAISubclassTests(xAI, {
285+ providerName: "xAI",
286+ defaultApiBase: "https://api.x.ai/v1/",
287+ modelConversions: {
288+ "grok-beta": "grok-beta",
289+ },
290+ modelConversionContent: "hello",
291+});
292+
293+createOpenAISubclassTests(Mistral, {
294+ providerName: "mistral",
295+ defaultApiBase: "https://api.mistral.ai/v1/",
296+ modelConversions: {
297+ "mistral-7b": "mistral-7b",
298+ "mistral-8x7b": "open-mixtral-8x7b",
299+ },
300+ modelConversionContent: "hello",
301+});
302+
303+createOpenAISubclassTests(LMStudio, {
304+ providerName: "lmstudio",
305+ defaultApiBase: "http://localhost:1234/v1/",
306+});
307+
308+createOpenAISubclassTests(Cerebras, {
309+ providerName: "cerebras",
310+ defaultApiBase: "https://api.cerebras.ai/v1/",
311+ modelConversions: {
312+ "llama3.1-8b": "llama3.1-8b",
313+ "llama3.1-70b": "llama3.1-70b",
314+ },
315+ modelConversionContent:
316+ "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
317+});
318+
319+createOpenAISubclassTests(DeepInfra, {
320+ providerName: "deepinfra",
321+ defaultApiBase: "https://api.deepinfra.com/v1/openai/",
322+ customEmbeddingsUrl:
323+ "https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
324+ customEmbeddingsHeaders: {
325+ Authorization: "bearer test-api-key",
326+ },
327+ customEmbeddingsBody: {
328+ inputs: ["Hello", "World"],
329+ },
330+});
331+
332+createOpenAISubclassTests(Nvidia, {
333+ providerName: "nvidia",
334+ defaultApiBase: "https://integrate.api.nvidia.com/v1/",
335+ customEmbeddingsHeaders: {
336+ Authorization: "Bearer test-api-key",
337+ "Content-Type": "application/json",
338+ },
339+ customEmbeddingsBody: {
340+ input: ["Hello", "World"],
341+ model: "text-embedding-ada-002",
342+ input_type: "passage",
343+ truncate: "END",
344+ },
345+});
346+
347+createOpenAISubclassTests(SambaNova, {
348+ providerName: "sambanova",
349+ defaultApiBase: "https://api.sambanova.ai/v1/",
350+});
351+
352+createOpenAISubclassTests(Scaleway, {
353+ providerName: "scaleway",
354+ defaultApiBase: "https://api.scaleway.ai/v1/",
355+});
356+
357+createOpenAISubclassTests(Venice, {
358+ providerName: "venice",
359+ defaultApiBase: "https://api.venice.ai/api/v1/",
360+});
361+
362+createOpenAISubclassTests(Moonshot, {
363+ providerName: "moonshot",
364+ defaultApiBase: "https://api.moonshot.cn/v1/",
365+});
366+
367+createOpenAISubclassTests(Novita, {
368+ providerName: "novita",
369+ defaultApiBase: "https://api.novita.ai/v3/openai/",
370+ customStreamCompleteEndpoint: "completions",
371+});
372+
373+createOpenAISubclassTests(SiliconFlow, {
374+ providerName: "siliconflow",
375+ defaultApiBase: "https://api.siliconflow.cn/v1/",
376+});
377+
378+createOpenAISubclassTests(Kindo, {
379+ providerName: "kindo",
380+ defaultApiBase: "https://llm.kindo.ai/v1/",
381+});
382+
383+createOpenAISubclassTests(Azure, {
384+ providerName: "azure",
385+});
386+
387+createOpenAISubclassTests(Inception, {
388+ providerName: "inception",
389+ defaultApiBase: "https://api.inceptionlabs.ai/v1/",
390+ customBodyOptions: {
391+ temperature: 0.0,
392+ presence_penalty: 1.5,
393+ stop: ["<|endoftext|>"],
394+ },
395+});
396+
397+createOpenAISubclassTests(Docker, {
398+ providerName: "docker",
399+ defaultApiBase: "http://localhost:12434/engines/v1/",
400+});
401+
402+createOpenAISubclassTests(Voyage, {
403+ providerName: "voyage",
404+ defaultApiBase: "https://api.voyageai.com/v1/",
405+});
406+
407+createOpenAISubclassTests(Vllm, {
408+ providerName: "vllm",
409+ defaultApiBase: "https://api.openai.com/v1/",
410+});
411+
412+createOpenAISubclassTests(TextGenWebUI, {
413+ providerName: "text-gen-webui",
414+ defaultApiBase: "http://localhost:5000/v1/",
415+});
416+
417+createOpenAISubclassTests(FunctionNetwork, {
418+ providerName: "function-network",
419+ defaultApiBase: "https://api.function.network/v1/",
420+ customEmbeddingsHeaders: {
421+ Authorization: "Bearer test-api-key",
422+ "Content-Type": "application/json",
423+ },
424+});
425+
426+createOpenAISubclassTests(NCompass, {
427+ providerName: "ncompass",
428+ defaultApiBase: "https://api.ncompass.tech/v1/",
429+ customEmbeddingsUrl: "https://api.gcp.ncompass.tech/v1/embeddings",
430+ customEmbeddingsHeaders: {
431+ Authorization: "Bearer test-api-key",
432+ "Content-Type": "application/json",
433+ },
434+ customEmbeddingsBody: {
435+ input: ["Hello", "World"],
436+ model: "text-embedding-ada-002",
437+ },
438+});
439+
440+createOpenAISubclassTests(LlamaStack, {
441+ providerName: "llamastack",
442+ defaultApiBase: "http://localhost:8321/v1/openai/v1/",
443+});
444+
445+createOpenAISubclassTests(Nebius, {
446+ providerName: "nebius",
447+ defaultApiBase: "https://api.studio.nebius.ai/v1/",
448+});
449+
450+createOpenAISubclassTests(OVHcloud, {
451+ providerName: "ovhcloud",
452+ defaultApiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
453+});
added core/llm/llms/OpenAI.vitest.ts +427 −0
@@ -0,0 +1,427 @@
1+import { afterEach, describe, expect, test, vi } from "vitest";
2+import { ILLM } from "../../index.js";
3+import OpenAI from "./OpenAI.js";
4+
5+interface LlmTestCase {
6+ llm: ILLM;
7+ methodToTest: keyof ILLM;
8+ params: any[];
9+ expectedRequest: {
10+ url: string;
11+ method: string;
12+ headers?: Record<string, string>;
13+ body?: Record<string, any>;
14+ };
15+ mockResponse?: any;
16+ mockStream?: any[];
17+}
18+
19+function createMockStream(mockStream: any[]) {
20+ const encoder = new TextEncoder();
21+ return new ReadableStream({
22+ start(controller) {
23+ for (const chunk of mockStream) {
24+ controller.enqueue(
25+ encoder.encode(
26+ `data: ${
27+ typeof chunk === "string" ? chunk : JSON.stringify(chunk)
28+ }\n\n`,
29+ ),
30+ );
31+ }
32+ controller.close();
33+ },
34+ });
35+}
36+
37+function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
38+ const mockFetch = vi.fn();
39+
40+ if (mockStream) {
41+ const stream = createMockStream(mockStream);
42+ mockFetch.mockResolvedValue(
43+ new Response(stream, {
44+ headers: {
45+ "Content-Type": "text/event-stream",
46+ },
47+ }),
48+ );
49+ } else {
50+ mockFetch.mockResolvedValue(
51+ new Response(JSON.stringify(mockResponse), {
52+ headers: { "Content-Type": "application/json" },
53+ }),
54+ );
55+ }
56+
57+ return mockFetch;
58+}
59+
60+function setupReadableStreamPolyfill() {
61+ // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
62+ // @ts-ignore
63+ const originalFrom = ReadableStream.from;
64+ // @ts-ignore
65+ ReadableStream.from = (body) => {
66+ if (body?.source) {
67+ return body;
68+ }
69+ return originalFrom(body);
70+ };
71+}
72+
73+async function executeLlmMethod(
74+ llm: ILLM,
75+ methodToTest: keyof ILLM,
76+ params: any[],
77+) {
78+ if (typeof (llm as any)[methodToTest] !== "function") {
79+ throw new Error(
80+ `Method ${String(methodToTest)} does not exist on the LLM instance.`,
81+ );
82+ }
83+
84+ const result = await (llm as any)[methodToTest](...params);
85+ if (result?.next) {
86+ for await (const _ of result) {
87+ }
88+ }
89+}
90+
91+function assertFetchCall(mockFetch: any, expectedRequest: any) {
92+ expect(mockFetch).toHaveBeenCalledTimes(1);
93+ const [url, options] = mockFetch.mock.calls[0];
94+
95+ expect(url.toString()).toBe(expectedRequest.url);
96+ expect(options.method).toBe(expectedRequest.method);
97+
98+ if (expectedRequest.headers) {
99+ expect(options.headers).toEqual(
100+ expect.objectContaining(expectedRequest.headers),
101+ );
102+ }
103+
104+ if (expectedRequest.body) {
105+ const actualBody = JSON.parse(options.body as string);
106+ expect(actualBody).toEqual(expectedRequest.body);
107+ }
108+}
109+
110+async function runLlmTest(testCase: LlmTestCase) {
111+ const {
112+ llm,
113+ methodToTest,
114+ params,
115+ expectedRequest,
116+ mockResponse,
117+ mockStream,
118+ } = testCase;
119+
120+ const mockFetch = setupMockFetch(mockResponse, mockStream);
121+ setupReadableStreamPolyfill();
122+
123+ (llm as any).fetch = mockFetch;
124+
125+ // Disable OpenAI adapter to use our custom fetch mock
126+ (llm as any).useOpenAIAdapterFor = [];
127+
128+ await executeLlmMethod(llm, methodToTest, params);
129+ assertFetchCall(mockFetch, expectedRequest);
130+}
131+
132+describe("OpenAI", () => {
133+ afterEach(() => {
134+ vi.clearAllMocks();
135+ });
136+
137+ test("streamChat should send a valid request", async () => {
138+ const openai = new OpenAI({
139+ apiKey: "test-api-key",
140+ model: "gpt-4",
141+ apiBase: "https://api.openai.com/v1/",
142+ });
143+
144+ await runLlmTest({
145+ llm: openai,
146+ methodToTest: "streamChat",
147+ params: [
148+ [{ role: "user", content: "hello" }],
149+ new AbortController().signal,
150+ ],
151+ expectedRequest: {
152+ url: "https://api.openai.com/v1/chat/completions",
153+ method: "POST",
154+ headers: {
155+ "Content-Type": "application/json",
156+ Authorization: "Bearer test-api-key",
157+ "api-key": "test-api-key",
158+ },
159+ body: {
160+ model: "gpt-4",
161+ messages: [{ role: "user", content: "hello" }],
162+ stream: true,
163+ max_tokens: 2048,
164+ },
165+ },
166+ mockStream: [
167+ { choices: [{ delta: { content: "Hello" } }] },
168+ { choices: [{ delta: { content: " world" } }] },
169+ ],
170+ });
171+ });
172+
173+ test("chat should send a valid request", async () => {
174+ const openai = new OpenAI({
175+ apiKey: "test-api-key",
176+ model: "gpt-4",
177+ apiBase: "https://api.openai.com/v1/",
178+ });
179+
180+ await runLlmTest({
181+ llm: openai,
182+ methodToTest: "chat",
183+ params: [
184+ [{ role: "user", content: "hello" }],
185+ new AbortController().signal,
186+ ],
187+ expectedRequest: {
188+ url: "https://api.openai.com/v1/chat/completions",
189+ method: "POST",
190+ headers: {
191+ "Content-Type": "application/json",
192+ Authorization: "Bearer test-api-key",
193+ "api-key": "test-api-key",
194+ },
195+ body: {
196+ model: "gpt-4",
197+ messages: [{ role: "user", content: "hello" }],
198+ stream: true,
199+ max_tokens: 2048,
200+ },
201+ },
202+ mockStream: [
203+ { choices: [{ delta: { content: "Hello" } }] },
204+ { choices: [{ delta: { content: " world" } }] },
205+ ],
206+ });
207+ });
208+
209+ test("streamComplete should send a valid request", async () => {
210+ const openai = new OpenAI({
211+ apiKey: "test-api-key",
212+ model: "gpt-4",
213+ apiBase: "https://api.openai.com/v1/",
214+ });
215+
216+ await runLlmTest({
217+ llm: openai,
218+ methodToTest: "streamComplete",
219+ params: ["Hello", new AbortController().signal],
220+ expectedRequest: {
221+ url: "https://api.openai.com/v1/chat/completions",
222+ method: "POST",
223+ headers: {
224+ "Content-Type": "application/json",
225+ Authorization: "Bearer test-api-key",
226+ "api-key": "test-api-key",
227+ },
228+ body: {
229+ model: "gpt-4",
230+ messages: [{ role: "user", content: "Hello" }],
231+ stream: true,
232+ max_tokens: 2048,
233+ },
234+ },
235+ mockStream: [
236+ { choices: [{ delta: { content: "Hello" } }] },
237+ { choices: [{ delta: { content: " world" } }] },
238+ ],
239+ });
240+ });
241+
242+ test("complete should send a valid request", async () => {
243+ const openai = new OpenAI({
244+ apiKey: "test-api-key",
245+ model: "gpt-4",
246+ apiBase: "https://api.openai.com/v1/",
247+ });
248+
249+ await runLlmTest({
250+ llm: openai,
251+ methodToTest: "complete",
252+ params: ["Hello", new AbortController().signal],
253+ expectedRequest: {
254+ url: "https://api.openai.com/v1/chat/completions",
255+ method: "POST",
256+ headers: {
257+ "Content-Type": "application/json",
258+ Authorization: "Bearer test-api-key",
259+ "api-key": "test-api-key",
260+ },
261+ body: {
262+ model: "gpt-4",
263+ messages: [{ role: "user", content: "Hello" }],
264+ stream: true,
265+ max_tokens: 2048,
266+ },
267+ },
268+ mockStream: [
269+ { choices: [{ delta: { content: "Hello" } }] },
270+ { choices: [{ delta: { content: " world" } }] },
271+ ],
272+ });
273+ });
274+
275+ test("should handle O1 models correctly", async () => {
276+ const openai = new OpenAI({
277+ apiKey: "test-api-key",
278+ model: "o1-preview",
279+ apiBase: "https://api.openai.com/v1/",
280+ });
281+
282+ await runLlmTest({
283+ llm: openai,
284+ methodToTest: "chat",
285+ params: [
286+ [{ role: "user", content: "hello" }],
287+ new AbortController().signal,
288+ { maxTokens: 100 },
289+ ],
290+ expectedRequest: {
291+ url: "https://api.openai.com/v1/chat/completions",
292+ method: "POST",
293+ headers: {
294+ "Content-Type": "application/json",
295+ Authorization: "Bearer test-api-key",
296+ "api-key": "test-api-key",
297+ },
298+ body: {
299+ model: "o1-preview",
300+ messages: [{ role: "user", content: "hello" }],
301+ stream: true,
302+ max_completion_tokens: 100,
303+ },
304+ },
305+ mockStream: [{ choices: [{ delta: { content: "Hello world" } }] }],
306+ });
307+ });
308+
309+ test("should handle tools", async () => {
310+ const openai = new OpenAI({
311+ apiKey: "test-api-key",
312+ model: "gpt-4",
313+ apiBase: "https://api.openai.com/v1/",
314+ });
315+
316+ const tools = [
317+ {
318+ type: "function" as const,
319+ function: {
320+ name: "test_function",
321+ description: "Test function",
322+ parameters: { type: "object", properties: {} },
323+ },
324+ },
325+ ];
326+
327+ await runLlmTest({
328+ llm: openai,
329+ methodToTest: "chat",
330+ params: [
331+ [{ role: "user", content: "hello" }],
332+ new AbortController().signal,
333+ { tools },
334+ ],
335+ expectedRequest: {
336+ url: "https://api.openai.com/v1/chat/completions",
337+ method: "POST",
338+ headers: {
339+ "Content-Type": "application/json",
340+ Authorization: "Bearer test-api-key",
341+ "api-key": "test-api-key",
342+ },
343+ body: {
344+ model: "gpt-4",
345+ messages: [{ role: "user", content: "hello" }],
346+ stream: true,
347+ max_tokens: 2048,
348+ tools: [
349+ {
350+ type: "function",
351+ function: {
352+ name: "test_function",
353+ description: "Test function",
354+ parameters: { type: "object", properties: {} },
355+ },
356+ },
357+ ],
358+ },
359+ },
360+ mockStream: [{ choices: [{ delta: { content: "I'll help you" } }] }],
361+ });
362+ });
363+
364+ test("should handle custom max tokens", async () => {
365+ const openai = new OpenAI({
366+ apiKey: "test-api-key",
367+ model: "gpt-4",
368+ apiBase: "https://api.openai.com/v1/",
369+ });
370+
371+ await runLlmTest({
372+ llm: openai,
373+ methodToTest: "chat",
374+ params: [
375+ [{ role: "user", content: "hello" }],
376+ new AbortController().signal,
377+ { maxTokens: 500 },
378+ ],
379+ expectedRequest: {
380+ url: "https://api.openai.com/v1/chat/completions",
381+ method: "POST",
382+ headers: {
383+ "Content-Type": "application/json",
384+ Authorization: "Bearer test-api-key",
385+ "api-key": "test-api-key",
386+ },
387+ body: {
388+ model: "gpt-4",
389+ messages: [{ role: "user", content: "hello" }],
390+ stream: true,
391+ max_tokens: 500,
392+ },
393+ },
394+ mockStream: [{ choices: [{ delta: { content: "Hello" } }] }],
395+ });
396+ });
397+
398+ test("should handle embeddings", async () => {
399+ const openai = new OpenAI({
400+ apiKey: "test-api-key",
401+ model: "text-embedding-ada-002",
402+ apiBase: "https://api.openai.com/v1/",
403+ });
404+
405+ await runLlmTest({
406+ llm: openai,
407+ methodToTest: "embed",
408+ params: [["Hello", "World"]],
409+ expectedRequest: {
410+ url: "https://api.openai.com/v1/embeddings",
411+ method: "POST",
412+ headers: {
413+ Authorization: "Bearer test-api-key",
414+ "Content-Type": "application/json",
415+ "api-key": "test-api-key",
416+ },
417+ body: {
418+ input: ["Hello", "World"],
419+ model: "text-embedding-ada-002",
420+ },
421+ },
422+ mockResponse: {
423+ data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
424+ },
425+ });
426+ });
427+});
modified core/llm/llms/Venice.ts +1 −1
@@ -6,7 +6,7 @@
66 class Venice extends OpenAI {
77 static providerName = "venice";
88 static defaultOptions: Partial<LLMOptions> = {
9- apiBase: "https://api.venice.ai/api/v1",
9+ apiBase: "https://api.venice.ai/api/v1/",
1010 };
1111
1212 protected _convertArgs(
added core/llm/llms/llmTestHarness.ts +93 −0
@@ -0,0 +1,93 @@
1+import { expect, jest } from "@jest/globals";
2+import { ILLM } from "../../index.js";
3+
4+export interface LlmTestCase {
5+ llm: ILLM;
6+ methodToTest: keyof ILLM;
7+ params: any[];
8+ expectedRequest: {
9+ url: string;
10+ method: string;
11+ headers?: Record<string, string>;
12+ body?: Record<string, any>;
13+ };
14+ mockResponse?: any;
15+ mockStream?: string[]; // array of string chunks for SSE
16+}
17+
18+export async function runLlmTest(testCase: LlmTestCase) {
19+ const {
20+ llm,
21+ methodToTest,
22+ params,
23+ expectedRequest,
24+ mockResponse,
25+ mockStream,
26+ } = testCase;
27+
28+ const mockFetch = jest.fn<any>();
29+
30+ if (mockStream) {
31+ const encoder = new TextEncoder();
32+ let streamIndex = 0;
33+ mockFetch.mockResolvedValue(
34+ new Response(
35+ new ReadableStream({
36+ start(controller) {
37+ mockStream.forEach((chunk) => {
38+ controller.enqueue(new TextEncoder().encode(chunk));
39+ });
40+ controller.close();
41+ },
42+ }),
43+ {
44+ headers: {
45+ "Content-Type": "text/event-stream",
46+ },
47+ },
48+ ),
49+ );
50+ } else {
51+ mockFetch.mockResolvedValue(
52+ new Response(JSON.stringify(mockResponse), {
53+ headers: {
54+ "Content-Type": "application/json",
55+ },
56+ }),
57+ );
58+ }
59+
60+ // @ts-ignore
61+ llm.fetch = mockFetch;
62+
63+ // @ts-ignore
64+ if (typeof llm[methodToTest] !== "function") {
65+ throw new Error(
66+ `Method ${String(methodToTest)} does not exist on the LLM instance.`,
67+ );
68+ }
69+
70+ // @ts-ignore
71+ const result = await llm[methodToTest](...params);
72+
73+ if (mockStream) {
74+ // Consume the stream to ensure it's processed correctly
75+ for await (const _ of result) {
76+ }
77+ }
78+
79+ expect(mockFetch).toHaveBeenCalledTimes(1);
80+ const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit];
81+
82+ expect(url.toString()).toBe(expectedRequest.url);
83+ expect(options.method).toBe(expectedRequest.method);
84+
85+ if (expectedRequest.headers) {
86+ expect(options.headers).toEqual(expectedRequest.headers);
87+ }
88+
89+ if (expectedRequest.body) {
90+ const actualBody = JSON.parse(options.body as string);
91+ expect(actualBody).toEqual(expectedRequest.body);
92+ }
93+}
modified core/llm/llms/stubs/ContinueProxy.ts +3 −0
@@ -11,6 +11,7 @@
1111
1212 import type { Chunk, LLMOptions } from "../../../index.js";
1313 import { LLMConfigurationStatuses } from "../../constants.js";
14+import { LlmApiRequestType } from "../../openaiTypeConverters.js";
1415
1516 class ContinueProxy extends OpenAI {
1617 set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
@@ -23,6 +24,8 @@
2324 }
2425 }
2526
27+ protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
28+
2629 // The apiKey and apiBase are set to the values for the proxy,
2730 // but we need to keep track of the actual values that the proxy will use
2831 // to call whatever LLM API is chosen
added core/llm/llms/stubs/ContinueProxy.vitest.ts +758 −0
@@ -0,0 +1,758 @@
1+import { afterEach, describe, expect, test, vi } from "vitest";
2+import { ILLM } from "../../../index.js";
3+import ContinueProxy from "./ContinueProxy.js";
4+
5+vi.mock("@continuedev/config-yaml", async (importOriginal) => {
6+ const mod = (await importOriginal()) as any;
7+ return {
8+ ...mod,
9+ parseProxyModelName: vi.fn(() => ({
10+ provider: "test-provider",
11+ model: "test-model",
12+ ownerSlug: "test-owner",
13+ packageSlug: "test-package",
14+ })),
15+ };
16+});
17+
18+interface LlmTestCase {
19+ llm: ILLM;
20+ methodToTest: keyof ILLM;
21+ params: any[];
22+ expectedRequest: {
23+ url: string;
24+ method: string;
25+ headers?: Record<string, string>;
26+ body?: Record<string, any>;
27+ };
28+ mockResponse?: any;
29+ mockStream?: any[];
30+}
31+
32+function createMockStream(mockStream: any[]) {
33+ const encoder = new TextEncoder();
34+ return new ReadableStream({
35+ start(controller) {
36+ for (const chunk of mockStream) {
37+ controller.enqueue(
38+ encoder.encode(
39+ `data: ${
40+ typeof chunk === "string" ? chunk : JSON.stringify(chunk)
41+ }\n\n`,
42+ ),
43+ );
44+ }
45+ controller.close();
46+ },
47+ });
48+}
49+
50+function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
51+ const mockFetch = vi.fn();
52+
53+ if (mockStream) {
54+ const stream = createMockStream(mockStream);
55+ mockFetch.mockResolvedValue(
56+ new Response(stream, {
57+ headers: {
58+ "Content-Type": "text/event-stream",
59+ },
60+ }),
61+ );
62+ } else {
63+ mockFetch.mockResolvedValue(
64+ new Response(JSON.stringify(mockResponse), {
65+ headers: { "Content-Type": "application/json" },
66+ }),
67+ );
68+ }
69+
70+ return mockFetch;
71+}
72+
73+function setupReadableStreamPolyfill() {
74+ // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
75+ // @ts-ignore
76+ const originalFrom = ReadableStream.from;
77+ // @ts-ignore
78+ ReadableStream.from = (body) => {
79+ if (body?.source) {
80+ return body;
81+ }
82+ return originalFrom(body);
83+ };
84+}
85+
86+async function executeLlmMethod(
87+ llm: ILLM,
88+ methodToTest: keyof ILLM,
89+ params: any[],
90+) {
91+ if (typeof (llm as any)[methodToTest] !== "function") {
92+ throw new Error(
93+ `Method ${String(methodToTest)} does not exist on the LLM instance.`,
94+ );
95+ }
96+
97+ const result = await (llm as any)[methodToTest](...params);
98+ if (result?.next) {
99+ for await (const _ of result) {
100+ }
101+ }
102+}
103+
104+function assertFetchCall(mockFetch: any, expectedRequest: any) {
105+ expect(mockFetch).toHaveBeenCalledTimes(1);
106+ const [url, options] = mockFetch.mock.calls[0];
107+
108+ expect(url.toString()).toBe(expectedRequest.url);
109+ expect(options.method).toBe(expectedRequest.method);
110+
111+ if (expectedRequest.headers) {
112+ expect(options.headers).toEqual(
113+ expect.objectContaining(expectedRequest.headers),
114+ );
115+ }
116+
117+ if (expectedRequest.body) {
118+ const actualBody = JSON.parse(options.body as string);
119+ expect(actualBody).toEqual(expectedRequest.body);
120+ }
121+}
122+
123+async function runLlmTest(testCase: LlmTestCase) {
124+ const {
125+ llm,
126+ methodToTest,
127+ params,
128+ expectedRequest,
129+ mockResponse,
130+ mockStream,
131+ } = testCase;
132+
133+ const mockFetch = setupMockFetch(mockResponse, mockStream);
134+ setupReadableStreamPolyfill();
135+
136+ (llm as any).fetch = mockFetch;
137+
138+ await executeLlmMethod(llm, methodToTest, params);
139+ assertFetchCall(mockFetch, expectedRequest);
140+}
141+
142+describe("ContinueProxy", () => {
143+ afterEach(() => {
144+ vi.clearAllMocks();
145+ });
146+
147+ test("rerank should send a valid request", async () => {
148+ const proxy = new ContinueProxy({
149+ apiKey: "test-api-key",
150+ model: "test-model",
151+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
152+ });
153+
154+ await runLlmTest({
155+ llm: proxy,
156+ methodToTest: "rerank",
157+ params: [
158+ "test query",
159+ [{ content: "document1" }, { content: "document2" }],
160+ ],
161+ expectedRequest: {
162+ url: "https://proxy.continue.dev/model-proxy/v1/rerank",
163+ method: "POST",
164+ headers: {
165+ "Content-Type": "application/json",
166+ Authorization: "Bearer test-api-key",
167+ },
168+ body: {
169+ query: "test query",
170+ documents: ["document1", "document2"],
171+ model: "test-model",
172+ continueProperties: {
173+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
174+ orgScopeId: null,
175+ },
176+ },
177+ },
178+ mockResponse: {
179+ data: [
180+ { index: 0, relevance_score: 0.9 },
181+ { index: 1, relevance_score: 0.1 },
182+ ],
183+ },
184+ });
185+ });
186+
187+ test("streamChat should send a valid request", async () => {
188+ const proxy = new ContinueProxy({
189+ apiKey: "test-api-key",
190+ model: "test-model",
191+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
192+ });
193+
194+ await runLlmTest({
195+ llm: proxy,
196+ methodToTest: "streamChat",
197+ params: [[{ role: "user", content: "hello" }]],
198+ expectedRequest: {
199+ url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
200+ method: "POST",
201+ headers: {
202+ "Content-Type": "application/json",
203+ Authorization: "Bearer test-api-key",
204+ "api-key": "test-api-key",
205+ "x-continue-unique-id": "NOT_UNIQUE",
206+ },
207+ body: {
208+ model: "test-model",
209+ messages: [{ role: "user", content: "hello" }],
210+ max_tokens: 4096,
211+ stream: true,
212+ continueProperties: {
213+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
214+ orgScopeId: null,
215+ },
216+ },
217+ },
218+ mockStream: [
219+ '{"choices": [{"delta": {"content": "response"}}]}',
220+ "[DONE]",
221+ ],
222+ });
223+ });
224+
225+ test("chat should send a valid request", async () => {
226+ const proxy = new ContinueProxy({
227+ apiKey: "test-api-key",
228+ model: "test-model",
229+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
230+ });
231+
232+ await runLlmTest({
233+ llm: proxy,
234+ methodToTest: "chat",
235+ params: [[{ role: "user", content: "hello" }]],
236+ expectedRequest: {
237+ url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
238+ method: "POST",
239+ headers: {
240+ "Content-Type": "application/json",
241+ Authorization: "Bearer test-api-key",
242+ "api-key": "test-api-key",
243+ "x-continue-unique-id": "NOT_UNIQUE",
244+ },
245+ body: {
246+ model: "test-model",
247+ messages: [{ role: "user", content: "hello" }],
248+ max_tokens: 4096,
249+ stream: true,
250+ continueProperties: {
251+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
252+ orgScopeId: null,
253+ },
254+ },
255+ },
256+ mockStream: [
257+ '{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}',
258+ "[DONE]",
259+ ],
260+ });
261+ });
262+
263+ test("streamComplete should send a valid request", async () => {
264+ const proxy = new ContinueProxy({
265+ apiKey: "test-api-key",
266+ model: "test-model",
267+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
268+ });
269+
270+ await runLlmTest({
271+ llm: proxy,
272+ methodToTest: "streamComplete",
273+ params: ["Complete this: Hello"],
274+ expectedRequest: {
275+ url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
276+ method: "POST",
277+ headers: {
278+ "Content-Type": "application/json",
279+ Authorization: "Bearer test-api-key",
280+ "api-key": "test-api-key",
281+ "x-continue-unique-id": "NOT_UNIQUE",
282+ },
283+ body: {
284+ model: "test-model",
285+ messages: [{ role: "user", content: "Complete this: Hello" }],
286+ max_tokens: 4096,
287+ stream: true,
288+ continueProperties: {
289+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
290+ orgScopeId: null,
291+ },
292+ },
293+ },
294+ mockStream: [
295+ '{"choices": [{"delta": {"content": " world!"}}]}',
296+ "[DONE]",
297+ ],
298+ });
299+ });
300+
301+ test("complete should send a valid request", async () => {
302+ const proxy = new ContinueProxy({
303+ apiKey: "test-api-key",
304+ model: "test-model",
305+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
306+ });
307+
308+ await runLlmTest({
309+ llm: proxy,
310+ methodToTest: "complete",
311+ params: ["Complete this: Hello"],
312+ expectedRequest: {
313+ url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
314+ method: "POST",
315+ headers: {
316+ "Content-Type": "application/json",
317+ Authorization: "Bearer test-api-key",
318+ "api-key": "test-api-key",
319+ "x-continue-unique-id": "NOT_UNIQUE",
320+ },
321+ body: {
322+ model: "test-model",
323+ messages: [{ role: "user", content: "Complete this: Hello" }],
324+ max_tokens: 4096,
325+ stream: true,
326+ continueProperties: {
327+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
328+ orgScopeId: null,
329+ },
330+ },
331+ },
332+ mockStream: [
333+ '{"choices": [{"delta": {"content": " world!"}}]}',
334+ "[DONE]",
335+ ],
336+ });
337+ });
338+
339+ test("streamFim should send a valid request", async () => {
340+ const proxy = new ContinueProxy({
341+ apiKey: "test-api-key",
342+ model: "test-model",
343+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
344+ });
345+
346+ await runLlmTest({
347+ llm: proxy,
348+ methodToTest: "streamFim",
349+ params: ["function test() {\n ", "\n}"],
350+ expectedRequest: {
351+ url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
352+ method: "POST",
353+ headers: {
354+ "Content-Type": "application/json",
355+ Accept: "application/json",
356+ "x-api-key": "test-api-key",
357+ Authorization: "Bearer test-api-key",
358+ },
359+ body: {
360+ model: "test-model",
361+ prompt: "function test() {\n ",
362+ suffix: "\n}",
363+ max_tokens: 4096,
364+ stream: true,
365+ continueProperties: {
366+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
367+ orgScopeId: null,
368+ },
369+ },
370+ },
371+ mockStream: [
372+ '{"choices": [{"delta": {"content": "console.log("Hello");"}}]}',
373+ "[DONE]",
374+ ],
375+ });
376+ });
377+
378+ test("embed should send a valid request", async () => {
379+ const proxy = new ContinueProxy({
380+ apiKey: "test-api-key",
381+ model: "test-model",
382+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
383+ });
384+
385+ await runLlmTest({
386+ llm: proxy,
387+ methodToTest: "embed",
388+ params: [["text to embed", "another text"]],
389+ expectedRequest: {
390+ url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
391+ method: "POST",
392+ headers: {
393+ "Content-Type": "application/json",
394+ Authorization: "Bearer test-api-key",
395+ "api-key": "test-api-key",
396+ },
397+ body: {
398+ input: ["text to embed", "another text"],
399+ model: "test-model",
400+ continueProperties: {
401+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
402+ orgScopeId: null,
403+ },
404+ },
405+ },
406+ mockResponse: {
407+ data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
408+ },
409+ });
410+ });
411+
412+ test("listModels should send a valid request", async () => {
413+ const proxy = new ContinueProxy({
414+ apiKey: "test-api-key",
415+ model: "test-model",
416+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
417+ });
418+
419+ await runLlmTest({
420+ llm: proxy,
421+ methodToTest: "listModels",
422+ params: [],
423+ expectedRequest: {
424+ url: "https://proxy.continue.dev/model-proxy/v1/models",
425+ method: "GET",
426+ headers: {
427+ "Content-Type": "application/json",
428+ Authorization: "Bearer test-api-key",
429+ "api-key": "test-api-key",
430+ },
431+ },
432+ mockResponse: {
433+ data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],
434+ },
435+ });
436+ });
437+
438+ describe("Different provider configurations", () => {
439+ test("should handle on-prem proxy URL", async () => {
440+ const proxy = new ContinueProxy({
441+ apiKey: "test-api-key",
442+ model: "test-model",
443+ onPremProxyUrl: "https://my-proxy.company.com/",
444+ });
445+
446+ await runLlmTest({
447+ llm: proxy,
448+ methodToTest: "rerank",
449+ params: [
450+ "test query",
451+ [{ content: "document1" }, { content: "document2" }],
452+ ],
453+ expectedRequest: {
454+ url: "https://my-proxy.company.com/model-proxy/v1/rerank",
455+ method: "POST",
456+ headers: {
457+ "Content-Type": "application/json",
458+ Authorization: "Bearer test-api-key",
459+ },
460+ body: {
461+ query: "test query",
462+ documents: ["document1", "document2"],
463+ model: "test-model",
464+ continueProperties: {
465+ apiBase: undefined,
466+ apiKeyLocation: undefined,
467+ env: undefined,
468+ envSecretLocations: undefined,
469+ orgScopeId: null,
470+ },
471+ },
472+ },
473+ mockResponse: {
474+ data: [
475+ { index: 0, relevance_score: 0.9 },
476+ { index: 1, relevance_score: 0.1 },
477+ ],
478+ },
479+ });
480+ });
481+
482+ test("should handle environment variables", async () => {
483+ const proxy = new ContinueProxy({
484+ apiKey: "test-api-key",
485+ model: "test-model",
486+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
487+ env: {
488+ CUSTOM_VAR: "custom-value",
489+ ANOTHER_VAR: "another-value",
490+ },
491+ });
492+
493+ await runLlmTest({
494+ llm: proxy,
495+ methodToTest: "streamChat",
496+ params: [[{ role: "user", content: "hello" }]],
497+ expectedRequest: {
498+ url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
499+ method: "POST",
500+ headers: {
501+ "Content-Type": "application/json",
502+ Authorization: "Bearer test-api-key",
503+ "api-key": "test-api-key",
504+ "x-continue-unique-id": "NOT_UNIQUE",
505+ },
506+ body: {
507+ model: "test-model",
508+ messages: [{ role: "user", content: "hello" }],
509+ max_tokens: 4096,
510+ stream: true,
511+ continueProperties: {
512+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
513+ env: {
514+ CUSTOM_VAR: "custom-value",
515+ ANOTHER_VAR: "another-value",
516+ },
517+ orgScopeId: null,
518+ },
519+ },
520+ },
521+ mockStream: [
522+ '{"choices": [{"delta": {"content": "response"}}]}',
523+ "[DONE]",
524+ ],
525+ });
526+ });
527+
528+ test("should handle API key location", async () => {
529+ const proxy = new ContinueProxy({
530+ apiKey: "test-api-key",
531+ model: "test-model",
532+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
533+ apiKeyLocation: "env:OPENAI_API_KEY",
534+ });
535+
536+ await runLlmTest({
537+ llm: proxy,
538+ methodToTest: "embed",
539+ params: [["test text"]],
540+ expectedRequest: {
541+ url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
542+ method: "POST",
543+ headers: {
544+ "Content-Type": "application/json",
545+ Authorization: "Bearer test-api-key",
546+ "api-key": "test-api-key",
547+ },
548+ body: {
549+ input: ["test text"],
550+ model: "test-model",
551+ continueProperties: {
552+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
553+ apiKeyLocation: "env:OPENAI_API_KEY",
554+ env: undefined,
555+ envSecretLocations: undefined,
556+ orgScopeId: null,
557+ },
558+ },
559+ },
560+ mockResponse: {
561+ data: [{ embedding: [0.1, 0.2, 0.3] }],
562+ },
563+ });
564+ });
565+
566+ test("should handle env secret locations", async () => {
567+ const proxy = new ContinueProxy({
568+ apiKey: "test-api-key",
569+ model: "test-model",
570+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
571+ envSecretLocations: {
572+ AZURE_API_KEY: "env:AZURE_API_KEY",
573+ AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
574+ },
575+ });
576+
577+ await runLlmTest({
578+ llm: proxy,
579+ methodToTest: "streamFim",
580+ params: ["const x = ", ";"],
581+ expectedRequest: {
582+ url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
583+ method: "POST",
584+ headers: {
585+ "Content-Type": "application/json",
586+ Accept: "application/json",
587+ "x-api-key": "test-api-key",
588+ Authorization: "Bearer test-api-key",
589+ },
590+ body: {
591+ model: "test-model",
592+ prompt: "const x = ",
593+ suffix: ";",
594+ max_tokens: 4096,
595+ stream: true,
596+ continueProperties: {
597+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
598+ envSecretLocations: {
599+ AZURE_API_KEY: "env:AZURE_API_KEY",
600+ AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
601+ },
602+ orgScopeId: null,
603+ },
604+ },
605+ },
606+ mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"],
607+ });
608+ });
609+
610+ test("should handle organization scope ID", async () => {
611+ const proxy = new ContinueProxy({
612+ apiKey: "test-api-key",
613+ model: "test-model",
614+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
615+ orgScopeId: "org_12345",
616+ });
617+
618+ await runLlmTest({
619+ llm: proxy,
620+ methodToTest: "listModels",
621+ params: [],
622+ expectedRequest: {
623+ url: "https://proxy.continue.dev/model-proxy/v1/models",
624+ method: "GET",
625+ headers: {
626+ "Content-Type": "application/json",
627+ Authorization: "Bearer test-api-key",
628+ "api-key": "test-api-key",
629+ },
630+ },
631+ mockResponse: {
632+ data: [{ id: "gpt-4" }],
633+ },
634+ });
635+ });
636+ });
637+
638+ describe("Edge cases", () => {
639+ test("should handle empty chunks array for rerank", async () => {
640+ const proxy = new ContinueProxy({
641+ apiKey: "test-api-key",
642+ model: "test-model",
643+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
644+ });
645+
646+ await runLlmTest({
647+ llm: proxy,
648+ methodToTest: "rerank",
649+ params: ["test query", []],
650+ expectedRequest: {
651+ url: "https://proxy.continue.dev/model-proxy/v1/rerank",
652+ method: "POST",
653+ headers: {
654+ "Content-Type": "application/json",
655+ Authorization: "Bearer test-api-key",
656+ },
657+ body: {
658+ query: "test query",
659+ documents: [],
660+ model: "test-model",
661+ continueProperties: {
662+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
663+ apiKeyLocation: undefined,
664+ env: undefined,
665+ envSecretLocations: undefined,
666+ orgScopeId: null,
667+ },
668+ },
669+ },
670+ mockResponse: {
671+ data: [],
672+ },
673+ });
674+ });
675+
676+ test("should handle complex chat messages", async () => {
677+ const proxy = new ContinueProxy({
678+ apiKey: "test-api-key",
679+ model: "test-model",
680+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
681+ });
682+
683+ const complexMessages = [
684+ { role: "system", content: "You are a helpful assistant." },
685+ { role: "user", content: "Hello!" },
686+ { role: "assistant", content: "Hi there! How can I help you today?" },
687+ { role: "user", content: "What's the weather like?" },
688+ ];
689+
690+ await runLlmTest({
691+ llm: proxy,
692+ methodToTest: "streamChat",
693+ params: [complexMessages],
694+ expectedRequest: {
695+ url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
696+ method: "POST",
697+ headers: {
698+ "Content-Type": "application/json",
699+ Authorization: "Bearer test-api-key",
700+ "api-key": "test-api-key",
701+ "x-continue-unique-id": "NOT_UNIQUE",
702+ },
703+ body: {
704+ model: "test-model",
705+ messages: complexMessages,
706+ max_tokens: 4096,
707+ stream: true,
708+ continueProperties: {
709+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
710+ orgScopeId: null,
711+ },
712+ },
713+ },
714+ mockStream: [
715+ '{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}',
716+ "[DONE]",
717+ ],
718+ });
719+ });
720+
721+ test("should handle single embedding chunk", async () => {
722+ const proxy = new ContinueProxy({
723+ apiKey: "test-api-key",
724+ model: "test-model",
725+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
726+ });
727+
728+ await runLlmTest({
729+ llm: proxy,
730+ methodToTest: "embed",
731+ params: [["single text"]],
732+ expectedRequest: {
733+ url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
734+ method: "POST",
735+ headers: {
736+ "Content-Type": "application/json",
737+ Authorization: "Bearer test-api-key",
738+ "api-key": "test-api-key",
739+ },
740+ body: {
741+ input: ["single text"],
742+ model: "test-model",
743+ continueProperties: {
744+ apiBase: "https://proxy.continue.dev/model-proxy/v1/",
745+ apiKeyLocation: undefined,
746+ env: undefined,
747+ envSecretLocations: undefined,
748+ orgScopeId: null,
749+ },
750+ },
751+ },
752+ mockResponse: {
753+ data: [{ embedding: [0.1, 0.2, 0.3] }],
754+ },
755+ });
756+ });
757+ });
758+});
added core/llm/llms/test-utils/openai-test-utils.ts +375 −0
@@ -0,0 +1,375 @@
1+import { afterEach, describe, expect, test, vi } from "vitest";
2+import { ILLM } from "../../../index.js";
3+import OpenAI from "../OpenAI.js";
4+
5+interface LlmTestCase {
6+ llm: ILLM;
7+ methodToTest: keyof ILLM;
8+ params: any[];
9+ expectedRequest: {
10+ url: string;
11+ method: string;
12+ headers?: Record<string, string>;
13+ body?: Record<string, any>;
14+ };
15+ mockResponse?: any;
16+ mockStream?: any[];
17+}
18+
19+function createMockStream(mockStream: any[]) {
20+ const encoder = new TextEncoder();
21+ return new ReadableStream({
22+ start(controller) {
23+ for (const chunk of mockStream) {
24+ controller.enqueue(
25+ encoder.encode(
26+ `data: ${
27+ typeof chunk === "string" ? chunk : JSON.stringify(chunk)
28+ }\n\n`,
29+ ),
30+ );
31+ }
32+ controller.close();
33+ },
34+ });
35+}
36+
37+function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
38+ const mockFetch = vi.fn();
39+
40+ if (mockStream) {
41+ const stream = createMockStream(mockStream);
42+ mockFetch.mockResolvedValue(
43+ new Response(stream, {
44+ headers: {
45+ "Content-Type": "text/event-stream",
46+ },
47+ }),
48+ );
49+ } else {
50+ mockFetch.mockResolvedValue(
51+ new Response(JSON.stringify(mockResponse), {
52+ headers: { "Content-Type": "application/json" },
53+ }),
54+ );
55+ }
56+
57+ return mockFetch;
58+}
59+
60+function setupReadableStreamPolyfill() {
61+ // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
62+ // @ts-ignore
63+ const originalFrom = ReadableStream.from;
64+ // @ts-ignore
65+ ReadableStream.from = (body) => {
66+ if (body?.source) {
67+ return body;
68+ }
69+ return originalFrom(body);
70+ };
71+}
72+
73+async function executeLlmMethod(
74+ llm: ILLM,
75+ methodToTest: keyof ILLM,
76+ params: any[],
77+) {
78+ if (typeof (llm as any)[methodToTest] !== "function") {
79+ throw new Error(
80+ `Method ${String(methodToTest)} does not exist on the LLM instance.`,
81+ );
82+ }
83+
84+ const result = await (llm as any)[methodToTest](...params);
85+ if (result?.next) {
86+ for await (const _ of result) {
87+ }
88+ }
89+}
90+
91+function assertFetchCall(mockFetch: any, expectedRequest: any) {
92+ expect(mockFetch).toHaveBeenCalledTimes(1);
93+ const [url, options] = mockFetch.mock.calls[0];
94+
95+ expect(url.toString()).toBe(expectedRequest.url);
96+ expect(options.method).toBe(expectedRequest.method);
97+
98+ if (expectedRequest.headers) {
99+ expect(options.headers).toEqual(
100+ expect.objectContaining(expectedRequest.headers),
101+ );
102+ }
103+
104+ if (expectedRequest.body) {
105+ const actualBody = JSON.parse(options.body as string);
106+ expect(actualBody).toEqual(expectedRequest.body);
107+ }
108+}
109+
110+async function runLlmTest(testCase: LlmTestCase) {
111+ const {
112+ llm,
113+ methodToTest,
114+ params,
115+ expectedRequest,
116+ mockResponse,
117+ mockStream,
118+ } = testCase;
119+
120+ const mockFetch = setupMockFetch(mockResponse, mockStream);
121+ setupReadableStreamPolyfill();
122+
123+ (llm as any).fetch = mockFetch;
124+
125+ // Disable OpenAI adapter to use our custom fetch mock
126+ (llm as any).useOpenAIAdapterFor = [];
127+
128+ await executeLlmMethod(llm, methodToTest, params);
129+ assertFetchCall(mockFetch, expectedRequest);
130+}
131+
132+export interface OpenAISubclassConfig {
133+ providerName: string;
134+ defaultApiBase?: string;
135+ modelConversions?: { [key: string]: string };
136+ customOptions?: any;
137+ modelConversionContent?: string;
138+ modelConversionMaxTokens?: number;
139+ customStreamCompleteEndpoint?: string;
140+ customEmbeddingsUrl?: string;
141+ customEmbeddingsHeaders?: { [key: string]: string };
142+ customEmbeddingsBody?: any;
143+ customBodyOptions?: any;
144+}
145+
146+function getExpectedUrl(
147+ config: OpenAISubclassConfig,
148+ endpoint: string,
149+ model: string = "gpt-4",
150+) {
151+ let baseUrl = config.defaultApiBase || "https://api.openai.com/v1/";
152+ if (config.providerName === "azure") {
153+ return `${baseUrl}openai/deployments/${model}/${endpoint}?api-version=2023-07-01-preview`;
154+ } else if (config.providerName === "ncompass") {
155+ return `${baseUrl}${endpoint}`;
156+ }
157+ return `${baseUrl}${endpoint}`;
158+}
159+
160+export const createOpenAISubclassTests = (
161+ ProviderClass: typeof OpenAI,
162+ config: OpenAISubclassConfig,
163+) => {
164+ describe(config.providerName, () => {
165+ afterEach(() => {
166+ vi.clearAllMocks();
167+ });
168+
169+ test("should have correct provider name", () => {
170+ expect(ProviderClass.providerName).toBe(config.providerName);
171+ });
172+
173+ if (config.defaultApiBase) {
174+ test("should have correct default API base", () => {
175+ expect(ProviderClass.defaultOptions?.apiBase).toBe(
176+ config.defaultApiBase,
177+ );
178+ });
179+ }
180+
181+ test("streamChat should send a valid request", async () => {
182+ const provider = new ProviderClass({
183+ apiKey: "test-api-key",
184+ model: "gpt-4",
185+ apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
186+ });
187+
188+ await runLlmTest({
189+ llm: provider,
190+ methodToTest: "streamChat",
191+ params: [
192+ [{ role: "user", content: "hello" }],
193+ new AbortController().signal,
194+ ],
195+ expectedRequest: {
196+ url: getExpectedUrl(config, "chat/completions"),
197+ method: "POST",
198+ headers: {
199+ "Content-Type": "application/json",
200+ Authorization: "Bearer test-api-key",
201+ "api-key": "test-api-key",
202+ },
203+ body: {
204+ model: "gpt-4",
205+ messages: [{ role: "user", content: "hello" }],
206+ stream: true,
207+ max_tokens: 2048,
208+ ...config.customBodyOptions,
209+ },
210+ },
211+ mockStream: [
212+ { choices: [{ delta: { content: "Hello" } }] },
213+ { choices: [{ delta: { content: " world" } }] },
214+ ],
215+ });
216+ });
217+
218+ test("chat should send a valid request", async () => {
219+ const provider = new ProviderClass({
220+ apiKey: "test-api-key",
221+ model: "gpt-4",
222+ apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
223+ });
224+
225+ await runLlmTest({
226+ llm: provider,
227+ methodToTest: "chat",
228+ params: [
229+ [{ role: "user", content: "hello" }],
230+ new AbortController().signal,
231+ ],
232+ expectedRequest: {
233+ url: getExpectedUrl(config, "chat/completions"),
234+ method: "POST",
235+ headers: {
236+ "Content-Type": "application/json",
237+ Authorization: "Bearer test-api-key",
238+ "api-key": "test-api-key",
239+ },
240+ body: {
241+ model: "gpt-4",
242+ messages: [{ role: "user", content: "hello" }],
243+ stream: true,
244+ max_tokens: 2048,
245+ ...config.customBodyOptions,
246+ },
247+ },
248+ mockStream: [
249+ { choices: [{ delta: { content: "Hello" } }] },
250+ { choices: [{ delta: { content: " world" } }] },
251+ ],
252+ });
253+ });
254+
255+ test("streamComplete should send a valid request", async () => {
256+ const provider = new ProviderClass({
257+ apiKey: "test-api-key",
258+ model: "gpt-4",
259+ apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
260+ });
261+
262+ await runLlmTest({
263+ llm: provider,
264+ methodToTest: "streamComplete",
265+ params: ["Hello", new AbortController().signal],
266+ expectedRequest: {
267+ url: getExpectedUrl(
268+ config,
269+ config.customStreamCompleteEndpoint || "chat/completions",
270+ ),
271+ method: "POST",
272+ headers: {
273+ "Content-Type": "application/json",
274+ Authorization: "Bearer test-api-key",
275+ "api-key": "test-api-key",
276+ },
277+ body:
278+ config.customStreamCompleteEndpoint === "completions"
279+ ? {
280+ model: "gpt-4",
281+ prompt: "Hello",
282+ stream: true,
283+ max_tokens: 2048,
284+ ...config.customBodyOptions,
285+ }
286+ : {
287+ model: "gpt-4",
288+ messages: [{ role: "user", content: "Hello" }],
289+ stream: true,
290+ max_tokens: 2048,
291+ ...config.customBodyOptions,
292+ },
293+ },
294+ mockStream: [
295+ { choices: [{ delta: { content: "Hello" } }] },
296+ { choices: [{ delta: { content: " world" } }] },
297+ ],
298+ });
299+ });
300+
301+ test("complete should send a valid request", async () => {
302+ const provider = new ProviderClass({
303+ apiKey: "test-api-key",
304+ model: "gpt-4",
305+ apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
306+ });
307+
308+ await runLlmTest({
309+ llm: provider,
310+ methodToTest: "complete",
311+ params: ["Hello", new AbortController().signal],
312+ expectedRequest: {
313+ url: getExpectedUrl(config, "chat/completions"),
314+ method: "POST",
315+ headers: {
316+ "Content-Type": "application/json",
317+ Authorization: "Bearer test-api-key",
318+ "api-key": "test-api-key",
319+ },
320+ body: {
321+ model: "gpt-4",
322+ messages: [{ role: "user", content: "Hello" }],
323+ stream: true,
324+ max_tokens: 2048,
325+ ...config.customBodyOptions,
326+ },
327+ },
328+ mockStream: [
329+ { choices: [{ delta: { content: "Hello" } }] },
330+ { choices: [{ delta: { content: " world" } }] },
331+ ],
332+ });
333+ });
334+
335+ test("should handle embeddings", async () => {
336+ const provider = new ProviderClass({
337+ apiKey: "test-api-key",
338+ model: "text-embedding-ada-002",
339+ apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
340+ });
341+
342+ // Skip test if provider doesn't support embeddings (e.g., ncompass with undefined endpoint)
343+ if (config.providerName === "ncompass" && !config.customEmbeddingsUrl) {
344+ return;
345+ }
346+
347+ await runLlmTest({
348+ llm: provider,
349+ methodToTest: "embed",
350+ params: [["Hello", "World"]],
351+ expectedRequest: {
352+ url:
353+ config.customEmbeddingsUrl ||
354+ `${config.defaultApiBase || "https://api.openai.com/v1/"}embeddings`,
355+ method: "POST",
356+ headers: config.customEmbeddingsHeaders || {
357+ Authorization: "Bearer test-api-key",
358+ "Content-Type": "application/json",
359+ "api-key": "test-api-key",
360+ },
361+ body: config.customEmbeddingsBody || {
362+ input: ["Hello", "World"],
363+ model: "text-embedding-ada-002",
364+ },
365+ },
366+ mockResponse: {
367+ data: [
368+ { embedding: [0.1, 0.2, 0.3] },
369+ { embedding: [0.4, 0.5, 0.6] },
370+ ],
371+ },
372+ });
373+ });
374+ });
375+};
modified core/llm/logFormatter.test.ts +5 −0
@@ -44,6 +44,7 @@
4444 content: "You are a helpful assistant",
4545 },
4646 ],
47+ provider: "watsonx",
4748 });
4849 logger._logItem({
4950 interactionId: "1",
@@ -79,6 +80,7 @@
7980 promptTokens: 10,
8081 generatedTokens: 20,
8182 thinkingTokens: 0,
83+ usage: undefined,
8284 });
8385
8486 expect(output.getText()).toBe(
@@ -113,6 +115,7 @@
113115 model: "granite3.2-dense:8b",
114116 },
115117 prompt: "A horse is a horse",
118+ provider: "watsonx",
116119 });
117120 logger._logItem({
118121 interactionId: "1",
@@ -149,6 +152,7 @@
149152 },
150153 prefix: "A\nB",
151154 suffix: "D\nE",
155+ provider: "watsonx",
152156 });
153157 logger._logItem({
154158 interactionId: "1",
@@ -225,6 +229,7 @@
225229 promptTokens: 10,
226230 generatedTokens: 20,
227231 thinkingTokens: 0,
232+ usage: undefined,
228233 });
229234 logger._logItem({
230235 interactionId: "3",
modified core/llm/rules/ruleColocation.vitest.ts +9 −9
@@ -9,7 +9,7 @@
99 generalRule: {
1010 name: "General Rule",
1111 rule: "Follow coding standards",
12- source: "rules-block",
12+ source: "colocated-markdown",
1313 ruleFile: "src/rules.md",
1414 },
1515
@@ -18,7 +18,7 @@
1818 name: "Redux Rule",
1919 rule: "Use Redux Toolkit",
2020 globs: "src/redux/**/*.{ts,tsx}",
21- source: "rules-block",
21+ source: "colocated-markdown",
2222 ruleFile: "src/redux/rules.md",
2323 },
2424
@@ -27,7 +27,7 @@
2727 name: "Component Rule",
2828 rule: "Use functional components",
2929 globs: ["src/components/**/*.tsx", "src/components/**/*.jsx"],
30- source: "rules-block",
30+ source: "colocated-markdown",
3131 ruleFile: "src/components/rules.md",
3232 },
3333
@@ -37,7 +37,7 @@
3737 rule: "Follow these guidelines always",
3838 alwaysApply: true,
3939 globs: "src/specific/**/*.ts", // Should be ignored since alwaysApply is true
40- source: "rules-block",
40+ source: "colocated-markdown",
4141 ruleFile: ".continue/rules.md",
4242 },
4343
@@ -47,7 +47,7 @@
4747 rule: "This rule should only apply to matching files",
4848 alwaysApply: false,
4949 // No globs, so should never apply
50- source: "rules-block",
50+ source: "colocated-markdown",
5151 ruleFile: ".continue/rules.md",
5252 },
5353
@@ -57,7 +57,7 @@
5757 rule: "Apply only to matching files",
5858 alwaysApply: false,
5959 globs: "src/utils/**/*.ts",
60- source: "rules-block",
60+ source: "colocated-markdown",
6161 ruleFile: "src/utils/rules.md",
6262 },
6363 };
@@ -127,7 +127,7 @@
127127 rule: "Follow nested module standards",
128128 // Fix: Specify the exact path prefix to restrict to this directory structure
129129 globs: "src/features/auth/utils/**/*.ts",
130- source: "rules-block",
130+ source: "colocated-markdown",
131131 ruleFile: "src/features/auth/utils/rules.md",
132132 };
133133
@@ -157,7 +157,7 @@
157157 // Note: Negative globs may not be supported by the current implementation
158158 // Testing with standard pattern instead
159159 globs: "src/**/[!.]*.ts",
160- source: "rules-block",
160+ source: "colocated-markdown",
161161 ruleFile: "src/rules.md",
162162 };
163163
@@ -174,7 +174,7 @@
174174 // Use a pattern that doesn't match test files
175175 globs: ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
176176 alwaysApply: false,
177- source: "rules-block",
177+ source: "colocated-markdown",
178178 ruleFile: "src/rules.md",
179179 };
180180
deleted core/llm/utils/__tests__/getSecureID.test.ts +0 −49
@@ -1,49 +0,0 @@
1-import { getSecureID } from "../getSecureID";
2-
3-// Mock the crypto.randomUUID function
4-const mockRandomUUID = jest.fn();
5-global.crypto = {
6- ...global.crypto,
7- randomUUID: mockRandomUUID,
8-};
9-
10-describe("getSecureID", () => {
11- beforeEach(() => {
12- // Reset the static property before each test
13- (getSecureID as any).uuid = undefined;
14-
15- // Reset the mock implementation
16- mockRandomUUID.mockReset();
17- // Setup a mock implementation that returns a fixed value for testing
18- mockRandomUUID.mockReturnValue("test-uuid-1234");
19- });
20-
21- test("should generate a UUID on first call", () => {
22- const result = getSecureID();
23- expect(mockRandomUUID).toHaveBeenCalledTimes(1);
24- expect(result).toBe("<!-- SID: test-uuid-1234 -->");
25- });
26-
27- test("should reuse the same UUID on subsequent calls", () => {
28- const firstResult = getSecureID();
29- const secondResult = getSecureID();
30-
31- // The UUID generation should only happen once
32- expect(mockRandomUUID).toHaveBeenCalledTimes(1);
33-
34- // Both results should be identical
35- expect(firstResult).toBe(secondResult);
36- expect(firstResult).toBe("<!-- SID: test-uuid-1234 -->");
37- });
38-
39- test("should maintain the same UUID across different test cases if not reset", () => {
40- // Don't reset the UUID here to test persistence
41- (getSecureID as any).uuid = "persistent-uuid";
42-
43- const result = getSecureID();
44-
45- // No new UUID should be generated
46- expect(mockRandomUUID).not.toHaveBeenCalled();
47- expect(result).toBe("<!-- SID: persistent-uuid -->");
48- });
49-});
added core/llm/utils/calculateRequestCost.ts +181 −0
@@ -0,0 +1,181 @@
1+import { Usage } from "../..";
2+
3+export interface CostBreakdown {
4+ cost: number;
5+ breakdown: string;
6+}
7+
8+function calculateAnthropicCost(
9+ model: string,
10+ usage: Usage,
11+): CostBreakdown | null {
12+ // Normalize model name to handle various formats
13+ const normalizedModel = model.toLowerCase();
14+
15+ // Define pricing per million tokens (MTok)
16+ const pricing: Record<
17+ string,
18+ { input: number; output: number; cacheWrite: number; cacheRead: number }
19+ > = {
20+ // Claude Opus 4 (most intelligent model)
21+ "claude-3-opus": {
22+ input: 15,
23+ output: 75,
24+ cacheWrite: 18.75,
25+ cacheRead: 1.5,
26+ },
27+ "claude-3-opus-20240229": {
28+ input: 15,
29+ output: 75,
30+ cacheWrite: 18.75,
31+ cacheRead: 1.5,
32+ },
33+
34+ // Claude Sonnet 4 (optimal balance)
35+ "claude-3-5-sonnet": {
36+ input: 3,
37+ output: 15,
38+ cacheWrite: 3.75,
39+ cacheRead: 0.3,
40+ },
41+ "claude-3-5-sonnet-20241022": {
42+ input: 3,
43+ output: 15,
44+ cacheWrite: 3.75,
45+ cacheRead: 0.3,
46+ },
47+ "claude-3-5-sonnet-20240620": {
48+ input: 3,
49+ output: 15,
50+ cacheWrite: 3.75,
51+ cacheRead: 0.3,
52+ },
53+
54+ // Claude Haiku 3.5 (fastest, most cost-effective)
55+ "claude-3-5-haiku": {
56+ input: 0.8,
57+ output: 4,
58+ cacheWrite: 1,
59+ cacheRead: 0.08,
60+ },
61+ "claude-3-5-haiku-20241022": {
62+ input: 0.8,
63+ output: 4,
64+ cacheWrite: 1,
65+ cacheRead: 0.08,
66+ },
67+
68+ // Legacy Claude 3 Haiku
69+ "claude-3-haiku": {
70+ input: 0.25,
71+ output: 1.25,
72+ cacheWrite: 0.3,
73+ cacheRead: 0.03,
74+ },
75+ "claude-3-haiku-20240307": {
76+ input: 0.25,
77+ output: 1.25,
78+ cacheWrite: 0.3,
79+ cacheRead: 0.03,
80+ },
81+ };
82+
83+ // Find matching pricing model
84+ let modelPricing = pricing[normalizedModel];
85+
86+ // If exact match not found, try to find by partial match
87+ if (!modelPricing) {
88+ for (const [key, value] of Object.entries(pricing)) {
89+ if (normalizedModel.includes(key) || key.includes(normalizedModel)) {
90+ modelPricing = value;
91+ break;
92+ }
93+ }
94+ }
95+
96+ // If still no match, try common patterns
97+ if (!modelPricing) {
98+ if (normalizedModel.includes("opus")) {
99+ modelPricing = pricing["claude-3-opus"];
100+ } else if (normalizedModel.includes("sonnet")) {
101+ modelPricing = pricing["claude-3-5-sonnet"];
102+ } else if (normalizedModel.includes("haiku")) {
103+ modelPricing = pricing["claude-3-5-haiku"];
104+ }
105+ }
106+
107+ if (!modelPricing) {
108+ return null; // Unknown model
109+ }
110+
111+ // Calculate costs
112+ const inputCost = (usage.promptTokens / 1_000_000) * modelPricing.input;
113+ const outputCost = (usage.completionTokens / 1_000_000) * modelPricing.output;
114+
115+ // Build breakdown components
116+ const breakdownParts: string[] = [];
117+
118+ // Input tokens breakdown
119+ if (usage.promptTokens > 0) {
120+ breakdownParts.push(
121+ `Input: ${usage.promptTokens.toLocaleString()} tokens × $${modelPricing.input}/MTok = $${inputCost.toFixed(6)}`,
122+ );
123+ }
124+
125+ // Output tokens breakdown
126+ if (usage.completionTokens > 0) {
127+ breakdownParts.push(
128+ `Output: ${usage.completionTokens.toLocaleString()} tokens × $${modelPricing.output}/MTok = $${outputCost.toFixed(6)}`,
129+ );
130+ }
131+
132+ // Handle prompt caching costs if available
133+ let cacheCost = 0;
134+ if (usage.promptTokensDetails) {
135+ const { cachedTokens, cacheWriteTokens } = usage.promptTokensDetails;
136+
137+ if (cacheWriteTokens && cacheWriteTokens > 0) {
138+ const cacheWriteCost =
139+ (cacheWriteTokens / 1_000_000) * modelPricing.cacheWrite;
140+ cacheCost += cacheWriteCost;
141+ breakdownParts.push(
142+ `Cache Write: ${cacheWriteTokens.toLocaleString()} tokens × $${modelPricing.cacheWrite}/MTok = $${cacheWriteCost.toFixed(6)}`,
143+ );
144+ }
145+
146+ if (cachedTokens && cachedTokens > 0) {
147+ const cacheReadCost = (cachedTokens / 1_000_000) * modelPricing.cacheRead;
148+ cacheCost += cacheReadCost;
149+ breakdownParts.push(
150+ `Cache Read: ${cachedTokens.toLocaleString()} tokens × $${modelPricing.cacheRead}/MTok = $${cacheReadCost.toFixed(6)}`,
151+ );
152+ }
153+ }
154+
155+ const totalCost = inputCost + outputCost + cacheCost;
156+
157+ // Build final breakdown string
158+ let breakdown = `Model: ${model}\n`;
159+ breakdown += breakdownParts.join("\n");
160+ if (breakdownParts.length > 1) {
161+ breakdown += `\nTotal: $${totalCost.toFixed(6)}`;
162+ }
163+
164+ return {
165+ cost: totalCost,
166+ breakdown,
167+ };
168+}
169+
170+export function calculateRequestCost(
171+ provider: string,
172+ model: string,
173+ usage: Usage,
174+): CostBreakdown | null {
175+ switch (provider) {
176+ case "anthropic":
177+ return calculateAnthropicCost(model, usage);
178+ default:
179+ return null;
180+ }
181+}
added core/llm/utils/getSecureID.test.ts +49 −0
@@ -0,0 +1,49 @@
1+import { getSecureID } from "./getSecureID";
2+
3+// Mock the crypto.randomUUID function
4+const mockRandomUUID = jest.fn();
5+global.crypto = {
6+ ...global.crypto,
7+ randomUUID: mockRandomUUID,
8+};
9+
10+describe("getSecureID", () => {
11+ beforeEach(() => {
12+ // Reset the static property before each test
13+ (getSecureID as any).uuid = undefined;
14+
15+ // Reset the mock implementation
16+ mockRandomUUID.mockReset();
17+ // Setup a mock implementation that returns a fixed value for testing
18+ mockRandomUUID.mockReturnValue("test-uuid-1234");
19+ });
20+
21+ test("should generate a UUID on first call", () => {
22+ const result = getSecureID();
23+ expect(mockRandomUUID).toHaveBeenCalledTimes(1);
24+ expect(result).toBe("<!-- SID: test-uuid-1234 -->");
25+ });
26+
27+ test("should reuse the same UUID on subsequent calls", () => {
28+ const firstResult = getSecureID();
29+ const secondResult = getSecureID();
30+
31+ // The UUID generation should only happen once
32+ expect(mockRandomUUID).toHaveBeenCalledTimes(1);
33+
34+ // Both results should be identical
35+ expect(firstResult).toBe(secondResult);
36+ expect(firstResult).toBe("<!-- SID: test-uuid-1234 -->");
37+ });
38+
39+ test("should maintain the same UUID across different test cases if not reset", () => {
40+ // Don't reset the UUID here to test persistence
41+ (getSecureID as any).uuid = "persistent-uuid";
42+
43+ const result = getSecureID();
44+
45+ // No new UUID should be generated
46+ expect(mockRandomUUID).not.toHaveBeenCalled();
47+ expect(result).toBe("<!-- SID: persistent-uuid -->");
48+ });
49+});
added core/llm/utils/retry.test.ts +481 −0
@@ -0,0 +1,481 @@
1+import { retryAsync, withLLMRetry, withRetry } from "./retry";
2+
3+// Mock console.warn to avoid noise in tests
4+const consoleSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
5+
6+describe("Retry Functionality", () => {
7+ beforeEach(() => {
8+ jest.clearAllMocks();
9+ });
10+
11+ describe("retryAsync", () => {
12+ it("should succeed on first attempt", async () => {
13+ const mockFn = jest.fn().mockResolvedValue("success");
14+
15+ const result = await retryAsync(mockFn);
16+
17+ expect(result).toBe("success");
18+ expect(mockFn).toHaveBeenCalledTimes(1);
19+ });
20+
21+ it("should retry on retryable errors", async () => {
22+ const error = new Error("ECONNRESET");
23+ (error as any).code = "ECONNRESET";
24+ const mockFn = jest
25+ .fn()
26+ .mockRejectedValueOnce(error)
27+ .mockResolvedValue("success");
28+
29+ const result = await retryAsync(mockFn, {
30+ maxAttempts: 2,
31+ baseDelay: 10, // Very short delay for testing
32+ });
33+
34+ expect(result).toBe("success");
35+ expect(mockFn).toHaveBeenCalledTimes(2);
36+ });
37+
38+ it("should not retry on non-retryable errors", async () => {
39+ const error = new Error("Bad Request");
40+ (error as any).status = 400;
41+ const mockFn = jest.fn().mockRejectedValue(error);
42+
43+ await expect(retryAsync(mockFn)).rejects.toThrow("Bad Request");
44+ expect(mockFn).toHaveBeenCalledTimes(1);
45+ });
46+
47+ it("should respect max attempts", async () => {
48+ const error = new Error("ECONNRESET");
49+ (error as any).code = "ECONNRESET";
50+ const mockFn = jest.fn().mockRejectedValue(error);
51+
52+ await expect(
53+ retryAsync(mockFn, {
54+ maxAttempts: 3,
55+ baseDelay: 10,
56+ }),
57+ ).rejects.toThrow("ECONNRESET");
58+ expect(mockFn).toHaveBeenCalledTimes(3);
59+ });
60+
61+ it("should throw the last error when all retries are exhausted", async () => {
62+ const firstError = new Error("First error");
63+ (firstError as any).code = "ECONNRESET";
64+ const secondError = new Error("Second error");
65+ (secondError as any).code = "ECONNRESET";
66+ const lastError = new Error("Last error");
67+ (lastError as any).code = "ECONNRESET";
68+
69+ const mockFn = jest
70+ .fn()
71+ .mockRejectedValueOnce(firstError)
72+ .mockRejectedValueOnce(secondError)
73+ .mockRejectedValueOnce(lastError);
74+
75+ await expect(
76+ retryAsync(mockFn, {
77+ maxAttempts: 3,
78+ baseDelay: 10,
79+ }),
80+ ).rejects.toThrow("Last error");
81+ expect(mockFn).toHaveBeenCalledTimes(3);
82+ });
83+
84+ it("should handle HTTP 429 errors", async () => {
85+ const error = new Error("Too Many Requests");
86+ (error as any).status = 429;
87+ const mockFn = jest
88+ .fn()
89+ .mockRejectedValueOnce(error)
90+ .mockResolvedValue("success");
91+
92+ const result = await retryAsync(mockFn, {
93+ maxAttempts: 2,
94+ baseDelay: 10,
95+ });
96+
97+ expect(result).toBe("success");
98+ expect(mockFn).toHaveBeenCalledTimes(2);
99+ });
100+
101+ it("should handle HTTP 5xx errors", async () => {
102+ const error = new Error("Internal Server Error");
103+ (error as any).status = 500;
104+ const mockFn = jest
105+ .fn()
106+ .mockRejectedValueOnce(error)
107+ .mockResolvedValue("success");
108+
109+ const result = await retryAsync(mockFn, {
110+ maxAttempts: 2,
111+ baseDelay: 10,
112+ });
113+
114+ expect(result).toBe("success");
115+ expect(mockFn).toHaveBeenCalledTimes(2);
116+ });
117+
118+ it("should handle AWS SDK errors", async () => {
119+ const error = new Error("Throttling");
120+ error.name = "ThrottlingException";
121+ (error as any).$fault = "client";
122+ (error as any).$metadata = {
123+ httpStatusCode: 429,
124+ requestId: "test-request-id",
125+ };
126+ const mockFn = jest
127+ .fn()
128+ .mockRejectedValueOnce(error)
129+ .mockResolvedValue("success");
130+
131+ const result = await retryAsync(mockFn, {
132+ maxAttempts: 2,
133+ baseDelay: 10,
134+ });
135+
136+ expect(result).toBe("success");
137+ expect(mockFn).toHaveBeenCalledTimes(2);
138+ });
139+
140+ it("should not retry AbortError", async () => {
141+ const error = new Error("Aborted");
142+ error.name = "AbortError";
143+ const mockFn = jest.fn().mockRejectedValue(error);
144+
145+ await expect(retryAsync(mockFn)).rejects.toThrow("Aborted");
146+ expect(mockFn).toHaveBeenCalledTimes(1);
147+ });
148+
149+ it("should use custom shouldRetry function", async () => {
150+ const mockFn = jest.fn().mockRejectedValue(new Error("Custom Error"));
151+ const customShouldRetry = jest.fn().mockReturnValue(true);
152+
153+ await expect(
154+ retryAsync(mockFn, {
155+ maxAttempts: 2,
156+ shouldRetry: customShouldRetry,
157+ baseDelay: 10,
158+ }),
159+ ).rejects.toThrow("Custom Error");
160+
161+ expect(customShouldRetry).toHaveBeenCalledWith(expect.any(Error), 1);
162+ expect(mockFn).toHaveBeenCalledTimes(2);
163+ });
164+ });
165+
166+ describe("withRetry decorator functional usage", () => {
167+ it("should work when applied manually to methods", async () => {
168+ const testClass = {
169+ attempts: 0,
170+
171+ async testMethod(): Promise<string> {
172+ this.attempts++;
173+ if (this.attempts < 3) {
174+ const error = new Error("ECONNRESET");
175+ (error as any).code = "ECONNRESET";
176+ throw error;
177+ }
178+ return "success";
179+ },
180+ };
181+
182+ // Apply decorator manually
183+ const decorator = withRetry({
184+ maxAttempts: 3,
185+ baseDelay: 10,
186+ });
187+ const descriptor = decorator(testClass, "testMethod", {
188+ value: testClass.testMethod,
189+ writable: true,
190+ enumerable: false,
191+ configurable: true,
192+ });
193+
194+ if (descriptor?.value) {
195+ testClass.testMethod = descriptor.value;
196+ }
197+
198+ const result = await testClass.testMethod();
199+
200+ expect(result).toBe("success");
201+ expect(testClass.attempts).toBe(3);
202+ });
203+
204+ it("should throw the last error when all retries are exhausted", async () => {
205+ const testClass = {
206+ attempts: 0,
207+
208+ async testMethod(): Promise<string> {
209+ this.attempts++;
210+ if (this.attempts === 1) {
211+ const error = new Error("First decorator error");
212+ (error as any).code = "ECONNRESET";
213+ throw error;
214+ } else if (this.attempts === 2) {
215+ const error = new Error("Second decorator error");
216+ (error as any).code = "ECONNRESET";
217+ throw error;
218+ } else {
219+ const error = new Error("Last decorator error");
220+ (error as any).code = "ECONNRESET";
221+ throw error;
222+ }
223+ },
224+ };
225+
226+ // Apply decorator manually
227+ const decorator = withRetry({
228+ maxAttempts: 3,
229+ baseDelay: 10,
230+ });
231+ const descriptor = decorator(testClass, "testMethod", {
232+ value: testClass.testMethod,
233+ writable: true,
234+ enumerable: false,
235+ configurable: true,
236+ });
237+
238+ if (descriptor?.value) {
239+ testClass.testMethod = descriptor.value;
240+ }
241+
242+ await expect(testClass.testMethod()).rejects.toThrow(
243+ "Last decorator error",
244+ );
245+ expect(testClass.attempts).toBe(3);
246+ });
247+ });
248+
249+ describe("withLLMRetry decorator functional usage", () => {
250+ it("should use LLM-specific defaults", async () => {
251+ const testLLM = {
252+ attempts: 0,
253+
254+ async streamChat(): Promise<string> {
255+ this.attempts++;
256+ if (this.attempts < 2) {
257+ const error = new Error("Too Many Requests");
258+ (error as any).status = 429;
259+ throw error;
260+ }
261+ return "success";
262+ },
263+ };
264+
265+ // Apply decorator manually
266+ const decorator = withLLMRetry({ baseDelay: 10 });
267+ const descriptor = decorator(testLLM, "streamChat", {
268+ value: testLLM.streamChat,
269+ writable: true,
270+ enumerable: false,
271+ configurable: true,
272+ });
273+
274+ if (descriptor?.value) {
275+ testLLM.streamChat = descriptor.value;
276+ }
277+
278+ const result = await testLLM.streamChat();
279+
280+ expect(result).toBe("success");
281+ expect(testLLM.attempts).toBe(2);
282+ });
283+ });
284+
285+ describe("exponential backoff with jitter", () => {
286+ it("should increase delay exponentially", async () => {
287+ const delays: number[] = [];
288+ const error = new Error("ECONNRESET");
289+ (error as any).code = "ECONNRESET";
290+ const mockFn = jest.fn().mockRejectedValue(error);
291+
292+ await expect(
293+ retryAsync(mockFn, {
294+ maxAttempts: 3,
295+ baseDelay: 1000,
296+ jitterFactor: 0, // No jitter for predictable testing
297+ onRetry: (error, attempt, delay) => {
298+ delays.push(delay);
299+ },
300+ }),
301+ ).rejects.toThrow();
302+
303+ // First retry should be ~1000ms, second should be ~2000ms
304+ expect(delays).toHaveLength(2);
305+ expect(delays[0]).toBe(1000);
306+ expect(delays[1]).toBe(2000);
307+ });
308+
309+ it("should respect maxDelay", async () => {
310+ const delays: number[] = [];
311+ const error = new Error("ECONNRESET");
312+ (error as any).code = "ECONNRESET";
313+ const mockFn = jest.fn().mockRejectedValue(error);
314+
315+ await expect(
316+ retryAsync(mockFn, {
317+ maxAttempts: 4,
318+ baseDelay: 1000,
319+ maxDelay: 2500,
320+ jitterFactor: 0,
321+ onRetry: (error, attempt, delay) => {
322+ delays.push(delay);
323+ },
324+ }),
325+ ).rejects.toThrow();
326+
327+ // Delays should be: 1000, 2000, 2500 (capped)
328+ expect(delays).toEqual([1000, 2000, 2500]);
329+ });
330+ });
331+
332+ describe("rate limiting headers", () => {
333+ it("should respect retry-after header in seconds", async () => {
334+ const delays: number[] = [];
335+ const error = new Error("Too Many Requests");
336+ (error as any).status = 429;
337+ (error as any).headers = { "retry-after": "1" }; // 1 second for fast testing
338+ const mockFn = jest
339+ .fn()
340+ .mockRejectedValueOnce(error)
341+ .mockResolvedValue("success");
342+
343+ const result = await retryAsync(mockFn, {
344+ maxAttempts: 2,
345+ baseDelay: 100, // 100ms fallback
346+ onRetry: (error, attempt, delay) => {
347+ delays.push(delay);
348+ },
349+ });
350+
351+ expect(result).toBe("success");
352+ expect(mockFn).toHaveBeenCalledTimes(2);
353+ // Should use header value (1000ms) not exponential backoff (100ms)
354+ expect(delays[0]).toBeGreaterThan(940); // 1000ms with wider tolerance for jitter and system performance
355+ expect(delays[0]).toBeLessThan(1080);
356+ });
357+
358+ it("should respect x-ratelimit-reset header", async () => {
359+ const delays: number[] = [];
360+ const error = new Error("Rate limited");
361+ (error as any).status = 429;
362+ (error as any).headers = { "x-ratelimit-reset": "0.5" }; // 500ms for fast testing
363+ const mockFn = jest
364+ .fn()
365+ .mockRejectedValueOnce(error)
366+ .mockResolvedValue("success");
367+
368+ const result = await retryAsync(mockFn, {
369+ maxAttempts: 2,
370+ baseDelay: 100,
371+ onRetry: (error, attempt, delay) => {
372+ delays.push(delay);
373+ },
374+ });
375+
376+ expect(result).toBe("success");
377+ // Should use header value (500ms) not exponential backoff (100ms)
378+ expect(delays[0]).toBeGreaterThan(470); // 500ms with wider tolerance for jitter and system performance
379+ expect(delays[0]).toBeLessThan(540);
380+ });
381+
382+ it("should handle HTTP date format in retry-after header", async () => {
383+ const delays: number[] = [];
384+ const futureDate = new Date(Date.now() + 2000); // 2 seconds from now to avoid timing issues
385+ const error = new Error("Rate limited");
386+ (error as any).status = 429;
387+ (error as any).headers = { "retry-after": futureDate.toUTCString() };
388+ const mockFn = jest
389+ .fn()
390+ .mockRejectedValueOnce(error)
391+ .mockResolvedValue("success");
392+
393+ const result = await retryAsync(mockFn, {
394+ maxAttempts: 2,
395+ baseDelay: 100,
396+ maxDelay: 300, // Cap at 300ms for fast testing
397+ onRetry: (error, attempt, delay) => {
398+ delays.push(delay);
399+ },
400+ });
401+
402+ expect(result).toBe("success");
403+ // Should be capped at maxDelay (300ms) since original would be ~2000ms
404+ expect(delays[0]).toBeGreaterThan(280);
405+ expect(delays[0]).toBeLessThan(320);
406+ });
407+
408+ it("should fallback to exponential backoff when no headers present", async () => {
409+ const delays: number[] = [];
410+ const error = new Error("Server Error");
411+ (error as any).status = 500;
412+ // No headers property
413+ const mockFn = jest
414+ .fn()
415+ .mockRejectedValueOnce(error)
416+ .mockResolvedValue("success");
417+
418+ const result = await retryAsync(mockFn, {
419+ maxAttempts: 2,
420+ baseDelay: 50, // Fast for testing
421+ jitterFactor: 0,
422+ onRetry: (error, attempt, delay) => {
423+ delays.push(delay);
424+ },
425+ });
426+
427+ expect(result).toBe("success");
428+ // Should use exponential backoff (50ms) since no headers
429+ expect(delays[0]).toBe(50);
430+ });
431+
432+ it("should respect maxDelay even with rate limit headers", async () => {
433+ const delays: number[] = [];
434+ const error = new Error("Rate limited");
435+ (error as any).status = 429;
436+ (error as any).headers = { "retry-after": "10" }; // 10 seconds requested
437+ const mockFn = jest
438+ .fn()
439+ .mockRejectedValueOnce(error)
440+ .mockResolvedValue("success");
441+
442+ const result = await retryAsync(mockFn, {
443+ maxAttempts: 2,
444+ baseDelay: 100,
445+ maxDelay: 200, // Cap at 200ms for fast testing
446+ onRetry: (error, attempt, delay) => {
447+ delays.push(delay);
448+ },
449+ });
450+
451+ expect(result).toBe("success");
452+ // Should be capped at maxDelay (200ms) not header value (10000ms)
453+ expect(delays[0]).toBeGreaterThan(190);
454+ expect(delays[0]).toBeLessThan(210);
455+ });
456+
457+ it("should handle case-insensitive header names", async () => {
458+ const delays: number[] = [];
459+ const error = new Error("Rate limited");
460+ (error as any).status = 429;
461+ (error as any).headers = { "Retry-After": "0.3" }; // 300ms for fast testing
462+ const mockFn = jest
463+ .fn()
464+ .mockRejectedValueOnce(error)
465+ .mockResolvedValue("success");
466+
467+ const result = await retryAsync(mockFn, {
468+ maxAttempts: 2,
469+ baseDelay: 100,
470+ onRetry: (error, attempt, delay) => {
471+ delays.push(delay);
472+ },
473+ });
474+
475+ expect(result).toBe("success");
476+ // Should use header value (300ms)
477+ expect(delays[0]).toBeGreaterThan(284);
478+ expect(delays[0]).toBeLessThan(316);
479+ });
480+ });
481+});
added core/llm/utils/retry.ts +459 −0
@@ -0,0 +1,459 @@
1+/**
2+ * Configuration options for the retry decorator
3+ */
4+export interface RetryOptions {
5+ /** Maximum number of retry attempts (default: 3) */
6+ maxAttempts?: number;
7+ /** Base delay in milliseconds (default: 1000) */
8+ baseDelay?: number;
9+ /** Maximum delay in milliseconds (default: 30000) */
10+ maxDelay?: number;
11+ /** Jitter factor between 0 and 1 (default: 0.3) */
12+ jitterFactor?: number;
13+ /** Custom function to determine if an error should be retried */
14+ shouldRetry?: (error: any, attempt: number) => boolean;
15+ /** Custom function called on each retry attempt */
16+ onRetry?: (error: any, attempt: number, delay: number) => void;
17+}
18+
19+/**
20+ * Default configuration for retry behavior
21+ */
22+const DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {
23+ maxAttempts: 3,
24+ baseDelay: 1000,
25+ maxDelay: 30000,
26+ jitterFactor: 0.3,
27+ shouldRetry: defaultShouldRetry,
28+ onRetry: defaultOnRetry,
29+};
30+
31+/**
32+ * Default function to determine if an error should be retried
33+ * Retries on:
34+ * - Network errors
35+ * - HTTP 429 (Too Many Requests)
36+ * - HTTP 5xx (Server errors)
37+ * - Specific AWS errors
38+ * - Timeout errors
39+ */
40+function defaultShouldRetry(error: any, attempt: number): boolean {
41+ // Note: maxAttempts check is handled by the retry logic itself
42+ // This function only determines if the error type is retryable
43+
44+ // Network/connection errors
45+ if (
46+ error.code === "ENOTFOUND" ||
47+ error.code === "ECONNRESET" ||
48+ error.code === "ECONNREFUSED" ||
49+ error.code === "ETIMEDOUT"
50+ ) {
51+ return true;
52+ }
53+
54+ // AWS SDK specific errors (v3 - check for AWS error structure and retryable types)
55+ const isAwsError =
56+ error.$fault || error.$metadata || (error.name && error.__type);
57+ const awsRetryableErrors = [
58+ "ThrottlingException",
59+ "ServiceUnavailableException",
60+ "InternalServerError",
61+ "RequestTimeout",
62+ "ModelNotReadyException",
63+ "ModelTimeoutException",
64+ "ResourceNotFoundException",
65+ ];
66+
67+ if (isAwsError && error.name && awsRetryableErrors.includes(error.name)) {
68+ return true;
69+ }
70+
71+ // HTTP status codes
72+ if (error.status || error.statusCode) {
73+ const status = error.status || error.statusCode;
74+
75+ // Rate limiting
76+ if (status === 429) {
77+ return true;
78+ }
79+
80+ // Server errors (5xx)
81+ if (status >= 500 && status < 600) {
82+ return true;
83+ }
84+
85+ // Don't retry client errors (4xx except 429)
86+ if (status >= 400 && status < 500) {
87+ return false;
88+ }
89+ }
90+
91+ // Timeout errors
92+ if (
93+ error.name === "TimeoutError" ||
94+ error.message?.includes("timeout") ||
95+ error.message?.includes("TIMEOUT")
96+ ) {
97+ return true;
98+ }
99+
100+ // Abort signal errors should not be retried
101+ if (error.name === "AbortError" || error.code === "ABORT_ERR") {
102+ return false;
103+ }
104+
105+ // Default to not retrying unknown errors
106+ return false;
107+}
108+
109+/**
110+ * Default function called on each retry attempt
111+ */
112+function defaultOnRetry(error: any, attempt: number, delay: number): void {
113+ console.warn(
114+ `Retry attempt ${attempt} after ${delay}ms delay. Error: ${error.message || error}`,
115+ );
116+}
117+
118+/**
119+ * Calculate delay with rate limit header awareness and exponential backoff fallback
120+ */
121+function calculateDelay(
122+ attempt: number,
123+ baseDelay: number,
124+ maxDelay: number,
125+ jitterFactor: number,
126+ error?: any,
127+): number {
128+ // Check for rate limiting headers first (more accurate than exponential backoff)
129+ if (error?.headers) {
130+ const retryAfter =
131+ error.headers["retry-after"] ||
132+ error.headers["x-ratelimit-reset"] ||
133+ error.headers["ratelimit-reset"] ||
134+ error.headers["Retry-After"] ||
135+ error.headers["X-RateLimit-Reset"] ||
136+ error.headers["RateLimit-Reset"];
137+
138+ if (retryAfter) {
139+ let delayMs: number;
140+
141+ // Parse retry-after header (can be seconds or HTTP date)
142+ if (typeof retryAfter === "string" && isNaN(Number(retryAfter))) {
143+ // HTTP date format
144+ const resetTime = new Date(retryAfter).getTime();
145+ const now = Date.now();
146+ delayMs = Math.max(0, resetTime - now);
147+ } else {
148+ // Seconds format
149+ delayMs = Number(retryAfter) * 1000;
150+ }
151+
152+ // Respect maxDelay and add small jitter to spread requests
153+ const cappedDelay = Math.min(delayMs, maxDelay);
154+ const jitterMultiplier = 1 + (Math.random() * 0.1 - 0.05); // Small jitter ±5%
155+ return Math.max(0, Math.floor(cappedDelay * jitterMultiplier));
156+ }
157+ }
158+
159+ // Fallback to exponential backoff if no rate limit headers
160+ const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
161+ const cappedDelay = Math.min(exponentialDelay, maxDelay);
162+
163+ // Add jitter: random value between (1 - jitterFactor) and (1 + jitterFactor)
164+ const jitterMultiplier = 1 + (Math.random() * 2 - 1) * jitterFactor;
165+ const jitteredDelay = cappedDelay * jitterMultiplier;
166+
167+ return Math.max(0, Math.floor(jitteredDelay));
168+}
169+
170+/**
171+ * Sleep for the specified number of milliseconds
172+ */
173+function sleep(ms: number): Promise<void> {
174+ return new Promise((resolve) => setTimeout(resolve, ms));
175+}
176+
177+/**
178+ * Retry decorator for async functions with exponential backoff and jitter
179+ *
180+ * @param options Retry configuration options
181+ * @returns Decorator function
182+ *
183+ * @example
184+ * ```typescript
185+ * class MyLLM {
186+ * @withRetry({ maxAttempts: 5, baseDelay: 2000 })
187+ * async streamChat(messages: ChatMessage[]): Promise<AsyncGenerator<ChatMessage>> {
188+ * // Implementation that might fail
189+ * }
190+ * }
191+ * ```
192+ */
193+export function withRetry(options: RetryOptions = {}) {
194+ const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
195+
196+ return function (...args: any[]): any {
197+ // Handle different decorator calling patterns
198+ const [target, propertyName, descriptor] = args;
199+
200+ // Get the original method
201+ let originalMethod: Function;
202+ if (descriptor && descriptor.value) {
203+ originalMethod = descriptor.value;
204+ } else {
205+ // Get method from prototype
206+ originalMethod = target[propertyName];
207+ }
208+
209+ if (!originalMethod || typeof originalMethod !== "function") {
210+ throw new Error(`@withRetry can only be applied to methods`);
211+ }
212+
213+ // Check if the original method is an async generator function
214+ const isAsyncGenerator =
215+ originalMethod.constructor.name === "AsyncGeneratorFunction";
216+
217+ const wrappedMethod = isAsyncGenerator
218+ ? async function* (this: any, ...methodArgs: any[]) {
219+ let lastError: any;
220+
221+ for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
222+ try {
223+ const generator = originalMethod.apply(this, methodArgs);
224+ yield* createRetryableAsyncGenerator(
225+ generator,
226+ config,
227+ originalMethod,
228+ this,
229+ methodArgs,
230+ attempt,
231+ );
232+ return; // Successfully completed
233+ } catch (error) {
234+ lastError = error;
235+
236+ // Check if we should retry this error
237+ if (!config.shouldRetry(error, attempt)) {
238+ throw error;
239+ }
240+
241+ // Don't delay on the last attempt
242+ if (attempt === config.maxAttempts) {
243+ break;
244+ }
245+
246+ // Calculate delay and wait
247+ const delay = calculateDelay(
248+ attempt,
249+ config.baseDelay,
250+ config.maxDelay,
251+ config.jitterFactor,
252+ error,
253+ );
254+
255+ config.onRetry(error, attempt, delay);
256+ await sleep(delay);
257+ }
258+ }
259+
260+ // If we get here, all attempts failed
261+ throw lastError;
262+ }
263+ : async function (this: any, ...methodArgs: any[]) {
264+ let lastError: any;
265+
266+ for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
267+ try {
268+ const result = originalMethod.apply(this, methodArgs);
269+ return await result;
270+ } catch (error) {
271+ lastError = error;
272+
273+ // Check if we should retry this error
274+ if (!config.shouldRetry(error, attempt)) {
275+ throw error;
276+ }
277+
278+ // Don't delay on the last attempt
279+ if (attempt === config.maxAttempts) {
280+ break;
281+ }
282+
283+ // Calculate delay and wait
284+ const delay = calculateDelay(
285+ attempt,
286+ config.baseDelay,
287+ config.maxDelay,
288+ config.jitterFactor,
289+ error,
290+ );
291+
292+ config.onRetry(error, attempt, delay);
293+
294+ await sleep(delay);
295+ }
296+ }
297+
298+ // If we get here, all attempts failed
299+ throw lastError;
300+ };
301+
302+ // Apply the wrapped method based on how the decorator was called
303+ if (descriptor) {
304+ descriptor.value = wrappedMethod;
305+ return descriptor;
306+ } else {
307+ // Handle case where descriptor is not provided
308+ target[propertyName] = wrappedMethod;
309+ return wrappedMethod;
310+ }
311+ };
312+}
313+
314+/**
315+ * Creates a retryable async generator that handles errors during iteration
316+ */
317+async function* createRetryableAsyncGenerator<T>(
318+ generator: AsyncGenerator<T>,
319+ config: Required<RetryOptions>,
320+ originalMethod: Function,
321+ context: any,
322+ args: any[],
323+ initialAttempt: number,
324+): AsyncGenerator<T> {
325+ let currentGenerator = generator;
326+ let attempt = initialAttempt;
327+
328+ try {
329+ for await (const value of currentGenerator) {
330+ yield value;
331+ }
332+ } catch (error) {
333+ // If we encounter an error during iteration, we can retry by creating a new generator
334+ let lastError = error;
335+
336+ for (
337+ let retryAttempt = attempt + 1;
338+ retryAttempt <= config.maxAttempts;
339+ retryAttempt++
340+ ) {
341+ // Check if we should retry this error
342+ if (!config.shouldRetry(error, retryAttempt)) {
343+ throw error;
344+ }
345+
346+ // Don't delay on the last attempt
347+ if (retryAttempt === config.maxAttempts) {
348+ break;
349+ }
350+
351+ // Calculate delay and wait
352+ const delay = calculateDelay(
353+ retryAttempt,
354+ config.baseDelay,
355+ config.maxDelay,
356+ config.jitterFactor,
357+ error,
358+ );
359+
360+ config.onRetry(error, retryAttempt, delay);
361+ await sleep(delay);
362+
363+ try {
364+ // Create a new generator and continue iteration
365+ const newGenerator = await originalMethod.apply(context, args);
366+
367+ if (
368+ newGenerator &&
369+ typeof newGenerator[Symbol.asyncIterator] === "function"
370+ ) {
371+ for await (const value of newGenerator) {
372+ yield value;
373+ }
374+ return; // Successfully completed
375+ } else {
376+ throw new Error("Method did not return an async generator on retry");
377+ }
378+ } catch (retryError) {
379+ lastError = retryError;
380+ error = retryError;
381+ }
382+ }
383+
384+ // If we get here, all retry attempts failed
385+ throw lastError;
386+ }
387+}
388+
389+/**
390+ * Functional version of retry for use without decorators
391+ *
392+ * @param fn Function to retry
393+ * @param options Retry configuration options
394+ * @returns Promise that resolves with the function result or rejects with the last error
395+ *
396+ * @example
397+ * ```typescript
398+ * const result = await retryAsync(
399+ * () => someApiCall(),
400+ * { maxAttempts: 3, baseDelay: 1000 }
401+ * );
402+ * ```
403+ */
404+export async function retryAsync<T>(
405+ fn: () => Promise<T>,
406+ options: RetryOptions = {},
407+): Promise<T> {
408+ const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
409+ let lastError: any;
410+
411+ for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
412+ try {
413+ return await fn();
414+ } catch (error) {
415+ lastError = error;
416+
417+ // Check if we should retry this error
418+ if (!config.shouldRetry(error, attempt)) {
419+ throw error;
420+ }
421+
422+ // Don't delay on the last attempt
423+ if (attempt === config.maxAttempts) {
424+ break;
425+ }
426+
427+ // Calculate delay and wait
428+ const delay = calculateDelay(
429+ attempt,
430+ config.baseDelay,
431+ config.maxDelay,
432+ config.jitterFactor,
433+ error,
434+ );
435+
436+ config.onRetry(error, attempt, delay);
437+
438+ await sleep(delay);
439+ }
440+ }
441+
442+ // If we get here, all attempts failed
443+ throw lastError;
444+}
445+
446+/**
447+ * Retry decorator specifically configured for LLM providers
448+ * Uses sensible defaults for LLM API calls, including longer delays
449+ * for capacity provisioning (e.g., AWS Bedrock can require up to 59+ seconds)
450+ */
451+export function withLLMRetry(options: Partial<RetryOptions> = {}) {
452+ return withRetry({
453+ maxAttempts: 5, // More attempts for capacity issues
454+ baseDelay: 2000, // Start with 2 seconds
455+ maxDelay: 90000, // Allow up to 90 seconds for capacity provisioning
456+ jitterFactor: 0.4, // Slightly more jitter to spread load
457+ ...options,
458+ });
459+}
modified core/nextEdit/NextEditProvider.ts +38 −18
@@ -158,19 +158,19 @@
158158 this.loggingService.cancel();
159159 }
160160
161- // public accept(completionId: string) {
162- // const outcome = this.loggingService.accept(completionId);
163- // if (!outcome) {
164- // return;
165- // }
166- // }
167-
168- // public reject(completionId: string) {
169- // const outcome = this.loggingService.reject(completionId);
170- // if (!outcome) {
171- // return;
172- // }
173- // }
161+ public accept(completionId: string) {
162+ const outcome = this.loggingService.accept(completionId);
163+ if (!outcome) {
164+ return;
165+ }
166+ }
167+
168+ public reject(completionId: string) {
169+ const outcome = this.loggingService.reject(completionId);
170+ if (!outcome) {
171+ return;
172+ }
173+ }
174174
175175 public markDisplayed(completionId: string, outcome: NextEditOutcome) {
176176 this.loggingService.markDisplayed(completionId, outcome);
@@ -237,7 +237,6 @@
237237
238238 // TODO: Toggle between the default endpoint and the finetuned endpoint.
239239 const prompts: Prompt[] = [];
240-
241240 if (this.endpointType === "default") {
242241 prompts.push(renderDefaultSystemPrompt());
243242 prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
@@ -272,17 +271,30 @@
272271 cursorPosition: helper.pos,
273272 ...helper.options,
274273 };
274+
275+ // When using the JetBrains extension, mark as displayed.
276+ // This helps us not need to make additional network calls just to mark as displayed.
277+ const ideType = (await this.ide.getIdeInfo()).ideType;
278+ if (ideType === "jetbrains") {
279+ this.markDisplayed(input.completionId, outcomeNext);
280+ }
281+
275282 return outcomeNext;
276283 } else {
277284 return undefined;
278285 }
279286 } else {
280287 const msg: ChatMessage = await llm.chat(prompts, token);
288+
281289 if (typeof msg.content === "string") {
282- // TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
283- const nextCompletion = replaceEscapedCharacters(
284- msg.content.split("<|editable_region_start|>\n")[1],
285- ).replace(/\n$/, "");
290+ // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
291+ const nextCompletion = msg.content.split(
292+ "<|editable_region_start|>\n",
293+ )[1]
294+ ? replaceEscapedCharacters(
295+ msg.content.split("<|editable_region_start|>\n")[1],
296+ ).replace(/\n$/, "")
297+ : "";
286298
287299 const currCursorPos = helper.pos;
288300 const editableRegionStartLine = Math.max(
@@ -319,6 +331,14 @@
319331 cursorPosition: helper.pos,
320332 ...helper.options,
321333 };
334+
335+ // When using the JetBrains extension, mark as displayed.
336+ // This helps us not need to make additional network calls just to mark as displayed.
337+ const ideType = (await this.ide.getIdeInfo()).ideType;
338+ if (ideType === "jetbrains") {
339+ this.markDisplayed(input.completionId, outcomeNext);
340+ }
341+
322342 return outcomeNext;
323343 } else {
324344 return undefined;
modified core/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified core/package.json +2 −1
@@ -78,6 +78,7 @@
7878 "handlebars": "^4.7.8",
7979 "http-proxy-agent": "^7.0.1",
8080 "https-proxy-agent": "^7.0.3",
81+ "iconv-lite": "^0.6.3",
8182 "ignore": "^5.3.1",
8283 "is-localhost-ip": "^2.0.0",
8384 "jinja-js": "0.1.8",
@@ -91,7 +92,7 @@
9192 "node-html-markdown": "^1.3.0",
9293 "ollama": "^0.4.6",
9394 "onnxruntime-node": "1.14.0",
94- "openai": "^4.76.0",
95+ "openai": "^4.104.0",
9596 "p-limit": "^6.1.0",
9697 "partial-json": "^0.1.7",
9798 "pg": "^8.11.3",
modified core/protocol/core.ts +11 −1
@@ -91,7 +91,7 @@
9191 },
9292 ];
9393 "config/deleteModel": [{ title: string }, void];
94- "config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
94+ "config/reload": [undefined, void];
9595 "config/refreshProfiles": [
9696 (
9797 | undefined
@@ -147,6 +147,9 @@
147147 "context/indexDocs": [{ reIndex: boolean }, void];
148148 "autocomplete/cancel": [undefined, void];
149149 "autocomplete/accept": [{ completionId: string }, void];
150+ "nextEdit/predict": [AutocompleteInput, string[]];
151+ "nextEdit/reject": [{ completionId: string }, void];
152+ "nextEdit/accept": [{ completionId: string }, void];
150153 "llm/complete": [
151154 {
152155 prompt: string;
@@ -183,6 +186,13 @@
183186 },
184187 string | undefined,
185188 ];
189+ "conversation/compact": [
190+ {
191+ index: number;
192+ sessionId: string;
193+ },
194+ string | undefined,
195+ ];
186196 "stats/getTokensPerDay": [
187197 undefined,
188198 { day: string; promptTokens: number; generatedTokens: number }[],
modified core/protocol/passThrough.ts +4 −0
@@ -37,6 +37,9 @@
3737 "autocomplete/complete",
3838 "autocomplete/cancel",
3939 "autocomplete/accept",
40+ "nextEdit/predict",
41+ "nextEdit/reject",
42+ "nextEdit/accept",
4043 "tts/kill",
4144 "llm/complete",
4245 "llm/streamChat",
@@ -44,6 +47,7 @@
4447 "llm/compileChat",
4548 "streamDiffLines",
4649 "chatDescriber/describe",
50+ "conversation/compact",
4751 "stats/getTokensPerDay",
4852 "stats/getTokensPerModel",
4953 // Codebase
modified core/test/fixtures.ts +1 −0
@@ -13,6 +13,7 @@
1313 export const testControlPlaneClient = new ControlPlaneClient(
1414 Promise.resolve(undefined),
1515 ideSettingsPromise,
16+ testIde.getIdeInfo(),
1617 );
1718
1819 export const testConfigHandler = new ConfigHandler(
modified core/tools/implementations/runTerminalCommand.ts +19 −2
@@ -1,5 +1,22 @@
1+import iconv from "iconv-lite";
12 import childProcess from "node:child_process";
23 import util from "node:util";
4+// Automatically decode the buffer according to the platform to avoid garbled Chinese
5+function getDecodedOutput(data: Buffer): string {
6+ if (process.platform === "win32") {
7+ try {
8+ let out = iconv.decode(data, "utf-8");
9+ if (/�/.test(out)) {
10+ out = iconv.decode(data, "gbk");
11+ }
12+ return out;
13+ } catch {
14+ return iconv.decode(data, "gbk");
15+ }
16+ } else {
17+ return data.toString();
18+ }
19+}
320
421 import { fileURLToPath } from "node:url";
522 import { ToolImpl } from ".";
@@ -77,7 +94,7 @@
7794 // Skip if this process has been backgrounded
7895 if (isProcessBackgrounded(toolCallId)) return;
7996
80- const newOutput = data.toString();
97+ const newOutput = getDecodedOutput(data);
8198 terminalOutput += newOutput;
8299
83100 // Send partial output to UI
@@ -103,7 +120,7 @@
103120 // Skip if this process has been backgrounded
104121 if (isProcessBackgrounded(toolCallId)) return;
105122
106- const newOutput = data.toString();
123+ const newOutput = getDecodedOutput(data);
107124 terminalOutput += newOutput;
108125
109126 // Send partial output to UI, status is not required
modified core/tsconfig.json +2 −0
@@ -16,6 +16,8 @@
1616 "noEmit": true,
1717 "jsx": "react-jsx",
1818 "noEmitOnError": false,
19+ "experimentalDecorators": true,
20+ "emitDecoratorMetadata": true,
1921 "types": ["jest", "node"]
2022 },
2123 "include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"],
modified core/util/GlobalContext.test.ts +65 −9
@@ -1,7 +1,6 @@
11 // core/util/GlobalContext.test.ts
2-import { GlobalContext, GlobalContextType } from "./GlobalContext";
32 import fs from "node:fs";
4-import path from "path";
3+import { GlobalContext } from "./GlobalContext";
54 import { getGlobalContextFilePath } from "./paths";
65
76 describe("GlobalContext", () => {
@@ -69,13 +68,40 @@
6968 const value = globalContext.get("indexingPaused");
7069 expect(value).toBeUndefined();
7170 expect(consoleWarnMock).toHaveBeenCalledWith(
72- expect.stringContaining("Error parsing global context"),
71+ expect.stringContaining(
72+ "Error parsing global context, deleting corrupted file",
73+ ),
7374 );
7475
7576 // Clean up
7677 consoleWarnMock.mockRestore();
7778 });
7879
80+ it("should delete corrupted file on get and allow fresh start", () => {
81+ // Write invalid JSON to the file
82+ fs.writeFileSync(globalContextFilePath, "{ invalid json }");
83+ expect(fs.existsSync(globalContextFilePath)).toBe(true);
84+
85+ const consoleWarnMock = jest
86+ .spyOn(console, "warn")
87+ .mockImplementation(() => {});
88+
89+ // Try to get a value - this should delete the corrupted file
90+ const value = globalContext.get("indexingPaused");
91+ expect(value).toBeUndefined();
92+
93+ // File should be deleted after corruption is detected
94+ expect(fs.existsSync(globalContextFilePath)).toBe(false);
95+
96+ // Now we should be able to update and get values normally
97+ globalContext.update("indexingPaused", true);
98+ const newValue = globalContext.get("indexingPaused");
99+ expect(newValue).toBe(true);
100+
101+ // Clean up
102+ consoleWarnMock.mockRestore();
103+ });
104+
79105 it("should handle JSON parsing errors gracefully on update", () => {
80106 // Write invalid JSON to the file
81107 fs.writeFileSync(globalContextFilePath, "{ invalid json }");
@@ -87,15 +113,45 @@
87113 // Attempt to update
88114 globalContext.update("indexingPaused", true);
89115
90- // The update should have been skipped due to JSON parsing error
91- // So attempting to get the value should return undefined
92- const value = globalContext.get("indexingPaused");
93- expect(value).toBeUndefined();
94-
95116 expect(consoleWarnMock).toHaveBeenCalledWith(
96- expect.stringContaining("Error updating global context"),
117+ expect.stringContaining(
118+ "Error updating global context, deleting corrupted file",
119+ ),
97120 );
98121
122+ // The update should have recreated the file with just the new value
123+ const value = globalContext.get("indexingPaused");
124+ expect(value).toBe(true);
125+
126+ // Clean up
127+ consoleWarnMock.mockRestore();
128+ });
129+
130+ it("should delete and recreate corrupted file on update", () => {
131+ // Write invalid JSON to the file
132+ fs.writeFileSync(globalContextFilePath, "{ invalid json }");
133+ expect(fs.existsSync(globalContextFilePath)).toBe(true);
134+
135+ const consoleWarnMock = jest
136+ .spyOn(console, "warn")
137+ .mockImplementation(() => {});
138+
139+ // Try to update - this should delete the corrupted file and recreate it
140+ globalContext.update("indexingPaused", true);
141+
142+ // File should still exist but with valid JSON now
143+ expect(fs.existsSync(globalContextFilePath)).toBe(true);
144+
145+ // Should be able to read the value
146+ const value = globalContext.get("indexingPaused");
147+ expect(value).toBe(true);
148+
149+ // Should be able to add more values
150+ globalContext.update("hasAlreadyCreatedAPromptFile", false);
151+ expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(false);
152+ // Original value should still be there
153+ expect(globalContext.get("indexingPaused")).toBe(true);
154+
99155 // Clean up
100156 consoleWarnMock.mockRestore();
101157 });
modified core/util/GlobalContext.ts +33 −2
@@ -68,7 +68,28 @@
6868 try {
6969 parsed = JSON.parse(data);
7070 } catch (e: any) {
71- console.warn(`Error updating global context: ${e}`);
71+ console.warn(
72+ `Error updating global context, deleting corrupted file: ${e}`,
73+ );
74+ // Delete the corrupted file and recreate it fresh
75+ try {
76+ fs.unlinkSync(filepath);
77+ } catch (deleteError) {
78+ console.warn(
79+ `Error deleting corrupted global context file: ${deleteError}`,
80+ );
81+ }
82+ // Recreate the file with just the new value
83+ fs.writeFileSync(
84+ filepath,
85+ JSON.stringify(
86+ {
87+ [key]: value,
88+ },
89+ null,
90+ 2,
91+ ),
92+ );
7293 return;
7394 }
7495
@@ -90,7 +111,17 @@
90111 const parsed = JSON.parse(data);
91112 return parsed[key];
92113 } catch (e: any) {
93- console.warn(`Error parsing global context: ${e}`);
114+ console.warn(
115+ `Error parsing global context, deleting corrupted file: ${e}`,
116+ );
117+ // Delete the corrupted file so it can be recreated fresh
118+ try {
119+ fs.unlinkSync(filepath);
120+ } catch (deleteError) {
121+ console.warn(
122+ `Error deleting corrupted global context file: ${deleteError}`,
123+ );
124+ }
94125 return undefined;
95126 }
96127 }
added core/util/conversationCompaction.ts +89 −0
@@ -0,0 +1,89 @@
1+import { ILLM } from "..";
2+import { HistoryManager } from "./history";
3+import { stripImages } from "./messageContent";
4+
5+export interface CompactionParams {
6+ sessionId: string;
7+ index: number;
8+ historyManager: HistoryManager;
9+ currentModel: ILLM;
10+}
11+
12+/**
13+ * Compacts conversation history up to a specified index by generating a summary.
14+ * This helper function extracts the compaction logic from the main core handler.
15+ *
16+ * @param params - Object containing sessionId, index, historyManager, and currentModel
17+ * @returns Promise<void> - Updates the session with the conversation summary
18+ */
19+export async function compactConversation({
20+ sessionId,
21+ index,
22+ historyManager,
23+ currentModel,
24+}: CompactionParams): Promise<void> {
25+ // Get the current session
26+ const session = historyManager.load(sessionId);
27+ const historyUpToIndex = session.history.slice(0, index + 1);
28+
29+ // Apply the same filtering logic as in constructMessages, but exclude the target message
30+ // if it already has a summary (we're re-compacting)
31+ let summaryContent = "";
32+ let filteredHistory = historyUpToIndex;
33+
34+ // First, check if the target message already has a summary and ignore it
35+ const targetMessageHasSummary = historyUpToIndex[index].conversationSummary;
36+ const searchHistory = targetMessageHasSummary
37+ ? historyUpToIndex.slice(0, index)
38+ : historyUpToIndex;
39+
40+ // Find the most recent conversation summary (excluding target if it has one)
41+ for (let i = searchHistory.length - 1; i >= 0; i--) {
42+ const summary = searchHistory[i].conversationSummary;
43+ if (summary) {
44+ summaryContent = summary;
45+ // Only include messages that come AFTER the message with the summary
46+ filteredHistory = historyUpToIndex.slice(i + 1);
47+ break;
48+ }
49+ }
50+
51+ // Create messages from filtered history
52+ const messages = filteredHistory.map((item: any) => item.message);
53+
54+ // If there's a previous summary, include it as a user message at the beginning
55+ if (summaryContent) {
56+ messages.unshift({
57+ role: "user",
58+ content: `Previous conversation summary:\n\n${summaryContent}`,
59+ });
60+ }
61+
62+ const compactionPrompt = {
63+ role: "user" as const,
64+ content:
65+ "Create a comprehensive summary of this conversation that captures all essential information needed to continue the work seamlessly. Structure your response to preserve technical accuracy and context continuity.\n\nYour summary should include:\n\n1. **Conversation Overview**: Describe the main topic and progression of the discussion, including any shifts in focus or direction.\n\n2. **Active Development**: Detail what was being implemented, modified, or debugged most recently. Include specific technical approaches and methodologies used.\n\n3. **Technical Stack**: List all relevant technologies, frameworks, libraries, coding patterns, and architectural decisions discussed.\n\n4. **File Operations**: Document all files that were created, modified, or referenced, including their purposes and key changes. Include important code snippets and their locations.\n\n5. **Solutions & Troubleshooting**: Summarize problems encountered and how they were resolved, including any debugging steps or workarounds applied.\n\n6. **Outstanding Work**: Clearly identify any incomplete tasks, pending implementations, or next steps that were discussed. Include direct references to user requests and current progress.\n\nIf there's a previous summary in the conversation, integrate its relevant information while removing outdated details. Focus on technical precision and include specific identifiers (file paths, function names, class names, etc.) that would be essential for continuation. Write in third person and maintain an objective, technical tone.",
66+ };
67+
68+ // Generate the summary using the current model
69+ const response = await currentModel.chat(
70+ [...messages, compactionPrompt],
71+ new AbortController().signal,
72+ {},
73+ );
74+
75+ // Update the target message with the conversation summary
76+ const updatedHistory = [...session.history];
77+ updatedHistory[index] = {
78+ ...updatedHistory[index],
79+ conversationSummary: stripImages(response.content),
80+ };
81+
82+ // Update the session with the new history
83+ const updatedSession = {
84+ ...session,
85+ history: updatedHistory,
86+ };
87+
88+ historyManager.save(updatedSession);
89+}
modified core/util/filesystem.ts +1 −0
@@ -120,6 +120,7 @@
120120 version: "0.1",
121121 remoteName: "na",
122122 extensionVersion: "na",
123+ isPrerelease: false,
123124 });
124125 }
125126
modified core/util/history.ts +1 −1
@@ -21,7 +21,7 @@
2121 }
2222 }
2323
24-class HistoryManager {
24+export class HistoryManager {
2525 list(options: ListHistoryOptions): SessionMetadata[] {
2626 const filepath = getSessionsListPath();
2727 if (!fs.existsSync(filepath)) {
modified docs/customize/deep-dives/mcp.mdx +1 −35
@@ -57,41 +57,7 @@
5757
5858 You can set up an MCP server to search the Continue documentation directly from your agent. This is particularly useful for getting help with Continue configuration and features.
5959
60-1. Create a folder called `.continue/mcpServers` at the top level of your workspace
61-2. Add a file called `continue-docs-mcp.yaml` to this folder
62-3. Write the following contents and save:
63-
64-```yaml title=".continue/mcpServers/continue-docs-mcp.yaml"
65-name: Continue Documentation MCP
66-version: 0.0.1
67-schema: v1
68-mcpServers:
69- - name: Continue Docs Search
70- type: stdio
71- command: npx
72- args:
73- - mint-mcp
74- - add
75- - continue-docs
76-```
77-
78-Now you can search the Continue documentation by asking questions like:
79-
80-```
81-Search for model setup instructions in the Continue docs
82-```
83-
84-```
85-Find documentation about context providers
86-```
87-
88-```
89-How do I configure autocomplete in Continue?
90-```
91-
92-The MCP server will search the Continue documentation and provide relevant information to help with your questions.
93-
94-For detailed setup instructions and troubleshooting, see the [Continue MCP Reference](/reference/continue-mcp).
60+For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp).
9561
9662 ## Using MCP Servers
9763
modified docs/customize/model-providers/top-level/xAI.mdx +6 −6
@@ -9,18 +9,18 @@
99
1010 ## Chat model
1111
12-We recommend configuring **grok-2-latest** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models).
12+We recommend configuring **grok-4** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models).
1313
1414 <Tabs>
1515 <Tab title="Config">
16- Add the [xAI Grok 2 model block](https://hub.continue.dev/xai/grok-2) on the hub.
16+ Add the [xAI Grok 4 model block](https://hub.continue.dev/xai/grok-4) on the hub.
1717 </Tab>
1818 <Tab title="YAML">
1919 ```yaml title="config.yaml"
2020 models:
21- - name: Grok 2
21+ - name: Grok 4
2222 provider: xAI
23- model: grok-2-latest
23+ model: grok-4
2424 apiKey: <YOUR_XAI_API_KEY>
2525 ```
2626 </Tab>
@@ -29,9 +29,9 @@
2929 {
3030 "models": [
3131 {
32- "title": "Grok 2",
32+ "title": "Grok 4",
3333 "provider": "xAI",
34- "model": "grok-2-latest",
34+ "model": "grok-4",
3535 "apiKey": "<YOUR_XAI_API_KEY>"
3636 }
3737 ]
modified docs/docs.json +2 −1
@@ -258,7 +258,8 @@
258258 "pages": [
259259 "reference",
260260 "reference/json-reference",
261- "reference/yaml-migration"
261+ "reference/yaml-migration",
262+ "reference/continue-mcp"
262263 ]
263264 }
264265 ]
modified docs/features/agent/model-setup.mdx +2 −13
@@ -1,14 +1,3 @@
1-We recommend **Claude 3.5 Sonnet** from Anthropic for the best Agent experience.
1+The models you set up for Chat mode will be used with Agent mode if the model supports tool calling.
22
3-- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022)
4-- Get your API key from the [Anthropic console](https://console.anthropic.com/)
5-
6-## Other recommended models
7-
8-- [Claude Sonnet 4 from Anthropic](https://hub.continue.dev/anthropic)
9-- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o)
10-- [Gemini 2.0 Pro from Google](https://hub.continue.dev/google/gemini-2.0-pro)
11-
12-Agent can be used with models that support tool use through Continue. The best chat models generally support tool use.
13-
14-For more information on models, check out [our recommended chat models](/features/chat/model-setup).
3+The recommended models and how to set them up can be found [here](/features/chat/model-setup).
modified docs/features/autocomplete/model-setup.mdx +28 −10
@@ -2,25 +2,43 @@
22
33 ## Recommended Models
44
5-### Hosted-Based (Best Performance)
5+### Hosted (Best Performance)
66
7-For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral. This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
7+For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral.
88
9-**Quick Setup:**
9+This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
10+
11+**Codestral Quick Setup:**
12+
13+1. Get your API key from [Mistral AI](https://console.mistral.ai)
14+2. Add [Codestral](https://hub.continue.dev/mistral/codestral) to your assistant on Continue Hub
15+3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
16+4. Click `Reload config` in the assistant selector in the Continue IDE extension
17+
18+### Hosted (Best Speed/Quality Tradeoff)
19+
20+For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception Labs.
21+
22+This model is specifically designed for code completion and is particularly fast because it is a diffusion model.
23+
24+**Mercury Coder Small Quick Setup:**
25+
26+1. Get your API key from [Inception Labs](https://platform.inceptionlabs.ai/)
27+2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub
28+3. Add `INCEPTION_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
29+4. Click `Reload config` in the assistant selector in the Continue IDE extension
1030
11-1. [Add Codestral from the hub](https://hub.continue.dev/mistral/codestral)
12-2. Get your API key from the [Mistral Platform](https://console.mistral.ai/codestral)
13-3. Configure it in your Continue settings
31+### Local (Offline / Privacy First)
1432
15-### Local/Offline (Privacy First)
33+For a fully local autocomplete experience, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)**.
1634
17-For a fully local autocomplete experience that doesn't send your code to external servers, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)** running on Ollama. This model provides good suggestions while keeping your code completely private.
35+This model provides good suggestions while keeping your code completely private.
1836
1937 **Quick Setup:**
2038
2139 1. Install [Ollama](https://ollama.ai/)
22-2. [Add Qwen 2.5 Coder from the hub](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)
23-3. Configure it in your Continue settings
40+2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub
41+3. Click `Reload config` in the assistant selector in the Continue IDE extension
2442
2543 ## Need Help?
2644
modified docs/features/chat/model-setup.mdx +72 −11
@@ -1,19 +1,80 @@
1-We recommend setting up a model for the best experience.
1+The model you use for for Chat mode will be
2+
3+- used with Edit mode by default but can be switched
4+- always used with Agent mode if the model supports tool calling
25
36 ## Recommended Models
47
5-Here's our primary model recommendation:
8+Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic.
9+
10+Its strong tool calling and reasoning capabilities make it the best model for Agent mode.
11+
12+1. Get your API key from [Anthropic](https://console.anthropic.com/)
13+2. Add [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) to your assistant on Continue Hub
14+3. Add `ANTHROPIC_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
15+4. Click `Reload config` in the assistant selector in the Continue IDE extension
16+
17+#### Other hosted models
18+
19+These models have varying tool calling and reasoning capabilities.
20+
21+[Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) from Google
22+
23+1. Get your API key from [Google AI Studio](https://aistudio.google.com)
24+2. Add [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) to your assistant on Continue Hub
25+3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
26+4. Click `Reload config` in the assistant selector in the Continue IDE extension
27+
28+[o3](https://hub.continue.dev/openai/o3) from OpenAI
29+
30+1. Get your API key from [OpenAI](https://platform.openai.com)
31+2. Add [o3](https://hub.continue.dev/openai/o3) to your assistant on Continue Hub
32+3. Add `OPENAI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
33+4. Click `Reload config` in the assistant selector in the Continue IDE extension
34+
35+[Grok 4](https://hub.continue.dev/xai/grok-4) from xAI
36+
37+1. Get your API key from [xAI](https://console.x.ai/)
38+2. Add [Grok 4](https://hub.continue.dev/xai/grok-4) to your assistant on Continue Hub
39+3. Add `XAI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
40+4. Click `Reload config` in the assistant selector in the Continue IDE extension
41+
42+[Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) from Mistral AI
43+
44+1. Get your API key from [Mistral AI](https://console.mistral.ai/)
45+2. Add [Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) to your assistant on Continue Hub
46+3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
47+4. Click `Reload config` in the assistant selector in the Continue IDE extension
48+
49+[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI
50+
51+1. Get your API key from [TogetherAI](https://api.together.ai)
52+2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub
53+3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
54+4. Click `Reload config` in the assistant selector in the Continue IDE extension
55+
56+#### Local models
57+
58+These models can be run on your computer if you have enough VRAM.
59+
60+Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode.
61+
62+[Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen
63+
64+1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to your assistant on Continue Hub
65+2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
66+3. Click `Reload config` in the assistant selector in the Continue IDE extension
667
7-**Claude 3.5 Sonnet** from Anthropic
68+[Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) from Google
869
9-- [Add Claude 3.5 Sonnet to your assistant from the hub](https://hub.continue.dev/anthropic/claude-3-5-sonnet-20241022)
10-- Get your API key from the [Anthropic console](https://console.anthropic.com/)
70+1. Add [Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) to your assistant on Continue Hub
71+2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
72+3. Click `Reload config` in the assistant selector in the Continue IDE extension
1173
12-Other top models to consider:
74+[Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) from Meta
1375
14-- [GPT-4o from OpenAI](https://hub.continue.dev/openai/gpt-4o)
15-- [Grok-2 from xAI](https://hub.continue.dev/xai/grok-2)
16-- [Gemini 2.0 Flash from Google](https://hub.continue.dev/google/gemini-2.0-flash)
17-- [Llama 3.1 8b from Meta (local)](https://hub.continue.dev/ollama/llama3.1)
76+1. Add [Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) to your assistant on Continue Hub
77+2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
78+3. Click `Reload config` in the assistant selector in the Continue IDE extension
1879
19-For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model).
80+For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model)
modified docs/features/edit/model-setup.mdx +4 −6
@@ -1,6 +1,6 @@
1-By default, Edit uses the same model as Chat. We recommend **Claude 3.5 Sonnet** from Anthropic.
1+The model you set up for Chat mode will be used for Edit mode by default.
22
3-[Explore other Edit models on the Continue Hub →](https://hub.continue.dev)
3+The recommended models and how to set them up can be found [here](/features/chat/model-setup).
44
55 ## Apply Model
66
@@ -8,7 +8,5 @@
88
99 **Recommended Apply models:**
1010
11-- [Morph v0 Fast Apply](https://hub.continue.dev)
12-- [Relace Instant Apply](https://hub.continue.dev)
13-
14-[Explore other Apply models on the Continue Hub →](https://hub.continue.dev)
11+- [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
12+- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)
added docs/images/mintlify-cli-selection-tree.png +0 −0

Binary content is not shown. View the file.

modified docs/reference/continue-mcp.mdx +19 −12
@@ -4,45 +4,52 @@
44 keywords: [mcp, documentation, search, mintlify, reference]
55 ---
66
7-# Continue Documentation MCP Server
8-
9-The Continue Documentation MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations. This is powered by Mintlify's MCP server generation.
7+The continue-docs MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations. This is powered by Mintlify's MCP server generation.
108
119 ## Installation
1210
1311 ### Step 1: Install the MCP Server
1412
15-Run the following command to install the Continue documentation MCP server:
13+Run the following command to install the continue-docs MCP server:
1614
1715 ```bash
18-npx mint-mcp add continue-docs
16+npx mint-mcp add docs.continue.dev
1917 ```
2018
21-This will:
19+When prompted, select "All" from the selection menu:
20+
21+![mintlify cli selection tree](/images/mintlify-cli-selection-tree.png)
22+
23+This command will:
2224
2325 - Download and install the MCP server locally
2426 - Set up the search tool for Continue documentation
2527 - Create the necessary configuration files
2628
29+<Info>
30+Take note of the installation path displayed after running the command above. You'll need to replace in the configuration below with your actual installation path.
31+
32+It will look like this: `/path/to/user/.mcp/docs.continue.dev/src/index.js`
33+
34+</Info>
35+
2736 ### Step 2: Configure Continue
2837
2938 1. Create a folder called `.continue/mcpServers` at the top level of your workspace
3039 2. Add a file called `continue-docs-mcp.yaml` to this folder
3140 3. Write the following contents and save:
3241
42+````yaml title=".continue/mcpServers/continue-docs-mcp.yaml"
3343 ```yaml title=".continue/mcpServers/continue-docs-mcp.yaml"
3444 name: Continue Documentation MCP
3545 version: 0.0.1
3646 schema: v1
3747 mcpServers:
3848 - name: Continue Docs Search
39- type: stdio
40- command: npx
49+ command: node
4150 args:
42- - mint-mcp
43- - add
44- - continue-docs
45-```
51+ - "/path/to/user/.mcp/docs.continue.dev/src/index.js"
52+````
4653
4754 ### Step 3: Enable Agent Mode
4855
modified extensions/intellij/gradle.properties +1 −1
@@ -3,7 +3,7 @@
33 pluginName=continue-intellij-extension
44 pluginRepositoryUrl=https://github.com/continuedev/continue
55 # SemVer format -> https://semver.org
6-pluginVersion=1.0.28
6+pluginVersion=1.0.30
77 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
88 pluginSinceBuild=223
99 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +8 −0
@@ -1,6 +1,7 @@
11 package com.github.continuedev.continueintellijextension.actions
22
33 import com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction
4+import com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction
45 import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
56 import com.intellij.openapi.actionSystem.ActionPromoter
67 import com.intellij.openapi.actionSystem.AnAction
@@ -19,6 +20,13 @@
1920 }
2021 }
2122
23+ if (actions.any { it is AcceptNextEditAction }) {
24+ val settings = service<ContinueExtensionSettings>()
25+ if (settings.continueState.showIDECompletionSideBySide) {
26+ return actions.filterIsInstance<AcceptNextEditAction>()
27+ }
28+ }
29+
2230 val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>()
2331 if (rejectDiffActions.isNotEmpty()) {
2432 return rejectDiffActions
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt +61 −5
@@ -1,5 +1,8 @@
11 package com.github.continuedev.continueintellijextension.autocomplete
22
3+import com.github.continuedev.continueintellijextension.nextEdit.NextEditService
4+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
5+import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
36 import com.intellij.openapi.application.invokeLater
47 import com.intellij.openapi.components.service
58 import com.intellij.openapi.editor.Editor
@@ -37,6 +40,16 @@
3740 class AutocompleteDocumentListener(private val editorManager: FileEditorManager, private val editor: Editor) :
3841 DocumentListener {
3942 override fun documentChanged(event: DocumentEvent) {
43+ // Ignore empty changes or changes where content didn't actually change.
44+ if (event.newFragment.isEmpty() && event.oldFragment.isEmpty()) {
45+ return
46+ }
47+
48+ // Make sure this is an actual text modification event.
49+ if (!event.isWholeTextReplaced && event.offset == 0 && event.oldLength == 0 && event.newLength == 0) {
50+ return
51+ }
52+
4053 if (editor != editorManager.selectedTextEditor) {
4154 return
4255 }
@@ -46,12 +59,55 @@
4659 return
4760 }
4861
49- // Invoke later is important, otherwise the completion will be triggered before the document is updated
50- // causing the old caret offset to be used
51- // TODO: concurrency
52- invokeLater {
53- service.triggerCompletion(editor)
62+ val nextEditService = editor.project?.service<NextEditService>() ?: return
63+
64+ // Check if we're in a test environment based on some property or condition
65+ val isAutocompleteTestEnvironment = System.getProperty("continue.autocomplete.test.environment") == "true"
66+ val isNextEditTestEnvironment = System.getProperty("continue.nextEdit.test.environment") == "true"
67+
68+ if (isAutocompleteTestEnvironment) {
69+ invokeLater {
70+ service.triggerCompletion(editor)
71+ }
72+ return
73+ } else if (isNextEditTestEnvironment) {
74+ invokeLater {
75+ nextEditService.triggerNextEdit(editor)
76+ }
77+ return
78+ }
79+
80+ // Check settings to see if next edit is enabled, and then trigger either autocomplete or next exit.
81+ val continuePluginService = editor.project?.service<ContinuePluginService>()
82+ if (continuePluginService == null) {
83+ return
5484 }
85+
86+ continuePluginService.coreMessenger?.request(
87+ "config/getSerializedProfileInfo",
88+ null,
89+ null,
90+ ({ response ->
91+ val optInNextEditFeature = response.castNestedOrNull<Boolean>(
92+ "content",
93+ "result",
94+ "config",
95+ "experimental",
96+ "optInNextEditFeature"
97+ ) ?: false
98+
99+ invokeLater {
100+ if (optInNextEditFeature) {
101+ nextEditService.triggerNextEdit(editor)
102+ } else {
103+ // Invoke later is important, otherwise the completion will be triggered before the document is updated
104+ // causing the old caret offset to be used
105+ // TODO: concurrency
106+ service.triggerCompletion(editor)
107+ }
108+ }
109+ })
110+ )
55111 }
56112 }
57113
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +5 −1
@@ -103,6 +103,9 @@
103103 "autocomplete/complete",
104104 "autocomplete/cancel",
105105 "autocomplete/accept",
106+ "nextEdit/predict",
107+ "nextEdit/reject",
108+ "nextEdit/accept",
106109 "tts/kill",
107110 "llm/complete",
108111 "llm/streamChat",
@@ -110,6 +113,7 @@
110113 "llm/compileChat",
111114 "streamDiffLines",
112115 "chatDescriber/describe",
116+ "conversation/compact",
113117 "stats/getTokensPerDay",
114118 "stats/getTokensPerModel",
115119 // Codebase
@@ -135,4 +139,4 @@
135139 "process/isBackgrounded",
136140 )
137141 }
138-}
No newline at the end of the file
142+}
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +3 −2
@@ -1,3 +1,4 @@
1+
12 package com.github.continuedev.continueintellijextension.`continue`
23
34 import com.github.continuedev.continueintellijextension.*
@@ -86,7 +87,8 @@
8687 name = ideName,
8788 version = ideVersion,
8889 remoteName = remoteName,
89- extensionVersion = extensionVersion
90+ extensionVersion = extensionVersion,
91+ isPrerelease = false // TODO: Implement prerelease detection for JetBrains
9092 )
9193 }
9294
@@ -623,4 +625,3 @@
623625 }
624626
625627 }
626-
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt +25 −0
@@ -0,0 +1,25 @@
1+package com.github.continuedev.continueintellijextension.nextEdit
2+
3+import com.intellij.openapi.actionSystem.DataContext
4+import com.intellij.openapi.application.ApplicationManager
5+import com.intellij.openapi.components.service
6+import com.intellij.openapi.editor.Caret
7+import com.intellij.openapi.editor.Editor
8+import com.intellij.openapi.editor.actionSystem.EditorAction
9+import com.intellij.openapi.editor.actionSystem.EditorActionHandler
10+
11+class AcceptNextEditAction : EditorAction(object : EditorActionHandler() {
12+ override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) {
13+ ApplicationManager.getApplication().runWriteAction {
14+ editor.project?.service<NextEditService>()?.accept()
15+ }
16+ }
17+
18+ override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean {
19+ val nextEditService = editor.project?.service<NextEditService>();
20+ val enabled = editor == nextEditService?.pendingCompletion?.editor
21+// && caret.offset == autocompleteService.pendingCompletion?.offset
22+ && nextEditService.pendingCompletion?.text != null
23+ return enabled
24+ }
25+})
No newline at the end of the file
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt +321 −0
@@ -0,0 +1,321 @@
1+package com.github.continuedev.continueintellijextension.nextEdit
2+
3+import com.github.continuedev.continueintellijextension.FimResult
4+import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteLookupListener
5+import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteSpinnerWidget
6+import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlayRenderer
7+import com.github.continuedev.continueintellijextension.autocomplete.PendingCompletion
8+import com.github.continuedev.continueintellijextension.autocomplete.addInlayElement
9+import com.github.continuedev.continueintellijextension.autocomplete.isInjectedText
10+import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
11+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
12+import com.github.continuedev.continueintellijextension.utils.checkFim
13+import com.github.continuedev.continueintellijextension.utils.toUriOrNull
14+import com.github.continuedev.continueintellijextension.utils.uuid
15+import com.intellij.openapi.application.ApplicationManager
16+import com.intellij.openapi.application.WriteAction
17+import com.intellij.openapi.application.invokeLater
18+import com.intellij.openapi.application.runReadAction
19+import com.intellij.openapi.components.Service
20+import com.intellij.openapi.components.service
21+import com.intellij.openapi.editor.Editor
22+import com.intellij.openapi.editor.InlayProperties
23+import com.intellij.openapi.fileEditor.FileDocumentManager
24+import com.intellij.openapi.project.Project
25+import com.intellij.openapi.util.TextRange
26+import com.intellij.openapi.wm.WindowManager
27+import com.intellij.psi.PsiDocumentManager
28+
29+@Service(Service.Level.PROJECT)
30+class NextEditService(private val project: Project) {
31+ var pendingCompletion: PendingCompletion? = null
32+ private val autocompleteLookupListener = project.service<AutocompleteLookupListener>()
33+ private val widget: AutocompleteSpinnerWidget? by lazy {
34+ WindowManager.getInstance().getStatusBar(project)
35+ ?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget
36+ }
37+
38+ // To avoid triggering another completion on partial acceptance,
39+ // we need to keep track of whether the last change was a partial accept.
40+ var lastChangeWasPartialAccept = false
41+
42+ fun triggerNextEdit(editor: Editor) {
43+ val settings = service<ContinueExtensionSettings>()
44+ if (!settings.continueState.enableTabAutocomplete) {
45+ return
46+ }
47+
48+ if (pendingCompletion != null) {
49+ clearCompletions(pendingCompletion!!.editor)
50+ }
51+
52+ // Set pending completion.
53+ val completionId = uuid()
54+ val offset = editor.caretModel.primaryCaret.offset
55+ pendingCompletion = PendingCompletion(editor, offset, completionId, null)
56+
57+ // Request a completion from the core.
58+ val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
59+
60+ val uri = virtualFile?.toUriOrNull() ?: return
61+
62+ widget?.setLoading(true)
63+
64+ val line = editor.caretModel.primaryCaret.logicalPosition.line
65+ val column = editor.caretModel.primaryCaret.logicalPosition.column
66+ val input = mapOf(
67+ "completionId" to completionId,
68+ "filepath" to uri,
69+ "pos" to mapOf(
70+ "line" to line,
71+ "character" to column
72+ ),
73+ "clipboardText" to "",
74+ "recentlyEditedRanges" to emptyList<Any>(),
75+ "recentlyVisitedRanges" to emptyList<Any>(),
76+ )
77+
78+ // TODO: Add message support for nextEdit/predict.
79+ project.service<ContinuePluginService>().coreMessenger?.request(
80+ "nextEdit/predict",
81+ input,
82+ null,
83+ ({ response ->
84+ if (pendingCompletion == null || pendingCompletion?.completionId == completionId) {
85+ widget?.setLoading(false)
86+ }
87+
88+ val responseObject = response as Map<*, *>
89+ val predictions = responseObject["content"] as List<*>
90+
91+ if (predictions.isNotEmpty()) {
92+ val prediction = predictions[0].toString()
93+ val oldEditRange = predictions[1].toString()
94+ // Check if the prediction is purely additive.
95+ val result = checkFim(
96+ oldEditRange,
97+ prediction,
98+ Pair(line, column)
99+ )
100+ when (result) {
101+ is FimResult.FimEdit -> {
102+ // If so, render ghost text.
103+ val finalTextToInsert = deduplicateCompletion(editor, offset, result.fimText)
104+ if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) {
105+ renderCompletion(editor, offset, finalTextToInsert)
106+ pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
107+ }
108+ }
109+ is FimResult.NotFimEdit -> {
110+ // Else, render a window.
111+ if (shouldRenderCompletion(prediction, offset, line, editor)) {
112+ val nextEditWindowService = NextEditWindowService.getInstance(project)
113+ nextEditWindowService.showCodePreview(prediction, editor, completionId)
114+ }
115+ }
116+ }
117+ }
118+ })
119+ )
120+ }
121+
122+ private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean {
123+ if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) {
124+ return false
125+ }
126+
127+ if (completion.lines().size == 1) {
128+ return true
129+ }
130+
131+ val endOffset = editor.document.getLineEndOffset(line)
132+
133+ // Do not render if completion is multi-line and caret is in middle of line
134+ return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank()
135+ }
136+
137+ private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String {
138+ // Check if completion matches the first 10 characters after the cursor
139+ return ApplicationManager.getApplication().runReadAction<String> {
140+ val document = editor.document
141+ val caretOffset = editor.caretModel.offset
142+
143+ // Don't care about it if it's at the end of the document
144+ if (caretOffset == document.textLength) return@runReadAction completion
145+
146+ val N = 10
147+ var textAfterCursor = if (caretOffset + N <= document.textLength) {
148+ document.getText(TextRange(caretOffset, caretOffset + N))
149+ } else {
150+ document.getText(TextRange(caretOffset, document.textLength))
151+ }
152+
153+ // Avoid truncating the completion text when the text after the cursor is blank
154+ if (textAfterCursor.isBlank()) return@runReadAction completion
155+
156+ // Determine the index of a newline character within the text following the cursor.
157+ val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n')
158+ // If a newline character is found and the current line is not empty, truncate the text at that point.
159+ if (newlineIndex > 0) {
160+ textAfterCursor = textAfterCursor.substring(0, newlineIndex)
161+ }
162+
163+ val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor)
164+ if (indexOfTextAfterCursorInCompletion > 0) {
165+ return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1)
166+ } else if (indexOfTextAfterCursorInCompletion == 0) {
167+ return@runReadAction ""
168+ }
169+
170+ return@runReadAction completion
171+ }
172+ }
173+
174+ private fun renderCompletion(editor: Editor, offset: Int, completion: String) {
175+ if (completion.isEmpty()) {
176+ return
177+ }
178+ if (isInjectedFile(editor)) return
179+ // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled
180+ if (shouldSkipRender()) {
181+ return
182+ }
183+
184+ ApplicationManager.getApplication().invokeLater {
185+ WriteAction.run<Throwable> {
186+ // Clear existing completions
187+ hideCompletions(editor)
188+
189+ val properties = InlayProperties()
190+ properties.relatesToPrecedingText(true)
191+ properties.disableSoftWrapping(true)
192+
193+ val lines = completion.lines()
194+ pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
195+ editor.addInlayElement(lines, offset, properties)
196+
197+// val attributes = TextAttributes().apply {
198+// backgroundColor = JBColor.GREEN
199+// }
200+// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE")
201+// key.let { editor.colorsScheme.setAttributes(it, attributes) }
202+// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST)
203+ }
204+ }
205+ }
206+
207+ fun accept() {
208+ val completion = pendingCompletion ?: return
209+ val text = completion.text ?: return
210+ val editor = completion.editor
211+ val offset = completion.offset
212+ editor.document.insertString(offset, text)
213+
214+ editor.caretModel.moveToOffset(offset + text.length)
215+
216+ project.service<ContinuePluginService>().coreMessenger?.request(
217+ "nextEdit/accept",
218+ hashMapOf("completionId" to completion.completionId),
219+ null,
220+ ({})
221+ )
222+ invokeLater {
223+ clearCompletions(editor, completion)
224+ }
225+ }
226+
227+ private fun shouldSkipRender(): Boolean {
228+ val settings = service<ContinueExtensionSettings>()
229+ return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
230+ }
231+
232+ private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List<String> {
233+ val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex())
234+ .filter { it.isNotEmpty() }
235+
236+ val result = mutableListOf<String>()
237+ var currentDelimiter = ""
238+
239+ for (part in initialSplit) {
240+ if (part.matches(delimiterPattern.toRegex())) {
241+ currentDelimiter += part
242+ } else {
243+ if (currentDelimiter.isNotEmpty()) {
244+ result.add(currentDelimiter)
245+ currentDelimiter = ""
246+ }
247+ result.add(part)
248+ }
249+ }
250+
251+ if (currentDelimiter.isNotEmpty()) {
252+ result.add(currentDelimiter)
253+
254+ }
255+
256+ return result
257+ }
258+
259+ fun partialAccept() {
260+ val completion = pendingCompletion ?: return
261+ val text = completion.text ?: return
262+ val editor = completion.editor
263+ val offset = completion.offset
264+
265+ lastChangeWasPartialAccept = true
266+
267+ // Split the text into words, keeping delimiters
268+ val words = splitKeepingDelimiters(text)
269+ println(words)
270+ val word = words[0]
271+ editor.document.insertString(offset, word)
272+ editor.caretModel.moveToOffset(offset + word.length)
273+
274+ // Remove the completion and re-display it
275+ hideCompletions(editor)
276+ completion.text = text.substring(word.length)
277+ completion.offset += word.length
278+ renderCompletion(editor, completion.offset, completion.text!!)
279+ }
280+
281+ private fun rejectCompletion(completion: PendingCompletion) {
282+ // Send rejection message to core
283+ widget?.setLoading(false)
284+ project.service<ContinuePluginService>().coreMessenger?.request("nextEdit/reject", null, null, ({}))
285+ }
286+
287+ fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) {
288+ if (isInjectedFile(editor)) return
289+
290+ if (completion != null) {
291+// cancelCompletion(completion)
292+ if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null
293+ }
294+ disposeInlayRenderer(editor)
295+ }
296+
297+ private fun isInjectedFile(editor: Editor): Boolean {
298+ return runReadAction {
299+ PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false
300+ }
301+ }
302+
303+ fun hideCompletions(editor: Editor) {
304+ if (isInjectedFile(editor)) return
305+
306+ disposeInlayRenderer(editor)
307+ }
308+
309+ private fun disposeInlayRenderer(editor: Editor) {
310+ editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
311+ if (it.renderer is ContinueInlayRenderer) {
312+ it.dispose()
313+ }
314+ }
315+ editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
316+ if (it.renderer is ContinueInlayRenderer) {
317+ it.dispose()
318+ }
319+ }
320+ }
321+}
No newline at the end of the file
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt +304 −0
@@ -0,0 +1,304 @@
1+package com.github.continuedev.continueintellijextension.nextEdit
2+
3+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
4+import com.intellij.openapi.actionSystem.AnAction
5+import com.intellij.openapi.actionSystem.AnActionEvent
6+import com.intellij.openapi.actionSystem.CustomShortcutSet
7+import com.intellij.openapi.command.WriteCommandAction
8+import com.intellij.openapi.components.Service
9+import com.intellij.openapi.components.service
10+import com.intellij.openapi.editor.Document
11+import com.intellij.openapi.editor.Editor
12+import com.intellij.openapi.editor.EditorSettings
13+import com.intellij.openapi.editor.colors.EditorColorsManager
14+import com.intellij.openapi.editor.ex.EditorEx
15+import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
16+import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory
17+import com.intellij.openapi.fileEditor.FileDocumentManager
18+import com.intellij.openapi.fileTypes.FileTypeManager
19+import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
20+import com.intellij.openapi.project.Project
21+import com.intellij.openapi.ui.popup.JBPopupFactory
22+import com.intellij.openapi.ui.popup.JBPopupListener
23+import com.intellij.openapi.ui.popup.LightweightWindowEvent
24+import com.intellij.psi.PsiDocumentManager
25+import com.intellij.ui.EditorTextField
26+import com.intellij.ui.components.JBScrollPane
27+import java.awt.BorderLayout
28+import java.awt.Color
29+import java.awt.Dimension
30+import java.awt.FlowLayout
31+import java.awt.Point
32+import java.awt.event.ActionEvent
33+import java.awt.event.KeyAdapter
34+import java.awt.event.KeyEvent
35+import javax.swing.AbstractAction
36+import javax.swing.JButton
37+import javax.swing.JComponent
38+import javax.swing.JPanel
39+import javax.swing.JScrollPane
40+import javax.swing.KeyStroke
41+
42+@Service(Service.Level.PROJECT)
43+class NextEditWindowService(private val project: Project) {
44+ /**
45+ * Creates a Swing component that displays syntax-highlighted code.
46+ *
47+ * @param code The code to display
48+ * @param language The language/file extension of the code (e.g. "java", "kotlin", "py")
49+ * @param isEditable Whether the code should be editable (default: false)
50+ * @return A JComponent that can be added to the UI
51+ */
52+ fun createCodeViewer(code: String, language: String, document: Document, isEditable: Boolean = false): JComponent {
53+ // Get file type based on extension.
54+ // NOTE: This is actually IDE and tier-dependent. For example, TypeScript won't work on IntelliJ CE.
55+ val fileType = FileTypeManager.getInstance().getFileTypeByExtension(language)
56+
57+ // Create an EditorTextField with the specified code and file type.
58+ val editorTextField = object : EditorTextField(code, project, fileType) {
59+ override fun createEditor(): EditorEx {
60+ val editor = super.createEditor()
61+
62+ // Configure editor settings.
63+ val settings: EditorSettings = editor.settings
64+ settings.isLineNumbersShown = true
65+ settings.isLineMarkerAreaShown = true
66+ settings.isIndentGuidesShown = true
67+ settings.isVirtualSpace = false
68+ settings.isRightMarginShown = false
69+ settings.additionalLinesCount = 0
70+ settings.isShowingSpecialChars = false
71+ settings.isCaretRowShown = true
72+
73+ // Set read-only if not editable.
74+ editor.isViewer = !isEditable
75+
76+ // Syntax highlighter.
77+ // Get current editor color scheme.
78+ val currentScheme = EditorColorsManager.getInstance().globalScheme
79+
80+ // Apply syntax highlighting with current theme.
81+ val virtualFile = FileDocumentManager.getInstance().getFile(document)
82+ var syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, virtualFile)
83+
84+ // If we couldn't get a syntax highlighter from the file, try to get one just from the file type.
85+ if (syntaxHighlighter == null) {
86+ syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, null)
87+ }
88+
89+ // If we have a highlighter, apply it.
90+ if (syntaxHighlighter != null) {
91+ editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(
92+ syntaxHighlighter,
93+ currentScheme
94+ )
95+ } else {
96+ // Fallback to plain text highlighting if all attempts fail.
97+ val plainTextFileType = FileTypeManager.getInstance().getFileTypeByExtension("txt")
98+ editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(
99+ project,
100+ plainTextFileType
101+ )
102+ }
103+
104+ // Apply the theme's background color.
105+ editor.backgroundColor = currentScheme.defaultBackground
106+
107+ return editor
108+ }
109+
110+ // Override to ensure multi-line support.
111+ override fun getPreferredSize(): Dimension {
112+ val lineCount = code.lines().size
113+ // Adjust height based on line count (with some minimum).
114+ val preferredSize = super.getPreferredSize()
115+ val lineHeight = preferredSize.height / (if (lineCount > 0) lineCount else 1)
116+ val newHeight = lineHeight * (if (lineCount > 0) lineCount else 1) + 10 // Add padding
117+ return Dimension(preferredSize.width, newHeight)
118+ }
119+ }
120+
121+ // Enable multi-line mode.
122+ editorTextField.setOneLineMode(false)
123+
124+ // Wrap in a scroll pane for larger code blocks.
125+ val panel = JPanel(BorderLayout())
126+ panel.add(JBScrollPane(editorTextField), BorderLayout.CENTER)
127+
128+ return panel
129+ }
130+
131+ /**
132+ * Shows a popup dialog with the code preview.
133+ */
134+ fun showCodePreview(code: String, parentEditor: Editor, completionId: String) {
135+ // Use invokeAndWait or invokeLater to ensure we're on the EDT.
136+ com.intellij.openapi.application.ApplicationManager.getApplication().invokeLater {
137+ val codeViewer = createCodeViewer(code, getFileLanguage(parentEditor.document), parentEditor.document)
138+
139+ // Create a button panel.
140+ val buttonPanel = JPanel(FlowLayout(FlowLayout.RIGHT))
141+ val acceptButton = JButton("Accept (Tab)")
142+ val dismissButton = JButton("Dismiss (Esc)")
143+ buttonPanel.add(acceptButton)
144+ buttonPanel.add(dismissButton)
145+
146+ // Create a panel to hold the code viewer and buttons.
147+ val panel = JPanel(BorderLayout())
148+ panel.add(codeViewer, BorderLayout.CENTER)
149+ panel.add(buttonPanel, BorderLayout.SOUTH)
150+
151+
152+ // Create the popup.
153+ val popup = JBPopupFactory.getInstance()
154+ .createComponentPopupBuilder(panel, codeViewer)
155+ .setMovable(true)
156+ .setResizable(true)
157+ .setRequestFocus(true)
158+ .setCancelOnClickOutside(true)
159+ .setCancelOnOtherWindowOpen(true)
160+ .setFocusable(true)
161+ .addListener(object : JBPopupListener {
162+ override fun onClosed(event: LightweightWindowEvent) {
163+ if (!event.isOk) {
164+ // This only triggers when dismissed, not when accepted.
165+ println("Dismissing code preview popup")
166+ project.service<ContinuePluginService>().coreMessenger?.request(
167+ "nextEdit/reject",
168+ hashMapOf("completionId" to completionId),
169+ null, ({})
170+ )
171+ }
172+ }
173+ })
174+ .createPopup()
175+
176+ // Helper function to accept the code and apply it to the editor.
177+ fun acceptCode() {
178+ val document = parentEditor.document
179+ val caretModel = parentEditor.caretModel
180+ val caretOffset = caretModel.offset
181+ val caretPosition = document.getLineNumber(caretOffset)
182+
183+ // Calculate start and end lines.
184+ val totalLines = document.lineCount
185+ val startLine = maxOf(0, caretPosition - 5)
186+ val endLine = minOf(totalLines - 1, caretPosition + 5)
187+
188+ // Get start and end offsets.
189+ val startOffset = document.getLineStartOffset(startLine)
190+ val endOffset = document.getLineEndOffset(endLine)
191+
192+ // Write command to replace the text.
193+ WriteCommandAction.runWriteCommandAction(project) {
194+ document.replaceString(startOffset, endOffset, code)
195+ }
196+
197+ project.service<ContinuePluginService>().coreMessenger?.request(
198+ "nextEdit/accept",
199+ hashMapOf("completionId" to completionId),
200+ null, ({})
201+ )
202+ }
203+
204+ // Use ActionManager to handle Tab key globally during popup display.
205+ val acceptAction = object : AnAction() {
206+ override fun actionPerformed(e: AnActionEvent) {
207+ acceptCode()
208+ popup.closeOk(null)
209+ }
210+ }
211+
212+ // Create a custom shortcut set for the Tab key.
213+ val customShortcutSet = CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0))
214+
215+
216+ // Register action with shortcut.
217+ acceptAction.registerCustomShortcutSet(customShortcutSet, panel)
218+
219+ // Add button actions.
220+ acceptButton.addActionListener {
221+ acceptCode()
222+ popup.closeOk(null)
223+ }
224+
225+ dismissButton.addActionListener {
226+ popup.cancel()
227+ }
228+
229+ // Get the exact position of the cursor.
230+ val visualPosition = parentEditor.caretModel.visualPosition
231+ val cursorPoint = parentEditor.visualPositionToXY(visualPosition)
232+
233+ // Convert to screen coordinates.
234+ val editorComponent = parentEditor.component
235+ val locationOnScreen = editorComponent.locationOnScreen
236+ val screenPoint = Point(
237+ locationOnScreen.x + cursorPoint.x,
238+ locationOnScreen.y + cursorPoint.y
239+ )
240+
241+ // Show the popup at the cursor position.
242+ popup.showInScreenCoordinates(editorComponent, screenPoint)
243+
244+ // Ensure proper focus for keyboard shortcuts.
245+ codeViewer.requestFocusInWindow()
246+ }
247+ }
248+
249+ // Move editorConfig to a proper instance property that gets actual editor settings.
250+ private val editorConfig: EditorConfig by lazy {
251+ val settings = EditorSettingsExternalizable.getInstance()
252+ val editorFontSize = EditorColorsManager.getInstance().globalScheme.editorFontSize
253+ val editorFontFamily = EditorColorsManager.getInstance().globalScheme.editorFontName
254+
255+ EditorConfig(
256+ fontSize = editorFontSize.toDouble(),
257+ fontFamily = editorFontFamily
258+ )
259+ }
260+
261+ // Data class to hold editor configuration.
262+ private data class EditorConfig(
263+ val fontSize: Double = 14.0,
264+ val fontFamily: String = "JetBrains Mono"
265+ )
266+
267+ /**
268+ * Convenience method to map common programming languages to their file extensions.
269+ */
270+ fun mapLanguageToExtension(language: String): String {
271+ return when (language.lowercase()) {
272+ "javascript" -> "js"
273+ "typescript" -> "ts"
274+ "python" -> "py"
275+ "java" -> "java"
276+ "kotlin" -> "kt"
277+ "c++" -> "cpp"
278+ "c#" -> "cs"
279+ "go" -> "go"
280+ "rust" -> "rs"
281+ "ruby" -> "rb"
282+ "php" -> "php"
283+ "swift" -> "swift"
284+ "shell", "bash" -> "sh"
285+ "html" -> "html"
286+ "css" -> "css"
287+ "json" -> "json"
288+ "xml" -> "xml"
289+ "yaml", "yml" -> "yaml"
290+ "markdown", "md" -> "md"
291+ // Add more mappings as needed
292+ else -> language
293+ }
294+ }
295+
296+ private fun getFileLanguage(document: Document): String {
297+ val virtualFile = FileDocumentManager.getInstance().getFile(document)
298+ return virtualFile?.extension?.lowercase() ?: "text"
299+ }
300+
301+ companion object {
302+ fun getInstance(project: Project): NextEditWindowService = project.service()
303+ }
304+}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +1 −0
@@ -46,6 +46,7 @@
4646 init {
4747 System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
4848 System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
49+ System.setProperty("ide.browser.jcef.out-of-process.enabled", "false")
4950 }
5051
5152 val browser: ContinueBrowser by lazy {
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +8 −2
@@ -30,7 +30,8 @@
3030 val name: String,
3131 val version: String,
3232 val remoteName: String,
33- val extensionVersion: String
33+ val extensionVersion: String,
34+ val isPrerelease: Boolean
3435 )
3536
3637 data class Problem(
@@ -247,4 +248,9 @@
247248
248249 data class ShowFilePayload(
249250 val filepath: String
250-)
No newline at the end of the file
251+)
252+
253+sealed class FimResult {
254+ data class FimEdit(val fimText: String) : FimResult()
255+ object NotFimEdit : FimResult()
256+}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt +68 −0
@@ -1,5 +1,6 @@
11 package com.github.continuedev.continueintellijextension.utils
22
3+import com.github.continuedev.continueintellijextension.FimResult
34 import com.intellij.openapi.vfs.VirtualFile
45 import java.net.NetworkInterface
56 import java.util.*
@@ -117,4 +118,71 @@
117118 }
118119
119120 return "$osStr-$arch"
121+}
122+
123+/**
124+ * Check if the diff is indeed a FIM (Fill-In-Middle).
125+ * @param oldEditRange Original string content.
126+ * @param newEditRange New string content.
127+ * @param cursorPosition The position of the cursor in the old string.
128+ * @return A Pair where the first value is a boolean indicating if the change is purely additive (FIM)
129+ * and the second value is the FIM text content or null if not a FIM.
130+ */
131+fun checkFim(
132+ oldEditRange: String,
133+ newEditRange: String,
134+ cursorPosition: Pair<Int, Int> // line, character
135+): FimResult {
136+ // Find the common prefix
137+ var prefixLength = 0
138+ while (prefixLength < oldEditRange.length &&
139+ prefixLength < newEditRange.length &&
140+ oldEditRange[prefixLength] == newEditRange[prefixLength]) {
141+ prefixLength++
142+ }
143+
144+ // Find the common suffix
145+ var oldSuffixPos = oldEditRange.length - 1
146+ var newSuffixPos = newEditRange.length - 1
147+
148+ while (oldSuffixPos >= prefixLength &&
149+ newSuffixPos >= prefixLength &&
150+ oldEditRange[oldSuffixPos] == newEditRange[newSuffixPos]) {
151+ oldSuffixPos--
152+ newSuffixPos--
153+ }
154+
155+ // The old text is purely preserved if:
156+ // 1. The prefix ends before or at the cursor.
157+ // 2. The suffix starts after or at the cursor.
158+ // 3. There's no gap between prefix and suffix in the old text.
159+
160+ val suffixStartInOld = oldSuffixPos + 1
161+ val suffixStartInNew = newSuffixPos + 1
162+
163+ // Convert cursor position to an offset in the string.
164+ // For simplicity, we need to calculate the cursor's position in the string.
165+ // This requires knowledge of line endings in the oldEditRange.
166+ val lines = oldEditRange.substring(0, prefixLength).split("\n")
167+ val cursorOffset = if (lines.size > 1) {
168+ lines.dropLast(1).sumOf { it.length + 1 } + cursorPosition.second
169+ } else {
170+ cursorPosition.second
171+ }
172+
173+ // Check if the cursor is positioned between the prefix and suffix.
174+ val cursorBetweenPrefixAndSuffix =
175+ prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld
176+
177+ // Check if the old text is completely preserved (no deletion).
178+ val noTextDeleted = suffixStartInOld - prefixLength <= 0
179+
180+ val isFim = cursorBetweenPrefixAndSuffix && noTextDeleted
181+
182+ return if (isFim) {
183+ // Extract the content between prefix and suffix in the new string.
184+ FimResult.FimEdit(newEditRange.substring(prefixLength, suffixStartInNew))
185+ } else {
186+ FimResult.NotFimEdit
187+ }
120188 }
No newline at the end of the file
modified extensions/intellij/src/main/resources/META-INF/plugin.xml +7 −0
@@ -176,6 +176,13 @@
176176 <keyboard-shortcut keymap="Mac OS X" first-keystroke="TAB"/>
177177 </action>
178178
179+ <action id="com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction"
180+ class="com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction"
181+ text="Accept Autocomplete Suggestion" description="Accept Next Edit Prediction">
182+ <keyboard-shortcut keymap="$default" first-keystroke="TAB"/>
183+ <keyboard-shortcut keymap="Mac OS X" first-keystroke="TAB"/>
184+ </action>
185+
179186 <action id="com.github.continuedev.continueintellijextension.autocomplete.CancelAutocompleteAction"
180187 class="com.github.continuedev.continueintellijextension.autocomplete.CancelAutocompleteAction"
181188 text="Cancel Autocomplete Suggestion" description="Cancel Autocomplete Suggestion">
modified extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt +5 −1
@@ -28,11 +28,15 @@
2828
2929 @BeforeEach
3030 fun waitForIde(remoteRobot: RemoteRobot) {
31+ System.setProperty("continue.autocomplete.test.environment", "true")
3132 waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
3233 }
3334
3435 @AfterEach
35- fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
36+ fun closeProject(remoteRobot: RemoteRobot) {
37+ System.clearProperty("continue.autocomplete.test.environment")
38+ CommonSteps(remoteRobot).closeProject()
39+ }
3640
3741 @Test
3842 @Video
added extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/CheckFimTest.kt +51 −0
@@ -0,0 +1,51 @@
1+package com.github.continuedev.continueintellijextension.unit
2+
3+import com.github.continuedev.continueintellijextension.FimResult
4+import com.github.continuedev.continueintellijextension.`continue`.UriUtils
5+import com.github.continuedev.continueintellijextension.utils.checkFim
6+import org.junit.jupiter.api.Disabled
7+import org.junit.jupiter.api.Test
8+import java.io.File
9+import kotlin.test.assertEquals
10+
11+class CheckFimTest {
12+ @Test
13+ fun testFim() {
14+ val oldEditRange = "hello world"
15+ val newEditRange = "hello this world"
16+ val cursorPosition = Pair(0, 6)
17+ assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("this "))
18+ }
19+
20+ @Test
21+ fun testMultilineFim() {
22+ val oldEditRange = "hello {\n world\n}"
23+ val newEditRange = "hello {\n print()\n world\n}"
24+ val cursorPosition = Pair(1, 2)
25+ assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("print()\n "))
26+ }
27+
28+ @Test
29+ fun testNotFim() {
30+ val oldEditRange = "hello world"
31+ val newEditRange = "hello this world"
32+ val cursorPosition = Pair(0, 8)
33+ assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
34+ }
35+
36+ @Test
37+ fun testMultilineNotFim() {
38+ val oldEditRange = "hello {\n world\n}"
39+ val newEditRange = "hello {\n world\n}\nprint()"
40+ val cursorPosition = Pair(1, 2)
41+ assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
42+ }
43+
44+ @Test
45+ fun testFimEdge() {
46+ val oldEditRange = ""
47+ val newEditRange = ""
48+ val cursorPosition = Pair(0, 0)
49+ assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit(""))
50+ }
51+}
deleted extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueProcessHandlerTest.kt +0 −51
@@ -1,51 +0,0 @@
1-package com.github.continuedev.continueintellijextension.unit
2-
3-import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcess
4-import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
5-import kotlinx.coroutines.Dispatchers
6-import kotlinx.coroutines.joinAll
7-import kotlinx.coroutines.launch
8-import kotlinx.coroutines.test.runTest
9-import org.junit.jupiter.api.Assertions
10-import org.junit.jupiter.api.RepeatedTest
11-import java.io.InputStream
12-import java.io.OutputStream
13-
14-class ContinueProcessHandlerTest {
15-
16- @RepeatedTest(5)
17- fun `test concurrent writes with queue`() = runTest {
18- val process = StringContinueProcess()
19- val handler = ContinueProcessHandler(this, process) {}
20-
21- (0..100).map { i -> launch(Dispatchers.Default) { handler.write("message number $i") } }
22- .joinAll()
23-
24- handler.close()
25-
26- // assert all message lines are present (order is not important)
27- val lines = process.string.split("\r\n").filter { it.isNotBlank() }
28- for (i in 0..100)
29- Assertions.assertTrue(lines.contains("message number $i"))
30-
31- // note: this test will fail if the handler writes messages directly to the output stream
32- // this problem can be easily reproduced by removing the channel<string> from the handler code
33- }
34-
35- class StringContinueProcess : ContinueProcess {
36- val string = StringBuilder()
37- override val input: InputStream = InputStream.nullInputStream()
38- override val output: OutputStream = object : OutputStream() {
39- override fun write(b: Int) {
40- string.append(b.toChar())
41- }
42-
43- override fun write(b: ByteArray, off: Int, len: Int) {
44- string.append(String(b, off, len))
45- }
46- }
47-
48- override fun close() {
49- }
50- }
51-}
modified extensions/vscode/README.md +13 −11
@@ -26,29 +26,31 @@
2626
2727 <p></p>
2828
29+## Agent
30+
31+[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
32+
33+![agent](../../docs/images/agent.gif)
34+
2935 ## Chat
3036
31-[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave the IDE
37+[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
38+the IDE
3239
33-![chat](docs/static/img/chat.gif)
40+![chat](../../docs/images/chat.gif)
3441
3542 ## Autocomplete
3643
3744 [Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
3845
39-![autocomplete](docs/static/img/autocomplete.gif)
46+![autocomplete](../../docs/images/autocomplete.gif)
4047
4148 ## Edit
4249
43-[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current file
44-
45-![edit](docs/static/img/edit.gif)
46-
47-## Agent
48-
49-[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
50+[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
51+file
5052
51-![agent](docs/static/img/agent.gif)
53+![edit](../../docs/images/edit.gif)
5254
5355 </div>
5456
modified extensions/vscode/e2e/README.md +1 −1
@@ -38,4 +38,4 @@
3838
3939 ### Quirks
4040
41-- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`.
No newline at the end of the file
41+- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`.
modified extensions/vscode/e2e/TestUtils.ts +7 −3
@@ -1,15 +1,19 @@
11 import { expect } from "chai";
22 import { Key } from "vscode-extension-tester";
33
4-import { access, constants } from 'fs/promises';
4+import { access, constants } from "fs/promises";
55 import * as path from "path";
66 import { DEFAULT_TIMEOUT } from "./constants";
77
88 export class TestUtils {
99 public static CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? "";
10-
10+
1111 public static getGlobalContextFilePath(): string {
12- return path.join(TestUtils.CONTINUE_GLOBAL_DIR, "index", "globalContext.json");
12+ return path.join(
13+ TestUtils.CONTINUE_GLOBAL_DIR,
14+ "index",
15+ "globalContext.json",
16+ );
1317 }
1418
1519 public static async fileExists(path: string): Promise<boolean> {
modified extensions/vscode/e2e/actions/NextEdit.actions.ts +11 −9
@@ -12,12 +12,14 @@
1212 public static async acceptNextEditSuggestion(editor: TextEditor) {
1313 const hasDecoration = await NextEditActions.forceNextEdit(editor);
1414 expect(hasDecoration).to.be.true;
15-
16- await new Workbench().executeCommand("Continue: Accept Next Edit Suggestion");
15+
16+ await new Workbench().executeCommand(
17+ "Continue: Accept Next Edit Suggestion",
18+ );
1719
1820 // Check if HELLO is written into the editor.
1921 const editorText = await editor.getTextAtLine(1);
20-
22+
2123 return editorText === "HELLO";
2224 }
2325
@@ -27,12 +29,12 @@
2729 public static async rejectNextEditSuggestion(editor: TextEditor) {
2830 const hasDecoration = await NextEditActions.forceNextEdit(editor);
2931 expect(hasDecoration).to.be.true;
30-
32+
3133 await new Workbench().executeCommand("Continue: Hide Next Edit Suggestion");
3234
3335 // Check if the editor text didn't change.
3436 const editorText = await editor.getText();
35-
37+
3638 return editorText === "def main():\n ";
3739 }
3840
@@ -45,16 +47,16 @@
4547
4648 await new Workbench().executeCommand("Continue: Force Next Edit");
4749 await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XL);
48-
50+
4951 const svgDecoration = await TestUtils.waitForSuccess(
5052 () => NextEditSelectors.getSvgDecoration(VSBrowser.instance.driver),
51- DEFAULT_TIMEOUT.XL
53+ DEFAULT_TIMEOUT.XL,
5254 );
53-
55+
5456 return svgDecoration !== null;
5557 }
5658
5759 public static async reload(): Promise<void> {
58- await new Workbench().executeCommand('workbench.action.reloadWindow');
60+ await new Workbench().executeCommand("workbench.action.reloadWindow");
5961 }
6062 }
modified extensions/vscode/e2e/selectors/GUI.selectors.ts +1 −4
@@ -100,10 +100,7 @@
100100 }
101101
102102 public static getNthMessageDeleteButton(view: WebView, index: number) {
103- return SelectorUtils.getElementByDataTestId(
104- view,
105- `delete-button-${index}`,
106- );
103+ return SelectorUtils.getElementByDataTestId(view, `delete-button-${index}`);
107104 }
108105
109106 public static getModelDropdownOption(view: WebView, option: string) {
modified extensions/vscode/e2e/selectors/NextEdit.selectors.ts +2 −2
@@ -8,7 +8,7 @@
88 try {
99 const decorations = await driver.findElement(
1010 // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]")
11- By.css("[class*='TextEditorDecorationType']")
11+ By.css("[class*='TextEditorDecorationType']"),
1212 );
1313 return decorations ?? null;
1414 } catch (error) {
@@ -16,4 +16,4 @@
1616 return null;
1717 }
1818 }
19-}
No newline at the end of the file
19+}
modified extensions/vscode/e2e/tests/GUI.test.ts +1 −1
@@ -584,4 +584,4 @@
584584 );
585585 }).timeout(DEFAULT_TIMEOUT.XL);
586586 });
587-});
No newline at the end of the file
587+});
modified extensions/vscode/e2e/tests/NextEdit.test.ts +47 −37
@@ -7,55 +7,59 @@
77 import { DEFAULT_TIMEOUT } from "../constants";
88 import { TestUtils } from "../TestUtils";
99
10-describe("Next Edit", () => {
10+describe("Next Edit", () => {
1111 let editor: TextEditor;
1212
1313 before(async function () {
1414 // this.timeout(DEFAULT_TIMEOUT.XL);
1515
1616 const globalContextPath = TestUtils.getGlobalContextFilePath();
17-
17+
1818 // Update config.json to add optInNextEditFeature.
1919 // globalContext.json does not exist in CI before this test runs.
2020 if (await TestUtils.fileExists(globalContextPath)) {
2121 const globalContext = await fs.readFile(globalContextPath, "utf8");
2222 const sharedConfig = JSON.parse(globalContext).sharedConfig;
23-
23+
2424 const sharedConfigWithNextEditEnabled = {
2525 ...sharedConfig,
26- "optInNextEditFeature": true
26+ optInNextEditFeature: true,
2727 };
28-
28+
2929 const globalContextWithNextEditEnabled = {
3030 ...JSON.parse(globalContext),
31- "sharedConfig": sharedConfigWithNextEditEnabled
31+ sharedConfig: sharedConfigWithNextEditEnabled,
3232 };
33-
34- await fs.writeFile(globalContextPath, JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8");
33+
34+ await fs.writeFile(
35+ globalContextPath,
36+ JSON.stringify(globalContextWithNextEditEnabled, null, 2),
37+ "utf8",
38+ );
3539 } else {
3640 await fs.writeFile(
37- globalContextPath,
38- JSON.stringify(
39- {
40- sharedConfig: {
41- optInNextEditFeature: true
42- },
43- selectedModelsByProfileId: {
44- local: {
45- chat: "TEST LLM",
46- edit: "TEST LLM",
47- apply: "TEST LLM",
48- embed: "Transformers.js (Built-In)",
49- autocomplete: "TEST LLM",
50- rerank: null,
51- summarize: null
52- }
53- }
54- },
55- null,
56- 2,
57- ),
58- );
41+ globalContextPath,
42+ JSON.stringify(
43+ {
44+ sharedConfig: {
45+ optInNextEditFeature: true,
46+ },
47+ selectedModelsByProfileId: {
48+ local: {
49+ chat: "TEST LLM",
50+ edit: "TEST LLM",
51+ apply: "TEST LLM",
52+ embed: "Transformers.js (Built-In)",
53+ autocomplete: "TEST LLM",
54+ rerank: null,
55+ summarize: null,
56+ },
57+ },
58+ },
59+ null,
60+ 2,
61+ ),
62+ );
5963 }
6064
6165 await NextEditActions.reload();
@@ -77,20 +81,27 @@
7781
7882 after(async function () {
7983 // this.timeout(DEFAULT_TIMEOUT.XL);
80-
84+
8185 // Update config.json to delete optInNextEditFeature.
82- const globalContext = await fs.readFile(TestUtils.getGlobalContextFilePath(), "utf8");
86+ const globalContext = await fs.readFile(
87+ TestUtils.getGlobalContextFilePath(),
88+ "utf8",
89+ );
8390 const sharedConfig = JSON.parse(globalContext).sharedConfig;
84-
91+
8592 const sharedConfigWithoutNextEdit = { ...sharedConfig };
8693 delete sharedConfigWithoutNextEdit.optInNextEditFeature;
8794
8895 const globalContextWithNextEditEnabled = {
8996 ...JSON.parse(globalContext),
90- "sharedConfig": sharedConfigWithoutNextEdit
97+ sharedConfig: sharedConfigWithoutNextEdit,
9198 };
9299
93- await fs.writeFile(TestUtils.getGlobalContextFilePath(), JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8");
100+ await fs.writeFile(
101+ TestUtils.getGlobalContextFilePath(),
102+ JSON.stringify(globalContextWithNextEditEnabled, null, 2),
103+ "utf8",
104+ );
94105 await NextEditActions.reload();
95106 }).timeout(DEFAULT_TIMEOUT.XL);
96107
@@ -116,5 +127,4 @@
116127 const rejected = await NextEditActions.rejectNextEditSuggestion(editor);
117128 expect(rejected).to.be.true;
118129 }).timeout(DEFAULT_TIMEOUT.XXL);
119-
120-});
No newline at the end of the file
130+});
modified extensions/vscode/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/package.json +1 −1
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.63",
5+ "version": "1.1.66",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
modified extensions/vscode/src/ContinueGUIWebviewViewProvider.ts +1 −8
@@ -1,4 +1,3 @@
1-import { ConfigHandler } from "core/config/ConfigHandler";
21 import * as vscode from "vscode";
32
43 import { getTheme } from "./util/getTheme";
@@ -59,16 +58,10 @@
5958 }
6059
6160 constructor(
62- private readonly configHandlerPromise: Promise<ConfigHandler>,
6361 private readonly windowId: string,
6462 private readonly extensionContext: vscode.ExtensionContext,
6563 ) {
66- this.webviewProtocol = new VsCodeWebviewProtocol(
67- (async () => {
68- const configHandler = await this.configHandlerPromise;
69- return configHandler.reloadConfig();
70- }).bind(this),
71- );
64+ this.webviewProtocol = new VsCodeWebviewProtocol();
7265 }
7366
7467 getSidebarContent(
modified extensions/vscode/src/VsCodeIde.ts +3 −3
@@ -27,6 +27,7 @@
2727 TerminalOptions,
2828 Thread,
2929 } from "core";
30+import { getExtensionVersion, isExtensionPrerelease } from "./util/util";
3031
3132 class VsCodeIde implements IDE {
3233 ideUtils: VsCodeIdeUtils;
@@ -153,9 +154,8 @@
153154 name: vscode.env.appName,
154155 version: vscode.version,
155156 remoteName: vscode.env.remoteName || "local",
156- extensionVersion:
157- vscode.extensions.getExtension("continue.continue")?.packageJSON
158- .version,
157+ extensionVersion: getExtensionVersion(),
158+ isPrerelease: isExtensionPrerelease(),
159159 });
160160 }
161161
modified extensions/vscode/src/extension/VsCodeExtension.ts +12 −7
@@ -100,7 +100,6 @@
100100 resolveConfigHandler = resolve;
101101 });
102102 this.sidebar = new ContinueGUIWebviewViewProvider(
103- configHandlerPromise,
104103 this.windowId,
105104 this.extensionContext,
106105 );
@@ -147,8 +146,10 @@
147146 );
148147 resolveVerticalDiffManager?.(this.verticalDiffManager);
149148
150- void setupRemoteConfigSync(
151- this.configHandler.reloadConfig.bind(this.configHandler),
149+ void setupRemoteConfigSync(() =>
150+ this.configHandler.reloadConfig.bind(this.configHandler)(
151+ "Remote config sync",
152+ ),
152153 );
153154
154155 void this.configHandler.loadConfig().then(({ config }) => {
@@ -284,7 +285,9 @@
284285 if (stats.size === 0) {
285286 return;
286287 }
287- await this.configHandler.reloadConfig();
288+ await this.configHandler.reloadConfig(
289+ "Global JSON config updated - fs file watch",
290+ );
288291 });
289292
290293 fs.watchFile(
@@ -294,7 +297,9 @@
294297 if (stats.size === 0) {
295298 return;
296299 }
297- await this.configHandler.reloadConfig();
300+ await this.configHandler.reloadConfig(
301+ "Global YAML config updated - fs file watch",
302+ );
298303 },
299304 );
300305
@@ -302,7 +307,7 @@
302307 if (stats.size === 0) {
303308 return;
304309 }
305- void this.configHandler.reloadConfig();
310+ void this.configHandler.reloadConfig("config.ts updated - fs file watch");
306311 });
307312
308313 vscode.workspace.onDidChangeTextDocument(async (event) => {
@@ -363,7 +368,7 @@
363368 );
364369
365370 if (e.provider.id === "github") {
366- this.configHandler.reloadConfig();
371+ this.configHandler.reloadConfig("Github sign-in status changed");
367372 }
368373 }
369374 });
modified extensions/vscode/src/stubs/WorkOsAuthProvider.ts +15 −1
@@ -8,6 +8,7 @@
88 } from "core/control-plane/AuthTypes";
99 import { getControlPlaneEnvSync } from "core/control-plane/env";
1010 import fetch from "node-fetch";
11+import { EventEmitter as NodeEventEmitter } from "node:events";
1112 import { v4 as uuidv4 } from "uuid";
1213 import {
1314 authentication,
@@ -101,6 +102,10 @@
101102 this.secretStorage = new SecretStorage(context);
102103
103104 // Immediately refresh any existing sessions
105+ this.attemptEmitter = new NodeEventEmitter();
106+ WorkOsAuthProvider.hasAttemptedRefresh = new Promise((resolve) => {
107+ this.attemptEmitter.on("attempted", resolve);
108+ });
104109 void this.refreshSessions();
105110
106111 // Set up a regular interval to refresh tokens
@@ -147,6 +152,7 @@
147152 public async getSessions(
148153 scopes?: string[],
149154 ): Promise<ContinueAuthenticationSession[]> {
155+ // await this.hasAttemptedRefresh;
150156 const data = await this.secretStorage.get(SESSIONS_SECRET_KEY);
151157 if (!data) {
152158 return [];
@@ -182,6 +188,8 @@
182188 return this.ideRedirectUri;
183189 }
184190
191+ public static hasAttemptedRefresh: Promise<void>;
192+ private attemptEmitter: NodeEventEmitter;
185193 async refreshSessions() {
186194 // Prevent concurrent refresh operations
187195 if (this._isRefreshing) {
@@ -198,9 +206,12 @@
198206 }
199207 }
200208
209+ // It is important that every path in this function emits the attempted event
210+ // As config loading in core will be locked until refresh is attempted
201211 private async _refreshSessions(): Promise<void> {
202212 const sessions = await this.getSessions();
203213 if (!sessions.length) {
214+ this.attemptEmitter.emit("attempted");
204215 return;
205216 }
206217
@@ -247,6 +258,7 @@
247258 try {
248259 return await this._refreshSession(refreshToken);
249260 } catch (error: any) {
261+ this.attemptEmitter.emit("attempted");
250262 // Don't retry for auth errors
251263 if (
252264 error.message?.includes("401") ||
@@ -270,6 +282,8 @@
270282 .catch(reject);
271283 }, delay);
272284 });
285+ } finally {
286+ this.attemptEmitter.emit("attempted");
273287 }
274288 }
275289
@@ -553,7 +567,7 @@
553567 if (useOnboarding) {
554568 WorkOsAuthProvider.useOnboardingUri = true;
555569 }
556-
570+ await WorkOsAuthProvider.hasAttemptedRefresh;
557571 const session = await authentication.getSession(
558572 controlPlaneEnv.AUTH_TYPE,
559573 [],
modified extensions/vscode/src/util/editLoggingUtils.ts +1 −1
@@ -61,7 +61,7 @@
6161 const editor = vscode.window.activeTextEditor;
6262 const { config } = await configHandler.loadConfig();
6363
64- if (!config?.experimental?.logEditingData) return;
64+ // if (!config?.experimental?.logEditingData) return;
6565 if (!editor) return;
6666 if (event.contentChanges.length === 0) return;
6767
modified extensions/vscode/src/util/util.ts +12 −0
@@ -126,3 +126,15 @@
126126 export function getvsCodeUriScheme(): string {
127127 return vscode.env.uriScheme;
128128 }
129+
130+export function isExtensionPrerelease(): boolean {
131+ const extensionVersion = getExtensionVersion();
132+ const versionParts = extensionVersion.split(".");
133+ if (versionParts.length >= 2) {
134+ const minorVersion = parseInt(versionParts[1], 10);
135+ if (!isNaN(minorVersion)) {
136+ return minorVersion % 2 !== 0;
137+ }
138+ }
139+ return false;
140+}
added extensions/vscode/src/util/util.vitest.ts +26 −0
@@ -0,0 +1,26 @@
1+import { expect, test, vi } from "vitest";
2+import * as vscode from "vscode";
3+
4+// Mock the vscode module
5+vi.mock("vscode", () => ({
6+ extensions: {
7+ getExtension: vi.fn(),
8+ },
9+}));
10+
11+// Import the function after mocking
12+import { isExtensionPrerelease } from "./util";
13+
14+test("isExtensionPrerelease detects prerelease versions correctly", () => {
15+ // 1.0.0 is not prerelease (even minor version)
16+ vi.mocked(vscode.extensions.getExtension).mockReturnValue({
17+ packageJSON: { version: "1.0.0" },
18+ } as any);
19+ expect(isExtensionPrerelease()).toBe(false);
20+
21+ // 1.1.0 is prerelease (odd minor version)
22+ vi.mocked(vscode.extensions.getExtension).mockReturnValue({
23+ packageJSON: { version: "1.1.0" },
24+ } as any);
25+ expect(isExtensionPrerelease()).toBe(true);
26+});
modified extensions/vscode/src/webviewProtocol.ts +1 −1
@@ -152,7 +152,7 @@
152152 this._webviewListener = this._webview.onDidReceiveMessage(handleMessage);
153153 }
154154
155- constructor(private readonly reloadConfig: () => void) {}
155+ constructor() {}
156156
157157 invoke<T extends keyof FromWebviewProtocol>(
158158 messageType: T,
modified gui/src/components/AssistantAndOrgListbox/index.tsx +2 −6
@@ -161,18 +161,14 @@
161161 </ListboxOption>
162162
163163 <ListboxOption
164- value="new-assistant"
164+ value="reload-assistant"
165165 fontSizeModifier={-2}
166166 className="border-border border-b px-2 py-1.5"
167- onClick={session ? onNewAssistant : () => login(false)}
167+ onClick={() => refreshProfiles()}
168168 >
169169 <span
170170 className="text-description flex flex-row items-center"
171171 style={{ fontSize: tinyFont }}
172- onClick={async (e) => {
173- e.stopPropagation();
174- await refreshProfiles();
175- }}
176172 >
177173 <ArrowPathIcon
178174 className={cn(
modified gui/src/components/Layout.tsx +1 −0
@@ -47,6 +47,7 @@
4747 const dispatch = useAppDispatch();
4848 const onboardingCard = useOnboardingCard();
4949 const ideMessenger = useContext(IdeMessengerContext);
50+ const currentSessionId = useAppSelector((state) => state.session.id);
5051
5152 const { mainEditor } = useMainEditor();
5253 const dialogMessage = useAppSelector((state) => state.ui.dialogMessage);
added gui/src/components/StepContainer/ConversationSummary.tsx +68 −0
@@ -0,0 +1,68 @@
1+import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
2+import { ChatHistoryItem } from "core";
3+import { useState } from "react";
4+import { AnimatedEllipsis } from "../";
5+import { useAppSelector } from "../../redux/hooks";
6+import StyledMarkdownPreview from "../StyledMarkdownPreview";
7+
8+interface ConversationSummaryProps {
9+ item: ChatHistoryItem;
10+ index: number;
11+}
12+
13+export default function ConversationSummary(props: ConversationSummaryProps) {
14+ const [open, setOpen] = useState(false);
15+ const isLoading = useAppSelector(
16+ (state) => state.session.compactionLoading[props.index] || false,
17+ );
18+
19+ if (!props.item.conversationSummary && !isLoading) {
20+ return null;
21+ }
22+
23+ // Loading state - much simpler
24+ if (isLoading) {
25+ return (
26+ <div className="mx-1.5 mb-4 mt-2">
27+ <div className="bg-vsc-input-background rounded-md shadow-sm">
28+ <div className="text-description flex items-center justify-start px-3 py-2 text-xs">
29+ <span>Generating conversation summary</span>
30+ <AnimatedEllipsis />
31+ </div>
32+ </div>
33+ </div>
34+ );
35+ }
36+
37+ // Normal state with content
38+ return (
39+ <div className="mx-1.5 mb-4 mt-2">
40+ <div className="bg-vsc-input-background rounded-md shadow-sm">
41+ <div
42+ className="text-description flex cursor-pointer items-center gap-2 px-3 py-2 text-xs transition-colors duration-200 hover:brightness-105"
43+ onClick={() => setOpen(!open)}
44+ >
45+ {open ? (
46+ <ChevronUpIcon className="h-3 w-3" />
47+ ) : (
48+ <ChevronDownIcon className="h-3 w-3" />
49+ )}
50+ <span>Conversation Summary</span>
51+ </div>
52+ {open && (
53+ <>
54+ <div className="border-border border-0 border-t border-solid"></div>
55+ <div className="max-h-[400px] overflow-y-auto px-3 pb-3 pt-2">
56+ <StyledMarkdownPreview
57+ isRenderingInStepContainer
58+ source={props.item.conversationSummary}
59+ itemIndex={props.index}
60+ useParentBackgroundColor
61+ />
62+ </div>
63+ </>
64+ )}
65+ </div>
66+ </div>
67+ );
68+}
modified gui/src/components/StepContainer/ResponseActions.tsx +53 −15
@@ -1,16 +1,19 @@
11 import {
2+ ArrowsPointingInIcon,
23 BarsArrowDownIcon,
3- PlusIcon,
4+ PencilSquareIcon,
45 TrashIcon,
56 } from "@heroicons/react/24/outline";
67 import { ChatHistoryItem } from "core";
78 import { modelSupportsTools } from "core/llm/autodetect";
89 import { renderChatMessage } from "core/util/messageContent";
9-import { useMemo } from "react";
10-import { useDispatch } from "react-redux";
11-import { useAppSelector } from "../../redux/hooks";
10+import { useContext, useMemo } from "react";
11+import { IdeMessengerContext } from "../../context/IdeMessenger";
12+import { useAppDispatch, useAppSelector } from "../../redux/hooks";
1213 import { selectSelectedChatModel } from "../../redux/slices/configSlice";
14+import { setCompactionLoading } from "../../redux/slices/sessionSlice";
1315 import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
16+import { loadSession } from "../../redux/thunks/session";
1417 import { FeedbackButtons } from "../FeedbackButtons";
1518 import { GenerateRuleDialog } from "../GenerateRuleDialog";
1619 import { CopyIconButton } from "../gui/CopyIconButton";
@@ -33,7 +36,9 @@
3336 onDelete,
3437 isLast,
3538 }: ResponseActionsProps) {
36- const dispatch = useDispatch();
39+ const dispatch = useAppDispatch();
40+ const ideMessenger = useContext(IdeMessengerContext);
41+ const currentSessionId = useAppSelector((state) => state.session.id);
3742 const selectedModel = useAppSelector(selectSelectedChatModel);
3843 const ruleGenerationSupported = useMemo(() => {
3944 return selectedModel && modelSupportsTools(selectedModel);
@@ -44,21 +49,45 @@
4449 dispatch(setDialogMessage(<GenerateRuleDialog />));
4550 };
4651
52+ const onCompactConversation = async () => {
53+ if (!currentSessionId) {
54+ return;
55+ }
56+
57+ try {
58+ // Set loading state
59+ dispatch(setCompactionLoading({ index, loading: true }));
60+
61+ await ideMessenger.request("conversation/compact", {
62+ index,
63+ sessionId: currentSessionId,
64+ });
65+
66+ // Reload the current session to refresh the conversation state
67+ dispatch(
68+ loadSession({
69+ sessionId: currentSessionId,
70+ saveCurrentSession: false,
71+ }),
72+ );
73+ } catch (error) {
74+ console.error("Error compacting conversation:", error);
75+ } finally {
76+ // Clear loading state
77+ dispatch(setCompactionLoading({ index, loading: false }));
78+ }
79+ };
80+
4781 return (
4882 <div className="text-description-muted mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs">
4983 {isLast && ruleGenerationSupported && (
50- <div
51- className="mr-1 border-y-0 border-l-0 border-r border-solid pr-2"
84+ <HeaderButtonWithToolTip
85+ tabIndex={-1}
86+ text="Generate rule"
5287 onClick={onGenerateRule}
5388 >
54- <span className="flex cursor-pointer items-center hover:brightness-125">
55- <PlusIcon className="mr-1 h-3 w-3" />
56- <span className="xs:block hidden whitespace-nowrap">
57- Generate rule
58- </span>
59- <span className="xs:hidden block whitespace-nowrap">Rule</span>
60- </span>
61- </div>
89+ <PencilSquareIcon className="text-description-muted h-3.5 w-3.5" />
90+ </HeaderButtonWithToolTip>
6291 )}
6392
6493 {isTruncated && (
@@ -71,6 +100,15 @@
71100 </HeaderButtonWithToolTip>
72101 )}
73102
103+ <HeaderButtonWithToolTip
104+ testId={`compact-button-${index}`}
105+ text="Compact conversation"
106+ tabIndex={-1}
107+ onClick={onCompactConversation}
108+ >
109+ <ArrowsPointingInIcon className="text-description-muted h-3.5 w-3.5" />
110+ </HeaderButtonWithToolTip>
111+
74112 <HeaderButtonWithToolTip
75113 testId={`delete-button-${index}`}
76114 text="Delete"
modified gui/src/components/StepContainer/StepContainer.tsx +32 −2
@@ -6,6 +6,7 @@
66 import { selectUIConfig } from "../../redux/slices/configSlice";
77 import { deleteMessage } from "../../redux/slices/sessionSlice";
88 import StyledMarkdownPreview from "../StyledMarkdownPreview";
9+import ConversationSummary from "./ConversationSummary";
910 import Reasoning from "./Reasoning";
1011 import ResponseActions from "./ResponseActions";
1112 import ThinkingIndicator from "./ThinkingIndicator";
@@ -14,6 +15,7 @@
1415 item: ChatHistoryItem;
1516 index: number;
1617 isLast: boolean;
18+ latestSummaryIndex?: number;
1719 }
1820
1921 export default function StepContainer(props: StepContainerProps) {
@@ -25,6 +27,13 @@
2527 );
2628 const uiConfig = useAppSelector(selectUIConfig);
2729
30+ // Calculate dimming and indicator state based on latest summary index
31+ const latestSummaryIndex = props.latestSummaryIndex ?? -1;
32+ const isBeforeLatestSummary =
33+ latestSummaryIndex !== -1 && props.index <= latestSummaryIndex;
34+ const isLatestSummary =
35+ latestSummaryIndex !== -1 && props.index === latestSummaryIndex;
36+
2837 const isNextMsgAssistantOrThinking =
2938 historyItemAfterThis?.message.role === "assistant" ||
3039 historyItemAfterThis?.message.role === "thinking" ||
@@ -80,7 +89,9 @@
8089
8190 return (
8291 <div>
83- <div className="bg-background overflow-hidden p-1 px-1.5">
92+ <div
93+ className={`bg-background p-1 px-1.5 ${isBeforeLatestSummary ? "opacity-35" : ""}`}
94+ >
8495 {uiConfig?.displayRawMarkdown ? (
8596 <pre className="text-2xs max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4">
8697 {renderChatMessage(props.item.message)}
@@ -98,9 +109,12 @@
98109 )}
99110 {props.isLast && <ThinkingIndicator historyItem={props.item} />}
100111 </div>
112+
101113 {shouldRenderResponseAction() && (
102114 // We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on stream complete
103- <div className={`mt-2 h-7 transition-opacity duration-300 ease-in-out`}>
115+ <div
116+ className={`mt-2 h-7 transition-opacity duration-300 ease-in-out ${isBeforeLatestSummary ? "opacity-35" : ""}`}
117+ >
104118 {!isStreaming && (
105119 <ResponseActions
106120 isTruncated={isTruncated}
@@ -113,6 +127,22 @@
113127 )}
114128 </div>
115129 )}
130+
131+ {/* Show compaction indicator for the latest summary */}
132+ {isLatestSummary && (
133+ <div className="mx-1.5 my-5">
134+ <div className="flex items-center">
135+ <div className="border-border flex-1 border-t border-solid"></div>
136+ <span className="text-description mx-3 text-xs">
137+ Previous Conversation Compacted
138+ </span>
139+ <div className="border-border flex-1 border-t border-solid"></div>
140+ </div>
141+ </div>
142+ )}
143+
144+ {/* ConversationSummary is outside the dimmed container so it's always at full opacity */}
145+ <ConversationSummary item={props.item} index={props.index} />
116146 </div>
117147 );
118148 }
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +1 −1
@@ -265,7 +265,7 @@
265265 return (
266266 <div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor mb-2 mt-2 flex min-w-0 flex-col outline outline-1">
267267 <div
268- className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "border-command-border border-b" : ""}`}
268+ className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`}
269269 style={{ fontSize: `${getFontSize() - 2}px` }}
270270 >
271271 <div className="flex max-w-[50%] flex-row items-center">
modified gui/src/components/console/Details.tsx +5 −0
@@ -117,6 +117,11 @@
117117 format={(v: number) => v.toFixed(1)}
118118 ></Cell>
119119 </div>
120+ {/* {summary.costBreakdown && (
121+ <pre className="whitespace-pre-wrap px-2 text-sm">
122+ {summary.costBreakdown.breakdown}
123+ </pre>
124+ )} */}
120125 </div>
121126 <div
122127 ref={scrollTop}
modified gui/src/components/console/Layout.tsx +42 −8
@@ -2,11 +2,13 @@
22 import useLLMLog from "../../hooks/useLLMLog";
33 import Details from "./Details";
44 import List from "./List";
5+import TotalUsage from "./TotalUsage";
56
67 export default function Layout() {
78 const llmLog = useLLMLog();
89
910 const [selectedId, setSelectedId] = useState<string | undefined>(undefined);
11+ const [showTotalUsage, setShowTotalUsage] = useState(false);
1012
1113 const interaction = selectedId
1214 ? llmLog.interactions.get(selectedId)
@@ -16,14 +18,46 @@
1618 <div>Loading...</div>
1719 ) : (
1820 <div className="flex h-full w-full">
19- <List
20- llmLog={llmLog}
21- onClickInteraction={(interactionId) => {
22- setSelectedId(interactionId);
23- }}
24- ></List>
25- {interaction && (
26- <Details key="{selectedId}" interaction={interaction}></Details>
21+ <div className="flex h-full w-full flex-col">
22+ {/* <div className="flex-shrink-0 border-b border-[color:var(--vscode-panel-border)] p-3">
23+ <button
24+ onClick={() => setShowTotalUsage(true)}
25+ className="float-right cursor-pointer border-none bg-transparent text-sm text-[color:var(--vscode-textLink-foreground)] underline hover:text-[color:var(--vscode-textLink-activeForeground)]"
26+ >
27+ View Total Usage Summary
28+ </button>
29+ </div> */}
30+ <div className="flex min-h-0 flex-1 overflow-hidden">
31+ <List
32+ llmLog={llmLog}
33+ onClickInteraction={(interactionId) => {
34+ setSelectedId(interactionId);
35+ }}
36+ ></List>
37+ {interaction && (
38+ <Details key="{selectedId}" interaction={interaction}></Details>
39+ )}
40+ </div>
41+ </div>
42+
43+ {/* Full-screen popover for TotalUsage */}
44+ {showTotalUsage && (
45+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
46+ <div className="relative h-full w-full max-w-6xl overflow-hidden bg-[color:var(--vscode-panel-background)] shadow-2xl">
47+ {/* Close button */}
48+ <button
49+ onClick={() => setShowTotalUsage(false)}
50+ className="absolute right-4 top-4 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-[color:var(--vscode-button-background)] text-[color:var(--vscode-button-foreground)] transition-colors hover:bg-[color:var(--vscode-button-hoverBackground)]"
51+ >
52+ ×
53+ </button>
54+
55+ {/* Content container with scroll */}
56+ <div className="h-full overflow-y-auto p-6">
57+ <TotalUsage llmLog={llmLog} />
58+ </div>
59+ </div>
60+ </div>
2761 )}
2862 </div>
2963 );
added gui/src/components/console/TotalUsage.tsx +362 −0
@@ -0,0 +1,362 @@
1+import { calculateRequestCost } from "core/llm/utils/calculateRequestCost";
2+import React, { useMemo, useState } from "react";
3+import { LLMLog } from "../../hooks/useLLMLog";
4+import useTotalUsage from "../../hooks/useTotalUsage";
5+
6+interface TotalUsageProps {
7+ llmLog: LLMLog;
8+}
9+
10+const StatCard: React.FC<{ label: string; value: number; color?: string }> = ({
11+ label,
12+ value,
13+ color = "var(--vscode-foreground)",
14+}) => (
15+ <div className="flex flex-col items-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3">
16+ <div className="text-sm text-[color:var(--vscode-descriptionForeground)]">
17+ {label}
18+ </div>
19+ <div className="text-lg font-semibold" style={{ color }}>
20+ {value.toLocaleString()}
21+ </div>
22+ </div>
23+);
24+
25+const CostChart: React.FC<{ llmLog: LLMLog }> = ({ llmLog }) => {
26+ const chartData = useMemo(() => {
27+ let cumulativeCost = 0;
28+ const dataPoints: { interaction: number; cost: number }[] = [];
29+
30+ llmLog.order.forEach((id, index) => {
31+ const interaction = llmLog.interactions.get(id);
32+
33+ // Calculate cost for this interaction if we have the necessary data
34+ if (
35+ interaction?.end?.usage &&
36+ interaction.start?.provider &&
37+ interaction.start?.options?.model
38+ ) {
39+ const costBreakdown = calculateRequestCost(
40+ interaction.start.provider,
41+ interaction.start.options.model,
42+ interaction.end.usage,
43+ );
44+ if (costBreakdown) {
45+ cumulativeCost += costBreakdown.cost;
46+ }
47+ }
48+
49+ dataPoints.push({ interaction: index + 1, cost: cumulativeCost });
50+ });
51+
52+ return dataPoints;
53+ }, [llmLog.order, llmLog.interactions]);
54+
55+ if (chartData.length === 0 || chartData[chartData.length - 1].cost === 0) {
56+ return null;
57+ }
58+
59+ const maxCost = Math.max(...chartData.map((d) => d.cost));
60+ const maxInteraction = chartData.length;
61+ const chartWidth = 400;
62+ const chartHeight = 200;
63+ const padding = 40;
64+
65+ const xScale = (interaction: number) =>
66+ ((interaction - 1) / (maxInteraction - 1)) * (chartWidth - 2 * padding) +
67+ padding;
68+
69+ const yScale = (cost: number) =>
70+ chartHeight - padding - (cost / maxCost) * (chartHeight - 2 * padding);
71+
72+ const pathData = chartData
73+ .map(
74+ (d, i) =>
75+ `${i === 0 ? "M" : "L"} ${xScale(d.interaction)} ${yScale(d.cost)}`,
76+ )
77+ .join(" ");
78+
79+ return (
80+ <div className="mb-4 rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-4">
81+ <h3 className="mb-3 text-sm font-semibold text-[color:var(--vscode-foreground)]">
82+ Cumulative Cost Over Interactions
83+ </h3>
84+ <div className="flex justify-center">
85+ <svg
86+ width={chartWidth}
87+ height={chartHeight}
88+ className="overflow-visible"
89+ >
90+ {/* Grid lines */}
91+ <defs>
92+ <pattern
93+ id="grid"
94+ width="20"
95+ height="20"
96+ patternUnits="userSpaceOnUse"
97+ >
98+ <path
99+ d="M 20 0 L 0 0 0 20"
100+ fill="none"
101+ stroke="var(--vscode-panel-border)"
102+ strokeWidth="0.5"
103+ opacity="0.3"
104+ />
105+ </pattern>
106+ </defs>
107+ <rect width={chartWidth} height={chartHeight} fill="url(#grid)" />
108+
109+ {/* Chart area background */}
110+ <rect
111+ x={padding}
112+ y={padding}
113+ width={chartWidth - 2 * padding}
114+ height={chartHeight - 2 * padding}
115+ fill="var(--vscode-editor-background)"
116+ stroke="var(--vscode-panel-border)"
117+ strokeWidth="1"
118+ />
119+
120+ {/* Cost line */}
121+ <path
122+ d={pathData}
123+ fill="none"
124+ stroke="var(--vscode-charts-green)"
125+ strokeWidth="2"
126+ strokeLinecap="round"
127+ />
128+
129+ {/* Data points */}
130+ {chartData.map((d, i) => (
131+ <circle
132+ key={i}
133+ cx={xScale(d.interaction)}
134+ cy={yScale(d.cost)}
135+ r="3"
136+ fill="var(--vscode-charts-green)"
137+ stroke="var(--vscode-editor-background)"
138+ strokeWidth="1"
139+ />
140+ ))}
141+
142+ {/* Y-axis labels */}
143+ {[0, 0.25, 0.5, 0.75, 1].map((ratio) => {
144+ const cost = maxCost * ratio;
145+ const y = yScale(cost);
146+ return (
147+ <g key={ratio}>
148+ <line
149+ x1={padding - 5}
150+ y1={y}
151+ x2={padding}
152+ y2={y}
153+ stroke="var(--vscode-foreground)"
154+ strokeWidth="1"
155+ />
156+ <text
157+ x={padding - 8}
158+ y={y + 4}
159+ textAnchor="end"
160+ fontSize="10"
161+ fill="var(--vscode-descriptionForeground)"
162+ >
163+ ${cost.toFixed(4)}
164+ </text>
165+ </g>
166+ );
167+ })}
168+
169+ {/* X-axis labels */}
170+ {[0, 0.25, 0.5, 0.75, 1].map((ratio) => {
171+ const interaction = Math.round(1 + ratio * (maxInteraction - 1));
172+ const x = xScale(interaction);
173+ return (
174+ <g key={ratio}>
175+ <line
176+ x1={x}
177+ y1={chartHeight - padding}
178+ x2={x}
179+ y2={chartHeight - padding + 5}
180+ stroke="var(--vscode-foreground)"
181+ strokeWidth="1"
182+ />
183+ <text
184+ x={x}
185+ y={chartHeight - padding + 18}
186+ textAnchor="middle"
187+ fontSize="10"
188+ fill="var(--vscode-descriptionForeground)"
189+ >
190+ {interaction}
191+ </text>
192+ </g>
193+ );
194+ })}
195+
196+ {/* Axis labels */}
197+ <text
198+ x={chartWidth / 2}
199+ y={chartHeight - 5}
200+ textAnchor="middle"
201+ fontSize="12"
202+ fill="var(--vscode-foreground)"
203+ >
204+ Interaction Number
205+ </text>
206+ <text
207+ x={15}
208+ y={chartHeight / 2}
209+ textAnchor="middle"
210+ fontSize="12"
211+ fill="var(--vscode-foreground)"
212+ transform={`rotate(-90 15 ${chartHeight / 2})`}
213+ >
214+ Cumulative Cost ($)
215+ </text>
216+ </svg>
217+ </div>
218+ </div>
219+ );
220+};
221+
222+const TotalUsage: React.FC<TotalUsageProps> = ({ llmLog }) => {
223+ const totalUsage = useTotalUsage(llmLog);
224+ const [showCostBreakdown, setShowCostBreakdown] = useState(false);
225+
226+ return (
227+ <div className="border-b border-[color:var(--vscode-panel-border)] p-4">
228+ <div className="mb-4 flex items-center justify-between">
229+ <h2 className="text-lg font-semibold text-[color:var(--vscode-foreground)]">
230+ Total Usage Summary
231+ </h2>
232+ <div className="flex items-center gap-4">
233+ {totalUsage.totalCost > 0 && (
234+ <button
235+ onClick={() => setShowCostBreakdown(!showCostBreakdown)}
236+ className="cursor-pointer text-lg font-semibold text-[color:var(--vscode-charts-green)] hover:text-[color:var(--vscode-charts-blue)]"
237+ >
238+ ${totalUsage.totalCost.toFixed(6)}
239+ </button>
240+ )}
241+ <div className="text-sm text-[color:var(--vscode-descriptionForeground)]">
242+ {totalUsage.totalInteractions} interactions
243+ </div>
244+ </div>
245+ </div>
246+
247+ {showCostBreakdown && totalUsage.costBreakdowns.length > 0 && (
248+ <div className="mb-4 max-h-32 overflow-y-auto rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3">
249+ <h3 className="mb-2 text-sm font-semibold text-[color:var(--vscode-foreground)]">
250+ Cost Breakdown
251+ </h3>
252+ <div className="space-y-2 text-xs">
253+ {totalUsage.costBreakdowns.map((breakdown, index) => (
254+ <div
255+ key={index}
256+ className="border-b border-[color:var(--vscode-panel-border)] pb-2 last:border-b-0"
257+ >
258+ <pre className="whitespace-pre-wrap text-[color:var(--vscode-descriptionForeground)]">
259+ {breakdown.breakdown}
260+ </pre>
261+ </div>
262+ ))}
263+ </div>
264+ </div>
265+ )}
266+
267+ <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4">
268+ <StatCard
269+ label="Input Tokens"
270+ value={totalUsage.totalPromptTokens}
271+ color="var(--vscode-charts-blue)"
272+ />
273+ <StatCard
274+ label="Output Tokens"
275+ value={totalUsage.totalGeneratedTokens}
276+ color="var(--vscode-charts-green)"
277+ />
278+ <StatCard
279+ label="Thinking Tokens"
280+ value={totalUsage.totalThinkingTokens}
281+ color="var(--vscode-charts-purple)"
282+ />
283+ <StatCard
284+ label="Cache Read"
285+ value={totalUsage.totalCachedTokens}
286+ color="var(--vscode-charts-orange)"
287+ />
288+ </div>
289+
290+ {totalUsage.totalCost > 0 && (
291+ <>
292+ <CostChart llmLog={llmLog} />
293+ <div className="mb-4">
294+ <div className="flex flex-col items-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3">
295+ <div className="text-sm text-[color:var(--vscode-descriptionForeground)]">
296+ Total Cost
297+ </div>
298+ <div className="text-2xl font-bold text-[color:var(--vscode-charts-green)]">
299+ ${totalUsage.totalCost.toFixed(6)}
300+ </div>
301+ <div className="text-xs text-[color:var(--vscode-descriptionForeground)]">
302+ {totalUsage.costBreakdowns.length} cost calculations
303+ </div>
304+ </div>
305+ </div>
306+ </>
307+ )}
308+
309+ {totalUsage.totalCacheWriteTokens > 0 && (
310+ <div className="mb-4 grid grid-cols-1 gap-3 md:grid-cols-2">
311+ <StatCard
312+ label="Cache Write"
313+ value={totalUsage.totalCacheWriteTokens}
314+ color="var(--vscode-charts-red)"
315+ />
316+ <div className="flex items-center justify-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3">
317+ <div className="text-sm text-[color:var(--vscode-descriptionForeground)]">
318+ Cache Hit Rate:{" "}
319+ {totalUsage.totalPromptTokens > 0
320+ ? (
321+ (totalUsage.totalCachedTokens /
322+ totalUsage.totalPromptTokens) *
323+ 100
324+ ).toFixed(1)
325+ : "0"}
326+ %
327+ </div>
328+ </div>
329+ </div>
330+ )}
331+
332+ <div className="grid grid-cols-3 gap-3 text-sm">
333+ <div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center">
334+ <div className="text-[color:var(--vscode-charts-green)]">
335+ {totalUsage.totalSuccessfulInteractions}
336+ </div>
337+ <div className="text-[color:var(--vscode-descriptionForeground)]">
338+ Success
339+ </div>
340+ </div>
341+ <div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center">
342+ <div className="text-[color:var(--vscode-charts-red)]">
343+ {totalUsage.totalErrorInteractions}
344+ </div>
345+ <div className="text-[color:var(--vscode-descriptionForeground)]">
346+ Error
347+ </div>
348+ </div>
349+ <div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center">
350+ <div className="text-[color:var(--vscode-charts-yellow)]">
351+ {totalUsage.totalCancelledInteractions}
352+ </div>
353+ <div className="text-[color:var(--vscode-descriptionForeground)]">
354+ Cancelled
355+ </div>
356+ </div>
357+ </div>
358+ </div>
359+ );
360+};
361+
362+export default TotalUsage;
modified gui/src/components/gui/Switch.tsx +9 −9
@@ -26,7 +26,7 @@
2626 <div className="flex flex-row items-center gap-1">
2727 {isToggled && !!showIfToggled && showIfToggled}
2828 <div
29- className={`border-vsc-input-border bg-vsc-input-background flex items-center rounded-full border border-solid`}
29+ className={`border-vsc-input-border bg-vsc-input-background relative flex items-center rounded-full border border-solid`}
3030 onClick={disabled ? undefined : onToggle}
3131 style={{
3232 height: size,
@@ -34,14 +34,14 @@
3434 padding: size / 8,
3535 }}
3636 >
37- <div className="relative h-full w-full">
38- <div
39- className={`absolute left-1/4 top-0 h-full w-1/2 transform rounded-full border-[0.2px] border-solid transition-all ${isToggled ? "translate-x-1/2 brightness-150" : "-translate-x-1/2 brightness-75"}`}
40- style={{
41- backgroundColor: isToggled ? vscButtonBackground : "",
42- }}
43- />
44- </div>
37+ <div
38+ className={`absolute left-1/4 transform rounded-full border-[0.2px] border-solid transition-all ${isToggled ? "translate-x-1/2 brightness-150" : "-translate-x-1/2 brightness-75"}`}
39+ style={{
40+ backgroundColor: isToggled ? vscButtonBackground : "",
41+ height: size,
42+ width: size,
43+ }}
44+ />
4545 </div>
4646 </div>
4747 </div>
modified gui/src/components/mainInput/belowMainInput/RulesPeek.tsx +12 −5
@@ -1,5 +1,6 @@
11 import { DocumentTextIcon, GlobeAltIcon } from "@heroicons/react/24/outline";
2-import { RuleSource, RuleWithSource } from "core";
2+import { RuleWithSource } from "core";
3+import { getLastNPathParts } from "core/util/uri";
34 import { ComponentType, useMemo, useState } from "react";
45 import ToggleDiv from "../../ToggleDiv";
56
@@ -13,8 +14,8 @@
1314 }
1415
1516 // Convert technical source to user-friendly text
16-const getSourceLabel = (source: RuleSource): string => {
17- switch (source) {
17+const getSourceLabel = (rule: RuleWithSource): string => {
18+ switch (rule.source) {
1819 case "default-chat":
1920 return "Default Chat";
2021 case "default-agent":
@@ -27,12 +28,18 @@
2728 return "Model Agent Options";
2829 case "rules-block":
2930 return "Rules Block";
31+ case "colocated-markdown":
32+ if (rule.ruleFile) {
33+ return getLastNPathParts(rule.ruleFile, 2);
34+ } else {
35+ return "rules.md";
36+ }
3037 case "json-systemMessage":
3138 return "System Message";
3239 case ".continuerules":
3340 return "Project Rules";
3441 default:
35- return source;
42+ return rule.source;
3643 }
3744 };
3845
@@ -95,7 +102,7 @@
95102 )}
96103 </div>
97104 <div className="mt-1 pl-6 pr-2 text-xs text-gray-500">
98- Source: {getSourceLabel(rule.source)}
105+ Source: {getSourceLabel(rule)}
99106 </div>
100107 </div>
101108 );
modified gui/src/console.tsx +1 −1
@@ -3,7 +3,7 @@
33 import Layout from "./components/console/Layout";
44 import "./indexConsole.css";
55
6-(async () => {
6+void (async () => {
77 ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
88 <React.StrictMode>
99 <Layout></Layout>
modified gui/src/context/Auth.tsx +2 −3
@@ -1,6 +1,6 @@
11 import {
2- OrganizationDescription,
32 ProfileDescription,
3+ SerializedOrgWithProfiles,
44 } from "core/config/ProfileLifecycleManager";
55 import { ControlPlaneSessionInfo } from "core/control-plane/AuthTypes";
66 import React, {
@@ -28,7 +28,7 @@
2828 selectedProfile: ProfileDescription | null;
2929 profiles: ProfileDescription[] | null;
3030 refreshProfiles: () => Promise<void>;
31- organizations: OrganizationDescription[];
31+ organizations: SerializedOrgWithProfiles[];
3232 }
3333
3434 const AuthContext = createContext<AuthContextType | undefined>(undefined);
@@ -95,7 +95,6 @@
9595 "sessionUpdate",
9696 async (data) => {
9797 setSession(data.sessionInfo);
98- void refreshProfiles();
9998 },
10099 [],
101100 );
modified gui/src/hooks/ParallelListeners.tsx +8 −12
@@ -101,8 +101,9 @@
101101 [dispatch, hasDoneInitialConfigLoad],
102102 );
103103
104- const initialLoadAuthAndConfig = useCallback(
105- async (initial: boolean) => {
104+ // Load config from the IDE
105+ useEffect(() => {
106+ async function initialLoadConfig() {
106107 dispatch(setIsSessionMetadataLoading(true));
107108 dispatch(setConfigLoading(true));
108109 const result = await ideMessenger.request(
@@ -110,16 +111,11 @@
110111 undefined,
111112 );
112113 if (result.status === "success") {
113- await handleConfigUpdate(initial, result.content);
114+ await handleConfigUpdate(true, result.content);
114115 }
115116 dispatch(setConfigLoading(false));
116- },
117- [ideMessenger, handleConfigUpdate],
118- );
119-
120- // Load config from the IDE
121- useEffect(() => {
122- void initialLoadAuthAndConfig(true);
117+ }
118+ void initialLoadConfig();
123119 const interval = setInterval(() => {
124120 if (hasDoneInitialConfigLoad.current) {
125121 // Init to run on initial config load
@@ -130,12 +126,12 @@
130126 // This triggers sending pending status to the GUI for relevant docs indexes
131127 clearInterval(interval);
132128 } else {
133- void initialLoadAuthAndConfig(true);
129+ void initialLoadConfig();
134130 }
135131 }, 2_000);
136132
137133 return () => clearInterval(interval);
138- }, [hasDoneInitialConfigLoad, initialLoadAuthAndConfig, ideMessenger]);
134+ }, [hasDoneInitialConfigLoad, ideMessenger]);
139135
140136 useWebviewListener(
141137 "configUpdate",
modified gui/src/hooks/useLLMSummary.ts +18 −0
@@ -1,3 +1,7 @@
1+import {
2+ calculateRequestCost,
3+ CostBreakdown,
4+} from "core/llm/utils/calculateRequestCost";
15 import { useMemo } from "react";
26 import { LLMInteraction } from "./useLLMLog";
37
@@ -62,6 +66,19 @@
6266 : undefined;
6367 }
6468
69+ let costBreakdown: CostBreakdown | null = null;
70+ if (
71+ interaction.end?.usage &&
72+ interaction.start?.provider &&
73+ interaction.start?.options?.model
74+ ) {
75+ costBreakdown = calculateRequestCost(
76+ interaction.start.provider,
77+ interaction.start.options.model,
78+ interaction.end.usage,
79+ );
80+ }
81+
6582 return {
6683 result,
6784 type,
@@ -71,6 +88,7 @@
7188 promptTokens,
7289 generatedTokens,
7390 thinkingTokens,
91+ costBreakdown,
7492 };
7593 }, [interaction]);
7694 }
added gui/src/hooks/useTotalUsage.ts +102 −0
@@ -0,0 +1,102 @@
1+import {
2+ calculateRequestCost,
3+ CostBreakdown,
4+} from "core/llm/utils/calculateRequestCost";
5+import { useMemo } from "react";
6+import { LLMLog } from "./useLLMLog";
7+
8+export interface TotalUsage {
9+ totalPromptTokens: number;
10+ totalGeneratedTokens: number;
11+ totalThinkingTokens: number;
12+ totalCachedTokens: number;
13+ totalCacheWriteTokens: number;
14+ totalInteractions: number;
15+ totalSuccessfulInteractions: number;
16+ totalErrorInteractions: number;
17+ totalCancelledInteractions: number;
18+ totalCost: number;
19+ costBreakdowns: CostBreakdown[];
20+}
21+
22+/**
23+ * Hook to calculate total usage across all interactions in the LLM log
24+ */
25+export default function useTotalUsage(llmLog: LLMLog): TotalUsage {
26+ return useMemo(() => {
27+ let totalPromptTokens = 0;
28+ let totalGeneratedTokens = 0;
29+ let totalThinkingTokens = 0;
30+ let totalCachedTokens = 0;
31+ let totalCacheWriteTokens = 0;
32+ let totalInteractions = 0;
33+ let totalSuccessfulInteractions = 0;
34+ let totalErrorInteractions = 0;
35+ let totalCancelledInteractions = 0;
36+ let totalCost = 0;
37+ const costBreakdowns: CostBreakdown[] = [];
38+
39+ // Iterate through all interactions
40+ for (const interaction of llmLog.interactions.values()) {
41+ if (interaction.end) {
42+ totalInteractions++;
43+
44+ // Add basic token counts
45+ totalPromptTokens += interaction.end.promptTokens || 0;
46+ totalGeneratedTokens += interaction.end.generatedTokens || 0;
47+ totalThinkingTokens += interaction.end.thinkingTokens || 0;
48+
49+ // Add cache-related tokens from usage if available
50+ if (interaction.end.usage) {
51+ const usage = interaction.end.usage;
52+ totalCachedTokens += usage.promptTokensDetails?.cachedTokens || 0;
53+ totalCacheWriteTokens +=
54+ usage.promptTokensDetails?.cacheWriteTokens || 0;
55+
56+ // Calculate cost if we have the necessary information
57+ if (
58+ interaction.start?.provider &&
59+ interaction.start?.options?.model
60+ ) {
61+ const costBreakdown = calculateRequestCost(
62+ interaction.start.provider,
63+ interaction.start.options.model,
64+ usage,
65+ );
66+ if (costBreakdown) {
67+ totalCost += costBreakdown.cost;
68+ costBreakdowns.push(costBreakdown);
69+ }
70+ }
71+ }
72+
73+ // Count interaction outcomes
74+ switch (interaction.end.kind) {
75+ case "success":
76+ totalSuccessfulInteractions++;
77+ break;
78+ case "error":
79+ totalErrorInteractions++;
80+ break;
81+ case "cancel":
82+ totalCancelledInteractions++;
83+ break;
84+ }
85+ }
86+ }
87+
88+ return {
89+ totalPromptTokens,
90+ totalGeneratedTokens,
91+ totalThinkingTokens,
92+ totalCachedTokens,
93+ totalCacheWriteTokens,
94+ totalInteractions,
95+ totalSuccessfulInteractions,
96+ totalErrorInteractions,
97+ totalCancelledInteractions,
98+ totalCost,
99+ costBreakdowns,
100+ };
101+ }, [llmLog]);
102+}
modified gui/src/pages/config/ContinueFeaturesMenu.tsx +0 −23
@@ -1,16 +1,10 @@
1-import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
21 import ToggleSwitch from "../../components/gui/Switch";
3-import { ToolTip } from "../../components/gui/Tooltip";
42 interface ContinueFeaturesMenuProps {
5- logEditingData: boolean;
6- handleLogEditingDataToggle: (value: boolean) => void;
73 optInNextEditFeature: boolean;
84 handleOptInNextEditToggle: (value: boolean) => void;
95 }
106
117 export function ContinueFeaturesMenu({
12- logEditingData,
13- handleLogEditingDataToggle,
148 optInNextEditFeature,
159 handleOptInNextEditToggle,
1610 }: ContinueFeaturesMenuProps) {
@@ -20,23 +14,6 @@
2014 🚧 INTERNAL SETTINGS 🚧
2115 </div>
2216 <div className="flex w-full flex-col gap-y-4">
23- <ToggleSwitch
24- isToggled={logEditingData}
25- onToggle={() => handleLogEditingDataToggle(!logEditingData)}
26- text="Log Editing Data"
27- showIfToggled={
28- <>
29- <ExclamationTriangleIcon
30- data-tooltip-id={`auto-accept-diffs-warning-tooltip`}
31- className="h-3 w-3 text-yellow-500"
32- />
33- <ToolTip id={`auto-accept-diffs-warning-tooltip`}>
34- {`Only turn this on if you want to log your editing processes in addition to the normal dev data. Note that this will store a lot of data.`}
35- </ToolTip>
36- </>
37- }
38- />
39-
4017 <ToggleSwitch
4118 isToggled={optInNextEditFeature}
4219 onToggle={() => handleOptInNextEditToggle(!optInNextEditFeature)}
modified gui/src/pages/config/HelpCenterSection.tsx +26 −1
@@ -1,13 +1,14 @@
11 import {
22 ArrowTopRightOnSquareIcon,
33 DocumentArrowUpIcon,
4+ NumberedListIcon,
45 PaintBrushIcon,
56 TableCellsIcon,
67 } from "@heroicons/react/24/outline";
78 import { useContext } from "react";
89 import { useNavigate } from "react-router-dom";
910 import { IdeMessengerContext } from "../../context/IdeMessenger";
10-import { useAppDispatch } from "../../redux/hooks";
11+import { useAppDispatch, useAppSelector } from "../../redux/hooks";
1112 import { setOnboardingCard } from "../../redux/slices/uiSlice";
1213 import { saveCurrentSession } from "../../redux/thunks/session";
1314 import { ROUTES } from "../../util/navigation";
@@ -18,6 +19,21 @@
1819 const navigate = useNavigate();
1920 const dispatch = useAppDispatch();
2021
22+ const currentSession = useAppSelector((state) => state.session);
23+
24+ const handleViewSessionData = async () => {
25+ const sessionData = await ideMessenger.request("history/load", {
26+ id: currentSession.id,
27+ });
28+
29+ if (sessionData.status === "success") {
30+ await ideMessenger.request("showVirtualFile", {
31+ name: `${sessionData.content.title}.json`,
32+ content: JSON.stringify(sessionData.content, null, 2),
33+ });
34+ }
35+ };
36+
2137 return (
2238 <div className="py-5">
2339 <h3 className="mb-4 mt-0 text-xl">Help center</h3>
@@ -68,6 +84,15 @@
6884 onClick={() => navigate("/stats")}
6985 />
7086
87+ {currentSession.history.length > 0 && !currentSession.isStreaming && (
88+ <MoreHelpRow
89+ title="View current session history"
90+ description="Open the current chat session file for troubleshooting"
91+ Icon={NumberedListIcon}
92+ onClick={handleViewSessionData}
93+ />
94+ )}
95+
7196 <MoreHelpRow
7297 title="Quickstart"
7398 description="Reopen the quickstart and tutorial file"
modified gui/src/pages/config/UserSettingsForm.tsx +0 −7
@@ -67,10 +67,6 @@
6767 });
6868 };
6969
70- const handleLogEditingDataToggle = (value: boolean) => {
71- handleUpdate({ logEditingData: value });
72- };
73-
7470 const handleOptInNextEditToggle = (value: boolean) => {
7571 handleUpdate({ optInNextEditFeature: value });
7672 };
@@ -86,7 +82,6 @@
8682 const showChatScrollbar = config.ui?.showChatScrollbar ?? false;
8783 const readResponseTTS = config.experimental?.readResponseTTS ?? false;
8884 const autoAcceptEditToolDiffs = config.ui?.autoAcceptEditToolDiffs ?? false;
89- const logEditingData = config.experimental?.logEditingData ?? false;
9085 const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false;
9186 const disableSessionTitles = config.disableSessionTitles ?? false;
9287 const useCurrentFileAsContext =
@@ -436,8 +431,6 @@
436431
437432 {hasContinueEmail && (
438433 <ContinueFeaturesMenu
439- logEditingData={logEditingData}
440- handleLogEditingDataToggle={handleLogEditingDataToggle}
441434 optInNextEditFeature={optInNextEditFeature}
442435 handleOptInNextEditToggle={handleOptInNextEditToggle}
443436 />
modified gui/src/pages/gui/Chat.tsx +41 −20
@@ -3,7 +3,7 @@
33 ChatBubbleOvalLeftIcon,
44 } from "@heroicons/react/24/outline";
55 import { Editor, JSONContent } from "@tiptap/react";
6-import { InputModifiers } from "core";
6+import { InputModifiers, ChatHistoryItem } from "core";
77 import { renderChatMessage } from "core/util/messageContent";
88 import {
99 useCallback,
@@ -49,6 +49,16 @@
4949 import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
5050 import { useAutoScroll } from "./useAutoScroll";
5151
52+// Helper function to find the index of the latest conversation summary
53+function findLatestSummaryIndex(history: ChatHistoryItem[]): number {
54+ for (let i = history.length - 1; i >= 0; i--) {
55+ if (history[i].conversationSummary) {
56+ return i;
57+ }
58+ }
59+ return -1; // No summary found
60+}
61+
5262 const StepsDiv = styled.div`
5363 position: relative;
5464 background-color: transparent;
@@ -271,19 +281,26 @@
271281 toolCallStates,
272282 } = item;
273283
284+ // Calculate once for the entire function
285+ const latestSummaryIndex = findLatestSummaryIndex(history);
286+ const isBeforeLatestSummary =
287+ latestSummaryIndex !== -1 && index < latestSummaryIndex;
288+
274289 if (message.role === "user") {
275290 return (
276- <ContinueInputBox
277- onEnter={(editorState, modifiers) =>
278- sendInput(editorState, modifiers, index)
279- }
280- isLastUserInput={isLastUserInput(index)}
281- isMainInput={false}
282- editorState={editorState}
283- contextItems={contextItems}
284- appliedRules={appliedRules}
285- inputId={message.id}
286- />
291+ <div className={isBeforeLatestSummary ? "opacity-50" : ""}>
292+ <ContinueInputBox
293+ onEnter={(editorState, modifiers) =>
294+ sendInput(editorState, modifiers, index)
295+ }
296+ isLastUserInput={isLastUserInput(index)}
297+ isMainInput={false}
298+ editorState={editorState}
299+ contextItems={contextItems}
300+ appliedRules={appliedRules}
301+ inputId={message.id}
302+ />
303+ </div>
287304 );
288305 }
289306
@@ -312,6 +329,7 @@
312329 index={index}
313330 isLast={index === history.length - 1}
314331 item={item}
332+ latestSummaryIndex={latestSummaryIndex}
315333 />
316334 </TimelineItem>
317335 </div>
@@ -328,14 +346,16 @@
328346
329347 if (message.role === "thinking") {
330348 return (
331- <ThinkingBlockPeek
332- content={renderChatMessage(message)}
333- redactedThinking={message.redactedThinking}
334- index={index}
335- prevItem={index > 0 ? history[index - 1] : null}
336- inProgress={index === history.length - 1}
337- signature={message.signature}
338- />
349+ <div className={isBeforeLatestSummary ? "opacity-50" : ""}>
350+ <ThinkingBlockPeek
351+ content={renderChatMessage(message)}
352+ redactedThinking={message.redactedThinking}
353+ index={index}
354+ prevItem={index > 0 ? history[index - 1] : null}
355+ inProgress={index === history.length - 1}
356+ signature={message.signature}
357+ />
358+ </div>
339359 );
340360 }
341361
@@ -354,6 +374,7 @@
354374 index={index}
355375 isLast={index === history.length - 1}
356376 item={item}
377+ latestSummaryIndex={latestSummaryIndex}
357378 />
358379 </TimelineItem>
359380 </div>
modified gui/src/redux/slices/sessionSlice.test.ts +1 −0
@@ -75,6 +75,7 @@
7575 },
7676 newestToolbarPreviewForInput: {},
7777 isSessionMetadataLoading: false,
78+ compactionLoading: {},
7879 });
7980
8081 describe("Basic Chat Message", () => {
modified gui/src/redux/slices/sessionSlice.ts +14 −1
@@ -227,6 +227,7 @@
227227 isPruned?: boolean;
228228 contextPercentage?: number;
229229 inlineErrorMessage?: InlineErrorMessageType;
230+ compactionLoading: Record<number, boolean>; // Track compaction loading by message index
230231 };
231232
232233 const initialState: SessionState = {
@@ -246,7 +247,7 @@
246247 },
247248 lastSessionId: undefined,
248249 newestToolbarPreviewForInput: {},
249- isPruned: false,
250+ compactionLoading: {},
250251 };
251252
252253 export const sessionSlice = createSlice({
@@ -904,6 +905,17 @@
904905 state.newestToolbarPreviewForInput[payload.inputId] =
905906 payload.contextItemId;
906907 },
908+ setCompactionLoading: (
909+ state,
910+ action: PayloadAction<{ index: number; loading: boolean }>,
911+ ) => {
912+ const { index, loading } = action.payload;
913+ if (loading) {
914+ state.compactionLoading[index] = true;
915+ } else {
916+ delete state.compactionLoading[index];
917+ }
918+ },
907919 setInlineErrorMessage: (
908920 state,
909921 action: PayloadAction<SessionState["inlineErrorMessage"]>,
@@ -1002,6 +1014,7 @@
10021014 setInlineErrorMessage,
10031015 setIsPruned,
10041016 setContextPercentage,
1017+ setCompactionLoading,
10051018 } = sessionSlice.actions;
10061019
10071020 export const { selectIsGatheringContext } = sessionSlice.selectors;
modified gui/src/redux/store.ts +1 −1
@@ -52,7 +52,7 @@
5252 "lastNonEditSessionWasEmpty",
5353 "codeToEdit",
5454 ]),
55- createFilter("config", ["defaultModelTitle"]),
55+ createFilter("config", []),
5656 createFilter("ui", ["toolSettings", "toolGroupSettings", "ruleSettings"]),
5757 createFilter("indexing", []),
5858 createFilter("tabs", ["tabs"]),
modified gui/src/redux/util/constructMessages.ts +25 −3
@@ -40,7 +40,21 @@
4040 appliedRules: RuleWithSource[];
4141 appliedRuleIndex: number;
4242 } {
43- const historyCopy = [...history];
43+ // Find the most recent conversation summary and filter history accordingly
44+ let summaryContent = "";
45+ let filteredHistory = history;
46+
47+ for (let i = history.length - 1; i >= 0; i--) {
48+ const summary = history[i].conversationSummary;
49+ if (summary) {
50+ summaryContent = summary;
51+ // Only include messages that come AFTER the message with the summary
52+ filteredHistory = history.slice(i + 1);
53+ break;
54+ }
55+ }
56+
57+ const historyCopy = [...filteredHistory];
4458
4559 const msgs: MessageWithContextItems[] = [];
4660 let appliedRuleIndex = -1;
@@ -160,12 +174,20 @@
160174 rulePolicies,
161175 });
162176
163- if (systemMessage.trim()) {
177+ // Append conversation summary to system message if it exists
178+ let finalSystemMessage = systemMessage;
179+ if (summaryContent) {
180+ finalSystemMessage = systemMessage
181+ ? `${systemMessage}\n\nPrevious conversation summary:\n\n ${summaryContent}`
182+ : `Previous conversation summary:\n\n ${summaryContent}`;
183+ }
184+
185+ if (finalSystemMessage.trim()) {
164186 msgs.unshift({
165187 ctxItems: [],
166188 message: {
167189 role: "system",
168- content: systemMessage,
190+ content: finalSystemMessage,
169191 },
170192 });
171193 }
modified package-lock.json +1 −1
@@ -1,5 +1,5 @@
11 {
2- "name": "continue",
2+ "name": "wt-openai-adapters-tests",
33 "lockfileVersion": 3,
44 "requires": true,
55 "packages": {
modified packages/config-types/src/index.ts +1 −1
@@ -207,7 +207,7 @@
207207 startUrl: z.string(),
208208 // rootUrl: z.string(),
209209 title: z.string(),
210- maxDepth: z.string().optional(),
210+ maxDepth: z.number().optional(),
211211 faviconUrl: z.string().optional(),
212212 useLocalCrawling: z.boolean().optional(),
213213 });
modified packages/config-yaml/CHANGELOG.md +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

added packages/config-yaml/src/load/unroll.test.ts +91 −0
@@ -0,0 +1,91 @@
1+import { PackageIdentifier } from "../interfaces/slugs.js";
2+import { parseMarkdownRuleOrAssistantUnrolled } from "./unroll.js";
3+
4+describe("parseMarkdownRuleOrAssistantUnrolled tests", () => {
5+ it("parses valid YAML content as AssistantUnrolled", () => {
6+ const mockId: PackageIdentifier = {
7+ uriType: "file",
8+ filePath: "./foo/bar.yaml",
9+ };
10+ const yamlContent = `
11+name: Test Assistant
12+version: 1.0.0
13+
14+models:
15+ - name: model
16+ model: modelname
17+ provider: ollama
18+`;
19+ const result = parseMarkdownRuleOrAssistantUnrolled(yamlContent, mockId);
20+ expect(result).toHaveProperty("name", "Test Assistant");
21+ expect(result).toHaveProperty("version", "1.0.0");
22+ expect(result.models?.length).toBe(1);
23+ expect(result.models?.[0]).toHaveProperty("name", "model");
24+ });
25+
26+ it("parses markdown rule content as AssistantUnrolled", () => {
27+ const mockId: PackageIdentifier = {
28+ uriType: "file",
29+ filePath: "./foo/bar.md",
30+ };
31+ const markdownContent = `
32+---
33+name: rulename
34+description: my rule description
35+pattern: "**"
36+---
37+This is the rule
38+`;
39+ const result = parseMarkdownRuleOrAssistantUnrolled(
40+ markdownContent,
41+ mockId,
42+ );
43+ expect(result).toHaveProperty("name");
44+ expect(result).toHaveProperty("version");
45+ expect(Array.isArray(result.rules)).toBe(true);
46+ expect(result.rules).toBeDefined();
47+ expect(result.rules!.length).toBe(1);
48+ const rule = result.rules![0];
49+ expect(rule).toHaveProperty("name", "rulename");
50+ expect(rule).toHaveProperty("description", "my rule description");
51+ expect(rule).toHaveProperty("globs", "./foo/**/*");
52+ expect(rule).toHaveProperty("rule", "This is the rule");
53+ });
54+
55+ it("throws error for invalid content in yaml file", () => {
56+ const mockId: PackageIdentifier = {
57+ uriType: "file",
58+ filePath: "./foo/bar.yaml",
59+ };
60+ const invalidContent = `
61+name: Test Assistant
62+version: 1.0.0
63+
64+model: # should be models
65+ - name: model
66+ model: modelname
67+ provider: ollama
68+`;
69+ expect(() =>
70+ parseMarkdownRuleOrAssistantUnrolled(invalidContent, mockId),
71+ ).toThrow();
72+ });
73+
74+ it("Every non-YAML file is a rule", () => {
75+ const mockId: PackageIdentifier = {
76+ uriType: "file",
77+ filePath: "./foo/bar",
78+ };
79+ const dubiousContent = `This is not \nproper #YAML#`;
80+ const result = parseMarkdownRuleOrAssistantUnrolled(dubiousContent, mockId);
81+ expect(result).toHaveProperty("name");
82+ expect(result).toHaveProperty("version");
83+ expect(Array.isArray(result.rules)).toBe(true);
84+ expect(result.rules).toBeDefined();
85+ expect(result.rules!.length).toBe(1);
86+ const rule = result.rules![0];
87+ expect(rule).toHaveProperty("name", "foo/bar");
88+ expect(rule).toHaveProperty("globs", "./foo/**/*");
89+ expect(rule).toHaveProperty("rule", dubiousContent);
90+ });
91+});
modified packages/config-yaml/src/load/unroll.ts +25 −52
@@ -286,9 +286,7 @@
286286 options.platformClient,
287287 options.alwaysUseProxy,
288288 );
289- const renderedYaml = renderTemplateData(templatedYaml, {
290- secrets,
291- });
289+ const renderedYaml = renderTemplateData(templatedYaml, { secrets });
292290
293291 // Parse again and replace models with proxy versions where secrets weren't rendered
294292 const finalConfig = useProxyForUnrenderedSecrets(
@@ -298,11 +296,7 @@
298296 options.onPremProxyUrl,
299297 );
300298
301- return {
302- config: finalConfig,
303- errors,
304- configLoadInterrupted,
305- };
299+ return { config: finalConfig, errors, configLoadInterrupted };
306300 }
307301
308302 export async function unrollBlocks(
@@ -366,10 +360,7 @@
366360 return {
367361 index,
368362 block: null,
369- error: {
370- fatal: false,
371- message: msg,
372- },
363+ error: { fatal: false, message: msg },
373364 };
374365 }
375366 } else {
@@ -461,11 +452,7 @@
461452 registry,
462453 );
463454
464- return {
465- blockType,
466- resolvedBlock,
467- error: null,
468- };
455+ return { blockType, resolvedBlock, error: null };
469456 } catch (err) {
470457 let msg = "";
471458 if (injectBlock.uriType === "file") {
@@ -481,10 +468,7 @@
481468 return {
482469 blockType: null,
483470 resolvedBlock: null,
484- error: {
485- fatal: false,
486- message: msg,
487- },
471+ error: { fatal: false, message: msg },
488472 };
489473 }
490474 });
@@ -581,57 +565,46 @@
581565 return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id);
582566 }
583567
584-function parseMarkdownRuleOrAssistantUnrolled(
568+export function parseMarkdownRuleOrAssistantUnrolled(
585569 content: string,
586570 id: PackageIdentifier,
587571 ): AssistantUnrolled {
588- // Try to parse as YAML first, then as markdown rule if that fails
589- let parsedYaml: AssistantUnrolled;
590- try {
591- parsedYaml = parseBlock(content);
592- } catch (yamlError) {
593- // If YAML parsing fails, try parsing as markdown rule
594- try {
595- const rule = markdownToRule(content, id);
596- // Convert the rule object to the expected format
597- parsedYaml = {
598- name: rule.name,
599- version: "1.0.0",
600- rules: [rule],
601- };
602- } catch (markdownError) {
603- // If both fail, throw the original YAML error
604- throw yamlError;
605- }
606- }
607-
608- return parsedYaml;
572+ return parseYamlOrMarkdownRule<AssistantUnrolled>(content, id, parseBlock);
609573 }
610574
611575 function parseMarkdownRuleOrConfigYaml(
612576 content: string,
613577 id: PackageIdentifier,
614578 ): ConfigYaml {
615- // Try to parse as YAML first, then as markdown rule if that fails
616- let parsedYaml: ConfigYaml;
579+ return parseYamlOrMarkdownRule<ConfigYaml>(content, id, parseConfigYaml);
580+}
581+
582+function parseYamlOrMarkdownRule<T>(
583+ content: string,
584+ id: PackageIdentifier,
585+ parseYamlFn: (content: string) => T,
586+): T {
587+ let parsedYaml: T;
617588 try {
618- parsedYaml = parseConfigYaml(content);
589+ // Try to parse as YAML first, then as markdown rule if that fails
590+ parsedYaml = parseYamlFn(content);
619591 } catch (yamlError) {
592+ if (
593+ id.uriType === "file" &&
594+ [".yaml", ".yml"].some((ext) => id.filePath.endsWith(ext))
595+ ) {
596+ throw yamlError;
597+ }
620598 // If YAML parsing fails, try parsing as markdown rule
621599 try {
622600 const rule = markdownToRule(content, id);
623601 // Convert the rule object to the expected format
624- parsedYaml = {
625- name: rule.name,
626- version: "1.0.0",
627- rules: [rule],
628- };
602+ parsedYaml = { name: rule.name, version: "1.0.0", rules: [rule] } as T;
629603 } catch (markdownError) {
630604 // If both fail, throw the original YAML error
631605 throw yamlError;
632606 }
633607 }
634-
635608 return parsedYaml;
636609 }
637610
modified packages/config-yaml/src/schemas/index.ts +2 −0
@@ -42,6 +42,8 @@
4242 startUrl: z.string(),
4343 rootUrl: z.string().optional(),
4444 faviconUrl: z.string().optional(),
45+ maxDepth: z.number().optional(),
46+ useLocalCrawling: z.boolean().optional(),
4547 });
4648
4749 export type DocsConfig = z.infer<typeof docSchema>;
modified packages/continue-sdk/typescript/src/createOpenAIClient.ts +4 −1
@@ -71,7 +71,10 @@
7171 );
7272 }
7373
74- if (!("apiKeyLocation" in modelConfig) && !("envSecretLocations" in modelConfig)) {
74+ if (
75+ !("apiKeyLocation" in modelConfig) &&
76+ !("envSecretLocations" in modelConfig)
77+ ) {
7578 throw new Error(
7679 `Model ${modelName} does not have an apiKeyLocation or envSecretLocations defined`,
7780 );
modified packages/openai-adapters/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/openai-adapters/package.json +12 −4
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.45",
3+ "version": "1.0.46",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
77 "type": "module",
88 "scripts": {
9- "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
9+ "test": "vitest",
1010 "build": "tsc"
1111 },
1212 "author": "Nate Sesti and Ty Dunn",
@@ -20,16 +20,24 @@
2020 "dotenv": "^16.5.0",
2121 "json-schema": "^0.4.0",
2222 "node-fetch": "^3.3.2",
23- "openai": "^4.76.0",
23+ "openai": "^4.104.0",
2424 "uuid": "^11.1.0",
2525 "zod": "^3.24.2"
2626 },
2727 "devDependencies": {
28+ "@semantic-release/changelog": "^6.0.3",
29+ "@semantic-release/commit-analyzer": "^13.0.1",
30+ "@semantic-release/git": "^10.0.1",
31+ "@semantic-release/github": "^11.0.3",
32+ "@semantic-release/npm": "^12.0.2",
33+ "@semantic-release/release-notes-generator": "^14.0.3",
2834 "@types/follow-redirects": "^1.14.4",
2935 "@types/jest": "^29.5.14",
3036 "@types/json-schema": "^7.0.15",
3137 "cross-env": "^7.0.3",
38+ "semantic-release": "^24.2.7",
3239 "ts-jest": "^29.2.3",
33- "ts-node": "^10.9.2"
40+ "ts-node": "^10.9.2",
41+ "vitest": "^1.6.1"
3442 }
3543 }
modified packages/openai-adapters/src/apis/Anthropic.ts +54 −3
@@ -8,12 +8,22 @@
88 Completion,
99 CompletionCreateParamsNonStreaming,
1010 CompletionCreateParamsStreaming,
11+ CompletionUsage,
1112 } from "openai/resources/index";
1213 import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
1314 import { AnthropicConfig } from "../types.js";
14-import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js";
15+import {
16+ chatChunk,
17+ chatChunkFromDelta,
18+ customFetch,
19+ usageChatChunk,
20+} from "../util.js";
1521 import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
1622 import { safeParseArgs } from "../util/parseArgs.js";
23+import {
24+ CACHING_STRATEGIES,
25+ CachingStrategyName,
26+} from "./AnthropicCachingStrategies.js";
1727 import {
1828 BaseLlmApi,
1929 CreateRerankResponse,
@@ -24,7 +34,11 @@
2434 export class AnthropicApi implements BaseLlmApi {
2535 apiBase: string = "https://api.anthropic.com/v1/";
2636
27- constructor(protected config: AnthropicConfig) {
37+ constructor(
38+ protected config: AnthropicConfig & {
39+ cachingStrategy?: CachingStrategyName;
40+ },
41+ ) {
2842 this.apiBase = config.apiBase ?? this.apiBase;
2943 if (!this.apiBase.endsWith("/")) {
3044 this.apiBase += "/";
@@ -32,6 +46,16 @@
3246 }
3347
3448 private _convertBody(oaiBody: ChatCompletionCreateParams) {
49+ // Step 1: Convert to clean Anthropic body (no caching)
50+ const cleanBody = this._convertToCleanAnthropicBody(oaiBody);
51+
52+ // Step 2: Apply caching strategy
53+ const cachingStrategy =
54+ CACHING_STRATEGIES[this.config.cachingStrategy ?? "systemAndTools"];
55+ return cachingStrategy(cleanBody);
56+ }
57+
58+ private _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) {
3559 let stop = undefined;
3660 if (oaiBody.stop && Array.isArray(oaiBody.stop)) {
3761 stop = oaiBody.stop.filter((x) => x.trim() !== "");
@@ -52,7 +76,6 @@
5276 {
5377 type: "text",
5478 text: systemMessage,
55- cache_control: { type: "ephemeral" },
5679 },
5780 ]
5881 : systemMessage,
@@ -155,6 +178,7 @@
155178 "Content-Type": "application/json",
156179 Accept: "application/json",
157180 "anthropic-version": "2023-06-01",
181+ "anthropic-beta": "prompt-caching-2024-07-31",
158182 "x-api-key": this.config.apiKey,
159183 },
160184 body: JSON.stringify(this._convertBody(body)),
@@ -177,6 +201,9 @@
177201 completion.usage.input_tokens + completion.usage.output_tokens,
178202 completion_tokens: completion.usage.output_tokens,
179203 prompt_tokens: completion.usage.input_tokens,
204+ prompt_tokens_details: {
205+ cached_tokens: completion.usage.cache_read_input_tokens || 0,
206+ },
180207 },
181208 choices: [
182209 {
@@ -205,6 +232,7 @@
205232 "Content-Type": "application/json",
206233 Accept: "application/json",
207234 "anthropic-version": "2023-06-01",
235+ "anthropic-beta": "prompt-caching-2024-07-31",
208236 "x-api-key": this.config.apiKey,
209237 },
210238 body: JSON.stringify(this._convertBody(body)),
@@ -214,6 +242,12 @@
214242
215243 let lastToolUseId: string | undefined;
216244 let lastToolUseName: string | undefined;
245+
246+ const usage: CompletionUsage = {
247+ completion_tokens: 0,
248+ prompt_tokens: 0,
249+ total_tokens: 0,
250+ };
217251 for await (const value of streamSse(response as any)) {
218252 // https://docs.anthropic.com/en/api/messages-streaming#event-types
219253 switch (value.type) {
@@ -223,6 +257,15 @@
223257 lastToolUseName = value.content_block.name;
224258 }
225259 break;
260+ case "message_start":
261+ usage.prompt_tokens = value.message.usage.input_tokens;
262+ usage.prompt_tokens_details = {
263+ cached_tokens: value.message.usage.cache_read_input_tokens || 0,
264+ };
265+ break;
266+ case "message_delta":
267+ usage.completion_tokens = value.usage.output_tokens;
268+ break;
226269 case "content_block_delta":
227270 // https://docs.anthropic.com/en/api/messages-streaming#delta-types
228271 switch (value.delta.type) {
@@ -263,6 +306,14 @@
263306 break;
264307 }
265308 }
309+
310+ yield usageChatChunk({
311+ model: body.model,
312+ usage: {
313+ ...usage,
314+ total_tokens: usage.completion_tokens + usage.prompt_tokens,
315+ },
316+ });
266317 }
267318 async completionNonStream(
268319 body: CompletionCreateParamsNonStreaming,
added packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts +369 −0
@@ -0,0 +1,369 @@
1+import {
2+ CACHING_STRATEGIES,
3+ CachingStrategy,
4+ CachingStrategyName,
5+ getAvailableStrategies,
6+ getStrategyDescription,
7+} from "./AnthropicCachingStrategies.js";
8+
9+describe("AnthropicCachingStrategies", () => {
10+ describe("noCachingStrategy", () => {
11+ it("should return the body unchanged", () => {
12+ const body = { system: "test", messages: [] };
13+ const result = CACHING_STRATEGIES.none(body);
14+ expect(result).toBe(body);
15+ });
16+
17+ it("should not modify complex objects", () => {
18+ const body = {
19+ system: [{ text: "test" }],
20+ tools: [{ name: "test" }],
21+ messages: [{ content: "test" }],
22+ };
23+ const result = CACHING_STRATEGIES.none(body);
24+ expect(result).toBe(body);
25+ });
26+ });
27+
28+ describe("systemOnlyStrategy", () => {
29+ it("should add cache_control to system messages array", () => {
30+ const body = {
31+ system: [{ text: "system message 1" }, { text: "system message 2" }],
32+ messages: [{ content: "user message" }],
33+ };
34+
35+ const result = CACHING_STRATEGIES.systemOnly(body);
36+
37+ expect(result.system).toEqual([
38+ { text: "system message 1", cache_control: { type: "ephemeral" } },
39+ { text: "system message 2", cache_control: { type: "ephemeral" } },
40+ ]);
41+ expect(result.messages).toEqual(body.messages);
42+ });
43+
44+ it("should return body unchanged if system is not an array", () => {
45+ const body = {
46+ system: "string system message",
47+ messages: [{ content: "user message" }],
48+ };
49+
50+ const result = CACHING_STRATEGIES.systemOnly(body);
51+ expect(result).toEqual(body);
52+ });
53+
54+ it("should return body unchanged if system is undefined", () => {
55+ const body = {
56+ messages: [{ content: "user message" }],
57+ };
58+
59+ const result = CACHING_STRATEGIES.systemOnly(body);
60+ expect(result).toEqual(body);
61+ });
62+ });
63+
64+ describe("systemAndToolsStrategy", () => {
65+ it("should add cache_control to both system and tools", () => {
66+ const body = {
67+ system: [{ text: "system message" }],
68+ tools: [{ name: "tool1" }, { name: "tool2" }],
69+ messages: [{ content: "user message" }],
70+ };
71+
72+ const result = CACHING_STRATEGIES.systemAndTools(body);
73+
74+ expect(result.system).toEqual([
75+ { text: "system message", cache_control: { type: "ephemeral" } },
76+ ]);
77+ expect(result.tools).toEqual([
78+ { name: "tool1" },
79+ { name: "tool2", cache_control: { type: "ephemeral" } },
80+ ]);
81+ expect(result.messages).toEqual(body.messages);
82+ });
83+
84+ it("should handle missing system messages", () => {
85+ const body = {
86+ tools: [{ name: "tool1" }],
87+ messages: [{ content: "user message" }],
88+ };
89+
90+ const result = CACHING_STRATEGIES.systemAndTools(body);
91+
92+ expect(result.tools).toEqual([
93+ { name: "tool1", cache_control: { type: "ephemeral" } },
94+ ]);
95+ expect(result.messages).toEqual(body.messages);
96+ });
97+
98+ it("should handle missing tools", () => {
99+ const body = {
100+ system: [{ text: "system message" }],
101+ messages: [{ content: "user message" }],
102+ };
103+
104+ const result = CACHING_STRATEGIES.systemAndTools(body);
105+
106+ expect(result.system).toEqual([
107+ { text: "system message", cache_control: { type: "ephemeral" } },
108+ ]);
109+ expect(result.messages).toEqual(body.messages);
110+ });
111+
112+ it("should handle non-array system and tools", () => {
113+ const body = {
114+ system: "string system",
115+ tools: "string tools",
116+ messages: [{ content: "user message" }],
117+ };
118+
119+ const result = CACHING_STRATEGIES.systemAndTools(body);
120+ expect(result).toEqual(body);
121+ });
122+ });
123+
124+ describe("optimizedStrategy", () => {
125+ it("should cache system messages and tools", () => {
126+ const body = {
127+ system: [{ text: "system message" }],
128+ tools: [{ name: "tool1" }],
129+ messages: [{ content: "short message" }],
130+ };
131+
132+ const result = CACHING_STRATEGIES.optimized(body);
133+
134+ expect(result.system).toEqual([
135+ { text: "system message", cache_control: { type: "ephemeral" } },
136+ ]);
137+ expect(result.tools).toEqual([
138+ { name: "tool1", cache_control: { type: "ephemeral" } },
139+ ]);
140+ });
141+
142+ it("should cache large string messages (>500 tokens)", () => {
143+ const largeContent = "a".repeat(2100); // ~525 tokens
144+ const body = {
145+ messages: [{ content: largeContent }],
146+ };
147+
148+ const result = CACHING_STRATEGIES.optimized(body);
149+
150+ expect(result.messages).toEqual([
151+ {
152+ content: [
153+ {
154+ type: "text",
155+ text: largeContent,
156+ cache_control: { type: "ephemeral" },
157+ },
158+ ],
159+ },
160+ ]);
161+ });
162+
163+ it("should not cache small string messages (<500 tokens)", () => {
164+ const smallContent = "a".repeat(100); // ~25 tokens
165+ const body = {
166+ messages: [{ content: smallContent }],
167+ };
168+
169+ const result = CACHING_STRATEGIES.optimized(body);
170+
171+ expect(result.messages).toEqual([{ content: smallContent }]);
172+ });
173+
174+ it("should cache large text items in array content", () => {
175+ const largeText = "a".repeat(2100); // ~525 tokens
176+ const smallText = "a".repeat(100); // ~25 tokens
177+ const body = {
178+ messages: [
179+ {
180+ content: [
181+ { type: "text", text: largeText },
182+ { type: "text", text: smallText },
183+ { type: "image", data: "image_data" },
184+ ],
185+ },
186+ ],
187+ };
188+
189+ const result = CACHING_STRATEGIES.optimized(body);
190+
191+ expect(result.messages).toEqual([
192+ {
193+ content: [
194+ {
195+ type: "text",
196+ text: largeText,
197+ cache_control: { type: "ephemeral" },
198+ },
199+ { type: "text", text: smallText },
200+ { type: "image", data: "image_data" },
201+ ],
202+ },
203+ ]);
204+ });
205+
206+ it("should handle complex message structure", () => {
207+ const body = {
208+ system: [{ text: "system" }],
209+ tools: [{ name: "tool" }],
210+ messages: [
211+ { content: "small content" },
212+ { content: "a".repeat(2100) }, // large content
213+ {
214+ content: [
215+ { type: "text", text: "a".repeat(2100) }, // large text
216+ { type: "image", data: "image" },
217+ ],
218+ },
219+ ],
220+ };
221+
222+ const result = CACHING_STRATEGIES.optimized(body);
223+
224+ expect(result.system).toEqual([
225+ { text: "system", cache_control: { type: "ephemeral" } },
226+ ]);
227+ expect(result.tools).toEqual([
228+ { name: "tool", cache_control: { type: "ephemeral" } },
229+ ]);
230+ expect(result.messages[0]).toEqual({ content: "small content" });
231+ expect(result.messages[1]).toEqual({
232+ content: [
233+ {
234+ type: "text",
235+ text: "a".repeat(2100),
236+ cache_control: { type: "ephemeral" },
237+ },
238+ ],
239+ });
240+ expect(result.messages[2].content[0]).toEqual({
241+ type: "text",
242+ text: "a".repeat(2100),
243+ cache_control: { type: "ephemeral" },
244+ });
245+ });
246+
247+ it("should handle empty or missing messages", () => {
248+ const body = {
249+ system: [{ text: "system" }],
250+ };
251+
252+ const result = CACHING_STRATEGIES.optimized(body);
253+
254+ expect(result.system).toEqual([
255+ { text: "system", cache_control: { type: "ephemeral" } },
256+ ]);
257+ expect(result.messages).toBeUndefined();
258+ });
259+
260+ it("should handle non-array messages", () => {
261+ const body = {
262+ system: [{ text: "system" }],
263+ messages: "not an array",
264+ };
265+
266+ const result = CACHING_STRATEGIES.optimized(body);
267+
268+ expect(result.system).toEqual([
269+ { text: "system", cache_control: { type: "ephemeral" } },
270+ ]);
271+ expect(result.messages).toBe("not an array");
272+ });
273+ });
274+
275+ describe("estimateTokenCount", () => {
276+ it("should estimate token count correctly", () => {
277+ // Test through the optimized strategy's behavior
278+ const smallContent = "a".repeat(100); // ~25 tokens
279+ const largeContent = "a".repeat(2100); // ~525 tokens
280+
281+ const bodySmall = { messages: [{ content: smallContent }] };
282+ const bodyLarge = { messages: [{ content: largeContent }] };
283+
284+ const resultSmall = CACHING_STRATEGIES.optimized(bodySmall);
285+ const resultLarge = CACHING_STRATEGIES.optimized(bodyLarge);
286+
287+ // Small content should not be cached (remains string)
288+ expect(resultSmall.messages[0].content).toBe(smallContent);
289+
290+ // Large content should be cached (converted to array)
291+ expect(Array.isArray(resultLarge.messages[0].content)).toBe(true);
292+ });
293+ });
294+
295+ describe("getAvailableStrategies", () => {
296+ it("should return all strategy names", () => {
297+ const strategies = getAvailableStrategies();
298+ expect(strategies).toEqual([
299+ "none",
300+ "systemOnly",
301+ "systemAndTools",
302+ "optimized",
303+ ]);
304+ });
305+ });
306+
307+ describe("getStrategyDescription", () => {
308+ it("should return correct descriptions for all strategies", () => {
309+ expect(getStrategyDescription("none")).toBe(
310+ "No caching - baseline for comparison",
311+ );
312+ expect(getStrategyDescription("systemOnly")).toBe(
313+ "Cache only system messages (current implementation)",
314+ );
315+ expect(getStrategyDescription("systemAndTools")).toBe(
316+ "Cache system messages and tool definitions (high impact)",
317+ );
318+ expect(getStrategyDescription("optimized")).toBe(
319+ "Intelligent caching - system, tools, and large content (best performance)",
320+ );
321+ });
322+ });
323+
324+ describe("CACHING_STRATEGIES", () => {
325+ it("should contain all expected strategies", () => {
326+ expect(Object.keys(CACHING_STRATEGIES)).toEqual([
327+ "none",
328+ "systemOnly",
329+ "systemAndTools",
330+ "optimized",
331+ ]);
332+ });
333+
334+ it("should have all strategies as functions", () => {
335+ Object.values(CACHING_STRATEGIES).forEach((strategy) => {
336+ expect(typeof strategy).toBe("function");
337+ });
338+ });
339+ });
340+
341+ describe("CachingStrategy type", () => {
342+ it("should accept valid caching strategy functions", () => {
343+ const customStrategy: CachingStrategy = (body) => ({
344+ ...body,
345+ custom: true,
346+ });
347+
348+ const input = { test: "value" };
349+ const result = customStrategy(input);
350+
351+ expect(result).toEqual({ test: "value", custom: true });
352+ });
353+ });
354+
355+ describe("CachingStrategyName type", () => {
356+ it("should work with valid strategy names", () => {
357+ const strategyNames: CachingStrategyName[] = [
358+ "none",
359+ "systemOnly",
360+ "systemAndTools",
361+ "optimized",
362+ ];
363+
364+ strategyNames.forEach((name) => {
365+ expect(typeof CACHING_STRATEGIES[name]).toBe("function");
366+ });
367+ });
368+ });
369+});
added packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts +147 −0
@@ -0,0 +1,147 @@
1+// Caching strategy type - transforms a clean Anthropic body by adding cache_control
2+export type CachingStrategy = (anthropicBody: any) => any;
3+
4+// Utility function to estimate token count
5+const estimateTokenCount = (text: string): number => Math.ceil(text.length / 4);
6+
7+// Strategy 1: No Caching (Baseline)
8+const noCachingStrategy: CachingStrategy = (body) => body;
9+
10+// Strategy 2: System Messages Only (Current Implementation)
11+const systemOnlyStrategy: CachingStrategy = (body) => {
12+ if (body.system && Array.isArray(body.system)) {
13+ return {
14+ ...body,
15+ system: body.system.map((item: any) => ({
16+ ...item,
17+ cache_control: { type: "ephemeral" },
18+ })),
19+ };
20+ }
21+ return body;
22+};
23+
24+// Strategy 3: System and Tools (High Impact)
25+const systemAndToolsStrategy: CachingStrategy = (body) => {
26+ const result = { ...body };
27+
28+ // Cache system messages
29+ if (result.system && Array.isArray(result.system)) {
30+ result.system = result.system.map((item: any) => ({
31+ ...item,
32+ cache_control: { type: "ephemeral" },
33+ }));
34+ }
35+
36+ // Cache tool definitions
37+ if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) {
38+ result.tools = result.tools.map((tool: any, index: number) => {
39+ if (index === result.tools.length - 1) {
40+ return {
41+ ...tool,
42+ cache_control: { type: "ephemeral" },
43+ };
44+ }
45+ return tool;
46+ });
47+ }
48+
49+ return result;
50+};
51+
52+// Strategy 4: Optimized (Intelligent Caching)
53+const optimizedStrategy: CachingStrategy = (body) => {
54+ const result = { ...body };
55+
56+ // Always cache system messages
57+ if (result.system && Array.isArray(result.system)) {
58+ result.system = result.system.map((item: any) => ({
59+ ...item,
60+ cache_control: { type: "ephemeral" },
61+ }));
62+ }
63+
64+ // Cache tool definitions
65+ if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) {
66+ result.tools = result.tools.map((tool: any, index: number) => {
67+ if (index === result.tools.length - 1) {
68+ return {
69+ ...tool,
70+ cache_control: { type: "ephemeral" },
71+ };
72+ }
73+ return tool;
74+ });
75+ }
76+
77+ // Cache large messages (>500 tokens)
78+ if (result.messages && Array.isArray(result.messages)) {
79+ result.messages = result.messages.map((message: any) => {
80+ if (message.content && typeof message.content === "string") {
81+ const tokens = estimateTokenCount(message.content);
82+ if (tokens > 500) {
83+ return {
84+ ...message,
85+ content: [
86+ {
87+ type: "text",
88+ text: message.content,
89+ cache_control: { type: "ephemeral" },
90+ },
91+ ],
92+ };
93+ }
94+ } else if (message.content && Array.isArray(message.content)) {
95+ const updatedContent = message.content.map((item: any) => {
96+ if (item.type === "text" && item.text) {
97+ const tokens = estimateTokenCount(item.text);
98+ if (tokens > 500) {
99+ return {
100+ ...item,
101+ cache_control: { type: "ephemeral" },
102+ };
103+ }
104+ }
105+ return item;
106+ });
107+
108+ return {
109+ ...message,
110+ content: updatedContent,
111+ };
112+ }
113+ return message;
114+ });
115+ }
116+
117+ return result;
118+};
119+
120+// Available caching strategies
121+export const CACHING_STRATEGIES = {
122+ none: noCachingStrategy,
123+ systemOnly: systemOnlyStrategy,
124+ systemAndTools: systemAndToolsStrategy,
125+ optimized: optimizedStrategy,
126+} as const;
127+
128+export type CachingStrategyName = keyof typeof CACHING_STRATEGIES;
129+
130+// Helper function to get available strategies
131+export const getAvailableStrategies = () => {
132+ return Object.keys(CACHING_STRATEGIES) as CachingStrategyName[];
133+};
134+
135+// Helper function to get strategy description
136+export const getStrategyDescription = (
137+ strategy: CachingStrategyName,
138+): string => {
139+ const descriptions = {
140+ none: "No caching - baseline for comparison",
141+ systemOnly: "Cache only system messages (current implementation)",
142+ systemAndTools: "Cache system messages and tool definitions (high impact)",
143+ optimized:
144+ "Intelligent caching - system, tools, and large content (best performance)",
145+ };
146+ return descriptions[strategy];
147+};
modified packages/openai-adapters/src/apis/Bedrock.ts +4 −1
@@ -16,6 +16,7 @@
1616 import {
1717 ChatCompletion,
1818 ChatCompletionChunk,
19+ ChatCompletionContentPartImage,
1920 ChatCompletionCreateParams,
2021 ChatCompletionCreateParamsNonStreaming,
2122 ChatCompletionCreateParamsStreaming,
@@ -120,7 +121,9 @@
120121 case "image_url":
121122 default:
122123 try {
123- const [mimeType, base64Data] = part.image_url.url.split(",");
124+ const [mimeType, base64Data] = (
125+ part as ChatCompletionContentPartImage
126+ ).image_url.url.split(",");
124127 const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
125128 if (
126129 format === ImageFormat.JPEG ||
added packages/openai-adapters/src/apis/ContinueProxy.ts +120 −0
@@ -0,0 +1,120 @@
1+import { OpenAI } from "openai/index";
2+import {
3+ ChatCompletionCreateParams,
4+ CompletionCreateParamsNonStreaming,
5+ CompletionCreateParamsStreaming,
6+} from "openai/resources/index";
7+import { z } from "zod";
8+import { ContinueProxyConfigSchema } from "../types.js";
9+import { FimCreateParamsStreaming, RerankCreateParams } from "./base.js";
10+import { OpenAIApi } from "./OpenAI.js";
11+
12+export interface ContinueProperties {
13+ apiKeyLocation?: string;
14+ envSecretLocations?: Record<string, string>;
15+ apiBase?: string;
16+ orgScopeId?: string | null;
17+ env?: Record<string, any>;
18+}
19+
20+export interface ProxyModelName {
21+ ownerSlug: string;
22+ packageSlug: string;
23+ provider: string;
24+ model: string;
25+}
26+
27+export class ContinueProxyApi extends OpenAIApi {
28+ // The apiKey and apiBase are set to the values for the proxy,
29+ // but we need to keep track of the actual values that the proxy will use
30+ // to call whatever LLM API is chosen
31+ private actualApiBase?: string;
32+
33+ // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
34+ private configEnv?: Record<string, any>;
35+
36+ // Store the continue proxy config separately
37+ private continueProxyConfig: z.infer<typeof ContinueProxyConfigSchema>;
38+
39+ constructor(config: z.infer<typeof ContinueProxyConfigSchema>) {
40+ // Convert ContinueProxyConfigSchema to OpenAIConfigSchema format
41+ const openaiConfig = {
42+ provider: "openai" as const,
43+ apiKey: config.apiKey,
44+ apiBase: config.env?.proxyUrl
45+ ? new URL("model-proxy/v1/", config.env?.proxyUrl).toString()
46+ : "https://api.continue.dev/model-proxy/v1/",
47+ requestOptions: config.requestOptions,
48+ };
49+
50+ super(openaiConfig);
51+
52+ this.continueProxyConfig = config;
53+ this.configEnv = config.env;
54+ this.actualApiBase = config.apiBase;
55+ }
56+
57+ protected extraBodyProperties(): Record<string, any> {
58+ const continueProperties: ContinueProperties = {
59+ apiKeyLocation: this.continueProxyConfig.env?.apiKeyLocation,
60+ envSecretLocations: this.continueProxyConfig.env?.envSecretLocations,
61+ apiBase: this.actualApiBase,
62+ orgScopeId: this.continueProxyConfig.env?.orgScopeId ?? null,
63+ env: this.configEnv,
64+ };
65+ return {
66+ continueProperties,
67+ };
68+ }
69+
70+ private modifyBodyWithContinueProperties<T extends Record<string, any>>(
71+ body: T,
72+ ): T {
73+ return {
74+ ...body,
75+ ...this.extraBodyProperties(),
76+ };
77+ }
78+
79+ modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T {
80+ // First apply OpenAI-specific modifications
81+ const modifiedBody = super.modifyChatBody(body);
82+ // Then add Continue properties
83+ return this.modifyBodyWithContinueProperties(modifiedBody);
84+ }
85+
86+ modifyCompletionBody<
87+ T extends
88+ | CompletionCreateParamsNonStreaming
89+ | CompletionCreateParamsStreaming,
90+ >(body: T): T {
91+ return this.modifyBodyWithContinueProperties(body);
92+ }
93+
94+ modifyFimBody<T extends FimCreateParamsStreaming>(body: T): T {
95+ const modifiedBody = super.modifyFimBody(body);
96+ return this.modifyBodyWithContinueProperties(modifiedBody);
97+ }
98+
99+ protected getHeaders(): Record<string, string> {
100+ return {
101+ "Content-Type": "application/json",
102+ Accept: "application/json",
103+ "x-api-key": this.continueProxyConfig.apiKey ?? "",
104+ Authorization: `Bearer ${this.continueProxyConfig.apiKey}`,
105+ };
106+ }
107+
108+ modifyEmbedBody<T extends OpenAI.Embeddings.EmbeddingCreateParams>(
109+ body: T,
110+ ): T {
111+ return this.modifyBodyWithContinueProperties(body);
112+ }
113+
114+ modifyRerankBody<T extends RerankCreateParams>(body: T): T {
115+ return {
116+ ...body,
117+ ...this.extraBodyProperties(),
118+ };
119+ }
120+}
modified packages/openai-adapters/src/apis/Gemini.ts +4 −1
@@ -3,6 +3,7 @@
33 import {
44 ChatCompletion,
55 ChatCompletionChunk,
6+ ChatCompletionContentPartImage,
67 ChatCompletionCreateParams,
78 ChatCompletionCreateParamsNonStreaming,
89 ChatCompletionCreateParamsStreaming,
@@ -75,7 +76,9 @@
7576 return {
7677 inlineData: {
7778 mimeType: "image/jpeg",
78- data: part.image_url?.url.split(",")[1],
79+ data: (part as ChatCompletionContentPartImage).image_url?.url.split(
80+ ",",
81+ )[1],
7982 },
8083 };
8184 }
modified packages/openai-adapters/src/apis/OpenAI.ts +57 −26
@@ -57,6 +57,37 @@
5757 return body;
5858 }
5959
60+ modifyCompletionBody<
61+ T extends
62+ | CompletionCreateParamsNonStreaming
63+ | CompletionCreateParamsStreaming,
64+ >(body: T): T {
65+ return body;
66+ }
67+
68+ modifyEmbedBody<T extends OpenAI.Embeddings.EmbeddingCreateParams>(
69+ body: T,
70+ ): T {
71+ return body;
72+ }
73+
74+ modifyFimBody<T extends FimCreateParamsStreaming>(body: T): T {
75+ return body;
76+ }
77+
78+ modifyRerankBody<T extends RerankCreateParams>(body: T): T {
79+ return body;
80+ }
81+
82+ protected getHeaders(): Record<string, string> {
83+ return {
84+ "Content-Type": "application/json",
85+ Accept: "application/json",
86+ "x-api-key": this.config.apiKey ?? "",
87+ Authorization: `Bearer ${this.config.apiKey}`,
88+ };
89+ }
90+
6091 async chatCompletionNonStream(
6192 body: ChatCompletionCreateParamsNonStreaming,
6293 signal: AbortSignal,
@@ -88,14 +119,20 @@
88119 body: CompletionCreateParamsNonStreaming,
89120 signal: AbortSignal,
90121 ): Promise<Completion> {
91- const response = await this.openai.completions.create(body, { signal });
122+ const response = await this.openai.completions.create(
123+ this.modifyCompletionBody(body),
124+ { signal },
125+ );
92126 return response;
93127 }
94128 async *completionStream(
95129 body: CompletionCreateParamsStreaming,
96130 signal: AbortSignal,
97131 ): AsyncGenerator<Completion, any, unknown> {
98- const response = await this.openai.completions.create(body, { signal });
132+ const response = await this.openai.completions.create(
133+ this.modifyCompletionBody(body),
134+ { signal },
135+ );
99136 for await (const result of response) {
100137 yield result;
101138 }
@@ -105,27 +142,23 @@
105142 signal: AbortSignal,
106143 ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
107144 const endpoint = new URL("fim/completions", this.apiBase);
145+ const modifiedBody = this.modifyFimBody(body);
108146 const resp = await customFetch(this.config.requestOptions)(endpoint, {
109147 method: "POST",
110148 body: JSON.stringify({
111- model: body.model,
112- prompt: body.prompt,
113- suffix: body.suffix,
114- max_tokens: body.max_tokens,
115- max_completion_tokens: (body as any).max_completion_tokens,
116- temperature: body.temperature,
117- top_p: body.top_p,
118- frequency_penalty: body.frequency_penalty,
119- presence_penalty: body.presence_penalty,
120- stop: body.stop,
149+ model: modifiedBody.model,
150+ prompt: modifiedBody.prompt,
151+ suffix: modifiedBody.suffix,
152+ max_tokens: modifiedBody.max_tokens,
153+ max_completion_tokens: (modifiedBody as any).max_completion_tokens,
154+ temperature: modifiedBody.temperature,
155+ top_p: modifiedBody.top_p,
156+ frequency_penalty: modifiedBody.frequency_penalty,
157+ presence_penalty: modifiedBody.presence_penalty,
158+ stop: modifiedBody.stop,
121159 stream: true,
122160 }),
123- headers: {
124- "Content-Type": "application/json",
125- Accept: "application/json",
126- "x-api-key": this.config.apiKey ?? "",
127- Authorization: `Bearer ${this.config.apiKey}`,
128- },
161+ headers: this.getHeaders(),
129162 signal,
130163 });
131164 for await (const chunk of streamSse(resp as any)) {
@@ -138,21 +171,19 @@
138171 async embed(
139172 body: OpenAI.Embeddings.EmbeddingCreateParams,
140173 ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
141- const response = await this.openai.embeddings.create(body);
174+ const response = await this.openai.embeddings.create(
175+ this.modifyEmbedBody(body),
176+ );
142177 return response;
143178 }
144179
145180 async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
146181 const endpoint = new URL("rerank", this.apiBase);
182+ const modifiedBody = this.modifyRerankBody(body);
147183 const response = await customFetch(this.config.requestOptions)(endpoint, {
148184 method: "POST",
149- body: JSON.stringify(body),
150- headers: {
151- "Content-Type": "application/json",
152- Accept: "application/json",
153- "x-api-key": this.config.apiKey ?? "",
154- Authorization: `Bearer ${this.config.apiKey}`,
155- },
185+ body: JSON.stringify(modifiedBody),
186+ headers: this.getHeaders(),
156187 });
157188 const data = await response.json();
158189 return data as any;
modified packages/openai-adapters/src/index.ts +4 −1
@@ -4,6 +4,7 @@
44 import { AzureApi } from "./apis/Azure.js";
55 import { BedrockApi } from "./apis/Bedrock.js";
66 import { CohereApi } from "./apis/Cohere.js";
7+import { ContinueProxyApi } from "./apis/ContinueProxy.js";
78 import { DeepSeekApi } from "./apis/DeepSeek.js";
89 import { GeminiApi } from "./apis/Gemini.js";
910 import { InceptionApi } from "./apis/Inception.js";
@@ -57,7 +58,9 @@
5758 return new WatsonXApi(config);
5859 case "llamastack":
5960 return new LlamastackApi(config);
60- case "x-ai":
61+ case "continue-proxy":
62+ return new ContinueProxyApi(config);
63+ case "xAI":
6164 return openAICompatible("https://api.x.ai/v1/", config);
6265 case "voyage":
6366 return openAICompatible("https://api.voyageai.com/v1/", config);
added packages/openai-adapters/src/test/adapter-test-utils.ts +321 −0
@@ -0,0 +1,321 @@
1+import { afterEach, describe, expect, test, vi } from "vitest";
2+import { BaseLlmApi } from "../apis/base.js";
3+import { LLMConfig } from "../types.js";
4+import { constructLlmApi } from "../index.js";
5+
6+interface AdapterTestCase {
7+ config: LLMConfig;
8+ methodToTest: keyof BaseLlmApi;
9+ params: any[];
10+ expectedRequest: {
11+ url: string;
12+ method: string;
13+ headers?: Record<string, string>;
14+ body?: Record<string, any>;
15+ };
16+ mockResponse?: any;
17+ mockStream?: any[];
18+}
19+
20+function createMockStream(mockStream: any[]) {
21+ const encoder = new TextEncoder();
22+ return new ReadableStream({
23+ start(controller) {
24+ for (const chunk of mockStream) {
25+ controller.enqueue(
26+ encoder.encode(
27+ `data: ${
28+ typeof chunk === "string" ? chunk : JSON.stringify(chunk)
29+ }\n\n`,
30+ ),
31+ );
32+ }
33+ controller.close();
34+ },
35+ });
36+}
37+
38+function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
39+ const mockFetch = vi.fn();
40+
41+ if (mockStream) {
42+ const stream = createMockStream(mockStream);
43+ mockFetch.mockResolvedValue(
44+ new Response(stream, {
45+ headers: {
46+ "Content-Type": "text/event-stream",
47+ },
48+ }),
49+ );
50+ } else {
51+ mockFetch.mockResolvedValue(
52+ new Response(JSON.stringify(mockResponse), {
53+ headers: { "Content-Type": "application/json" },
54+ }),
55+ );
56+ }
57+
58+ return mockFetch;
59+}
60+
61+function setupReadableStreamPolyfill() {
62+ // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
63+ // @ts-ignore
64+ const originalFrom = ReadableStream.from;
65+ // @ts-ignore
66+ ReadableStream.from = (body) => {
67+ if (body?.source) {
68+ return body;
69+ }
70+ return originalFrom(body);
71+ };
72+}
73+
74+async function executeAdapterMethod(
75+ api: BaseLlmApi,
76+ methodToTest: keyof BaseLlmApi,
77+ params: any[],
78+) {
79+ if (typeof (api as any)[methodToTest] !== "function") {
80+ throw new Error(
81+ `Method ${String(methodToTest)} does not exist on the adapter instance.`,
82+ );
83+ }
84+
85+ const result = await (api as any)[methodToTest](...params);
86+
87+ // If it's a generator/async iterator, consume it to trigger the HTTP request
88+ if (result?.next) {
89+ for await (const _ of result) {
90+ // Just consume the generator to trigger the request
91+ }
92+ }
93+}
94+
95+function assertFetchCall(mockFetch: any, expectedRequest: any) {
96+ expect(mockFetch).toHaveBeenCalledTimes(1);
97+ const [url, options] = mockFetch.mock.calls[0];
98+
99+ expect(url.toString()).toBe(expectedRequest.url);
100+ expect(options.method).toBe(expectedRequest.method);
101+
102+ if (expectedRequest.headers) {
103+ expect(options.headers).toEqual(
104+ expect.objectContaining(expectedRequest.headers),
105+ );
106+ }
107+
108+ if (expectedRequest.body) {
109+ const actualBody = JSON.parse(options.body as string);
110+ expect(actualBody).toEqual(expectedRequest.body);
111+ }
112+}
113+
114+export async function runAdapterTest(testCase: AdapterTestCase) {
115+ const {
116+ config,
117+ methodToTest,
118+ params,
119+ expectedRequest,
120+ mockResponse,
121+ mockStream,
122+ } = testCase;
123+
124+ const mockFetch = setupMockFetch(mockResponse, mockStream);
125+ setupReadableStreamPolyfill();
126+
127+ // Mock fetch globally before constructing the API
128+ vi.stubGlobal("fetch", mockFetch);
129+
130+ // For non-OpenAI adapters, mock the fetch package
131+ const fetchPackage = await import("@continuedev/fetch");
132+ if (fetchPackage.fetchwithRequestOptions) {
133+ vi.mocked(fetchPackage.fetchwithRequestOptions).mockImplementation(
134+ mockFetch as any,
135+ );
136+ }
137+
138+ const api = constructLlmApi(config);
139+ if (!api) {
140+ throw new Error(`Failed to construct API for provider: ${config.provider}`);
141+ }
142+
143+ // For OpenAI adapters, we need to replace the fetch on the OpenAI client
144+ if ((api as any).openai) {
145+ (api as any).openai.fetch = mockFetch;
146+ }
147+
148+ await executeAdapterMethod(api, methodToTest, params);
149+ assertFetchCall(mockFetch, expectedRequest);
150+}
151+
152+export interface AdapterTestConfig {
153+ providerName: string;
154+ config: LLMConfig;
155+ expectedApiBase: string;
156+ customHeaders?: Record<string, string>;
157+ customBodyOptions?: any;
158+}
159+
160+export const createAdapterTests = (testConfig: AdapterTestConfig) => {
161+ describe(testConfig.providerName, () => {
162+ afterEach(() => {
163+ vi.clearAllMocks();
164+ vi.unstubAllGlobals();
165+ });
166+
167+ test("should construct API correctly", () => {
168+ const api = constructLlmApi(testConfig.config);
169+ expect(api).toBeDefined();
170+ });
171+
172+ test("chatCompletionNonStream should send a valid request", async () => {
173+ await runAdapterTest({
174+ config: testConfig.config,
175+ methodToTest: "chatCompletionNonStream",
176+ params: [
177+ {
178+ model: "gpt-4",
179+ messages: [{ role: "user", content: "hello" }],
180+ },
181+ new AbortController().signal,
182+ ],
183+ expectedRequest: {
184+ url: `${testConfig.expectedApiBase}chat/completions`,
185+ method: "POST",
186+ headers: {
187+ ...testConfig.customHeaders,
188+ },
189+ body: {
190+ model: "gpt-4",
191+ messages: [{ role: "user", content: "hello" }],
192+ ...testConfig.customBodyOptions,
193+ },
194+ },
195+ mockResponse: {
196+ id: "test-id",
197+ object: "chat.completion",
198+ created: 1234567890,
199+ model: "gpt-4",
200+ choices: [
201+ {
202+ index: 0,
203+ message: {
204+ role: "assistant",
205+ content: "Hello! How can I help you today?",
206+ },
207+ finish_reason: "stop",
208+ },
209+ ],
210+ usage: {
211+ prompt_tokens: 10,
212+ completion_tokens: 15,
213+ total_tokens: 25,
214+ },
215+ },
216+ });
217+ });
218+
219+ test("chatCompletionStream should send a valid request", async () => {
220+ await runAdapterTest({
221+ config: testConfig.config,
222+ methodToTest: "chatCompletionStream",
223+ params: [
224+ {
225+ model: "gpt-4",
226+ messages: [{ role: "user", content: "hello" }],
227+ stream: true,
228+ },
229+ new AbortController().signal,
230+ ],
231+ expectedRequest: {
232+ url: `${testConfig.expectedApiBase}chat/completions`,
233+ method: "POST",
234+ headers: {
235+ ...testConfig.customHeaders,
236+ },
237+ body: {
238+ model: "gpt-4",
239+ messages: [{ role: "user", content: "hello" }],
240+ stream: true,
241+ ...testConfig.customBodyOptions,
242+ },
243+ },
244+ mockStream: [
245+ {
246+ id: "test-id",
247+ object: "chat.completion.chunk",
248+ created: 1234567890,
249+ model: "gpt-4",
250+ choices: [
251+ {
252+ index: 0,
253+ delta: { content: "Hello" },
254+ finish_reason: null,
255+ },
256+ ],
257+ },
258+ {
259+ id: "test-id",
260+ object: "chat.completion.chunk",
261+ created: 1234567890,
262+ model: "gpt-4",
263+ choices: [
264+ {
265+ index: 0,
266+ delta: { content: " world" },
267+ finish_reason: null,
268+ },
269+ ],
270+ },
271+ ],
272+ });
273+ });
274+
275+ test("embed should send a valid request", async () => {
276+ await runAdapterTest({
277+ config: testConfig.config,
278+ methodToTest: "embed",
279+ params: [
280+ {
281+ model: "text-embedding-ada-002",
282+ input: ["Hello", "World"],
283+ },
284+ ],
285+ expectedRequest: {
286+ url: `${testConfig.expectedApiBase}embeddings`,
287+ method: "POST",
288+ headers: {
289+ ...testConfig.customHeaders,
290+ },
291+ body: {
292+ model: "text-embedding-ada-002",
293+ input: ["Hello", "World"],
294+ encoding_format: "base64",
295+ ...testConfig.customBodyOptions,
296+ },
297+ },
298+ mockResponse: {
299+ object: "list",
300+ data: [
301+ {
302+ object: "embedding",
303+ embedding: [0.1, 0.2, 0.3],
304+ index: 0,
305+ },
306+ {
307+ object: "embedding",
308+ embedding: [0.4, 0.5, 0.6],
309+ index: 1,
310+ },
311+ ],
312+ model: "text-embedding-ada-002",
313+ usage: {
314+ prompt_tokens: 6,
315+ total_tokens: 6,
316+ },
317+ },
318+ });
319+ });
320+ });
321+};
added packages/openai-adapters/src/test/anthropic-adapter.vitest.ts +201 −0
@@ -0,0 +1,201 @@
1+import { describe, test, vi, expect, afterEach } from "vitest";
2+import { runAdapterTest } from "./adapter-test-utils.js";
3+
4+// Mock the fetch package
5+vi.mock("@continuedev/fetch", async () => {
6+ const actual = await vi.importActual("@continuedev/fetch");
7+ return {
8+ ...actual,
9+ fetchwithRequestOptions: vi.fn(),
10+ };
11+});
12+
13+describe("Anthropic Adapter Tests", () => {
14+ afterEach(() => {
15+ vi.clearAllMocks();
16+ vi.unstubAllGlobals();
17+ });
18+
19+ test("should construct API correctly", async () => {
20+ const { constructLlmApi } = await import("../index.js");
21+ const api = constructLlmApi({
22+ provider: "anthropic",
23+ apiKey: "test-api-key",
24+ });
25+ expect(api).toBeDefined();
26+ });
27+
28+ test("chatCompletionNonStream should send a valid request", async () => {
29+ await runAdapterTest({
30+ config: {
31+ provider: "anthropic",
32+ apiKey: "test-api-key",
33+ apiBase: "https://api.anthropic.com/v1/",
34+ },
35+ methodToTest: "chatCompletionNonStream",
36+ params: [
37+ {
38+ model: "claude-3-5-sonnet-20241022",
39+ messages: [{ role: "user", content: "hello" }],
40+ },
41+ new AbortController().signal,
42+ ],
43+ expectedRequest: {
44+ url: "https://api.anthropic.com/v1/messages",
45+ method: "POST",
46+ headers: {
47+ "Content-Type": "application/json",
48+ Accept: "application/json",
49+ "anthropic-version": "2023-06-01",
50+ "x-api-key": "test-api-key",
51+ },
52+ body: {
53+ messages: [{ role: "user", content: "hello" }],
54+ system: undefined,
55+ model: "claude-3-5-sonnet-20241022",
56+ max_tokens: 4096,
57+ stream: undefined,
58+ },
59+ },
60+ mockResponse: {
61+ id: "msg_test",
62+ type: "message",
63+ role: "assistant",
64+ content: [
65+ {
66+ type: "text",
67+ text: "Hello! How can I help you today?",
68+ },
69+ ],
70+ model: "claude-3-5-sonnet-20241022",
71+ stop_reason: "end_turn",
72+ stop_sequence: null,
73+ usage: {
74+ input_tokens: 10,
75+ output_tokens: 15,
76+ },
77+ },
78+ });
79+ });
80+
81+ test("chatCompletionStream should send a valid request", async () => {
82+ await runAdapterTest({
83+ config: {
84+ provider: "anthropic",
85+ apiKey: "test-api-key",
86+ apiBase: "https://api.anthropic.com/v1/",
87+ },
88+ methodToTest: "chatCompletionStream",
89+ params: [
90+ {
91+ model: "claude-3-5-sonnet-20241022",
92+ messages: [{ role: "user", content: "hello" }],
93+ stream: true,
94+ },
95+ new AbortController().signal,
96+ ],
97+ expectedRequest: {
98+ url: "https://api.anthropic.com/v1/messages",
99+ method: "POST",
100+ headers: {
101+ "Content-Type": "application/json",
102+ Accept: "application/json",
103+ "anthropic-version": "2023-06-01",
104+ "x-api-key": "test-api-key",
105+ },
106+ body: {
107+ messages: [{ role: "user", content: "hello" }],
108+ system: undefined,
109+ model: "claude-3-5-sonnet-20241022",
110+ max_tokens: 4096,
111+ stream: true,
112+ },
113+ },
114+ mockStream: [
115+ {
116+ type: "content_block_delta",
117+ delta: {
118+ type: "text_delta",
119+ text: "Hello",
120+ },
121+ },
122+ {
123+ type: "content_block_delta",
124+ delta: {
125+ type: "text_delta",
126+ text: " world",
127+ },
128+ },
129+ ],
130+ });
131+ });
132+
133+ test("chatCompletionStream with system message should convert correctly", async () => {
134+ await runAdapterTest({
135+ config: {
136+ provider: "anthropic",
137+ apiKey: "test-api-key",
138+ apiBase: "https://api.anthropic.com/v1/",
139+ },
140+ methodToTest: "chatCompletionStream",
141+ params: [
142+ {
143+ model: "claude-3-5-sonnet-20241022",
144+ messages: [
145+ { role: "system", content: "You are a helpful assistant." },
146+ { role: "user", content: "hello" },
147+ ],
148+ stream: true,
149+ },
150+ new AbortController().signal,
151+ ],
152+ expectedRequest: {
153+ url: "https://api.anthropic.com/v1/messages",
154+ method: "POST",
155+ headers: {
156+ "Content-Type": "application/json",
157+ Accept: "application/json",
158+ "anthropic-version": "2023-06-01",
159+ "x-api-key": "test-api-key",
160+ },
161+ body: {
162+ messages: [{ role: "user", content: "hello" }],
163+ system: [
164+ {
165+ type: "text",
166+ text: "You are a helpful assistant.",
167+ cache_control: { type: "ephemeral" },
168+ },
169+ ],
170+ model: "claude-3-5-sonnet-20241022",
171+ max_tokens: 4096,
172+ stream: true,
173+ },
174+ },
175+ mockStream: [
176+ {
177+ type: "content_block_delta",
178+ delta: {
179+ type: "text_delta",
180+ text: "Hello",
181+ },
182+ },
183+ ],
184+ });
185+ });
186+
187+ test("embed should throw not implemented error", async () => {
188+ const { constructLlmApi } = await import("../index.js");
189+ const api = constructLlmApi({
190+ provider: "anthropic",
191+ apiKey: "test-api-key",
192+ });
193+
194+ await expect(
195+ api!.embed({
196+ model: "text-embedding-ada-002",
197+ input: ["Hello", "World"],
198+ }),
199+ ).rejects.toThrow("Method not implemented.");
200+ });
201+});
modified packages/openai-adapters/src/test/main.test.ts +36 −29
@@ -4,12 +4,13 @@
44 import { INCEPTION_API_BASE } from "../apis/Inception.js";
55 import { OpenAIApi } from "../apis/OpenAI.js";
66 import { constructLlmApi } from "../index.js";
7-import { getLlmApi, testChat, testEmbed } from "./util.js";
7+import { getLlmApi, testChat, testEmbed, testFim, testRerank } from "./util.js";
88
99 dotenv.config();
1010
1111 export interface TestConfigOptions {
1212 skipTools: boolean;
13+ expectUsage?: boolean;
1314 }
1415
1516 function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) {
@@ -34,8 +35,12 @@
3435 testEmbed(api, model);
3536 }
3637
37- if (config.roles?.includes("embed")) {
38- testEmbed(api, model);
38+ if (config.roles?.includes("rerank")) {
39+ testRerank(api, model);
40+ }
41+
42+ if (config.roles?.includes("autocomplete")) {
43+ testFim(api, model);
3944 }
4045 }
4146
@@ -51,6 +56,10 @@
5156 model: "claude-3-5-haiku-latest",
5257 apiKey: process.env.ANTHROPIC_API_KEY!,
5358 roles: ["chat"],
59+ options: {
60+ skipTools: false,
61+ expectUsage: true,
62+ },
5463 },
5564 {
5665 provider: "gemini",
@@ -58,19 +67,19 @@
5867 apiKey: process.env.GEMINI_API_KEY!,
5968 roles: ["chat"],
6069 },
61- {
62- provider: "mistral",
63- model: "codestral-latest",
64- apiKey: process.env.MISTRAL_API_KEY!,
65- apiBase: "https://api.mistral.ai/v1",
66- roles: ["autocomplete"],
67- },
68- {
69- provider: "deepseek",
70- model: "deepseek-coder",
71- apiKey: process.env.DEEPSEEK_API_KEY!,
72- roles: ["autocomplete"],
73- },
70+ // {
71+ // provider: "mistral",
72+ // model: "codestral-latest",
73+ // apiKey: process.env.MISTRAL_API_KEY!,
74+ // apiBase: "https://api.mistral.ai/v1",
75+ // roles: ["autocomplete"],
76+ // },
77+ // {
78+ // provider: "deepseek",
79+ // model: "deepseek-coder",
80+ // apiKey: process.env.DEEPSEEK_API_KEY!,
81+ // roles: ["autocomplete"],
82+ // },
7483 {
7584 provider: "openai",
7685 model: "text-embedding-3-small",
@@ -112,28 +121,26 @@
112121 model: "gpt-4.1",
113122 apiBase: "https://continue-openai.openai.azure.com",
114123 apiKey: process.env.AZURE_OPENAI_GPT41_API_KEY,
124+ roles: ["chat"],
115125 env: {
116126 deployment: "gpt-4.1",
117127 apiVersion: "2024-02-15-preview",
118128 apiType: "azure-openai",
119129 },
120- roles: ["chat"],
121- },
122- {
123- provider: "azure",
124- model: "mistral-small-2503",
125- apiBase: "https://nate-0276-resource.services.ai.azure.com/models",
126- apiKey: process.env.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY,
127- roles: ["chat"],
128- options: { skipTools: true },
129130 },
130131 ];
131132
132-TESTS.forEach((config) => {
133- describe(`${config.provider}/${config.model}`, () => {
134- testConfig({ name: config.model, ...config });
133+if (process.env.IGNORE_API_KEY_TESTS === "true") {
134+ test("Skipping API key tests", () => {
135+ console.log("Skipping API key tests due to IGNORE_API_KEY_TESTS being set");
135136 });
136-});
137+} else {
138+ TESTS.forEach((config) => {
139+ describe(`${config.provider}/${config.model}`, () => {
140+ testConfig({ name: config.model, ...config });
141+ });
142+ });
143+}
137144
138145 describe("Configuration", () => {
139146 it("should configure DeepSeek OpenAI client with correct apiBase and apiKey", () => {
added packages/openai-adapters/src/test/openai-adapter.vitest.ts +28 −0
@@ -0,0 +1,28 @@
1+import { describe, vi } from "vitest";
2+import { createAdapterTests } from "./adapter-test-utils.js";
3+
4+// Mock the fetch package (not needed for OpenAI but required by the shared test utils)
5+vi.mock("@continuedev/fetch", async () => {
6+ const actual = await vi.importActual("@continuedev/fetch");
7+ return {
8+ ...actual,
9+ fetchwithRequestOptions: vi.fn(),
10+ };
11+});
12+
13+describe("OpenAI Adapter Tests", () => {
14+ createAdapterTests({
15+ providerName: "openai",
16+ config: {
17+ provider: "openai",
18+ apiKey: "test-api-key",
19+ apiBase: "https://api.openai.com/v1/",
20+ },
21+ expectedApiBase: "https://api.openai.com/v1/",
22+ customHeaders: {
23+ authorization: "Bearer test-api-key",
24+ "content-type": "application/json",
25+ accept: "application/json",
26+ },
27+ });
28+});
modified packages/openai-adapters/src/test/util.ts +31 −3
@@ -1,3 +1,4 @@
1+import { CompletionUsage } from "openai/resources/completions.mjs";
12 import { BaseLlmApi, constructLlmApi } from "../index.js";
23 import { LLMConfig } from "../types.js";
34 import { TestConfigOptions } from "./main.test.js";
@@ -88,12 +89,27 @@
8889 new AbortController().signal,
8990 );
9091 let completion = "";
92+ let usage: CompletionUsage | undefined = undefined;
9193 for await (const result of stream) {
92- completion += result.choices[0].delta.content ?? "";
93-
94- expect(result.choices.length).toBeGreaterThan(0);
94+ completion += result.choices[0]?.delta.content ?? "";
95+
96+ if (result.usage) {
97+ usage = result.usage;
98+ } else {
99+ // At the end we expect a final message without choices that shares usage
100+ expect(result.choices.length).toBeGreaterThan(0);
101+ }
95102 }
96103 expect(completion.length).toBeGreaterThan(0);
104+
105+ if (options?.expectUsage === true) {
106+ expect(usage).toBeDefined();
107+ expect(usage!.completion_tokens).toBeGreaterThan(0);
108+ expect(usage!.prompt_tokens).toBeGreaterThan(0);
109+ expect(usage!.total_tokens).toEqual(
110+ usage!.prompt_tokens + usage!.completion_tokens,
111+ );
112+ }
97113 });
98114
99115 test("should successfully stream multi-part chat with empty text", async () => {
@@ -122,6 +138,10 @@
122138 );
123139 let completion = "";
124140 for await (const result of stream) {
141+ // Skip usage chunks that have empty choices array
142+ if (result.choices.length === 0) {
143+ continue;
144+ }
125145 completion += result.choices[0].delta.content ?? "";
126146
127147 expect(result.choices.length).toBeGreaterThan(0);
@@ -246,6 +266,10 @@
246266 },
247267 new AbortController().signal,
248268 )) {
269+ // Skip usage chunks that have empty choices array
270+ if (chunk.choices.length === 0) {
271+ continue;
272+ }
249273 const toolCall = chunk.choices[0].delta.tool_calls?.[0];
250274 if (!toolCall) {
251275 continue;
@@ -317,6 +341,10 @@
317341 },
318342 new AbortController().signal,
319343 )) {
344+ // Skip usage chunks that have empty choices array
345+ if (chunk.choices.length === 0) {
346+ continue;
347+ }
320348 response += chunk.choices[0].delta.content ?? "";
321349 }
322350
modified packages/openai-adapters/src/types.ts +13 −1
@@ -53,7 +53,7 @@
5353 z.literal("sambanova"),
5454 z.literal("text-gen-webui"),
5555 z.literal("vllm"),
56- z.literal("x-ai"),
56+ z.literal("xAI"),
5757 z.literal("scaleway"),
5858 z.literal("ncompass"),
5959 z.literal("relace"),
@@ -91,6 +91,17 @@
9191 });
9292 export type LlamastackConfig = z.infer<typeof LlamastackConfigSchema>;
9393
94+export const ContinueProxyConfigSchema = BasePlusConfig.extend({
95+ provider: z.literal("continue-proxy"),
96+ env: z.object({
97+ apiKeyLocation: z.string().optional(),
98+ envSecretLocations: z.record(z.string(), z.string()).optional(),
99+ orgScopeId: z.string().nullable(),
100+ proxyUrl: z.string().optional(),
101+ }),
102+});
103+export type ContinueProxyConfig = z.infer<typeof ContinueProxyConfigSchema>;
104+
94105 export const MockConfigSchema = BasePlusConfig.extend({
95106 provider: z.literal("mock"),
96107 });
@@ -169,5 +180,6 @@
169180 MockConfigSchema,
170181 InceptionConfigSchema,
171182 LlamastackConfigSchema,
183+ ContinueProxyConfigSchema,
172184 ]);
173185 export type LLMConfig = z.infer<typeof LLMConfigSchema>;
modified packages/openai-adapters/src/util.ts +15 −0
@@ -38,6 +38,21 @@
3838 };
3939 }
4040
41+export function usageChatChunk(options: {
42+ model: string;
43+ id?: string | null;
44+ usage?: CompletionUsage;
45+}): ChatCompletionChunk {
46+ return {
47+ choices: [],
48+ usage: options.usage,
49+ created: Date.now(),
50+ id: options.id ?? "",
51+ model: options.model,
52+ object: "chat.completion.chunk",
53+ };
54+}
55+
4156 export function chatChunkFromDelta(options: {
4257 delta: ChatCompletionChunk.Choice["delta"];
4358 model: string;
added packages/openai-adapters/vitest.config.ts +15 −0
@@ -0,0 +1,15 @@
1+import { defineConfig } from "vitest/config";
2+
3+export default defineConfig({
4+ test: {
5+ environment: "node",
6+ globals: true,
7+ testTimeout: 10000,
8+ include: ["src/**/*.test.{ts,tsx}", "src/**/*.vitest.{ts,tsx}"],
9+ },
10+ resolve: {
11+ alias: {
12+ "(.+)\\.js": "$1",
13+ },
14+ },
15+});