From 30bfaa0904477e4db09420fdd6a9b54425a69fe5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 15:37:07 -0700 Subject: [PATCH 001/178] add initial fplab static contextualization code --- .../static-context/StaticContextService.ts | 181 ++++++++++++++++++ .../queries/hole-queries/typescript.scm | 36 ++++ .../queries/hole-queries/typescript.ts | 36 ++++ .../typescript-get-toplevel-headers.scm | 22 +++ .../typescript-get-toplevel-headers.ts | 22 +++ .../typescript-extract-identifiers.scm | 10 + .../typescript-extract-identifiers.ts | 10 + ...ipt-find-typedecl-given-typeidentifier.scm | 11 ++ ...ript-find-typedecl-given-typeidentifier.ts | 11 ++ .../context/static-context/types.ts | 23 +++ 10 files changed, 362 insertions(+) create mode 100644 core/autocomplete/context/static-context/StaticContextService.ts create mode 100644 core/autocomplete/context/static-context/queries/hole-queries/typescript.scm create mode 100644 core/autocomplete/context/static-context/queries/hole-queries/typescript.ts create mode 100644 core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.scm create mode 100644 core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.ts create mode 100644 core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.scm create mode 100644 core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.ts create mode 100644 core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm create mode 100644 core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.ts create mode 100644 core/autocomplete/context/static-context/types.ts diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts new file mode 100644 index 000000000..eb005d0cb --- /dev/null +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -0,0 +1,181 @@ +import * as fs from "fs/promises"; +import { IDE, Position } from "../../.."; +import { AutocompleteCodeSnippet, AutocompleteStaticSnippet } from "../../snippets/types"; +import { HelperVars } from "../../util/HelperVars"; +import { HoleContext, RelevantHeaders, RelevantTypes } from "./types"; +import { getAst } from "../../util/ast"; +import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; +import path from "path"; + +export class StaticContextService { + private readonly ide: IDE; + + constructor(ide: IDE) { + this.ide = ide; + } + + public async getContext( + helper: HelperVars + ): Promise { + // Get the three contexts holeContext, relevantTypes, relevantHeaders. + const holeContext = await this.getHoleContext(helper.filepath, helper.pos); + + const relevantTypes = await this.extractRelevantTypes( + holeContext.fullHoverResult, + holeContext.functionName, + holeContext.range.start.line, + new Map(), + holeContext.source, + new Map(), + ); + + let repo: string[] = []; + if (this.language === "typescript") { + repo = getAllTSFiles(this.repoPath); + } else if (this.language === "ocaml") { + repo = getAllOCamlFiles(this.repoPath); + } + + const relevantHeaders = await this.extractRelevantHeaders( + repo, + relevantTypes, + holeContext.functionTypeSpan, + holeContext.functionName, + this.repoPath + ); + + const relevantTypesToReturn: Map = new Map(); + relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => { + if (relevantTypesToReturn.has(src)) { + const updated = relevantTypesToReturn.get(src)!; + updated.push(v); + relevantTypesToReturn.set(src, updated); + } else { + relevantTypesToReturn.set(src, [v]); + } + }) + + + const relevantHeadersToReturn: Map = new Map(); + relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => { + if (relevantHeadersToReturn.has(src)) { + const updated = relevantHeadersToReturn.get(src)!; + if (!updated.includes(v)) { + updated.push(v); + } + relevantHeadersToReturn.set(src, updated); + } else { + relevantHeadersToReturn.set(src, [v]); + } + }) + + return { + holeType: "" + relevantTypes: "" + relevantHeaders: "" + }; + } + + private async getHoleContext( + sketchFilePath: string, + cursorPosition: Position + ): Promise { + // We need to inject the hole @ to trigger a treesitter error node. + const sketchFileContent = await fs.readFile(sketchFilePath, "utf8"); + const injectedContent = this.insertAtPosition( + sketchFileContent, + cursorPosition, + "@;" + ); + + // The hole's position is cursorPosition. + + // Use treesitter to parse. + const ast = await getAst(sketchFilePath, injectedContent); + if (!ast) { + throw new Error("failed to get ast"); + } + const language = getFullLanguageName(sketchFilePath); + const query = await getQueryForFile( + sketchFilePath, + path.join(`./queries/hole-queries/${language}.scm`) + ); + if (!query) { + throw new Error( + `failed to get query for file ${sketchFilePath} and language ${language}` + ); + } + + const captures = query.captures(ast.rootNode); + const res: HoleContext = { + fullHoverResult: "", + functionName: "", + functionTypeSpan: "", + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 52 }, + }, + source: `file://${sketchFilePath}`, + }; + for (const c of captures) { + const { name, node } = c; + // console.log(`${name} →`, node.text, node.startPosition, node.endPosition); + + switch (name) { + case "function.decl": { + res.fullHoverResult = node.text; + } + case "function.name": { + res.functionName = node.text; + } + case "function.type": { + res.functionTypeSpan = node.text; + res.range = { + start: { + line: node.startPosition.row, + character: node.startPosition.column, + }, + end: { + line: node.endPosition.row, + character: node.endPosition.column, + }, + }; + } + } + } + + return res; + } + + private async extractRelevantTypes(): Promise { + + } + + private async extractRelevantHeaders(): Promise { + + } + + + private insertAtPosition = ( + contents: string, + cursorPosition: { line: number, character: number }, + insertText: string + ): string => { + const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings + const { line, character } = cursorPosition; + + if (line < 0 || line >= lines.length) { + throw new Error("Invalid line number"); + } + + const targetLine = lines[line]; + if (character < 0 || character > targetLine.length) { + throw new Error("Invalid character index"); + } + + // Insert the text + lines[line] = targetLine.slice(0, character) + insertText + targetLine.slice(character); + + return lines.join("\n"); // Reconstruct the file + } +} diff --git a/core/autocomplete/context/static-context/queries/hole-queries/typescript.scm b/core/autocomplete/context/static-context/queries/hole-queries/typescript.scm new file mode 100644 index 000000000..e69122b07 --- /dev/null +++ b/core/autocomplete/context/static-context/queries/hole-queries/typescript.scm @@ -0,0 +1,36 @@ +;; Capture the variable/function name +(variable_declarator + name: (identifier) @function.name + type: (type_annotation + (function_type) @function.type)) + +;; Capture the full parameter list +(function_type + parameters: (formal_parameters) @function.params) + +;; Capture the type identifiers used in the parameters +(formal_parameters + (required_parameter + type: (type_annotation + (type_identifier) @param.type)) + (required_parameter + type: (type_annotation + (type_identifier) @param.type))) + +;; Capture the return type of the function +(function_type + return_type: (type_identifier) @return.type) + +;; Capture any parse errors (e.g., the `??`) +(ERROR) @error.node + +;; Capture the entire function declaration line +(lexical_declaration) @function.decl + +;; Matches import declarations like: import { A, B } from "module"; +(import_statement + (import_clause + (named_imports + (import_specifier + name: (identifier) @import.name))) + source: (string) @import.source) diff --git a/core/autocomplete/context/static-context/queries/hole-queries/typescript.ts b/core/autocomplete/context/static-context/queries/hole-queries/typescript.ts new file mode 100644 index 000000000..b0b4ae8ab --- /dev/null +++ b/core/autocomplete/context/static-context/queries/hole-queries/typescript.ts @@ -0,0 +1,36 @@ +export const TYPESCRIPT_HOLE_QUERY = `;; Capture the variable/function name +(variable_declarator + name: (identifier) @function.name + type: (type_annotation + (function_type) @function.type)) + +;; Capture the full parameter list +(function_type + parameters: (formal_parameters) @function.params) + +;; Capture the type identifiers used in the parameters +(formal_parameters + (required_parameter + type: (type_annotation + (type_identifier) @param.type)) + (required_parameter + type: (type_annotation + (type_identifier) @param.type))) + +;; Capture the return type of the function +(function_type + return_type: (type_identifier) @return.type) + +;; Capture any parse errors (e.g., the '?? ') +(ERROR) @error.node + +;; Capture the entire function declaration line +(lexical_declaration) @function.decl + +;; Matches import declarations like: import { A, B } from "module"; +(import_statement + (import_clause + (named_imports + (import_specifier + name: (identifier) @import.name))) + source: (string) @import.source)`; diff --git a/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.scm b/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.scm new file mode 100644 index 000000000..02b0bda77 --- /dev/null +++ b/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.scm @@ -0,0 +1,22 @@ +;; Match top-level `var`, `let`, or `const` declarations +(lexical_declaration + (variable_declarator + name: (identifier) @top.var.name + type: (type_annotation + (_) @top.var.type))) @top.var.decl + +(variable_declaration + (variable_declarator + name: (identifier) @top.var.name + type: (type_annotation + (_) @top.var.type))) @top.var.decl + +;; Match function declarations +(function_declaration + name: (identifier) @top.fn.name + parameters: (formal_parameters + (required_parameter + pattern: (identifier) @top.fn.param.name + type: (type_annotation (_) @top.fn.param.type)))* + + return_type: (type_annotation (_) @top.fn.type)?) @top.fn.decl diff --git a/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.ts b/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.ts new file mode 100644 index 000000000..bd0213af7 --- /dev/null +++ b/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.ts @@ -0,0 +1,22 @@ +export const TYPESCRIPT_GET_TOPLEVEL_HEADERS = `;; Match top-level 'var', 'let', or 'const' declarations +(lexical_declaration + (variable_declarator + name: (identifier) @top.var.name + type: (type_annotation + (_) @top.var.type))) @top.var.decl + +(variable_declaration + (variable_declarator + name: (identifier) @top.var.name + type: (type_annotation + (_) @top.var.type))) @top.var.decl + +;; Match function declarations +(function_declaration + name: (identifier) @top.fn.name + parameters: (formal_parameters + (required_parameter + pattern: (identifier) @top.fn.param.name + type: (type_annotation (_) @top.fn.param.type)))* + + return_type: (type_annotation (_) @top.fn.type)?) @top.fn.decl` diff --git a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.scm b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.scm new file mode 100644 index 000000000..b5051cb77 --- /dev/null +++ b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.scm @@ -0,0 +1,10 @@ +;; Capture the type alias name (left-hand side) +; (type_alias_declaration +; name: (type_identifier) @type.name) + +;; Capture all identifiers on the right-hand side (value), recursively +; (type_alias_declaration +; value: (_) @type.value) + +;; Match all identifiers inside the type value — deeply nested +(type_identifier) @type.identifier diff --git a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.ts b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.ts new file mode 100644 index 000000000..6e76a0a78 --- /dev/null +++ b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.ts @@ -0,0 +1,10 @@ +export const TYPESCRIPT_EXTRACT_IDENTIFIERS = `;; Capture the type alias name (left-hand side) +; (type_alias_declaration +; name: (type_identifier) @type.name) + +;; Capture all identifiers on the right-hand side (value), recursively +; (type_alias_declaration +; value: (_) @type.value) + +;; Match all identifiers inside the type value — deeply nested +(type_identifier) @type.identifier`; diff --git a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm new file mode 100644 index 000000000..b26180e05 --- /dev/null +++ b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm @@ -0,0 +1,11 @@ +(type_alias_declaration + name: (type_identifier) @type.identifier + value: (_) @type.value) + +(interface_declaration + name: (type_identifier) @type.identifier + body: (_) @type.value) + +(enum_declaration + name: (type_identifier) @type.identifier + body: (_) @type.value) diff --git a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.ts b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.ts new file mode 100644 index 000000000..4e1eabd7f --- /dev/null +++ b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.ts @@ -0,0 +1,11 @@ +export const TYPESCRIPT_FIND_TYPEDECL_GIVEN_TYPEIDENTIFIER = `(type_alias_declaration + name: (type_identifier) @type.identifier + value: (_) @type.value) + +(interface_declaration + name: (type_identifier) @type.identifier + body: (_) @type.value) + +(enum_declaration + name: (type_identifier) @type.identifier + body: (_) @type.value)`; diff --git a/core/autocomplete/context/static-context/types.ts b/core/autocomplete/context/static-context/types.ts new file mode 100644 index 000000000..7ddefda97 --- /dev/null +++ b/core/autocomplete/context/static-context/types.ts @@ -0,0 +1,23 @@ +import { Tree } from "web-tree-sitter"; +import { Range } from "../../.."; + +interface TypeSpanAndSourceFile { + typeSpan: string, + sourceFile: string, +} + +interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile { + ast: Tree +} + +export interface HoleContext { + fullHoverResult: string; + functionName: string; + functionTypeSpan: string; + range: Range; + source: string; +} + +export type RelevantTypes = Map; +export type RelevantHeaders = Set; + From be46653d1efbfb00bb2fd36da76d4b9d24e6718a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 15:37:51 -0700 Subject: [PATCH 002/178] pull in static context --- .../context/ContextRetrievalService.ts | 10 ++++++++++ core/autocomplete/snippets/getAllSnippets.ts | 3 +++ core/autocomplete/snippets/types.ts | 14 +++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 72e061fed..c21473d65 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -2,16 +2,19 @@ import { IDE } from "../.."; import { AutocompleteCodeSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; +import { StaticContextService } from "./static-context/StaticContextService"; export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; + private staticContextService: StaticContextService; constructor(private readonly ide: IDE) { this.importDefinitionsService = new ImportDefinitionsService(this.ide); @@ -19,6 +22,7 @@ export class ContextRetrievalService { this.importDefinitionsService, this.ide, ); + this.staticContextService = new StaticContextService(this.ide); } public async getSnippetsFromImportDefinitions( @@ -70,4 +74,10 @@ export class ContextRetrievalService { helper.treePath, ); } + + public async getStaticContextSnippets( + helper: HelperVars + ): Promise { + return this.staticContextService.getContext(helper); + } } diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index eaf287587..3db2c2542 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -1,3 +1,4 @@ +import { context } from "esbuild"; import { IDE } from "../../index"; import { findUriInDirs } from "../../util/uri"; import { ContextRetrievalService } from "../context/ContextRetrievalService"; @@ -123,6 +124,7 @@ export const getAllSnippets = async ({ ideSnippets, diffSnippets, clipboardSnippets, + staticSnippets ] = await Promise.all([ racePromise(contextRetrievalService.getRootPathSnippets(helper)), racePromise( @@ -133,6 +135,7 @@ export const getAllSnippets = async ({ : [], [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, racePromise(getClipboardSnippets(ide)), + racePromise(contextRetrievalService.getStaticContextSnippets(helper)) ]); return { diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts index e43b59862..3c2cddcb6 100644 --- a/core/autocomplete/snippets/types.ts +++ b/core/autocomplete/snippets/types.ts @@ -23,7 +23,19 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { copiedAt: string; } +type Filepath = string; +type RelevantType = string; +type RelevantHeader = string; + +export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Code; + holeType: string, + relevantTypes: Map, + relevantHeaders: Map +} + export type AutocompleteSnippet = | AutocompleteCodeSnippet | AutocompleteDiffSnippet - | AutocompleteClipboardSnippet; + | AutocompleteClipboardSnippet + | AutocompleteStaticSnippet; From a70c0b78417e256787be91665cf36633b4b4a885 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 16:00:33 -0700 Subject: [PATCH 003/178] add treesitter utility functions that are exclusively used for static context retrieval --- .../static-context/tree-sitter-utils.ts | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 core/autocomplete/context/static-context/tree-sitter-utils.ts diff --git a/core/autocomplete/context/static-context/tree-sitter-utils.ts b/core/autocomplete/context/static-context/tree-sitter-utils.ts new file mode 100644 index 000000000..12872e17f --- /dev/null +++ b/core/autocomplete/context/static-context/tree-sitter-utils.ts @@ -0,0 +1,164 @@ +import * as fs from "fs/promises"; +import Parser from "web-tree-sitter"; +import { getAst } from "../../util/ast"; +import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; +import path from "path"; + +export interface TypeDeclarationResult { + name: string; + fullText: string; + startLine: number; + startColumn: number; + endLine: number; + endColumn: number; + kind: string; +} + +export function findEnclosingTypeDeclaration( + sourceCode: string, + cursorLine: number, + cursorColumn: number, + ast: Parser.Tree +): TypeDeclarationResult | null { + const point = { row: cursorLine, column: cursorColumn }; + let node = ast.rootNode.descendantForPosition(point); + + while ( + node && + ![ + "type_alias_declaration", + "interface_declaration", + "enum_declaration", + ].includes(node.type) + ) { + if (!node.parent) return null; + node = node.parent; + } + + if (!node) return null; + + const nameNode = node.childForFieldName("name"); + const name = nameNode?.text ?? ""; + const fullText = sourceCode.slice(node.startIndex, node.endIndex); + + return { + name, + fullText, + startLine: node.startPosition.row, + startColumn: node.startPosition.column, + endLine: node.endPosition.row, + endColumn: node.endPosition.column, + kind: node.type, + }; +} + +export async function extractTopLevelDecls(currentFile: string, givenParser?: Parser) { + const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8")); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + let language; + if (givenParser) { + language = givenParser.getLanguage(); + } else { + language = getFullLanguageName(currentFile); + } + + const query = await getQueryForFile( + currentFile, + path.join( + __dirname, + "queries", + "relevant-headers-queries", + `${language}-get-toplevel-headers.scm` + ) + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}` + ); + } + return query.matches(ast.rootNode); +} + +export async function extractTopLevelDeclsWithFormatting(currentFile: string, givenParser?: Parser) { + const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8")); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + let language; + if (givenParser) { + language = givenParser.getLanguage(); + } else { + language = getFullLanguageName(currentFile); + } + + const query = await getQueryForFile( + currentFile, + path.join( + __dirname, + "queries", + "relevant-headers-queries", + `${language}-get-toplevel-headers.scm` + ) + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}` + ); + } + const matches = query.matches(ast.rootNode); + + const results = []; + + for (const match of matches) { + const item: { + declaration: string; + nodeType: string; + name: string; + declaredType: string; + returnType?: string; + } = { + declaration: "", + nodeType: "", + name: "", + declaredType: "", + }; + + for (const { name, node } of match.captures) { + if (name === "top.var.decl") { + item.nodeType = "variable"; + item.declaration = node.text; + + // Attempt to get the declared type (e.g., const x: string = ...) + const typeNode = node.descendantsOfType("type_annotation")[0]; + if (typeNode) { + item.declaredType = typeNode.text.replace(/^:\s*/, ""); + } + } else if (name === "top.var.name" || name === "top.fn.name") { + item.name = node.text; + } else if (name === "top.fn.decl") { + item.nodeType = "function"; + item.declaration = node.text; + + // Get the return type (e.g., function foo(): string) + const returnTypeNode = node.childForFieldName("return_type"); + if (returnTypeNode) { + item.returnType = returnTypeNode.text.replace(/^:\s*/, ""); + } + + // Get declaredType if needed (TypeScript style) + const nameNode = node.childForFieldName("name"); + if (nameNode && nameNode.nextSibling?.type === "type_annotation") { + item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, ""); + } + } + } + + if (item.name && item.declaration) { + results.push(item); + } + } + + return results; +} From e4b412acfeda3aac0e4683b1b308a2d07e91f009 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 16:01:00 -0700 Subject: [PATCH 004/178] export types --- core/autocomplete/context/static-context/types.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/autocomplete/context/static-context/types.ts b/core/autocomplete/context/static-context/types.ts index 7ddefda97..03f1f839d 100644 --- a/core/autocomplete/context/static-context/types.ts +++ b/core/autocomplete/context/static-context/types.ts @@ -1,12 +1,12 @@ import { Tree } from "web-tree-sitter"; import { Range } from "../../.."; -interface TypeSpanAndSourceFile { +export interface TypeSpanAndSourceFile { typeSpan: string, sourceFile: string, } -interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile { +export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile { ast: Tree } From fed6ba1591d6608dfb93a643d251cfaca356fc4d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 16:04:46 -0700 Subject: [PATCH 005/178] add gotoTypeDefinition method --- core/index.d.ts | 47 +++++++++++++++--------------- extensions/vscode/src/VsCodeIde.ts | 11 +++++++ 2 files changed, 35 insertions(+), 23 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index eb0de41d5..470b0eed9 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -49,13 +49,13 @@ export interface IndexingProgressUpdate { desc: string; shouldClearIndexes?: boolean; status: - | "loading" - | "indexing" - | "done" - | "failed" - | "paused" - | "disabled" - | "cancelled"; + | "loading" + | "indexing" + | "done" + | "failed" + | "paused" + | "disabled" + | "cancelled"; debugInfo?: string; } @@ -91,7 +91,7 @@ type RequiredLLMOptions = export interface ILLM extends Omit, - Required> { + Required> { get providerName(): string; get underlyingProviderName(): string; @@ -773,10 +773,10 @@ export interface IDE { getCurrentFile(): Promise< | undefined | { - isUntitled: boolean; - path: string; - contents: string; - } + isUntitled: boolean; + path: string; + contents: string; + } >; getPinnedFiles(): Promise; @@ -814,6 +814,7 @@ export interface IDE { // LSP gotoDefinition(location: Location): Promise; + gotoTypeDefinition(location: Location): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; @@ -955,11 +956,11 @@ export interface CustomCommand { export interface Prediction { type: "content"; content: - | string - | { - type: "text"; - text: string; - }[]; + | string + | { + type: "text"; + text: string; + }[]; } export interface ToolExtras { @@ -1455,9 +1456,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | ILLM; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | JSONModelDescription - | (CustomLLM | JSONModelDescription)[]; + | CustomLLM + | JSONModelDescription + | (CustomLLM | JSONModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -1551,9 +1552,9 @@ export type PackageDetailsSuccess = PackageDetails & { export type PackageDocsResult = { packageInfo: ParsedPackageInfo; } & ( - | { error: string; details?: never } - | { details: PackageDetailsSuccess; error?: never } -); + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } + ); export interface TerminalOptions { reuseTerminal?: boolean; diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 5ca51d183..a9ea5d9c6 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -88,6 +88,17 @@ class VsCodeIde implements IDE { return result; } + async gotoTypeDefinition(location: Location): Promise { + const result = await executeGotoProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeTypeDefinitionProvider", + }); + + return result; + } + onDidChangeActiveTextEditor(callback: (uri: string) => void): void { vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor) { From 1717fca23193b56e42e748218a10003e95b453b8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 16:05:01 -0700 Subject: [PATCH 006/178] add method to extract relevant types --- .../static-context/StaticContextService.ts | 126 +++++++++++++++++- 1 file changed, 123 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts index eb005d0cb..465be3456 100644 --- a/core/autocomplete/context/static-context/StaticContextService.ts +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -2,10 +2,11 @@ import * as fs from "fs/promises"; import { IDE, Position } from "../../.."; import { AutocompleteCodeSnippet, AutocompleteStaticSnippet } from "../../snippets/types"; import { HelperVars } from "../../util/HelperVars"; -import { HoleContext, RelevantHeaders, RelevantTypes } from "./types"; +import { HoleContext, RelevantHeaders, RelevantTypes, TypeSpanAndSourceFileAndAst } from "./types"; import { getAst } from "../../util/ast"; import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; import path from "path"; +import { findEnclosingTypeDeclaration } from "./tree-sitter-utils"; export class StaticContextService { private readonly ide: IDE; @@ -24,7 +25,6 @@ export class StaticContextService { holeContext.fullHoverResult, holeContext.functionName, holeContext.range.start.line, - new Map(), holeContext.source, new Map(), ); @@ -147,10 +147,130 @@ export class StaticContextService { return res; } - private async extractRelevantTypes(): Promise { + private async extractRelevantTypes( + declText: string, + typeName: string, + startLine: number, + currentFile: string, + foundContents: Map, // uri -> contents + ): Promise { + const foundSoFar = new Map(); // identifier -> [full hover result, source] + await this.extractRelevantTypesHelper( + declText, + typeName, + startLine, + foundSoFar, + currentFile, + foundContents, + ); + + return foundSoFar; } + private async extractRelevantTypesHelper( + declText: string, + typeName: string, + startLine: number, + foundSoFar: Map, // identifier -> [full hover result, source] + currentFile: string, + foundContents: Map, // uri -> contents + ) { + if (!foundSoFar.has(typeName)) { + const ast = await getAst(currentFile, declText); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + foundSoFar.set(typeName, { + typeSpan: declText, + sourceFile: currentFile.slice(7), + ast: ast, + }); + + const language = getFullLanguageName(currentFile); + const query = await getQueryForFile( + currentFile, + path.join( + __dirname, + "queries", + "relevant-types-queries", + `${language}-extract-identifiers.scm` + ) + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}` + ); + } + + const identifiers = query.captures(ast.rootNode); + + for (const { name, node } of identifiers) { + if (!foundSoFar.has(node.text)) { + try { + const typeDefinitionResult = + await this.ide.gotoTypeDefinition({ + filepath: currentFile, + position: { + character: node.startPosition.column, + line: startLine + node.startPosition.row, + }, + }); + + if (typeDefinitionResult.length != 0) { + const tdLocation = typeDefinitionResult[0]; + + let content = ""; + + if (foundContents.has(tdLocation.filepath)) { + content = foundContents.get(tdLocation.filepath)!; + } else { + content = await fs.readFile(tdLocation.filepath, "utf8"); + foundContents.set(tdLocation.filepath, content); + } + + const ast = await getAst(tdLocation.filepath, content); + if (!ast) { + throw new Error( + `failed to get ast for file ${tdLocation.filepath}` + ); + } + const decl = findEnclosingTypeDeclaration( + content, + tdLocation.range.start.line, + tdLocation.range.start.character, + ast + ); + if (!decl) { + // throw new Error(`failed to get decl for file ${tdLocation.uri}`); + console.error(`failed to get decl for file ${tdLocation.filepath}`); + } + + if (decl) { + await this.extractRelevantTypesHelper( + decl.fullText, + node.text, + tdLocation.range.start.line, + foundSoFar, + tdLocation.filepath, + foundContents, + ); + } else { + // console.log("decl not found"); + } + } else { + // console.log("td not found"); + } + } catch (err) { + console.log(err); + } + } else { + } + } + } + } + + private async extractRelevantHeaders(): Promise { } From 4e97c922d5d2968b8f9513865c346af77df705a7 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 19:54:19 -0700 Subject: [PATCH 007/178] move queries to extensions/vscode --- .../queries/hole-queries/typescript.ts | 36 ------------------- .../typescript-get-toplevel-headers.ts | 22 ------------ .../typescript-extract-identifiers.ts | 10 ------ ...ript-find-typedecl-given-typeidentifier.ts | 11 ------ .../hole-queries/typescript.scm | 0 .../typescript-get-toplevel-headers.scm | 0 .../typescript-extract-identifiers.scm | 0 ...ipt-find-typedecl-given-typeidentifier.scm | 0 8 files changed, 79 deletions(-) delete mode 100644 core/autocomplete/context/static-context/queries/hole-queries/typescript.ts delete mode 100644 core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.ts delete mode 100644 core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.ts delete mode 100644 core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.ts rename {core/autocomplete/context/static-context/queries => extensions/vscode/tree-sitter/static-context-queries}/hole-queries/typescript.scm (100%) rename {core/autocomplete/context/static-context/queries => extensions/vscode/tree-sitter/static-context-queries}/relevant-headers-queries/typescript-get-toplevel-headers.scm (100%) rename {core/autocomplete/context/static-context/queries => extensions/vscode/tree-sitter/static-context-queries}/relevant-types-queries/typescript-extract-identifiers.scm (100%) rename {core/autocomplete/context/static-context/queries => extensions/vscode/tree-sitter/static-context-queries}/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm (100%) diff --git a/core/autocomplete/context/static-context/queries/hole-queries/typescript.ts b/core/autocomplete/context/static-context/queries/hole-queries/typescript.ts deleted file mode 100644 index b0b4ae8ab..000000000 --- a/core/autocomplete/context/static-context/queries/hole-queries/typescript.ts +++ /dev/null @@ -1,36 +0,0 @@ -export const TYPESCRIPT_HOLE_QUERY = `;; Capture the variable/function name -(variable_declarator - name: (identifier) @function.name - type: (type_annotation - (function_type) @function.type)) - -;; Capture the full parameter list -(function_type - parameters: (formal_parameters) @function.params) - -;; Capture the type identifiers used in the parameters -(formal_parameters - (required_parameter - type: (type_annotation - (type_identifier) @param.type)) - (required_parameter - type: (type_annotation - (type_identifier) @param.type))) - -;; Capture the return type of the function -(function_type - return_type: (type_identifier) @return.type) - -;; Capture any parse errors (e.g., the '?? ') -(ERROR) @error.node - -;; Capture the entire function declaration line -(lexical_declaration) @function.decl - -;; Matches import declarations like: import { A, B } from "module"; -(import_statement - (import_clause - (named_imports - (import_specifier - name: (identifier) @import.name))) - source: (string) @import.source)`; diff --git a/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.ts b/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.ts deleted file mode 100644 index bd0213af7..000000000 --- a/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.ts +++ /dev/null @@ -1,22 +0,0 @@ -export const TYPESCRIPT_GET_TOPLEVEL_HEADERS = `;; Match top-level 'var', 'let', or 'const' declarations -(lexical_declaration - (variable_declarator - name: (identifier) @top.var.name - type: (type_annotation - (_) @top.var.type))) @top.var.decl - -(variable_declaration - (variable_declarator - name: (identifier) @top.var.name - type: (type_annotation - (_) @top.var.type))) @top.var.decl - -;; Match function declarations -(function_declaration - name: (identifier) @top.fn.name - parameters: (formal_parameters - (required_parameter - pattern: (identifier) @top.fn.param.name - type: (type_annotation (_) @top.fn.param.type)))* - - return_type: (type_annotation (_) @top.fn.type)?) @top.fn.decl` diff --git a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.ts b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.ts deleted file mode 100644 index 6e76a0a78..000000000 --- a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.ts +++ /dev/null @@ -1,10 +0,0 @@ -export const TYPESCRIPT_EXTRACT_IDENTIFIERS = `;; Capture the type alias name (left-hand side) -; (type_alias_declaration -; name: (type_identifier) @type.name) - -;; Capture all identifiers on the right-hand side (value), recursively -; (type_alias_declaration -; value: (_) @type.value) - -;; Match all identifiers inside the type value — deeply nested -(type_identifier) @type.identifier`; diff --git a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.ts b/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.ts deleted file mode 100644 index 4e1eabd7f..000000000 --- a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.ts +++ /dev/null @@ -1,11 +0,0 @@ -export const TYPESCRIPT_FIND_TYPEDECL_GIVEN_TYPEIDENTIFIER = `(type_alias_declaration - name: (type_identifier) @type.identifier - value: (_) @type.value) - -(interface_declaration - name: (type_identifier) @type.identifier - body: (_) @type.value) - -(enum_declaration - name: (type_identifier) @type.identifier - body: (_) @type.value)`; diff --git a/core/autocomplete/context/static-context/queries/hole-queries/typescript.scm b/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm similarity index 100% rename from core/autocomplete/context/static-context/queries/hole-queries/typescript.scm rename to extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm diff --git a/core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm similarity index 100% rename from core/autocomplete/context/static-context/queries/relevant-headers-queries/typescript-get-toplevel-headers.scm rename to extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm diff --git a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm similarity index 100% rename from core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-extract-identifiers.scm rename to extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm diff --git a/core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm similarity index 100% rename from core/autocomplete/context/static-context/queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm rename to extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm From 97788f2b9db43b906147fdbd9f251eae57cdab43 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 19:54:53 -0700 Subject: [PATCH 008/178] fix path to query --- .../static-context/tree-sitter-utils.ts | 69 +++++++++++++++---- 1 file changed, 57 insertions(+), 12 deletions(-) diff --git a/core/autocomplete/context/static-context/tree-sitter-utils.ts b/core/autocomplete/context/static-context/tree-sitter-utils.ts index 12872e17f..c7a9a20a3 100644 --- a/core/autocomplete/context/static-context/tree-sitter-utils.ts +++ b/core/autocomplete/context/static-context/tree-sitter-utils.ts @@ -66,12 +66,7 @@ export async function extractTopLevelDecls(currentFile: string, givenParser?: Pa const query = await getQueryForFile( currentFile, - path.join( - __dirname, - "queries", - "relevant-headers-queries", - `${language}-get-toplevel-headers.scm` - ) + `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm` ); if (!query) { throw new Error( @@ -95,12 +90,7 @@ export async function extractTopLevelDeclsWithFormatting(currentFile: string, gi const query = await getQueryForFile( currentFile, - path.join( - __dirname, - "queries", - "relevant-headers-queries", - `${language}-get-toplevel-headers.scm` - ) + `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm` ); if (!query) { throw new Error( @@ -162,3 +152,58 @@ export async function extractTopLevelDeclsWithFormatting(currentFile: string, gi return results; } + +export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string { + let paramsNode: Parser.SyntaxNode | undefined = undefined; + let returnNode: Parser.SyntaxNode | undefined = undefined; + + for (const capture of match.captures) { + if (capture.name === "top.fn.param.type") { + paramsNode = capture.node; + } else if (capture.name === "top.fn.type") { + returnNode = capture.node; + } + } + + if (!paramsNode) { + console.error(`extractFunctionTypeFromDecl: ${paramsNode} not found`); + throw new Error(`extractFunctionTypeFromDecl: ${paramsNode} not found`); + } + + if (!returnNode) { + console.error(`extractFunctionTypeFromDecl: ${returnNode} not found`); + throw new Error(`extractFunctionTypeFromDecl: ${returnNode} not found`); + } + + return `(${paramsNode!.text}) => ${returnNode!.text}`; +} + +export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode { + if ( + [ + "function_type", + "tuple_type", + "type_identifier", + "predefined_type", + ].includes(node.type) + ) { + return node; + } + + for (const child of node.namedChildren) { + const unwrapped = unwrapToBaseType(child!); + if ( + unwrapped !== child || + [ + "function_type", + "tuple_type", + "type_identifier", + "predefined_type", + ].includes(unwrapped.type) + ) { + return unwrapped; + } + } + + return node; +} From 408038275dbfd27adf9692469e095ff5e8d27d22 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 19:55:28 -0700 Subject: [PATCH 009/178] update types --- core/autocomplete/templating/filtering.ts | 17 +++++++++++++---- core/autocomplete/templating/formatting.ts | 9 +++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index 7f69398c6..e3eb6f1fe 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -3,6 +3,7 @@ import { SnippetPayload } from "../snippets"; import { AutocompleteCodeSnippet, AutocompleteSnippet, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; @@ -30,9 +31,9 @@ const shuffleArray = (array: T[]): T[] => { }; function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteCodeSnippet[], + snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[], caretWindow: string, -): AutocompleteCodeSnippet[] { +): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] { return snippets.filter( (s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()), ); @@ -49,7 +50,11 @@ export const getSnippets = ( diff: payload.diffSnippets, base: shuffleArray( filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], + [ + ...payload.rootPathSnippets, + ...payload.importDefinitionSnippets, + ...payload.staticSnippet, + ], helper.prunedCaretWindow, ), ), @@ -98,7 +103,11 @@ export const getSnippets = ( defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override snippets: shuffleArray( filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], + [ + ...payload.rootPathSnippets, + ...payload.importDefinitionSnippets, + ...payload.staticSnippet, + ], helper.prunedCaretWindow, ), ), diff --git a/core/autocomplete/templating/formatting.ts b/core/autocomplete/templating/formatting.ts index 2a91ad438..583873c2d 100644 --- a/core/autocomplete/templating/formatting.ts +++ b/core/autocomplete/templating/formatting.ts @@ -5,6 +5,7 @@ import { AutocompleteDiffSnippet, AutocompleteSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; @@ -51,6 +52,12 @@ const formatDiffSnippet = ( return snippet; }; +const formatStaticSnippet = ( + snippet: AutocompleteStaticSnippet, +): AutocompleteStaticSnippet => { + return snippet; +}; + const commentifySnippet = ( helper: HelperVars, snippet: AutocompleteSnippet, @@ -81,6 +88,8 @@ export const formatSnippets = ( return formatDiffSnippet(snippet); case AutocompleteSnippetType.Clipboard: return formatClipboardSnippet(snippet, workspaceDirs); + case AutocompleteSnippetType.Static: + return formatStaticSnippet(snippet); } }) .map((item) => { From 4e9690e058b9dfd275a92bafd46483addca83a25 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 19:55:42 -0700 Subject: [PATCH 010/178] move types from snippets to static --- core/autocomplete/context/static-context/types.ts | 15 ++++++++++++--- core/autocomplete/snippets/types.ts | 10 ++-------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/core/autocomplete/context/static-context/types.ts b/core/autocomplete/context/static-context/types.ts index 03f1f839d..2400c2a7a 100644 --- a/core/autocomplete/context/static-context/types.ts +++ b/core/autocomplete/context/static-context/types.ts @@ -2,12 +2,12 @@ import { Tree } from "web-tree-sitter"; import { Range } from "../../.."; export interface TypeSpanAndSourceFile { - typeSpan: string, - sourceFile: string, + typeSpan: string; + sourceFile: string; } export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile { - ast: Tree + ast: Tree; } export interface HoleContext { @@ -21,3 +21,12 @@ export interface HoleContext { export type RelevantTypes = Map; export type RelevantHeaders = Set; +export type Filepath = string; +export type RelevantType = string; +export type RelevantHeader = string; + +export interface StaticContext { + holeType: string; + relevantTypes: Map; + relevantHeaders: Map; +} diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts index 3c2cddcb6..c486c0106 100644 --- a/core/autocomplete/snippets/types.ts +++ b/core/autocomplete/snippets/types.ts @@ -2,6 +2,7 @@ export enum AutocompleteSnippetType { Code = "code", Diff = "diff", Clipboard = "clipboard", + Static = "static", } interface BaseAutocompleteSnippet { @@ -23,15 +24,8 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { copiedAt: string; } -type Filepath = string; -type RelevantType = string; -type RelevantHeader = string; - export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet { - type: AutocompleteSnippetType.Code; - holeType: string, - relevantTypes: Map, - relevantHeaders: Map + type: AutocompleteSnippetType.Static; } export type AutocompleteSnippet = From a2c1c6312e722ca6673c3815de4f13a002283eb0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 19:55:53 -0700 Subject: [PATCH 011/178] conform to interface --- core/autocomplete/context/ContextRetrievalService.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index c21473d65..8cf63d8b9 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -77,7 +77,7 @@ export class ContextRetrievalService { public async getStaticContextSnippets( helper: HelperVars - ): Promise { + ): Promise { return this.staticContextService.getContext(helper); } } From 29f9c726dd306af47ae78b5def6cdb074c0e227a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 19:56:02 -0700 Subject: [PATCH 012/178] static contextualization works --- .../static-context/StaticContextService.ts | 681 +++++++++++++++--- core/autocomplete/snippets/getAllSnippets.ts | 8 +- 2 files changed, 592 insertions(+), 97 deletions(-) diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts index 465be3456..4b9b41917 100644 --- a/core/autocomplete/context/static-context/StaticContextService.ts +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -1,12 +1,29 @@ import * as fs from "fs/promises"; -import { IDE, Position } from "../../.."; -import { AutocompleteCodeSnippet, AutocompleteStaticSnippet } from "../../snippets/types"; -import { HelperVars } from "../../util/HelperVars"; -import { HoleContext, RelevantHeaders, RelevantTypes, TypeSpanAndSourceFileAndAst } from "./types"; -import { getAst } from "../../util/ast"; -import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; import path from "path"; -import { findEnclosingTypeDeclaration } from "./tree-sitter-utils"; +import Parser from "web-tree-sitter"; +import { IDE, Position } from "../../.."; +import { localPathOrUriToPath } from "../../../util/pathToUri"; +import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; +import { + AutocompleteSnippetType, + AutocompleteStaticSnippet, +} from "../../snippets/types"; +import { getAst } from "../../util/ast"; +import { HelperVars } from "../../util/HelperVars"; +import { + extractFunctionTypeFromDecl, + extractTopLevelDecls, + findEnclosingTypeDeclaration, + unwrapToBaseType, +} from "./tree-sitter-utils"; +import { + HoleContext, + RelevantHeaders, + RelevantTypes, + StaticContext, + TypeSpanAndSourceFile, + TypeSpanAndSourceFileAndAst, +} from "./types"; export class StaticContextService { private readonly ide: IDE; @@ -15,9 +32,58 @@ export class StaticContextService { this.ide = ide; } + public logAutocompleteStaticSnippet( + ctx: StaticContext, + label = "Static Snippet", + ) { + console.log(`=== ${label} ===`); + console.log("Hole Type:", ctx.holeType); + + console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`); + ctx.relevantTypes.forEach((types, filepath) => { + console.log(` 📁 ${filepath}`); + types.forEach((type) => console.log(` • ${type}`)); + }); + + console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`); + ctx.relevantHeaders.forEach((headers, filepath) => { + console.log(` 📁 ${filepath}`); + headers.forEach((header) => console.log(` • ${header}`)); + }); + } + + public static formatAutocompleteStaticSnippet(ctx: StaticContext): string { + let output = `AutocompleteStaticSnippet:\n`; + output += ` holeType: ${ctx.holeType}\n`; + + output += ` relevantTypes:\n`; + if (ctx.relevantTypes.size === 0) { + output += ` (none)\n`; + } else { + ctx.relevantTypes.forEach((types, filepath) => { + output += ` ${filepath}: [${types.join(", ")}]\n`; + }); + } + + output += ` relevantHeaders:\n`; + if (ctx.relevantHeaders.size === 0) { + output += ` (none)\n`; + } else { + ctx.relevantHeaders.forEach((headers, filepath) => { + output += ` ${filepath}: [${headers.join(", ")}]\n`; + }); + } + + return output; + } + public async getContext( - helper: HelperVars - ): Promise { + helper: HelperVars, + ): Promise { + const start = Date.now(); + const tsFiles = await this.getTypeScriptFilesFromWorkspaces( + helper.workspaceUris, + ); // Get the three contexts holeContext, relevantTypes, relevantHeaders. const holeContext = await this.getHoleContext(helper.filepath, helper.pos); @@ -29,22 +95,23 @@ export class StaticContextService { new Map(), ); - let repo: string[] = []; - if (this.language === "typescript") { - repo = getAllTSFiles(this.repoPath); - } else if (this.language === "ocaml") { - repo = getAllOCamlFiles(this.repoPath); - } + // if (this.language === "typescript") { + // repo = getAllTSFiles(this.repoPath); + // } else if (this.language === "ocaml") { + // repo = getAllOCamlFiles(this.repoPath); + // } + // const relevantHeaders = await this.extractRelevantHeaders( - repo, + tsFiles, relevantTypes, holeContext.functionTypeSpan, - holeContext.functionName, - this.repoPath ); - const relevantTypesToReturn: Map = new Map(); + const relevantTypesToReturn: Map = new Map< + string, + string[] + >(); relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => { if (relevantTypesToReturn.has(src)) { const updated = relevantTypesToReturn.get(src)!; @@ -53,10 +120,12 @@ export class StaticContextService { } else { relevantTypesToReturn.set(src, [v]); } - }) + }); - - const relevantHeadersToReturn: Map = new Map(); + const relevantHeadersToReturn: Map = new Map< + string, + string[] + >(); relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => { if (relevantHeadersToReturn.has(src)) { const updated = relevantHeadersToReturn.get(src)!; @@ -67,25 +136,38 @@ export class StaticContextService { } else { relevantHeadersToReturn.set(src, [v]); } - }) + }); - return { - holeType: "" - relevantTypes: "" - relevantHeaders: "" + const ctx = { + holeType: holeContext.functionTypeSpan, + relevantTypes: relevantTypesToReturn, + relevantHeaders: relevantHeadersToReturn, }; + const end = Date.now(); + + this.logAutocompleteStaticSnippet(ctx); + + console.log(end - start); + + return [ + { + type: AutocompleteSnippetType.Static, + content: StaticContextService.formatAutocompleteStaticSnippet(ctx), + }, + ]; } private async getHoleContext( sketchFilePath: string, - cursorPosition: Position + cursorPosition: Position, ): Promise { // We need to inject the hole @ to trigger a treesitter error node. + sketchFilePath = localPathOrUriToPath(sketchFilePath); const sketchFileContent = await fs.readFile(sketchFilePath, "utf8"); const injectedContent = this.insertAtPosition( sketchFileContent, cursorPosition, - "@;" + "@;", ); // The hole's position is cursorPosition. @@ -98,11 +180,11 @@ export class StaticContextService { const language = getFullLanguageName(sketchFilePath); const query = await getQueryForFile( sketchFilePath, - path.join(`./queries/hole-queries/${language}.scm`) + `static-context-queries/hole-queries/${language}.scm`, ); if (!query) { throw new Error( - `failed to get query for file ${sketchFilePath} and language ${language}` + `getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`, ); } @@ -190,96 +272,425 @@ export class StaticContextService { const language = getFullLanguageName(currentFile); const query = await getQueryForFile( currentFile, - path.join( - __dirname, - "queries", - "relevant-types-queries", - `${language}-extract-identifiers.scm` - ) + `static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`, ); if (!query) { throw new Error( - `failed to get query for file ${currentFile} and language ${language}` + `failed to get query for file ${currentFile} and language ${language}`, ); } const identifiers = query.captures(ast.rootNode); for (const { name, node } of identifiers) { - if (!foundSoFar.has(node.text)) { - try { - const typeDefinitionResult = - await this.ide.gotoTypeDefinition({ - filepath: currentFile, - position: { - character: node.startPosition.column, - line: startLine + node.startPosition.row, - }, - }); + if (foundSoFar.has(node.text)) continue; - if (typeDefinitionResult.length != 0) { - const tdLocation = typeDefinitionResult[0]; + try { + const typeDefinitionResult = await this.ide.gotoTypeDefinition({ + filepath: currentFile, + position: { + character: node.startPosition.column, + line: startLine + node.startPosition.row, + }, + }); - let content = ""; + if (typeDefinitionResult.length > 0) { + const tdLocation = typeDefinitionResult[0]; - if (foundContents.has(tdLocation.filepath)) { - content = foundContents.get(tdLocation.filepath)!; - } else { - content = await fs.readFile(tdLocation.filepath, "utf8"); - foundContents.set(tdLocation.filepath, content); - } + let content = ""; - const ast = await getAst(tdLocation.filepath, content); - if (!ast) { - throw new Error( - `failed to get ast for file ${tdLocation.filepath}` - ); - } - const decl = findEnclosingTypeDeclaration( - content, - tdLocation.range.start.line, - tdLocation.range.start.character, - ast - ); - if (!decl) { - // throw new Error(`failed to get decl for file ${tdLocation.uri}`); - console.error(`failed to get decl for file ${tdLocation.filepath}`); - } - - if (decl) { - await this.extractRelevantTypesHelper( - decl.fullText, - node.text, - tdLocation.range.start.line, - foundSoFar, - tdLocation.filepath, - foundContents, - ); - } else { - // console.log("decl not found"); - } + if (foundContents.has(tdLocation.filepath)) { + content = foundContents.get(tdLocation.filepath)!; } else { - // console.log("td not found"); + content = await fs.readFile( + localPathOrUriToPath(tdLocation.filepath), + "utf8", + ); + foundContents.set(tdLocation.filepath, content); } - } catch (err) { - console.log(err); + + const ast = await getAst(tdLocation.filepath, content); + if (!ast) { + throw new Error( + `failed to get ast for file ${tdLocation.filepath}`, + ); + } + const decl = findEnclosingTypeDeclaration( + content, + tdLocation.range.start.line, + tdLocation.range.start.character, + ast, + ); + if (!decl) { + // throw new Error(`failed to get decl for file ${tdLocation.uri}`); + console.error( + `failed to get decl for file ${tdLocation.filepath}`, + ); + } + + if (decl) { + await this.extractRelevantTypesHelper( + decl.fullText, + node.text, + tdLocation.range.start.line, + foundSoFar, + tdLocation.filepath, + foundContents, + ); + } else { + // console.log("decl not found"); + } + } else { + // console.log("td not found"); } - } else { + } catch (err) { + console.log(err); } } } } + private async extractRelevantHeaders( + sources: string[], + relevantTypes: Map, + holeType: string, + ): Promise { + const relevantContext = new Set(); + // NOTE: This is necessary because TypeScript sucks. + // There is no way to compare objects by value, + // so sets of objects starts to accumulate tons of duplicates. + const relevantContextMap = new Map(); + const foundNormalForms = new Map(); - private async extractRelevantHeaders(): Promise { + const targetTypes = await this.generateTargetTypes(relevantTypes, holeType); + for (const source of sources) { + const topLevelDecls = await extractTopLevelDecls(source); + for (const tld of topLevelDecls) { + // pattern 0 is let/const, 1 is var, 2 is fun + // if (!seenDecls.has(JSON.stringify()) { + const originalDeclText = + tld.pattern === 2 + ? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text + : tld.captures.find((d) => d.name === "top.var.decl")!.node.text; + + if (tld.pattern === 2) { + // build a type span + // TODO: this fails sometimes with Cannot read properties of undefined (reading 'text') + // most likely due to my scm query and how I'm not attaching param name along with param type + const funcType = extractFunctionTypeFromDecl(tld); + const wrapped = `type __TMP = ${funcType};`; + + const ast = await getAst("file.ts", wrapped); + if (!ast) { + throw new Error(`failed to generate ast for ${wrapped}`); + } + + console.log(ast.rootNode); + const alias = ast.rootNode.namedChild(0); + console.log(alias); + if (!alias || alias.type !== "type_alias_declaration") { + throw new Error( + "extractRelevantHeaders: Failed to parse type alias", + ); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + + await this.extractRelevantHeadersHelper( + originalDeclText, + baseNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } else { + const varTypNode = tld.captures.find( + (d) => d.name === "top.var.type", + )!.node; + await this.extractRelevantHeadersHelper( + originalDeclText, + varTypNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } + } + + for (const v of relevantContextMap.values()) { + relevantContext.add(v); + } + + return relevantContext; } + private async extractRelevantHeadersHelper( + originalDeclText: string, + node: Parser.SyntaxNode, + targetTypes: Set, + relevantTypes: Map, + relevantContext: Set, + relevantContextMap: Map, + foundNormalForms: Map, + source: string, + ) { + for (const typ of targetTypes) { + if ( + await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms) + ) { + const ctx = { typeSpan: originalDeclText, sourceFile: source }; + relevantContextMap.set(JSON.stringify(ctx), ctx); + } + + if (node.type === "function_type") { + const retTypeNode = node.namedChildren.find( + (c) => c && c.type === "return_type", + ); + if (retTypeNode) { + await this.extractRelevantHeadersHelper( + originalDeclText, + retTypeNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } else if (node.type === "tuple_type") { + for (const c of node.namedChildren) { + await this.extractRelevantHeadersHelper( + originalDeclText, + c!, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } + } + } + + private async generateTargetTypes( + relevantTypes: Map, + holeType: string, + ) { + const targetTypes = new Set(); + // const ast = relevantTypes.get(holeIdentifier)!.ast; + const ast = await getAst("file.ts", `type T = ${holeType};`); + if (!ast) { + throw new Error(`failed to generate ast for ${holeType}`); + } + + const alias = ast.rootNode.namedChild(0); + if (!alias || alias.type !== "type_alias_declaration") { + throw new Error("generateTargetTypes: Failed to parse type alias"); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + targetTypes.add(baseNode); + await this.generateTargetTypesHelper( + relevantTypes, + holeType, + targetTypes, + baseNode, + ); + + return targetTypes; + } + + private async generateTargetTypesHelper( + relevantTypes: Map, + currType: string, + targetTypes: Set, + node: Parser.SyntaxNode | null, + ): Promise { + if (!node) return; + + if (node.type === "function_type") { + const returnType = node.childForFieldName("return_type"); + if (returnType) { + targetTypes.add(returnType); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + returnType, + ); + } + } + + if (node.type === "tuple_type") { + for (const child of node.namedChildren) { + if (child) { + targetTypes.add(child); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + child, + ); + } + } + } + + if (relevantTypes.has(node.text)) { + // const ast = relevantTypes.get(node.text)!.ast; + const typeSpan = relevantTypes.get(node.text)?.typeSpan; + + // const ast = await getAst("file.ts", `type T = ${typeSpan}`); + const ast = await getAst("file.ts", typeSpan!); + if (!ast) { + throw new Error(`failed to generate ast for ${typeSpan}`); + } + + const alias = ast.rootNode.namedChild(0); + if (!alias || alias.type !== "type_alias_declaration") { + throw new Error( + "generateTargetTypesHelper: Failed to parse type alias", + ); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + baseNode, + ); + } + + // if (node.type === "type_identifier" || node.type === "predefined_type") { + // return [node.text]; + // } + + return; + } + + private async isTypeEquivalent( + node: Parser.SyntaxNode, + typ: Parser.SyntaxNode, + relevantTypes: Map, + foundNormalForms: Map, + ): Promise { + if (!node || !typ) { + return false; + } + let normT1 = ""; + let normT2 = ""; + if (foundNormalForms.has(node.text)) { + // console.log("found t1", true) + normT1 = foundNormalForms.get(node.text)!; + } else { + // console.log("not found t1", false) + normT1 = await this.normalize(node, relevantTypes); + foundNormalForms.set(node.text, normT1); + } + if (foundNormalForms.has(typ.text)) { + // console.log("found t2", true) + normT2 = foundNormalForms.get(typ.text)!; + } else { + // console.log("not found t2", false) + normT2 = await this.normalize(typ, relevantTypes); + foundNormalForms.set(typ.text, normT2); + } + // const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes); + // const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes); + // console.log(`normal forms: ${normT1} {}{} ${normT2}`) + return normT1 === normT2; + } + + private async normalize( + node: Parser.SyntaxNode, + relevantTypes: Map, + ): Promise { + if (!node) return ""; + + switch (node.type) { + case "function_type": { + const params = node.child(0); // formal_parameters + const returnType = + node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return + + const paramTypes = + params?.namedChildren + .map((param) => + this.normalize( + param!.childForFieldName("type")! || + param!.namedChildren.at(-1), + relevantTypes, + ), + ) + .join(", ") || ""; + + const ret = this.normalize(returnType!, relevantTypes); + return `(${paramTypes}) => ${ret}`; + } + + case "tuple_type": { + const elements = node.namedChildren.map((c) => + this.normalize(c!, relevantTypes), + ); + return `[${elements.join(", ")}]`; + } + + case "union_type": { + const parts = node.namedChildren.map((c) => + this.normalize(c!, relevantTypes), + ); + return parts.join(" | "); + } + + case "type_identifier": { + const alias = relevantTypes.get(node.text); + if (!alias) return node.text; + + // Parse the alias's type span + const wrapped = `type __TMP = ${alias};`; + const tree = await getAst("file.ts", wrapped); + const valueNode = tree!.rootNode + .descendantsOfType("type_alias_declaration")[0] + ?.childForFieldName("value"); + + return this.normalize(valueNode!, relevantTypes); + } + + case "predefined_type": + case "number": + case "string": + return node.text; + + default: + // Fallback for types like array, etc. + return node.text; + } + } private insertAtPosition = ( contents: string, - cursorPosition: { line: number, character: number }, - insertText: string + cursorPosition: { line: number; character: number }, + insertText: string, ): string => { const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings const { line, character } = cursorPosition; @@ -294,8 +705,90 @@ export class StaticContextService { } // Insert the text - lines[line] = targetLine.slice(0, character) + insertText + targetLine.slice(character); + lines[line] = + targetLine.slice(0, character) + insertText + targetLine.slice(character); return lines.join("\n"); // Reconstruct the file + }; + + private async getTypeScriptFilesFromWorkspaces( + workspaceUris: string[], + ): Promise { + const tsExtensions = [".ts"]; + const allTsFiles: string[] = []; + + for (const workspaceUri of workspaceUris) { + try { + // Convert URI to file path + const folderPath = workspaceUri.startsWith("file://") + ? new URL(workspaceUri).pathname + : workspaceUri; + + const tsFiles = await this.scanDirectoryForTypeScriptFiles( + folderPath, + tsExtensions, + ); + allTsFiles.push(...tsFiles); + } catch (error) { + console.error(`Error scanning workspace ${workspaceUri}:`, error); + } + } + + return allTsFiles; + } + + private async scanDirectoryForTypeScriptFiles( + dirPath: string, + tsExtensions: string[], + ): Promise { + const tsFiles: string[] = []; + + const shouldSkipDirectory = (dirName: string): boolean => { + const skipDirs = [ + "node_modules", + ".git", + ".vscode", + "dist", + "build", + "out", + ".next", + "coverage", + ".nyc_output", + "tmp", + "temp", + ".cache", + ]; + + return skipDirs.includes(dirName) || dirName.startsWith("."); + }; + + async function scanRecursively(currentPath: string): Promise { + try { + const entries = await fs.readdir(currentPath, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = localPathOrUriToPath( + path.join(currentPath, entry.name), + ); + + if (entry.isDirectory()) { + // Skip common directories that typically don't contain source files + if (!shouldSkipDirectory(entry.name)) { + await scanRecursively(fullPath); + } + } else if (entry.isFile()) { + const extension = path.extname(entry.name).toLowerCase(); + if (tsExtensions.includes(extension)) { + tsFiles.push(fullPath); + } + } + } + } catch (error) { + console.error(`Error reading directory ${currentPath}:`, error); + } + } + + await scanRecursively(dirPath); + return tsFiles; } } diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 3db2c2542..681e20478 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -1,4 +1,3 @@ -import { context } from "esbuild"; import { IDE } from "../../index"; import { findUriInDirs } from "../../util/uri"; import { ContextRetrievalService } from "../context/ContextRetrievalService"; @@ -11,6 +10,7 @@ import { AutocompleteCodeSnippet, AutocompleteDiffSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "./types"; const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled @@ -23,6 +23,7 @@ export interface SnippetPayload { recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[]; diffSnippets: AutocompleteDiffSnippet[]; clipboardSnippets: AutocompleteClipboardSnippet[]; + staticSnippet: AutocompleteStaticSnippet[]; } function racePromise(promise: Promise, timeout = 100): Promise { @@ -124,7 +125,7 @@ export const getAllSnippets = async ({ ideSnippets, diffSnippets, clipboardSnippets, - staticSnippets + staticSnippet, ] = await Promise.all([ racePromise(contextRetrievalService.getRootPathSnippets(helper)), racePromise( @@ -135,7 +136,7 @@ export const getAllSnippets = async ({ : [], [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, racePromise(getClipboardSnippets(ide)), - racePromise(contextRetrievalService.getStaticContextSnippets(helper)) + contextRetrievalService.getStaticContextSnippets(helper), ]); return { @@ -146,5 +147,6 @@ export const getAllSnippets = async ({ diffSnippets, clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, + staticSnippet, }; }; From 61b389e5fb7947755da3215d31eaebff7cea9569 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 28 Jun 2025 20:14:49 -0700 Subject: [PATCH 013/178] prettier --- .../context/static-context/StaticContextService.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts index 4b9b41917..6ba954fc7 100644 --- a/core/autocomplete/context/static-context/StaticContextService.ts +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -764,7 +764,9 @@ export class StaticContextService { async function scanRecursively(currentPath: string): Promise { try { - const entries = await fs.readdir(currentPath, { withFileTypes: true }); + const entries = await fs.readdir(currentPath, { + withFileTypes: true, + }); for (const entry of entries) { const fullPath = localPathOrUriToPath( From 1320ff828e8e812465bb4344ed5227387e2d1402 Mon Sep 17 00:00:00 2001 From: dipfocus Date: Sat, 5 Jul 2025 18:54:27 +0800 Subject: [PATCH 014/178] Refactor downloadFile function to use fetch API and support proxy configuration. --- .../scripts/download-copy-sqlite-esbuild.js | 89 +++++-------------- 1 file changed, 23 insertions(+), 66 deletions(-) diff --git a/extensions/vscode/scripts/download-copy-sqlite-esbuild.js b/extensions/vscode/scripts/download-copy-sqlite-esbuild.js index ea6f8ebd9..b595c3bdf 100644 --- a/extensions/vscode/scripts/download-copy-sqlite-esbuild.js +++ b/extensions/vscode/scripts/download-copy-sqlite-esbuild.js @@ -1,83 +1,40 @@ const { fork } = require("child_process"); const fs = require("fs"); -const https = require("https"); const path = require("path"); +const { ProxyAgent } = require("undici"); const { rimrafSync } = require("rimraf"); const { execCmdSync } = require("../../../scripts/util"); /** - * download a file using nodejs http + * download a file using fetch API * @param {string} url * @param {string} outputPath - * @param {number} maxRedirects */ -async function downloadFile(url, outputPath, maxRedirects = 5) { - return new Promise((resolve, reject) => { - const downloadWithRedirects = (currentUrl, redirectCount = 0) => { - if (redirectCount > maxRedirects) { - return reject(new Error(`Too many redirects (${maxRedirects})`)); - } +async function downloadFile(url, outputPath) { + // Use proxy if set in environment variables + const proxy = process.env.https_proxy || process.env.HTTPS_PROXY; + const agent = proxy ? new ProxyAgent(proxy) : undefined; - const request = https.get(currentUrl, (response) => { - if ( - response.statusCode >= 300 && - response.statusCode < 400 && - response.headers.location - ) { - return downloadWithRedirects( - response.headers.location, - redirectCount + 1, - ); - } - - if (response.statusCode !== 200) { - return reject( - new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`), - ); - } - - const outputDir = path.dirname(outputPath); - if (!fs.existsSync(outputDir)) { - fs.mkdirSync(outputDir, { recursive: true }); - } - - const writeStream = fs.createWriteStream(outputPath); - - const totalSize = parseInt(response.headers["content-length"], 10); - let downloadedSize = 0; - - response.on("data", (chunk) => { - downloadedSize += chunk.length; - if (totalSize) { - const percent = ((downloadedSize / totalSize) * 100).toFixed(1); - process.stdout.write( - `\rDownloading: ${percent}% (${downloadedSize}/${totalSize} bytes)`, - ); - } - }); - - response.pipe(writeStream); - - writeStream.on("finish", () => { - console.log(`\nDownload completed: ${outputPath}`); - resolve(outputPath); - }); - - writeStream.on("error", reject); - response.on("error", reject); - }); - - request.on("error", reject); - request.setTimeout(30000, () => { - request.destroy(); - reject(new Error("Request timeout")); - }); - }; - - downloadWithRedirects(url); + const response = await fetch(url, { + redirect: "follow", // Automatically follow redirects + dispatcher: agent, }); + + if (!response.ok) { + throw new Error(`Failed to download file, status code: ${response.status}`); + } + + // Create output directory if it doesn't exist + const outputDir = path.dirname(outputPath); + if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }); + } + + // Get the response as an array buffer and write it to the file + const buffer = await response.arrayBuffer(); + fs.writeFileSync(outputPath, Buffer.from(buffer)); } /** From 482ed61a5e9ffd0592b1e65c229299bdb7351ce3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 08:49:59 -0700 Subject: [PATCH 016/178] resolve merge conflicts --- core/autocomplete/snippets/getAllSnippets.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 7ba487054..fccc8530b 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -199,6 +199,7 @@ export const getAllSnippets = async ({ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, racePromise(getClipboardSnippets(ide)), racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete + racePromise(contextRetrievalService.getStaticContextSnippets(helper)), ]); return { @@ -210,6 +211,7 @@ export const getAllSnippets = async ({ clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, recentlyOpenedFileSnippets, + staticSnippet, }; }; @@ -234,6 +236,7 @@ export const getAllSnippetsWithoutRace = async ({ diffSnippets, clipboardSnippets, recentlyOpenedFileSnippets, + staticSnippet, ] = await Promise.all([ contextRetrievalService.getRootPathSnippets(helper), contextRetrievalService.getSnippetsFromImportDefinitions(helper), From b0b2de7dff9ddcbdce55f1e8a927a9f5c151453c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:28:16 -0700 Subject: [PATCH 017/178] add methods for go to type definitions and get signature help --- core/index.d.ts | 118 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 94 insertions(+), 24 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index e173e9a58..5bd5de1ad 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -49,13 +49,13 @@ export interface IndexingProgressUpdate { desc: string; shouldClearIndexes?: boolean; status: - | "loading" - | "indexing" - | "done" - | "failed" - | "paused" - | "disabled" - | "cancelled"; + | "loading" + | "indexing" + | "done" + | "failed" + | "paused" + | "disabled" + | "cancelled"; debugInfo?: string; warnings?: string[]; } @@ -92,7 +92,7 @@ type RequiredLLMOptions = export interface ILLM extends Omit, - Required> { + Required> { get providerName(): string; get underlyingProviderName(): string; @@ -778,10 +778,10 @@ export interface IDE { getCurrentFile(): Promise< | undefined | { - isUntitled: boolean; - path: string; - contents: string; - } + isUntitled: boolean; + path: string; + contents: string; + } >; getPinnedFiles(): Promise; @@ -819,7 +819,8 @@ export interface IDE { // LSP gotoDefinition(location: Location): Promise; - gotoTypeDefinition(location: Location): Promise; + gotoTypeDefinition(location: Location): Promise; // TODO: add to jetbrains + getSignatureHelp(location: Location): Promise; // TODO: add to jetbrains // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; @@ -989,11 +990,11 @@ export interface CustomCommand { export interface Prediction { type: "content"; content: - | string - | { - type: "text"; - text: string; - }[]; + | string + | { + type: "text"; + text: string; + }[]; } export interface ToolExtras { @@ -1156,6 +1157,7 @@ export interface TabAutocompleteOptions { experimental_includeRecentlyVisitedRanges: boolean | number; experimental_includeRecentlyEditedRanges: boolean | number; experimental_includeDiff: boolean | number; + experimental_enableStaticContextualization: boolean; } export interface StdioOptions { @@ -1355,6 +1357,68 @@ export interface RangeInFileWithNextEditInfo { export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents; +/** + * Signature help represents the signature of something + * callable. There can be multiple signatures but only one + * active and only one active parameter. + */ +export class SignatureHelp { + /** + * One or more signatures. + */ + signatures: SignatureInformation[]; + + /** + * The active signature. + */ + activeSignature: number; + + /** + * The active parameter of the active signature. + */ + activeParameter: number; +} + +/** + * Represents the signature of something callable. A signature + * can have a label, like a function-name, a doc-comment, and + * a set of parameters. + */ +export class SignatureInformation { + /** + * The label of this signature. Will be shown in + * the UI. + */ + label: string; + + /** + * The parameters of this signature. + */ + parameters: ParameterInformation[]; + + /** + * The index of the active parameter. + * + * If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}. + */ + activeParameter?: number; +} + +/** + * Represents a parameter of a callable-signature. A parameter can + * have a label and a doc-comment. + */ +export class ParameterInformation { + /** + * The label of this signature. + * + * Either a string or inclusive start and exclusive end offsets within its containing + * {@link SignatureInformation.label signature label}. *Note*: A label of type string must be + * a substring of its containing signature information's {@link SignatureInformation.label label}. + */ + label: string | [number, number]; +} + /** * Represents the configuration for a quick action in the Code Lens. * Quick actions are custom commands that can be added to function and class declarations. @@ -1430,6 +1494,12 @@ export interface ExperimentalConfig { * instead of embeddings, FTS, recently edited files, etc. */ codebaseToolCallingOnly?: boolean; + + /** + * If enabled, static contextualization will be used to + * gather context for the model where necessary. + */ + enableStaticContextualization?: boolean; } export interface AnalyticsConfig { @@ -1529,9 +1599,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | ILLM; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | JSONModelDescription - | (CustomLLM | JSONModelDescription)[]; + | CustomLLM + | JSONModelDescription + | (CustomLLM | JSONModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -1625,9 +1695,9 @@ export type PackageDetailsSuccess = PackageDetails & { export type PackageDocsResult = { packageInfo: ParsedPackageInfo; } & ( - | { error: string; details?: never } - | { details: PackageDetailsSuccess; error?: never } - ); + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } +); export interface TerminalOptions { reuseTerminal?: boolean; From f04260a7efac3aeffc92a849fbc7bfdd0df5be33 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:28:32 -0700 Subject: [PATCH 018/178] enable static contextualization when needed --- core/autocomplete/CompletionProvider.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 749b44e25..4d4327bcc 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -10,7 +10,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { getAllSnippets } from "./snippets/index.js"; +import { getAllSnippetsWithoutRace } from "./snippets/index.js"; import { renderPrompt } from "./templating/index.js"; import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; @@ -121,6 +121,11 @@ export class CompletionProvider { ...config?.tabAutocompleteOptions, ...llm.autocompleteOptions, }; + + // Enable static contextualization if defined. + options.experimental_enableStaticContextualization = + config?.experimental?.enableStaticContextualization ?? false; + return options; } @@ -171,7 +176,7 @@ export class CompletionProvider { } const [snippetPayload, workspaceDirs] = await Promise.all([ - getAllSnippets({ + getAllSnippetsWithoutRace({ helper, ide: this.ide, getDefinitionsFromLsp: this.getDefinitionsFromLsp, From 8b03b9a67d9152dee1239c3c653edd31c9346f76 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:28:53 -0700 Subject: [PATCH 019/178] improve usability --- .../static-context/StaticContextService.ts | 90 +++++++++++++++++-- 1 file changed, 81 insertions(+), 9 deletions(-) diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts index 6ba954fc7..fb6919d35 100644 --- a/core/autocomplete/context/static-context/StaticContextService.ts +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -85,7 +85,11 @@ export class StaticContextService { helper.workspaceUris, ); // Get the three contexts holeContext, relevantTypes, relevantHeaders. - const holeContext = await this.getHoleContext(helper.filepath, helper.pos); + const holeContext = await this.getHoleContext( + helper.fileContents, + helper.filepath, + helper.pos, + ); const relevantTypes = await this.extractRelevantTypes( holeContext.fullHoverResult, @@ -106,6 +110,8 @@ export class StaticContextService { tsFiles, relevantTypes, holeContext.functionTypeSpan, + helper.pos, + holeContext.returnTypeIsAny, ); const relevantTypesToReturn: Map = new Map< @@ -158,12 +164,13 @@ export class StaticContextService { } private async getHoleContext( + sketchFileContent: string, sketchFilePath: string, cursorPosition: Position, ): Promise { // We need to inject the hole @ to trigger a treesitter error node. sketchFilePath = localPathOrUriToPath(sketchFilePath); - const sketchFileContent = await fs.readFile(sketchFilePath, "utf8"); + // const sketchFileContent = await fs.readFile(sketchFilePath, "utf8"); const injectedContent = this.insertAtPosition( sketchFileContent, cursorPosition, @@ -193,12 +200,14 @@ export class StaticContextService { fullHoverResult: "", functionName: "", functionTypeSpan: "", + returnTypeIsAny: false, range: { start: { line: 0, character: 0 }, - end: { line: 0, character: 52 }, + end: { line: 0, character: 0 }, }, source: `file://${sketchFilePath}`, }; + let paramsTypes = ""; for (const c of captures) { const { name, node } = c; // console.log(`${name} →`, node.text, node.startPosition, node.endPosition); @@ -206,9 +215,25 @@ export class StaticContextService { switch (name) { case "function.decl": { res.fullHoverResult = node.text; + break; } case "function.name": { res.functionName = node.text; + break; + } + case "function.params": { + paramsTypes = node.text; + res.range = { + start: { + line: node.startPosition.row, + character: node.startPosition.column, + }, + end: { + line: node.endPosition.row, + character: node.endPosition.column, + }, + }; + break; } case "function.type": { res.functionTypeSpan = node.text; @@ -222,10 +247,16 @@ export class StaticContextService { character: node.endPosition.column, }, }; + break; } } } + if (res.functionTypeSpan === "") { + res.functionTypeSpan = `${paramsTypes} => any`; + res.returnTypeIsAny = true; + } + return res; } @@ -354,8 +385,11 @@ export class StaticContextService { sources: string[], relevantTypes: Map, holeType: string, + cursorPosition: Position, + returnTypeIsAny: boolean, ): Promise { const relevantContext = new Set(); + if (returnTypeIsAny) return relevantContext; // NOTE: This is necessary because TypeScript sucks. // There is no way to compare objects by value, // so sets of objects starts to accumulate tons of duplicates. @@ -378,7 +412,43 @@ export class StaticContextService { // build a type span // TODO: this fails sometimes with Cannot read properties of undefined (reading 'text') // most likely due to my scm query and how I'm not attaching param name along with param type - const funcType = extractFunctionTypeFromDecl(tld); + let funcType = ""; + try { + funcType = extractFunctionTypeFromDecl(tld); + } catch (err) { + // Most likely is the case that there is no explicit return type annotation. + const sigHelp = await this.ide.getSignatureHelp({ + filepath: source, + position: cursorPosition, + }); + if (!sigHelp) continue; + funcType = sigHelp.signatures[0].label; + + // TODO: This only works for TypeScript. + function convertToArrowType(signature: string): string { + // Handle various function declaration formats. + const patterns = [ + // Standard: functionName(params): returnType. + /^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/, + // With generics: functionName(params): returnType. + /^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/, + // With modifiers: export function functionName(params): returnType. + /^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/, + ]; + + for (const pattern of patterns) { + const match = signature.match(pattern); + if (match) { + const [, , parameters, returnType] = match; + return `(${parameters}) => ${returnType}`; + } + } + + return signature; + } + + funcType = convertToArrowType(funcType); + } const wrapped = `type __TMP = ${funcType};`; const ast = await getAst("file.ts", wrapped); @@ -386,9 +456,9 @@ export class StaticContextService { throw new Error(`failed to generate ast for ${wrapped}`); } - console.log(ast.rootNode); + // console.log(ast.rootNode); const alias = ast.rootNode.namedChild(0); - console.log(alias); + // console.log(alias); if (!alias || alias.type !== "type_alias_declaration") { throw new Error( "extractRelevantHeaders: Failed to parse type alias", @@ -564,9 +634,11 @@ export class StaticContextService { const alias = ast.rootNode.namedChild(0); if (!alias || alias.type !== "type_alias_declaration") { - throw new Error( - "generateTargetTypesHelper: Failed to parse type alias", - ); + console.error("generateTargetTypesHelper: Failed to parse type alias"); + return; + // throw new Error( + // "generateTargetTypesHelper: Failed to parse type alias", + // ); } const valueNode = alias.childForFieldName("value"); From f1cdd5fb754b0eb5e1d930d44b0dc424749d9c52 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:29:14 -0700 Subject: [PATCH 020/178] prettier check --- .../static-context/tree-sitter-utils.ts | 39 ++++++++++++------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/core/autocomplete/context/static-context/tree-sitter-utils.ts b/core/autocomplete/context/static-context/tree-sitter-utils.ts index c7a9a20a3..6e751f547 100644 --- a/core/autocomplete/context/static-context/tree-sitter-utils.ts +++ b/core/autocomplete/context/static-context/tree-sitter-utils.ts @@ -1,8 +1,7 @@ import * as fs from "fs/promises"; import Parser from "web-tree-sitter"; -import { getAst } from "../../util/ast"; import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; -import path from "path"; +import { getAst } from "../../util/ast"; export interface TypeDeclarationResult { name: string; @@ -18,7 +17,7 @@ export function findEnclosingTypeDeclaration( sourceCode: string, cursorLine: number, cursorColumn: number, - ast: Parser.Tree + ast: Parser.Tree, ): TypeDeclarationResult | null { const point = { row: cursorLine, column: cursorColumn }; let node = ast.rootNode.descendantForPosition(point); @@ -52,7 +51,10 @@ export function findEnclosingTypeDeclaration( }; } -export async function extractTopLevelDecls(currentFile: string, givenParser?: Parser) { +export async function extractTopLevelDecls( + currentFile: string, + givenParser?: Parser, +) { const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8")); if (!ast) { throw new Error(`failed to get ast for file ${currentFile}`); @@ -66,17 +68,20 @@ export async function extractTopLevelDecls(currentFile: string, givenParser?: Pa const query = await getQueryForFile( currentFile, - `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm` + `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`, ); if (!query) { throw new Error( - `failed to get query for file ${currentFile} and language ${language}` + `failed to get query for file ${currentFile} and language ${language}`, ); } return query.matches(ast.rootNode); } -export async function extractTopLevelDeclsWithFormatting(currentFile: string, givenParser?: Parser) { +export async function extractTopLevelDeclsWithFormatting( + currentFile: string, + givenParser?: Parser, +) { const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8")); if (!ast) { throw new Error(`failed to get ast for file ${currentFile}`); @@ -90,11 +95,11 @@ export async function extractTopLevelDeclsWithFormatting(currentFile: string, gi const query = await getQueryForFile( currentFile, - `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm` + `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`, ); if (!query) { throw new Error( - `failed to get query for file ${currentFile} and language ${language}` + `failed to get query for file ${currentFile} and language ${language}`, ); } const matches = query.matches(ast.rootNode); @@ -166,13 +171,21 @@ export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string { } if (!paramsNode) { - console.error(`extractFunctionTypeFromDecl: ${paramsNode} not found`); - throw new Error(`extractFunctionTypeFromDecl: ${paramsNode} not found`); + console.error( + `extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`, + ); + throw new Error( + `extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`, + ); } if (!returnNode) { - console.error(`extractFunctionTypeFromDecl: ${returnNode} not found`); - throw new Error(`extractFunctionTypeFromDecl: ${returnNode} not found`); + console.error( + `extractFunctionTypeFromDecl: returnNode ${returnNode} not found`, + ); + throw new Error( + `extractFunctionTypeFromDecl: returnNode ${returnNode} not found`, + ); } return `(${paramsNode!.text}) => ${returnNode!.text}`; From 0f7a0023770285b777051ce8ebb79aa95fb9528f Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:29:27 -0700 Subject: [PATCH 021/178] check for config enable --- core/autocomplete/snippets/getAllSnippets.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index fccc8530b..079127abc 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -199,7 +199,9 @@ export const getAllSnippets = async ({ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, racePromise(getClipboardSnippets(ide)), racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete - racePromise(contextRetrievalService.getStaticContextSnippets(helper)), + helper.options.experimental_enableStaticContextualization + ? racePromise(contextRetrievalService.getStaticContextSnippets(helper)) + : [], ]); return { @@ -246,7 +248,9 @@ export const getAllSnippetsWithoutRace = async ({ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, getClipboardSnippets(ide), getSnippetsFromRecentlyOpenedFiles(helper, ide), - contextRetrievalService.getStaticContextSnippets(helper), + helper.options.experimental_enableStaticContextualization + ? contextRetrievalService.getStaticContextSnippets(helper) + : [], ]); return { From e7a75a59031c3853cea6f1165ee1bd0bd89b44e3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:29:45 -0700 Subject: [PATCH 022/178] check for any return type for quick optimization --- core/autocomplete/context/static-context/types.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/autocomplete/context/static-context/types.ts b/core/autocomplete/context/static-context/types.ts index 2400c2a7a..1aa8b473d 100644 --- a/core/autocomplete/context/static-context/types.ts +++ b/core/autocomplete/context/static-context/types.ts @@ -14,6 +14,7 @@ export interface HoleContext { fullHoverResult: string; functionName: string; functionTypeSpan: string; + returnTypeIsAny: boolean; range: Range; source: string; } From 068b7f28327ffa737679f51824987277278ef7a2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:30:06 -0700 Subject: [PATCH 023/178] add defs for static contextualization --- core/config/sharedConfig.ts | 5 +++++ core/util/parameters.ts | 1 + gui/src/pages/config/UserSettingsForm.tsx | 13 +++++++++++++ 3 files changed, 19 insertions(+) diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 5d7053cf8..87f923f3c 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -23,6 +23,7 @@ export const sharedConfigSchema = z optInNextEditFeature: z.boolean(), enableExperimentalTools: z.boolean(), codebaseToolCallingOnly: z.boolean(), + enableStaticContextualization: z.boolean(), // `ui` in `ContinueConfig` showSessionTabs: z.boolean(), @@ -192,6 +193,10 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.codebaseToolCallingOnly = sharedConfig.codebaseToolCallingOnly; } + if (sharedConfig.enableStaticContextualization !== undefined) { + configCopy.experimental.enableStaticContextualization = + sharedConfig.enableStaticContextualization; + } return configCopy; } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index cadbe9a47..147c3979a 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -24,6 +24,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { experimental_includeRecentlyVisitedRanges: true, experimental_includeRecentlyEditedRanges: true, experimental_includeDiff: true, + experimental_enableStaticContextualization: false, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 04405f1be..54783c254 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -97,6 +97,8 @@ export function UserSettingsForm() { config.experimental?.optInNextEditFeature ?? false; const codebaseToolCallingOnly = config.experimental?.codebaseToolCallingOnly ?? false; + const enableStaticContextualization = + config.experimental?.enableStaticContextualization ?? false; const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true; const disableIndexing = config.disableIndexing ?? false; @@ -434,6 +436,17 @@ export function UserSettingsForm() { text="@Codebase: use tool calling only" /> + + handleUpdate({ + enableStaticContextualization: + !enableStaticContextualization, + }) + } + text="Use Static Contextualization" + /> + {hasContinueEmail && ( Date: Sat, 5 Jul 2025 17:30:21 -0700 Subject: [PATCH 024/178] add methods for get signature help --- extensions/vscode/src/VsCodeIde.ts | 17 ++++++- extensions/vscode/src/autocomplete/lsp.ts | 54 ++++++++++++++++++++++- 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 01246e35f..ec68fb065 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -6,7 +6,10 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import { executeGotoProvider } from "./autocomplete/lsp"; +import { + executeGotoProvider, + executeSignatureHelpProvider, +} from "./autocomplete/lsp"; import { Repository } from "./otherExtensions/git"; import { SecretStorage } from "./stubs/SecretStorage"; import { VsCodeIdeUtils } from "./util/ideUtils"; @@ -24,6 +27,7 @@ import type { Location, Problem, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "core"; @@ -97,6 +101,17 @@ class VsCodeIde implements IDE { return result; } + async getSignatureHelp(location: Location): Promise { + const result = await executeSignatureHelpProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeSignatureHelpProvider", + }); + + return result; + } + onDidChangeActiveTextEditor(callback: (uri: string) => void): void { vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor) { diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index a6900291a..c3d5c11a4 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -13,7 +13,13 @@ import { intersection } from "core/util/ranges"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core"; +import type { + IDE, + Range, + RangeInFile, + RangeInFileWithContents, + SignatureHelp, +} from "core"; import type Parser from "web-tree-sitter"; type GotoProviderName = @@ -23,6 +29,8 @@ type GotoProviderName = | "vscode.executeImplementationProvider" | "vscode.executeReferenceProvider"; +type SignatureHelpProviderName = "vscode.executeSignatureHelpProvider"; + interface GotoInput { uri: vscode.Uri; line: number; @@ -33,8 +41,19 @@ function gotoInputKey(input: GotoInput) { return `${input.name}${input.uri.toString()}${input.line}${input.character}`; } +interface SignatureHelpInput { + uri: vscode.Uri; + line: number; + character: number; + name: SignatureHelpProviderName; +} +function signatureHelpKey(input: SignatureHelpInput) { + return `${input.name}${input.uri.toString()}${input.line}${input.character}`; +} + const MAX_CACHE_SIZE = 500; const gotoCache = new Map(); +const signatureHelpCache = new Map(); export async function executeGotoProvider( input: GotoInput, @@ -382,3 +401,36 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( return []; } }; + +export async function executeSignatureHelpProvider( + input: SignatureHelpInput, +): Promise { + const cacheKey = signatureHelpKey(input); + const cached = signatureHelpCache.get(cacheKey); + if (cached) { + return cached; + } + + try { + const definitions = (await vscode.commands.executeCommand( + input.name, + input.uri, + new vscode.Position(input.line, input.character), + )) as SignatureHelp; + + // Add to cache + if (signatureHelpCache.size >= MAX_CACHE_SIZE) { + // Remove the oldest item from the cache + const oldestKey = signatureHelpCache.keys().next().value; + if (oldestKey) { + signatureHelpCache.delete(oldestKey); + } + } + signatureHelpCache.set(cacheKey, definitions); + + return definitions; + } catch (e) { + console.warn(`Error executing ${input.name}:`, e); + return null; + } +} From 3edf8097b3eb75f2aca80d8e55ca301558ee8fd5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:30:37 -0700 Subject: [PATCH 025/178] handle cases where function declarations have no body --- .../hole-queries/typescript.scm | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm b/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm index e69122b07..02de34466 100644 --- a/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm +++ b/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm @@ -21,7 +21,7 @@ (function_type return_type: (type_identifier) @return.type) -;; Capture any parse errors (e.g., the `??`) +;; Capture any parse errors (e.g., the `@`) (ERROR) @error.node ;; Capture the entire function declaration line @@ -34,3 +34,26 @@ (import_specifier name: (identifier) @import.name))) source: (string) @import.source) + +;; Capture standalone function declarations +(function_declaration + name: (identifier) @function.name) @function.decl + +;; Capture the function signature including parameters and return type +(function_declaration + parameters: (formal_parameters) @function.params + return_type: (type_annotation)? @function.type) + +;; For function expressions or arrow functions +(function_type + parameters: (formal_parameters) @function.params) @function.decl + +;; For arrow functions +(arrow_function + parameters: (formal_parameters) @function.params) @function.decl + +;; For function signatures without a body (like in your example) +(function_signature + name: (identifier) @function.name + parameters: (formal_parameters) @function.params + return_type: (type_annotation)? @function.type) @function.decl From be10c078c7c57789a2c23b29bfdf89648e497547 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 17:52:27 -0700 Subject: [PATCH 026/178] match type definition parity with vscode --- .../continue/IntelliJIde.kt | 8 +++ .../continueintellijextension/types.kt | 64 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 2dfc3e3e1..782a878d6 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -592,6 +592,14 @@ class IntelliJIDE( throw NotImplementedError("gotoDefinition not implemented yet") } + override suspend fun gotoTypeDefinition(location: Location): List { + throw NotImplementedError("gotoTypeDefinition not implemented yet") + } + + override suspend fun getSignatureHelp(location: Location): SignatureHelp? { + throw NotImplementedError("getSignatureHelp not implemented yet") + } + override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) { throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 5ff9e9454..dd898eca2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -63,6 +63,68 @@ data class RangeInFileWithContents( val contents: String ) +/** + * Signature help represents the signature of something + * callable. There can be multiple signatures but only one + * active and only one active parameter. + */ +data class SignatureHelp( + /** + * One or more signatures. + */ + val signatures: List, + + /** + * The active signature. + */ + val activeSignature: Int, + + /** + * The active parameter of the active signature. + */ + val activeParameter: Int +) + +/** + * Represents the signature of something callable. A signature + * can have a label, like a function-name, a doc-comment, and + * a set of parameters. + */ +data class SignatureInformation( + /** + * The label of this signature. Will be shown in + * the UI. + */ + val label: String, + + /** + * The parameters of this signature. + */ + val parameters: List, + + /** + * The index of the active parameter. + * + * If provided, this is used in place of [SignatureHelp.activeParameter]. + */ + val activeParameter: Int? = null +) + +/** + * Represents a parameter of a callable-signature. A parameter can + * have a label and a doc-comment. + */ +data class ParameterInformation( + /** + * The label of this signature. + * + * Either a string or inclusive start and exclusive end offsets within its containing + * [SignatureInformation.label] signature label. *Note*: A label of type string must be + * a substring of its containing signature information's [SignatureInformation.label] label. + */ + val label: String // Note: Kotlin doesn't have union types, so this represents the string case +) + data class ControlPlaneSessionInfo( val accessToken: String, val account: Account @@ -191,6 +253,8 @@ interface IDE { // LSP suspend fun gotoDefinition(location: Location): List + suspend fun gotoTypeDefinition(location: Location): List + suspend fun getSignatureHelp(location: Location): SignatureHelp? // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) From 6a2ede397179b7ee3033e4533f3a772ac556c340 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 20:28:02 -0700 Subject: [PATCH 027/178] add a flag to check if static contextualization was enabled --- packages/config-yaml/src/schemas/data/autocomplete/index.ts | 3 +++ packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/packages/config-yaml/src/schemas/data/autocomplete/index.ts b/packages/config-yaml/src/schemas/data/autocomplete/index.ts index 8ae073e2e..4d2a0b91b 100644 --- a/packages/config-yaml/src/schemas/data/autocomplete/index.ts +++ b/packages/config-yaml/src/schemas/data/autocomplete/index.ts @@ -36,6 +36,9 @@ export const autocompleteEventAllSchema = baseDevDataAllSchema.extend({ uniqueId: z.string(), timestamp: z.number(), + // For static contextualization. + enabledStaticContextualization: z.boolean().optional(), + // DEPRECATED - no more nested objects after v0.1.0, all flat values completionOptions: completionOptionsSchema.optional(), disableInFiles: z.array(z.string()).optional(), diff --git a/packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts b/packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts index 5866b9865..123a05b75 100644 --- a/packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts +++ b/packages/config-yaml/src/schemas/data/autocomplete/v0.2.0.ts @@ -38,6 +38,9 @@ export const autocompleteEventSchema_0_2_0 = autocompleteEventAllSchema.pick({ completionId: true, uniqueId: true, + // For static contextualization. + enabledStaticContextualization: true, + // Note objects (completionOptions and disableInfiles) removed from 0.1.0 => 0.2.0 }); From 53b28146ebbbfc282cca74b429dec9d48a7277f2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sat, 5 Jul 2025 20:32:06 -0700 Subject: [PATCH 028/178] log static contextualization --- core/autocomplete/CompletionProvider.ts | 9 +++- .../util/AutocompleteLoggingService.ts | 44 +++++++++++-------- core/autocomplete/util/types.ts | 1 + 3 files changed, 33 insertions(+), 21 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 4d4327bcc..2e3cd320d 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -123,8 +123,9 @@ export class CompletionProvider { }; // Enable static contextualization if defined. - options.experimental_enableStaticContextualization = - config?.experimental?.enableStaticContextualization ?? false; + if (config?.experimental?.enableStaticContextualization) { + options.experimental_enableStaticContextualization = true; + } return options; } @@ -263,6 +264,10 @@ export class CompletionProvider { ...helper.options, }; + if (options.experimental_enableStaticContextualization) { + outcome.enabledStaticContextualization = true; + } + ////////// // Save to cache diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 2e4d19844..4f600a8c5 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -105,24 +105,30 @@ export class AutocompleteLoggingService { }); const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; - void Telemetry.capture( - "autocomplete", - { - accepted: restOfOutcome.accepted, - cacheHit: restOfOutcome.cacheHit, - completionId: restOfOutcome.completionId, - completionOptions: restOfOutcome.completionOptions, - debounceDelay: restOfOutcome.debounceDelay, - fileExtension: getUriFileExtension(restOfOutcome.filepath), - maxPromptTokens: restOfOutcome.maxPromptTokens, - modelName: restOfOutcome.modelName, - modelProvider: restOfOutcome.modelProvider, - multilineCompletions: restOfOutcome.multilineCompletions, - time: restOfOutcome.time, - useRecentlyEdited: restOfOutcome.useRecentlyEdited, - numLines: restOfOutcome.numLines, - }, - true, - ); + const toLog = { + accepted: restOfOutcome.accepted, + cacheHit: restOfOutcome.cacheHit, + completionId: restOfOutcome.completionId, + completionOptions: restOfOutcome.completionOptions, + debounceDelay: restOfOutcome.debounceDelay, + fileExtension: getUriFileExtension(restOfOutcome.filepath), + maxPromptTokens: restOfOutcome.maxPromptTokens, + modelName: restOfOutcome.modelName, + modelProvider: restOfOutcome.modelProvider, + multilineCompletions: restOfOutcome.multilineCompletions, + time: restOfOutcome.time, + useRecentlyEdited: restOfOutcome.useRecentlyEdited, + numLines: restOfOutcome.numLines, + }; + + outcome.enabledStaticContextualization + ? void Telemetry.capture("autocomplete", { + ...toLog, + enabledStaticContextualization: true, + prefix, + suffix, + prompt, + }) + : void Telemetry.capture("autocomplete", toLog); } } diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index 3959bff9c..32be50e2f 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -42,4 +42,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions { completionId: string; uniqueId: string; timestamp: number; + enabledStaticContextualization?: boolean; } From 031ad9dc0b11d788f327e885160e20a4559fb5f6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 7 Jul 2025 18:53:49 -0700 Subject: [PATCH 029/178] move to continue-only feature for internal testing --- gui/src/pages/config/ContinueFeaturesMenu.tsx | 14 +++++++++++++ gui/src/pages/config/UserSettingsForm.tsx | 21 +++++++++---------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/gui/src/pages/config/ContinueFeaturesMenu.tsx b/gui/src/pages/config/ContinueFeaturesMenu.tsx index f3cb738ca..c83b5a334 100644 --- a/gui/src/pages/config/ContinueFeaturesMenu.tsx +++ b/gui/src/pages/config/ContinueFeaturesMenu.tsx @@ -6,6 +6,8 @@ interface ContinueFeaturesMenuProps { handleLogEditingDataToggle: (value: boolean) => void; optInNextEditFeature: boolean; handleOptInNextEditToggle: (value: boolean) => void; + enableStaticContextualization: boolean; + handleEnableStaticContextualizationToggle: (value: boolean) => void; } export function ContinueFeaturesMenu({ @@ -13,6 +15,8 @@ export function ContinueFeaturesMenu({ handleLogEditingDataToggle, optInNextEditFeature, handleOptInNextEditToggle, + enableStaticContextualization, + handleEnableStaticContextualizationToggle, }: ContinueFeaturesMenuProps) { return (
@@ -42,6 +46,16 @@ export function ContinueFeaturesMenu({ onToggle={() => handleOptInNextEditToggle(!optInNextEditFeature)} text="Enable Next Edit Over Autocomplete" /> + + + handleEnableStaticContextualizationToggle( + !enableStaticContextualization, + ) + } + text="Use Static Contextualization" + />
); diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 54783c254..ea6b27cfd 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -75,6 +75,10 @@ export function UserSettingsForm() { handleUpdate({ optInNextEditFeature: value }); }; + const handleEnableStaticContextualizationToggle = (value: boolean) => { + handleUpdate({ enableStaticContextualization: value }); + }; + useEffect(() => { // Necessary so that reformatted/trimmed values don't cause dirty state setFormPromptPath(promptPath); @@ -436,23 +440,18 @@ export function UserSettingsForm() { text="@Codebase: use tool calling only" /> - - handleUpdate({ - enableStaticContextualization: - !enableStaticContextualization, - }) - } - text="Use Static Contextualization" - /> - {hasContinueEmail && ( )} From 367e6672ca4de6eddf4f79816f8287d803744f13 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 7 Jul 2025 19:20:17 -0700 Subject: [PATCH 030/178] refactor: :art: format snippets so that it's more model prefix-friendly --- .../static-context/StaticContextService.ts | 32 +++++++++++++++---- core/autocomplete/snippets/types.ts | 1 + 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts index fb6919d35..b955a38ff 100644 --- a/core/autocomplete/context/static-context/StaticContextService.ts +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -1,5 +1,6 @@ import * as fs from "fs/promises"; import path from "path"; +import { pathToFileURL } from "url"; import Parser from "web-tree-sitter"; import { IDE, Position } from "../../.."; import { localPathOrUriToPath } from "../../../util/pathToUri"; @@ -153,14 +154,33 @@ export class StaticContextService { this.logAutocompleteStaticSnippet(ctx); - console.log(end - start); + // console.log(end - start); - return [ - { + const snippets: AutocompleteStaticSnippet[] = []; + + snippets.push({ + type: AutocompleteSnippetType.Static, + filepath: pathToFileURL(path.resolve(holeContext.source)).toString(), + content: holeContext.fullHoverResult, + }); + + for (const [filepath, typs] of ctx.relevantTypes.entries()) { + snippets.push({ type: AutocompleteSnippetType.Static, - content: StaticContextService.formatAutocompleteStaticSnippet(ctx), - }, - ]; + filepath: pathToFileURL(path.resolve(filepath)).toString(), + content: typs.join("\n"), + }); + } + + for (const [filepath, headers] of ctx.relevantHeaders.entries()) { + snippets.push({ + type: AutocompleteSnippetType.Static, + filepath: pathToFileURL(path.resolve(filepath)).toString(), + content: headers.join("\n"), + }); + } + + return snippets; } private async getHoleContext( diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts index c486c0106..be820609b 100644 --- a/core/autocomplete/snippets/types.ts +++ b/core/autocomplete/snippets/types.ts @@ -26,6 +26,7 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet { type: AutocompleteSnippetType.Static; + filepath: string; } export type AutocompleteSnippet = From 9472bb1e4562e64e0ab4752aecbf4b3f1cb723bd Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 9 Jul 2025 21:07:31 -0700 Subject: [PATCH 031/178] bug: satisfy IDE --- core/protocol/ide.ts | 3 +++ core/protocol/messenger/messageIde.ts | 9 +++++++++ core/util/filesystem.ts | 9 +++++++++ 3 files changed, 21 insertions(+) diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index ba4cf4f88..c67b8c94a 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -10,6 +10,7 @@ import type { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "../"; @@ -82,6 +83,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { getFileStats: [{ files: string[] }, FileStatsMap]; gotoDefinition: [{ location: Location }, RangeInFile[]]; + gotoTypeDefinition: [{ location: Location }, RangeInFile[]]; + getSignatureHelp: [{ location: Location }, SignatureHelp | null]; getControlPlaneSessionInfo: [ { silent: boolean; useOnboarding: boolean }, diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 30d9b8177..2365117c0 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -13,6 +13,7 @@ import type { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "../.."; @@ -45,6 +46,14 @@ export class MessageIde implements IDE { return this.request("gotoDefinition", { location }); } + async gotoTypeDefinition(location: Location): Promise { + return this.request("gotoTypeDefinition", { location }); + } + + async getSignatureHelp(location: Location): Promise { + return this.request("getSignatureHelp", { location }); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index f415e5e86..959ea939f 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -13,6 +13,7 @@ import { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, ToastType, @@ -44,6 +45,14 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } + gotoTypeDefinition(location: Location): Promise { + return Promise.resolve([]); + } + + getSignatureHelp(location: Location): Promise { + return Promise.resolve(null); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } From 5b1848d2f179e7b078814260b86bfd33ebdd0ef1 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 9 Jul 2025 21:10:02 -0700 Subject: [PATCH 032/178] bump: version --- binary/package-lock.json | 2 ++ packages/config-yaml/package-lock.json | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/binary/package-lock.json b/binary/package-lock.json index 51e6f5cf9..11dd6505b 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -121,6 +121,8 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", + "@shikijs/colorized-brackets": "^3.7.0", + "@shikijs/transformers": "^3.7.0", "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 014ecac95..51091ea04 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.95", + "version": "1.0.96", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.95", + "version": "1.0.96", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", From b72fc0ea8f8dc0e1f88934e18b1b9ab5d34826ef Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Thu, 10 Jul 2025 18:47:06 +0200 Subject: [PATCH 033/178] fix: Send the process exit reason to Sentry + add OS info --- .../continue/IdeProtocolClient.kt | 1 - .../continue/IntelliJIde.kt | 1 - .../continue/process/ContinueBinaryProcess.kt | 9 ++++----- .../error/ContinueErrorService.kt | 12 +++++++++++- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 08a5e8d18..6b2da6179 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -13,7 +13,6 @@ import com.github.continuedev.continueintellijextension.utils.* import com.google.gson.Gson import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileEditorManager diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 2dfc3e3e1..52161f2e3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -26,7 +26,6 @@ import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir -import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt index eb45cc4da..f10dd9d65 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.`continue`.process +import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.github.continuedev.continueintellijextension.services.TelemetryService import com.github.continuedev.continueintellijextension.utils.OS import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath @@ -44,11 +45,8 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess { err = err.substring(doneIndex + delimiter.length) } } - - println("Core process exited with output: $err") - - val telemetryService = service() - telemetryService.capture("jetbrains_core_exit", mapOf("error" to err)) + service().reportMessage("Core process exited with output: $err") + service().capture("jetbrains_core_exit", mapOf("error" to err)) } private companion object { @@ -67,6 +65,7 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess { elevatePermissions() } + // todo: consider setting permissions ahead-of-time during build/packaging, not at runtime private fun elevatePermissions() { val path = getContinueBinaryPath() val permissions = setOf( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt index 21f920ef9..35e23d8a2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt @@ -6,6 +6,7 @@ import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId +import com.intellij.openapi.util.SystemInfo import com.intellij.ui.jcef.JBCefApp import io.sentry.Hint import io.sentry.Sentry @@ -26,6 +27,8 @@ class ContinueErrorService { config.setTag("ide_version", ApplicationInfo.getInstance().build.asString()) config.setTag("jcef_supported", JBCefApp.isSupported().toString()) config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version) + config.setTag("system", SystemInfo.OS_NAME) + config.setTag("system_version", SystemInfo.OS_VERSION) } } @@ -39,7 +42,14 @@ class ContinueErrorService { sentryEvent.message = Message().apply { this.message = message } val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) }) Sentry.captureEvent(sentryEvent, hint) - log.warn("Problem sent to Sentry: $message", throwable) + log.warn("Exception sent to Sentry: $message", throwable) + } + + fun reportMessage( + message: String, + ) { + Sentry.captureMessage(message) + log.warn("Message sent to Sentry: $message") } private companion object { From b3e4d368bd457401eff9d5eb0f5713efa1f56b1e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 10 Jul 2025 16:57:47 -0700 Subject: [PATCH 034/178] feat: remove logging code to telemetry --- core/autocomplete/util/AutocompleteLoggingService.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 4f600a8c5..58b3d2d0d 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -125,9 +125,6 @@ export class AutocompleteLoggingService { ? void Telemetry.capture("autocomplete", { ...toLog, enabledStaticContextualization: true, - prefix, - suffix, - prompt, }) : void Telemetry.capture("autocomplete", toLog); } From 30dbdee5dc10b5ff25b47d8c9751d206e946dfa1 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 10 Jul 2025 23:59:05 -0700 Subject: [PATCH 035/178] fix: reload assistants, not config --- gui/src/components/AssistantAndOrgListbox/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index 65b9e6a81..e9b3fb023 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -180,7 +180,7 @@ export function AssistantAndOrgListbox() { configLoading && "animate-spin-slow", )} /> - Reload config + Reload assistants From 572c4a7539a8405cc07326966c198172c3293bf0 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 11 Jul 2025 00:13:16 -0700 Subject: [PATCH 036/178] always show user email --- .../AssistantAndOrgListbox/index.tsx | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index e9b3fb023..a55758ca1 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -1,5 +1,5 @@ import { ArrowPathIcon, PlusIcon } from "@heroicons/react/24/outline"; -import { isOnPremSession } from "core/control-plane/AuthTypes"; +import { AuthType, isOnPremSession } from "core/control-plane/AuthTypes"; import { useContext, useEffect, useRef } from "react"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -126,19 +126,23 @@ export function AssistantAndOrgListbox() { - {shouldRenderOrgInfo && ( -
-
+
+
+ {session && session?.AUTH_TYPE !== AuthType.OnPrem && ( - {session.account.id} + {session?.account.id} - - -
+ )} + {shouldRenderOrgInfo && ( + <> + + + + )}
- )} +
Date: Fri, 11 Jul 2025 00:17:01 -0700 Subject: [PATCH 037/178] fix: reload assistants button leading to new assistant page --- gui/src/components/AssistantAndOrgListbox/index.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index a55758ca1..7072c38e3 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -165,18 +165,17 @@ export function AssistantAndOrgListbox() { login(false)} + onClick={async (e: any) => { + e.stopPropagation(); + await refreshProfiles(); + }} > { - e.stopPropagation(); - await refreshProfiles(); - }} > Date: Fri, 11 Jul 2025 00:27:49 -0700 Subject: [PATCH 038/178] fix: don't block user with "create your first assistant" --- .../AssistantOptions.tsx | 22 ++++++++++------ .../SelectedAssistantButton.tsx | 6 +++-- .../AssistantAndOrgListbox/index.tsx | 25 ++----------------- 3 files changed, 20 insertions(+), 33 deletions(-) diff --git a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx index 23c54184d..89ac2a81b 100644 --- a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx +++ b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx @@ -20,14 +20,20 @@ export function AssistantOptions({
- {profiles?.map((profile, idx) => ( - - ))} + {profiles?.length === 0 ? ( +
+ No assistants found +
+ ) : ( + profiles?.map((profile, idx) => ( + + )) + )}
); diff --git a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx index bb0a301e1..86ba08916 100644 --- a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx +++ b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx @@ -9,7 +9,7 @@ import { ListboxButton } from "../ui"; import { AssistantIcon } from "./AssistantIcon"; interface SelectedAssistantButtonProps { - selectedProfile: ProfileDescription; + selectedProfile: ProfileDescription | null; } export function SelectedAssistantButton({ @@ -25,7 +25,9 @@ export function SelectedAssistantButton({ style={{ fontSize: fontSize(-3) }} >
- {configLoading ? ( + {selectedProfile === null ? ( + "Create your first assistant" + ) : configLoading ? ( { - void ideMessenger.request("controlPlane/openUrl", { - path: "/new?type=assistant", - orgSlug: currentOrg?.slug, - }); - }} - className="text-description flex cursor-pointer select-none items-center gap-1" - style={{ fontSize: smallFont }} - > - - - Create your first assistant - -
- ); - } - return (
@@ -143,8 +121,9 @@ export function AssistantAndOrgListbox() { )}
+ From 48a5783abc352e56972c3487f2b620eac2b8ecba Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 11 Jul 2025 00:46:12 -0700 Subject: [PATCH 039/178] fix: after hub login, show user success message and tutorial --- .../OnboardingCard/components/OnboardingCardLanding.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx index d9eae491c..40abbea5f 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx @@ -31,6 +31,9 @@ export function OnboardingCardLanding({ // A new assistant is created when the account is created // We want to switch to this immediately void dispatch(selectFirstHubProfile()); + + ideMessenger.post("showTutorial", undefined); + ideMessenger.post("showToast", ["info", "🎉 Welcome to Continue!"]); } }); } From da0335ab3282346c058b520de88f890bdea61bef Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 11 Jul 2025 00:47:00 -0700 Subject: [PATCH 040/178] don't mention prompts in input placeholder --- gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 0cbb1e818..dd874e886 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -38,7 +38,7 @@ export function getPlaceholderText( } return historyLength === 0 - ? "Ask anything, '/' for prompts, '@' to add context" + ? "Ask anything, '@' to add context" : "Ask a follow-up"; } From ac96f3da03b0c59092e5ea9f595f4a894aff1474 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 11 Jul 2025 00:51:30 -0700 Subject: [PATCH 041/178] add padding to input box --- gui/src/components/mainInput/InputToolbar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index c58fc0eeb..b4ad6a860 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -74,7 +74,7 @@ function InputToolbar(props: InputToolbarProps) { <>
Date: Fri, 11 Jul 2025 01:00:53 -0700 Subject: [PATCH 042/178] feat: view config.yaml reference codelens --- .../DownloadYamlExtensionCodeLensProvider.ts | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts index dd46ad401..58b167e66 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts @@ -15,20 +15,34 @@ export class DownloadYamlExtensionCodeLensProvider if (!document.uri.fsPath.includes(".continue")) { return []; } - if (this.yamlExtensionDownloaded()) { - return []; - } - const codeLens: vscode.CodeLens = { + const codeLenses: vscode.CodeLens[] = []; + + // Always show documentation link + const docCodeLens: vscode.CodeLens = { range: new vscode.Range(0, 0, 0, 0), command: { - title: "Download YAML extension for Intellisense", - command: "workbench.extensions.installExtension", - arguments: ["redhat.vscode-yaml"], + title: "📖 View Continue Reference", + command: "vscode.open", + arguments: [vscode.Uri.parse("https://docs.continue.dev/reference")], }, isResolved: true, }; + codeLenses.push(docCodeLens); - return [codeLens]; + if (!this.yamlExtensionDownloaded()) { + const codeLens: vscode.CodeLens = { + range: new vscode.Range(0, 0, 0, 0), + command: { + title: "Download YAML extension for Intellisense", + command: "workbench.extensions.installExtension", + arguments: ["redhat.vscode-yaml"], + }, + isResolved: true, + }; + codeLenses.push(codeLens); + } + + return codeLenses; } } From 00fc90badca92b6d03c40eb2e2e3462ba3213aaf Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 27 Jun 2025 16:00:29 -0700 Subject: [PATCH 043/178] fix: :bug: Project structure creation with bare codeblocks is breaking markdown display and creation --- .../utils/isOpeningNestedBlock.test.ts | 157 ++++++++++++++++++ .../utils/isOpeningNestedBlock.ts | 66 ++++++++ .../utils/patchNestedMarkdown.test.ts | 8 + .../utils/patchNestedMarkdown.ts | 15 +- 4 files changed, 242 insertions(+), 4 deletions(-) create mode 100644 gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts create mode 100644 gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts diff --git a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts new file mode 100644 index 000000000..e5eb02f0c --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts @@ -0,0 +1,157 @@ +import { expect, test } from "vitest"; +import { isOpeningNestedBlock } from "./isOpeningNestedBlock"; + +test("isOpeningNestedBlock should return true when odd number of bare backticks ahead", () => { + const trimmedLines = [ + "```markdown", + "# Header", + + "```", // <- index 2: should be opening (1 ``` ahead = odd) + "content", + + "```", // <- index 4: closing (0 ``` ahead = even) + ]; + + expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(true); + expect(isOpeningNestedBlock(trimmedLines, 4, 2)).toBe(false); +}); + +test("isOpeningNestedBlock should return false when even number (zero) of bare backticks ahead", () => { + const trimmedLines = [ + "```markdown", + "# Header", + + "```", // <- index 2: should be closing (0 ``` ahead = even) + ]; + + expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); +}); + +test("isOpeningNestedBlock should handle multiple nested pairs", () => { + const trimmedLines = [ + "```markdown", + "# Header", + + "```", // <- index 2: opening (3 ``` ahead = odd) + "```", // <- index 3: opening (2 ``` ahead = even) -> should be false + "content", + + "```", // <- index 5: closing (1 ``` ahead = odd) -> should be true + "```", // <- index 6: closing (0 ``` ahead = even) -> should be false + ]; + + expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(true); // 3 ahead = odd + expect(isOpeningNestedBlock(trimmedLines, 3, 2)).toBe(false); // 2 ahead = even + expect(isOpeningNestedBlock(trimmedLines, 5, 2)).toBe(true); // 1 ahead = odd + expect(isOpeningNestedBlock(trimmedLines, 6, 1)).toBe(false); // 0 ahead = even +}); + +test("isOpeningNestedBlock should return false when reaching end of markdown block via ~~~", () => { + const trimmedLines = [ + "```markdown", + "# Header", + + "```", // <- index 2: should be closing since ~~~ terminates the block + "content", + + "~~~", // <- terminator stops counting + "```", // <- this one is after the markdown block ends + ]; + + expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); +}); + +test("isOpeningNestedBlock should return false when reaching new markdown block", () => { + const trimmedLines = [ + "```markdown", + "# Header", + + "```", // <- index 2: should be closing since new markdown block starts + "content", + + "```md", // <- new markdown block terminates counting + "```", // <- this one belongs to the new block + ]; + + expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); +}); + +test("isOpeningNestedBlock should handle empty content between backticks", () => { + const trimmedLines = [ + "```markdown", + + "```", // <- index 1: opening (1 ``` ahead = odd) + "", + + "```", // <- index 3: closing (0 ``` ahead = even) + ]; + + expect(isOpeningNestedBlock(trimmedLines, 1, 1)).toBe(true); + expect(isOpeningNestedBlock(trimmedLines, 3, 2)).toBe(false); +}); + +test("isOpeningNestedBlock should handle case where currentIndex is last line", () => { + const trimmedLines = [ + "```markdown", + "# Header", + + "```", // <- index 2: last line, should be closing (0 ahead = even) + ]; + + expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); +}); + +test("isOpeningNestedBlock should not be confused by backticks in content", () => { + const trimmedLines = [ + "```markdown", + "Some `code` with backticks", + + "```", // <- index 2: should be closing (0 bare ``` ahead = even) + ]; + + expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); +}); + +test("isOpeningNestedBlock should handle GitHub markdown variants as terminators", () => { + const trimmedLines = [ + "```markdown", + "# Header", + + "```", // <- index 2: should be closing (terminator stops counting) + "content", + + "```gfm", // <- GitHub markdown variant starts new block + "```", + ]; + + expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); +}); + +test("isOpeningNestedBlock should only check terminators at nest level 1", () => { + const trimmedLines = [ + "```markdown", + + "```", // <- index 1: at nest level 1, ~~~ should terminate counting + "~~~", // <- terminator found, stops counting + "```", // <- this doesn't count towards the logic + ]; + + expect(isOpeningNestedBlock(trimmedLines, 1, 1)).toBe(false); +}); + +test("isOpeningNestedBlock should handle complex realistic markdown structure", () => { + const trimmedLines = [ + "```markdown README.md", + "# Project Structure", + "", + "```", // <- index 3: has 2 ``` ahead (even), so should be closing + ".", + "│ └── file.ts", + "```", // <- index 7: has 1 ``` ahead (odd), so should be opening + "```", // <- index 8: has 0 ``` ahead (even), so should be closing + ]; + + expect(isOpeningNestedBlock(trimmedLines, 3, 1)).toBe(false); // 2 ahead = even + expect(isOpeningNestedBlock(trimmedLines, 7, 2)).toBe(true); // 1 ahead = odd + expect(isOpeningNestedBlock(trimmedLines, 8, 1)).toBe(false); // 0 ahead = even +}); diff --git a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts new file mode 100644 index 000000000..8327ed219 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts @@ -0,0 +1,66 @@ +import { headerIsMarkdown } from "./headerIsMarkdown"; + +/** + * Determines if a line with bare backticks (```) should be treated as opening + * a nested code block rather than closing the current block. + * + * Uses look-ahead to check if there are more bare backtick lines ahead, + * which would indicate this is opening a nested block. + * + * @param trimmedLines - Array of trimmed lines from the source + * @param currentIndex - Index of the current line with bare backticks + * @param nestCount - Current nesting level + * @returns true if this should open a nested block, false if it should close + */ +export function isOpeningNestedBlock( + trimmedLines: string[], + currentIndex: number, + nestCount: number, +): boolean { + // Simulate what would happen if we continue processing from this point + // Count how many blocks would need to be closed vs opened + + let simulatedNestCount = nestCount; + let bareBackticksAhead = 0; + + for (let j = currentIndex + 1; j < trimmedLines.length; j++) { + const line = trimmedLines[j]; + + // Count bare backticks lines + if (line.match(/^`+$/)) { + bareBackticksAhead++; + } else if (line.startsWith("```")) { + // Non-bare backticks (with language/type) always open + simulatedNestCount++; + } + + // Stop looking if we hit what appears to be the end of current markdown block + if (nestCount === 1) { + // At top level of markdown block - check for block terminators + if ( + line.startsWith("~~~") || + (line.startsWith("```") && headerIsMarkdown(line.replaceAll("`", ""))) + ) { + break; + } + } + } + + // The key insight: if we need the current backticks to close to get back to nestCount=1, + // and there are more bare backticks ahead than what we'd need to close everything, + // then this should open + + if (nestCount > 1) { + // We're deeply nested, usually should close + return bareBackticksAhead > nestCount - 1; + } + + // At top level (nestCount === 1), if there are exactly 2 ahead and we're at top level, + // this suggests: current=open, first_ahead=close, second_ahead=close_markdown + if (nestCount === 1 && bareBackticksAhead === 2) { + return true; + } + + // Default to the original logic + return bareBackticksAhead % 2 === 1; +} diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts index af94f118d..4e347a9e2 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts @@ -6,6 +6,14 @@ describe("patchNestedMarkdown", () => { expect(patchNestedMarkdown(source)).toBe(source); }); + it("should handle nested blocks without a type", () => { + const source = + "```markdown README.md\n# Project Structure\n\n```\n.\n├── AdvancedPage.tsx\n├── Calculator.java\n├── Dockerfile\n├── calculator_test/\n│ ├── Calculator.java\n│ └── Main.java\n├── data.json\n├── example.ipynb\n├── logs/\n├── nested-folder/\n│ ├── helloNested.py\n│ ├── package.json\n│ └── rules.md\n├── program.cs\n├── query.sql\n├── react-calculator/\n├── readme.md\n├── requirements.txt\n├── test.css\n├── test.html\n├── test.js\n├── test.kt\n├── test.php\n├── test.py\n├── test.rb\n├── test.rs\n├── test.sh\n└── test.ts\n```\n```"; + const expected = + "~~~markdown README.md\n# Project Structure\n\n```\n.\n├── AdvancedPage.tsx\n├── Calculator.java\n├── Dockerfile\n├── calculator_test/\n│ ├── Calculator.java\n│ └── Main.java\n├── data.json\n├── example.ipynb\n├── logs/\n├── nested-folder/\n│ ├── helloNested.py\n│ ├── package.json\n│ └── rules.md\n├── program.cs\n├── query.sql\n├── react-calculator/\n├── readme.md\n├── requirements.txt\n├── test.css\n├── test.html\n├── test.js\n├── test.kt\n├── test.php\n├── test.py\n├── test.rb\n├── test.rs\n├── test.sh\n└── test.ts\n```\n~~~"; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + it("should replace backticks with tildes for markdown codeblocks", () => { const source = "```markdown\n# Header\nSome text\n```"; const expected = "~~~markdown\n# Header\nSome text\n~~~"; diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 9be5bfbb2..30bd8fa1f 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -8,6 +8,7 @@ Note, this was benchmarked at sub-millisecond */ import { headerIsMarkdown } from "./headerIsMarkdown"; +import { isOpeningNestedBlock } from "./isOpeningNestedBlock"; export const patchNestedMarkdown = (source: string): string => { // Early return if no markdown codeblock pattern is found (including GitHub variants) @@ -24,10 +25,16 @@ export const patchNestedMarkdown = (source: string): string => { if (nestCount > 0) { // Inside a markdown block if (line.match(/^`+$/)) { - // Ending a block with just backticks (```) - nestCount--; - if (nestCount === 0) { - lines[i] = "~~~"; // End of markdown block + // Found bare backticks - determine if opening or closing + if (isOpeningNestedBlock(trimmedLines, i, nestCount)) { + // Opening a nested codeblock + nestCount++; + } else { + // Closing a block + nestCount--; + if (nestCount === 0) { + lines[i] = "~~~"; // End of markdown block + } } } else if (line.startsWith("```")) { // Going into a nested codeblock From 9cd2f8b34b2ef814b2d1f386c024f993cc66274a Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 17:43:32 -0700 Subject: [PATCH 044/178] enhancing the solution --- .../filtering/streamTransforms/lineStream.ts | 116 ++++- .../streamTransforms/lineStream.vitest.ts | 144 ++++++ core/edit/lazy/replace.ts | 14 +- core/edit/lazy/streamLazyApply.test.ts | 459 ++++++++++++++++++ core/edit/lazy/streamLazyApply.ts | 118 ++++- core/edit/recursiveStream.ts | 3 +- .../utils/isOpeningNestedBlock.test.ts | 157 ------ .../utils/isOpeningNestedBlock.ts | 66 --- .../utils/patchNestedMarkdown.ts | 25 +- 9 files changed, 836 insertions(+), 266 deletions(-) create mode 100644 core/edit/lazy/streamLazyApply.test.ts delete mode 100644 gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts delete mode 100644 gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index bc193cb12..eabfca5a7 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -16,6 +16,23 @@ export type CharacterFilter = (args: { multiline: boolean; }) => AsyncGenerator; +// Duplicated from gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts +function headerIsMarkdown(header: string): boolean { + return ( + header === "md" || + header === "markdown" || + header === "gfm" || + header === "github-markdown" || + header.includes(" md") || + header.includes(" markdown") || + header.includes(" gfm") || + header.includes(" github-markdown") || + header.split(" ")[0]?.split(".").pop() === "md" || + header.split(" ")[0]?.split(".").pop() === "markdown" || + header.split(" ")[0]?.split(".").pop() === "gfm" + ); +} + function isBracketEnding(line: string): boolean { return line .trim() @@ -331,25 +348,52 @@ export async function* removeTrailingWhitespace( /** * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. + * Now includes markdown-aware processing to handle nested markdown blocks properly. * * @param {LineStream} rawLines - The input stream of lines to filter. + * @param {string} filepath - Optional filepath to determine if this is a markdown file. * @yields {string} Filtered and processed lines from the code block. * * @description * This generator function performs the following tasks: * 1. Removes initial lines that should be removed before the actual code starts. - * 2. Filters out ending code block markers (```) unless they are the last line. - * 3. Handles special cases where lines should be changed and the stream should stop. - * 4. Yields processed lines that are part of the actual code block content. + * 2. For markdown files, applies nested markdown block logic to avoid premature termination. + * 3. For non-markdown files, uses original stopping behavior. + * 4. Handles special cases where lines should be changed and the stream should stop. + * 5. Yields processed lines that are part of the actual code block content. */ -export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { +export async function* filterCodeBlockLines( + rawLines: LineStream, + filepath?: string, +): LineStream { let seenFirstFence = false; // nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented - // when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early + // when an inner code block is discovered to avoid exiting the function prematurely. The function will exit early // when all blocks are matched. When no outer fence is discovered the function will always continue to the end. let nestCount = 0; + // Check if this is a markdown file and collect lines for analysis + const isMarkdownFile = + filepath && + ["md", "markdown", "gfm"].includes( + filepath.split(".").pop()?.toLowerCase() || "", + ); + + const allLines: string[] = []; for await (const line of rawLines) { + allLines.push(line); + } + + // Check if it has nested markdown blocks (like ```markdown or ```md) + const firstLine = allLines[0] || ""; + const hasNestedMarkdown = + (firstLine.startsWith("```") && + headerIsMarkdown(firstLine.replace(/`/g, ""))) || + (filepath && headerIsMarkdown(filepath)); + + for (let i = 0; i < allLines.length; i++) { + const line = allLines[i]; + if (!seenFirstFence) { if (shouldRemoveLineBeforeStart(line)) { // Filter out starting ``` or START block @@ -365,14 +409,66 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { const changedEndLine = shouldChangeLineAndStop(line); if (typeof changedEndLine === "string") { // Ending a block with just backticks (```) or STOP + + // For markdown files with nested markdown blocks, apply special logic + if (hasNestedMarkdown && line.trim() === "```") { + // Apply the same nested markdown logic as patchNestedMarkdown + const trimmedLines = allLines.map((l) => l.trim()); + + let markdownNestCount = 0; + let shouldStop = false; + + for (let j = 0; j <= i; j++) { + const currentLine = trimmedLines[j]; + + if (markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - count remaining ones + let remainingBareBackticks = 0; + for (let k = j + 1; k < trimmedLines.length; k++) { + if (trimmedLines[k].match(/^`+$/)) { + remainingBareBackticks++; + } + } + + // If this is the last bare backticks and we're at position i, stop + if (remainingBareBackticks === 0 && j === i) { + markdownNestCount = 0; + shouldStop = true; + break; + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + markdownNestCount = 1; + } + } + } + } + + if (shouldStop) { + return; // Stop without yielding the final closing ``` + } else { + // This is an inner block delimiter, yield it as content + yield line; + continue; + } + } + + // Original logic for non-markdown files or simple cases nestCount--; if (nestCount === 0) { - // if we are closing the outer block then exit early - // only exit early if the outer block was started with a block - // it it was text, we will never exit early + // We've closed the outer wrapper - stop without yielding the closing ``` return; } else { - // otherwise just yield the line + // This is a nested block closing, yield it as content yield line; } } else if (line.startsWith("```")) { @@ -380,7 +476,7 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { nestCount++; yield line; } else { - // otherwise just yield the line + // Otherwise just yield the line as content yield line; } } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index 8861b968c..f68447c39 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -301,6 +301,37 @@ describe("lineStream", () => { ]); }); + it("should ignore ticks inside of code blocks such as tests", async () => { + const linesGenerator = await getLineGenerator([ + "```typescript", + 'it("should handle included inner ticks", async () => {', + " const linesGenerator = await getLineGenerator([`", + ' "```md"', + ' "const x = 5;"', + ' "```bash"', + ' "echo ```test```"', + ' "```"', + ' "```"', + "]);", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + 'it("should handle included inner ticks", async () => {', + " const linesGenerator = await getLineGenerator([`", + ' "```md"', + ' "const x = 5;"', + ' "```bash"', + ' "echo ```test```"', + ' "```"', + ' "```"', + "]);", + ]); + }); + it("should handle included inner ticks", async () => { const linesGenerator = await getLineGenerator([ "```md", @@ -395,6 +426,119 @@ describe("lineStream", () => { "```", ]); }); + + // Markdown-aware tests + it("should handle markdown files with nested code blocks and a filename is included", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown README.md", + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines( + linesGenerator, + "README.md", + ); + const filteredLines = await getFilteredLines(result); + + // Should include all content up to the final closing ``` + expect(filteredLines).toEqual([ + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + ]); + }); + + // Markdown-aware tests + it("should handle markdown files with nested code blocks and a filename is excluded", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown README.md", + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + // Should include all content up to the final closing ``` + expect(filteredLines).toEqual([ + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + ]); + }); + + it("should handle non-markdown files normally with filepath parameter", async () => { + const linesGenerator = await getLineGenerator([ + "```", + "function test() {", + " return 'hello';", + "}", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js"); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "function test() {", + " return 'hello';", + "}", + ]); + }); + + it("should handle simple markdown code blocks", async () => { + const linesGenerator = await getLineGenerator([ + "```", + "Here's some code:", + "```", + "function example() {", + " console.log('test');", + "}", + "```", + ]); + + const result = lineStream.filterCodeBlockLines( + linesGenerator, + "README.md", + ); + const filteredLines = await getFilteredLines(result); + + // Should remove the outer markdown wrapper, and return just the inner content. + // The lack of an end tag should cause it to return all remaining lines. + expect(filteredLines).toEqual([ + "Here's some code:", + "```", + "function example() {", + " console.log('test');", + "}", + "```", + ]); + }); }); describe("filterEnglishLinesAtStart", () => { diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index 1a5ba704d..e7ec47dc9 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -1,8 +1,5 @@ import { ILLM } from "../.."; -import { - filterLeadingNewline, - stopAtLines, -} from "../../autocomplete/filtering/streamTransforms/lineStream"; +import { filterLeadingNewline } from "../../autocomplete/filtering/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { dedent } from "../../util"; @@ -90,11 +87,18 @@ export async function* getReplacementWithLlm( { role: "assistant", content: assistantPrompt }, ], abortController.signal, + { + raw: true, + prediction: undefined, + reasoning: false, + }, ); let lines = streamLines(completion); lines = filterLeadingNewline(lines); - lines = stopAtLines(lines, () => {}, ["```"]); + // We want to retrive everything from the llm + // then let the filterCodeBlocks function clean up for any trailing text. + // if we stop here early, we run the risk of loosing inner markdown content. for await (const line of lines) { yield line; diff --git a/core/edit/lazy/streamLazyApply.test.ts b/core/edit/lazy/streamLazyApply.test.ts new file mode 100644 index 000000000..3a829b5f4 --- /dev/null +++ b/core/edit/lazy/streamLazyApply.test.ts @@ -0,0 +1,459 @@ +import { streamLazyApply } from "./streamLazyApply"; + +// Mock LLM for testing +class MockLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate LLM response for markdown file with nested blocks + const lines = [ + "# Project Structure", + "", + "```markdown README.md", + "# Project Structure", + "", + "```", + ".", + "├── src/", + "│ └── main.js", + "└── package.json", + "```", + "```", + ]; + + // Yield each line separately (more realistic streaming) + for (const line of lines) { + yield line; + } + } +} + +class MockJavaScriptLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate LLM response for JavaScript file + const lines = [ + "function calculateSum(a, b) {", + " return a + b;", + "}", + "", + "function calculateProduct(a, b) {", + " return a * b;", + "}", + ]; + + for (const line of lines) { + yield line; + } + } +} + +class MockPythonLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate LLM response for Python file + const lines = [ + "def calculate_sum(a, b):", + " return a + b", + "", + "def calculate_product(a, b):", + " return a * b", + ]; + + for (const line of lines) { + yield line; + } + } +} + +class MockWithUnchangedCodeLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate LLM response with UNCHANGED_CODE markers + const lines = [ + "function newFunction() {", + " return 'new';", + "}", + "", + "// ... unchanged code ...", + "", + "function anotherFunction() {", + " return 'updated';", + "}", + ]; + + for (const line of lines) { + yield line; + } + } +} + +class MockTypeScriptLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + const lines = [ + "interface User {", + " id: number;", + " name: string;", + "}", + "", + "function getUser(id: number): User {", + " return { id, name: 'Test User' };", + "}", + ]; + + for (const line of lines) { + yield line; + } + } +} + +class MockEmptyLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Empty response + return; + } +} + +class MockSimpleLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + const lines = ["function test() {", " return true;", "}"]; + for (const line of lines) { + yield line; + } + } +} + +class MockRegularMarkdownLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate regular markdown with simple code block + const lines = [ + "# Debug Test Folder", + "The sole purpose of this folder is to open it when debugging.", + "", + "## File Structure", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "├── Dockerfile", + "└── test.ts", + "```", + ]; + + for (const line of lines) { + yield line; + } + } +} + +describe("streamLazyApply", () => { + test("should handle markdown files with nested blocks without stopping early", async () => { + const oldCode = "# Project\n\nBasic readme content."; + const newCode = `# Project Structure + +\`\`\`markdown README.md +# Project Structure + +\`\`\` +. +├── src/ +│ └── main.js +└── package.json +\`\`\` +\`\`\``; + const filename = "README.md"; + const llm = new MockLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines (not empty) + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain the nested markdown content + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("```markdown README.md"); + expect(allContent).toContain("└── package.json"); + + // Should not have been truncated at the first ``` + expect(allContent).toContain("src/"); + }); + + test("should handle JavaScript files correctly", async () => { + const oldCode = "function calculateSum(a, b) {\n return a + b;\n}"; + const newCode = `function calculateSum(a, b) { + return a + b; +} + +function calculateProduct(a, b) { + return a * b; +}`; + const filename = "calculator.js"; + const llm = new MockJavaScriptLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain the JavaScript functions + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("calculateSum"); + expect(allContent).toContain("calculateProduct"); + }); + + test("should handle Python files correctly", async () => { + const oldCode = "def calculate_sum(a, b):\n return a + b"; + const newCode = `def calculate_sum(a, b): + return a + b + +def calculate_product(a, b): + return a * b`; + const filename = "calculator.py"; + const llm = new MockPythonLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain the Python functions + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("calculate_sum"); + expect(allContent).toContain("calculate_product"); + }); + + test("should handle UNCHANGED_CODE markers in responses", async () => { + const oldCode = `function oldFunction() { + return 'old'; +} + +function existingFunction() { + return 'existing'; +}`; + const newCode = `function newFunction() { + return 'new'; +} + +function existingFunction() { + return 'existing'; +} + +function anotherFunction() { + return 'updated'; +}`; + const filename = "example.js"; + const llm = new MockWithUnchangedCodeLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain new and updated functions + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("newFunction"); + expect(allContent).toContain("anotherFunction"); + }); + + test("should handle TypeScript files correctly", async () => { + const oldCode = "interface User {\n id: number;\n}"; + const newCode = `interface User { + id: number; + name: string; +} + +function getUser(id: number): User { + return { id, name: 'Test User' }; +}`; + const filename = "user.ts"; + const llm = new MockTypeScriptLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain TypeScript interface and function + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("interface User"); + expect(allContent).toContain("getUser"); + expect(allContent).toContain("name: string"); + }); + + test("should work with empty LLM responses", async () => { + const oldCode = "function test() { return 1; }"; + const newCode = "function test() { return 2; }"; + const filename = "test.js"; + const llm = new MockEmptyLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should handle empty response gracefully + expect(diffLines).toBeDefined(); + }); + + test("should correctly identify markdown vs non-markdown files", async () => { + // Test that our isMarkdownFile logic works + const markdownFiles = ["README.md", "docs.markdown", "example.gfm"]; + const nonMarkdownFiles = [ + "script.js", + "code.py", + "style.css", + "component.tsx", + ]; + + // This is more of a unit test, but verifies our file detection logic + // We can test this indirectly by checking that different file types + // are processed through different code paths + + const oldCode = "function test() { return false; }"; + const newCode = "function test() { return true; }"; + const llm = new MockSimpleLLM() as any; + + // Test each file type + for (const filename of [...markdownFiles, ...nonMarkdownFiles]) { + const abortController = new AbortController(); + const diffLines = []; + + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should work for all file types + expect(diffLines.length).toBeGreaterThan(0); + + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("test"); + } + }); + + test("should handle regular markdown files with simple code blocks", async () => { + const oldCode = "# Old Content"; + const newCode = `# Debug Test Folder +The sole purpose of this folder is to open it when debugging. + +## File Structure +\`\`\` +debug-test-folder/ +├── AdvancedPage.tsx +├── Calculator.java +├── Dockerfile +└── test.ts +\`\`\``; + + const filename = "README.md"; + const llm = new MockRegularMarkdownLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines (not empty) + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain the full file structure + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("Debug Test Folder"); + expect(allContent).toContain("File Structure"); + expect(allContent).toContain("debug-test-folder/"); + expect(allContent).toContain("├── AdvancedPage.tsx"); + expect(allContent).toContain("└── test.ts"); + + // Should not have been truncated at the opening ``` + expect(allContent).toContain("Calculator.java"); + expect(allContent).toContain("Dockerfile"); + }); +}); diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index f8ec0905c..1186ca6de 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -2,7 +2,6 @@ import { filterLeadingAndTrailingNewLineInsertion, filterLeadingNewline, removeTrailingWhitespace, - stopAtLines, } from "../../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; @@ -11,6 +10,102 @@ import { DiffLine, ILLM } from "../../index.js"; import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js"; import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js"; +function headerIsMarkdown(header: string): boolean { + return ( + header === "md" || + header === "markdown" || + header === "gfm" || + header === "github-markdown" || + header.includes(" md") || + header.includes(" markdown") || + header.includes(" gfm") || + header.includes(" github-markdown") || + header.split(" ")[0]?.split(".").pop() === "md" || + header.split(" ")[0]?.split(".").pop() === "markdown" || + header.split(" ")[0]?.split(".").pop() === "gfm" + ); +} + +function isMarkdownFile(filename: string): boolean { + const ext = filename.split(".").pop()?.toLowerCase(); + return ["md", "markdown", "gfm"].includes(ext || ""); +} + +async function* stopAtLinesWithMarkdownSupport( + lines: LineStream, + filename: string, +): LineStream { + if (!isMarkdownFile(filename)) { + for await (const line of lines) { + if (line.trim() === "```") { + return; + } + yield line; + } + return; + } + + const allLines: string[] = []; + for await (const line of lines) { + allLines.push(line); + } + + const source = allLines.join("\n"); + if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) { + for (let i = 0; i < allLines.length; i++) { + if (allLines[i].trim() === "```") { + for (let j = 0; j < i; j++) { + yield allLines[j]; + } + return; + } + yield allLines[i]; + } + return; + } + + let nestCount = 0; + const trimmedLines = allLines.map((l) => l.trim()); + + for (let i = 0; i < trimmedLines.length; i++) { + const line = trimmedLines[i]; + + if (nestCount > 0) { + if (line.match(/^`+$/)) { + let remainingBareBackticks = 0; + for (let j = i + 1; j < trimmedLines.length; j++) { + if (trimmedLines[j].match(/^`+$/)) { + remainingBareBackticks++; + } + } + + if (remainingBareBackticks === 0) { + nestCount = 0; + for (let j = 0; j < i; j++) { + yield allLines[j]; + } + return; + } + } else if (line.startsWith("```")) { + nestCount++; + } + } else { + if (line.startsWith("```")) { + const header = line.replaceAll("`", ""); + const isMarkdown = headerIsMarkdown(header); + + if (isMarkdown) { + nestCount = 1; + } + } + } + } + + for (const line of allLines) { + yield line; + } +} + export async function* streamLazyApply( oldCode: string, filename: string, @@ -26,7 +121,6 @@ export async function* streamLazyApply( const promptMessages = promptFactory(oldCode, filename, newCode); const lazyCompletion = llm.streamChat(promptMessages, abortController.signal); - // Do find and replace over the lazy edit response async function* replacementFunction( oldCode: string, linesBefore: string[], @@ -44,20 +138,21 @@ export async function* streamLazyApply( } let lazyCompletionLines = streamLines(lazyCompletion, true); - // Process line output - // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); - lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); + + lazyCompletionLines = stopAtLinesWithMarkdownSupport( + lazyCompletionLines, + filename, + ); + lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines); - // Fill in unchanged code let lines = streamFillUnchangedCode( lazyCompletionLines, oldCode, replacementFunction, ); - // Convert output to diff const oldLines = oldCode.split(/\r?\n/); let diffLines = streamDiff(oldLines, lines); diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines); @@ -78,13 +173,11 @@ async function* streamFillUnchangedCode( const newLines = []; let buffer = []; let waitingForBuffer = false; - for await (const line of lines) { if (waitingForBuffer) { buffer.push(line); if (buffer.length >= BUFFER_LINES_BELOW) { - // Find the replacement and continue streaming once we have it const replacementLines = replacementFunction(oldCode, newLines, buffer); let replacement = ""; for await (const replacementLine of replacementLines) { @@ -92,8 +185,6 @@ async function* streamFillUnchangedCode( newLines.push(replacementLine); replacement += replacementLine + "\n"; } - - // Yield the buffered lines for (const bufferedLine of buffer) { yield bufferedLine; newLines.push(bufferedLine); @@ -108,9 +199,7 @@ async function* streamFillUnchangedCode( } if (line.includes(UNCHANGED_CODE)) { - // Buffer so we can give the context of BUFFER_LINES_BELOW lines below waitingForBuffer = true; - // TODO: If the UNCHANGED CODE is at the very top of the file we need to handle a bit differently } else { yield line; newLines.push(line); @@ -118,14 +207,11 @@ async function* streamFillUnchangedCode( } if (waitingForBuffer) { - // If we're still waiting for a buffer, we've reached the end of the stream - // and we should just look for the replacement with what we have const replacementLines = replacementFunction(oldCode, newLines, buffer); for await (const replacementLine of replacementLines) { yield replacementLine; newLines.push(replacementLine); } - // Yield the buffered lines for (const bufferedLine of buffer) { yield bufferedLine; newLines.push(bufferedLine); diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts index 004563cdb..d249755f4 100644 --- a/core/edit/recursiveStream.ts +++ b/core/edit/recursiveStream.ts @@ -63,7 +63,8 @@ export async function* recursiveStream( } } else { const generator = llm.streamChat(prompt, abortController.signal, { - prediction, + raw: true, + prediction: undefined, reasoning: false, }); diff --git a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts deleted file mode 100644 index e5eb02f0c..000000000 --- a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { expect, test } from "vitest"; -import { isOpeningNestedBlock } from "./isOpeningNestedBlock"; - -test("isOpeningNestedBlock should return true when odd number of bare backticks ahead", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be opening (1 ``` ahead = odd) - "content", - - "```", // <- index 4: closing (0 ``` ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(true); - expect(isOpeningNestedBlock(trimmedLines, 4, 2)).toBe(false); -}); - -test("isOpeningNestedBlock should return false when even number (zero) of bare backticks ahead", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be closing (0 ``` ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should handle multiple nested pairs", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: opening (3 ``` ahead = odd) - "```", // <- index 3: opening (2 ``` ahead = even) -> should be false - "content", - - "```", // <- index 5: closing (1 ``` ahead = odd) -> should be true - "```", // <- index 6: closing (0 ``` ahead = even) -> should be false - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(true); // 3 ahead = odd - expect(isOpeningNestedBlock(trimmedLines, 3, 2)).toBe(false); // 2 ahead = even - expect(isOpeningNestedBlock(trimmedLines, 5, 2)).toBe(true); // 1 ahead = odd - expect(isOpeningNestedBlock(trimmedLines, 6, 1)).toBe(false); // 0 ahead = even -}); - -test("isOpeningNestedBlock should return false when reaching end of markdown block via ~~~", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be closing since ~~~ terminates the block - "content", - - "~~~", // <- terminator stops counting - "```", // <- this one is after the markdown block ends - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should return false when reaching new markdown block", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be closing since new markdown block starts - "content", - - "```md", // <- new markdown block terminates counting - "```", // <- this one belongs to the new block - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should handle empty content between backticks", () => { - const trimmedLines = [ - "```markdown", - - "```", // <- index 1: opening (1 ``` ahead = odd) - "", - - "```", // <- index 3: closing (0 ``` ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 1, 1)).toBe(true); - expect(isOpeningNestedBlock(trimmedLines, 3, 2)).toBe(false); -}); - -test("isOpeningNestedBlock should handle case where currentIndex is last line", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: last line, should be closing (0 ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should not be confused by backticks in content", () => { - const trimmedLines = [ - "```markdown", - "Some `code` with backticks", - - "```", // <- index 2: should be closing (0 bare ``` ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should handle GitHub markdown variants as terminators", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be closing (terminator stops counting) - "content", - - "```gfm", // <- GitHub markdown variant starts new block - "```", - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should only check terminators at nest level 1", () => { - const trimmedLines = [ - "```markdown", - - "```", // <- index 1: at nest level 1, ~~~ should terminate counting - "~~~", // <- terminator found, stops counting - "```", // <- this doesn't count towards the logic - ]; - - expect(isOpeningNestedBlock(trimmedLines, 1, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should handle complex realistic markdown structure", () => { - const trimmedLines = [ - "```markdown README.md", - "# Project Structure", - "", - "```", // <- index 3: has 2 ``` ahead (even), so should be closing - ".", - "│ └── file.ts", - "```", // <- index 7: has 1 ``` ahead (odd), so should be opening - "```", // <- index 8: has 0 ``` ahead (even), so should be closing - ]; - - expect(isOpeningNestedBlock(trimmedLines, 3, 1)).toBe(false); // 2 ahead = even - expect(isOpeningNestedBlock(trimmedLines, 7, 2)).toBe(true); // 1 ahead = odd - expect(isOpeningNestedBlock(trimmedLines, 8, 1)).toBe(false); // 0 ahead = even -}); diff --git a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts deleted file mode 100644 index 8327ed219..000000000 --- a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { headerIsMarkdown } from "./headerIsMarkdown"; - -/** - * Determines if a line with bare backticks (```) should be treated as opening - * a nested code block rather than closing the current block. - * - * Uses look-ahead to check if there are more bare backtick lines ahead, - * which would indicate this is opening a nested block. - * - * @param trimmedLines - Array of trimmed lines from the source - * @param currentIndex - Index of the current line with bare backticks - * @param nestCount - Current nesting level - * @returns true if this should open a nested block, false if it should close - */ -export function isOpeningNestedBlock( - trimmedLines: string[], - currentIndex: number, - nestCount: number, -): boolean { - // Simulate what would happen if we continue processing from this point - // Count how many blocks would need to be closed vs opened - - let simulatedNestCount = nestCount; - let bareBackticksAhead = 0; - - for (let j = currentIndex + 1; j < trimmedLines.length; j++) { - const line = trimmedLines[j]; - - // Count bare backticks lines - if (line.match(/^`+$/)) { - bareBackticksAhead++; - } else if (line.startsWith("```")) { - // Non-bare backticks (with language/type) always open - simulatedNestCount++; - } - - // Stop looking if we hit what appears to be the end of current markdown block - if (nestCount === 1) { - // At top level of markdown block - check for block terminators - if ( - line.startsWith("~~~") || - (line.startsWith("```") && headerIsMarkdown(line.replaceAll("`", ""))) - ) { - break; - } - } - } - - // The key insight: if we need the current backticks to close to get back to nestCount=1, - // and there are more bare backticks ahead than what we'd need to close everything, - // then this should open - - if (nestCount > 1) { - // We're deeply nested, usually should close - return bareBackticksAhead > nestCount - 1; - } - - // At top level (nestCount === 1), if there are exactly 2 ahead and we're at top level, - // this suggests: current=open, first_ahead=close, second_ahead=close_markdown - if (nestCount === 1 && bareBackticksAhead === 2) { - return true; - } - - // Default to the original logic - return bareBackticksAhead % 2 === 1; -} diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 30bd8fa1f..224ed18bf 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -8,7 +8,6 @@ Note, this was benchmarked at sub-millisecond */ import { headerIsMarkdown } from "./headerIsMarkdown"; -import { isOpeningNestedBlock } from "./isOpeningNestedBlock"; export const patchNestedMarkdown = (source: string): string => { // Early return if no markdown codeblock pattern is found (including GitHub variants) @@ -25,19 +24,23 @@ export const patchNestedMarkdown = (source: string): string => { if (nestCount > 0) { // Inside a markdown block if (line.match(/^`+$/)) { - // Found bare backticks - determine if opening or closing - if (isOpeningNestedBlock(trimmedLines, i, nestCount)) { - // Opening a nested codeblock - nestCount++; - } else { - // Closing a block - nestCount--; - if (nestCount === 0) { - lines[i] = "~~~"; // End of markdown block + // Found bare backticks + // Count how many bare backticks are remaining after this one + let remainingBareBackticks = 0; + for (let j = i + 1; j < trimmedLines.length; j++) { + if (trimmedLines[j].match(/^`+$/)) { + remainingBareBackticks++; } } + + // If this is the last bare backticks, it closes the markdown block + if (remainingBareBackticks === 0) { + nestCount = 0; + lines[i] = "~~~"; // Convert final closing delimiter to tildes + } + // Otherwise, keep as backticks (inner nested block delimiter) } else if (line.startsWith("```")) { - // Going into a nested codeblock + // Going into a nested codeblock (with language identifier) nestCount++; } } else { From 370b68ca1a12b777df43c7d5bf02207018f7e9d3 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 17:58:29 -0700 Subject: [PATCH 045/178] linting fixes --- .../filtering/streamTransforms/lineStream.ts | 185 +++++++++------ .../streamTransforms/lineStream.vitest.ts | 213 ++++++++++++++++++ 2 files changed, 335 insertions(+), 63 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index eabfca5a7..b603bc9ea 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -88,6 +88,118 @@ function isUselessLine(line: string): boolean { return hasUselessLine || trimmed.startsWith("// end"); } +/** + * Determines if a file is a markdown file based on its filepath. + */ +export function isMarkdownFile(filepath?: string): boolean { + if (!filepath) { + return false; + } + + return ["md", "markdown", "gfm"].includes( + filepath.split(".").pop()?.toLowerCase() || "", + ); +} + +/** + * Determines if the code block has nested markdown blocks. + */ +export function hasNestedMarkdownBlocks( + firstLine: string, + filepath?: string, +): boolean { + return ( + (firstLine.startsWith("```") && + headerIsMarkdown(firstLine.replace(/`/g, ""))) || + Boolean(filepath && headerIsMarkdown(filepath)) + ); +} + +/** + * Collects all lines from a LineStream into an array for analysis. + */ +export async function collectAllLines(rawLines: LineStream): Promise { + const allLines: string[] = []; + for await (const line of rawLines) { + allLines.push(line); + } + return allLines; +} + +/** + * Determines if we should stop at a markdown block based on nested markdown logic. + * This handles the complex case where markdown blocks contain other markdown blocks. + */ +export function shouldStopAtMarkdownBlock( + allLines: string[], + currentIndex: number, + hasNestedMarkdown: boolean, +): boolean { + if (!hasNestedMarkdown || allLines[currentIndex].trim() !== "```") { + return false; + } + + // Apply the same nested markdown logic as patchNestedMarkdown + const trimmedLines = allLines.map((l) => l.trim()); + let markdownNestCount = 0; + let shouldStop = false; + + for (let j = 0; j <= currentIndex; j++) { + const currentLine = trimmedLines[j]; + + if (markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - count remaining ones + let remainingBareBackticks = 0; + for (let k = j + 1; k < trimmedLines.length; k++) { + if (trimmedLines[k].match(/^`+$/)) { + remainingBareBackticks++; + } + } + + // If this is the last bare backticks and we're at position currentIndex, stop + if (remainingBareBackticks === 0 && j === currentIndex) { + markdownNestCount = 0; + shouldStop = true; + break; + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + markdownNestCount = 1; + } + } + } + } + + return shouldStop; +} + +/** + * Processes block nesting logic and returns updated state. + */ +export function processBlockNesting( + line: string, + seenFirstFence: boolean, +): { newSeenFirstFence: boolean; shouldSkip: boolean } { + if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) { + return { newSeenFirstFence: false, shouldSkip: true }; + } + + if (!seenFirstFence) { + return { newSeenFirstFence: true, shouldSkip: false }; + } + + return { newSeenFirstFence: seenFirstFence, shouldSkip: false }; +} + export const USELESS_LINES = [""]; export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"]; export const CODE_STOP_BLOCK = "[/CODE]"; @@ -372,34 +484,22 @@ export async function* filterCodeBlockLines( // when all blocks are matched. When no outer fence is discovered the function will always continue to the end. let nestCount = 0; - // Check if this is a markdown file and collect lines for analysis - const isMarkdownFile = - filepath && - ["md", "markdown", "gfm"].includes( - filepath.split(".").pop()?.toLowerCase() || "", - ); - - const allLines: string[] = []; - for await (const line of rawLines) { - allLines.push(line); - } + // Collect all lines for analysis + const allLines = await collectAllLines(rawLines); // Check if it has nested markdown blocks (like ```markdown or ```md) const firstLine = allLines[0] || ""; - const hasNestedMarkdown = - (firstLine.startsWith("```") && - headerIsMarkdown(firstLine.replace(/`/g, ""))) || - (filepath && headerIsMarkdown(filepath)); + const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); for (let i = 0; i < allLines.length; i++) { const line = allLines[i]; - if (!seenFirstFence) { - if (shouldRemoveLineBeforeStart(line)) { - // Filter out starting ``` or START block - continue; - } - // Regardless of a fence or START block start tracking the nesting level + // Process block nesting logic for the first fence + const nesting = processBlockNesting(line, seenFirstFence); + if (nesting.shouldSkip) { + continue; // Filter out starting ``` or START block + } + if (!seenFirstFence && nesting.newSeenFirstFence) { seenFirstFence = true; nestCount = 1; } @@ -412,48 +512,7 @@ export async function* filterCodeBlockLines( // For markdown files with nested markdown blocks, apply special logic if (hasNestedMarkdown && line.trim() === "```") { - // Apply the same nested markdown logic as patchNestedMarkdown - const trimmedLines = allLines.map((l) => l.trim()); - - let markdownNestCount = 0; - let shouldStop = false; - - for (let j = 0; j <= i; j++) { - const currentLine = trimmedLines[j]; - - if (markdownNestCount > 0) { - // Inside a markdown block - if (currentLine.match(/^`+$/)) { - // Found bare backticks - count remaining ones - let remainingBareBackticks = 0; - for (let k = j + 1; k < trimmedLines.length; k++) { - if (trimmedLines[k].match(/^`+$/)) { - remainingBareBackticks++; - } - } - - // If this is the last bare backticks and we're at position i, stop - if (remainingBareBackticks === 0 && j === i) { - markdownNestCount = 0; - shouldStop = true; - break; - } - } else if (currentLine.startsWith("```")) { - // Going into a nested codeblock - markdownNestCount++; - } - } else { - // Not inside a markdown block yet - if (currentLine.startsWith("```")) { - const header = currentLine.replaceAll("`", ""); - if (headerIsMarkdown(header)) { - markdownNestCount = 1; - } - } - } - } - - if (shouldStop) { + if (shouldStopAtMarkdownBlock(allLines, i, hasNestedMarkdown)) { return; // Stop without yielding the final closing ``` } else { // This is an inner block delimiter, yield it as content diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index f68447c39..c37e853b5 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -757,4 +757,217 @@ describe("lineStream", () => { expect(mockFullStop).toHaveBeenCalledTimes(1); }); }); + + // Tests for new helper functions + describe("isMarkdownFile", () => { + it("should return true for markdown file extensions", () => { + expect(lineStream.isMarkdownFile("README.md")).toBe(true); + expect(lineStream.isMarkdownFile("docs.markdown")).toBe(true); + expect(lineStream.isMarkdownFile("notes.gfm")).toBe(true); + expect(lineStream.isMarkdownFile("path/to/file.md")).toBe(true); + }); + + it("should return false for non-markdown file extensions", () => { + expect(lineStream.isMarkdownFile("script.js")).toBe(false); + expect(lineStream.isMarkdownFile("styles.css")).toBe(false); + expect(lineStream.isMarkdownFile("document.txt")).toBe(false); + expect(lineStream.isMarkdownFile("config.json")).toBe(false); + }); + + it("should return false for undefined or empty filepath", () => { + expect(lineStream.isMarkdownFile(undefined)).toBe(false); + expect(lineStream.isMarkdownFile("")).toBe(false); + }); + + it("should handle case insensitive extensions", () => { + expect(lineStream.isMarkdownFile("README.MD")).toBe(true); + expect(lineStream.isMarkdownFile("docs.MARKDOWN")).toBe(true); + expect(lineStream.isMarkdownFile("notes.GFM")).toBe(true); + }); + }); + + describe("hasNestedMarkdownBlocks", () => { + it("should detect nested markdown blocks from first line", () => { + expect(lineStream.hasNestedMarkdownBlocks("```markdown", undefined)).toBe( + true, + ); + expect(lineStream.hasNestedMarkdownBlocks("```md", undefined)).toBe(true); + expect(lineStream.hasNestedMarkdownBlocks("```gfm", undefined)).toBe( + true, + ); + }); + + it("should detect nested markdown blocks from filepath", () => { + expect( + lineStream.hasNestedMarkdownBlocks("```typescript", "README.md"), + ).toBe(true); + expect( + lineStream.hasNestedMarkdownBlocks("```javascript", "docs.markdown"), + ).toBe(true); + }); + + it("should return false for non-markdown scenarios", () => { + expect( + lineStream.hasNestedMarkdownBlocks("```typescript", "script.js"), + ).toBe(false); + expect(lineStream.hasNestedMarkdownBlocks("```python", undefined)).toBe( + false, + ); + expect( + lineStream.hasNestedMarkdownBlocks("const x = 5;", undefined), + ).toBe(false); + }); + + it("should handle complex first line scenarios", () => { + expect( + lineStream.hasNestedMarkdownBlocks("```markdown README.md", undefined), + ).toBe(true); + expect( + lineStream.hasNestedMarkdownBlocks("```md with extra text", undefined), + ).toBe(true); + }); + }); + + describe("collectAllLines", () => { + it("should collect all lines from a stream", async () => { + const linesGenerator = await getLineGenerator([ + "line1", + "line2", + "line3", + ]); + + const result = await lineStream.collectAllLines(linesGenerator); + + expect(result).toEqual(["line1", "line2", "line3"]); + }); + + it("should handle empty stream", async () => { + const linesGenerator = await getLineGenerator([]); + + const result = await lineStream.collectAllLines(linesGenerator); + + expect(result).toEqual([]); + }); + + it("should handle stream with empty lines", async () => { + const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]); + + const result = await lineStream.collectAllLines(linesGenerator); + + expect(result).toEqual(["", "line2", "", "line4"]); + }); + }); + + describe("shouldStopAtMarkdownBlock", () => { + it("should return false when hasNestedMarkdown is false", () => { + const allLines = ["```markdown", "content", "```"]; + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, false)).toBe( + false, + ); + }); + + it("should return false when current line is not closing backticks", () => { + const allLines = ["```markdown", "content", "more content"]; + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( + false, + ); + }); + + it("should handle simple nested markdown case", () => { + const allLines = ["```markdown", "# Title", "```"]; + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( + true, + ); + }); + + it("should handle complex nested markdown with inner code blocks", () => { + const allLines = [ + "```markdown", + "# Title", + "```javascript", + "console.log('hello');", + "```", + "```", + ]; + // At index 4 (first inner closing), should not stop + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 4, true)).toBe( + false, + ); + // At index 5 (outer closing), should stop + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 5, true)).toBe( + true, + ); + }); + + it("should handle multiple bare backticks scenario", () => { + const allLines = [ + "```markdown", + "Content with ```inline code```", + "```", + "More content", + "```", + ]; + // At index 2, should not stop (not the last bare backticks) + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( + false, + ); + // At index 4, should stop (last bare backticks) + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 4, true)).toBe( + true, + ); + }); + }); + + describe("processBlockNesting", () => { + it("should skip lines that should be removed before start", () => { + const result = lineStream.processBlockNesting("```typescript", false); + expect(result).toEqual({ + newSeenFirstFence: false, + shouldSkip: true, + }); + }); + + it("should skip [CODE] blocks", () => { + const result = lineStream.processBlockNesting("[CODE]", false); + expect(result).toEqual({ + newSeenFirstFence: false, + shouldSkip: true, + }); + }); + + it("should set first fence when not seen yet", () => { + const result = lineStream.processBlockNesting("const x = 5;", false); + expect(result).toEqual({ + newSeenFirstFence: true, + shouldSkip: false, + }); + }); + + it("should not change state when first fence already seen", () => { + const result = lineStream.processBlockNesting("const x = 5;", true); + expect(result).toEqual({ + newSeenFirstFence: true, + shouldSkip: false, + }); + }); + + it("should handle prefix", () => { + const result = lineStream.processBlockNesting("", false); + expect(result).toEqual({ + newSeenFirstFence: false, + shouldSkip: true, + }); + }); + + it("should handle START EDITING HERE blocks", () => { + const result = lineStream.processBlockNesting( + "", + false, + ); + expect(result).toEqual({ + newSeenFirstFence: false, + shouldSkip: true, + }); + }); + }); }); From 49cf77997cfab9eccb0012a66f967f2684d762c4 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 22:02:36 -0700 Subject: [PATCH 046/178] performance enhancements --- .../filtering/streamTransforms/lineStream.ts | 131 ++++++---- .../streamTransforms/lineStream.vitest.ts | 228 ++++++++++++++++-- 2 files changed, 285 insertions(+), 74 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index b603bc9ea..b36d3e3a4 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -127,59 +127,82 @@ export async function collectAllLines(rawLines: LineStream): Promise { } /** - * Determines if we should stop at a markdown block based on nested markdown logic. - * This handles the complex case where markdown blocks contain other markdown blocks. + * State tracker for markdown block analysis to avoid recomputing on each call. */ -export function shouldStopAtMarkdownBlock( - allLines: string[], - currentIndex: number, - hasNestedMarkdown: boolean, -): boolean { - if (!hasNestedMarkdown || allLines[currentIndex].trim() !== "```") { - return false; - } +export class MarkdownBlockState { + private trimmedLines: string[]; + private bareBacktickPositions: number[]; + private markdownNestCount: number = 0; + private lastProcessedIndex: number = -1; - // Apply the same nested markdown logic as patchNestedMarkdown - const trimmedLines = allLines.map((l) => l.trim()); - let markdownNestCount = 0; - let shouldStop = false; - - for (let j = 0; j <= currentIndex; j++) { - const currentLine = trimmedLines[j]; - - if (markdownNestCount > 0) { - // Inside a markdown block - if (currentLine.match(/^`+$/)) { - // Found bare backticks - count remaining ones - let remainingBareBackticks = 0; - for (let k = j + 1; k < trimmedLines.length; k++) { - if (trimmedLines[k].match(/^`+$/)) { - remainingBareBackticks++; - } - } - - // If this is the last bare backticks and we're at position currentIndex, stop - if (remainingBareBackticks === 0 && j === currentIndex) { - markdownNestCount = 0; - shouldStop = true; - break; - } - } else if (currentLine.startsWith("```")) { - // Going into a nested codeblock - markdownNestCount++; - } - } else { - // Not inside a markdown block yet - if (currentLine.startsWith("```")) { - const header = currentLine.replaceAll("`", ""); - if (headerIsMarkdown(header)) { - markdownNestCount = 1; - } + constructor(allLines: string[]) { + this.trimmedLines = allLines.map((l) => l.trim()); + // Pre-compute positions of all bare backtick lines for faster lookup + this.bareBacktickPositions = []; + for (let i = 0; i < this.trimmedLines.length; i++) { + if (this.trimmedLines[i].match(/^`+$/)) { + this.bareBacktickPositions.push(i); } } } - return shouldStop; + /** + * Determines if we should stop at the given markdown block position. + * Maintains state across calls to avoid redundant computation. + */ + shouldStopAtPosition(currentIndex: number): boolean { + if (this.trimmedLines[currentIndex] !== "```") { + return false; + } + + // Process any lines we haven't seen yet up to currentIndex + for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { + const currentLine = this.trimmedLines[j]; + + if (this.markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - check if this is the last one + if (j === currentIndex) { + const remainingBareBackticks = this.bareBacktickPositions.filter( + (pos) => pos > j, + ).length; + if (remainingBareBackticks === 0) { + this.markdownNestCount = 0; + this.lastProcessedIndex = j; + return true; + } + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + this.markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + this.markdownNestCount = 1; + } + } + } + } + + this.lastProcessedIndex = currentIndex; + return false; + } +} + +/** + * Determines if we should stop at a markdown block based on nested markdown logic. + * This handles the complex case where markdown blocks contain other markdown blocks. + * Uses optimized state tracking to avoid redundant computation. + */ +export function shouldStopAtMarkdownBlock( + stateTracker: MarkdownBlockState, + currentIndex: number, +): boolean { + return stateTracker.shouldStopAtPosition(currentIndex); } /** @@ -491,6 +514,12 @@ export async function* filterCodeBlockLines( const firstLine = allLines[0] || ""; const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); + // Create optimized state tracker for markdown block analysis if needed + let markdownStateTracker: MarkdownBlockState | undefined; + if (hasNestedMarkdown) { + markdownStateTracker = new MarkdownBlockState(allLines); + } + for (let i = 0; i < allLines.length; i++) { const line = allLines[i]; @@ -511,8 +540,12 @@ export async function* filterCodeBlockLines( // Ending a block with just backticks (```) or STOP // For markdown files with nested markdown blocks, apply special logic - if (hasNestedMarkdown && line.trim() === "```") { - if (shouldStopAtMarkdownBlock(allLines, i, hasNestedMarkdown)) { + if ( + hasNestedMarkdown && + line.trim() === "```" && + markdownStateTracker + ) { + if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) { return; // Stop without yielding the final closing ``` } else { // This is an inner block delimiter, yield it as content diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index c37e853b5..709b744d9 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -859,25 +859,16 @@ describe("lineStream", () => { }); describe("shouldStopAtMarkdownBlock", () => { - it("should return false when hasNestedMarkdown is false", () => { - const allLines = ["```markdown", "content", "```"]; - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, false)).toBe( - false, - ); - }); - it("should return false when current line is not closing backticks", () => { const allLines = ["```markdown", "content", "more content"]; - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( - false, - ); + const state = new lineStream.MarkdownBlockState(allLines); + expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(false); }); it("should handle simple nested markdown case", () => { const allLines = ["```markdown", "# Title", "```"]; - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( - true, - ); + const state = new lineStream.MarkdownBlockState(allLines); + expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(true); }); it("should handle complex nested markdown with inner code blocks", () => { @@ -889,14 +880,11 @@ describe("lineStream", () => { "```", "```", ]; + const state = new lineStream.MarkdownBlockState(allLines); // At index 4 (first inner closing), should not stop - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 4, true)).toBe( - false, - ); + expect(lineStream.shouldStopAtMarkdownBlock(state, 4)).toBe(false); // At index 5 (outer closing), should stop - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 5, true)).toBe( - true, - ); + expect(lineStream.shouldStopAtMarkdownBlock(state, 5)).toBe(true); }); it("should handle multiple bare backticks scenario", () => { @@ -907,14 +895,11 @@ describe("lineStream", () => { "More content", "```", ]; + const state = new lineStream.MarkdownBlockState(allLines); // At index 2, should not stop (not the last bare backticks) - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( - false, - ); + expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(false); // At index 4, should stop (last bare backticks) - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 4, true)).toBe( - true, - ); + expect(lineStream.shouldStopAtMarkdownBlock(state, 4)).toBe(true); }); }); @@ -970,4 +955,197 @@ describe("lineStream", () => { }); }); }); + + describe("MarkdownBlockState", () => { + it("should initialize with correct state", () => { + const allLines = ["```markdown", "content", "```", "more content", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + // Test basic initialization - we can't directly test private properties, + // but we can test the behavior through shouldStopAtPosition + expect(state).toBeDefined(); + }); + + it("should correctly identify bare backticks positions", () => { + const allLines = ["```markdown", "```", "content", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + // At position 1 (first bare backticks), should not stop + expect(state.shouldStopAtPosition(1)).toBe(false); + // At position 3 (last bare backticks), should stop + expect(state.shouldStopAtPosition(3)).toBe(true); + }); + + it("should maintain state across multiple calls", () => { + const allLines = [ + "```markdown", + "# Title", + "```javascript", + "console.log('test');", + "```", + "More content", + "```", + ]; + const state = new lineStream.MarkdownBlockState(allLines); + + // Process positions incrementally + expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block + expect(state.shouldStopAtPosition(4)).toBe(false); // End of inner block + expect(state.shouldStopAtPosition(6)).toBe(true); // End of outer block + }); + + it("should handle complex nesting scenarios efficiently", () => { + const allLines = [ + "```markdown", + "# Documentation", + "```typescript", + "interface Config {", + " name: string;", + "}", + "```", + "", + "```bash", + "npm install", + "```", + "", + "Final notes", + "```", + ]; + const state = new lineStream.MarkdownBlockState(allLines); + + // Test multiple positions in sequence + expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block + expect(state.shouldStopAtPosition(10)).toBe(false); // End of second inner block + expect(state.shouldStopAtPosition(13)).toBe(true); // End of outer markdown block + }); + + it("should handle non-backtick lines correctly", () => { + const allLines = ["```markdown", "regular content", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + // Position 1 is not backticks, should return false + expect(state.shouldStopAtPosition(1)).toBe(false); + }); + + it("should handle empty lines and edge cases", () => { + const allLines = ["```markdown", "", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line + expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks + }); + + it("should reset nest count when reaching final bare backticks", () => { + const allLines = ["```markdown", "content", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + // First call should stop and reset count + expect(state.shouldStopAtPosition(2)).toBe(true); + + // If we had more content, it should start fresh + // (This tests the internal state management) + }); + }); + + describe("shouldStopAtMarkdownBlock optimization", () => { + it("should maintain performance benefits with state reuse", () => { + const allLines = Array.from({ length: 100 }, (_, i) => { + if (i === 0) return "```markdown"; + if (i === 99) return "```"; + if (i % 10 === 0) return "```javascript"; + if (i % 10 === 5) return "```"; + return `line ${i}`; + }); + + const state = new lineStream.MarkdownBlockState(allLines); + + // Test that we can call multiple times without recomputing everything + const start = performance.now(); + + // Test several positions in sequence + for (let i = 10; i < 90; i += 10) { + if (allLines[i].trim() === "```") { + lineStream.shouldStopAtMarkdownBlock(state, i); + } + } + + const duration = performance.now() - start; + expect(duration).toBeLessThan(10); // Should be very fast due to state caching + }); + }); + + describe("filterCodeBlockLines with optimized MarkdownBlockState", () => { + it("should use optimized state tracker for markdown files", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown", + "# Documentation", + "```typescript", + "const config = { name: 'test' };", + "```", + "Final notes", + "```", + ]); + + const result = lineStream.filterCodeBlockLines( + linesGenerator, + "README.md", + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "# Documentation", + "```typescript", + "const config = { name: 'test' };", + "```", + "Final notes", + ]); + }); + + it("should fall back to legacy behavior when no markdown nesting detected", async () => { + const linesGenerator = await getLineGenerator([ + "```typescript", + "const x = 5;", + "```", + ]); + + const result = lineStream.filterCodeBlockLines( + linesGenerator, + "script.ts", + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should handle mixed markdown and code scenarios with optimization", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "## API Reference", + "", + "```javascript", + "async function fetchData() {", + " return await fetch('/api/data');", + "}", + "```", + "", + "Usage notes and more documentation.", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "## API Reference", + "", + "```javascript", + "async function fetchData() {", + " return await fetch('/api/data');", + "}", + "```", + "", + "Usage notes and more documentation.", + ]); + }); + }); }); From 0a29810ee038d4494664e664563d9d3f5a3dc003 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 22:19:51 -0700 Subject: [PATCH 047/178] add checks to avoid stopping prematurely on stop constants --- .../filtering/streamTransforms/lineStream.ts | 87 +++++++++++- .../streamTransforms/lineStream.vitest.ts | 134 ++++++++++++++++++ 2 files changed, 218 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index b36d3e3a4..a674c7d1b 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -67,13 +67,47 @@ function shouldRemoveLineBeforeStart(line: string): boolean { ); } -function shouldChangeLineAndStop(line: string): string | undefined { +export function shouldChangeLineAndStop(line: string): string | undefined { if (line.trimStart() === "```") { return line; } + // Check if [/CODE] appears in the line if (line.includes(CODE_STOP_BLOCK)) { - return line.split(CODE_STOP_BLOCK)[0].trimEnd(); + const stopBlockIndex = line.indexOf(CODE_STOP_BLOCK); + + // Check if [/CODE] is preceded by a non-whitespace character + // If so, it might be part of an identifier, so don't handle it + if (stopBlockIndex > 0) { + const charBefore = line[stopBlockIndex - 1]; + if (charBefore && !charBefore.match(/\s/)) { + return undefined; // Don't handle [/CODE] that's part of an identifier + } + } + + // Check if [/CODE] appears to be inside quotes + // Simple heuristic: count unmatched quotes before the stop block + const beforeStopBlock = line.substring(0, stopBlockIndex); + const singleQuotes = (beforeStopBlock.match(/'/g) || []).length; + const doubleQuotes = (beforeStopBlock.match(/"/g) || []).length; + + // If there's an odd number of quotes before [/CODE], we're likely inside quotes + if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { + return undefined; // Don't handle [/CODE] inside quotes + } + + // Get the trimmed line to check if [/CODE] is at logical start + const trimmedLine = line.trimStart(); + + if (trimmedLine.startsWith(CODE_STOP_BLOCK)) { + // [/CODE] is at the logical start (after whitespace only) + if (trimmedLine === CODE_STOP_BLOCK) { + return line; // Return the whole line including leading whitespace + } + } + + // [/CODE] appears after some content (separated by whitespace) - return part before + return beforeStopBlock.trimEnd(); } return undefined; @@ -413,7 +447,54 @@ export async function* stopAtLines( linesToStopAt: string[] = LINES_TO_STOP_AT, ): LineStream { for await (const line of stream) { - if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) { + let shouldStop = false; + + // Check each stop phrase + for (const stopAt of linesToStopAt) { + if (line.includes(stopAt)) { + const stopAtIndex = line.indexOf(stopAt); + + // Check if stop phrase is preceded by a non-whitespace character + // If so, it might be part of an identifier, so don't handle it + if (stopAtIndex > 0) { + const charBefore = line[stopAtIndex - 1]; + if (charBefore && !charBefore.match(/\s/)) { + continue; // Don't handle stop phrase that's part of an identifier + } + } + + // Check if stop phrase appears to be inside quotes + // Simple heuristic: count unmatched quotes before the stop phrase + const beforeStopPhrase = line.substring(0, stopAtIndex); + const singleQuotes = (beforeStopPhrase.match(/'/g) || []).length; + const doubleQuotes = (beforeStopPhrase.match(/"/g) || []).length; + + // If there's an odd number of quotes before stop phrase, we're likely inside quotes + if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { + continue; // Don't handle stop phrase inside quotes + } + + // Get the trimmed line to check if stop phrase is at logical start + const trimmedLine = line.trimStart(); + + if (trimmedLine.startsWith(stopAt)) { + // Stop phrase is at the logical start (after whitespace only) - should stop + shouldStop = true; + break; + } else { + // Stop phrase appears after some content - check if it's separated by whitespace + const contentBeforeStopPhrase = beforeStopPhrase.trimEnd(); + if (contentBeforeStopPhrase.length < beforeStopPhrase.length) { + // There's whitespace before the stop phrase, so it's properly separated + shouldStop = true; + break; + } + // If no whitespace separation, it's part of larger text, so continue + } + } + } + + if (shouldStop) { fullStop(); break; } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index 709b744d9..ff137f442 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -174,6 +174,93 @@ describe("lineStream", () => { expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); expect(mockFullStop).toHaveBeenCalledTimes(1); }); + + it("should stop at lines with leading whitespace", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + ` ${lineStream.LINES_TO_STOP_AT[0]}`, + "const z = 15;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + + it("should NOT stop when stop phrase is inside quotes", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + 'console.log("# End of file. not really");', + "let y = 10;", + "const z = 15;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + // Should not stop, should yield all lines + expect(filteredLines).toEqual([ + "const x = 5;", + 'console.log("# End of file. not really");', + "let y = 10;", + "const z = 15;", + ]); + expect(mockFullStop).toHaveBeenCalledTimes(0); + }); + + it("should NOT stop when stop phrase is inside single quotes", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "const message = '# End of file. not really';", + "let y = 10;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "const message = '# End of file. not really';", + "let y = 10;", + ]); + expect(mockFullStop).toHaveBeenCalledTimes(0); + }); + + it("should NOT stop when stop phrase is part of larger text", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "// This function stopsafter processing", + "let y = 10;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "// This function stopsafter processing", + "let y = 10;", + ]); + expect(mockFullStop).toHaveBeenCalledTimes(0); + }); + + it("should stop when stop phrase appears properly at start of content", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + "# End of file. Done here", + "const z = 15;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); }); describe("skipPrefixes", () => { @@ -903,6 +990,53 @@ describe("lineStream", () => { }); }); + describe("shouldChangeLineAndStop", () => { + it("should handle [/CODE] at start of line", () => { + const result = lineStream.shouldChangeLineAndStop("[/CODE]"); + expect(result).toBe("[/CODE]"); + }); + + it("should handle [/CODE] with leading whitespace", () => { + const result = lineStream.shouldChangeLineAndStop(" [/CODE]"); + expect(result).toBe(" [/CODE]"); + }); + + it("should return partial line before [/CODE] when at start/after whitespace", () => { + const result = lineStream.shouldChangeLineAndStop( + "some code [/CODE] more text", + ); + expect(result).toBe("some code"); + }); + + it("should NOT trigger on [/CODE] within quotes or non-whitespace preceded", () => { + // This test demonstrates the current bug - it WILL fail initially + const result = lineStream.shouldChangeLineAndStop( + 'console.log("test [/CODE] end");', + ); + expect(result).toBeUndefined(); // Should not trigger stopping + }); + + it("should NOT trigger on [/CODE] in middle of identifier", () => { + // Another case that shows the bug + const result = lineStream.shouldChangeLineAndStop( + 'const var[/CODE]Name = "test";', + ); + expect(result).toBeUndefined(); // Should not trigger stopping + }); + + it("should handle ``` with trimStart correctly", () => { + const result = lineStream.shouldChangeLineAndStop(" ```"); + expect(result).toBe(" ```"); + }); + + it("should NOT handle ``` in middle of line", () => { + const result = lineStream.shouldChangeLineAndStop( + 'console.log("test ``` end");', + ); + expect(result).toBeUndefined(); + }); + }); + describe("processBlockNesting", () => { it("should skip lines that should be removed before start", () => { const result = lineStream.processBlockNesting("```typescript", false); From 938b7506cf73dfda8f794e9fab0a713e5c7a682a Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Wed, 2 Jul 2025 14:21:16 -0700 Subject: [PATCH 048/178] Optimize for more tests and nova --- .../streamTransforms/filterCodeBlock.ts | 139 ++++++ .../filterCodeBlock.vitest.ts | 452 ++++++++++++++++++ .../filtering/streamTransforms/lineStream.ts | 96 +--- core/edit/lazy/streamLazyApply.ts | 80 +++- core/llm/autodetect.ts | 3 +- .../utils/patchNestedMarkdown.ts | 50 +- 6 files changed, 707 insertions(+), 113 deletions(-) create mode 100644 core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts create mode 100644 core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts diff --git a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts new file mode 100644 index 000000000..28af7d372 --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts @@ -0,0 +1,139 @@ +import { LineStream } from "../../../diff/util"; + +import { + collectAllLines, + hasNestedMarkdownBlocks, + MarkdownBlockState, + processBlockNesting, + shouldChangeLineAndStop, + shouldStopAtMarkdownBlock, +} from "./lineStream"; + +/** + * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. + * Now includes markdown-aware processing to handle nested markdown blocks properly. + * + * @param {LineStream} rawLines - The input stream of lines to filter. + * @param {string} filepath - Optional filepath to determine if this is a markdown file. + * @yields {string} Filtered and processed lines from the code block. + * + * @description + * This generator function performs the following tasks: + * 1. Removes initial lines that should be removed before the actual code starts. + * 2. For markdown files, applies nested markdown block logic to avoid premature termination. + * 3. For mixed content, uses simplified processing to avoid premature termination. + * 4. For traditional code blocks, uses original logic. + * 5. Yields processed lines that are part of the actual code block content. + */ +export async function* filterCodeBlockLines( + rawLines: LineStream, + filepath?: string, +): LineStream { + // Collect all lines for analysis + const allLines = await collectAllLines(rawLines); + + // Check if it has nested markdown blocks (like ```markdown or ```md) + const firstLine = allLines[0] || ""; + const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); + + // TARGETED FIX: Detect if this is mixed content (markdown headers + code blocks) + // But exclude cases where we have nested markdown blocks + const hasMarkdownHeaders = allLines.some( + (line) => line.trim().startsWith("#") && !line.trim().startsWith("```"), + ); + + const hasCodeBlocks = allLines.some( + (line) => line.trim().startsWith("```") && line.trim().length >= 3, + ); + const isMixedContent = + hasMarkdownHeaders && hasCodeBlocks && !hasNestedMarkdown; + + // If this is mixed content, use simplified processing + if (isMixedContent) { + for (let i = 0; i < allLines.length; i++) { + const line = allLines[i]; + + // Skip initial wrapper lines if they exist + if (i === 0 && shouldRemoveLineBeforeStart(line)) { + continue; + } + + yield line; + } + return; + } + + // Original logic for non-mixed content + let seenFirstFence = false; + let nestCount = 0; + + // Create optimized state tracker for markdown block analysis if needed + let markdownStateTracker: MarkdownBlockState | undefined; + if (hasNestedMarkdown) { + markdownStateTracker = new MarkdownBlockState(allLines); + } + + for (let i = 0; i < allLines.length; i++) { + const line = allLines[i]; + + // Process block nesting logic for the first fence + const nesting = processBlockNesting(line, seenFirstFence); + if (nesting.shouldSkip) { + continue; // Filter out starting ``` or START block + } + if (!seenFirstFence && nesting.newSeenFirstFence) { + seenFirstFence = true; + nestCount = 1; + } + + if (nestCount > 0) { + // Inside a block including the outer block + const changedEndLine = shouldChangeLineAndStop(line); + if (typeof changedEndLine === "string") { + // Ending a block with just backticks (```) or STOP + + // For markdown files with nested markdown blocks, apply special logic + if ( + hasNestedMarkdown && + line.trim() === "```" && + markdownStateTracker + ) { + if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) { + return; // Stop without yielding the final closing ``` + } else { + // This is an inner block delimiter, yield it as content + yield line; + continue; + } + } + + // Original logic for non-markdown files or simple cases + nestCount--; + if (nestCount === 0) { + // We've closed the outer wrapper - stop without yielding the closing ``` + return; + } else { + // This is a nested block closing, yield it as content + yield line; + } + } else if (line.startsWith("```")) { + // Going into a nested codeblock + nestCount++; + yield line; + } else { + // Otherwise just yield the line as content + yield line; + } + } + } +} + +function shouldRemoveLineBeforeStart(line: string): boolean { + return ( + line.trimStart().startsWith("```") || + line.trim() === "[CODE]" || + line.trim() === "" || + line.trim() === "" || + line.trim() === "{{FILL_HERE}}" + ); +} diff --git a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts new file mode 100644 index 000000000..78936a28c --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts @@ -0,0 +1,452 @@ +// eslint-disable-next-line max-lines-per-function +import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; + +import * as lineStream from "./lineStream"; + +describe("filterCodeBlock", () => { + let mockFullStop: Mock; + + async function getLineGenerator(lines: any) { + return (async function* () { + for (const line of lines) { + yield line; + } + })(); + } + + async function getFilteredLines(results: any) { + const output = []; + + for await (const line of results) { + output.push(line); + } + + return output; + } + + beforeEach(() => { + mockFullStop = vi.fn(); + }); + + it("should handle unfenced code", async () => { + const linesGenerator = await getLineGenerator(["const x = 5;"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should handle unfenced code with a code block", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "```bash", + "ls -al", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); + }); + + it("should handle unfenced code with a complex code block", async () => { + const linesGenerator = await getLineGenerator([ + "# Manual Testing Sandbox", + "", + "## Project Structure", + "", + "```", + "manual-testing-sandbox/", + "├── readme.md # Project documentation", + "├── package.json # Node.js dependencies and scripts", + "├── tsconfig.json # TypeScript configuration", + "├── jest.config.js # Jest testing configuration", + "├── requirements.txt # Python dependencies", + "├── Dockerfile # Docker container configuration", + "├── data.json # Sample JSON data", + "├── example.ipynb # Jupyter notebook example", + "│", + "├── src/ # Source code directory", + "│ ├── example.ts # TypeScript example", + "│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter", + "│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter", + "│ ├── MarkdownProcessor.ts # Markdown processing utility", + "│ └── MarkdownProcessor.test.ts # Tests for Markdown processor", + "│", + "├── react-calculator/ # React calculator application", + "├── calculator_test/ # Java calculator implementation", + "│ ├── Calculator.java # Calculator class", + "│ └── Main.java # Main application entry", + "│", + "├── nested-folder/ # Nested project example", + "│ ├── helloNested.py # Python script", + "│ ├── package.json # Nested package configuration", + "│ └── rules.md # Documentation", + "│", + "├── coverage/ # Test coverage reports", + "├── logs/ # Application logs", + "│", + "└── Test Files # Various language examples", + " ├── AdvancedPage.tsx # React TypeScript component", + " ├── Calculator.java # Java calculator", + " ├── program.cs # C# program", + " ├── query.sql # SQL query example", + " ├── test.css # CSS styles", + " ├── test.html # HTML page", + " ├── test.js # JavaScript code", + " ├── test.kt # Kotlin example", + " ├── test.php # PHP script", + " ├── test.py # Python script", + " ├── test.rb # Ruby script", + " ├── test.rs # Rust code", + " ├── test.sh # Shell script", + " └── test.ts # TypeScript code", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "# Manual Testing Sandbox", + "", + "## Project Structure", + "", + "```", + "manual-testing-sandbox/", + "├── readme.md # Project documentation", + "├── package.json # Node.js dependencies and scripts", + "├── tsconfig.json # TypeScript configuration", + "├── jest.config.js # Jest testing configuration", + "├── requirements.txt # Python dependencies", + "├── Dockerfile # Docker container configuration", + "├── data.json # Sample JSON data", + "├── example.ipynb # Jupyter notebook example", + "│", + "├── src/ # Source code directory", + "│ ├── example.ts # TypeScript example", + "│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter", + "│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter", + "│ ├── MarkdownProcessor.ts # Markdown processing utility", + "│ └── MarkdownProcessor.test.ts # Tests for Markdown processor", + "│", + "├── react-calculator/ # React calculator application", + "├── calculator_test/ # Java calculator implementation", + "│ ├── Calculator.java # Calculator class", + "│ └── Main.java # Main application entry", + "│", + "├── nested-folder/ # Nested project example", + "│ ├── helloNested.py # Python script", + "│ ├── package.json # Nested package configuration", + "│ └── rules.md # Documentation", + "│", + "├── coverage/ # Test coverage reports", + "├── logs/ # Application logs", + "│", + "└── Test Files # Various language examples", + " ├── AdvancedPage.tsx # React TypeScript component", + " ├── Calculator.java # Java calculator", + " ├── program.cs # C# program", + " ├── query.sql # SQL query example", + " ├── test.css # CSS styles", + " ├── test.html # HTML page", + " ├── test.js # JavaScript code", + " ├── test.kt # Kotlin example", + " ├── test.php # PHP script", + " ├── test.py # Python script", + " ├── test.rb # Ruby script", + " ├── test.rs # Rust code", + " ├── test.sh # Shell script", + " └── test.ts # TypeScript code", + "```", + ]); + }); + + it("should handle unfenced code with two code blocks", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "```bash", + "ls -al", + "```", + "```bash", + "ls -al", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "```bash", + "ls -al", + "```", + "```bash", + "ls -al", + "```", + ]); + }); + + it("should remove lines before the first valid line", async () => { + const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should remove outer blocks", async () => { + const linesGenerator = await getLineGenerator([ + "```ts", + "const x = 5;", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should leave inner blocks intact", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "const x = 5;", + "```bash", + "ls -al", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); + }); + + it("should ignore ticks inside of code blocks such as tests", async () => { + const linesGenerator = await getLineGenerator([ + "```typescript", + 'it("should handle included inner ticks", async () => {', + " const linesGenerator = await getLineGenerator([`", + ' "```md"', + ' "const x = 5;"', + ' "```bash"', + ' "echo ```test```"', + ' "```"', + ' "```"', + "]);", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + 'it("should handle included inner ticks", async () => {', + " const linesGenerator = await getLineGenerator([`", + ' "```md"', + ' "const x = 5;"', + ' "```bash"', + ' "echo ```test```"', + ' "```"', + ' "```"', + "]);", + ]); + }); + + it("should handle included inner ticks", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "const x = 5;", + "```bash", + "echo ```test```", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "```bash", + "echo ```test```", + "```", + ]); + }); + + it("should leave single inner blocks intact but not return trailing text", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "const x = 5;", + "```bash", + "ls -al", + "```", + "```", + "trailing text", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); + }); + + it("should leave double inner blocks intact but not return trailing text", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "const x = 5;", + "```bash", + "ls -al", + "```", + "const y = 10;", + "```sh", + "echo `hello world`", + "```", + "```", + "trailing text", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "```bash", + "ls -al", + "```", + "const y = 10;", + "```sh", + "echo `hello world`", + "```", + ]); + }); + + it("should leave inner blocks intact but not return trailing or leading text", async () => { + const linesGenerator = await getLineGenerator([ + "[CODE]", + "const x = 5;", + "```bash", + "ls -al", + "```", + "[/CODE]", + "trailing text", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); + }); + + // Markdown-aware tests + it("should handle markdown files with nested code blocks and a filename is included", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown README.md", + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md"); + const filteredLines = await getFilteredLines(result); + + // Should include all content up to the final closing ``` + expect(filteredLines).toEqual([ + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + ]); + }); + + // Markdown-aware tests + it("should handle markdown files with nested code blocks and a filename is excluded", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown README.md", + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + // Should include all content up to the final closing ``` + expect(filteredLines).toEqual([ + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + ]); + }); + + it("should handle non-markdown files normally with filepath parameter", async () => { + const linesGenerator = await getLineGenerator([ + "```", + "function test() {", + " return 'hello';", + "}", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js"); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "function test() {", + " return 'hello';", + "}", + ]); + }); + + it("should handle simple markdown code blocks", async () => { + const linesGenerator = await getLineGenerator([ + "```", + "Here's some code:", + "```", + "function example() {", + " console.log('test');", + "}", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md"); + const filteredLines = await getFilteredLines(result); + + // Should remove the outer markdown wrapper, and return just the inner content. + // The lack of an end tag should cause it to return all remaining lines. + expect(filteredLines).toEqual([ + "Here's some code:", + "```", + "function example() {", + " console.log('test');", + "}", + "```", + ]); + }); +}); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index a674c7d1b..182990fef 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -3,6 +3,8 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; +export { filterCodeBlockLines } from "./filterCodeBlock"; + export type LineFilter = (args: { lines: LineStream; fullStop: () => void; @@ -562,100 +564,6 @@ export async function* removeTrailingWhitespace( } } -/** - * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. - * Now includes markdown-aware processing to handle nested markdown blocks properly. - * - * @param {LineStream} rawLines - The input stream of lines to filter. - * @param {string} filepath - Optional filepath to determine if this is a markdown file. - * @yields {string} Filtered and processed lines from the code block. - * - * @description - * This generator function performs the following tasks: - * 1. Removes initial lines that should be removed before the actual code starts. - * 2. For markdown files, applies nested markdown block logic to avoid premature termination. - * 3. For non-markdown files, uses original stopping behavior. - * 4. Handles special cases where lines should be changed and the stream should stop. - * 5. Yields processed lines that are part of the actual code block content. - */ -export async function* filterCodeBlockLines( - rawLines: LineStream, - filepath?: string, -): LineStream { - let seenFirstFence = false; - // nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented - // when an inner code block is discovered to avoid exiting the function prematurely. The function will exit early - // when all blocks are matched. When no outer fence is discovered the function will always continue to the end. - let nestCount = 0; - - // Collect all lines for analysis - const allLines = await collectAllLines(rawLines); - - // Check if it has nested markdown blocks (like ```markdown or ```md) - const firstLine = allLines[0] || ""; - const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); - - // Create optimized state tracker for markdown block analysis if needed - let markdownStateTracker: MarkdownBlockState | undefined; - if (hasNestedMarkdown) { - markdownStateTracker = new MarkdownBlockState(allLines); - } - - for (let i = 0; i < allLines.length; i++) { - const line = allLines[i]; - - // Process block nesting logic for the first fence - const nesting = processBlockNesting(line, seenFirstFence); - if (nesting.shouldSkip) { - continue; // Filter out starting ``` or START block - } - if (!seenFirstFence && nesting.newSeenFirstFence) { - seenFirstFence = true; - nestCount = 1; - } - - if (nestCount > 0) { - // Inside a block including the outer block - const changedEndLine = shouldChangeLineAndStop(line); - if (typeof changedEndLine === "string") { - // Ending a block with just backticks (```) or STOP - - // For markdown files with nested markdown blocks, apply special logic - if ( - hasNestedMarkdown && - line.trim() === "```" && - markdownStateTracker - ) { - if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) { - return; // Stop without yielding the final closing ``` - } else { - // This is an inner block delimiter, yield it as content - yield line; - continue; - } - } - - // Original logic for non-markdown files or simple cases - nestCount--; - if (nestCount === 0) { - // We've closed the outer wrapper - stop without yielding the closing ``` - return; - } else { - // This is a nested block closing, yield it as content - yield line; - } - } else if (line.startsWith("```")) { - // Going into a nested codeblock - nestCount++; - yield line; - } else { - // Otherwise just yield the line as content - yield line; - } - } - } -} - /** * Filters out English explanations at the start of a code block. * diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 1186ca6de..4aa746e79 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -31,6 +31,73 @@ function isMarkdownFile(filename: string): boolean { return ["md", "markdown", "gfm"].includes(ext || ""); } +/** + * Optimized state tracker for markdown block analysis to avoid recomputing on each call. + */ +class MarkdownBlockStateTracker { + private trimmedLines: string[]; + private bareBacktickPositions: number[]; + private markdownNestCount: number = 0; + private lastProcessedIndex: number = -1; + + constructor(allLines: string[]) { + this.trimmedLines = allLines.map((l) => l.trim()); + // Pre-compute positions of all bare backtick lines for faster lookup + this.bareBacktickPositions = []; + for (let i = 0; i < this.trimmedLines.length; i++) { + if (this.trimmedLines[i].match(/^`+$/)) { + this.bareBacktickPositions.push(i); + } + } + } + + /** + * Determines if we should stop at the given markdown block position. + * Maintains state across calls to avoid redundant computation. + */ + shouldStopAtPosition(currentIndex: number): boolean { + if (this.trimmedLines[currentIndex] !== "```") { + return false; + } + + // Process any lines we haven't seen yet up to currentIndex + for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { + const currentLine = this.trimmedLines[j]; + + if (this.markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - check if this is the last one + if (j === currentIndex) { + const remainingBareBackticks = this.bareBacktickPositions.filter( + (pos) => pos > j, + ).length; + if (remainingBareBackticks === 0) { + this.markdownNestCount = 0; + this.lastProcessedIndex = j; + return true; + } + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + this.markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + this.markdownNestCount = 1; + } + } + } + } + + this.lastProcessedIndex = currentIndex; + return false; + } +} + async function* stopAtLinesWithMarkdownSupport( lines: LineStream, filename: string, @@ -64,6 +131,8 @@ async function* stopAtLinesWithMarkdownSupport( return; } + // Use optimized state tracker for markdown block analysis + const stateTracker = new MarkdownBlockStateTracker(allLines); let nestCount = 0; const trimmedLines = allLines.map((l) => l.trim()); @@ -72,15 +141,8 @@ async function* stopAtLinesWithMarkdownSupport( if (nestCount > 0) { if (line.match(/^`+$/)) { - let remainingBareBackticks = 0; - for (let j = i + 1; j < trimmedLines.length; j++) { - if (trimmedLines[j].match(/^`+$/)) { - remainingBareBackticks++; - } - } - - if (remainingBareBackticks === 0) { - nestCount = 0; + // Use optimized state tracker for markdown block logic + if (stateTracker.shouldStopAtPosition(i)) { for (let j = 0; j < i; j++) { yield allLines[j]; } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index a220b5dbd..df575bfed 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -400,5 +400,6 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, - modelSupportsTools, + modelSupportsTools }; + diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 224ed18bf..562c70086 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -9,6 +9,40 @@ */ import { headerIsMarkdown } from "./headerIsMarkdown"; +/** + * Optimized state tracker for markdown patch operations to avoid recomputing on each call. + */ +class MarkdownPatchStateTracker { + private trimmedLines: string[]; + private bareBacktickPositions: number[]; + + constructor(lines: string[]) { + this.trimmedLines = lines.map((l) => l.trim()); + // Pre-compute positions of all bare backtick lines for faster lookup + this.bareBacktickPositions = []; + for (let i = 0; i < this.trimmedLines.length; i++) { + if (this.trimmedLines[i].match(/^`+$/)) { + this.bareBacktickPositions.push(i); + } + } + } + + /** + * Efficiently determines if there are remaining bare backticks after the given position. + */ + getRemainingBareBackticksAfter(currentIndex: number): number { + return this.bareBacktickPositions.filter((pos) => pos > currentIndex) + .length; + } + + /** + * Checks if the line at the given index is a bare backtick line. + */ + isBareBacktickLine(index: number): boolean { + return this.bareBacktickPositions.includes(index); + } +} + export const patchNestedMarkdown = (source: string): string => { // Early return if no markdown codeblock pattern is found (including GitHub variants) if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) @@ -18,20 +52,18 @@ export const patchNestedMarkdown = (source: string): string => { const lines = source.split("\n"); const trimmedLines = lines.map((l) => l.trim()); + // Use optimized state tracker for efficient bare backtick analysis + const stateTracker = new MarkdownPatchStateTracker(lines); + for (let i = 0; i < trimmedLines.length; i++) { const line = trimmedLines[i]; if (nestCount > 0) { // Inside a markdown block - if (line.match(/^`+$/)) { - // Found bare backticks - // Count how many bare backticks are remaining after this one - let remainingBareBackticks = 0; - for (let j = i + 1; j < trimmedLines.length; j++) { - if (trimmedLines[j].match(/^`+$/)) { - remainingBareBackticks++; - } - } + if (stateTracker.isBareBacktickLine(i)) { + // Found bare backticks - use optimized lookup for remaining count + const remainingBareBackticks = + stateTracker.getRemainingBareBackticksAfter(i); // If this is the last bare backticks, it closes the markdown block if (remainingBareBackticks === 0) { From f6d6c4fb81dd81eddd68691fb9fcc4c54539649e Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 4 Jul 2025 13:57:49 -0700 Subject: [PATCH 049/178] deduplicate code --- .../filtering/streamTransforms/lineStream.ts | 156 +++-------------- .../streamTransforms/lineStream.vitest.ts | 79 --------- core/edit/lazy/streamLazyApply.ts | 159 +----------------- core/utils/markdownUtils.ts | 113 +++++++++++++ core/utils/markdownUtils.vitest.ts | 80 +++++++++ core/utils/streamMarkdownUtils.ts | 122 ++++++++++++++ core/utils/streamMarkdownUtils.vitest.ts | 102 +++++++++++ 7 files changed, 441 insertions(+), 370 deletions(-) create mode 100644 core/utils/markdownUtils.ts create mode 100644 core/utils/markdownUtils.vitest.ts create mode 100644 core/utils/streamMarkdownUtils.ts create mode 100644 core/utils/streamMarkdownUtils.vitest.ts diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 182990fef..70ef1d20e 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -3,6 +3,17 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; +import { + headerIsMarkdown, + isMarkdownFile, + MarkdownBlockStateTracker, + collectAllLines, +} from "../../../utils/markdownUtils"; +import { + shouldStopAtMarkdownBlock, + processBlockNesting as processBlockNestingUtil, +} from "../../../utils/streamMarkdownUtils"; + export { filterCodeBlockLines } from "./filterCodeBlock"; export type LineFilter = (args: { @@ -18,23 +29,6 @@ export type CharacterFilter = (args: { multiline: boolean; }) => AsyncGenerator; -// Duplicated from gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts -function headerIsMarkdown(header: string): boolean { - return ( - header === "md" || - header === "markdown" || - header === "gfm" || - header === "github-markdown" || - header.includes(" md") || - header.includes(" markdown") || - header.includes(" gfm") || - header.includes(" github-markdown") || - header.split(" ")[0]?.split(".").pop() === "md" || - header.split(" ")[0]?.split(".").pop() === "markdown" || - header.split(" ")[0]?.split(".").pop() === "gfm" - ); -} - function isBracketEnding(line: string): boolean { return line .trim() @@ -124,19 +118,6 @@ function isUselessLine(line: string): boolean { return hasUselessLine || trimmed.startsWith("// end"); } -/** - * Determines if a file is a markdown file based on its filepath. - */ -export function isMarkdownFile(filepath?: string): boolean { - if (!filepath) { - return false; - } - - return ["md", "markdown", "gfm"].includes( - filepath.split(".").pop()?.toLowerCase() || "", - ); -} - /** * Determines if the code block has nested markdown blocks. */ @@ -147,116 +128,25 @@ export function hasNestedMarkdownBlocks( return ( (firstLine.startsWith("```") && headerIsMarkdown(firstLine.replace(/`/g, ""))) || - Boolean(filepath && headerIsMarkdown(filepath)) + Boolean(filepath && isMarkdownFile(filepath)) ); } -/** - * Collects all lines from a LineStream into an array for analysis. - */ -export async function collectAllLines(rawLines: LineStream): Promise { - const allLines: string[] = []; - for await (const line of rawLines) { - allLines.push(line); - } - return allLines; -} +// Re-export shared utilities +export { collectAllLines, isMarkdownFile }; +export { MarkdownBlockStateTracker as MarkdownBlockState }; +export { shouldStopAtMarkdownBlock }; -/** - * State tracker for markdown block analysis to avoid recomputing on each call. - */ -export class MarkdownBlockState { - private trimmedLines: string[]; - private bareBacktickPositions: number[]; - private markdownNestCount: number = 0; - private lastProcessedIndex: number = -1; - - constructor(allLines: string[]) { - this.trimmedLines = allLines.map((l) => l.trim()); - // Pre-compute positions of all bare backtick lines for faster lookup - this.bareBacktickPositions = []; - for (let i = 0; i < this.trimmedLines.length; i++) { - if (this.trimmedLines[i].match(/^`+$/)) { - this.bareBacktickPositions.push(i); - } - } - } - - /** - * Determines if we should stop at the given markdown block position. - * Maintains state across calls to avoid redundant computation. - */ - shouldStopAtPosition(currentIndex: number): boolean { - if (this.trimmedLines[currentIndex] !== "```") { - return false; - } - - // Process any lines we haven't seen yet up to currentIndex - for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { - const currentLine = this.trimmedLines[j]; - - if (this.markdownNestCount > 0) { - // Inside a markdown block - if (currentLine.match(/^`+$/)) { - // Found bare backticks - check if this is the last one - if (j === currentIndex) { - const remainingBareBackticks = this.bareBacktickPositions.filter( - (pos) => pos > j, - ).length; - if (remainingBareBackticks === 0) { - this.markdownNestCount = 0; - this.lastProcessedIndex = j; - return true; - } - } - } else if (currentLine.startsWith("```")) { - // Going into a nested codeblock - this.markdownNestCount++; - } - } else { - // Not inside a markdown block yet - if (currentLine.startsWith("```")) { - const header = currentLine.replaceAll("`", ""); - if (headerIsMarkdown(header)) { - this.markdownNestCount = 1; - } - } - } - } - - this.lastProcessedIndex = currentIndex; - return false; - } -} - -/** - * Determines if we should stop at a markdown block based on nested markdown logic. - * This handles the complex case where markdown blocks contain other markdown blocks. - * Uses optimized state tracking to avoid redundant computation. - */ -export function shouldStopAtMarkdownBlock( - stateTracker: MarkdownBlockState, - currentIndex: number, -): boolean { - return stateTracker.shouldStopAtPosition(currentIndex); -} - -/** - * Processes block nesting logic and returns updated state. - */ +// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function export function processBlockNesting( line: string, seenFirstFence: boolean, ): { newSeenFirstFence: boolean; shouldSkip: boolean } { - if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) { - return { newSeenFirstFence: false, shouldSkip: true }; - } - - if (!seenFirstFence) { - return { newSeenFirstFence: true, shouldSkip: false }; - } - - return { newSeenFirstFence: seenFirstFence, shouldSkip: false }; + return processBlockNestingUtil( + line, + seenFirstFence, + shouldRemoveLineBeforeStart, + ); } export const USELESS_LINES = [""]; @@ -326,7 +216,7 @@ export async function* avoidPathLine( // Sometimes the model with copy this pattern, which is unwanted for await (const line of stream) { if (line.startsWith(`${comment} Path: `)) { - continue; + continue; // continue in the Continue codebase! How meta! } yield line; } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index ff137f442..1cd569ae4 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -846,32 +846,6 @@ describe("lineStream", () => { }); // Tests for new helper functions - describe("isMarkdownFile", () => { - it("should return true for markdown file extensions", () => { - expect(lineStream.isMarkdownFile("README.md")).toBe(true); - expect(lineStream.isMarkdownFile("docs.markdown")).toBe(true); - expect(lineStream.isMarkdownFile("notes.gfm")).toBe(true); - expect(lineStream.isMarkdownFile("path/to/file.md")).toBe(true); - }); - - it("should return false for non-markdown file extensions", () => { - expect(lineStream.isMarkdownFile("script.js")).toBe(false); - expect(lineStream.isMarkdownFile("styles.css")).toBe(false); - expect(lineStream.isMarkdownFile("document.txt")).toBe(false); - expect(lineStream.isMarkdownFile("config.json")).toBe(false); - }); - - it("should return false for undefined or empty filepath", () => { - expect(lineStream.isMarkdownFile(undefined)).toBe(false); - expect(lineStream.isMarkdownFile("")).toBe(false); - }); - - it("should handle case insensitive extensions", () => { - expect(lineStream.isMarkdownFile("README.MD")).toBe(true); - expect(lineStream.isMarkdownFile("docs.MARKDOWN")).toBe(true); - expect(lineStream.isMarkdownFile("notes.GFM")).toBe(true); - }); - }); describe("hasNestedMarkdownBlocks", () => { it("should detect nested markdown blocks from first line", () => { @@ -1037,59 +1011,6 @@ describe("lineStream", () => { }); }); - describe("processBlockNesting", () => { - it("should skip lines that should be removed before start", () => { - const result = lineStream.processBlockNesting("```typescript", false); - expect(result).toEqual({ - newSeenFirstFence: false, - shouldSkip: true, - }); - }); - - it("should skip [CODE] blocks", () => { - const result = lineStream.processBlockNesting("[CODE]", false); - expect(result).toEqual({ - newSeenFirstFence: false, - shouldSkip: true, - }); - }); - - it("should set first fence when not seen yet", () => { - const result = lineStream.processBlockNesting("const x = 5;", false); - expect(result).toEqual({ - newSeenFirstFence: true, - shouldSkip: false, - }); - }); - - it("should not change state when first fence already seen", () => { - const result = lineStream.processBlockNesting("const x = 5;", true); - expect(result).toEqual({ - newSeenFirstFence: true, - shouldSkip: false, - }); - }); - - it("should handle prefix", () => { - const result = lineStream.processBlockNesting("", false); - expect(result).toEqual({ - newSeenFirstFence: false, - shouldSkip: true, - }); - }); - - it("should handle START EDITING HERE blocks", () => { - const result = lineStream.processBlockNesting( - "", - false, - ); - expect(result).toEqual({ - newSeenFirstFence: false, - shouldSkip: true, - }); - }); - }); - describe("MarkdownBlockState", () => { it("should initialize with correct state", () => { const allLines = ["```markdown", "content", "```", "more content", "```"]; diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 4aa746e79..77d952e7b 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -6,168 +6,11 @@ import { import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; import { DiffLine, ILLM } from "../../index.js"; +import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js"; import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js"; import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js"; -function headerIsMarkdown(header: string): boolean { - return ( - header === "md" || - header === "markdown" || - header === "gfm" || - header === "github-markdown" || - header.includes(" md") || - header.includes(" markdown") || - header.includes(" gfm") || - header.includes(" github-markdown") || - header.split(" ")[0]?.split(".").pop() === "md" || - header.split(" ")[0]?.split(".").pop() === "markdown" || - header.split(" ")[0]?.split(".").pop() === "gfm" - ); -} - -function isMarkdownFile(filename: string): boolean { - const ext = filename.split(".").pop()?.toLowerCase(); - return ["md", "markdown", "gfm"].includes(ext || ""); -} - -/** - * Optimized state tracker for markdown block analysis to avoid recomputing on each call. - */ -class MarkdownBlockStateTracker { - private trimmedLines: string[]; - private bareBacktickPositions: number[]; - private markdownNestCount: number = 0; - private lastProcessedIndex: number = -1; - - constructor(allLines: string[]) { - this.trimmedLines = allLines.map((l) => l.trim()); - // Pre-compute positions of all bare backtick lines for faster lookup - this.bareBacktickPositions = []; - for (let i = 0; i < this.trimmedLines.length; i++) { - if (this.trimmedLines[i].match(/^`+$/)) { - this.bareBacktickPositions.push(i); - } - } - } - - /** - * Determines if we should stop at the given markdown block position. - * Maintains state across calls to avoid redundant computation. - */ - shouldStopAtPosition(currentIndex: number): boolean { - if (this.trimmedLines[currentIndex] !== "```") { - return false; - } - - // Process any lines we haven't seen yet up to currentIndex - for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { - const currentLine = this.trimmedLines[j]; - - if (this.markdownNestCount > 0) { - // Inside a markdown block - if (currentLine.match(/^`+$/)) { - // Found bare backticks - check if this is the last one - if (j === currentIndex) { - const remainingBareBackticks = this.bareBacktickPositions.filter( - (pos) => pos > j, - ).length; - if (remainingBareBackticks === 0) { - this.markdownNestCount = 0; - this.lastProcessedIndex = j; - return true; - } - } - } else if (currentLine.startsWith("```")) { - // Going into a nested codeblock - this.markdownNestCount++; - } - } else { - // Not inside a markdown block yet - if (currentLine.startsWith("```")) { - const header = currentLine.replaceAll("`", ""); - if (headerIsMarkdown(header)) { - this.markdownNestCount = 1; - } - } - } - } - - this.lastProcessedIndex = currentIndex; - return false; - } -} - -async function* stopAtLinesWithMarkdownSupport( - lines: LineStream, - filename: string, -): LineStream { - if (!isMarkdownFile(filename)) { - for await (const line of lines) { - if (line.trim() === "```") { - return; - } - yield line; - } - return; - } - - const allLines: string[] = []; - for await (const line of lines) { - allLines.push(line); - } - - const source = allLines.join("\n"); - if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) { - for (let i = 0; i < allLines.length; i++) { - if (allLines[i].trim() === "```") { - for (let j = 0; j < i; j++) { - yield allLines[j]; - } - return; - } - yield allLines[i]; - } - return; - } - - // Use optimized state tracker for markdown block analysis - const stateTracker = new MarkdownBlockStateTracker(allLines); - let nestCount = 0; - const trimmedLines = allLines.map((l) => l.trim()); - - for (let i = 0; i < trimmedLines.length; i++) { - const line = trimmedLines[i]; - - if (nestCount > 0) { - if (line.match(/^`+$/)) { - // Use optimized state tracker for markdown block logic - if (stateTracker.shouldStopAtPosition(i)) { - for (let j = 0; j < i; j++) { - yield allLines[j]; - } - return; - } - } else if (line.startsWith("```")) { - nestCount++; - } - } else { - if (line.startsWith("```")) { - const header = line.replaceAll("`", ""); - const isMarkdown = headerIsMarkdown(header); - - if (isMarkdown) { - nestCount = 1; - } - } - } - } - - for (const line of allLines) { - yield line; - } -} - export async function* streamLazyApply( oldCode: string, filename: string, diff --git a/core/utils/markdownUtils.ts b/core/utils/markdownUtils.ts new file mode 100644 index 000000000..e292d8bf8 --- /dev/null +++ b/core/utils/markdownUtils.ts @@ -0,0 +1,113 @@ +/** + * Utility functions for working with markdown files and code blocks + */ + +/** + * Determines if a code block header indicates markdown content + */ +export function headerIsMarkdown(header: string): boolean { + return ( + header === "md" || + header === "markdown" || + header === "gfm" || + header === "github-markdown" || + header.includes(" md") || + header.includes(" markdown") || + header.includes(" gfm") || + header.includes(" github-markdown") || + header.split(" ")[0]?.split(".").pop() === "md" || + header.split(" ")[0]?.split(".").pop() === "markdown" || + header.split(" ")[0]?.split(".").pop() === "gfm" + ); +} + +/** + * Determines if a file is a markdown file based on its filepath. + */ +export function isMarkdownFile(filepath?: string): boolean { + if (!filepath) { + return false; + } + + const ext = filepath.split(".").pop()?.toLowerCase() || ""; + return ["md", "markdown", "gfm"].includes(ext); +} + +/** + * State tracker for markdown block analysis to avoid recomputing on each call. + * Optimized to handle nested markdown code blocks. + */ +export class MarkdownBlockStateTracker { + private trimmedLines: string[]; + private bareBacktickPositions: number[]; + private markdownNestCount: number = 0; + private lastProcessedIndex: number = -1; + + constructor(allLines: string[]) { + this.trimmedLines = allLines.map((l) => l.trim()); + // Pre-compute positions of all bare backtick lines for faster lookup + this.bareBacktickPositions = []; + for (let i = 0; i < this.trimmedLines.length; i++) { + if (this.trimmedLines[i].match(/^`+$/)) { + this.bareBacktickPositions.push(i); + } + } + } + + /** + * Determines if we should stop at the given markdown block position. + * Maintains state across calls to avoid redundant computation. + */ + shouldStopAtPosition(currentIndex: number): boolean { + if (this.trimmedLines[currentIndex] !== "```") { + return false; + } + + // Process any lines we haven't seen yet up to currentIndex + for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { + const currentLine = this.trimmedLines[j]; + + if (this.markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - check if this is the last one + if (j === currentIndex) { + const remainingBareBackticks = this.bareBacktickPositions.filter( + (pos) => pos > j, + ).length; + if (remainingBareBackticks === 0) { + this.markdownNestCount = 0; + this.lastProcessedIndex = j; + return true; + } + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + this.markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + this.markdownNestCount = 1; + } + } + } + } + + this.lastProcessedIndex = currentIndex; + return false; + } +} + +/** + * Collects all lines from a LineStream into an array for analysis. + */ +export async function collectAllLines(stream: AsyncGenerator): Promise { + const allLines: T[] = []; + for await (const line of stream) { + allLines.push(line); + } + return allLines; +} \ No newline at end of file diff --git a/core/utils/markdownUtils.vitest.ts b/core/utils/markdownUtils.vitest.ts new file mode 100644 index 000000000..e1380e08e --- /dev/null +++ b/core/utils/markdownUtils.vitest.ts @@ -0,0 +1,80 @@ +import { test, expect } from 'vitest'; +import { headerIsMarkdown, isMarkdownFile, MarkdownBlockStateTracker } from './markdownUtils'; + +test('headerIsMarkdown correctly identifies markdown headers', () => { + // Should return true for markdown headers + expect(headerIsMarkdown('md')).toBe(true); + expect(headerIsMarkdown('markdown')).toBe(true); + expect(headerIsMarkdown('gfm')).toBe(true); + expect(headerIsMarkdown('github-markdown')).toBe(true); + expect(headerIsMarkdown('language md')).toBe(true); + expect(headerIsMarkdown('language markdown')).toBe(true); + expect(headerIsMarkdown('filename.md')).toBe(true); + expect(headerIsMarkdown('path/to/file.md language')).toBe(true); + + // Should return false for non-markdown headers + expect(headerIsMarkdown('javascript')).toBe(false); + expect(headerIsMarkdown('typescript')).toBe(false); + expect(headerIsMarkdown('python')).toBe(false); + expect(headerIsMarkdown('')).toBe(false); +}); + +test('isMarkdownFile correctly identifies markdown files', () => { + // Should return true for markdown files + expect(isMarkdownFile('test.md')).toBe(true); + expect(isMarkdownFile('path/to/file.markdown')).toBe(true); + expect(isMarkdownFile('README.md')).toBe(true); + + // Should return false for non-markdown files + expect(isMarkdownFile('test.js')).toBe(false); + expect(isMarkdownFile('script.ts')).toBe(false); + expect(isMarkdownFile('')).toBe(false); + expect(isMarkdownFile(undefined)).toBe(false); +}); + +test('MarkdownBlockStateTracker correctly tracks nested markdown blocks', () => { + const lines = [ + '# Header', + '', + 'Some text', + '', + '```md', + 'Nested markdown content', + '```javascript', + 'function test() {', + ' return true;', + '}', + '```', + 'More nested markdown', + '```', + '', + 'End of file' + ]; + + const stateTracker = new MarkdownBlockStateTracker(lines); + + // First backtick closure is within nested block (not markdown end) + expect(stateTracker.shouldStopAtPosition(10)).toBe(false); + + // This is the backtick that closes the outer markdown block + expect(stateTracker.shouldStopAtPosition(12)).toBe(true); +}); + +test('MarkdownBlockStateTracker handles simple code blocks correctly', () => { + const lines = [ + 'Some code:', + '', + '```javascript', + 'function test() {', + ' return true;', + '}', + '```', + '', + 'More text' + ]; + + const stateTracker = new MarkdownBlockStateTracker(lines); + + // This is just a simple code block, not nested markdown + expect(stateTracker.shouldStopAtPosition(6)).toBe(false); +}); \ No newline at end of file diff --git a/core/utils/streamMarkdownUtils.ts b/core/utils/streamMarkdownUtils.ts new file mode 100644 index 000000000..b1c8c7658 --- /dev/null +++ b/core/utils/streamMarkdownUtils.ts @@ -0,0 +1,122 @@ +import { LineStream } from "../diff/util"; +import { + isMarkdownFile, + MarkdownBlockStateTracker, + headerIsMarkdown, +} from "./markdownUtils"; + +/** + * Determines if we should stop at a markdown block based on nested markdown logic. + * This handles the complex case where markdown blocks contain other markdown blocks. + * Uses optimized state tracking to avoid redundant computation. + */ +export function shouldStopAtMarkdownBlock( + stateTracker: MarkdownBlockStateTracker, + currentIndex: number, +): boolean { + return stateTracker.shouldStopAtPosition(currentIndex); +} + +/** + * Processes block nesting logic and returns updated state. + */ +export function processBlockNesting( + line: string, + seenFirstFence: boolean, + shouldRemoveLineBeforeStart: (line: string) => boolean, +): { newSeenFirstFence: boolean; shouldSkip: boolean } { + if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) { + return { newSeenFirstFence: false, shouldSkip: true }; + } + + if (!seenFirstFence) { + return { newSeenFirstFence: true, shouldSkip: false }; + } + + return { newSeenFirstFence: seenFirstFence, shouldSkip: false }; +} + +/** + * Stream transformation that stops when encountering a markdown code block ending. + * Handles nested markdown blocks in markdown files. + */ +export async function* stopAtLinesWithMarkdownSupport( + lines: LineStream, + filename: string, +): LineStream { + if (!isMarkdownFile(filename)) { + for await (const line of lines) { + if (line.trim() === "```") { + return; + } + yield line; + } + return; + } + + const allLines: string[] = []; + for await (const line of lines) { + allLines.push(line); + } + + const source = allLines.join("\n"); + if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) { + // No nested markdown blocks detected, check for simple ``` stopping condition + let foundStandaloneBackticks = false; + for (let i = 0; i < allLines.length; i++) { + if (allLines[i].trim() === "```") { + // Found standalone backticks, yield lines up to this point + for (let j = 0; j < i; j++) { + yield allLines[j]; + } + foundStandaloneBackticks = true; + return; + } + } + + // No standalone backticks found, yield all lines + if (!foundStandaloneBackticks) { + for (const line of allLines) { + yield line; + } + } + return; + } + + // Use optimized state tracker for markdown block analysis + const stateTracker = new MarkdownBlockStateTracker(allLines); + let nestCount = 0; + const trimmedLines = allLines.map((l) => l.trim()); + + for (let i = 0; i < trimmedLines.length; i++) { + const line = trimmedLines[i]; + + if (nestCount > 0) { + if (line.match(/^`+$/)) { + // Use optimized state tracker for markdown block logic + if (stateTracker.shouldStopAtPosition(i)) { + for (let j = 0; j < i; j++) { + yield allLines[j]; + } + return; + } + } else if (line.startsWith("```")) { + nestCount++; + } + } else { + if (line.startsWith("```")) { + const header = line.replaceAll("`", ""); + const isMarkdown = headerIsMarkdown(header); + + if (isMarkdown) { + nestCount = 1; + } + } + } + } + + // If we get here, yield all lines + for (const line of allLines) { + yield line; + } +} diff --git a/core/utils/streamMarkdownUtils.vitest.ts b/core/utils/streamMarkdownUtils.vitest.ts new file mode 100644 index 000000000..097b1fbd5 --- /dev/null +++ b/core/utils/streamMarkdownUtils.vitest.ts @@ -0,0 +1,102 @@ +import { expect, test } from "vitest"; +import { LineStream } from "../diff/util"; +import { + processBlockNesting, + stopAtLinesWithMarkdownSupport, +} from "./streamMarkdownUtils"; + +test("processBlockNesting correctly handles starting blocks", () => { + // Mock function to determine which lines should be removed + const shouldRemoveLineBeforeStart = (line: string) => + line === "[CODE]" || line === "```"; + + // Test not seeing first fence yet + const result1 = processBlockNesting( + "[CODE]", + false, + shouldRemoveLineBeforeStart, + ); + expect(result1.newSeenFirstFence).toBe(false); + expect(result1.shouldSkip).toBe(true); + + // Test not seeing first fence but line shouldn't be removed + const result2 = processBlockNesting( + "normal code", + false, + shouldRemoveLineBeforeStart, + ); + expect(result2.newSeenFirstFence).toBe(true); + expect(result2.shouldSkip).toBe(false); + + // Test already seen first fence + const result3 = processBlockNesting( + "more code", + true, + shouldRemoveLineBeforeStart, + ); + expect(result3.newSeenFirstFence).toBe(true); + expect(result3.shouldSkip).toBe(false); +}); + +test("stopAtLinesWithMarkdownSupport handles non-markdown files", async () => { + // Create a mock line stream + const mockLines = ["line 1", "line 2", "```", "line 4"]; + const lineStream: LineStream = (async function* () { + for (const line of mockLines) { + yield line; + } + })(); + + // Test with a non-markdown file + const filename = "test.js"; + const result = stopAtLinesWithMarkdownSupport(lineStream, filename); + + // Should only yield lines up to the backticks + const collected = []; + for await (const line of result) { + collected.push(line); + } + + expect(collected).toEqual(["line 1", "line 2"]); +}); + +test("stopAtLinesWithMarkdownSupport handles markdown files with no nested blocks", async () => { + // Create a mock line stream with markdown content - but NOT nested markdown blocks + const mockLines = [ + "Some markdown text", + "", + "```javascript", + "function test() {", + " return true;", + "}", + "```", + "More text", + ]; + + const lineStream: LineStream = (async function* () { + for (const line of mockLines) { + yield line; + } + })(); + + // Test with a markdown file + const filename = "test.md"; + const result = stopAtLinesWithMarkdownSupport(lineStream, filename); + + // Should yield everything since there's no nested markdown blocks + const collected = []; + for await (const line of result) { + collected.push(line); + } + + // The function should stop at the standalone ``` line (not yield it or lines after) + // This is the correct behavior - it stops when it encounters standalone backticks + expect(collected).toEqual([ + "Some markdown text", + "", + "```javascript", + "function test() {", + " return true;", + "}", + ]); +}); From db25f4a89b6d0f035d21fe08e6c0e6f48bae9114 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 4 Jul 2025 14:03:37 -0700 Subject: [PATCH 050/178] prettier fixes --- core/utils/markdownUtils.ts | 6 +- core/utils/markdownUtils.vitest.ts | 108 +++++++++++++++-------------- 2 files changed, 60 insertions(+), 54 deletions(-) diff --git a/core/utils/markdownUtils.ts b/core/utils/markdownUtils.ts index e292d8bf8..edf827a08 100644 --- a/core/utils/markdownUtils.ts +++ b/core/utils/markdownUtils.ts @@ -104,10 +104,12 @@ export class MarkdownBlockStateTracker { /** * Collects all lines from a LineStream into an array for analysis. */ -export async function collectAllLines(stream: AsyncGenerator): Promise { +export async function collectAllLines( + stream: AsyncGenerator, +): Promise { const allLines: T[] = []; for await (const line of stream) { allLines.push(line); } return allLines; -} \ No newline at end of file +} diff --git a/core/utils/markdownUtils.vitest.ts b/core/utils/markdownUtils.vitest.ts index e1380e08e..211bcd8e1 100644 --- a/core/utils/markdownUtils.vitest.ts +++ b/core/utils/markdownUtils.vitest.ts @@ -1,80 +1,84 @@ -import { test, expect } from 'vitest'; -import { headerIsMarkdown, isMarkdownFile, MarkdownBlockStateTracker } from './markdownUtils'; +import { test, expect } from "vitest"; +import { + headerIsMarkdown, + isMarkdownFile, + MarkdownBlockStateTracker, +} from "./markdownUtils"; -test('headerIsMarkdown correctly identifies markdown headers', () => { +test("headerIsMarkdown correctly identifies markdown headers", () => { // Should return true for markdown headers - expect(headerIsMarkdown('md')).toBe(true); - expect(headerIsMarkdown('markdown')).toBe(true); - expect(headerIsMarkdown('gfm')).toBe(true); - expect(headerIsMarkdown('github-markdown')).toBe(true); - expect(headerIsMarkdown('language md')).toBe(true); - expect(headerIsMarkdown('language markdown')).toBe(true); - expect(headerIsMarkdown('filename.md')).toBe(true); - expect(headerIsMarkdown('path/to/file.md language')).toBe(true); + expect(headerIsMarkdown("md")).toBe(true); + expect(headerIsMarkdown("markdown")).toBe(true); + expect(headerIsMarkdown("gfm")).toBe(true); + expect(headerIsMarkdown("github-markdown")).toBe(true); + expect(headerIsMarkdown("language md")).toBe(true); + expect(headerIsMarkdown("language markdown")).toBe(true); + expect(headerIsMarkdown("filename.md")).toBe(true); + expect(headerIsMarkdown("path/to/file.md language")).toBe(true); // Should return false for non-markdown headers - expect(headerIsMarkdown('javascript')).toBe(false); - expect(headerIsMarkdown('typescript')).toBe(false); - expect(headerIsMarkdown('python')).toBe(false); - expect(headerIsMarkdown('')).toBe(false); + expect(headerIsMarkdown("javascript")).toBe(false); + expect(headerIsMarkdown("typescript")).toBe(false); + expect(headerIsMarkdown("python")).toBe(false); + expect(headerIsMarkdown("")).toBe(false); }); -test('isMarkdownFile correctly identifies markdown files', () => { +test("isMarkdownFile correctly identifies markdown files", () => { // Should return true for markdown files - expect(isMarkdownFile('test.md')).toBe(true); - expect(isMarkdownFile('path/to/file.markdown')).toBe(true); - expect(isMarkdownFile('README.md')).toBe(true); + expect(isMarkdownFile("test.md")).toBe(true); + expect(isMarkdownFile("path/to/file.markdown")).toBe(true); + expect(isMarkdownFile("README.md")).toBe(true); // Should return false for non-markdown files - expect(isMarkdownFile('test.js')).toBe(false); - expect(isMarkdownFile('script.ts')).toBe(false); - expect(isMarkdownFile('')).toBe(false); + expect(isMarkdownFile("test.js")).toBe(false); + expect(isMarkdownFile("script.ts")).toBe(false); + expect(isMarkdownFile("")).toBe(false); expect(isMarkdownFile(undefined)).toBe(false); }); -test('MarkdownBlockStateTracker correctly tracks nested markdown blocks', () => { +test("MarkdownBlockStateTracker correctly tracks nested markdown blocks", () => { const lines = [ - '# Header', - '', - 'Some text', - '', - '```md', - 'Nested markdown content', - '```javascript', - 'function test() {', - ' return true;', - '}', - '```', - 'More nested markdown', - '```', - '', - 'End of file' + "# Header", + "", + "Some text", + "", + "```md", + "Nested markdown content", + "```javascript", + "function test() {", + " return true;", + "}", + "```", + "More nested markdown", + "```", + "", + "End of file", ]; const stateTracker = new MarkdownBlockStateTracker(lines); - + // First backtick closure is within nested block (not markdown end) expect(stateTracker.shouldStopAtPosition(10)).toBe(false); - + // This is the backtick that closes the outer markdown block expect(stateTracker.shouldStopAtPosition(12)).toBe(true); }); -test('MarkdownBlockStateTracker handles simple code blocks correctly', () => { +test("MarkdownBlockStateTracker handles simple code blocks correctly", () => { const lines = [ - 'Some code:', - '', - '```javascript', - 'function test() {', - ' return true;', - '}', - '```', - '', - 'More text' + "Some code:", + "", + "```javascript", + "function test() {", + " return true;", + "}", + "```", + "", + "More text", ]; const stateTracker = new MarkdownBlockStateTracker(lines); - + // This is just a simple code block, not nested markdown expect(stateTracker.shouldStopAtPosition(6)).toBe(false); -}); \ No newline at end of file +}); From 361685dc9da5b0a643b2ac038d76df61220f09f5 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 4 Jul 2025 21:38:22 -0700 Subject: [PATCH 051/178] remove nova change --- core/edit/streamDiffLines.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index c2cd32b0e..7cf1af2f7 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -55,11 +55,7 @@ export async function* addIndentation( } function modelIsInept(model: string): boolean { - return !( - model.includes("gpt") || - model.includes("claude") || - model.includes("nova") - ); + return !(model.includes("gpt") || model.includes("claude")); } export async function* streamDiffLines({ From 1bd49276c09d1e65a86fc91441e9244034e2752e Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 12:15:45 -0700 Subject: [PATCH 052/178] fix re-exports --- .../streamTransforms/filterCodeBlock.ts | 18 +++++--- .../filtering/streamTransforms/lineStream.ts | 12 +---- .../streamTransforms/lineStream.vitest.ts | 46 ++++++++++--------- 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts index 28af7d372..31e37b844 100644 --- a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts +++ b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts @@ -2,11 +2,17 @@ import { LineStream } from "../../../diff/util"; import { collectAllLines, - hasNestedMarkdownBlocks, - MarkdownBlockState, + MarkdownBlockStateTracker, +} from "../../../utils/markdownUtils"; + +import { processBlockNesting, - shouldChangeLineAndStop, shouldStopAtMarkdownBlock, +} from "../../../utils/streamMarkdownUtils"; + +import { + hasNestedMarkdownBlocks, + shouldChangeLineAndStop, } from "./lineStream"; /** @@ -68,16 +74,16 @@ export async function* filterCodeBlockLines( let nestCount = 0; // Create optimized state tracker for markdown block analysis if needed - let markdownStateTracker: MarkdownBlockState | undefined; + let markdownStateTracker: MarkdownBlockStateTracker | undefined; if (hasNestedMarkdown) { - markdownStateTracker = new MarkdownBlockState(allLines); + markdownStateTracker = new MarkdownBlockStateTracker(allLines); } for (let i = 0; i < allLines.length; i++) { const line = allLines[i]; // Process block nesting logic for the first fence - const nesting = processBlockNesting(line, seenFirstFence); + const nesting = processBlockNesting(line, seenFirstFence, shouldRemoveLineBeforeStart); if (nesting.shouldSkip) { continue; // Filter out starting ``` or START block } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 70ef1d20e..b355a2aa1 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -5,13 +5,10 @@ import { LineStream } from "../../../diff/util"; import { headerIsMarkdown, - isMarkdownFile, - MarkdownBlockStateTracker, - collectAllLines, + isMarkdownFile } from "../../../utils/markdownUtils"; import { - shouldStopAtMarkdownBlock, - processBlockNesting as processBlockNestingUtil, + processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils"; export { filterCodeBlockLines } from "./filterCodeBlock"; @@ -132,11 +129,6 @@ export function hasNestedMarkdownBlocks( ); } -// Re-export shared utilities -export { collectAllLines, isMarkdownFile }; -export { MarkdownBlockStateTracker as MarkdownBlockState }; -export { shouldStopAtMarkdownBlock }; - // Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function export function processBlockNesting( line: string, diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index 1cd569ae4..994b47b1a 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -1,5 +1,7 @@ import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; +import { collectAllLines, MarkdownBlockStateTracker } from "../../../utils/markdownUtils"; +import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils"; import * as lineStream from "./lineStream"; // eslint-disable-next-line max-lines-per-function @@ -897,7 +899,7 @@ describe("lineStream", () => { "line3", ]); - const result = await lineStream.collectAllLines(linesGenerator); + const result = await collectAllLines(linesGenerator); expect(result).toEqual(["line1", "line2", "line3"]); }); @@ -905,7 +907,7 @@ describe("lineStream", () => { it("should handle empty stream", async () => { const linesGenerator = await getLineGenerator([]); - const result = await lineStream.collectAllLines(linesGenerator); + const result = await collectAllLines(linesGenerator); expect(result).toEqual([]); }); @@ -913,7 +915,7 @@ describe("lineStream", () => { it("should handle stream with empty lines", async () => { const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]); - const result = await lineStream.collectAllLines(linesGenerator); + const result = await collectAllLines(linesGenerator); expect(result).toEqual(["", "line2", "", "line4"]); }); @@ -922,14 +924,14 @@ describe("lineStream", () => { describe("shouldStopAtMarkdownBlock", () => { it("should return false when current line is not closing backticks", () => { const allLines = ["```markdown", "content", "more content"]; - const state = new lineStream.MarkdownBlockState(allLines); - expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(false); + const state = new MarkdownBlockStateTracker(allLines); + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false); }); it("should handle simple nested markdown case", () => { const allLines = ["```markdown", "# Title", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); - expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(true); + const state = new MarkdownBlockStateTracker(allLines); + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(true); }); it("should handle complex nested markdown with inner code blocks", () => { @@ -941,11 +943,11 @@ describe("lineStream", () => { "```", "```", ]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // At index 4 (first inner closing), should not stop - expect(lineStream.shouldStopAtMarkdownBlock(state, 4)).toBe(false); + expect(shouldStopAtMarkdownBlock(state, 4)).toBe(false); // At index 5 (outer closing), should stop - expect(lineStream.shouldStopAtMarkdownBlock(state, 5)).toBe(true); + expect(shouldStopAtMarkdownBlock(state, 5)).toBe(true); }); it("should handle multiple bare backticks scenario", () => { @@ -956,11 +958,11 @@ describe("lineStream", () => { "More content", "```", ]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // At index 2, should not stop (not the last bare backticks) - expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(false); + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false); // At index 4, should stop (last bare backticks) - expect(lineStream.shouldStopAtMarkdownBlock(state, 4)).toBe(true); + expect(shouldStopAtMarkdownBlock(state, 4)).toBe(true); }); }); @@ -1014,7 +1016,7 @@ describe("lineStream", () => { describe("MarkdownBlockState", () => { it("should initialize with correct state", () => { const allLines = ["```markdown", "content", "```", "more content", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Test basic initialization - we can't directly test private properties, // but we can test the behavior through shouldStopAtPosition @@ -1023,7 +1025,7 @@ describe("lineStream", () => { it("should correctly identify bare backticks positions", () => { const allLines = ["```markdown", "```", "content", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // At position 1 (first bare backticks), should not stop expect(state.shouldStopAtPosition(1)).toBe(false); @@ -1041,7 +1043,7 @@ describe("lineStream", () => { "More content", "```", ]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Process positions incrementally expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block @@ -1066,7 +1068,7 @@ describe("lineStream", () => { "Final notes", "```", ]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Test multiple positions in sequence expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block @@ -1076,7 +1078,7 @@ describe("lineStream", () => { it("should handle non-backtick lines correctly", () => { const allLines = ["```markdown", "regular content", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Position 1 is not backticks, should return false expect(state.shouldStopAtPosition(1)).toBe(false); @@ -1084,7 +1086,7 @@ describe("lineStream", () => { it("should handle empty lines and edge cases", () => { const allLines = ["```markdown", "", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks @@ -1092,7 +1094,7 @@ describe("lineStream", () => { it("should reset nest count when reaching final bare backticks", () => { const allLines = ["```markdown", "content", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // First call should stop and reset count expect(state.shouldStopAtPosition(2)).toBe(true); @@ -1112,7 +1114,7 @@ describe("lineStream", () => { return `line ${i}`; }); - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Test that we can call multiple times without recomputing everything const start = performance.now(); @@ -1120,7 +1122,7 @@ describe("lineStream", () => { // Test several positions in sequence for (let i = 10; i < 90; i += 10) { if (allLines[i].trim() === "```") { - lineStream.shouldStopAtMarkdownBlock(state, i); + shouldStopAtMarkdownBlock(state, i); } } From 7cd725264ab35ed9b79816e844ffdec7a8700c43 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 12:47:28 -0700 Subject: [PATCH 053/178] fix duplicate logic --- core/utils/streamMarkdownUtils.ts | 33 ++++++------------------------- 1 file changed, 6 insertions(+), 27 deletions(-) diff --git a/core/utils/streamMarkdownUtils.ts b/core/utils/streamMarkdownUtils.ts index b1c8c7658..94505dfdf 100644 --- a/core/utils/streamMarkdownUtils.ts +++ b/core/utils/streamMarkdownUtils.ts @@ -1,8 +1,7 @@ import { LineStream } from "../diff/util"; import { isMarkdownFile, - MarkdownBlockStateTracker, - headerIsMarkdown, + MarkdownBlockStateTracker } from "./markdownUtils"; /** @@ -85,33 +84,13 @@ export async function* stopAtLinesWithMarkdownSupport( // Use optimized state tracker for markdown block analysis const stateTracker = new MarkdownBlockStateTracker(allLines); - let nestCount = 0; - const trimmedLines = allLines.map((l) => l.trim()); - for (let i = 0; i < trimmedLines.length; i++) { - const line = trimmedLines[i]; - - if (nestCount > 0) { - if (line.match(/^`+$/)) { - // Use optimized state tracker for markdown block logic - if (stateTracker.shouldStopAtPosition(i)) { - for (let j = 0; j < i; j++) { - yield allLines[j]; - } - return; - } - } else if (line.startsWith("```")) { - nestCount++; - } - } else { - if (line.startsWith("```")) { - const header = line.replaceAll("`", ""); - const isMarkdown = headerIsMarkdown(header); - - if (isMarkdown) { - nestCount = 1; - } + for (let i = 0; i < allLines.length; i++) { + if (stateTracker.shouldStopAtPosition(i)) { + for (let j = 0; j < i; j++) { + yield allLines[j]; } + return; } } From f604c17c27951119f33e1a5bc0f8c23850416c3d Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 13:07:08 -0700 Subject: [PATCH 054/178] fix rundundant trimming --- .../StyledMarkdownPreview/utils/patchNestedMarkdown.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 562c70086..b054f0bd9 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -41,6 +41,13 @@ class MarkdownPatchStateTracker { isBareBacktickLine(index: number): boolean { return this.bareBacktickPositions.includes(index); } + + /** + * Gets the trimmed lines array. + */ + getTrimmedLines(): string[] { + return this.trimmedLines; + } } export const patchNestedMarkdown = (source: string): string => { @@ -50,10 +57,10 @@ export const patchNestedMarkdown = (source: string): string => { let nestCount = 0; const lines = source.split("\n"); - const trimmedLines = lines.map((l) => l.trim()); // Use optimized state tracker for efficient bare backtick analysis const stateTracker = new MarkdownPatchStateTracker(lines); + const trimmedLines = stateTracker.getTrimmedLines(); for (let i = 0; i < trimmedLines.length; i++) { const line = trimmedLines[i]; From ad2bbc28c9256bf16c2918e6a81225d4860fbcb6 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 13:20:31 -0700 Subject: [PATCH 055/178] add back comments --- core/edit/lazy/streamLazyApply.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 77d952e7b..f806e956f 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -26,6 +26,7 @@ export async function* streamLazyApply( const promptMessages = promptFactory(oldCode, filename, newCode); const lazyCompletion = llm.streamChat(promptMessages, abortController.signal); + // Do find and replace over the lazy edit response async function* replacementFunction( oldCode: string, linesBefore: string[], @@ -52,12 +53,14 @@ export async function* streamLazyApply( lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines); + // Fill in unchanged code let lines = streamFillUnchangedCode( lazyCompletionLines, oldCode, replacementFunction, ); + // Convert output to diff const oldLines = oldCode.split(/\r?\n/); let diffLines = streamDiff(oldLines, lines); diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines); @@ -78,11 +81,13 @@ async function* streamFillUnchangedCode( const newLines = []; let buffer = []; let waitingForBuffer = false; + for await (const line of lines) { if (waitingForBuffer) { buffer.push(line); if (buffer.length >= BUFFER_LINES_BELOW) { + // Find the replacement and continue streaming once we have it const replacementLines = replacementFunction(oldCode, newLines, buffer); let replacement = ""; for await (const replacementLine of replacementLines) { @@ -90,6 +95,7 @@ async function* streamFillUnchangedCode( newLines.push(replacementLine); replacement += replacementLine + "\n"; } + // Yield the buffered lines for (const bufferedLine of buffer) { yield bufferedLine; newLines.push(bufferedLine); @@ -104,7 +110,9 @@ async function* streamFillUnchangedCode( } if (line.includes(UNCHANGED_CODE)) { + // Buffer so we can give the context of BUFFER_LINES_BELOW lines below waitingForBuffer = true; + // TODO: If the UNCHANGED CODE is at the very top of the file we need to handle a bit differently } else { yield line; newLines.push(line); @@ -112,11 +120,14 @@ async function* streamFillUnchangedCode( } if (waitingForBuffer) { + // If we're still waiting for a buffer, we've reached the end of the stream + // and we should just look for the replacement with what we have const replacementLines = replacementFunction(oldCode, newLines, buffer); for await (const replacementLine of replacementLines) { yield replacementLine; newLines.push(replacementLine); } + // Yield the buffered lines for (const bufferedLine of buffer) { yield bufferedLine; newLines.push(bufferedLine); From 948246dc443815e6a722334179dcde6ab6f87102 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 14:47:54 -0700 Subject: [PATCH 056/178] prettier and code cleanup --- .../streamTransforms/filterCodeBlock.ts | 11 +- .../filtering/streamTransforms/lineStream.ts | 102 ++--- .../streamTransforms/lineStream.vitest.ts | 95 ++++- core/llm/autodetect.ts | 3 +- core/utils/markdownUtils.ts | 31 +- core/utils/markdownUtils.vitest.ts | 350 ++++++++++++++---- core/utils/streamMarkdownUtils.ts | 5 +- .../utils/headerIsMarkdown.test.ts | 67 ---- .../utils/headerIsMarkdown.ts | 26 -- .../utils/patchNestedMarkdown.ts | 48 +-- 10 files changed, 473 insertions(+), 265 deletions(-) delete mode 100644 gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts delete mode 100644 gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts diff --git a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts index 31e37b844..d9cb8e8ac 100644 --- a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts +++ b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts @@ -10,10 +10,7 @@ import { shouldStopAtMarkdownBlock, } from "../../../utils/streamMarkdownUtils"; -import { - hasNestedMarkdownBlocks, - shouldChangeLineAndStop, -} from "./lineStream"; +import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream"; /** * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. @@ -83,7 +80,11 @@ export async function* filterCodeBlockLines( const line = allLines[i]; // Process block nesting logic for the first fence - const nesting = processBlockNesting(line, seenFirstFence, shouldRemoveLineBeforeStart); + const nesting = processBlockNesting( + line, + seenFirstFence, + shouldRemoveLineBeforeStart, + ); if (nesting.shouldSkip) { continue; // Filter out starting ``` or START block } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index b355a2aa1..3cf1cec9f 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -3,13 +3,8 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; -import { - headerIsMarkdown, - isMarkdownFile -} from "../../../utils/markdownUtils"; -import { - processBlockNesting as processBlockNestingUtil -} from "../../../utils/streamMarkdownUtils"; +import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils"; +import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils"; export { filterCodeBlockLines } from "./filterCodeBlock"; @@ -60,6 +55,47 @@ function shouldRemoveLineBeforeStart(line: string): boolean { ); } +/** + * Shared utility for validating patterns in lines to avoid code duplication. + * Checks if a pattern appears in a valid context (not inside quotes or identifiers). + */ +export function validatePatternInLine( + line: string, + pattern: string, +): { + isValid: boolean; + patternIndex: number; + beforePattern: string; +} { + const patternIndex = line.indexOf(pattern); + + if (patternIndex === -1) { + return { isValid: false, patternIndex: -1, beforePattern: "" }; + } + + // Check if pattern is preceded by a non-whitespace character + // If so, it might be part of an identifier, so don't handle it + if (patternIndex > 0) { + const charBefore = line[patternIndex - 1]; + if (charBefore && !charBefore.match(/\s/)) { + return { isValid: false, patternIndex, beforePattern: "" }; + } + } + + // Check if pattern appears to be inside quotes + // Simple heuristic: count unmatched quotes before the pattern + const beforePattern = line.substring(0, patternIndex); + const singleQuotes = (beforePattern.match(/'/g) || []).length; + const doubleQuotes = (beforePattern.match(/"/g) || []).length; + + // If there's an odd number of quotes before pattern, we're likely inside quotes + if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { + return { isValid: false, patternIndex, beforePattern }; + } + + return { isValid: true, patternIndex, beforePattern }; +} + export function shouldChangeLineAndStop(line: string): string | undefined { if (line.trimStart() === "```") { return line; @@ -67,26 +103,10 @@ export function shouldChangeLineAndStop(line: string): string | undefined { // Check if [/CODE] appears in the line if (line.includes(CODE_STOP_BLOCK)) { - const stopBlockIndex = line.indexOf(CODE_STOP_BLOCK); + const validation = validatePatternInLine(line, CODE_STOP_BLOCK); - // Check if [/CODE] is preceded by a non-whitespace character - // If so, it might be part of an identifier, so don't handle it - if (stopBlockIndex > 0) { - const charBefore = line[stopBlockIndex - 1]; - if (charBefore && !charBefore.match(/\s/)) { - return undefined; // Don't handle [/CODE] that's part of an identifier - } - } - - // Check if [/CODE] appears to be inside quotes - // Simple heuristic: count unmatched quotes before the stop block - const beforeStopBlock = line.substring(0, stopBlockIndex); - const singleQuotes = (beforeStopBlock.match(/'/g) || []).length; - const doubleQuotes = (beforeStopBlock.match(/"/g) || []).length; - - // If there's an odd number of quotes before [/CODE], we're likely inside quotes - if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { - return undefined; // Don't handle [/CODE] inside quotes + if (!validation.isValid) { + return undefined; } // Get the trimmed line to check if [/CODE] is at logical start @@ -100,7 +120,7 @@ export function shouldChangeLineAndStop(line: string): string | undefined { } // [/CODE] appears after some content (separated by whitespace) - return part before - return beforeStopBlock.trimEnd(); + return validation.beforePattern.trimEnd(); } return undefined; @@ -336,26 +356,10 @@ export async function* stopAtLines( // Check each stop phrase for (const stopAt of linesToStopAt) { if (line.includes(stopAt)) { - const stopAtIndex = line.indexOf(stopAt); + const validation = validatePatternInLine(line, stopAt); - // Check if stop phrase is preceded by a non-whitespace character - // If so, it might be part of an identifier, so don't handle it - if (stopAtIndex > 0) { - const charBefore = line[stopAtIndex - 1]; - if (charBefore && !charBefore.match(/\s/)) { - continue; // Don't handle stop phrase that's part of an identifier - } - } - - // Check if stop phrase appears to be inside quotes - // Simple heuristic: count unmatched quotes before the stop phrase - const beforeStopPhrase = line.substring(0, stopAtIndex); - const singleQuotes = (beforeStopPhrase.match(/'/g) || []).length; - const doubleQuotes = (beforeStopPhrase.match(/"/g) || []).length; - - // If there's an odd number of quotes before stop phrase, we're likely inside quotes - if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { - continue; // Don't handle stop phrase inside quotes + if (!validation.isValid) { + continue; } // Get the trimmed line to check if stop phrase is at logical start @@ -367,8 +371,10 @@ export async function* stopAtLines( break; } else { // Stop phrase appears after some content - check if it's separated by whitespace - const contentBeforeStopPhrase = beforeStopPhrase.trimEnd(); - if (contentBeforeStopPhrase.length < beforeStopPhrase.length) { + const contentBeforeStopPhrase = validation.beforePattern.trimEnd(); + if ( + contentBeforeStopPhrase.length < validation.beforePattern.length + ) { // There's whitespace before the stop phrase, so it's properly separated shouldStop = true; break; diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index 994b47b1a..741c2b125 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -1,6 +1,9 @@ import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; -import { collectAllLines, MarkdownBlockStateTracker } from "../../../utils/markdownUtils"; +import { + collectAllLines, + MarkdownBlockStateTracker, +} from "../../../utils/markdownUtils"; import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils"; import * as lineStream from "./lineStream"; @@ -1205,4 +1208,94 @@ describe("lineStream", () => { ]); }); }); + + describe("validatePatternInLine", () => { + it("should return false when pattern is not found", () => { + const result = lineStream.validatePatternInLine( + "const x = 5;", + "[/CODE]", + ); + expect(result.isValid).toBe(false); + expect(result.patternIndex).toBe(-1); + expect(result.beforePattern).toBe(""); + }); + + it("should return false when pattern is preceded by non-whitespace", () => { + const result = lineStream.validatePatternInLine( + 'const var[/CODE]Name = "test";', + "[/CODE]", + ); + expect(result.isValid).toBe(false); + expect(result.patternIndex).toBe(9); + }); + + it("should return false when pattern is inside double quotes", () => { + const result = lineStream.validatePatternInLine( + 'console.log("test [/CODE] end");', + "[/CODE]", + ); + expect(result.isValid).toBe(false); + expect(result.patternIndex).toBe(18); + }); + + it("should return false when pattern is inside single quotes", () => { + const result = lineStream.validatePatternInLine( + "const message = 'test [/CODE] end';", + "[/CODE]", + ); + expect(result.isValid).toBe(false); + expect(result.patternIndex).toBe(22); + }); + + it("should return true when pattern is properly separated by whitespace", () => { + const result = lineStream.validatePatternInLine( + "some code [/CODE] more text", + "[/CODE]", + ); + expect(result.isValid).toBe(true); + expect(result.patternIndex).toBe(10); + expect(result.beforePattern).toBe("some code "); + }); + + it("should return true when pattern is at start of line", () => { + const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]"); + expect(result.isValid).toBe(true); + expect(result.patternIndex).toBe(0); + expect(result.beforePattern).toBe(""); + }); + + it("should return true when pattern has only whitespace before it", () => { + const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]"); + expect(result.isValid).toBe(true); + expect(result.patternIndex).toBe(4); + expect(result.beforePattern).toBe(" "); + }); + + it("should handle complex quote scenarios correctly", () => { + // Unmatched quote should make it invalid + const result1 = lineStream.validatePatternInLine( + 'const x = "unclosed quote [/CODE]', + "[/CODE]", + ); + expect(result1.isValid).toBe(false); + + // Matched quotes should make it valid + const result2 = lineStream.validatePatternInLine( + 'const x = "closed"; [/CODE]', + "[/CODE]", + ); + expect(result2.isValid).toBe(true); + }); + + it("should work with different patterns", () => { + const result1 = lineStream.validatePatternInLine( + "# End of file. Done", + "# End of file.", + ); + expect(result1.isValid).toBe(true); + + const result2 = lineStream.validatePatternInLine(" ```", "```"); + expect(result2.isValid).toBe(true); + }); + }); }); diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index df575bfed..a220b5dbd 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -400,6 +400,5 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, - modelSupportsTools + modelSupportsTools, }; - diff --git a/core/utils/markdownUtils.ts b/core/utils/markdownUtils.ts index edf827a08..365f72811 100644 --- a/core/utils/markdownUtils.ts +++ b/core/utils/markdownUtils.ts @@ -38,8 +38,8 @@ export function isMarkdownFile(filepath?: string): boolean { * Optimized to handle nested markdown code blocks. */ export class MarkdownBlockStateTracker { - private trimmedLines: string[]; - private bareBacktickPositions: number[]; + protected trimmedLines: string[]; + protected bareBacktickPositions: number[]; private markdownNestCount: number = 0; private lastProcessedIndex: number = -1; @@ -72,9 +72,8 @@ export class MarkdownBlockStateTracker { if (currentLine.match(/^`+$/)) { // Found bare backticks - check if this is the last one if (j === currentIndex) { - const remainingBareBackticks = this.bareBacktickPositions.filter( - (pos) => pos > j, - ).length; + const remainingBareBackticks = + this.getRemainingBareBackticksAfter(j); if (remainingBareBackticks === 0) { this.markdownNestCount = 0; this.lastProcessedIndex = j; @@ -99,6 +98,28 @@ export class MarkdownBlockStateTracker { this.lastProcessedIndex = currentIndex; return false; } + + /** + * Efficiently determines if there are remaining bare backticks after the given position. + */ + getRemainingBareBackticksAfter(currentIndex: number): number { + return this.bareBacktickPositions.filter((pos) => pos > currentIndex) + .length; + } + + /** + * Checks if the line at the given index is a bare backtick line. + */ + isBareBacktickLine(index: number): boolean { + return this.bareBacktickPositions.includes(index); + } + + /** + * Gets the trimmed lines array. + */ + getTrimmedLines(): string[] { + return this.trimmedLines; + } } /** diff --git a/core/utils/markdownUtils.vitest.ts b/core/utils/markdownUtils.vitest.ts index 211bcd8e1..c21c27587 100644 --- a/core/utils/markdownUtils.vitest.ts +++ b/core/utils/markdownUtils.vitest.ts @@ -1,84 +1,306 @@ -import { test, expect } from "vitest"; +import { describe, expect, it } from "vitest"; import { + collectAllLines, headerIsMarkdown, isMarkdownFile, MarkdownBlockStateTracker, } from "./markdownUtils"; -test("headerIsMarkdown correctly identifies markdown headers", () => { - // Should return true for markdown headers - expect(headerIsMarkdown("md")).toBe(true); - expect(headerIsMarkdown("markdown")).toBe(true); - expect(headerIsMarkdown("gfm")).toBe(true); - expect(headerIsMarkdown("github-markdown")).toBe(true); - expect(headerIsMarkdown("language md")).toBe(true); - expect(headerIsMarkdown("language markdown")).toBe(true); - expect(headerIsMarkdown("filename.md")).toBe(true); - expect(headerIsMarkdown("path/to/file.md language")).toBe(true); +describe("headerIsMarkdown", () => { + // Test exact match with common Markdown identifiers + it("should identify exact matches with common Markdown identifiers", () => { + expect(headerIsMarkdown("md")).toBe(true); + expect(headerIsMarkdown("markdown")).toBe(true); + expect(headerIsMarkdown("gfm")).toBe(true); + expect(headerIsMarkdown("github-markdown")).toBe(true); + }); - // Should return false for non-markdown headers - expect(headerIsMarkdown("javascript")).toBe(false); - expect(headerIsMarkdown("typescript")).toBe(false); - expect(headerIsMarkdown("python")).toBe(false); - expect(headerIsMarkdown("")).toBe(false); + // Test identifiers preceded by a space + it("should identify identifiers preceded by a space", () => { + expect(headerIsMarkdown("lang md")).toBe(true); + expect(headerIsMarkdown("something markdown")).toBe(true); + expect(headerIsMarkdown("language gfm")).toBe(true); + expect(headerIsMarkdown("spec github-markdown")).toBe(true); + }); + + // Test file extensions + it("should identify file names with markdown extensions", () => { + expect(headerIsMarkdown("example.md")).toBe(true); + expect(headerIsMarkdown("document.markdown")).toBe(true); + expect(headerIsMarkdown("readme.gfm")).toBe(true); + }); + + // Test more complex cases with extensions + it("should identify file names with markdown extensions followed by other text", () => { + expect(headerIsMarkdown("example.md additional text")).toBe(true); + expect(headerIsMarkdown("document.markdown with some description")).toBe( + true, + ); + expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true); + }); + + // Test non-markdown cases + it("should not identify non-markdown headers", () => { + expect(headerIsMarkdown("javascript")).toBe(false); + expect(headerIsMarkdown("typescript")).toBe(false); + expect(headerIsMarkdown("plain")).toBe(false); + expect(headerIsMarkdown("python")).toBe(false); + }); + + // Test edge cases + it("should handle edge cases correctly", () => { + expect(headerIsMarkdown("")).toBe(false); + expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md" + expect(headerIsMarkdown("readme md")).toBe(true); + expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension + }); + + // Test case sensitivity + it("should respect case sensitivity", () => { + expect(headerIsMarkdown("MD")).toBe(false); + expect(headerIsMarkdown("MARKDOWN")).toBe(false); + expect(headerIsMarkdown("example.MD")).toBe(false); + expect(headerIsMarkdown("lang MD")).toBe(false); + }); + + // Test with special characters and spacing + it("should handle special characters and spacing correctly", () => { + expect(headerIsMarkdown(" md")).toBe(true); // Space before "md" + expect(headerIsMarkdown("md ")).toBe(true); // Space after "md" + expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix + expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix + }); }); -test("isMarkdownFile correctly identifies markdown files", () => { - // Should return true for markdown files - expect(isMarkdownFile("test.md")).toBe(true); - expect(isMarkdownFile("path/to/file.markdown")).toBe(true); - expect(isMarkdownFile("README.md")).toBe(true); +describe("isMarkdownFile", () => { + it("should identify markdown files by .md extension", () => { + expect(isMarkdownFile("README.md")).toBe(true); + expect(isMarkdownFile("docs/guide.md")).toBe(true); + expect(isMarkdownFile("/path/to/file.md")).toBe(true); + }); - // Should return false for non-markdown files - expect(isMarkdownFile("test.js")).toBe(false); - expect(isMarkdownFile("script.ts")).toBe(false); - expect(isMarkdownFile("")).toBe(false); - expect(isMarkdownFile(undefined)).toBe(false); + it("should identify markdown files by .markdown extension", () => { + expect(isMarkdownFile("README.markdown")).toBe(true); + expect(isMarkdownFile("docs/guide.markdown")).toBe(true); + expect(isMarkdownFile("/path/to/file.markdown")).toBe(true); + }); + + it("should identify markdown files by .gfm extension", () => { + expect(isMarkdownFile("README.gfm")).toBe(true); + expect(isMarkdownFile("docs/guide.gfm")).toBe(true); + expect(isMarkdownFile("/path/to/file.gfm")).toBe(true); + }); + + it("should handle case insensitive extensions", () => { + expect(isMarkdownFile("README.MD")).toBe(true); + expect(isMarkdownFile("guide.MARKDOWN")).toBe(true); + expect(isMarkdownFile("file.GFM")).toBe(true); + }); + + it("should return false for non-markdown files", () => { + expect(isMarkdownFile("script.js")).toBe(false); + expect(isMarkdownFile("style.css")).toBe(false); + expect(isMarkdownFile("data.json")).toBe(false); + expect(isMarkdownFile("document.txt")).toBe(false); + }); + + it("should return false for undefined or empty filepath", () => { + expect(isMarkdownFile(undefined)).toBe(false); + expect(isMarkdownFile("")).toBe(false); + }); + + it("should return false for files without extensions", () => { + expect(isMarkdownFile("README")).toBe(false); + expect(isMarkdownFile("Dockerfile")).toBe(false); + }); + + it("should handle files with multiple dots", () => { + expect(isMarkdownFile("file.backup.md")).toBe(true); + expect(isMarkdownFile("config.test.js")).toBe(false); + }); }); -test("MarkdownBlockStateTracker correctly tracks nested markdown blocks", () => { - const lines = [ - "# Header", - "", - "Some text", - "", - "```md", - "Nested markdown content", - "```javascript", - "function test() {", - " return true;", - "}", - "```", - "More nested markdown", - "```", - "", - "End of file", - ]; +describe("MarkdownBlockStateTracker", () => { + it("should initialize correctly with empty lines", () => { + const tracker = new MarkdownBlockStateTracker([]); + expect(tracker.shouldStopAtPosition(0)).toBe(false); + }); - const stateTracker = new MarkdownBlockStateTracker(lines); + it("should initialize correctly with non-markdown lines", () => { + const tracker = new MarkdownBlockStateTracker([ + "const x = 5;", + "console.log(x);", + ]); + expect(tracker.shouldStopAtPosition(0)).toBe(false); + expect(tracker.shouldStopAtPosition(1)).toBe(false); + }); - // First backtick closure is within nested block (not markdown end) - expect(stateTracker.shouldStopAtPosition(10)).toBe(false); + it("should detect simple markdown blocks", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "# Title", + "```", + ]); + expect(tracker.shouldStopAtPosition(0)).toBe(false); // Opening + expect(tracker.shouldStopAtPosition(1)).toBe(false); // Content + expect(tracker.shouldStopAtPosition(2)).toBe(true); // Closing + }); - // This is the backtick that closes the outer markdown block - expect(stateTracker.shouldStopAtPosition(12)).toBe(true); + it("should handle nested code blocks within markdown", () => { + const tracker = new MarkdownBlockStateTracker([ + "```md", + "Here's some code:", + "```javascript", + "console.log('hello');", + "```", + "More content", + "```", + ]); + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening + expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing + expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing + }); + + it("should handle multiple bare backticks", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "Content with ```inline``` code", + "```", + "More content", + "```", + ]); + expect(tracker.shouldStopAtPosition(2)).toBe(false); // First bare backticks + expect(tracker.shouldStopAtPosition(4)).toBe(true); // Last bare backticks + }); + + it("should handle non-markdown code blocks", () => { + const tracker = new MarkdownBlockStateTracker([ + "```javascript", + "console.log('hello');", + "```", + ]); + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Not a markdown block + }); + + it("should handle mixed markdown types", () => { + const tracker = new MarkdownBlockStateTracker([ + "```gfm", + "# GitHub Flavored Markdown", + "```", + ]); + expect(tracker.shouldStopAtPosition(2)).toBe(true); + }); + + it("should handle state persistence across multiple calls", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "# Documentation", + "```typescript", + "interface Config {}", + "```", + "Final notes", + "```", + ]); + + // Process incrementally + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening + expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing + expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing + }); + + it("should handle lines that are not closing backticks", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "Regular content line", + "```", + ]); + expect(tracker.shouldStopAtPosition(1)).toBe(false); // Not backticks + }); + + it("should provide access to trimmed lines", () => { + const tracker = new MarkdownBlockStateTracker([ + " ```markdown ", + " # Title ", + " ``` ", + ]); + const trimmedLines = tracker.getTrimmedLines(); + expect(trimmedLines).toEqual(["```markdown", "# Title", "```"]); + }); + + it("should identify bare backtick lines correctly", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "```", + "content", + "```", + ]); + expect(tracker.isBareBacktickLine(0)).toBe(false); // Has language + expect(tracker.isBareBacktickLine(1)).toBe(true); // Bare backticks + expect(tracker.isBareBacktickLine(2)).toBe(false); // Content + expect(tracker.isBareBacktickLine(3)).toBe(true); // Bare backticks + }); + + it("should count remaining bare backticks correctly", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "```", + "content", + "```", + "more content", + "```", + ]); + expect(tracker.getRemainingBareBackticksAfter(0)).toBe(3); // After opening + expect(tracker.getRemainingBareBackticksAfter(1)).toBe(2); // After first bare + expect(tracker.getRemainingBareBackticksAfter(3)).toBe(1); // After second bare + expect(tracker.getRemainingBareBackticksAfter(5)).toBe(0); // After last bare + }); }); -test("MarkdownBlockStateTracker handles simple code blocks correctly", () => { - const lines = [ - "Some code:", - "", - "```javascript", - "function test() {", - " return true;", - "}", - "```", - "", - "More text", - ]; +describe("collectAllLines", () => { + async function* createAsyncGenerator(items: T[]): AsyncGenerator { + for (const item of items) { + yield item; + } + } - const stateTracker = new MarkdownBlockStateTracker(lines); + it("should collect all lines from a stream", async () => { + const stream = createAsyncGenerator(["line1", "line2", "line3"]); + const result = await collectAllLines(stream); + expect(result).toEqual(["line1", "line2", "line3"]); + }); - // This is just a simple code block, not nested markdown - expect(stateTracker.shouldStopAtPosition(6)).toBe(false); + it("should handle empty streams", async () => { + const stream = createAsyncGenerator([]); + const result = await collectAllLines(stream); + expect(result).toEqual([]); + }); + + it("should handle streams with mixed types", async () => { + const stream = createAsyncGenerator([1, "text", null, true]); + const result = await collectAllLines(stream); + expect(result).toEqual([1, "text", null, true]); + }); + + it("should handle streams with empty strings", async () => { + const stream = createAsyncGenerator(["", "line2", "", "line4"]); + const result = await collectAllLines(stream); + expect(result).toEqual(["", "line2", "", "line4"]); + }); + + it("should handle large streams", async () => { + const largeArray = Array.from({ length: 1000 }, (_, i) => `line${i}`); + const stream = createAsyncGenerator(largeArray); + const result = await collectAllLines(stream); + expect(result).toEqual(largeArray); + }); + + it("should handle object streams", async () => { + const objects = [ + { type: "new", line: "const x = 5;" }, + { type: "old", line: "let y = 10;" }, + ]; + const stream = createAsyncGenerator(objects); + const result = await collectAllLines(stream); + expect(result).toEqual(objects); + }); }); diff --git a/core/utils/streamMarkdownUtils.ts b/core/utils/streamMarkdownUtils.ts index 94505dfdf..88e8eabec 100644 --- a/core/utils/streamMarkdownUtils.ts +++ b/core/utils/streamMarkdownUtils.ts @@ -1,8 +1,5 @@ import { LineStream } from "../diff/util"; -import { - isMarkdownFile, - MarkdownBlockStateTracker -} from "./markdownUtils"; +import { isMarkdownFile, MarkdownBlockStateTracker } from "./markdownUtils"; /** * Determines if we should stop at a markdown block based on nested markdown logic. diff --git a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts b/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts deleted file mode 100644 index 51649c251..000000000 --- a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { headerIsMarkdown } from "./headerIsMarkdown"; - -describe("headerIsMarkdown", () => { - // Test exact match with common Markdown identifiers - it("should identify exact matches with common Markdown identifiers", () => { - expect(headerIsMarkdown("md")).toBe(true); - expect(headerIsMarkdown("markdown")).toBe(true); - expect(headerIsMarkdown("gfm")).toBe(true); - expect(headerIsMarkdown("github-markdown")).toBe(true); - }); - - // Test identifiers preceded by a space - it("should identify identifiers preceded by a space", () => { - expect(headerIsMarkdown("lang md")).toBe(true); - expect(headerIsMarkdown("something markdown")).toBe(true); - expect(headerIsMarkdown("language gfm")).toBe(true); - expect(headerIsMarkdown("spec github-markdown")).toBe(true); - }); - - // Test file extensions - it("should identify file names with markdown extensions", () => { - expect(headerIsMarkdown("example.md")).toBe(true); - expect(headerIsMarkdown("document.markdown")).toBe(true); - expect(headerIsMarkdown("readme.gfm")).toBe(true); - }); - - // Test more complex cases with extensions - it("should identify file names with markdown extensions followed by other text", () => { - expect(headerIsMarkdown("example.md additional text")).toBe(true); - expect(headerIsMarkdown("document.markdown with some description")).toBe( - true, - ); - expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true); - }); - - // Test non-markdown cases - it("should not identify non-markdown headers", () => { - expect(headerIsMarkdown("javascript")).toBe(false); - expect(headerIsMarkdown("typescript")).toBe(false); - expect(headerIsMarkdown("plain")).toBe(false); - expect(headerIsMarkdown("python")).toBe(false); - }); - - // Test edge cases - it("should handle edge cases correctly", () => { - expect(headerIsMarkdown("")).toBe(false); - expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md" - expect(headerIsMarkdown("readme md")).toBe(true); - expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension - }); - - // Test case sensitivity - it("should respect case sensitivity", () => { - expect(headerIsMarkdown("MD")).toBe(false); - expect(headerIsMarkdown("MARKDOWN")).toBe(false); - expect(headerIsMarkdown("example.MD")).toBe(false); - expect(headerIsMarkdown("lang MD")).toBe(false); - }); - - // Test with special characters and spacing - it("should handle special characters and spacing correctly", () => { - expect(headerIsMarkdown(" md")).toBe(true); // Space before "md" - expect(headerIsMarkdown("md ")).toBe(true); // Space after "md" - expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix - expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix - }); -}); diff --git a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts deleted file mode 100644 index cfdba2fde..000000000 --- a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Determines if a given header string represents Markdown content. - * - * The function checks various patterns to identify Markdown headers: - * - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown) - * - Contains these identifiers preceded by a space - * - First word has a file extension of md, markdown, or gfm - * - * @param header - The string to check for Markdown indicators - * @returns True if the header represents Markdown content, false otherwise - */ -export function headerIsMarkdown(header: string): boolean { - return ( - header === "md" || - header === "markdown" || - header === "gfm" || - header === "github-markdown" || - header.includes(" md") || - header.includes(" markdown") || - header.includes(" gfm") || - header.includes(" github-markdown") || - header.split(" ")[0]?.split(".").pop() === "md" || - header.split(" ")[0]?.split(".").pop() === "markdown" || - header.split(" ")[0]?.split(".").pop() === "gfm" - ); -} diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index b054f0bd9..380c1a18a 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -7,48 +7,10 @@ Note, this was benchmarked at sub-millisecond */ -import { headerIsMarkdown } from "./headerIsMarkdown"; - -/** - * Optimized state tracker for markdown patch operations to avoid recomputing on each call. - */ -class MarkdownPatchStateTracker { - private trimmedLines: string[]; - private bareBacktickPositions: number[]; - - constructor(lines: string[]) { - this.trimmedLines = lines.map((l) => l.trim()); - // Pre-compute positions of all bare backtick lines for faster lookup - this.bareBacktickPositions = []; - for (let i = 0; i < this.trimmedLines.length; i++) { - if (this.trimmedLines[i].match(/^`+$/)) { - this.bareBacktickPositions.push(i); - } - } - } - - /** - * Efficiently determines if there are remaining bare backticks after the given position. - */ - getRemainingBareBackticksAfter(currentIndex: number): number { - return this.bareBacktickPositions.filter((pos) => pos > currentIndex) - .length; - } - - /** - * Checks if the line at the given index is a bare backtick line. - */ - isBareBacktickLine(index: number): boolean { - return this.bareBacktickPositions.includes(index); - } - - /** - * Gets the trimmed lines array. - */ - getTrimmedLines(): string[] { - return this.trimmedLines; - } -} +import { + headerIsMarkdown, + MarkdownBlockStateTracker, +} from "../../../../../core/utils/markdownUtils"; export const patchNestedMarkdown = (source: string): string => { // Early return if no markdown codeblock pattern is found (including GitHub variants) @@ -59,7 +21,7 @@ export const patchNestedMarkdown = (source: string): string => { const lines = source.split("\n"); // Use optimized state tracker for efficient bare backtick analysis - const stateTracker = new MarkdownPatchStateTracker(lines); + const stateTracker = new MarkdownBlockStateTracker(lines); const trimmedLines = stateTracker.getTrimmedLines(); for (let i = 0; i < trimmedLines.length; i++) { From f642b1c7cf138f2b24255799a91adb61a26e0702 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 14 Jul 2025 11:03:43 -0700 Subject: [PATCH 057/178] Revert "remove accountbutton" This reverts commit b96068408e65b2c5687b7736eba831febcc02fc8. --- .../AssistantAndOrgListbox/AccountOption.tsx | 51 ------------ .../AssistantAndOrgListbox/index.tsx | 23 +++++- gui/src/pages/config/AccountButton.tsx | 82 +++++++++++++++++++ gui/src/pages/config/index.tsx | 2 + gui/src/pages/history/index.tsx | 8 +- 5 files changed, 112 insertions(+), 54 deletions(-) delete mode 100644 gui/src/components/AssistantAndOrgListbox/AccountOption.tsx create mode 100644 gui/src/pages/config/AccountButton.tsx diff --git a/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx b/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx deleted file mode 100644 index 98e8adbc5..000000000 --- a/gui/src/components/AssistantAndOrgListbox/AccountOption.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ArrowRightEndOnRectangleIcon, - UserCircleIcon as UserCircleIconOutline, -} from "@heroicons/react/24/outline"; -import { isOnPremSession } from "core/control-plane/AuthTypes"; -import { useAuth } from "../../context/Auth"; -import { ListboxOption, useFontSize } from "../ui"; - -interface AccountOptionProps { - onClose: () => void; -} - -export function AccountOption({ onClose }: AccountOptionProps) { - const { session, logout, login } = useAuth(); - const tinyFont = useFontSize(-4); - - // No account option for on-prem deployments - if (session && isOnPremSession(session)) { - return null; - } - - async function handleClick() { - if (session) { - logout(); - } else { - await login(false); - } - onClose(); - } - - return ( - -
- {session ? ( - - ) : ( - - )} - {session ? "Log out" : "Sign in"} -
-
- ); -} diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index 65b9e6a81..40d15c709 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -18,7 +18,6 @@ import { Transition, useFontSize, } from "../ui"; -import { AccountOption } from "./AccountOption"; import { AssistantOptions } from "./AssistantOptions"; import { ScopeSelect } from "./ScopeSelect"; import { SelectedAssistantButton } from "./SelectedAssistantButton"; @@ -34,6 +33,7 @@ export function AssistantAndOrgListbox() { selectedProfile, session, login, + logout, organizations, refreshProfiles, } = useAuth(); @@ -57,6 +57,11 @@ export function AssistantAndOrgListbox() { close(); } + function onLogout() { + logout(); + close(); + } + useEffect(() => { let lastToggleTime = 0; const DEBOUNCE_MS = 800; @@ -184,7 +189,21 @@ export function AssistantAndOrgListbox() { - + {session && ( + +
+ Log out +
+
+ )}
login(false)} + > + Sign in + + ); + } + + // No login button for on-prem deployments + if (isOnPremSession(session)) { + return null; + } + + return ( + + {({ close }) => ( + <> + +
+ + {selectedOrg === null ? "Personal" : selectedOrg.name} + + +
+
+ + + +
+
+ {session.account.label} + + {session.account.id} + +
+ + {organizations.length > 0 && ( +
+ + +
+ )} + + +
+
+
+ + )} +
+ ); +} diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index d9939a2c8..ea5ccef44 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -9,6 +9,7 @@ import { useNavigate } from "react-router-dom"; import { PageHeader } from "../../components/PageHeader"; import { useNavigationListener } from "../../hooks/useNavigationListener"; import { fontSize } from "../../util"; +import { AccountButton } from "./AccountButton"; import { HelpCenterSection } from "./HelpCenterSection"; import { IndexingSettingsSection } from "./IndexingSettingsSection"; import KeyboardShortcuts from "./KeyboardShortcuts"; @@ -62,6 +63,7 @@ function ConfigPage() { showBorder onTitleClick={() => navigate("/")} title="Chat" + rightContent={} /> {/* Tab Headers */} diff --git a/gui/src/pages/history/index.tsx b/gui/src/pages/history/index.tsx index 86950ff24..a8be3d92f 100644 --- a/gui/src/pages/history/index.tsx +++ b/gui/src/pages/history/index.tsx @@ -2,6 +2,7 @@ import { useNavigate } from "react-router-dom"; import { History } from "../../components/History"; import { PageHeader } from "../../components/PageHeader"; import { getFontSize } from "../../util"; +import { AccountButton } from "../config/AccountButton"; export default function HistoryPage() { const navigate = useNavigate(); @@ -11,7 +12,12 @@ export default function HistoryPage() { className="flex flex-1 flex-col overflow-auto" style={{ fontSize: getFontSize() }} > - navigate("/")} title="Chat" /> + navigate("/")} + title="Chat" + rightContent={} + />
); From 4b4afe193eb17eddac68d0c9996d14494ad0a3e9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 14 Jul 2025 12:48:36 -0700 Subject: [PATCH 058/178] perf: reduce redundant calculations, make window disappear immediately --- .../src/activation/NextEditWindowManager.ts | 87 +++++++++---------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 58d03239d..62ae5eaf5 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -117,6 +117,9 @@ export class NextEditWindowManager { // Track for logging purposes. private loggingService: NextEditLoggingService; private mostRecentCompletionId: string | null = null; + // Helps us skip redundant calculations. No need for cleanup because this always gets reassigned with new values at showNextEditWindow, and we don't reuse windows. + private editableRegionStartLine: number = 0; + private editableRegionEndLine: number = 0; // Disposables private disposables: vscode.Disposable[] = []; @@ -261,6 +264,7 @@ export class NextEditWindowManager { editor: vscode.TextEditor, currCursorPos: vscode.Position, editableRegionStartLine: number, + editableRegionEndLine: number, oldEditRangeSlice: string, newEditRangeSlice: string, diffLines: DiffLine[], @@ -272,11 +276,14 @@ export class NextEditWindowManager { // Clear any existing decorations first (very important to prevent overlapping). await this.hideAllNextEditWindows(); + this.editableRegionStartLine = editableRegionStartLine; + this.editableRegionEndLine = editableRegionEndLine; + // Store the current tooltip text for accepting later. this.currentTooltipText = newEditRangeSlice; // How far away is the current line from the start of the editable region? - const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine; + const lineOffsetAtCursorPos = currCursorPos.line - this.editableRegionStartLine; // How long is the line at the current cursor position? const lineContentAtCursorPos = @@ -291,7 +298,7 @@ export class NextEditWindowManager { // Calculate the actual line number in the editor by adding the startPos offset // to the line number from the diff calculation. this.finalCursorPos = new vscode.Position( - editableRegionStartLine + offset.line, + this.editableRegionStartLine + offset.line, offset.character, ); @@ -301,13 +308,13 @@ export class NextEditWindowManager { currCursorPos, oldEditRangeSlice, newEditRangeSlice, - editableRegionStartLine, + this.editableRegionStartLine, diffLines, ); const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); - this.renderDeletes(editor, editableRegionStartLine, diffChars); + this.renderDeletes(editor, diffChars); // Reserve tab and esc to either accept or reject the displayed next edit contents. await NextEditWindowManager.reserveTabAndEsc(); @@ -317,6 +324,8 @@ export class NextEditWindowManager { * Hide all tooltips in all editors. */ public async hideAllNextEditWindows() { + await NextEditWindowManager.freeTabAndEsc(); + if (this.currentDecoration) { vscode.window.visibleTextEditors.forEach((editor) => { editor.setDecorations(this.currentDecoration!, []); @@ -339,12 +348,10 @@ export class NextEditWindowManager { // Clear the current tooltip text. this.currentTooltipText = null; } - - await NextEditWindowManager.freeTabAndEsc(); } public async hideAllNextEditWindowsAndResetCompletionId() { - this.hideAllNextEditWindows(); + await this.hideAllNextEditWindows(); // Log with accept = false. await vscode.commands.executeCommand( @@ -352,6 +359,7 @@ export class NextEditWindowManager { this.mostRecentCompletionId, this.loggingService, ); + this.mostRecentCompletionId = null; } @@ -369,6 +377,10 @@ export class NextEditWindowManager { const position = editor.selection.active; let success = false; + + // Hide windows first for a snappier feel. + await this.hideAllNextEditWindows(); + if (this.textApplier) { success = await this.textApplier.applyText( editor, @@ -377,20 +389,12 @@ export class NextEditWindowManager { this.finalCursorPos, ); } else { - // Define the editable region. - const editableRegionStartLine = Math.max( - 0, - position.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - ); - const editableRegionEndLine = Math.min( - editor.document.lineCount - 1, - position.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - ); - const startPos = new vscode.Position(editableRegionStartLine, 0); - const endPosChar = editor.document.lineAt(editableRegionEndLine).text + // Define the range to replace. + const startPos = new vscode.Position(this.editableRegionStartLine, 0); + const endPosChar = editor.document.lineAt(this.editableRegionEndLine).text .length; - const endPos = new vscode.Position(editableRegionEndLine, endPosChar); + const endPos = new vscode.Position(this.editableRegionEndLine, endPosChar); const editRange = new vscode.Range(startPos, endPos); success = await editor.edit((editBuilder) => { @@ -405,23 +409,19 @@ export class NextEditWindowManager { .update("editor.inlineSuggest.enabled", false, true); } - if (success) { + if (success && this.finalCursorPos) { // Move cursor to the final position if available. - if (this.finalCursorPos) { - editor.selection = new vscode.Selection( - this.finalCursorPos, - this.finalCursorPos, - ); - - // Reenable inline suggestions after we move the cursor. - await vscode.workspace - .getConfiguration() - .update("editor.inlineSuggest.enabled", true, true); - - await this.hideAllNextEditWindows(); - } + editor.selection = new vscode.Selection( + this.finalCursorPos, + this.finalCursorPos, + ); } + // Reenable inline suggestions. + await vscode.workspace + .getConfiguration() + .update("editor.inlineSuggest.enabled", true, true); + // Log with accept = true. await vscode.commands.executeCommand( "continue.logNextEditOutcomeAccept", @@ -454,7 +454,7 @@ export class NextEditWindowManager { */ private setupListeners() { // Theme change listener. - vscode.workspace.onDidChangeConfiguration((e) => { + vscode.workspace.onDidChangeConfiguration(async (e) => { if ( e.affectsConfiguration("workbench.colorTheme") || e.affectsConfiguration("editor.fontSize") || @@ -467,7 +467,7 @@ export class NextEditWindowManager { e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme") ) { this.theme = getThemeString(); - this.codeRenderer.setTheme(this.theme); + await this.codeRenderer.setTheme(this.theme); console.log( "Theme updated:", this.theme ? "Theme exists" : "Theme is undefined", @@ -479,9 +479,9 @@ export class NextEditWindowManager { }); // Listen for active color theme changes. - vscode.window.onDidChangeActiveColorTheme(() => { + vscode.window.onDidChangeActiveColorTheme(async () => { this.theme = getThemeString(); - this.codeRenderer.setTheme(this.theme); + await this.codeRenderer.setTheme(this.theme); console.log( "Active theme changed:", this.theme ? "Theme exists" : "Theme is undefined", @@ -495,10 +495,11 @@ export class NextEditWindowManager { this.activeEditor && !vscode.window.visibleTextEditors.includes(this.activeEditor) ) { - if (this.mostRecentCompletionId) + if (this.mostRecentCompletionId) { this.loggingService.cancelRejectionTimeout( this.mostRecentCompletionId, ); + } await this.hideAllNextEditWindows(); } }); @@ -508,10 +509,11 @@ export class NextEditWindowManager { // If the selection changed in our active editor, hide the tooltip. if (this.activeEditor && e.textEditor === this.activeEditor) { // If the cursor moved because of something other than accepting next edit, stop logging it. - if (!this.accepted && this.mostRecentCompletionId) + if (!this.accepted && this.mostRecentCompletionId) { this.loggingService.cancelRejectionTimeout( this.mostRecentCompletionId, ); + } await this.hideAllNextEditWindows(); } }); @@ -788,9 +790,6 @@ export class NextEditWindowManager { private renderDeletes( editor: vscode.TextEditor, - editableRegionStartLine: number, - // oldEditRangeSlice: string, - // newEditRangeSlice: string, oldDiffChars: DiffChar[], ) { const charsToDelete: vscode.DecorationOptions[] = []; @@ -803,11 +802,11 @@ export class NextEditWindowManager { charsToDelete.push({ range: new vscode.Range( new vscode.Position( - editableRegionStartLine + diff.oldLineIndex!, + this.editableRegionStartLine + diff.oldLineIndex!, diff.oldCharIndexInLine!, ), new vscode.Position( - editableRegionStartLine + diff.oldLineIndex!, + this.editableRegionStartLine + diff.oldLineIndex!, diff.oldCharIndexInLine! + diff.char.length, ), ), From 5085c2f602cfc183511831cf8876d0fced937aac Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 14 Jul 2025 12:49:01 -0700 Subject: [PATCH 059/178] perf: pass editableRegionEndLine --- extensions/vscode/src/autocomplete/completionProvider.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 88131a3e8..39b82c1a0 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -420,6 +420,7 @@ export class ContinueCompletionProvider editor, currCursorPos, editableRegionStartLine, + editableRegionEndLine, oldEditRangeSlice, newEditRangeSlice, diffLines, From 4bc7f0ca262145f3aa9252f68efb4f095f085b47 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 14 Jul 2025 14:21:47 -0700 Subject: [PATCH 060/178] feat: remove redundant hides --- .../src/activation/NextEditWindowManager.ts | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 62ae5eaf5..5c432d0e6 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -6,10 +6,6 @@ import * as vscode from "vscode"; import { DiffChar, DiffLine } from "core"; import { CodeRenderer } from "core/codeRenderer/CodeRenderer"; import { myersCharDiff } from "core/diff/myers"; -import { - NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, -} from "core/nextEdit/constants"; import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { getThemeString } from "../util/getTheme"; @@ -283,7 +279,8 @@ export class NextEditWindowManager { this.currentTooltipText = newEditRangeSlice; // How far away is the current line from the start of the editable region? - const lineOffsetAtCursorPos = currCursorPos.line - this.editableRegionStartLine; + const lineOffsetAtCursorPos = + currCursorPos.line - this.editableRegionStartLine; // How long is the line at the current cursor position? const lineContentAtCursorPos = @@ -394,7 +391,10 @@ export class NextEditWindowManager { const endPosChar = editor.document.lineAt(this.editableRegionEndLine).text .length; - const endPos = new vscode.Position(this.editableRegionEndLine, endPosChar); + const endPos = new vscode.Position( + this.editableRegionEndLine, + endPosChar, + ); const editRange = new vscode.Range(startPos, endPos); success = await editor.edit((editBuilder) => { @@ -749,7 +749,6 @@ export class NextEditWindowManager { } // Store the decoration and editor. - await this.hideAllNextEditWindows(); this.currentDecoration = decoration; // TODO: This might be redundant. this.disposables.push(decoration); this.activeEditor = editor; @@ -788,10 +787,7 @@ export class NextEditWindowManager { ); } - private renderDeletes( - editor: vscode.TextEditor, - oldDiffChars: DiffChar[], - ) { + private renderDeletes(editor: vscode.TextEditor, oldDiffChars: DiffChar[]) { const charsToDelete: vscode.DecorationOptions[] = []; // const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice); From 48b48b122f503cf9cdee2ed08b636a1d177747ce Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 15 Jul 2025 08:53:15 -0700 Subject: [PATCH 061/178] Create typescript-enum-usage.md --- .continue/rules/typescript-enum-usage.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .continue/rules/typescript-enum-usage.md diff --git a/.continue/rules/typescript-enum-usage.md b/.continue/rules/typescript-enum-usage.md new file mode 100644 index 000000000..34728c1d5 --- /dev/null +++ b/.continue/rules/typescript-enum-usage.md @@ -0,0 +1,6 @@ +--- +globs: "**/*.{ts,tsx}" +alwaysApply: false +--- + +Use enums instead of simple string unions when possible in TypeScript code From 2e46efaf9e0742d3eef4a74ea05f9cce6f834121 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 10:34:52 -0700 Subject: [PATCH 062/178] add more routes to continue sdk --- packages/continue-sdk/openapi.yaml | 388 ++++ packages/continue-sdk/package-lock.json | 7 +- .../python/api/.openapi-generator/FILES | 30 + packages/continue-sdk/python/api/README.md | 61 +- .../python/api/docs/DefaultApi.md | 604 +++++- .../api/docs/GetAssistant200Response.md | 35 + .../api/docs/GetAssistant403Response.md | 29 + .../api/docs/GetAssistant404Response.md | 29 + .../api/docs/GetFreeTrialStatus200Response.md | 33 + .../GetModelsAddOnCheckoutUrl200Response.md | 29 + .../GetModelsAddOnCheckoutUrl500Response.md | 29 + .../python/api/docs/GetPolicy200Response.md | 30 + .../docs/ListAssistantFullSlugs429Response.md | 29 + .../docs/ListAssistants200ResponseInner.md | 22 +- ...tAssistants200ResponseInnerConfigResult.md | 14 +- .../api/docs/ListAssistants401Response.md | 10 +- .../api/docs/ListAssistants404Response.md | 10 +- .../api/docs/ListOrganizations200Response.md | 29 + ...anizations200ResponseOrganizationsInner.md | 32 + .../python/api/docs/SyncSecretsRequest.md | 31 + .../python/api/openapi_client/__init__.py | 11 + .../api/openapi_client/api/default_api.py | 1883 ++++++++++++++++- .../api/openapi_client/models/__init__.py | 11 + .../models/get_assistant200_response.py | 118 ++ .../models/get_assistant403_response.py | 87 + .../models/get_assistant404_response.py | 87 + .../get_free_trial_status200_response.py | 105 + ..._models_add_on_checkout_url200_response.py | 87 + ..._models_add_on_checkout_url500_response.py | 87 + .../models/get_policy200_response.py | 99 + .../list_assistant_full_slugs429_response.py | 87 + .../models/list_organizations200_response.py | 95 + ...zations200_response_organizations_inner.py | 98 + .../models/sync_secrets_request.py | 101 + .../test/test_get_assistant200_response.py | 70 + .../test/test_get_assistant403_response.py | 51 + .../test/test_get_assistant404_response.py | 51 + .../test_get_free_trial_status200_response.py | 58 + ..._models_add_on_checkout_url200_response.py | 52 + ..._models_add_on_checkout_url500_response.py | 51 + .../api/test/test_get_policy200_response.py | 52 + ...t_list_assistant_full_slugs429_response.py | 51 + .../test_list_organizations200_response.py | 64 + ...zations200_response_organizations_inner.py | 57 + .../api/test/test_sync_secrets_request.py | 58 + .../typescript/api/.openapi-generator/FILES | 11 + .../continue-sdk/typescript/api/README.md | 18 +- .../typescript/api/src/apis/DefaultApi.ts | 616 +++++- .../typescript/api/src/apis/index.ts | 2 +- .../continue-sdk/typescript/api/src/index.ts | 6 +- .../api/src/models/GetAssistant200Response.ts | 124 ++ .../api/src/models/GetAssistant403Response.ts | 65 + .../api/src/models/GetAssistant404Response.ts | 65 + .../models/GetFreeTrialStatus200Response.ts | 100 + .../GetModelsAddOnCheckoutUrl200Response.ts | 66 + .../GetModelsAddOnCheckoutUrl500Response.ts | 65 + .../api/src/models/GetPolicy200Response.ts | 73 + .../ListAssistantFullSlugs429Response.ts | 65 + .../models/ListAssistants200ResponseInner.ts | 197 +- ...tAssistants200ResponseInnerConfigResult.ts | 115 +- .../src/models/ListAssistants401Response.ts | 75 +- .../src/models/ListAssistants404Response.ts | 75 +- .../models/ListOrganizations200Response.ts | 74 + ...anizations200ResponseOrganizationsInner.ts | 92 + .../api/src/models/SyncSecretsRequest.ts | 82 + .../typescript/api/src/models/index.ts | 19 +- .../typescript/api/src/runtime.ts | 706 +++--- .../continue-sdk/typescript/api/tsconfig.json | 9 +- packages/continue-sdk/typescript/build.sh | 2 +- .../continue-sdk/typescript/package-lock.json | 4 +- .../continue-sdk/typescript/tsconfig.json | 1 - 71 files changed, 6947 insertions(+), 832 deletions(-) create mode 100644 packages/continue-sdk/python/api/docs/GetAssistant200Response.md create mode 100644 packages/continue-sdk/python/api/docs/GetAssistant403Response.md create mode 100644 packages/continue-sdk/python/api/docs/GetAssistant404Response.md create mode 100644 packages/continue-sdk/python/api/docs/GetFreeTrialStatus200Response.md create mode 100644 packages/continue-sdk/python/api/docs/GetModelsAddOnCheckoutUrl200Response.md create mode 100644 packages/continue-sdk/python/api/docs/GetModelsAddOnCheckoutUrl500Response.md create mode 100644 packages/continue-sdk/python/api/docs/GetPolicy200Response.md create mode 100644 packages/continue-sdk/python/api/docs/ListAssistantFullSlugs429Response.md create mode 100644 packages/continue-sdk/python/api/docs/ListOrganizations200Response.md create mode 100644 packages/continue-sdk/python/api/docs/ListOrganizations200ResponseOrganizationsInner.md create mode 100644 packages/continue-sdk/python/api/docs/SyncSecretsRequest.md create mode 100644 packages/continue-sdk/python/api/openapi_client/models/get_assistant200_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/get_assistant403_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/get_assistant404_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/get_free_trial_status200_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/get_models_add_on_checkout_url200_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/get_models_add_on_checkout_url500_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/get_policy200_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/list_assistant_full_slugs429_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/list_organizations200_response.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/list_organizations200_response_organizations_inner.py create mode 100644 packages/continue-sdk/python/api/openapi_client/models/sync_secrets_request.py create mode 100644 packages/continue-sdk/python/api/test/test_get_assistant200_response.py create mode 100644 packages/continue-sdk/python/api/test/test_get_assistant403_response.py create mode 100644 packages/continue-sdk/python/api/test/test_get_assistant404_response.py create mode 100644 packages/continue-sdk/python/api/test/test_get_free_trial_status200_response.py create mode 100644 packages/continue-sdk/python/api/test/test_get_models_add_on_checkout_url200_response.py create mode 100644 packages/continue-sdk/python/api/test/test_get_models_add_on_checkout_url500_response.py create mode 100644 packages/continue-sdk/python/api/test/test_get_policy200_response.py create mode 100644 packages/continue-sdk/python/api/test/test_list_assistant_full_slugs429_response.py create mode 100644 packages/continue-sdk/python/api/test/test_list_organizations200_response.py create mode 100644 packages/continue-sdk/python/api/test/test_list_organizations200_response_organizations_inner.py create mode 100644 packages/continue-sdk/python/api/test/test_sync_secrets_request.py create mode 100644 packages/continue-sdk/typescript/api/src/models/GetAssistant200Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/GetAssistant403Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/GetAssistant404Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/GetFreeTrialStatus200Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/GetModelsAddOnCheckoutUrl200Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/GetModelsAddOnCheckoutUrl500Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/GetPolicy200Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/ListAssistantFullSlugs429Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/ListOrganizations200Response.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/ListOrganizations200ResponseOrganizationsInner.ts create mode 100644 packages/continue-sdk/typescript/api/src/models/SyncSecretsRequest.ts diff --git a/packages/continue-sdk/openapi.yaml b/packages/continue-sdk/openapi.yaml index de3aee93e..7235e3879 100644 --- a/packages/continue-sdk/openapi.yaml +++ b/packages/continue-sdk/openapi.yaml @@ -114,6 +114,394 @@ paths: message: type: string example: "User not found" + + /ide/get-assistant/{ownerSlug}/{packageSlug}: + get: + summary: Get a specific assistant by slug + description: | + Returns a single assistant configuration by its owner and package slug. + This endpoint is useful when you need to retrieve or refresh a specific assistant + without fetching the entire list. + operationId: getAssistant + parameters: + - name: ownerSlug + in: path + description: Slug of the user or organization that owns the assistant + required: true + schema: + type: string + - name: packageSlug + in: path + description: Slug of the assistant package + required: true + schema: + type: string + - name: alwaysUseProxy + in: query + description: Whether to always use the Continue-managed proxy for model requests + required: false + schema: + type: string + enum: ["true", "false"] + - name: organizationId + in: query + description: ID of the organization to scope assistants to. If not provided, personal assistants are returned. + required: false + schema: + type: string + security: + - apiKeyAuth: [] + responses: + "200": + description: Successfully retrieved assistant + content: + application/json: + schema: + type: object + nullable: true + required: + - configResult + - ownerSlug + - packageSlug + properties: + configResult: + type: object + required: + - config + - configLoadInterrupted + properties: + config: + type: object + description: The unrolled assistant configuration + nullable: true + configLoadInterrupted: + type: boolean + description: Whether the configuration loading was interrupted + errors: + type: array + items: + type: string + nullable: true + description: Any errors that occurred during configuration loading + ownerSlug: + type: string + description: Slug of the user or organization that owns the assistant + packageSlug: + type: string + description: Slug of the assistant package + iconUrl: + type: string + nullable: true + description: Pre-signed URL for the assistant's icon + onPremProxyUrl: + type: string + nullable: true + description: URL of the on-premises proxy if the organization uses one + useOnPremProxy: + type: boolean + nullable: true + description: Whether the organization uses an on-premises proxy + rawYaml: + type: string + description: Raw YAML configuration of the assistant + "401": + description: Unauthorized - Authentication failed + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "Unauthorized" + "403": + description: Forbidden - Assistant not allowed in organization + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "This assistant is not allowed in this organization" + "404": + description: User or assistant not found + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "Assistant not found" + + /ide/free-trial-status: + get: + summary: Get free trial status for user + description: | + Returns the current free trial status for the authenticated user, including + usage counts and limits for chat and autocomplete features. + operationId: getFreeTrialStatus + security: + - apiKeyAuth: [] + responses: + "200": + description: Successfully retrieved free trial status + content: + application/json: + schema: + type: object + required: + - optedInToFreeTrial + - chatLimit + - autocompleteLimit + properties: + optedInToFreeTrial: + type: boolean + description: Whether the user has opted into the free trial + chatCount: + type: number + nullable: true + description: Current number of chat messages used + autocompleteCount: + type: number + nullable: true + description: Current number of autocomplete requests used + chatLimit: + type: number + description: Maximum number of chat messages allowed in free trial + autocompleteLimit: + type: number + description: Maximum number of autocomplete requests allowed in free trial + "404": + description: User not found + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "User not found" + + /ide/get-models-add-on-checkout-url: + get: + summary: Get Stripe checkout URL for models add-on + description: | + Creates a Stripe checkout session for the models add-on subscription + and returns the checkout URL. + operationId: getModelsAddOnCheckoutUrl + parameters: + - name: profile_id + in: query + description: Profile ID to include in the callback URL + required: false + schema: + type: string + - name: vscode_uri_scheme + in: query + description: VS Code URI scheme to include in the callback URL + required: false + schema: + type: string + security: + - apiKeyAuth: [] + responses: + "200": + description: Successfully created checkout session + content: + application/json: + schema: + type: object + required: + - url + properties: + url: + type: string + description: Stripe checkout session URL + "404": + description: User not found + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "User not found" + "500": + description: Failed to create checkout session + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "Failed to create checkout session" + + /ide/policy: + get: + summary: Get organization policy + description: | + Returns the policy configuration for the first organization + that the user belongs to which has a policy configured. + operationId: getPolicy + security: + - apiKeyAuth: [] + responses: + "200": + description: Successfully retrieved policy + content: + application/json: + schema: + type: object + properties: + policy: + type: object + nullable: true + description: Organization policy configuration + orgSlug: + type: string + nullable: true + description: Slug of the organization that has the policy + "404": + description: User not found + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "User not found" + + /ide/sync-secrets: + post: + summary: Synchronize secrets for user + description: | + Resolves and synchronizes secrets for the authenticated user based on + the provided Fully Qualified Secret Names (FQSNs). + operationId: syncSecrets + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - fqsns + properties: + fqsns: + type: array + items: + type: object + description: Array of Fully Qualified Secret Names to resolve + orgScopeId: + type: string + nullable: true + description: Organization ID to scope secret resolution to + orgScopeSlug: + type: string + nullable: true + description: Organization slug to scope secret resolution to + security: + - apiKeyAuth: [] + responses: + "200": + description: Successfully resolved secrets + content: + application/json: + schema: + type: array + items: + type: object + nullable: true + description: Resolved secret result or undefined if not found + "404": + description: User not found + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "User not found" + + /ide/list-assistant-full-slugs: + get: + summary: List assistant full slugs (currently returns 429) + description: | + This endpoint is temporarily disabled and returns a 429 status code + to prevent constant refreshes of the full assistant list until a + fixed client version can be deployed. + operationId: listAssistantFullSlugs + security: + - apiKeyAuth: [] + responses: + "429": + description: Too many requests - endpoint temporarily disabled + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "Too many requests" + + /ide/list-organizations: + get: + summary: List organizations for user + description: | + Returns a list of organizations that the authenticated user belongs to, + including organization metadata and pre-signed icon URLs. + operationId: listOrganizations + security: + - apiKeyAuth: [] + responses: + "200": + description: Successfully retrieved organizations + content: + application/json: + schema: + type: object + required: + - organizations + properties: + organizations: + type: array + items: + type: object + required: + - id + - name + - slug + properties: + id: + type: string + description: Organization ID + name: + type: string + description: Organization name + iconUrl: + type: string + nullable: true + description: Pre-signed URL for the organization's icon + slug: + type: string + description: Organization slug + "404": + description: User not found + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "User not found" components: securitySchemes: diff --git a/packages/continue-sdk/package-lock.json b/packages/continue-sdk/package-lock.json index e95db526f..85d4ac59e 100644 --- a/packages/continue-sdk/package-lock.json +++ b/packages/continue-sdk/package-lock.json @@ -20,7 +20,7 @@ }, "../config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.88", + "version": "1.0.96", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -31,10 +31,15 @@ "config-yaml": "dist/cli.js" }, "devDependencies": { + "@semantic-release/changelog": "^6.0.3", + "@semantic-release/git": "^10.0.1", + "@semantic-release/github": "^9.2.6", + "@semantic-release/npm": "^10.0.6", "@types/jest": "^29.5.14", "@types/node": "^20.0.0", "cross-env": "^7.0.3", "jest": "^29.7.0", + "semantic-release": "^21.1.2", "ts-jest": "^29.2.3", "ts-node": "^10.9.2", "zod-to-json-schema": "^3.24.5" diff --git a/packages/continue-sdk/python/api/.openapi-generator/FILES b/packages/continue-sdk/python/api/.openapi-generator/FILES index 641b0db00..f3e894c56 100644 --- a/packages/continue-sdk/python/api/.openapi-generator/FILES +++ b/packages/continue-sdk/python/api/.openapi-generator/FILES @@ -4,10 +4,21 @@ .travis.yml README.md docs/DefaultApi.md +docs/GetAssistant200Response.md +docs/GetAssistant403Response.md +docs/GetAssistant404Response.md +docs/GetFreeTrialStatus200Response.md +docs/GetModelsAddOnCheckoutUrl200Response.md +docs/GetModelsAddOnCheckoutUrl500Response.md +docs/GetPolicy200Response.md +docs/ListAssistantFullSlugs429Response.md docs/ListAssistants200ResponseInner.md docs/ListAssistants200ResponseInnerConfigResult.md docs/ListAssistants401Response.md docs/ListAssistants404Response.md +docs/ListOrganizations200Response.md +docs/ListOrganizations200ResponseOrganizationsInner.md +docs/SyncSecretsRequest.md git_push.sh openapi_client/__init__.py openapi_client/api/__init__.py @@ -17,10 +28,21 @@ openapi_client/api_response.py openapi_client/configuration.py openapi_client/exceptions.py openapi_client/models/__init__.py +openapi_client/models/get_assistant200_response.py +openapi_client/models/get_assistant403_response.py +openapi_client/models/get_assistant404_response.py +openapi_client/models/get_free_trial_status200_response.py +openapi_client/models/get_models_add_on_checkout_url200_response.py +openapi_client/models/get_models_add_on_checkout_url500_response.py +openapi_client/models/get_policy200_response.py +openapi_client/models/list_assistant_full_slugs429_response.py openapi_client/models/list_assistants200_response_inner.py openapi_client/models/list_assistants200_response_inner_config_result.py openapi_client/models/list_assistants401_response.py openapi_client/models/list_assistants404_response.py +openapi_client/models/list_organizations200_response.py +openapi_client/models/list_organizations200_response_organizations_inner.py +openapi_client/models/sync_secrets_request.py openapi_client/py.typed openapi_client/rest.py pyproject.toml @@ -29,4 +51,12 @@ setup.cfg setup.py test-requirements.txt test/__init__.py +test/test_get_free_trial_status200_response.py +test/test_get_models_add_on_checkout_url200_response.py +test/test_get_models_add_on_checkout_url500_response.py +test/test_get_policy200_response.py +test/test_list_assistant_full_slugs429_response.py +test/test_list_organizations200_response.py +test/test_list_organizations200_response_organizations_inner.py +test/test_sync_secrets_request.py tox.ini diff --git a/packages/continue-sdk/python/api/README.md b/packages/continue-sdk/python/api/README.md index 67200c21e..faa81d2fe 100644 --- a/packages/continue-sdk/python/api/README.md +++ b/packages/continue-sdk/python/api/README.md @@ -1,22 +1,21 @@ # openapi-client - API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: - API version: 1.0.0 - Package version: 1.0.0 - Generator version: 7.12.0 - Build package: org.openapitools.codegen.languages.PythonClientCodegen - For more information, please visit [https://continue.dev](https://continue.dev) +For more information, please visit [https://continue.dev](https://continue.dev) ## Requirements. Python 3.8+ ## Installation & Usage - ### pip install If the python package is hosted on a repository, you can install directly using: @@ -24,11 +23,9 @@ If the python package is hosted on a repository, you can install directly using: ```sh pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git ``` - (you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) Then import the package: - ```python import openapi_client ``` @@ -40,11 +37,9 @@ Install via [Setuptools](http://pypi.python.org/pypi/setuptools). ```sh python setup.py install --user ``` - (or `sudo python setup.py install` to install the package for all users) Then import the package: - ```python import openapi_client ``` @@ -84,16 +79,18 @@ configuration = openapi_client.Configuration( with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = openapi_client.DefaultApi(api_client) + owner_slug = 'owner_slug_example' # str | Slug of the user or organization that owns the assistant + package_slug = 'package_slug_example' # str | Slug of the assistant package always_use_proxy = 'always_use_proxy_example' # str | Whether to always use the Continue-managed proxy for model requests (optional) organization_id = 'organization_id_example' # str | ID of the organization to scope assistants to. If not provided, personal assistants are returned. (optional) try: - # List assistants for IDE - api_response = api_instance.list_assistants(always_use_proxy=always_use_proxy, organization_id=organization_id) - print("The response of DefaultApi->list_assistants:\n") + # Get a specific assistant by slug + api_response = api_instance.get_assistant(owner_slug, package_slug, always_use_proxy=always_use_proxy, organization_id=organization_id) + print("The response of DefaultApi->get_assistant:\n") pprint(api_response) except ApiException as e: - print("Exception when calling DefaultApi->list_assistants: %s\n" % e) + print("Exception when calling DefaultApi->get_assistant: %s\n" % e) ``` @@ -101,26 +98,50 @@ with openapi_client.ApiClient(configuration) as api_client: All URIs are relative to *https://api.continue.dev* -| Class | Method | HTTP request | Description | -| ------------ | --------------------------------------------------------- | ---------------------------- | ----------------------- | -| _DefaultApi_ | [**list_assistants**](docs/DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE | +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**get_assistant**](docs/DefaultApi.md#get_assistant) | **GET** /ide/get-assistant/{ownerSlug}/{packageSlug} | Get a specific assistant by slug +*DefaultApi* | [**get_free_trial_status**](docs/DefaultApi.md#get_free_trial_status) | **GET** /ide/free-trial-status | Get free trial status for user +*DefaultApi* | [**get_models_add_on_checkout_url**](docs/DefaultApi.md#get_models_add_on_checkout_url) | **GET** /ide/get-models-add-on-checkout-url | Get Stripe checkout URL for models add-on +*DefaultApi* | [**get_policy**](docs/DefaultApi.md#get_policy) | **GET** /ide/policy | Get organization policy +*DefaultApi* | [**list_assistant_full_slugs**](docs/DefaultApi.md#list_assistant_full_slugs) | **GET** /ide/list-assistant-full-slugs | List assistant full slugs (currently returns 429) +*DefaultApi* | [**list_assistants**](docs/DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE +*DefaultApi* | [**list_organizations**](docs/DefaultApi.md#list_organizations) | **GET** /ide/list-organizations | List organizations for user +*DefaultApi* | [**sync_secrets**](docs/DefaultApi.md#sync_secrets) | **POST** /ide/sync-secrets | Synchronize secrets for user + ## Documentation For Models -- [ListAssistants200ResponseInner](docs/ListAssistants200ResponseInner.md) -- [ListAssistants200ResponseInnerConfigResult](docs/ListAssistants200ResponseInnerConfigResult.md) -- [ListAssistants401Response](docs/ListAssistants401Response.md) -- [ListAssistants404Response](docs/ListAssistants404Response.md) + - [GetAssistant200Response](docs/GetAssistant200Response.md) + - [GetAssistant403Response](docs/GetAssistant403Response.md) + - [GetAssistant404Response](docs/GetAssistant404Response.md) + - [GetFreeTrialStatus200Response](docs/GetFreeTrialStatus200Response.md) + - [GetModelsAddOnCheckoutUrl200Response](docs/GetModelsAddOnCheckoutUrl200Response.md) + - [GetModelsAddOnCheckoutUrl500Response](docs/GetModelsAddOnCheckoutUrl500Response.md) + - [GetPolicy200Response](docs/GetPolicy200Response.md) + - [ListAssistantFullSlugs429Response](docs/ListAssistantFullSlugs429Response.md) + - [ListAssistants200ResponseInner](docs/ListAssistants200ResponseInner.md) + - [ListAssistants200ResponseInnerConfigResult](docs/ListAssistants200ResponseInnerConfigResult.md) + - [ListAssistants401Response](docs/ListAssistants401Response.md) + - [ListAssistants404Response](docs/ListAssistants404Response.md) + - [ListOrganizations200Response](docs/ListOrganizations200Response.md) + - [ListOrganizations200ResponseOrganizationsInner](docs/ListOrganizations200ResponseOrganizationsInner.md) + - [SyncSecretsRequest](docs/SyncSecretsRequest.md) + - ## Documentation For Authorization + Authentication schemes defined for the API: - ### apiKeyAuth - **Type**: Bearer authentication + ## Author + + + + diff --git a/packages/continue-sdk/python/api/docs/DefaultApi.md b/packages/continue-sdk/python/api/docs/DefaultApi.md index b5632904f..1a551ec97 100644 --- a/packages/continue-sdk/python/api/docs/DefaultApi.md +++ b/packages/continue-sdk/python/api/docs/DefaultApi.md @@ -2,12 +2,421 @@ All URIs are relative to *https://api.continue.dev* -| Method | HTTP request | Description | -| ---------------------------------------------------- | ---------------------------- | ----------------------- | -| [**list_assistants**](DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE | +Method | HTTP request | Description +------------- | ------------- | ------------- +[**get_assistant**](DefaultApi.md#get_assistant) | **GET** /ide/get-assistant/{ownerSlug}/{packageSlug} | Get a specific assistant by slug +[**get_free_trial_status**](DefaultApi.md#get_free_trial_status) | **GET** /ide/free-trial-status | Get free trial status for user +[**get_models_add_on_checkout_url**](DefaultApi.md#get_models_add_on_checkout_url) | **GET** /ide/get-models-add-on-checkout-url | Get Stripe checkout URL for models add-on +[**get_policy**](DefaultApi.md#get_policy) | **GET** /ide/policy | Get organization policy +[**list_assistant_full_slugs**](DefaultApi.md#list_assistant_full_slugs) | **GET** /ide/list-assistant-full-slugs | List assistant full slugs (currently returns 429) +[**list_assistants**](DefaultApi.md#list_assistants) | **GET** /ide/list-assistants | List assistants for IDE +[**list_organizations**](DefaultApi.md#list_organizations) | **GET** /ide/list-organizations | List organizations for user +[**sync_secrets**](DefaultApi.md#sync_secrets) | **POST** /ide/sync-secrets | Synchronize secrets for user + + +# **get_assistant** +> GetAssistant200Response get_assistant(owner_slug, package_slug, always_use_proxy=always_use_proxy, organization_id=organization_id) + +Get a specific assistant by slug + +Returns a single assistant configuration by its owner and package slug. +This endpoint is useful when you need to retrieve or refresh a specific assistant +without fetching the entire list. + + +### Example + +* Bearer Authentication (apiKeyAuth): + +```python +import openapi_client +from openapi_client.models.get_assistant200_response import GetAssistant200Response +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + owner_slug = 'owner_slug_example' # str | Slug of the user or organization that owns the assistant + package_slug = 'package_slug_example' # str | Slug of the assistant package + always_use_proxy = 'always_use_proxy_example' # str | Whether to always use the Continue-managed proxy for model requests (optional) + organization_id = 'organization_id_example' # str | ID of the organization to scope assistants to. If not provided, personal assistants are returned. (optional) + + try: + # Get a specific assistant by slug + api_response = api_instance.get_assistant(owner_slug, package_slug, always_use_proxy=always_use_proxy, organization_id=organization_id) + print("The response of DefaultApi->get_assistant:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->get_assistant: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **owner_slug** | **str**| Slug of the user or organization that owns the assistant | + **package_slug** | **str**| Slug of the assistant package | + **always_use_proxy** | **str**| Whether to always use the Continue-managed proxy for model requests | [optional] + **organization_id** | **str**| ID of the organization to scope assistants to. If not provided, personal assistants are returned. | [optional] + +### Return type + +[**GetAssistant200Response**](GetAssistant200Response.md) + +### Authorization + +[apiKeyAuth](../README.md#apiKeyAuth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successfully retrieved assistant | - | +**401** | Unauthorized - Authentication failed | - | +**403** | Forbidden - Assistant not allowed in organization | - | +**404** | User or assistant not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_free_trial_status** +> GetFreeTrialStatus200Response get_free_trial_status() + +Get free trial status for user + +Returns the current free trial status for the authenticated user, including +usage counts and limits for chat and autocomplete features. + + +### Example + +* Bearer Authentication (apiKeyAuth): + +```python +import openapi_client +from openapi_client.models.get_free_trial_status200_response import GetFreeTrialStatus200Response +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + + try: + # Get free trial status for user + api_response = api_instance.get_free_trial_status() + print("The response of DefaultApi->get_free_trial_status:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->get_free_trial_status: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**GetFreeTrialStatus200Response**](GetFreeTrialStatus200Response.md) + +### Authorization + +[apiKeyAuth](../README.md#apiKeyAuth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successfully retrieved free trial status | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_models_add_on_checkout_url** +> GetModelsAddOnCheckoutUrl200Response get_models_add_on_checkout_url(profile_id=profile_id, vscode_uri_scheme=vscode_uri_scheme) + +Get Stripe checkout URL for models add-on + +Creates a Stripe checkout session for the models add-on subscription +and returns the checkout URL. + + +### Example + +* Bearer Authentication (apiKeyAuth): + +```python +import openapi_client +from openapi_client.models.get_models_add_on_checkout_url200_response import GetModelsAddOnCheckoutUrl200Response +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + profile_id = 'profile_id_example' # str | Profile ID to include in the callback URL (optional) + vscode_uri_scheme = 'vscode_uri_scheme_example' # str | VS Code URI scheme to include in the callback URL (optional) + + try: + # Get Stripe checkout URL for models add-on + api_response = api_instance.get_models_add_on_checkout_url(profile_id=profile_id, vscode_uri_scheme=vscode_uri_scheme) + print("The response of DefaultApi->get_models_add_on_checkout_url:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->get_models_add_on_checkout_url: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **profile_id** | **str**| Profile ID to include in the callback URL | [optional] + **vscode_uri_scheme** | **str**| VS Code URI scheme to include in the callback URL | [optional] + +### Return type + +[**GetModelsAddOnCheckoutUrl200Response**](GetModelsAddOnCheckoutUrl200Response.md) + +### Authorization + +[apiKeyAuth](../README.md#apiKeyAuth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successfully created checkout session | - | +**404** | User not found | - | +**500** | Failed to create checkout session | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_policy** +> GetPolicy200Response get_policy() + +Get organization policy + +Returns the policy configuration for the first organization +that the user belongs to which has a policy configured. + + +### Example + +* Bearer Authentication (apiKeyAuth): + +```python +import openapi_client +from openapi_client.models.get_policy200_response import GetPolicy200Response +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + + try: + # Get organization policy + api_response = api_instance.get_policy() + print("The response of DefaultApi->get_policy:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->get_policy: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**GetPolicy200Response**](GetPolicy200Response.md) + +### Authorization + +[apiKeyAuth](../README.md#apiKeyAuth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successfully retrieved policy | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **list_assistant_full_slugs** +> list_assistant_full_slugs() + +List assistant full slugs (currently returns 429) + +This endpoint is temporarily disabled and returns a 429 status code +to prevent constant refreshes of the full assistant list until a +fixed client version can be deployed. + + +### Example + +* Bearer Authentication (apiKeyAuth): + +```python +import openapi_client +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + + try: + # List assistant full slugs (currently returns 429) + api_instance.list_assistant_full_slugs() + except Exception as e: + print("Exception when calling DefaultApi->list_assistant_full_slugs: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +[apiKeyAuth](../README.md#apiKeyAuth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**429** | Too many requests - endpoint temporarily disabled | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **list_assistants** - > List[ListAssistants200ResponseInner] list_assistants(always_use_proxy=always_use_proxy, organization_id=organization_id) List assistants for IDE @@ -18,9 +427,10 @@ icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + ### Example -- Bearer Authentication (apiKeyAuth): +* Bearer Authentication (apiKeyAuth): ```python import openapi_client @@ -60,12 +470,15 @@ with openapi_client.ApiClient(configuration) as api_client: print("Exception when calling DefaultApi->list_assistants: %s\n" % e) ``` + + ### Parameters -| Name | Type | Description | Notes | -| -------------------- | ------- | ------------------------------------------------------------------------------------------------- | ---------- | -| **always_use_proxy** | **str** | Whether to always use the Continue-managed proxy for model requests | [optional] | -| **organization_id** | **str** | ID of the organization to scope assistants to. If not provided, personal assistants are returned. | [optional] | + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **always_use_proxy** | **str**| Whether to always use the Continue-managed proxy for model requests | [optional] + **organization_id** | **str**| ID of the organization to scope assistants to. If not provided, personal assistants are returned. | [optional] ### Return type @@ -77,15 +490,174 @@ with openapi_client.ApiClient(configuration) as api_client: ### HTTP request headers -- **Content-Type**: Not defined -- **Accept**: application/json + - **Content-Type**: Not defined + - **Accept**: application/json ### HTTP response details -| Status code | Description | Response headers | -| ----------- | ------------------------------------ | ---------------- | -| **200** | Successfully retrieved assistants | - | -| **401** | Unauthorized - Authentication failed | - | -| **404** | User not found | - | +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successfully retrieved assistants | - | +**401** | Unauthorized - Authentication failed | - | +**404** | User not found | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **list_organizations** +> ListOrganizations200Response list_organizations() + +List organizations for user + +Returns a list of organizations that the authenticated user belongs to, +including organization metadata and pre-signed icon URLs. + + +### Example + +* Bearer Authentication (apiKeyAuth): + +```python +import openapi_client +from openapi_client.models.list_organizations200_response import ListOrganizations200Response +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + + try: + # List organizations for user + api_response = api_instance.list_organizations() + print("The response of DefaultApi->list_organizations:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->list_organizations: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**ListOrganizations200Response**](ListOrganizations200Response.md) + +### Authorization + +[apiKeyAuth](../README.md#apiKeyAuth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successfully retrieved organizations | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **sync_secrets** +> List[Optional[object]] sync_secrets(sync_secrets_request) + +Synchronize secrets for user + +Resolves and synchronizes secrets for the authenticated user based on +the provided Fully Qualified Secret Names (FQSNs). + + +### Example + +* Bearer Authentication (apiKeyAuth): + +```python +import openapi_client +from openapi_client.models.sync_secrets_request import SyncSecretsRequest +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to https://api.continue.dev +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "https://api.continue.dev" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: apiKeyAuth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.DefaultApi(api_client) + sync_secrets_request = openapi_client.SyncSecretsRequest() # SyncSecretsRequest | + + try: + # Synchronize secrets for user + api_response = api_instance.sync_secrets(sync_secrets_request) + print("The response of DefaultApi->sync_secrets:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->sync_secrets: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **sync_secrets_request** | [**SyncSecretsRequest**](SyncSecretsRequest.md)| | + +### Return type + +**List[Optional[object]]** + +### Authorization + +[apiKeyAuth](../README.md#apiKeyAuth) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successfully resolved secrets | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/packages/continue-sdk/python/api/docs/GetAssistant200Response.md b/packages/continue-sdk/python/api/docs/GetAssistant200Response.md new file mode 100644 index 000000000..9718487aa --- /dev/null +++ b/packages/continue-sdk/python/api/docs/GetAssistant200Response.md @@ -0,0 +1,35 @@ +# GetAssistant200Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**config_result** | [**ListAssistants200ResponseInnerConfigResult**](ListAssistants200ResponseInnerConfigResult.md) | | +**owner_slug** | **str** | Slug of the user or organization that owns the assistant | +**package_slug** | **str** | Slug of the assistant package | +**icon_url** | **str** | Pre-signed URL for the assistant's icon | [optional] +**on_prem_proxy_url** | **str** | URL of the on-premises proxy if the organization uses one | [optional] +**use_on_prem_proxy** | **bool** | Whether the organization uses an on-premises proxy | [optional] +**raw_yaml** | **str** | Raw YAML configuration of the assistant | [optional] + +## Example + +```python +from openapi_client.models.get_assistant200_response import GetAssistant200Response + +# TODO update the JSON string below +json = "{}" +# create an instance of GetAssistant200Response from a JSON string +get_assistant200_response_instance = GetAssistant200Response.from_json(json) +# print the JSON string representation of the object +print(GetAssistant200Response.to_json()) + +# convert the object into a dict +get_assistant200_response_dict = get_assistant200_response_instance.to_dict() +# create an instance of GetAssistant200Response from a dict +get_assistant200_response_from_dict = GetAssistant200Response.from_dict(get_assistant200_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/GetAssistant403Response.md b/packages/continue-sdk/python/api/docs/GetAssistant403Response.md new file mode 100644 index 000000000..b6cc7c7f9 --- /dev/null +++ b/packages/continue-sdk/python/api/docs/GetAssistant403Response.md @@ -0,0 +1,29 @@ +# GetAssistant403Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **str** | | [optional] + +## Example + +```python +from openapi_client.models.get_assistant403_response import GetAssistant403Response + +# TODO update the JSON string below +json = "{}" +# create an instance of GetAssistant403Response from a JSON string +get_assistant403_response_instance = GetAssistant403Response.from_json(json) +# print the JSON string representation of the object +print(GetAssistant403Response.to_json()) + +# convert the object into a dict +get_assistant403_response_dict = get_assistant403_response_instance.to_dict() +# create an instance of GetAssistant403Response from a dict +get_assistant403_response_from_dict = GetAssistant403Response.from_dict(get_assistant403_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/GetAssistant404Response.md b/packages/continue-sdk/python/api/docs/GetAssistant404Response.md new file mode 100644 index 000000000..2602256e8 --- /dev/null +++ b/packages/continue-sdk/python/api/docs/GetAssistant404Response.md @@ -0,0 +1,29 @@ +# GetAssistant404Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **str** | | [optional] + +## Example + +```python +from openapi_client.models.get_assistant404_response import GetAssistant404Response + +# TODO update the JSON string below +json = "{}" +# create an instance of GetAssistant404Response from a JSON string +get_assistant404_response_instance = GetAssistant404Response.from_json(json) +# print the JSON string representation of the object +print(GetAssistant404Response.to_json()) + +# convert the object into a dict +get_assistant404_response_dict = get_assistant404_response_instance.to_dict() +# create an instance of GetAssistant404Response from a dict +get_assistant404_response_from_dict = GetAssistant404Response.from_dict(get_assistant404_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/GetFreeTrialStatus200Response.md b/packages/continue-sdk/python/api/docs/GetFreeTrialStatus200Response.md new file mode 100644 index 000000000..5ce22fbb7 --- /dev/null +++ b/packages/continue-sdk/python/api/docs/GetFreeTrialStatus200Response.md @@ -0,0 +1,33 @@ +# GetFreeTrialStatus200Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**opted_in_to_free_trial** | **bool** | Whether the user has opted into the free trial | +**chat_count** | **float** | Current number of chat messages used | [optional] +**autocomplete_count** | **float** | Current number of autocomplete requests used | [optional] +**chat_limit** | **float** | Maximum number of chat messages allowed in free trial | +**autocomplete_limit** | **float** | Maximum number of autocomplete requests allowed in free trial | + +## Example + +```python +from openapi_client.models.get_free_trial_status200_response import GetFreeTrialStatus200Response + +# TODO update the JSON string below +json = "{}" +# create an instance of GetFreeTrialStatus200Response from a JSON string +get_free_trial_status200_response_instance = GetFreeTrialStatus200Response.from_json(json) +# print the JSON string representation of the object +print(GetFreeTrialStatus200Response.to_json()) + +# convert the object into a dict +get_free_trial_status200_response_dict = get_free_trial_status200_response_instance.to_dict() +# create an instance of GetFreeTrialStatus200Response from a dict +get_free_trial_status200_response_from_dict = GetFreeTrialStatus200Response.from_dict(get_free_trial_status200_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/GetModelsAddOnCheckoutUrl200Response.md b/packages/continue-sdk/python/api/docs/GetModelsAddOnCheckoutUrl200Response.md new file mode 100644 index 000000000..548fb8408 --- /dev/null +++ b/packages/continue-sdk/python/api/docs/GetModelsAddOnCheckoutUrl200Response.md @@ -0,0 +1,29 @@ +# GetModelsAddOnCheckoutUrl200Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**url** | **str** | Stripe checkout session URL | + +## Example + +```python +from openapi_client.models.get_models_add_on_checkout_url200_response import GetModelsAddOnCheckoutUrl200Response + +# TODO update the JSON string below +json = "{}" +# create an instance of GetModelsAddOnCheckoutUrl200Response from a JSON string +get_models_add_on_checkout_url200_response_instance = GetModelsAddOnCheckoutUrl200Response.from_json(json) +# print the JSON string representation of the object +print(GetModelsAddOnCheckoutUrl200Response.to_json()) + +# convert the object into a dict +get_models_add_on_checkout_url200_response_dict = get_models_add_on_checkout_url200_response_instance.to_dict() +# create an instance of GetModelsAddOnCheckoutUrl200Response from a dict +get_models_add_on_checkout_url200_response_from_dict = GetModelsAddOnCheckoutUrl200Response.from_dict(get_models_add_on_checkout_url200_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/GetModelsAddOnCheckoutUrl500Response.md b/packages/continue-sdk/python/api/docs/GetModelsAddOnCheckoutUrl500Response.md new file mode 100644 index 000000000..0bc34a0cc --- /dev/null +++ b/packages/continue-sdk/python/api/docs/GetModelsAddOnCheckoutUrl500Response.md @@ -0,0 +1,29 @@ +# GetModelsAddOnCheckoutUrl500Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **str** | | [optional] + +## Example + +```python +from openapi_client.models.get_models_add_on_checkout_url500_response import GetModelsAddOnCheckoutUrl500Response + +# TODO update the JSON string below +json = "{}" +# create an instance of GetModelsAddOnCheckoutUrl500Response from a JSON string +get_models_add_on_checkout_url500_response_instance = GetModelsAddOnCheckoutUrl500Response.from_json(json) +# print the JSON string representation of the object +print(GetModelsAddOnCheckoutUrl500Response.to_json()) + +# convert the object into a dict +get_models_add_on_checkout_url500_response_dict = get_models_add_on_checkout_url500_response_instance.to_dict() +# create an instance of GetModelsAddOnCheckoutUrl500Response from a dict +get_models_add_on_checkout_url500_response_from_dict = GetModelsAddOnCheckoutUrl500Response.from_dict(get_models_add_on_checkout_url500_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/GetPolicy200Response.md b/packages/continue-sdk/python/api/docs/GetPolicy200Response.md new file mode 100644 index 000000000..e5c81128c --- /dev/null +++ b/packages/continue-sdk/python/api/docs/GetPolicy200Response.md @@ -0,0 +1,30 @@ +# GetPolicy200Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**policy** | **object** | Organization policy configuration | [optional] +**org_slug** | **str** | Slug of the organization that has the policy | [optional] + +## Example + +```python +from openapi_client.models.get_policy200_response import GetPolicy200Response + +# TODO update the JSON string below +json = "{}" +# create an instance of GetPolicy200Response from a JSON string +get_policy200_response_instance = GetPolicy200Response.from_json(json) +# print the JSON string representation of the object +print(GetPolicy200Response.to_json()) + +# convert the object into a dict +get_policy200_response_dict = get_policy200_response_instance.to_dict() +# create an instance of GetPolicy200Response from a dict +get_policy200_response_from_dict = GetPolicy200Response.from_dict(get_policy200_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/ListAssistantFullSlugs429Response.md b/packages/continue-sdk/python/api/docs/ListAssistantFullSlugs429Response.md new file mode 100644 index 000000000..e8425b13f --- /dev/null +++ b/packages/continue-sdk/python/api/docs/ListAssistantFullSlugs429Response.md @@ -0,0 +1,29 @@ +# ListAssistantFullSlugs429Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **str** | | [optional] + +## Example + +```python +from openapi_client.models.list_assistant_full_slugs429_response import ListAssistantFullSlugs429Response + +# TODO update the JSON string below +json = "{}" +# create an instance of ListAssistantFullSlugs429Response from a JSON string +list_assistant_full_slugs429_response_instance = ListAssistantFullSlugs429Response.from_json(json) +# print the JSON string representation of the object +print(ListAssistantFullSlugs429Response.to_json()) + +# convert the object into a dict +list_assistant_full_slugs429_response_dict = list_assistant_full_slugs429_response_instance.to_dict() +# create an instance of ListAssistantFullSlugs429Response from a dict +list_assistant_full_slugs429_response_from_dict = ListAssistantFullSlugs429Response.from_dict(list_assistant_full_slugs429_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/ListAssistants200ResponseInner.md b/packages/continue-sdk/python/api/docs/ListAssistants200ResponseInner.md index 1fe63505b..f642b43c2 100644 --- a/packages/continue-sdk/python/api/docs/ListAssistants200ResponseInner.md +++ b/packages/continue-sdk/python/api/docs/ListAssistants200ResponseInner.md @@ -1,16 +1,17 @@ # ListAssistants200ResponseInner + ## Properties -| Name | Type | Description | Notes | -| --------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ---------- | -| **config_result** | [**ListAssistants200ResponseInnerConfigResult**](ListAssistants200ResponseInnerConfigResult.md) | | -| **owner_slug** | **str** | Slug of the user or organization that owns the assistant | -| **package_slug** | **str** | Slug of the assistant package | -| **icon_url** | **str** | Pre-signed URL for the assistant's icon | [optional] | -| **on_prem_proxy_url** | **str** | URL of the on-premises proxy if the organization uses one | [optional] | -| **use_on_prem_proxy** | **bool** | Whether the organization uses an on-premises proxy | [optional] | -| **raw_yaml** | **str** | Raw YAML configuration of the assistant | [optional] | +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**config_result** | [**ListAssistants200ResponseInnerConfigResult**](ListAssistants200ResponseInnerConfigResult.md) | | +**owner_slug** | **str** | Slug of the user or organization that owns the assistant | +**package_slug** | **str** | Slug of the assistant package | +**icon_url** | **str** | Pre-signed URL for the assistant's icon | [optional] +**on_prem_proxy_url** | **str** | URL of the on-premises proxy if the organization uses one | [optional] +**use_on_prem_proxy** | **bool** | Whether the organization uses an on-premises proxy | [optional] +**raw_yaml** | **str** | Raw YAML configuration of the assistant | [optional] ## Example @@ -29,5 +30,6 @@ list_assistants200_response_inner_dict = list_assistants200_response_inner_insta # create an instance of ListAssistants200ResponseInner from a dict list_assistants200_response_inner_from_dict = ListAssistants200ResponseInner.from_dict(list_assistants200_response_inner_dict) ``` - [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/ListAssistants200ResponseInnerConfigResult.md b/packages/continue-sdk/python/api/docs/ListAssistants200ResponseInnerConfigResult.md index e12781d04..bcee818dd 100644 --- a/packages/continue-sdk/python/api/docs/ListAssistants200ResponseInnerConfigResult.md +++ b/packages/continue-sdk/python/api/docs/ListAssistants200ResponseInnerConfigResult.md @@ -1,12 +1,13 @@ # ListAssistants200ResponseInnerConfigResult + ## Properties -| Name | Type | Description | Notes | -| --------------------------- | ------------- | ----------------------------------------------------- | ---------- | -| **config** | **object** | The unrolled assistant configuration | -| **config_load_interrupted** | **bool** | Whether the configuration loading was interrupted | -| **errors** | **List[str]** | Any errors that occurred during configuration loading | [optional] | +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**config** | **object** | The unrolled assistant configuration | +**config_load_interrupted** | **bool** | Whether the configuration loading was interrupted | +**errors** | **List[str]** | Any errors that occurred during configuration loading | [optional] ## Example @@ -25,5 +26,6 @@ list_assistants200_response_inner_config_result_dict = list_assistants200_respon # create an instance of ListAssistants200ResponseInnerConfigResult from a dict list_assistants200_response_inner_config_result_from_dict = ListAssistants200ResponseInnerConfigResult.from_dict(list_assistants200_response_inner_config_result_dict) ``` - [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/ListAssistants401Response.md b/packages/continue-sdk/python/api/docs/ListAssistants401Response.md index eb64e678d..f10de1a66 100644 --- a/packages/continue-sdk/python/api/docs/ListAssistants401Response.md +++ b/packages/continue-sdk/python/api/docs/ListAssistants401Response.md @@ -1,10 +1,11 @@ # ListAssistants401Response + ## Properties -| Name | Type | Description | Notes | -| ----------- | ------- | ----------- | ---------- | -| **message** | **str** | | [optional] | +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **str** | | [optional] ## Example @@ -23,5 +24,6 @@ list_assistants401_response_dict = list_assistants401_response_instance.to_dict( # create an instance of ListAssistants401Response from a dict list_assistants401_response_from_dict = ListAssistants401Response.from_dict(list_assistants401_response_dict) ``` - [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/ListAssistants404Response.md b/packages/continue-sdk/python/api/docs/ListAssistants404Response.md index a20b0f7b4..5752771ec 100644 --- a/packages/continue-sdk/python/api/docs/ListAssistants404Response.md +++ b/packages/continue-sdk/python/api/docs/ListAssistants404Response.md @@ -1,10 +1,11 @@ # ListAssistants404Response + ## Properties -| Name | Type | Description | Notes | -| ----------- | ------- | ----------- | ---------- | -| **message** | **str** | | [optional] | +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **str** | | [optional] ## Example @@ -23,5 +24,6 @@ list_assistants404_response_dict = list_assistants404_response_instance.to_dict( # create an instance of ListAssistants404Response from a dict list_assistants404_response_from_dict = ListAssistants404Response.from_dict(list_assistants404_response_dict) ``` - [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/ListOrganizations200Response.md b/packages/continue-sdk/python/api/docs/ListOrganizations200Response.md new file mode 100644 index 000000000..4f01cc94b --- /dev/null +++ b/packages/continue-sdk/python/api/docs/ListOrganizations200Response.md @@ -0,0 +1,29 @@ +# ListOrganizations200Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**organizations** | [**List[ListOrganizations200ResponseOrganizationsInner]**](ListOrganizations200ResponseOrganizationsInner.md) | | + +## Example + +```python +from openapi_client.models.list_organizations200_response import ListOrganizations200Response + +# TODO update the JSON string below +json = "{}" +# create an instance of ListOrganizations200Response from a JSON string +list_organizations200_response_instance = ListOrganizations200Response.from_json(json) +# print the JSON string representation of the object +print(ListOrganizations200Response.to_json()) + +# convert the object into a dict +list_organizations200_response_dict = list_organizations200_response_instance.to_dict() +# create an instance of ListOrganizations200Response from a dict +list_organizations200_response_from_dict = ListOrganizations200Response.from_dict(list_organizations200_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/ListOrganizations200ResponseOrganizationsInner.md b/packages/continue-sdk/python/api/docs/ListOrganizations200ResponseOrganizationsInner.md new file mode 100644 index 000000000..61b0338e7 --- /dev/null +++ b/packages/continue-sdk/python/api/docs/ListOrganizations200ResponseOrganizationsInner.md @@ -0,0 +1,32 @@ +# ListOrganizations200ResponseOrganizationsInner + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **str** | Organization ID | +**name** | **str** | Organization name | +**icon_url** | **str** | Pre-signed URL for the organization's icon | [optional] +**slug** | **str** | Organization slug | + +## Example + +```python +from openapi_client.models.list_organizations200_response_organizations_inner import ListOrganizations200ResponseOrganizationsInner + +# TODO update the JSON string below +json = "{}" +# create an instance of ListOrganizations200ResponseOrganizationsInner from a JSON string +list_organizations200_response_organizations_inner_instance = ListOrganizations200ResponseOrganizationsInner.from_json(json) +# print the JSON string representation of the object +print(ListOrganizations200ResponseOrganizationsInner.to_json()) + +# convert the object into a dict +list_organizations200_response_organizations_inner_dict = list_organizations200_response_organizations_inner_instance.to_dict() +# create an instance of ListOrganizations200ResponseOrganizationsInner from a dict +list_organizations200_response_organizations_inner_from_dict = ListOrganizations200ResponseOrganizationsInner.from_dict(list_organizations200_response_organizations_inner_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/docs/SyncSecretsRequest.md b/packages/continue-sdk/python/api/docs/SyncSecretsRequest.md new file mode 100644 index 000000000..863cf2477 --- /dev/null +++ b/packages/continue-sdk/python/api/docs/SyncSecretsRequest.md @@ -0,0 +1,31 @@ +# SyncSecretsRequest + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**fqsns** | **List[object]** | Array of Fully Qualified Secret Names to resolve | +**org_scope_id** | **str** | Organization ID to scope secret resolution to | [optional] +**org_scope_slug** | **str** | Organization slug to scope secret resolution to | [optional] + +## Example + +```python +from openapi_client.models.sync_secrets_request import SyncSecretsRequest + +# TODO update the JSON string below +json = "{}" +# create an instance of SyncSecretsRequest from a JSON string +sync_secrets_request_instance = SyncSecretsRequest.from_json(json) +# print the JSON string representation of the object +print(SyncSecretsRequest.to_json()) + +# convert the object into a dict +sync_secrets_request_dict = sync_secrets_request_instance.to_dict() +# create an instance of SyncSecretsRequest from a dict +sync_secrets_request_from_dict = SyncSecretsRequest.from_dict(sync_secrets_request_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/packages/continue-sdk/python/api/openapi_client/__init__.py b/packages/continue-sdk/python/api/openapi_client/__init__.py index c5b552747..e11cfb7eb 100644 --- a/packages/continue-sdk/python/api/openapi_client/__init__.py +++ b/packages/continue-sdk/python/api/openapi_client/__init__.py @@ -31,7 +31,18 @@ from openapi_client.exceptions import ApiAttributeError from openapi_client.exceptions import ApiException # import models into sdk package +from openapi_client.models.get_assistant200_response import GetAssistant200Response +from openapi_client.models.get_assistant403_response import GetAssistant403Response +from openapi_client.models.get_assistant404_response import GetAssistant404Response +from openapi_client.models.get_free_trial_status200_response import GetFreeTrialStatus200Response +from openapi_client.models.get_models_add_on_checkout_url200_response import GetModelsAddOnCheckoutUrl200Response +from openapi_client.models.get_models_add_on_checkout_url500_response import GetModelsAddOnCheckoutUrl500Response +from openapi_client.models.get_policy200_response import GetPolicy200Response +from openapi_client.models.list_assistant_full_slugs429_response import ListAssistantFullSlugs429Response from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner from openapi_client.models.list_assistants200_response_inner_config_result import ListAssistants200ResponseInnerConfigResult from openapi_client.models.list_assistants401_response import ListAssistants401Response from openapi_client.models.list_assistants404_response import ListAssistants404Response +from openapi_client.models.list_organizations200_response import ListOrganizations200Response +from openapi_client.models.list_organizations200_response_organizations_inner import ListOrganizations200ResponseOrganizationsInner +from openapi_client.models.sync_secrets_request import SyncSecretsRequest diff --git a/packages/continue-sdk/python/api/openapi_client/api/default_api.py b/packages/continue-sdk/python/api/openapi_client/api/default_api.py index cd1e05cdf..4e87fe17b 100644 --- a/packages/continue-sdk/python/api/openapi_client/api/default_api.py +++ b/packages/continue-sdk/python/api/openapi_client/api/default_api.py @@ -17,9 +17,15 @@ from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated from pydantic import Field, StrictStr, field_validator -from typing import List, Optional +from typing import Any, Dict, List, Optional from typing_extensions import Annotated +from openapi_client.models.get_assistant200_response import GetAssistant200Response +from openapi_client.models.get_free_trial_status200_response import GetFreeTrialStatus200Response +from openapi_client.models.get_models_add_on_checkout_url200_response import GetModelsAddOnCheckoutUrl200Response +from openapi_client.models.get_policy200_response import GetPolicy200Response from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner +from openapi_client.models.list_organizations200_response import ListOrganizations200Response +from openapi_client.models.sync_secrets_request import SyncSecretsRequest from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse @@ -39,6 +45,1355 @@ class DefaultApi: self.api_client = api_client + @validate_call + def get_assistant( + self, + owner_slug: Annotated[StrictStr, Field(description="Slug of the user or organization that owns the assistant")], + package_slug: Annotated[StrictStr, Field(description="Slug of the assistant package")], + always_use_proxy: Annotated[Optional[StrictStr], Field(description="Whether to always use the Continue-managed proxy for model requests")] = None, + organization_id: Annotated[Optional[StrictStr], Field(description="ID of the organization to scope assistants to. If not provided, personal assistants are returned.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> GetAssistant200Response: + """Get a specific assistant by slug + + Returns a single assistant configuration by its owner and package slug. This endpoint is useful when you need to retrieve or refresh a specific assistant without fetching the entire list. + + :param owner_slug: Slug of the user or organization that owns the assistant (required) + :type owner_slug: str + :param package_slug: Slug of the assistant package (required) + :type package_slug: str + :param always_use_proxy: Whether to always use the Continue-managed proxy for model requests + :type always_use_proxy: str + :param organization_id: ID of the organization to scope assistants to. If not provided, personal assistants are returned. + :type organization_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_assistant_serialize( + owner_slug=owner_slug, + package_slug=package_slug, + always_use_proxy=always_use_proxy, + organization_id=organization_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetAssistant200Response", + '401': "ListAssistants401Response", + '403': "GetAssistant403Response", + '404': "GetAssistant404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_assistant_with_http_info( + self, + owner_slug: Annotated[StrictStr, Field(description="Slug of the user or organization that owns the assistant")], + package_slug: Annotated[StrictStr, Field(description="Slug of the assistant package")], + always_use_proxy: Annotated[Optional[StrictStr], Field(description="Whether to always use the Continue-managed proxy for model requests")] = None, + organization_id: Annotated[Optional[StrictStr], Field(description="ID of the organization to scope assistants to. If not provided, personal assistants are returned.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[GetAssistant200Response]: + """Get a specific assistant by slug + + Returns a single assistant configuration by its owner and package slug. This endpoint is useful when you need to retrieve or refresh a specific assistant without fetching the entire list. + + :param owner_slug: Slug of the user or organization that owns the assistant (required) + :type owner_slug: str + :param package_slug: Slug of the assistant package (required) + :type package_slug: str + :param always_use_proxy: Whether to always use the Continue-managed proxy for model requests + :type always_use_proxy: str + :param organization_id: ID of the organization to scope assistants to. If not provided, personal assistants are returned. + :type organization_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_assistant_serialize( + owner_slug=owner_slug, + package_slug=package_slug, + always_use_proxy=always_use_proxy, + organization_id=organization_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetAssistant200Response", + '401': "ListAssistants401Response", + '403': "GetAssistant403Response", + '404': "GetAssistant404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_assistant_without_preload_content( + self, + owner_slug: Annotated[StrictStr, Field(description="Slug of the user or organization that owns the assistant")], + package_slug: Annotated[StrictStr, Field(description="Slug of the assistant package")], + always_use_proxy: Annotated[Optional[StrictStr], Field(description="Whether to always use the Continue-managed proxy for model requests")] = None, + organization_id: Annotated[Optional[StrictStr], Field(description="ID of the organization to scope assistants to. If not provided, personal assistants are returned.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a specific assistant by slug + + Returns a single assistant configuration by its owner and package slug. This endpoint is useful when you need to retrieve or refresh a specific assistant without fetching the entire list. + + :param owner_slug: Slug of the user or organization that owns the assistant (required) + :type owner_slug: str + :param package_slug: Slug of the assistant package (required) + :type package_slug: str + :param always_use_proxy: Whether to always use the Continue-managed proxy for model requests + :type always_use_proxy: str + :param organization_id: ID of the organization to scope assistants to. If not provided, personal assistants are returned. + :type organization_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_assistant_serialize( + owner_slug=owner_slug, + package_slug=package_slug, + always_use_proxy=always_use_proxy, + organization_id=organization_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetAssistant200Response", + '401': "ListAssistants401Response", + '403': "GetAssistant403Response", + '404': "GetAssistant404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_assistant_serialize( + self, + owner_slug, + package_slug, + always_use_proxy, + organization_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if owner_slug is not None: + _path_params['ownerSlug'] = owner_slug + if package_slug is not None: + _path_params['packageSlug'] = package_slug + # process the query parameters + if always_use_proxy is not None: + + _query_params.append(('alwaysUseProxy', always_use_proxy)) + + if organization_id is not None: + + _query_params.append(('organizationId', organization_id)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/ide/get-assistant/{ownerSlug}/{packageSlug}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_free_trial_status( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> GetFreeTrialStatus200Response: + """Get free trial status for user + + Returns the current free trial status for the authenticated user, including usage counts and limits for chat and autocomplete features. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_free_trial_status_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetFreeTrialStatus200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_free_trial_status_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[GetFreeTrialStatus200Response]: + """Get free trial status for user + + Returns the current free trial status for the authenticated user, including usage counts and limits for chat and autocomplete features. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_free_trial_status_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetFreeTrialStatus200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_free_trial_status_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get free trial status for user + + Returns the current free trial status for the authenticated user, including usage counts and limits for chat and autocomplete features. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_free_trial_status_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetFreeTrialStatus200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_free_trial_status_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/ide/free-trial-status', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_models_add_on_checkout_url( + self, + profile_id: Annotated[Optional[StrictStr], Field(description="Profile ID to include in the callback URL")] = None, + vscode_uri_scheme: Annotated[Optional[StrictStr], Field(description="VS Code URI scheme to include in the callback URL")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> GetModelsAddOnCheckoutUrl200Response: + """Get Stripe checkout URL for models add-on + + Creates a Stripe checkout session for the models add-on subscription and returns the checkout URL. + + :param profile_id: Profile ID to include in the callback URL + :type profile_id: str + :param vscode_uri_scheme: VS Code URI scheme to include in the callback URL + :type vscode_uri_scheme: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_models_add_on_checkout_url_serialize( + profile_id=profile_id, + vscode_uri_scheme=vscode_uri_scheme, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetModelsAddOnCheckoutUrl200Response", + '404': "ListAssistants404Response", + '500': "GetModelsAddOnCheckoutUrl500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_models_add_on_checkout_url_with_http_info( + self, + profile_id: Annotated[Optional[StrictStr], Field(description="Profile ID to include in the callback URL")] = None, + vscode_uri_scheme: Annotated[Optional[StrictStr], Field(description="VS Code URI scheme to include in the callback URL")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[GetModelsAddOnCheckoutUrl200Response]: + """Get Stripe checkout URL for models add-on + + Creates a Stripe checkout session for the models add-on subscription and returns the checkout URL. + + :param profile_id: Profile ID to include in the callback URL + :type profile_id: str + :param vscode_uri_scheme: VS Code URI scheme to include in the callback URL + :type vscode_uri_scheme: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_models_add_on_checkout_url_serialize( + profile_id=profile_id, + vscode_uri_scheme=vscode_uri_scheme, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetModelsAddOnCheckoutUrl200Response", + '404': "ListAssistants404Response", + '500': "GetModelsAddOnCheckoutUrl500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_models_add_on_checkout_url_without_preload_content( + self, + profile_id: Annotated[Optional[StrictStr], Field(description="Profile ID to include in the callback URL")] = None, + vscode_uri_scheme: Annotated[Optional[StrictStr], Field(description="VS Code URI scheme to include in the callback URL")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get Stripe checkout URL for models add-on + + Creates a Stripe checkout session for the models add-on subscription and returns the checkout URL. + + :param profile_id: Profile ID to include in the callback URL + :type profile_id: str + :param vscode_uri_scheme: VS Code URI scheme to include in the callback URL + :type vscode_uri_scheme: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_models_add_on_checkout_url_serialize( + profile_id=profile_id, + vscode_uri_scheme=vscode_uri_scheme, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetModelsAddOnCheckoutUrl200Response", + '404': "ListAssistants404Response", + '500': "GetModelsAddOnCheckoutUrl500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_models_add_on_checkout_url_serialize( + self, + profile_id, + vscode_uri_scheme, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if profile_id is not None: + + _query_params.append(('profile_id', profile_id)) + + if vscode_uri_scheme is not None: + + _query_params.append(('vscode_uri_scheme', vscode_uri_scheme)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/ide/get-models-add-on-checkout-url', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_policy( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> GetPolicy200Response: + """Get organization policy + + Returns the policy configuration for the first organization that the user belongs to which has a policy configured. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_policy_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetPolicy200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_policy_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[GetPolicy200Response]: + """Get organization policy + + Returns the policy configuration for the first organization that the user belongs to which has a policy configured. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_policy_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetPolicy200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_policy_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get organization policy + + Returns the policy configuration for the first organization that the user belongs to which has a policy configured. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_policy_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetPolicy200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_policy_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/ide/policy', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def list_assistant_full_slugs( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """List assistant full slugs (currently returns 429) + + This endpoint is temporarily disabled and returns a 429 status code to prevent constant refreshes of the full assistant list until a fixed client version can be deployed. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_assistant_full_slugs_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '429': "ListAssistantFullSlugs429Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def list_assistant_full_slugs_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """List assistant full slugs (currently returns 429) + + This endpoint is temporarily disabled and returns a 429 status code to prevent constant refreshes of the full assistant list until a fixed client version can be deployed. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_assistant_full_slugs_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '429': "ListAssistantFullSlugs429Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def list_assistant_full_slugs_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List assistant full slugs (currently returns 429) + + This endpoint is temporarily disabled and returns a 429 status code to prevent constant refreshes of the full assistant list until a fixed client version can be deployed. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_assistant_full_slugs_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '429': "ListAssistantFullSlugs429Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_assistant_full_slugs_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/ide/list-assistant-full-slugs', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + @validate_call def list_assistants( self, @@ -323,3 +1678,529 @@ class DefaultApi: ) + + + @validate_call + def list_organizations( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ListOrganizations200Response: + """List organizations for user + + Returns a list of organizations that the authenticated user belongs to, including organization metadata and pre-signed icon URLs. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_organizations_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListOrganizations200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def list_organizations_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ListOrganizations200Response]: + """List organizations for user + + Returns a list of organizations that the authenticated user belongs to, including organization metadata and pre-signed icon URLs. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_organizations_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListOrganizations200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def list_organizations_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List organizations for user + + Returns a list of organizations that the authenticated user belongs to, including organization metadata and pre-signed icon URLs. + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._list_organizations_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ListOrganizations200Response", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _list_organizations_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/ide/list-organizations', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def sync_secrets( + self, + sync_secrets_request: SyncSecretsRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Optional[object]]: + """Synchronize secrets for user + + Resolves and synchronizes secrets for the authenticated user based on the provided Fully Qualified Secret Names (FQSNs). + + :param sync_secrets_request: (required) + :type sync_secrets_request: SyncSecretsRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._sync_secrets_serialize( + sync_secrets_request=sync_secrets_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Optional[object]]", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def sync_secrets_with_http_info( + self, + sync_secrets_request: SyncSecretsRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Optional[object]]]: + """Synchronize secrets for user + + Resolves and synchronizes secrets for the authenticated user based on the provided Fully Qualified Secret Names (FQSNs). + + :param sync_secrets_request: (required) + :type sync_secrets_request: SyncSecretsRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._sync_secrets_serialize( + sync_secrets_request=sync_secrets_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Optional[object]]", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def sync_secrets_without_preload_content( + self, + sync_secrets_request: SyncSecretsRequest, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Synchronize secrets for user + + Resolves and synchronizes secrets for the authenticated user based on the provided Fully Qualified Secret Names (FQSNs). + + :param sync_secrets_request: (required) + :type sync_secrets_request: SyncSecretsRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._sync_secrets_serialize( + sync_secrets_request=sync_secrets_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Optional[object]]", + '404': "ListAssistants404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _sync_secrets_serialize( + self, + sync_secrets_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if sync_secrets_request is not None: + _body_params = sync_secrets_request + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'apiKeyAuth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/ide/sync-secrets', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/__init__.py b/packages/continue-sdk/python/api/openapi_client/models/__init__.py index a26380850..4cee1e67b 100644 --- a/packages/continue-sdk/python/api/openapi_client/models/__init__.py +++ b/packages/continue-sdk/python/api/openapi_client/models/__init__.py @@ -14,7 +14,18 @@ # import models into model package +from openapi_client.models.get_assistant200_response import GetAssistant200Response +from openapi_client.models.get_assistant403_response import GetAssistant403Response +from openapi_client.models.get_assistant404_response import GetAssistant404Response +from openapi_client.models.get_free_trial_status200_response import GetFreeTrialStatus200Response +from openapi_client.models.get_models_add_on_checkout_url200_response import GetModelsAddOnCheckoutUrl200Response +from openapi_client.models.get_models_add_on_checkout_url500_response import GetModelsAddOnCheckoutUrl500Response +from openapi_client.models.get_policy200_response import GetPolicy200Response +from openapi_client.models.list_assistant_full_slugs429_response import ListAssistantFullSlugs429Response from openapi_client.models.list_assistants200_response_inner import ListAssistants200ResponseInner from openapi_client.models.list_assistants200_response_inner_config_result import ListAssistants200ResponseInnerConfigResult from openapi_client.models.list_assistants401_response import ListAssistants401Response from openapi_client.models.list_assistants404_response import ListAssistants404Response +from openapi_client.models.list_organizations200_response import ListOrganizations200Response +from openapi_client.models.list_organizations200_response_organizations_inner import ListOrganizations200ResponseOrganizationsInner +from openapi_client.models.sync_secrets_request import SyncSecretsRequest diff --git a/packages/continue-sdk/python/api/openapi_client/models/get_assistant200_response.py b/packages/continue-sdk/python/api/openapi_client/models/get_assistant200_response.py new file mode 100644 index 000000000..10a3b1392 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/get_assistant200_response.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from openapi_client.models.list_assistants200_response_inner_config_result import ListAssistants200ResponseInnerConfigResult +from typing import Optional, Set +from typing_extensions import Self + +class GetAssistant200Response(BaseModel): + """ + GetAssistant200Response + """ # noqa: E501 + config_result: ListAssistants200ResponseInnerConfigResult = Field(alias="configResult") + owner_slug: StrictStr = Field(description="Slug of the user or organization that owns the assistant", alias="ownerSlug") + package_slug: StrictStr = Field(description="Slug of the assistant package", alias="packageSlug") + icon_url: Optional[StrictStr] = Field(default=None, description="Pre-signed URL for the assistant's icon", alias="iconUrl") + on_prem_proxy_url: Optional[StrictStr] = Field(default=None, description="URL of the on-premises proxy if the organization uses one", alias="onPremProxyUrl") + use_on_prem_proxy: Optional[StrictBool] = Field(default=None, description="Whether the organization uses an on-premises proxy", alias="useOnPremProxy") + raw_yaml: Optional[StrictStr] = Field(default=None, description="Raw YAML configuration of the assistant", alias="rawYaml") + __properties: ClassVar[List[str]] = ["configResult", "ownerSlug", "packageSlug", "iconUrl", "onPremProxyUrl", "useOnPremProxy", "rawYaml"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetAssistant200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of config_result + if self.config_result: + _dict['configResult'] = self.config_result.to_dict() + # set to None if icon_url (nullable) is None + # and model_fields_set contains the field + if self.icon_url is None and "icon_url" in self.model_fields_set: + _dict['iconUrl'] = None + + # set to None if on_prem_proxy_url (nullable) is None + # and model_fields_set contains the field + if self.on_prem_proxy_url is None and "on_prem_proxy_url" in self.model_fields_set: + _dict['onPremProxyUrl'] = None + + # set to None if use_on_prem_proxy (nullable) is None + # and model_fields_set contains the field + if self.use_on_prem_proxy is None and "use_on_prem_proxy" in self.model_fields_set: + _dict['useOnPremProxy'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetAssistant200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "configResult": ListAssistants200ResponseInnerConfigResult.from_dict(obj["configResult"]) if obj.get("configResult") is not None else None, + "ownerSlug": obj.get("ownerSlug"), + "packageSlug": obj.get("packageSlug"), + "iconUrl": obj.get("iconUrl"), + "onPremProxyUrl": obj.get("onPremProxyUrl"), + "useOnPremProxy": obj.get("useOnPremProxy"), + "rawYaml": obj.get("rawYaml") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/get_assistant403_response.py b/packages/continue-sdk/python/api/openapi_client/models/get_assistant403_response.py new file mode 100644 index 000000000..55de4c291 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/get_assistant403_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class GetAssistant403Response(BaseModel): + """ + GetAssistant403Response + """ # noqa: E501 + message: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["message"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetAssistant403Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetAssistant403Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "message": obj.get("message") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/get_assistant404_response.py b/packages/continue-sdk/python/api/openapi_client/models/get_assistant404_response.py new file mode 100644 index 000000000..769319660 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/get_assistant404_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class GetAssistant404Response(BaseModel): + """ + GetAssistant404Response + """ # noqa: E501 + message: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["message"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetAssistant404Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetAssistant404Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "message": obj.get("message") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/get_free_trial_status200_response.py b/packages/continue-sdk/python/api/openapi_client/models/get_free_trial_status200_response.py new file mode 100644 index 000000000..f7e832668 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/get_free_trial_status200_response.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self + +class GetFreeTrialStatus200Response(BaseModel): + """ + GetFreeTrialStatus200Response + """ # noqa: E501 + opted_in_to_free_trial: StrictBool = Field(description="Whether the user has opted into the free trial", alias="optedInToFreeTrial") + chat_count: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Current number of chat messages used", alias="chatCount") + autocomplete_count: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Current number of autocomplete requests used", alias="autocompleteCount") + chat_limit: Union[StrictFloat, StrictInt] = Field(description="Maximum number of chat messages allowed in free trial", alias="chatLimit") + autocomplete_limit: Union[StrictFloat, StrictInt] = Field(description="Maximum number of autocomplete requests allowed in free trial", alias="autocompleteLimit") + __properties: ClassVar[List[str]] = ["optedInToFreeTrial", "chatCount", "autocompleteCount", "chatLimit", "autocompleteLimit"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetFreeTrialStatus200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if chat_count (nullable) is None + # and model_fields_set contains the field + if self.chat_count is None and "chat_count" in self.model_fields_set: + _dict['chatCount'] = None + + # set to None if autocomplete_count (nullable) is None + # and model_fields_set contains the field + if self.autocomplete_count is None and "autocomplete_count" in self.model_fields_set: + _dict['autocompleteCount'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetFreeTrialStatus200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "optedInToFreeTrial": obj.get("optedInToFreeTrial"), + "chatCount": obj.get("chatCount"), + "autocompleteCount": obj.get("autocompleteCount"), + "chatLimit": obj.get("chatLimit"), + "autocompleteLimit": obj.get("autocompleteLimit") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/get_models_add_on_checkout_url200_response.py b/packages/continue-sdk/python/api/openapi_client/models/get_models_add_on_checkout_url200_response.py new file mode 100644 index 000000000..db8dae468 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/get_models_add_on_checkout_url200_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class GetModelsAddOnCheckoutUrl200Response(BaseModel): + """ + GetModelsAddOnCheckoutUrl200Response + """ # noqa: E501 + url: StrictStr = Field(description="Stripe checkout session URL") + __properties: ClassVar[List[str]] = ["url"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetModelsAddOnCheckoutUrl200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetModelsAddOnCheckoutUrl200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "url": obj.get("url") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/get_models_add_on_checkout_url500_response.py b/packages/continue-sdk/python/api/openapi_client/models/get_models_add_on_checkout_url500_response.py new file mode 100644 index 000000000..fd408b4e9 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/get_models_add_on_checkout_url500_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class GetModelsAddOnCheckoutUrl500Response(BaseModel): + """ + GetModelsAddOnCheckoutUrl500Response + """ # noqa: E501 + message: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["message"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetModelsAddOnCheckoutUrl500Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetModelsAddOnCheckoutUrl500Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "message": obj.get("message") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/get_policy200_response.py b/packages/continue-sdk/python/api/openapi_client/models/get_policy200_response.py new file mode 100644 index 000000000..77bd82dbd --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/get_policy200_response.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class GetPolicy200Response(BaseModel): + """ + GetPolicy200Response + """ # noqa: E501 + policy: Optional[Dict[str, Any]] = Field(default=None, description="Organization policy configuration") + org_slug: Optional[StrictStr] = Field(default=None, description="Slug of the organization that has the policy", alias="orgSlug") + __properties: ClassVar[List[str]] = ["policy", "orgSlug"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetPolicy200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if policy (nullable) is None + # and model_fields_set contains the field + if self.policy is None and "policy" in self.model_fields_set: + _dict['policy'] = None + + # set to None if org_slug (nullable) is None + # and model_fields_set contains the field + if self.org_slug is None and "org_slug" in self.model_fields_set: + _dict['orgSlug'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetPolicy200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "policy": obj.get("policy"), + "orgSlug": obj.get("orgSlug") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/list_assistant_full_slugs429_response.py b/packages/continue-sdk/python/api/openapi_client/models/list_assistant_full_slugs429_response.py new file mode 100644 index 000000000..58bc80b77 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/list_assistant_full_slugs429_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ListAssistantFullSlugs429Response(BaseModel): + """ + ListAssistantFullSlugs429Response + """ # noqa: E501 + message: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["message"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListAssistantFullSlugs429Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListAssistantFullSlugs429Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "message": obj.get("message") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/list_organizations200_response.py b/packages/continue-sdk/python/api/openapi_client/models/list_organizations200_response.py new file mode 100644 index 000000000..077694169 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/list_organizations200_response.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List +from openapi_client.models.list_organizations200_response_organizations_inner import ListOrganizations200ResponseOrganizationsInner +from typing import Optional, Set +from typing_extensions import Self + +class ListOrganizations200Response(BaseModel): + """ + ListOrganizations200Response + """ # noqa: E501 + organizations: List[ListOrganizations200ResponseOrganizationsInner] + __properties: ClassVar[List[str]] = ["organizations"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListOrganizations200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in organizations (list) + _items = [] + if self.organizations: + for _item_organizations in self.organizations: + if _item_organizations: + _items.append(_item_organizations.to_dict()) + _dict['organizations'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListOrganizations200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "organizations": [ListOrganizations200ResponseOrganizationsInner.from_dict(_item) for _item in obj["organizations"]] if obj.get("organizations") is not None else None + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/list_organizations200_response_organizations_inner.py b/packages/continue-sdk/python/api/openapi_client/models/list_organizations200_response_organizations_inner.py new file mode 100644 index 000000000..b252db0c1 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/list_organizations200_response_organizations_inner.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ListOrganizations200ResponseOrganizationsInner(BaseModel): + """ + ListOrganizations200ResponseOrganizationsInner + """ # noqa: E501 + id: StrictStr = Field(description="Organization ID") + name: StrictStr = Field(description="Organization name") + icon_url: Optional[StrictStr] = Field(default=None, description="Pre-signed URL for the organization's icon", alias="iconUrl") + slug: StrictStr = Field(description="Organization slug") + __properties: ClassVar[List[str]] = ["id", "name", "iconUrl", "slug"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ListOrganizations200ResponseOrganizationsInner from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if icon_url (nullable) is None + # and model_fields_set contains the field + if self.icon_url is None and "icon_url" in self.model_fields_set: + _dict['iconUrl'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ListOrganizations200ResponseOrganizationsInner from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "iconUrl": obj.get("iconUrl"), + "slug": obj.get("slug") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/openapi_client/models/sync_secrets_request.py b/packages/continue-sdk/python/api/openapi_client/models/sync_secrets_request.py new file mode 100644 index 000000000..d9fa54226 --- /dev/null +++ b/packages/continue-sdk/python/api/openapi_client/models/sync_secrets_request.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class SyncSecretsRequest(BaseModel): + """ + SyncSecretsRequest + """ # noqa: E501 + fqsns: List[Dict[str, Any]] = Field(description="Array of Fully Qualified Secret Names to resolve") + org_scope_id: Optional[StrictStr] = Field(default=None, description="Organization ID to scope secret resolution to", alias="orgScopeId") + org_scope_slug: Optional[StrictStr] = Field(default=None, description="Organization slug to scope secret resolution to", alias="orgScopeSlug") + __properties: ClassVar[List[str]] = ["fqsns", "orgScopeId", "orgScopeSlug"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SyncSecretsRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if org_scope_id (nullable) is None + # and model_fields_set contains the field + if self.org_scope_id is None and "org_scope_id" in self.model_fields_set: + _dict['orgScopeId'] = None + + # set to None if org_scope_slug (nullable) is None + # and model_fields_set contains the field + if self.org_scope_slug is None and "org_scope_slug" in self.model_fields_set: + _dict['orgScopeSlug'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SyncSecretsRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fqsns": obj.get("fqsns"), + "orgScopeId": obj.get("orgScopeId"), + "orgScopeSlug": obj.get("orgScopeSlug") + }) + return _obj + + diff --git a/packages/continue-sdk/python/api/test/test_get_assistant200_response.py b/packages/continue-sdk/python/api/test/test_get_assistant200_response.py new file mode 100644 index 000000000..78025e2e1 --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_get_assistant200_response.py @@ -0,0 +1,70 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.get_assistant200_response import GetAssistant200Response + +class TestGetAssistant200Response(unittest.TestCase): + """GetAssistant200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> GetAssistant200Response: + """Test GetAssistant200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `GetAssistant200Response` + """ + model = GetAssistant200Response() + if include_optional: + return GetAssistant200Response( + config_result = openapi_client.models.list_assistants_200_response_inner_config_result.listAssistants_200_response_inner_configResult( + config = openapi_client.models.config.config(), + config_load_interrupted = True, + errors = [ + '' + ], ), + owner_slug = '', + package_slug = '', + icon_url = '', + on_prem_proxy_url = '', + use_on_prem_proxy = True, + raw_yaml = '' + ) + else: + return GetAssistant200Response( + config_result = openapi_client.models.list_assistants_200_response_inner_config_result.listAssistants_200_response_inner_configResult( + config = openapi_client.models.config.config(), + config_load_interrupted = True, + errors = [ + '' + ], ), + owner_slug = '', + package_slug = '', + ) + """ + + def testGetAssistant200Response(self): + """Test GetAssistant200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_get_assistant403_response.py b/packages/continue-sdk/python/api/test/test_get_assistant403_response.py new file mode 100644 index 000000000..370685042 --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_get_assistant403_response.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.get_assistant403_response import GetAssistant403Response + +class TestGetAssistant403Response(unittest.TestCase): + """GetAssistant403Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> GetAssistant403Response: + """Test GetAssistant403Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `GetAssistant403Response` + """ + model = GetAssistant403Response() + if include_optional: + return GetAssistant403Response( + message = 'This assistant is not allowed in this organization' + ) + else: + return GetAssistant403Response( + ) + """ + + def testGetAssistant403Response(self): + """Test GetAssistant403Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_get_assistant404_response.py b/packages/continue-sdk/python/api/test/test_get_assistant404_response.py new file mode 100644 index 000000000..2b0c20477 --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_get_assistant404_response.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.get_assistant404_response import GetAssistant404Response + +class TestGetAssistant404Response(unittest.TestCase): + """GetAssistant404Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> GetAssistant404Response: + """Test GetAssistant404Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `GetAssistant404Response` + """ + model = GetAssistant404Response() + if include_optional: + return GetAssistant404Response( + message = 'Assistant not found' + ) + else: + return GetAssistant404Response( + ) + """ + + def testGetAssistant404Response(self): + """Test GetAssistant404Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_get_free_trial_status200_response.py b/packages/continue-sdk/python/api/test/test_get_free_trial_status200_response.py new file mode 100644 index 000000000..172e40b5c --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_get_free_trial_status200_response.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.get_free_trial_status200_response import GetFreeTrialStatus200Response + +class TestGetFreeTrialStatus200Response(unittest.TestCase): + """GetFreeTrialStatus200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> GetFreeTrialStatus200Response: + """Test GetFreeTrialStatus200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `GetFreeTrialStatus200Response` + """ + model = GetFreeTrialStatus200Response() + if include_optional: + return GetFreeTrialStatus200Response( + opted_in_to_free_trial = True, + chat_count = 1.337, + autocomplete_count = 1.337, + chat_limit = 1.337, + autocomplete_limit = 1.337 + ) + else: + return GetFreeTrialStatus200Response( + opted_in_to_free_trial = True, + chat_limit = 1.337, + autocomplete_limit = 1.337, + ) + """ + + def testGetFreeTrialStatus200Response(self): + """Test GetFreeTrialStatus200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_get_models_add_on_checkout_url200_response.py b/packages/continue-sdk/python/api/test/test_get_models_add_on_checkout_url200_response.py new file mode 100644 index 000000000..17a102e77 --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_get_models_add_on_checkout_url200_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.get_models_add_on_checkout_url200_response import GetModelsAddOnCheckoutUrl200Response + +class TestGetModelsAddOnCheckoutUrl200Response(unittest.TestCase): + """GetModelsAddOnCheckoutUrl200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> GetModelsAddOnCheckoutUrl200Response: + """Test GetModelsAddOnCheckoutUrl200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `GetModelsAddOnCheckoutUrl200Response` + """ + model = GetModelsAddOnCheckoutUrl200Response() + if include_optional: + return GetModelsAddOnCheckoutUrl200Response( + url = '' + ) + else: + return GetModelsAddOnCheckoutUrl200Response( + url = '', + ) + """ + + def testGetModelsAddOnCheckoutUrl200Response(self): + """Test GetModelsAddOnCheckoutUrl200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_get_models_add_on_checkout_url500_response.py b/packages/continue-sdk/python/api/test/test_get_models_add_on_checkout_url500_response.py new file mode 100644 index 000000000..1f665deb8 --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_get_models_add_on_checkout_url500_response.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.get_models_add_on_checkout_url500_response import GetModelsAddOnCheckoutUrl500Response + +class TestGetModelsAddOnCheckoutUrl500Response(unittest.TestCase): + """GetModelsAddOnCheckoutUrl500Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> GetModelsAddOnCheckoutUrl500Response: + """Test GetModelsAddOnCheckoutUrl500Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `GetModelsAddOnCheckoutUrl500Response` + """ + model = GetModelsAddOnCheckoutUrl500Response() + if include_optional: + return GetModelsAddOnCheckoutUrl500Response( + message = 'Failed to create checkout session' + ) + else: + return GetModelsAddOnCheckoutUrl500Response( + ) + """ + + def testGetModelsAddOnCheckoutUrl500Response(self): + """Test GetModelsAddOnCheckoutUrl500Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_get_policy200_response.py b/packages/continue-sdk/python/api/test/test_get_policy200_response.py new file mode 100644 index 000000000..9a5c30e97 --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_get_policy200_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.get_policy200_response import GetPolicy200Response + +class TestGetPolicy200Response(unittest.TestCase): + """GetPolicy200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> GetPolicy200Response: + """Test GetPolicy200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `GetPolicy200Response` + """ + model = GetPolicy200Response() + if include_optional: + return GetPolicy200Response( + policy = None, + org_slug = '' + ) + else: + return GetPolicy200Response( + ) + """ + + def testGetPolicy200Response(self): + """Test GetPolicy200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_list_assistant_full_slugs429_response.py b/packages/continue-sdk/python/api/test/test_list_assistant_full_slugs429_response.py new file mode 100644 index 000000000..2226cd3eb --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_list_assistant_full_slugs429_response.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.list_assistant_full_slugs429_response import ListAssistantFullSlugs429Response + +class TestListAssistantFullSlugs429Response(unittest.TestCase): + """ListAssistantFullSlugs429Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListAssistantFullSlugs429Response: + """Test ListAssistantFullSlugs429Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListAssistantFullSlugs429Response` + """ + model = ListAssistantFullSlugs429Response() + if include_optional: + return ListAssistantFullSlugs429Response( + message = 'Too many requests' + ) + else: + return ListAssistantFullSlugs429Response( + ) + """ + + def testListAssistantFullSlugs429Response(self): + """Test ListAssistantFullSlugs429Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_list_organizations200_response.py b/packages/continue-sdk/python/api/test/test_list_organizations200_response.py new file mode 100644 index 000000000..f7c9a68a8 --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_list_organizations200_response.py @@ -0,0 +1,64 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.list_organizations200_response import ListOrganizations200Response + +class TestListOrganizations200Response(unittest.TestCase): + """ListOrganizations200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListOrganizations200Response: + """Test ListOrganizations200Response + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListOrganizations200Response` + """ + model = ListOrganizations200Response() + if include_optional: + return ListOrganizations200Response( + organizations = [ + openapi_client.models.list_organizations_200_response_organizations_inner.listOrganizations_200_response_organizations_inner( + id = '', + name = '', + icon_url = '', + slug = '', ) + ] + ) + else: + return ListOrganizations200Response( + organizations = [ + openapi_client.models.list_organizations_200_response_organizations_inner.listOrganizations_200_response_organizations_inner( + id = '', + name = '', + icon_url = '', + slug = '', ) + ], + ) + """ + + def testListOrganizations200Response(self): + """Test ListOrganizations200Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_list_organizations200_response_organizations_inner.py b/packages/continue-sdk/python/api/test/test_list_organizations200_response_organizations_inner.py new file mode 100644 index 000000000..7986b752f --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_list_organizations200_response_organizations_inner.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.list_organizations200_response_organizations_inner import ListOrganizations200ResponseOrganizationsInner + +class TestListOrganizations200ResponseOrganizationsInner(unittest.TestCase): + """ListOrganizations200ResponseOrganizationsInner unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ListOrganizations200ResponseOrganizationsInner: + """Test ListOrganizations200ResponseOrganizationsInner + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ListOrganizations200ResponseOrganizationsInner` + """ + model = ListOrganizations200ResponseOrganizationsInner() + if include_optional: + return ListOrganizations200ResponseOrganizationsInner( + id = '', + name = '', + icon_url = '', + slug = '' + ) + else: + return ListOrganizations200ResponseOrganizationsInner( + id = '', + name = '', + slug = '', + ) + """ + + def testListOrganizations200ResponseOrganizationsInner(self): + """Test ListOrganizations200ResponseOrganizationsInner""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/python/api/test/test_sync_secrets_request.py b/packages/continue-sdk/python/api/test/test_sync_secrets_request.py new file mode 100644 index 000000000..94c33700f --- /dev/null +++ b/packages/continue-sdk/python/api/test/test_sync_secrets_request.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + Continue Hub IDE API + + API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from openapi_client.models.sync_secrets_request import SyncSecretsRequest + +class TestSyncSecretsRequest(unittest.TestCase): + """SyncSecretsRequest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> SyncSecretsRequest: + """Test SyncSecretsRequest + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `SyncSecretsRequest` + """ + model = SyncSecretsRequest() + if include_optional: + return SyncSecretsRequest( + fqsns = [ + None + ], + org_scope_id = '', + org_scope_slug = '' + ) + else: + return SyncSecretsRequest( + fqsns = [ + None + ], + ) + """ + + def testSyncSecretsRequest(self): + """Test SyncSecretsRequest""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/packages/continue-sdk/typescript/api/.openapi-generator/FILES b/packages/continue-sdk/typescript/api/.openapi-generator/FILES index bd16b13fc..5784df41b 100644 --- a/packages/continue-sdk/typescript/api/.openapi-generator/FILES +++ b/packages/continue-sdk/typescript/api/.openapi-generator/FILES @@ -5,10 +5,21 @@ package.json src/apis/DefaultApi.ts src/apis/index.ts src/index.ts +src/models/GetAssistant200Response.ts +src/models/GetAssistant403Response.ts +src/models/GetAssistant404Response.ts +src/models/GetFreeTrialStatus200Response.ts +src/models/GetModelsAddOnCheckoutUrl200Response.ts +src/models/GetModelsAddOnCheckoutUrl500Response.ts +src/models/GetPolicy200Response.ts +src/models/ListAssistantFullSlugs429Response.ts src/models/ListAssistants200ResponseInner.ts src/models/ListAssistants200ResponseInnerConfigResult.ts src/models/ListAssistants401Response.ts src/models/ListAssistants404Response.ts +src/models/ListOrganizations200Response.ts +src/models/ListOrganizations200ResponseOrganizationsInner.ts +src/models/SyncSecretsRequest.ts src/models/index.ts src/runtime.ts tsconfig.esm.json diff --git a/packages/continue-sdk/typescript/api/README.md b/packages/continue-sdk/typescript/api/README.md index fd744e00b..ed367262b 100644 --- a/packages/continue-sdk/typescript/api/README.md +++ b/packages/continue-sdk/typescript/api/README.md @@ -3,27 +3,23 @@ This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: Environment - -- Node.js -- Webpack -- Browserify +* Node.js +* Webpack +* Browserify Language level - -- ES5 - you must have a Promises/A+ library installed -- ES6 +* ES5 - you must have a Promises/A+ library installed +* ES6 Module system - -- CommonJS -- ES6 module system +* CommonJS +* ES6 module system It can be used in both TypeScript and JavaScript. In TypeScript, the definition will be automatically resolved via `package.json`. ([Reference](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html)) ### Building To build and compile the typescript sources to javascript use: - ``` npm install npm run build diff --git a/packages/continue-sdk/typescript/api/src/apis/DefaultApi.ts b/packages/continue-sdk/typescript/api/src/apis/DefaultApi.ts index 6bf466f23..0795d9438 100644 --- a/packages/continue-sdk/typescript/api/src/apis/DefaultApi.ts +++ b/packages/continue-sdk/typescript/api/src/apis/DefaultApi.ts @@ -2,136 +2,576 @@ /* eslint-disable */ /** * Continue Hub IDE API - * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. * * The version of the OpenAPI document: 1.0.0 - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -import * as runtime from "../runtime"; + +import * as runtime from '../runtime'; import type { + GetAssistant200Response, + GetAssistant403Response, + GetAssistant404Response, + GetFreeTrialStatus200Response, + GetModelsAddOnCheckoutUrl200Response, + GetModelsAddOnCheckoutUrl500Response, + GetPolicy200Response, + ListAssistantFullSlugs429Response, ListAssistants200ResponseInner, ListAssistants401Response, ListAssistants404Response, -} from "../models/index"; + ListOrganizations200Response, + SyncSecretsRequest, +} from '../models/index'; import { - ListAssistants200ResponseInnerFromJSON, - ListAssistants200ResponseInnerToJSON, - ListAssistants401ResponseFromJSON, - ListAssistants401ResponseToJSON, - ListAssistants404ResponseFromJSON, - ListAssistants404ResponseToJSON, -} from "../models/index"; + GetAssistant200ResponseFromJSON, + GetAssistant200ResponseToJSON, + GetAssistant403ResponseFromJSON, + GetAssistant403ResponseToJSON, + GetAssistant404ResponseFromJSON, + GetAssistant404ResponseToJSON, + GetFreeTrialStatus200ResponseFromJSON, + GetFreeTrialStatus200ResponseToJSON, + GetModelsAddOnCheckoutUrl200ResponseFromJSON, + GetModelsAddOnCheckoutUrl200ResponseToJSON, + GetModelsAddOnCheckoutUrl500ResponseFromJSON, + GetModelsAddOnCheckoutUrl500ResponseToJSON, + GetPolicy200ResponseFromJSON, + GetPolicy200ResponseToJSON, + ListAssistantFullSlugs429ResponseFromJSON, + ListAssistantFullSlugs429ResponseToJSON, + ListAssistants200ResponseInnerFromJSON, + ListAssistants200ResponseInnerToJSON, + ListAssistants401ResponseFromJSON, + ListAssistants401ResponseToJSON, + ListAssistants404ResponseFromJSON, + ListAssistants404ResponseToJSON, + ListOrganizations200ResponseFromJSON, + ListOrganizations200ResponseToJSON, + SyncSecretsRequestFromJSON, + SyncSecretsRequestToJSON, +} from '../models/index'; + +export interface GetAssistantRequest { + ownerSlug: string; + packageSlug: string; + alwaysUseProxy?: GetAssistantAlwaysUseProxyEnum; + organizationId?: string; +} + +export interface GetModelsAddOnCheckoutUrlRequest { + profileId?: string; + vscodeUriScheme?: string; +} export interface ListAssistantsRequest { - alwaysUseProxy?: ListAssistantsAlwaysUseProxyEnum; - organizationId?: string; + alwaysUseProxy?: ListAssistantsAlwaysUseProxyEnum; + organizationId?: string; +} + +export interface SyncSecretsOperationRequest { + syncSecretsRequest: SyncSecretsRequest; } /** * DefaultApi - interface - * + * * @export * @interface DefaultApiInterface */ export interface DefaultApiInterface { - /** - * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. - * @summary List assistants for IDE - * @param {'true' | 'false'} [alwaysUseProxy] Whether to always use the Continue-managed proxy for model requests - * @param {string} [organizationId] ID of the organization to scope assistants to. If not provided, personal assistants are returned. - * @param {*} [options] Override http request option. - * @throws {RequiredError} - * @memberof DefaultApiInterface - */ - listAssistantsRaw( - requestParameters: ListAssistantsRequest, - initOverrides?: RequestInit | runtime.InitOverrideFunction, - ): Promise>>; + /** + * Returns a single assistant configuration by its owner and package slug. This endpoint is useful when you need to retrieve or refresh a specific assistant without fetching the entire list. + * @summary Get a specific assistant by slug + * @param {string} ownerSlug Slug of the user or organization that owns the assistant + * @param {string} packageSlug Slug of the assistant package + * @param {'true' | 'false'} [alwaysUseProxy] Whether to always use the Continue-managed proxy for model requests + * @param {string} [organizationId] ID of the organization to scope assistants to. If not provided, personal assistants are returned. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + getAssistantRaw(requestParameters: GetAssistantRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + + /** + * Returns a single assistant configuration by its owner and package slug. This endpoint is useful when you need to retrieve or refresh a specific assistant without fetching the entire list. + * Get a specific assistant by slug + */ + getAssistant(requestParameters: GetAssistantRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise; + + /** + * Returns the current free trial status for the authenticated user, including usage counts and limits for chat and autocomplete features. + * @summary Get free trial status for user + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + getFreeTrialStatusRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + + /** + * Returns the current free trial status for the authenticated user, including usage counts and limits for chat and autocomplete features. + * Get free trial status for user + */ + getFreeTrialStatus(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise; + + /** + * Creates a Stripe checkout session for the models add-on subscription and returns the checkout URL. + * @summary Get Stripe checkout URL for models add-on + * @param {string} [profileId] Profile ID to include in the callback URL + * @param {string} [vscodeUriScheme] VS Code URI scheme to include in the callback URL + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + getModelsAddOnCheckoutUrlRaw(requestParameters: GetModelsAddOnCheckoutUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + + /** + * Creates a Stripe checkout session for the models add-on subscription and returns the checkout URL. + * Get Stripe checkout URL for models add-on + */ + getModelsAddOnCheckoutUrl(requestParameters: GetModelsAddOnCheckoutUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise; + + /** + * Returns the policy configuration for the first organization that the user belongs to which has a policy configured. + * @summary Get organization policy + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + getPolicyRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + + /** + * Returns the policy configuration for the first organization that the user belongs to which has a policy configured. + * Get organization policy + */ + getPolicy(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise; + + /** + * This endpoint is temporarily disabled and returns a 429 status code to prevent constant refreshes of the full assistant list until a fixed client version can be deployed. + * @summary List assistant full slugs (currently returns 429) + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + listAssistantFullSlugsRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + + /** + * This endpoint is temporarily disabled and returns a 429 status code to prevent constant refreshes of the full assistant list until a fixed client version can be deployed. + * List assistant full slugs (currently returns 429) + */ + listAssistantFullSlugs(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise; + + /** + * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + * @summary List assistants for IDE + * @param {'true' | 'false'} [alwaysUseProxy] Whether to always use the Continue-managed proxy for model requests + * @param {string} [organizationId] ID of the organization to scope assistants to. If not provided, personal assistants are returned. + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + listAssistantsRaw(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>>; + + /** + * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + * List assistants for IDE + */ + listAssistants(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + + /** + * Returns a list of organizations that the authenticated user belongs to, including organization metadata and pre-signed icon URLs. + * @summary List organizations for user + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + listOrganizationsRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; + + /** + * Returns a list of organizations that the authenticated user belongs to, including organization metadata and pre-signed icon URLs. + * List organizations for user + */ + listOrganizations(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise; + + /** + * Resolves and synchronizes secrets for the authenticated user based on the provided Fully Qualified Secret Names (FQSNs). + * @summary Synchronize secrets for user + * @param {SyncSecretsRequest} syncSecretsRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof DefaultApiInterface + */ + syncSecretsRaw(requestParameters: SyncSecretsOperationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>>; + + /** + * Resolves and synchronizes secrets for the authenticated user based on the provided Fully Qualified Secret Names (FQSNs). + * Synchronize secrets for user + */ + syncSecrets(requestParameters: SyncSecretsOperationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; - /** - * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. - * List assistants for IDE - */ - listAssistants( - requestParameters: ListAssistantsRequest, - initOverrides?: RequestInit | runtime.InitOverrideFunction, - ): Promise>; } /** - * + * */ export class DefaultApi extends runtime.BaseAPI implements DefaultApiInterface { - /** - * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. - * List assistants for IDE - */ - async listAssistantsRaw( - requestParameters: ListAssistantsRequest, - initOverrides?: RequestInit | runtime.InitOverrideFunction, - ): Promise>> { - const queryParameters: any = {}; - if (requestParameters["alwaysUseProxy"] != null) { - queryParameters["alwaysUseProxy"] = requestParameters["alwaysUseProxy"]; + /** + * Returns a single assistant configuration by its owner and package slug. This endpoint is useful when you need to retrieve or refresh a specific assistant without fetching the entire list. + * Get a specific assistant by slug + */ + async getAssistantRaw(requestParameters: GetAssistantRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + if (requestParameters['ownerSlug'] == null) { + throw new runtime.RequiredError( + 'ownerSlug', + 'Required parameter "ownerSlug" was null or undefined when calling getAssistant().' + ); + } + + if (requestParameters['packageSlug'] == null) { + throw new runtime.RequiredError( + 'packageSlug', + 'Required parameter "packageSlug" was null or undefined when calling getAssistant().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['alwaysUseProxy'] != null) { + queryParameters['alwaysUseProxy'] = requestParameters['alwaysUseProxy']; + } + + if (requestParameters['organizationId'] != null) { + queryParameters['organizationId'] = requestParameters['organizationId']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/get-assistant/{ownerSlug}/{packageSlug}`.replace(`{${"ownerSlug"}}`, encodeURIComponent(String(requestParameters['ownerSlug']))).replace(`{${"packageSlug"}}`, encodeURIComponent(String(requestParameters['packageSlug']))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetAssistant200ResponseFromJSON(jsonValue)); } - if (requestParameters["organizationId"] != null) { - queryParameters["organizationId"] = requestParameters["organizationId"]; + /** + * Returns a single assistant configuration by its owner and package slug. This endpoint is useful when you need to retrieve or refresh a specific assistant without fetching the entire list. + * Get a specific assistant by slug + */ + async getAssistant(requestParameters: GetAssistantRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getAssistantRaw(requestParameters, initOverrides); + return await response.value(); } - const headerParameters: runtime.HTTPHeaders = {}; + /** + * Returns the current free trial status for the authenticated user, including usage counts and limits for chat and autocomplete features. + * Get free trial status for user + */ + async getFreeTrialStatusRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; - if (this.configuration && this.configuration.accessToken) { - const token = this.configuration.accessToken; - const tokenString = await token("apiKeyAuth", []); + const headerParameters: runtime.HTTPHeaders = {}; - if (tokenString) { - headerParameters["Authorization"] = `Bearer ${tokenString}`; - } + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/free-trial-status`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetFreeTrialStatus200ResponseFromJSON(jsonValue)); } - const response = await this.request( - { - path: `/ide/list-assistants`, - method: "GET", - headers: headerParameters, - query: queryParameters, - }, - initOverrides, - ); - return new runtime.JSONApiResponse(response, (jsonValue) => - jsonValue.map(ListAssistants200ResponseInnerFromJSON), - ); - } + /** + * Returns the current free trial status for the authenticated user, including usage counts and limits for chat and autocomplete features. + * Get free trial status for user + */ + async getFreeTrialStatus(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getFreeTrialStatusRaw(initOverrides); + return await response.value(); + } + + /** + * Creates a Stripe checkout session for the models add-on subscription and returns the checkout URL. + * Get Stripe checkout URL for models add-on + */ + async getModelsAddOnCheckoutUrlRaw(requestParameters: GetModelsAddOnCheckoutUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + if (requestParameters['profileId'] != null) { + queryParameters['profile_id'] = requestParameters['profileId']; + } + + if (requestParameters['vscodeUriScheme'] != null) { + queryParameters['vscode_uri_scheme'] = requestParameters['vscodeUriScheme']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/get-models-add-on-checkout-url`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetModelsAddOnCheckoutUrl200ResponseFromJSON(jsonValue)); + } + + /** + * Creates a Stripe checkout session for the models add-on subscription and returns the checkout URL. + * Get Stripe checkout URL for models add-on + */ + async getModelsAddOnCheckoutUrl(requestParameters: GetModelsAddOnCheckoutUrlRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getModelsAddOnCheckoutUrlRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Returns the policy configuration for the first organization that the user belongs to which has a policy configured. + * Get organization policy + */ + async getPolicyRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/policy`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetPolicy200ResponseFromJSON(jsonValue)); + } + + /** + * Returns the policy configuration for the first organization that the user belongs to which has a policy configured. + * Get organization policy + */ + async getPolicy(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getPolicyRaw(initOverrides); + return await response.value(); + } + + /** + * This endpoint is temporarily disabled and returns a 429 status code to prevent constant refreshes of the full assistant list until a fixed client version can be deployed. + * List assistant full slugs (currently returns 429) + */ + async listAssistantFullSlugsRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/list-assistant-full-slugs`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * This endpoint is temporarily disabled and returns a 429 status code to prevent constant refreshes of the full assistant list until a fixed client version can be deployed. + * List assistant full slugs (currently returns 429) + */ + async listAssistantFullSlugs(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.listAssistantFullSlugsRaw(initOverrides); + } + + /** + * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + * List assistants for IDE + */ + async listAssistantsRaw(requestParameters: ListAssistantsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { + const queryParameters: any = {}; + + if (requestParameters['alwaysUseProxy'] != null) { + queryParameters['alwaysUseProxy'] = requestParameters['alwaysUseProxy']; + } + + if (requestParameters['organizationId'] != null) { + queryParameters['organizationId'] = requestParameters['organizationId']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/list-assistants`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(ListAssistants200ResponseInnerFromJSON)); + } + + /** + * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. + * List assistants for IDE + */ + async listAssistants(requestParameters: ListAssistantsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const response = await this.listAssistantsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Returns a list of organizations that the authenticated user belongs to, including organization metadata and pre-signed icon URLs. + * List organizations for user + */ + async listOrganizationsRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/list-organizations`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ListOrganizations200ResponseFromJSON(jsonValue)); + } + + /** + * Returns a list of organizations that the authenticated user belongs to, including organization metadata and pre-signed icon URLs. + * List organizations for user + */ + async listOrganizations(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.listOrganizationsRaw(initOverrides); + return await response.value(); + } + + /** + * Resolves and synchronizes secrets for the authenticated user based on the provided Fully Qualified Secret Names (FQSNs). + * Synchronize secrets for user + */ + async syncSecretsRaw(requestParameters: SyncSecretsOperationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { + if (requestParameters['syncSecretsRequest'] == null) { + throw new runtime.RequiredError( + 'syncSecretsRequest', + 'Required parameter "syncSecretsRequest" was null or undefined when calling syncSecrets().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + const token = this.configuration.accessToken; + const tokenString = await token("apiKeyAuth", []); + + if (tokenString) { + headerParameters["Authorization"] = `Bearer ${tokenString}`; + } + } + const response = await this.request({ + path: `/ide/sync-secrets`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: SyncSecretsRequestToJSON(requestParameters['syncSecretsRequest']), + }, initOverrides); + + return new runtime.JSONApiResponse(response); + } + + /** + * Resolves and synchronizes secrets for the authenticated user based on the provided Fully Qualified Secret Names (FQSNs). + * Synchronize secrets for user + */ + async syncSecrets(requestParameters: SyncSecretsOperationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const response = await this.syncSecretsRaw(requestParameters, initOverrides); + return await response.value(); + } - /** - * Returns a complete list of assistants available to the user, with their full configurations, icons, and other metadata needed by the IDE to display and use them. This endpoint performs a full refresh of the list of assistants, including unrolling configurations and resolving secrets. - * List assistants for IDE - */ - async listAssistants( - requestParameters: ListAssistantsRequest = {}, - initOverrides?: RequestInit | runtime.InitOverrideFunction, - ): Promise> { - const response = await this.listAssistantsRaw( - requestParameters, - initOverrides, - ); - return await response.value(); - } } /** * @export */ -export const ListAssistantsAlwaysUseProxyEnum = { - TRUE: "true", - FALSE: "false", +export const GetAssistantAlwaysUseProxyEnum = { + TRUE: 'true', + FALSE: 'false' } as const; -export type ListAssistantsAlwaysUseProxyEnum = - (typeof ListAssistantsAlwaysUseProxyEnum)[keyof typeof ListAssistantsAlwaysUseProxyEnum]; +export type GetAssistantAlwaysUseProxyEnum = typeof GetAssistantAlwaysUseProxyEnum[keyof typeof GetAssistantAlwaysUseProxyEnum]; +/** + * @export + */ +export const ListAssistantsAlwaysUseProxyEnum = { + TRUE: 'true', + FALSE: 'false' +} as const; +export type ListAssistantsAlwaysUseProxyEnum = typeof ListAssistantsAlwaysUseProxyEnum[keyof typeof ListAssistantsAlwaysUseProxyEnum]; diff --git a/packages/continue-sdk/typescript/api/src/apis/index.ts b/packages/continue-sdk/typescript/api/src/apis/index.ts index f70f3d328..69c44c00f 100644 --- a/packages/continue-sdk/typescript/api/src/apis/index.ts +++ b/packages/continue-sdk/typescript/api/src/apis/index.ts @@ -1,3 +1,3 @@ /* tslint:disable */ /* eslint-disable */ -export * from "./DefaultApi"; +export * from './DefaultApi'; diff --git a/packages/continue-sdk/typescript/api/src/index.ts b/packages/continue-sdk/typescript/api/src/index.ts index ee2637724..bebe8bbbe 100644 --- a/packages/continue-sdk/typescript/api/src/index.ts +++ b/packages/continue-sdk/typescript/api/src/index.ts @@ -1,5 +1,5 @@ /* tslint:disable */ /* eslint-disable */ -export * from "./runtime"; -export * from "./apis/index"; -export * from "./models/index"; +export * from './runtime'; +export * from './apis/index'; +export * from './models/index'; diff --git a/packages/continue-sdk/typescript/api/src/models/GetAssistant200Response.ts b/packages/continue-sdk/typescript/api/src/models/GetAssistant200Response.ts new file mode 100644 index 000000000..8b22c4fbb --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/GetAssistant200Response.ts @@ -0,0 +1,124 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ListAssistants200ResponseInnerConfigResult } from './ListAssistants200ResponseInnerConfigResult'; +import { + ListAssistants200ResponseInnerConfigResultFromJSON, + ListAssistants200ResponseInnerConfigResultFromJSONTyped, + ListAssistants200ResponseInnerConfigResultToJSON, + ListAssistants200ResponseInnerConfigResultToJSONTyped, +} from './ListAssistants200ResponseInnerConfigResult'; + +/** + * + * @export + * @interface GetAssistant200Response + */ +export interface GetAssistant200Response { + /** + * + * @type {ListAssistants200ResponseInnerConfigResult} + * @memberof GetAssistant200Response + */ + configResult: ListAssistants200ResponseInnerConfigResult; + /** + * Slug of the user or organization that owns the assistant + * @type {string} + * @memberof GetAssistant200Response + */ + ownerSlug: string; + /** + * Slug of the assistant package + * @type {string} + * @memberof GetAssistant200Response + */ + packageSlug: string; + /** + * Pre-signed URL for the assistant's icon + * @type {string} + * @memberof GetAssistant200Response + */ + iconUrl?: string | null; + /** + * URL of the on-premises proxy if the organization uses one + * @type {string} + * @memberof GetAssistant200Response + */ + onPremProxyUrl?: string | null; + /** + * Whether the organization uses an on-premises proxy + * @type {boolean} + * @memberof GetAssistant200Response + */ + useOnPremProxy?: boolean | null; + /** + * Raw YAML configuration of the assistant + * @type {string} + * @memberof GetAssistant200Response + */ + rawYaml?: string; +} + +/** + * Check if a given object implements the GetAssistant200Response interface. + */ +export function instanceOfGetAssistant200Response(value: object): value is GetAssistant200Response { + if (!('configResult' in value) || value['configResult'] === undefined) return false; + if (!('ownerSlug' in value) || value['ownerSlug'] === undefined) return false; + if (!('packageSlug' in value) || value['packageSlug'] === undefined) return false; + return true; +} + +export function GetAssistant200ResponseFromJSON(json: any): GetAssistant200Response { + return GetAssistant200ResponseFromJSONTyped(json, false); +} + +export function GetAssistant200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetAssistant200Response { + if (json == null) { + return json; + } + return { + + 'configResult': ListAssistants200ResponseInnerConfigResultFromJSON(json['configResult']), + 'ownerSlug': json['ownerSlug'], + 'packageSlug': json['packageSlug'], + 'iconUrl': json['iconUrl'] == null ? undefined : json['iconUrl'], + 'onPremProxyUrl': json['onPremProxyUrl'] == null ? undefined : json['onPremProxyUrl'], + 'useOnPremProxy': json['useOnPremProxy'] == null ? undefined : json['useOnPremProxy'], + 'rawYaml': json['rawYaml'] == null ? undefined : json['rawYaml'], + }; +} + +export function GetAssistant200ResponseToJSON(json: any): GetAssistant200Response { + return GetAssistant200ResponseToJSONTyped(json, false); +} + +export function GetAssistant200ResponseToJSONTyped(value?: GetAssistant200Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'configResult': ListAssistants200ResponseInnerConfigResultToJSON(value['configResult']), + 'ownerSlug': value['ownerSlug'], + 'packageSlug': value['packageSlug'], + 'iconUrl': value['iconUrl'], + 'onPremProxyUrl': value['onPremProxyUrl'], + 'useOnPremProxy': value['useOnPremProxy'], + 'rawYaml': value['rawYaml'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/GetAssistant403Response.ts b/packages/continue-sdk/typescript/api/src/models/GetAssistant403Response.ts new file mode 100644 index 000000000..c074c4555 --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/GetAssistant403Response.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface GetAssistant403Response + */ +export interface GetAssistant403Response { + /** + * + * @type {string} + * @memberof GetAssistant403Response + */ + message?: string; +} + +/** + * Check if a given object implements the GetAssistant403Response interface. + */ +export function instanceOfGetAssistant403Response(value: object): value is GetAssistant403Response { + return true; +} + +export function GetAssistant403ResponseFromJSON(json: any): GetAssistant403Response { + return GetAssistant403ResponseFromJSONTyped(json, false); +} + +export function GetAssistant403ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetAssistant403Response { + if (json == null) { + return json; + } + return { + + 'message': json['message'] == null ? undefined : json['message'], + }; +} + +export function GetAssistant403ResponseToJSON(json: any): GetAssistant403Response { + return GetAssistant403ResponseToJSONTyped(json, false); +} + +export function GetAssistant403ResponseToJSONTyped(value?: GetAssistant403Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'message': value['message'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/GetAssistant404Response.ts b/packages/continue-sdk/typescript/api/src/models/GetAssistant404Response.ts new file mode 100644 index 000000000..15e60c01d --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/GetAssistant404Response.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface GetAssistant404Response + */ +export interface GetAssistant404Response { + /** + * + * @type {string} + * @memberof GetAssistant404Response + */ + message?: string; +} + +/** + * Check if a given object implements the GetAssistant404Response interface. + */ +export function instanceOfGetAssistant404Response(value: object): value is GetAssistant404Response { + return true; +} + +export function GetAssistant404ResponseFromJSON(json: any): GetAssistant404Response { + return GetAssistant404ResponseFromJSONTyped(json, false); +} + +export function GetAssistant404ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetAssistant404Response { + if (json == null) { + return json; + } + return { + + 'message': json['message'] == null ? undefined : json['message'], + }; +} + +export function GetAssistant404ResponseToJSON(json: any): GetAssistant404Response { + return GetAssistant404ResponseToJSONTyped(json, false); +} + +export function GetAssistant404ResponseToJSONTyped(value?: GetAssistant404Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'message': value['message'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/GetFreeTrialStatus200Response.ts b/packages/continue-sdk/typescript/api/src/models/GetFreeTrialStatus200Response.ts new file mode 100644 index 000000000..cd084b794 --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/GetFreeTrialStatus200Response.ts @@ -0,0 +1,100 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface GetFreeTrialStatus200Response + */ +export interface GetFreeTrialStatus200Response { + /** + * Whether the user has opted into the free trial + * @type {boolean} + * @memberof GetFreeTrialStatus200Response + */ + optedInToFreeTrial: boolean; + /** + * Current number of chat messages used + * @type {number} + * @memberof GetFreeTrialStatus200Response + */ + chatCount?: number | null; + /** + * Current number of autocomplete requests used + * @type {number} + * @memberof GetFreeTrialStatus200Response + */ + autocompleteCount?: number | null; + /** + * Maximum number of chat messages allowed in free trial + * @type {number} + * @memberof GetFreeTrialStatus200Response + */ + chatLimit: number; + /** + * Maximum number of autocomplete requests allowed in free trial + * @type {number} + * @memberof GetFreeTrialStatus200Response + */ + autocompleteLimit: number; +} + +/** + * Check if a given object implements the GetFreeTrialStatus200Response interface. + */ +export function instanceOfGetFreeTrialStatus200Response(value: object): value is GetFreeTrialStatus200Response { + if (!('optedInToFreeTrial' in value) || value['optedInToFreeTrial'] === undefined) return false; + if (!('chatLimit' in value) || value['chatLimit'] === undefined) return false; + if (!('autocompleteLimit' in value) || value['autocompleteLimit'] === undefined) return false; + return true; +} + +export function GetFreeTrialStatus200ResponseFromJSON(json: any): GetFreeTrialStatus200Response { + return GetFreeTrialStatus200ResponseFromJSONTyped(json, false); +} + +export function GetFreeTrialStatus200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetFreeTrialStatus200Response { + if (json == null) { + return json; + } + return { + + 'optedInToFreeTrial': json['optedInToFreeTrial'], + 'chatCount': json['chatCount'] == null ? undefined : json['chatCount'], + 'autocompleteCount': json['autocompleteCount'] == null ? undefined : json['autocompleteCount'], + 'chatLimit': json['chatLimit'], + 'autocompleteLimit': json['autocompleteLimit'], + }; +} + +export function GetFreeTrialStatus200ResponseToJSON(json: any): GetFreeTrialStatus200Response { + return GetFreeTrialStatus200ResponseToJSONTyped(json, false); +} + +export function GetFreeTrialStatus200ResponseToJSONTyped(value?: GetFreeTrialStatus200Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'optedInToFreeTrial': value['optedInToFreeTrial'], + 'chatCount': value['chatCount'], + 'autocompleteCount': value['autocompleteCount'], + 'chatLimit': value['chatLimit'], + 'autocompleteLimit': value['autocompleteLimit'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/GetModelsAddOnCheckoutUrl200Response.ts b/packages/continue-sdk/typescript/api/src/models/GetModelsAddOnCheckoutUrl200Response.ts new file mode 100644 index 000000000..2c935ffda --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/GetModelsAddOnCheckoutUrl200Response.ts @@ -0,0 +1,66 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface GetModelsAddOnCheckoutUrl200Response + */ +export interface GetModelsAddOnCheckoutUrl200Response { + /** + * Stripe checkout session URL + * @type {string} + * @memberof GetModelsAddOnCheckoutUrl200Response + */ + url: string; +} + +/** + * Check if a given object implements the GetModelsAddOnCheckoutUrl200Response interface. + */ +export function instanceOfGetModelsAddOnCheckoutUrl200Response(value: object): value is GetModelsAddOnCheckoutUrl200Response { + if (!('url' in value) || value['url'] === undefined) return false; + return true; +} + +export function GetModelsAddOnCheckoutUrl200ResponseFromJSON(json: any): GetModelsAddOnCheckoutUrl200Response { + return GetModelsAddOnCheckoutUrl200ResponseFromJSONTyped(json, false); +} + +export function GetModelsAddOnCheckoutUrl200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetModelsAddOnCheckoutUrl200Response { + if (json == null) { + return json; + } + return { + + 'url': json['url'], + }; +} + +export function GetModelsAddOnCheckoutUrl200ResponseToJSON(json: any): GetModelsAddOnCheckoutUrl200Response { + return GetModelsAddOnCheckoutUrl200ResponseToJSONTyped(json, false); +} + +export function GetModelsAddOnCheckoutUrl200ResponseToJSONTyped(value?: GetModelsAddOnCheckoutUrl200Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'url': value['url'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/GetModelsAddOnCheckoutUrl500Response.ts b/packages/continue-sdk/typescript/api/src/models/GetModelsAddOnCheckoutUrl500Response.ts new file mode 100644 index 000000000..e548161ac --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/GetModelsAddOnCheckoutUrl500Response.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface GetModelsAddOnCheckoutUrl500Response + */ +export interface GetModelsAddOnCheckoutUrl500Response { + /** + * + * @type {string} + * @memberof GetModelsAddOnCheckoutUrl500Response + */ + message?: string; +} + +/** + * Check if a given object implements the GetModelsAddOnCheckoutUrl500Response interface. + */ +export function instanceOfGetModelsAddOnCheckoutUrl500Response(value: object): value is GetModelsAddOnCheckoutUrl500Response { + return true; +} + +export function GetModelsAddOnCheckoutUrl500ResponseFromJSON(json: any): GetModelsAddOnCheckoutUrl500Response { + return GetModelsAddOnCheckoutUrl500ResponseFromJSONTyped(json, false); +} + +export function GetModelsAddOnCheckoutUrl500ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetModelsAddOnCheckoutUrl500Response { + if (json == null) { + return json; + } + return { + + 'message': json['message'] == null ? undefined : json['message'], + }; +} + +export function GetModelsAddOnCheckoutUrl500ResponseToJSON(json: any): GetModelsAddOnCheckoutUrl500Response { + return GetModelsAddOnCheckoutUrl500ResponseToJSONTyped(json, false); +} + +export function GetModelsAddOnCheckoutUrl500ResponseToJSONTyped(value?: GetModelsAddOnCheckoutUrl500Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'message': value['message'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/GetPolicy200Response.ts b/packages/continue-sdk/typescript/api/src/models/GetPolicy200Response.ts new file mode 100644 index 000000000..e43e8c882 --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/GetPolicy200Response.ts @@ -0,0 +1,73 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface GetPolicy200Response + */ +export interface GetPolicy200Response { + /** + * Organization policy configuration + * @type {object} + * @memberof GetPolicy200Response + */ + policy?: object | null; + /** + * Slug of the organization that has the policy + * @type {string} + * @memberof GetPolicy200Response + */ + orgSlug?: string | null; +} + +/** + * Check if a given object implements the GetPolicy200Response interface. + */ +export function instanceOfGetPolicy200Response(value: object): value is GetPolicy200Response { + return true; +} + +export function GetPolicy200ResponseFromJSON(json: any): GetPolicy200Response { + return GetPolicy200ResponseFromJSONTyped(json, false); +} + +export function GetPolicy200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetPolicy200Response { + if (json == null) { + return json; + } + return { + + 'policy': json['policy'] == null ? undefined : json['policy'], + 'orgSlug': json['orgSlug'] == null ? undefined : json['orgSlug'], + }; +} + +export function GetPolicy200ResponseToJSON(json: any): GetPolicy200Response { + return GetPolicy200ResponseToJSONTyped(json, false); +} + +export function GetPolicy200ResponseToJSONTyped(value?: GetPolicy200Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'policy': value['policy'], + 'orgSlug': value['orgSlug'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/ListAssistantFullSlugs429Response.ts b/packages/continue-sdk/typescript/api/src/models/ListAssistantFullSlugs429Response.ts new file mode 100644 index 000000000..a16577260 --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/ListAssistantFullSlugs429Response.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface ListAssistantFullSlugs429Response + */ +export interface ListAssistantFullSlugs429Response { + /** + * + * @type {string} + * @memberof ListAssistantFullSlugs429Response + */ + message?: string; +} + +/** + * Check if a given object implements the ListAssistantFullSlugs429Response interface. + */ +export function instanceOfListAssistantFullSlugs429Response(value: object): value is ListAssistantFullSlugs429Response { + return true; +} + +export function ListAssistantFullSlugs429ResponseFromJSON(json: any): ListAssistantFullSlugs429Response { + return ListAssistantFullSlugs429ResponseFromJSONTyped(json, false); +} + +export function ListAssistantFullSlugs429ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistantFullSlugs429Response { + if (json == null) { + return json; + } + return { + + 'message': json['message'] == null ? undefined : json['message'], + }; +} + +export function ListAssistantFullSlugs429ResponseToJSON(json: any): ListAssistantFullSlugs429Response { + return ListAssistantFullSlugs429ResponseToJSONTyped(json, false); +} + +export function ListAssistantFullSlugs429ResponseToJSONTyped(value?: ListAssistantFullSlugs429Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'message': value['message'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInner.ts b/packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInner.ts index 015aeb3ba..9f572de3e 100644 --- a/packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInner.ts +++ b/packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInner.ts @@ -2,140 +2,123 @@ /* eslint-disable */ /** * Continue Hub IDE API - * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. * * The version of the OpenAPI document: 1.0.0 - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -import { mapValues } from "../runtime"; -import type { ListAssistants200ResponseInnerConfigResult } from "./ListAssistants200ResponseInnerConfigResult"; +import { mapValues } from '../runtime'; +import type { ListAssistants200ResponseInnerConfigResult } from './ListAssistants200ResponseInnerConfigResult'; import { - ListAssistants200ResponseInnerConfigResultFromJSON, - ListAssistants200ResponseInnerConfigResultFromJSONTyped, - ListAssistants200ResponseInnerConfigResultToJSON, - ListAssistants200ResponseInnerConfigResultToJSONTyped, -} from "./ListAssistants200ResponseInnerConfigResult"; + ListAssistants200ResponseInnerConfigResultFromJSON, + ListAssistants200ResponseInnerConfigResultFromJSONTyped, + ListAssistants200ResponseInnerConfigResultToJSON, + ListAssistants200ResponseInnerConfigResultToJSONTyped, +} from './ListAssistants200ResponseInnerConfigResult'; /** - * + * * @export * @interface ListAssistants200ResponseInner */ export interface ListAssistants200ResponseInner { - /** - * - * @type {ListAssistants200ResponseInnerConfigResult} - * @memberof ListAssistants200ResponseInner - */ - configResult: ListAssistants200ResponseInnerConfigResult; - /** - * Slug of the user or organization that owns the assistant - * @type {string} - * @memberof ListAssistants200ResponseInner - */ - ownerSlug: string; - /** - * Slug of the assistant package - * @type {string} - * @memberof ListAssistants200ResponseInner - */ - packageSlug: string; - /** - * Pre-signed URL for the assistant's icon - * @type {string} - * @memberof ListAssistants200ResponseInner - */ - iconUrl?: string | null; - /** - * URL of the on-premises proxy if the organization uses one - * @type {string} - * @memberof ListAssistants200ResponseInner - */ - onPremProxyUrl?: string | null; - /** - * Whether the organization uses an on-premises proxy - * @type {boolean} - * @memberof ListAssistants200ResponseInner - */ - useOnPremProxy?: boolean | null; - /** - * Raw YAML configuration of the assistant - * @type {string} - * @memberof ListAssistants200ResponseInner - */ - rawYaml?: string; + /** + * + * @type {ListAssistants200ResponseInnerConfigResult} + * @memberof ListAssistants200ResponseInner + */ + configResult: ListAssistants200ResponseInnerConfigResult; + /** + * Slug of the user or organization that owns the assistant + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + ownerSlug: string; + /** + * Slug of the assistant package + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + packageSlug: string; + /** + * Pre-signed URL for the assistant's icon + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + iconUrl?: string | null; + /** + * URL of the on-premises proxy if the organization uses one + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + onPremProxyUrl?: string | null; + /** + * Whether the organization uses an on-premises proxy + * @type {boolean} + * @memberof ListAssistants200ResponseInner + */ + useOnPremProxy?: boolean | null; + /** + * Raw YAML configuration of the assistant + * @type {string} + * @memberof ListAssistants200ResponseInner + */ + rawYaml?: string; } /** * Check if a given object implements the ListAssistants200ResponseInner interface. */ -export function instanceOfListAssistants200ResponseInner( - value: object, -): value is ListAssistants200ResponseInner { - if (!("configResult" in value) || value["configResult"] === undefined) - return false; - if (!("ownerSlug" in value) || value["ownerSlug"] === undefined) return false; - if (!("packageSlug" in value) || value["packageSlug"] === undefined) - return false; - return true; +export function instanceOfListAssistants200ResponseInner(value: object): value is ListAssistants200ResponseInner { + if (!('configResult' in value) || value['configResult'] === undefined) return false; + if (!('ownerSlug' in value) || value['ownerSlug'] === undefined) return false; + if (!('packageSlug' in value) || value['packageSlug'] === undefined) return false; + return true; } -export function ListAssistants200ResponseInnerFromJSON( - json: any, -): ListAssistants200ResponseInner { - return ListAssistants200ResponseInnerFromJSONTyped(json, false); +export function ListAssistants200ResponseInnerFromJSON(json: any): ListAssistants200ResponseInner { + return ListAssistants200ResponseInnerFromJSONTyped(json, false); } -export function ListAssistants200ResponseInnerFromJSONTyped( - json: any, - ignoreDiscriminator: boolean, -): ListAssistants200ResponseInner { - if (json == null) { - return json; - } - return { - configResult: ListAssistants200ResponseInnerConfigResultFromJSON( - json["configResult"], - ), - ownerSlug: json["ownerSlug"], - packageSlug: json["packageSlug"], - iconUrl: json["iconUrl"] == null ? undefined : json["iconUrl"], - onPremProxyUrl: - json["onPremProxyUrl"] == null ? undefined : json["onPremProxyUrl"], - useOnPremProxy: - json["useOnPremProxy"] == null ? undefined : json["useOnPremProxy"], - rawYaml: json["rawYaml"] == null ? undefined : json["rawYaml"], - }; +export function ListAssistants200ResponseInnerFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants200ResponseInner { + if (json == null) { + return json; + } + return { + + 'configResult': ListAssistants200ResponseInnerConfigResultFromJSON(json['configResult']), + 'ownerSlug': json['ownerSlug'], + 'packageSlug': json['packageSlug'], + 'iconUrl': json['iconUrl'] == null ? undefined : json['iconUrl'], + 'onPremProxyUrl': json['onPremProxyUrl'] == null ? undefined : json['onPremProxyUrl'], + 'useOnPremProxy': json['useOnPremProxy'] == null ? undefined : json['useOnPremProxy'], + 'rawYaml': json['rawYaml'] == null ? undefined : json['rawYaml'], + }; } -export function ListAssistants200ResponseInnerToJSON( - json: any, -): ListAssistants200ResponseInner { - return ListAssistants200ResponseInnerToJSONTyped(json, false); +export function ListAssistants200ResponseInnerToJSON(json: any): ListAssistants200ResponseInner { + return ListAssistants200ResponseInnerToJSONTyped(json, false); } -export function ListAssistants200ResponseInnerToJSONTyped( - value?: ListAssistants200ResponseInner | null, - ignoreDiscriminator: boolean = false, -): any { - if (value == null) { - return value; - } +export function ListAssistants200ResponseInnerToJSONTyped(value?: ListAssistants200ResponseInner | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } - return { - configResult: ListAssistants200ResponseInnerConfigResultToJSON( - value["configResult"], - ), - ownerSlug: value["ownerSlug"], - packageSlug: value["packageSlug"], - iconUrl: value["iconUrl"], - onPremProxyUrl: value["onPremProxyUrl"], - useOnPremProxy: value["useOnPremProxy"], - rawYaml: value["rawYaml"], - }; + return { + + 'configResult': ListAssistants200ResponseInnerConfigResultToJSON(value['configResult']), + 'ownerSlug': value['ownerSlug'], + 'packageSlug': value['packageSlug'], + 'iconUrl': value['iconUrl'], + 'onPremProxyUrl': value['onPremProxyUrl'], + 'useOnPremProxy': value['useOnPremProxy'], + 'rawYaml': value['rawYaml'], + }; } + diff --git a/packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInnerConfigResult.ts b/packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInnerConfigResult.ts index a3a9e9522..fd2e6ea8c 100644 --- a/packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInnerConfigResult.ts +++ b/packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInnerConfigResult.ts @@ -2,95 +2,82 @@ /* eslint-disable */ /** * Continue Hub IDE API - * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. * * The version of the OpenAPI document: 1.0.0 - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -import { mapValues } from "../runtime"; +import { mapValues } from '../runtime'; /** - * + * * @export * @interface ListAssistants200ResponseInnerConfigResult */ export interface ListAssistants200ResponseInnerConfigResult { - /** - * The unrolled assistant configuration - * @type {object} - * @memberof ListAssistants200ResponseInnerConfigResult - */ - config: object | null; - /** - * Whether the configuration loading was interrupted - * @type {boolean} - * @memberof ListAssistants200ResponseInnerConfigResult - */ - configLoadInterrupted: boolean; - /** - * Any errors that occurred during configuration loading - * @type {Array} - * @memberof ListAssistants200ResponseInnerConfigResult - */ - errors?: Array | null; + /** + * The unrolled assistant configuration + * @type {object} + * @memberof ListAssistants200ResponseInnerConfigResult + */ + config: object | null; + /** + * Whether the configuration loading was interrupted + * @type {boolean} + * @memberof ListAssistants200ResponseInnerConfigResult + */ + configLoadInterrupted: boolean; + /** + * Any errors that occurred during configuration loading + * @type {Array} + * @memberof ListAssistants200ResponseInnerConfigResult + */ + errors?: Array | null; } /** * Check if a given object implements the ListAssistants200ResponseInnerConfigResult interface. */ -export function instanceOfListAssistants200ResponseInnerConfigResult( - value: object, -): value is ListAssistants200ResponseInnerConfigResult { - if (!("config" in value) || value["config"] === undefined) return false; - if ( - !("configLoadInterrupted" in value) || - value["configLoadInterrupted"] === undefined - ) - return false; - return true; +export function instanceOfListAssistants200ResponseInnerConfigResult(value: object): value is ListAssistants200ResponseInnerConfigResult { + if (!('config' in value) || value['config'] === undefined) return false; + if (!('configLoadInterrupted' in value) || value['configLoadInterrupted'] === undefined) return false; + return true; } -export function ListAssistants200ResponseInnerConfigResultFromJSON( - json: any, -): ListAssistants200ResponseInnerConfigResult { - return ListAssistants200ResponseInnerConfigResultFromJSONTyped(json, false); +export function ListAssistants200ResponseInnerConfigResultFromJSON(json: any): ListAssistants200ResponseInnerConfigResult { + return ListAssistants200ResponseInnerConfigResultFromJSONTyped(json, false); } -export function ListAssistants200ResponseInnerConfigResultFromJSONTyped( - json: any, - ignoreDiscriminator: boolean, -): ListAssistants200ResponseInnerConfigResult { - if (json == null) { - return json; - } - return { - config: json["config"], - configLoadInterrupted: json["configLoadInterrupted"], - errors: json["errors"] == null ? undefined : json["errors"], - }; +export function ListAssistants200ResponseInnerConfigResultFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants200ResponseInnerConfigResult { + if (json == null) { + return json; + } + return { + + 'config': json['config'], + 'configLoadInterrupted': json['configLoadInterrupted'], + 'errors': json['errors'] == null ? undefined : json['errors'], + }; } -export function ListAssistants200ResponseInnerConfigResultToJSON( - json: any, -): ListAssistants200ResponseInnerConfigResult { - return ListAssistants200ResponseInnerConfigResultToJSONTyped(json, false); +export function ListAssistants200ResponseInnerConfigResultToJSON(json: any): ListAssistants200ResponseInnerConfigResult { + return ListAssistants200ResponseInnerConfigResultToJSONTyped(json, false); } -export function ListAssistants200ResponseInnerConfigResultToJSONTyped( - value?: ListAssistants200ResponseInnerConfigResult | null, - ignoreDiscriminator: boolean = false, -): any { - if (value == null) { - return value; - } +export function ListAssistants200ResponseInnerConfigResultToJSONTyped(value?: ListAssistants200ResponseInnerConfigResult | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } - return { - config: value["config"], - configLoadInterrupted: value["configLoadInterrupted"], - errors: value["errors"], - }; + return { + + 'config': value['config'], + 'configLoadInterrupted': value['configLoadInterrupted'], + 'errors': value['errors'], + }; } + diff --git a/packages/continue-sdk/typescript/api/src/models/ListAssistants401Response.ts b/packages/continue-sdk/typescript/api/src/models/ListAssistants401Response.ts index 9c4a961a5..a8d7d10b1 100644 --- a/packages/continue-sdk/typescript/api/src/models/ListAssistants401Response.ts +++ b/packages/continue-sdk/typescript/api/src/models/ListAssistants401Response.ts @@ -2,73 +2,64 @@ /* eslint-disable */ /** * Continue Hub IDE API - * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. * * The version of the OpenAPI document: 1.0.0 - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -import { mapValues } from "../runtime"; +import { mapValues } from '../runtime'; /** - * + * * @export * @interface ListAssistants401Response */ export interface ListAssistants401Response { - /** - * - * @type {string} - * @memberof ListAssistants401Response - */ - message?: string; + /** + * + * @type {string} + * @memberof ListAssistants401Response + */ + message?: string; } /** * Check if a given object implements the ListAssistants401Response interface. */ -export function instanceOfListAssistants401Response( - value: object, -): value is ListAssistants401Response { - return true; +export function instanceOfListAssistants401Response(value: object): value is ListAssistants401Response { + return true; } -export function ListAssistants401ResponseFromJSON( - json: any, -): ListAssistants401Response { - return ListAssistants401ResponseFromJSONTyped(json, false); +export function ListAssistants401ResponseFromJSON(json: any): ListAssistants401Response { + return ListAssistants401ResponseFromJSONTyped(json, false); } -export function ListAssistants401ResponseFromJSONTyped( - json: any, - ignoreDiscriminator: boolean, -): ListAssistants401Response { - if (json == null) { - return json; - } - return { - message: json["message"] == null ? undefined : json["message"], - }; +export function ListAssistants401ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants401Response { + if (json == null) { + return json; + } + return { + + 'message': json['message'] == null ? undefined : json['message'], + }; } -export function ListAssistants401ResponseToJSON( - json: any, -): ListAssistants401Response { - return ListAssistants401ResponseToJSONTyped(json, false); +export function ListAssistants401ResponseToJSON(json: any): ListAssistants401Response { + return ListAssistants401ResponseToJSONTyped(json, false); } -export function ListAssistants401ResponseToJSONTyped( - value?: ListAssistants401Response | null, - ignoreDiscriminator: boolean = false, -): any { - if (value == null) { - return value; - } +export function ListAssistants401ResponseToJSONTyped(value?: ListAssistants401Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } - return { - message: value["message"], - }; + return { + + 'message': value['message'], + }; } + diff --git a/packages/continue-sdk/typescript/api/src/models/ListAssistants404Response.ts b/packages/continue-sdk/typescript/api/src/models/ListAssistants404Response.ts index 8483c508b..b90a21824 100644 --- a/packages/continue-sdk/typescript/api/src/models/ListAssistants404Response.ts +++ b/packages/continue-sdk/typescript/api/src/models/ListAssistants404Response.ts @@ -2,73 +2,64 @@ /* eslint-disable */ /** * Continue Hub IDE API - * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. * * The version of the OpenAPI document: 1.0.0 - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ -import { mapValues } from "../runtime"; +import { mapValues } from '../runtime'; /** - * + * * @export * @interface ListAssistants404Response */ export interface ListAssistants404Response { - /** - * - * @type {string} - * @memberof ListAssistants404Response - */ - message?: string; + /** + * + * @type {string} + * @memberof ListAssistants404Response + */ + message?: string; } /** * Check if a given object implements the ListAssistants404Response interface. */ -export function instanceOfListAssistants404Response( - value: object, -): value is ListAssistants404Response { - return true; +export function instanceOfListAssistants404Response(value: object): value is ListAssistants404Response { + return true; } -export function ListAssistants404ResponseFromJSON( - json: any, -): ListAssistants404Response { - return ListAssistants404ResponseFromJSONTyped(json, false); +export function ListAssistants404ResponseFromJSON(json: any): ListAssistants404Response { + return ListAssistants404ResponseFromJSONTyped(json, false); } -export function ListAssistants404ResponseFromJSONTyped( - json: any, - ignoreDiscriminator: boolean, -): ListAssistants404Response { - if (json == null) { - return json; - } - return { - message: json["message"] == null ? undefined : json["message"], - }; +export function ListAssistants404ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListAssistants404Response { + if (json == null) { + return json; + } + return { + + 'message': json['message'] == null ? undefined : json['message'], + }; } -export function ListAssistants404ResponseToJSON( - json: any, -): ListAssistants404Response { - return ListAssistants404ResponseToJSONTyped(json, false); +export function ListAssistants404ResponseToJSON(json: any): ListAssistants404Response { + return ListAssistants404ResponseToJSONTyped(json, false); } -export function ListAssistants404ResponseToJSONTyped( - value?: ListAssistants404Response | null, - ignoreDiscriminator: boolean = false, -): any { - if (value == null) { - return value; - } +export function ListAssistants404ResponseToJSONTyped(value?: ListAssistants404Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } - return { - message: value["message"], - }; + return { + + 'message': value['message'], + }; } + diff --git a/packages/continue-sdk/typescript/api/src/models/ListOrganizations200Response.ts b/packages/continue-sdk/typescript/api/src/models/ListOrganizations200Response.ts new file mode 100644 index 000000000..812178a90 --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/ListOrganizations200Response.ts @@ -0,0 +1,74 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ListOrganizations200ResponseOrganizationsInner } from './ListOrganizations200ResponseOrganizationsInner'; +import { + ListOrganizations200ResponseOrganizationsInnerFromJSON, + ListOrganizations200ResponseOrganizationsInnerFromJSONTyped, + ListOrganizations200ResponseOrganizationsInnerToJSON, + ListOrganizations200ResponseOrganizationsInnerToJSONTyped, +} from './ListOrganizations200ResponseOrganizationsInner'; + +/** + * + * @export + * @interface ListOrganizations200Response + */ +export interface ListOrganizations200Response { + /** + * + * @type {Array} + * @memberof ListOrganizations200Response + */ + organizations: Array; +} + +/** + * Check if a given object implements the ListOrganizations200Response interface. + */ +export function instanceOfListOrganizations200Response(value: object): value is ListOrganizations200Response { + if (!('organizations' in value) || value['organizations'] === undefined) return false; + return true; +} + +export function ListOrganizations200ResponseFromJSON(json: any): ListOrganizations200Response { + return ListOrganizations200ResponseFromJSONTyped(json, false); +} + +export function ListOrganizations200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListOrganizations200Response { + if (json == null) { + return json; + } + return { + + 'organizations': ((json['organizations'] as Array).map(ListOrganizations200ResponseOrganizationsInnerFromJSON)), + }; +} + +export function ListOrganizations200ResponseToJSON(json: any): ListOrganizations200Response { + return ListOrganizations200ResponseToJSONTyped(json, false); +} + +export function ListOrganizations200ResponseToJSONTyped(value?: ListOrganizations200Response | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'organizations': ((value['organizations'] as Array).map(ListOrganizations200ResponseOrganizationsInnerToJSON)), + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/ListOrganizations200ResponseOrganizationsInner.ts b/packages/continue-sdk/typescript/api/src/models/ListOrganizations200ResponseOrganizationsInner.ts new file mode 100644 index 000000000..454de1ca0 --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/ListOrganizations200ResponseOrganizationsInner.ts @@ -0,0 +1,92 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface ListOrganizations200ResponseOrganizationsInner + */ +export interface ListOrganizations200ResponseOrganizationsInner { + /** + * Organization ID + * @type {string} + * @memberof ListOrganizations200ResponseOrganizationsInner + */ + id: string; + /** + * Organization name + * @type {string} + * @memberof ListOrganizations200ResponseOrganizationsInner + */ + name: string; + /** + * Pre-signed URL for the organization's icon + * @type {string} + * @memberof ListOrganizations200ResponseOrganizationsInner + */ + iconUrl?: string | null; + /** + * Organization slug + * @type {string} + * @memberof ListOrganizations200ResponseOrganizationsInner + */ + slug: string; +} + +/** + * Check if a given object implements the ListOrganizations200ResponseOrganizationsInner interface. + */ +export function instanceOfListOrganizations200ResponseOrganizationsInner(value: object): value is ListOrganizations200ResponseOrganizationsInner { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('slug' in value) || value['slug'] === undefined) return false; + return true; +} + +export function ListOrganizations200ResponseOrganizationsInnerFromJSON(json: any): ListOrganizations200ResponseOrganizationsInner { + return ListOrganizations200ResponseOrganizationsInnerFromJSONTyped(json, false); +} + +export function ListOrganizations200ResponseOrganizationsInnerFromJSONTyped(json: any, ignoreDiscriminator: boolean): ListOrganizations200ResponseOrganizationsInner { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'iconUrl': json['iconUrl'] == null ? undefined : json['iconUrl'], + 'slug': json['slug'], + }; +} + +export function ListOrganizations200ResponseOrganizationsInnerToJSON(json: any): ListOrganizations200ResponseOrganizationsInner { + return ListOrganizations200ResponseOrganizationsInnerToJSONTyped(json, false); +} + +export function ListOrganizations200ResponseOrganizationsInnerToJSONTyped(value?: ListOrganizations200ResponseOrganizationsInner | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'iconUrl': value['iconUrl'], + 'slug': value['slug'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/SyncSecretsRequest.ts b/packages/continue-sdk/typescript/api/src/models/SyncSecretsRequest.ts new file mode 100644 index 000000000..d3504056f --- /dev/null +++ b/packages/continue-sdk/typescript/api/src/models/SyncSecretsRequest.ts @@ -0,0 +1,82 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Continue Hub IDE API + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface SyncSecretsRequest + */ +export interface SyncSecretsRequest { + /** + * Array of Fully Qualified Secret Names to resolve + * @type {Array} + * @memberof SyncSecretsRequest + */ + fqsns: Array; + /** + * Organization ID to scope secret resolution to + * @type {string} + * @memberof SyncSecretsRequest + */ + orgScopeId?: string | null; + /** + * Organization slug to scope secret resolution to + * @type {string} + * @memberof SyncSecretsRequest + */ + orgScopeSlug?: string | null; +} + +/** + * Check if a given object implements the SyncSecretsRequest interface. + */ +export function instanceOfSyncSecretsRequest(value: object): value is SyncSecretsRequest { + if (!('fqsns' in value) || value['fqsns'] === undefined) return false; + return true; +} + +export function SyncSecretsRequestFromJSON(json: any): SyncSecretsRequest { + return SyncSecretsRequestFromJSONTyped(json, false); +} + +export function SyncSecretsRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): SyncSecretsRequest { + if (json == null) { + return json; + } + return { + + 'fqsns': json['fqsns'], + 'orgScopeId': json['orgScopeId'] == null ? undefined : json['orgScopeId'], + 'orgScopeSlug': json['orgScopeSlug'] == null ? undefined : json['orgScopeSlug'], + }; +} + +export function SyncSecretsRequestToJSON(json: any): SyncSecretsRequest { + return SyncSecretsRequestToJSONTyped(json, false); +} + +export function SyncSecretsRequestToJSONTyped(value?: SyncSecretsRequest | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'fqsns': value['fqsns'], + 'orgScopeId': value['orgScopeId'], + 'orgScopeSlug': value['orgScopeSlug'], + }; +} + diff --git a/packages/continue-sdk/typescript/api/src/models/index.ts b/packages/continue-sdk/typescript/api/src/models/index.ts index ccbb2cafa..da68ee7ca 100644 --- a/packages/continue-sdk/typescript/api/src/models/index.ts +++ b/packages/continue-sdk/typescript/api/src/models/index.ts @@ -1,6 +1,17 @@ /* tslint:disable */ /* eslint-disable */ -export * from "./ListAssistants200ResponseInner"; -export * from "./ListAssistants200ResponseInnerConfigResult"; -export * from "./ListAssistants401Response"; -export * from "./ListAssistants404Response"; +export * from './GetAssistant200Response'; +export * from './GetAssistant403Response'; +export * from './GetAssistant404Response'; +export * from './GetFreeTrialStatus200Response'; +export * from './GetModelsAddOnCheckoutUrl200Response'; +export * from './GetModelsAddOnCheckoutUrl500Response'; +export * from './GetPolicy200Response'; +export * from './ListAssistantFullSlugs429Response'; +export * from './ListAssistants200ResponseInner'; +export * from './ListAssistants200ResponseInnerConfigResult'; +export * from './ListAssistants401Response'; +export * from './ListAssistants404Response'; +export * from './ListOrganizations200Response'; +export * from './ListOrganizations200ResponseOrganizationsInner'; +export * from './SyncSecretsRequest'; diff --git a/packages/continue-sdk/typescript/api/src/runtime.ts b/packages/continue-sdk/typescript/api/src/runtime.ts index 3679049f8..759761f32 100644 --- a/packages/continue-sdk/typescript/api/src/runtime.ts +++ b/packages/continue-sdk/typescript/api/src/runtime.ts @@ -2,97 +2,86 @@ /* eslint-disable */ /** * Continue Hub IDE API - * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. + * API for Continue IDE to fetch assistants and other related information. These endpoints are primarily used by the Continue IDE extensions for VS Code and JetBrains. * * The version of the OpenAPI document: 1.0.0 - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ + export const BASE_PATH = "https://api.continue.dev".replace(/\/+$/, ""); export interface ConfigurationParameters { - basePath?: string; // override base path - fetchApi?: FetchAPI; // override for fetch implementation - middleware?: Middleware[]; // middleware to apply before/after fetch requests - queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings - username?: string; // parameter for basic security - password?: string; // parameter for basic security - apiKey?: - | string - | Promise - | ((name: string) => string | Promise); // parameter for apiKey security - accessToken?: - | string - | Promise - | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security - headers?: HTTPHeaders; //header params we want to use on every request - credentials?: RequestCredentials; //value for the credentials param we want to use on each request + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | Promise | ((name: string) => string | Promise); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request } export class Configuration { - constructor(private configuration: ConfigurationParameters = {}) {} + constructor(private configuration: ConfigurationParameters = {}) {} - set config(configuration: Configuration) { - this.configuration = configuration; - } - - get basePath(): string { - return this.configuration.basePath != null - ? this.configuration.basePath - : BASE_PATH; - } - - get fetchApi(): FetchAPI | undefined { - return this.configuration.fetchApi; - } - - get middleware(): Middleware[] { - return this.configuration.middleware || []; - } - - get queryParamsStringify(): (params: HTTPQuery) => string { - return this.configuration.queryParamsStringify || querystring; - } - - get username(): string | undefined { - return this.configuration.username; - } - - get password(): string | undefined { - return this.configuration.password; - } - - get apiKey(): ((name: string) => string | Promise) | undefined { - const apiKey = this.configuration.apiKey; - if (apiKey) { - return typeof apiKey === "function" ? apiKey : () => apiKey; + set config(configuration: Configuration) { + this.configuration = configuration; } - return undefined; - } - get accessToken(): - | ((name?: string, scopes?: string[]) => string | Promise) - | undefined { - const accessToken = this.configuration.accessToken; - if (accessToken) { - return typeof accessToken === "function" - ? accessToken - : async () => accessToken; + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; } - return undefined; - } - get headers(): HTTPHeaders | undefined { - return this.configuration.headers; - } + get fetchApi(): FetchAPI | undefined { + return this.configuration.fetchApi; + } - get credentials(): RequestCredentials | undefined { - return this.configuration.credentials; - } + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string | Promise) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } } export const DefaultConfig = new Configuration(); @@ -101,429 +90,342 @@ export const DefaultConfig = new Configuration(); * This is the base class for all generated API classes. */ export class BaseAPI { - private static readonly jsonRegex = new RegExp( - "^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", - "i", - ); - private middleware: Middleware[]; - constructor(protected configuration = DefaultConfig) { - this.middleware = configuration.middleware; - } + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private middleware: Middleware[]; - withMiddleware(this: T, ...middlewares: Middleware[]) { - const next = this.clone(); - next.middleware = next.middleware.concat(...middlewares); - return next; - } - - withPreMiddleware( - this: T, - ...preMiddlewares: Array - ) { - const middlewares = preMiddlewares.map((pre) => ({ pre })); - return this.withMiddleware(...middlewares); - } - - withPostMiddleware( - this: T, - ...postMiddlewares: Array - ) { - const middlewares = postMiddlewares.map((post) => ({ post })); - return this.withMiddleware(...middlewares); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * @param mime - MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - protected isJsonMime(mime: string | null | undefined): boolean { - if (!mime) { - return false; - } - return BaseAPI.jsonRegex.test(mime); - } - - protected async request( - context: RequestOpts, - initOverrides?: RequestInit | InitOverrideFunction, - ): Promise { - const { url, init } = await this.createFetchParams(context, initOverrides); - const response = await this.fetchApi(url, init); - if (response && response.status >= 200 && response.status < 300) { - return response; - } - throw new ResponseError(response, "Response returned an error code"); - } - - private async createFetchParams( - context: RequestOpts, - initOverrides?: RequestInit | InitOverrideFunction, - ) { - let url = this.configuration.basePath + context.path; - if ( - context.query !== undefined && - Object.keys(context.query).length !== 0 - ) { - // only add the querystring to the URL if there are query parameters. - // this is done to avoid urls ending with a "?" character which buggy webservers - // do not handle correctly sometimes. - url += "?" + this.configuration.queryParamsStringify(context.query); + constructor(protected configuration = DefaultConfig) { + this.middleware = configuration.middleware; } - const headers = Object.assign( - {}, - this.configuration.headers, - context.headers, - ); - Object.keys(headers).forEach((key) => - headers[key] === undefined ? delete headers[key] : {}, - ); - - const initOverrideFn = - typeof initOverrides === "function" - ? initOverrides - : async () => initOverrides; - - const initParams = { - method: context.method, - headers, - body: context.body, - credentials: this.configuration.credentials, - }; - - const overriddenInit: RequestInit = { - ...initParams, - ...(await initOverrideFn({ - init: initParams, - context, - })), - }; - - let body: any; - if ( - isFormData(overriddenInit.body) || - overriddenInit.body instanceof URLSearchParams || - isBlob(overriddenInit.body) - ) { - body = overriddenInit.body; - } else if (this.isJsonMime(headers["Content-Type"])) { - body = JSON.stringify(overriddenInit.body); - } else { - body = overriddenInit.body; + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; } - const init: RequestInit = { - ...overriddenInit, - body, - }; - - return { url, init }; - } - - private fetchApi = async (url: string, init: RequestInit) => { - let fetchParams = { url, init }; - for (const middleware of this.middleware) { - if (middleware.pre) { - fetchParams = - (await middleware.pre({ - fetch: this.fetchApi, - ...fetchParams, - })) || fetchParams; - } + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); } - let response: Response | undefined = undefined; - try { - response = await (this.configuration.fetchApi || fetch)( - fetchParams.url, - fetchParams.init, - ); - } catch (e) { - for (const middleware of this.middleware) { - if (middleware.onError) { - response = - (await middleware.onError({ - fetch: this.fetchApi, - url: fetchParams.url, - init: fetchParams.init, - error: e, - response: response ? response.clone() : undefined, - })) || response; + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + protected isJsonMime(mime: string | null | undefined): boolean { + if (!mime) { + return false; } - } - if (response === undefined) { - if (e instanceof Error) { - throw new FetchError( - e, - "The request failed and the interceptors did not return an alternative response", - ); + return BaseAPI.jsonRegex.test(mime); + } + + protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { + const { url, init } = await this.createFetchParams(context, initOverrides); + const response = await this.fetchApi(url, init); + if (response && (response.status >= 200 && response.status < 300)) { + return response; + } + throw new ResponseError(response, 'Response returned an error code'); + } + + private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + + const headers = Object.assign({}, this.configuration.headers, context.headers); + Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {}); + + const initOverrideFn = + typeof initOverrides === "function" + ? initOverrides + : async () => initOverrides; + + const initParams = { + method: context.method, + headers, + body: context.body, + credentials: this.configuration.credentials, + }; + + const overriddenInit: RequestInit = { + ...initParams, + ...(await initOverrideFn({ + init: initParams, + context, + })) + }; + + let body: any; + if (isFormData(overriddenInit.body) + || (overriddenInit.body instanceof URLSearchParams) + || isBlob(overriddenInit.body)) { + body = overriddenInit.body; + } else if (this.isJsonMime(headers['Content-Type'])) { + body = JSON.stringify(overriddenInit.body); } else { - throw e; + body = overriddenInit.body; } - } - } - for (const middleware of this.middleware) { - if (middleware.post) { - response = - (await middleware.post({ - fetch: this.fetchApi, - url: fetchParams.url, - init: fetchParams.init, - response: response.clone(), - })) || response; - } - } - return response; - }; - /** - * Create a shallow clone of `this` by constructing a new instance - * and then shallow cloning data members. - */ - private clone(this: T): T { - const constructor = this.constructor as any; - const next = new constructor(this.configuration); - next.middleware = this.middleware.slice(); - return next; - } -} + const init: RequestInit = { + ...overriddenInit, + body + }; + + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response: Response | undefined = undefined; + try { + response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init); + } catch (e) { + for (const middleware of this.middleware) { + if (middleware.onError) { + response = await middleware.onError({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + error: e, + response: response ? response.clone() : undefined, + }) || response; + } + } + if (response === undefined) { + if (e instanceof Error) { + throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } + } + } + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; function isBlob(value: any): value is Blob { - return typeof Blob !== "undefined" && value instanceof Blob; + return typeof Blob !== 'undefined' && value instanceof Blob; } function isFormData(value: any): value is FormData { - return typeof FormData !== "undefined" && value instanceof FormData; + return typeof FormData !== "undefined" && value instanceof FormData; } export class ResponseError extends Error { - override name: "ResponseError" = "ResponseError"; - constructor( - public response: Response, - msg?: string, - ) { - super(msg); - } + override name: "ResponseError" = "ResponseError"; + constructor(public response: Response, msg?: string) { + super(msg); + } } export class FetchError extends Error { - override name: "FetchError" = "FetchError"; - constructor( - public cause: Error, - msg?: string, - ) { - super(msg); - } + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { + super(msg); + } } export class RequiredError extends Error { - override name: "RequiredError" = "RequiredError"; - constructor( - public field: string, - msg?: string, - ) { - super(msg); - } + override name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } } export const COLLECTION_FORMATS = { - csv: ",", - ssv: " ", - tsv: "\t", - pipes: "|", + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", }; -export type FetchAPI = WindowOrWorkerGlobalScope["fetch"]; +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; export type Json = any; -export type HTTPMethod = - | "GET" - | "POST" - | "PUT" - | "PATCH" - | "DELETE" - | "OPTIONS" - | "HEAD"; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; export type HTTPHeaders = { [key: string]: string }; -export type HTTPQuery = { - [key: string]: - | string - | number - | null - | boolean - | Array - | Set - | HTTPQuery; -}; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | Set | HTTPQuery }; export type HTTPBody = Json | FormData | URLSearchParams; -export type HTTPRequestInit = { - headers?: HTTPHeaders; - method: HTTPMethod; - credentials?: RequestCredentials; - body?: HTTPBody; -}; -export type ModelPropertyNaming = - | "camelCase" - | "snake_case" - | "PascalCase" - | "original"; +export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody }; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; -export type InitOverrideFunction = (requestContext: { - init: HTTPRequestInit; - context: RequestOpts; -}) => Promise; +export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise export interface FetchParams { - url: string; - init: RequestInit; + url: string; + init: RequestInit; } export interface RequestOpts { - path: string; - method: HTTPMethod; - headers: HTTPHeaders; - query?: HTTPQuery; - body?: HTTPBody; + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; } -export function querystring(params: HTTPQuery, prefix: string = ""): string { - return Object.keys(params) - .map((key) => querystringSingleKey(key, params[key], prefix)) - .filter((part) => part.length > 0) - .join("&"); +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map(key => querystringSingleKey(key, params[key], prefix)) + .filter(part => part.length > 0) + .join('&'); } -function querystringSingleKey( - key: string, - value: - | string - | number - | null - | undefined - | boolean - | Array - | Set - | HTTPQuery, - keyPrefix: string = "", -): string { - const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key); - if (value instanceof Array) { - const multiValue = value - .map((singleValue) => encodeURIComponent(String(singleValue))) - .join(`&${encodeURIComponent(fullKey)}=`); - return `${encodeURIComponent(fullKey)}=${multiValue}`; - } - if (value instanceof Set) { - const valueAsArray = Array.from(value); - return querystringSingleKey(key, valueAsArray, keyPrefix); - } - if (value instanceof Date) { - return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; - } - if (value instanceof Object) { - return querystring(value as HTTPQuery, fullKey); - } - return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; +function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array | Set | HTTPQuery, keyPrefix: string = ''): string { + const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key); + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Set) { + const valueAsArray = Array.from(value); + return querystringSingleKey(key, valueAsArray, keyPrefix); + } + if (value instanceof Date) { + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; } export function exists(json: any, key: string) { - const value = json[key]; - return value !== null && value !== undefined; + const value = json[key]; + return value !== null && value !== undefined; } export function mapValues(data: any, fn: (item: any) => any) { return Object.keys(data).reduce( (acc, key) => ({ ...acc, [key]: fn(data[key]) }), - {}, + {} ); } export function canConsumeForm(consumes: Consume[]): boolean { - for (const consume of consumes) { - if ("multipart/form-data" === consume.contentType) { - return true; + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } } - } - return false; + return false; } export interface Consume { - contentType: string; + contentType: string; } export interface RequestContext { - fetch: FetchAPI; - url: string; - init: RequestInit; + fetch: FetchAPI; + url: string; + init: RequestInit; } export interface ResponseContext { - fetch: FetchAPI; - url: string; - init: RequestInit; - response: Response; + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; } export interface ErrorContext { - fetch: FetchAPI; - url: string; - init: RequestInit; - error: unknown; - response?: Response; + fetch: FetchAPI; + url: string; + init: RequestInit; + error: unknown; + response?: Response; } export interface Middleware { - pre?(context: RequestContext): Promise; - post?(context: ResponseContext): Promise; - onError?(context: ErrorContext): Promise; + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; + onError?(context: ErrorContext): Promise; } export interface ApiResponse { - raw: Response; - value(): Promise; + raw: Response; + value(): Promise; } export interface ResponseTransformer { - (json: any): T; + (json: any): T; } export class JSONApiResponse { - constructor( - public raw: Response, - private transformer: ResponseTransformer = (jsonValue: any) => jsonValue, - ) {} + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} - async value(): Promise { - return this.transformer(await this.raw.json()); - } + async value(): Promise { + return this.transformer(await this.raw.json()); + } } export class VoidApiResponse { - constructor(public raw: Response) {} + constructor(public raw: Response) {} - async value(): Promise { - return undefined; - } + async value(): Promise { + return undefined; + } } export class BlobApiResponse { - constructor(public raw: Response) {} + constructor(public raw: Response) {} - async value(): Promise { - return await this.raw.blob(); - } + async value(): Promise { + return await this.raw.blob(); + }; } export class TextApiResponse { - constructor(public raw: Response) {} + constructor(public raw: Response) {} - async value(): Promise { - return await this.raw.text(); - } + async value(): Promise { + return await this.raw.text(); + }; } diff --git a/packages/continue-sdk/typescript/api/tsconfig.json b/packages/continue-sdk/typescript/api/tsconfig.json index e69c9c2f7..250280d9a 100644 --- a/packages/continue-sdk/typescript/api/tsconfig.json +++ b/packages/continue-sdk/typescript/api/tsconfig.json @@ -5,7 +5,12 @@ "module": "commonjs", "moduleResolution": "node", "outDir": "dist", - "typeRoots": ["node_modules/@types"] + "typeRoots": [ + "node_modules/@types" + ] }, - "exclude": ["dist", "node_modules"] + "exclude": [ + "dist", + "node_modules" + ] } diff --git a/packages/continue-sdk/typescript/build.sh b/packages/continue-sdk/typescript/build.sh index 17b564e35..af5c95441 100755 --- a/packages/continue-sdk/typescript/build.sh +++ b/packages/continue-sdk/typescript/build.sh @@ -4,7 +4,7 @@ cd api && npm run build cd .. # Build the SDK -tsc +npx tsc # Create the necessary directory structure in dist mkdir -p dist/api/dist diff --git a/packages/continue-sdk/typescript/package-lock.json b/packages/continue-sdk/typescript/package-lock.json index 5eb8e7999..0e5fb590f 100644 --- a/packages/continue-sdk/typescript/package-lock.json +++ b/packages/continue-sdk/typescript/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/sdk", - "version": "0.0.7", + "version": "0.0.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/sdk", - "version": "0.0.7", + "version": "0.0.12", "license": "Apache-2.0", "dependencies": { "openai": "^4.96.2" diff --git a/packages/continue-sdk/typescript/tsconfig.json b/packages/continue-sdk/typescript/tsconfig.json index 14c7265d1..a21b3f5b6 100644 --- a/packages/continue-sdk/typescript/tsconfig.json +++ b/packages/continue-sdk/typescript/tsconfig.json @@ -7,7 +7,6 @@ "strict": true, "outDir": "dist", "declaration": true, - "types": ["node", "jest"], "skipLibCheck": true, "isolatedModules": true }, From 107dae9c62cd2712088369c75d8ab07a9dda67bb Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 18:01:56 -0700 Subject: [PATCH 063/178] bump sdk version --- packages/continue-sdk/typescript/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/continue-sdk/typescript/package.json b/packages/continue-sdk/typescript/package.json index 1d0544e9d..7b67a3219 100644 --- a/packages/continue-sdk/typescript/package.json +++ b/packages/continue-sdk/typescript/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/sdk", - "version": "0.0.12", + "version": "0.0.13", "description": "SDK for Continue.dev", "main": "dist/src/index.js", "types": "dist/src/index.d.ts", From 58c721b8528b231f6499ae93935aa8f8b0f845c9 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 16 Jul 2025 12:42:24 +0530 Subject: [PATCH 064/178] fix: internal permalinks with file extensions --- docs/customize/context/documentation.mdx | 2 +- docs/customize/deep-dives/slash-commands.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/customize/context/documentation.mdx b/docs/customize/context/documentation.mdx index d2bb0f5f0..38403eedb 100644 --- a/docs/customize/context/documentation.mdx +++ b/docs/customize/context/documentation.mdx @@ -54,7 +54,7 @@ The `@Docs` context provider works by ### Hub `docs` Blocks -@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs). +@Docs uses [`docs` blocks](../../hub/blocks/block-types#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs). ### Through the `@Docs` Context Provider diff --git a/docs/customize/deep-dives/slash-commands.mdx b/docs/customize/deep-dives/slash-commands.mdx index 7057575bd..81579d3ed 100644 --- a/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/customize/deep-dives/slash-commands.mdx @@ -15,7 +15,7 @@ Slash commands can be combined with additional instructions, including [context ### Assistant prompt blocks -The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx). +The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx). ### Prompt files From 7c82166a5ab9758edf1a53a95e930f966b47667f Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 16 Jul 2025 12:45:25 +0530 Subject: [PATCH 065/178] fix .mdx links --- docs/customize/context/codebase.mdx | 2 +- docs/customize/model-roles/embeddings.mdx | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/customize/context/codebase.mdx b/docs/customize/context/codebase.mdx index 674167045..5cad74c59 100644 --- a/docs/customize/context/codebase.mdx +++ b/docs/customize/context/codebase.mdx @@ -94,4 +94,4 @@ If you need to force a refresh of the index, reload the VS Code window with Date: Wed, 16 Jul 2025 18:04:59 +0530 Subject: [PATCH 066/178] fix: double slash on opening hub urls --- core/core.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index 915099a3e..dc6651eaa 100644 --- a/core/core.ts +++ b/core/core.ts @@ -359,7 +359,10 @@ export class Core { on("controlPlane/openUrl", async (msg) => { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); - let url = `${env.APP_URL}${msg.data.path}`; + const urlPath = msg.data.path.startsWith("/") + ? msg.data.path.slice(1) + : msg.data.path; + let url = `${env.APP_URL}${urlPath}`; if (msg.data.orgSlug) { url += `?org=${msg.data.orgSlug}`; } From 87d55c5b4d9e5ec662a19018ee2cb4bbeb433070 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 16 Jul 2025 16:08:06 -0700 Subject: [PATCH 067/178] fix: test fix for fetch package and publish version with improved error logging --- packages/fetch/package-lock.json | 4 ++-- packages/fetch/package.json | 2 +- packages/fetch/src/stream.test.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/fetch/package-lock.json b/packages/fetch/package-lock.json index b832b32fd..a9a4742ff 100644 --- a/packages/fetch/package-lock.json +++ b/packages/fetch/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/fetch", - "version": "1.0.15", + "version": "1.0.16", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/fetch", - "version": "1.0.15", + "version": "1.0.16", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", diff --git a/packages/fetch/package.json b/packages/fetch/package.json index 5cd0a38e4..b50a7ce84 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.15", + "version": "1.0.16", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/fetch/src/stream.test.ts b/packages/fetch/src/stream.test.ts index eba47de26..d52221954 100644 --- a/packages/fetch/src/stream.test.ts +++ b/packages/fetch/src/stream.test.ts @@ -86,7 +86,7 @@ describe("parseDataLine", () => { test("parseDataLine should throw error when data contains error field", () => { const line = 'data: {"error":"something went wrong"}'; expect(() => parseDataLine(line)).toThrow( - "Error streaming response: something went wrong", + 'Error streaming response: "something went wrong"', ); }); From 0ecf32c37d1d94eefc6a07daaaac547f94e13662 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 16 Jul 2025 16:11:53 -0700 Subject: [PATCH 068/178] bump fetch version in openai-adapters, but don't publish a stable release of openai-adapters --- packages/openai-adapters/package-lock.json | 9 ++++----- packages/openai-adapters/package.json | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 97d95ef12..c168a46cd 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.15", + "@continuedev/fetch": "^1.0.16", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", @@ -1418,10 +1418,9 @@ } }, "node_modules/@continuedev/fetch": { - "version": "1.0.15", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.15.tgz", - "integrity": "sha512-49jLwAwAOczcFLfa2Og9+c+qxrq+Z6+p+B5BbXgHENrQIsuST1liKTXEiga5gSVAyHD+m+1Ftl4jqRq2oxMngw==", - "license": "Apache-2.0", + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.16.tgz", + "integrity": "sha512-LSjVbTKA+UwqCjV8x45sfJQGtG/iekkqCYpSJsakY0ruad807swwEuuui5luuYVUhJAZZpVfZzeJArHfjiJJSw==", "dependencies": { "@continuedev/config-types": "^1.0.5", "follow-redirects": "^1.15.6", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index f7c7d3133..11aedc4c5 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -16,7 +16,7 @@ "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.15", + "@continuedev/fetch": "^1.0.16", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", From 717e11321b9ece0781b9b531a3a2b329ae339b42 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 16 Jul 2025 17:26:01 -0700 Subject: [PATCH 069/178] Update bug_report.yml --- .github/ISSUE_TEMPLATE/bug_report.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 4a0595a38..4ff2b89da 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -11,6 +11,7 @@ body: attributes: label: Before submitting your bug report options: + - label: I've tried using the "Ask AI" feature on the [Continue docs site](https://docs.continue.dev/) to see if the docs have an answer - label: I believe this is a bug. I'll try to join the [Continue Discord](https://discord.gg/NWtdYexhMs) for questions required: false - label: I'm not able to find an [open issue](https://github.com/continuedev/continue/issues?q=is%3Aopen+is%3Aissue) that reports the same bug From a69900c1462110a991ece8f5857de6abc3e1cc77 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 16 Jul 2025 17:27:44 -0700 Subject: [PATCH 070/178] Update bug_report.yml --- .github/ISSUE_TEMPLATE/bug_report.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 4ff2b89da..cc85d0d0a 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -12,6 +12,7 @@ body: label: Before submitting your bug report options: - label: I've tried using the "Ask AI" feature on the [Continue docs site](https://docs.continue.dev/) to see if the docs have an answer + required: false - label: I believe this is a bug. I'll try to join the [Continue Discord](https://discord.gg/NWtdYexhMs) for questions required: false - label: I'm not able to find an [open issue](https://github.com/continuedev/continue/issues?q=is%3Aopen+is%3Aissue) that reports the same bug From c132986c95d9fe6aafe68c0d47e71f783f16bc3d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 17 Jul 2025 16:10:21 +0200 Subject: [PATCH 071/178] remove YAML maxDepth --- core/config/yaml/loadYaml.ts | 1 - docs/customize/context/documentation.mdx | 1 - docs/reference.mdx | 3 --- packages/config-yaml/src/schemas/index.ts | 1 - 4 files changed, 6 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 04c19b326..9398e377d 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -235,7 +235,6 @@ async function configYamlToContinueConfig(options: { startUrl: doc.startUrl, rootUrl: doc.rootUrl, faviconUrl: doc.faviconUrl, - maxDepth: doc.maxDepth, useLocalCrawling: doc.useLocalCrawling, })); diff --git a/docs/customize/context/documentation.mdx b/docs/customize/context/documentation.mdx index d2bb0f5f0..433b96d30 100644 --- a/docs/customize/context/documentation.mdx +++ b/docs/customize/context/documentation.mdx @@ -354,7 +354,6 @@ The following configuration example includes: - title: My Private Docs startUrl: http://10.2.1.2/docs faviconUrl: http://10.2.1.2/docs/assets/favicon.ico - maxDepth: 4 useLocalCrawling: true ``` diff --git a/docs/reference.mdx b/docs/reference.mdx index 9a9381622..931bb3f54 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -357,8 +357,6 @@ List of documentation sites to index. - `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs - -- `maxDepth`: Maximum link depth for crawling. Default `4` - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). - `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. @@ -507,7 +505,6 @@ context: params: startUrl: https://docs.example.com/introduction rootUrl: https://docs.example.com - maxDepth: 3 mcpServers: - name: DevServer command: npm diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 4ac2aa1f5..cca4fcf32 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -42,7 +42,6 @@ const docSchema = z.object({ startUrl: z.string(), rootUrl: z.string().optional(), faviconUrl: z.string().optional(), - maxDepth: z.number().optional(), useLocalCrawling: z.boolean().optional(), }); From eba3a3e65acb40aa837655635cee07d6a1c6f061 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 17 Jul 2025 16:57:38 +0200 Subject: [PATCH 072/178] remove duplicate getWorkspaceConfigs logic and only load for json --- core/config/load.ts | 30 ++++++++++++++++++- core/config/profile/doLoadConfig.ts | 21 ------------- core/config/types.ts | 2 -- core/index.d.ts | 2 -- core/protocol/ide.ts | 2 -- core/protocol/messenger/messageIde.ts | 5 ---- core/protocol/messenger/reverseMessageIde.ts | 4 --- core/util/filesystem.ts | 5 ---- .../constants/MessageTypes.kt | 1 - .../continue/IdeProtocolClient.kt | 5 ---- .../continue/IntelliJIde.kt | 23 -------------- .../continueintellijextension/types.kt | 12 -------- extensions/vscode/src/VsCodeIde.ts | 27 ----------------- .../vscode/src/extension/VsCodeMessenger.ts | 4 --- 14 files changed, 29 insertions(+), 114 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index a5da010f9..0836fc13b 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -19,6 +19,7 @@ import { ContinueRcJson, CustomContextProvider, EmbeddingsProviderDescription, + FileType, IContextProvider, IDE, IdeInfo, @@ -64,6 +65,7 @@ import { localPathToUri } from "../util/pathToUri"; import { getToolsForIde } from "../tools"; import { resolveRelativePathInDir } from "../util/ideUtils"; +import { joinPathsToUri } from "../util/uri"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; import { getModelByRole, @@ -72,6 +74,32 @@ import { } from "./util"; import { validateConfig } from "./validation.js"; +async function getWorkspaceRcConfigs(ide: IDE): Promise { + try { + const workspaces = await ide.getWorkspaceDirs(); + const rcFiles = await Promise.all( + workspaces.map(async (dir) => { + const ls = await ide.listDir(dir); + const rcFiles = ls + .filter( + (entry) => + (entry[1] === FileType.File || + entry[1] === FileType.SymbolicLink) && + entry[0].endsWith(".continuerc.json"), + ) + .map((entry) => joinPathsToUri(dir, entry[0])); + return await Promise.all(rcFiles.map(ide.readFile)); + }), + ); + return rcFiles + .flat() + .map((file) => JSONC.parse(file) as unknown as ContinueRcJson); + } catch (e) { + console.debug("Failed to load workspace configs: ", e); + return []; + } +} + export function resolveSerializedConfig( filepath: string, ): SerializedContinueConfig { @@ -876,7 +904,6 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) { async function loadContinueConfigFromJson( ide: IDE, - workspaceConfigs: ContinueRcJson[], ideSettings: IdeSettings, ideInfo: IdeInfo, uniqueId: string, @@ -884,6 +911,7 @@ async function loadContinueConfigFromJson( workOsAccessToken: string | undefined, overrideConfigJson: SerializedContinueConfig | undefined, ): Promise> { + const workspaceConfigs = await getWorkspaceRcConfigs(ide); // Serialized config let { config: serialized, diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 1a5d27ab9..8407154e7 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -10,7 +10,6 @@ import { import { ContinueConfig, - ContinueRcJson, IDE, IdeSettings, ILLMLogger, @@ -86,7 +85,6 @@ export default async function doLoadConfig(options: { packageIdentifier, } = options; - const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); const uniqueId = await ide.getUniqueId(); const ideSettings = await ideSettingsPromise; @@ -126,7 +124,6 @@ export default async function doLoadConfig(options: { } else { const result = await loadContinueConfigFromJson( ide, - workspaceConfigs, ideSettings, ideInfo, uniqueId, @@ -366,21 +363,3 @@ async function injectControlPlaneProxyInfo( return config; } - -async function getWorkspaceConfigs(ide: IDE): Promise { - const ideInfo = await ide.getIdeInfo(); - let workspaceConfigs: ContinueRcJson[] = []; - - try { - workspaceConfigs = await ide.getWorkspaceConfigs(); - - // Config is sent over the wire from JB so we need to parse it - if (ideInfo.ideType === "jetbrains") { - workspaceConfigs = (workspaceConfigs as any).map(JSON.parse); - } - } catch (e) { - console.debug("Failed to load workspace configs: ", e); - } - - return workspaceConfigs; -} diff --git a/core/config/types.ts b/core/config/types.ts index 406f40ddd..c5ec3b45a 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -682,8 +682,6 @@ declare global { getWorkspaceDirs(): Promise; - getWorkspaceConfigs(): Promise; - fileExists(filepath: string): Promise; writeFile(path: string, contents: string): Promise; diff --git a/core/index.d.ts b/core/index.d.ts index a32e5532f..3358b6085 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -775,8 +775,6 @@ export interface IDE { getWorkspaceDirs(): Promise; - getWorkspaceConfigs(): Promise; - fileExists(fileUri: string): Promise; writeFile(path: string, contents: string): Promise; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index ba4cf4f88..b3cfe1164 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -1,5 +1,4 @@ import type { - ContinueRcJson, FileStatsMap, FileType, IDE, @@ -51,7 +50,6 @@ export type ToIdeFromWebviewOrCoreProtocol = { showLines: [{ filepath: string; startLine: number; endLine: number }, void]; readRangeInFile: [{ filepath: string; range: Range }, string]; getDiff: [{ includeUnstaged: boolean }, string[]]; - getWorkspaceConfigs: [undefined, ContinueRcJson[]]; getTerminalContents: [undefined, string]; getDebugLocals: [{ threadIndex: number }, string]; getTopLevelCallStackSources: [ diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 30d9b8177..5cc5d6787 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -2,7 +2,6 @@ import { FromIdeProtocol } from ".."; import { ToIdeFromWebviewOrCoreProtocol } from "../ide"; import type { - ContinueRcJson, FileStatsMap, FileType, IDE, @@ -114,10 +113,6 @@ export class MessageIde implements IDE { return this.request("getUniqueId", undefined); } - getWorkspaceConfigs(): Promise { - return this.request("getWorkspaceConfigs", undefined); - } - async getDiff(includeUnstaged: boolean) { return await this.request("getDiff", { includeUnstaged }); } diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index ba37c610d..9ce82db54 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -89,10 +89,6 @@ export class ReverseMessageIde { return this.ide.getUniqueId(); }); - this.on("getWorkspaceConfigs", () => { - return this.ide.getWorkspaceConfigs(); - }); - this.on("getIdeSettings", () => { return this.ide.getIdeSettings(); }); diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index f415e5e86..7075d75d5 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -2,7 +2,6 @@ import * as fs from "node:fs"; import { fileURLToPath } from "node:url"; import { - ContinueRcJson, FileStatsMap, FileType, IDE, @@ -135,10 +134,6 @@ class FileSystemIde implements IDE { return Promise.resolve("NOT_UNIQUE"); } - getWorkspaceConfigs(): Promise { - return Promise.resolve([]); - } - getDiff(includeUnstaged: boolean): Promise { return Promise.resolve([]); } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index d9eb5f62d..55b39d344 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -6,7 +6,6 @@ class MessageTypes { "readRangeInFile", "isTelemetryEnabled", "getUniqueId", - "getWorkspaceConfigs", "getDiff", "getTerminalContents", "getWorkspaceDirs", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 08a5e8d18..9a916a014 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -192,11 +192,6 @@ class IdeProtocolClient( respond(tags) } - "getWorkspaceConfigs" -> { - val configs = ide.getWorkspaceConfigs() - respond(configs) - } - "getTerminalContents" -> { val contents = ide.getTerminalContents() respond(contents) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index e1b6624d1..0d1cdd9a8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -152,29 +152,6 @@ class IntelliJIDE( return workspaceDirectories().toList() } - override suspend fun getWorkspaceConfigs(): List { - val workspaceDirs = this.getWorkspaceDirs() - - val configs = mutableListOf() - - for (workspaceDir in workspaceDirs) { - val dir = VirtualFileManager.getInstance().findFileByUrl(workspaceDir) - if (dir != null) { - val contents = dir.children.mapNotNull { it.toUriOrNull() } - - // Find any .continuerc.json files - for (file in contents) { - if (file.endsWith(".continuerc.json")) { - val fileContent = UriUtils.uriToFile(file).readText() - configs.add(fileContent) - } - } - } - } - - return configs as List - } - override suspend fun fileExists(filepath: String): Boolean { val file = UriUtils.uriToFile(filepath) return file.exists() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index dae734881..852196bfa 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -16,11 +16,6 @@ enum class FileType(val value: Int) { SYMBOLIC_LINK(64) } -enum class ConfigMergeType { - MERGE, - OVERWRITE -} - data class Position(val line: Int, val character: Int) data class Range(val start: Position, val end: Position) @@ -86,11 +81,6 @@ data class IdeSettings( val continueTestEnvironment: String ) -data class ContinueRcJson( - val mergeBehavior: ConfigMergeType -) - - interface IDE { suspend fun getIdeInfo(): IdeInfo @@ -119,8 +109,6 @@ interface IDE { suspend fun getWorkspaceDirs(): List - suspend fun getWorkspaceConfigs(): List - suspend fun fileExists(filepath: String): Boolean suspend fun writeFile(path: String, contents: String) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 91fb6154b..ca49014cf 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -14,7 +14,6 @@ import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; import { VsCodeWebviewProtocol } from "./webviewProtocol"; import type { - ContinueRcJson, FileStatsMap, FileType, IDE, @@ -240,32 +239,6 @@ class VsCodeIde implements IDE { return await this.ideUtils.getAvailableThreads(); } - async getWorkspaceConfigs() { - const workspaceDirs = - vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || []; - const configs: ContinueRcJson[] = []; - for (const workspaceDir of workspaceDirs) { - const files = await this.ideUtils.readDirectory(workspaceDir); - if (files === null) { - //Unlikely, but just in case... - continue; - } - for (const [filename, type] of files) { - if ( - (type === vscode.FileType.File || - type === vscode.FileType.SymbolicLink) && - filename === ".continuerc.json" - ) { - const contents = await this.readFile( - vscode.Uri.joinPath(workspaceDir, filename).toString(), - ); - configs.push(JSON.parse(contents)); - } - } - } - return configs; - } - async getWorkspaceDirs(): Promise { return this.ideUtils.getWorkspaceDirectories().map((uri) => uri.toString()); } diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 430c4fff1..41336cd24 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -418,10 +418,6 @@ export class VsCodeMessenger { return await ide.isTelemetryEnabled(); }); - this.onWebviewOrCore("getWorkspaceConfigs", async (msg) => { - return await ide.getWorkspaceConfigs(); - }); - this.onWebviewOrCore("getUniqueId", async (msg) => { return await ide.getUniqueId(); }); From c82d1fa1caf3b7928d3e5042426cb8b1ddf49aba Mon Sep 17 00:00:00 2001 From: Huy Huynh Date: Thu, 17 Jul 2025 17:05:29 -0300 Subject: [PATCH 073/178] docs: Fix Codestral autocomplete setup - Azure AI Foundry FIM endpoint deprecated --- docs/customize/model-providers/top-level/azure.mdx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/customize/model-providers/top-level/azure.mdx b/docs/customize/model-providers/top-level/azure.mdx index 26392fe1b..c91404df9 100644 --- a/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/customize/model-providers/top-level/azure.mdx @@ -48,7 +48,13 @@ We recommend configuring **GPT-4o** as your chat model. ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral: +We recommend configuring **Codestral** as your autocomplete model. + + +**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint. + + +If you use Azure Machine Learning Studio to deploy Codestral: From ce26a8439d9acaf13c37875265a4071c1552fc04 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 18 Jul 2025 11:40:55 +0200 Subject: [PATCH 074/178] fix: don't stringify os methods --- core/tools/definitions/runTerminalCommand.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index f9ddd4f9a..fe5e032de 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -20,7 +20,7 @@ export function getPreferredShell(): string { } } -export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`; +export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`; export const runTerminalCommandTool: Tool = { type: "function", From f1f4d1f09d7563546b98accc2763899c150909d2 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 18 Jul 2025 22:38:55 +0530 Subject: [PATCH 075/178] chore: add unit tests for file click on codeblock --- .../CodeBlock/CodeBlockPreview.test.tsx | 83 +++++++++++++++++++ .../extensions/CodeBlock/CodeBlockPreview.tsx | 2 +- 2 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.test.tsx diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.test.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.test.tsx new file mode 100644 index 000000000..8478b56e5 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.test.tsx @@ -0,0 +1,83 @@ +import { screen } from "@testing-library/react"; +import { NodeViewProps } from "@tiptap/react"; +import { ContextItemWithId } from "core"; +import { beforeEach, describe, it, vi } from "vitest"; +import { renderWithProviders } from "../../../../../util/test/render"; +import { CodeBlockPreview } from "./CodeBlockPreview"; + +const postIde = vi.fn(); + +vi.mock("../../../../../context/MockIdeMessenger", async (importOriginal) => { + const original = (await importOriginal()) as any; + return { + ...original, + MockIdeMessenger: class MockedMockIdeMessenger extends original.MockIdeMessenger { + post(...args: any[]) { + postIde(...args); + } + }, + }; +}); + +describe("CodeBlockPreview", () => { + const createMockContextItem = ( + overrides: Partial = {}, + ): ContextItemWithId => ({ + content: "console.log('test');", + name: "test.ts", + description: "Test file", + id: { + providerTitle: "file", + itemId: "test-item-id", + }, + uri: { + type: "file", + value: "/test/test.ts", + }, + ...overrides, + }); + + const createMockNodeViewProps = ( + item: ContextItemWithId, + selected = false, + ): NodeViewProps => ({ + node: { + attrs: { + item, + }, + } as any, + view: {} as any, + getPos: vi.fn(() => 0), + innerDecorations: {} as any, + editor: {} as any, + extension: {} as any, + HTMLAttributes: {}, + decorations: [] as any, + selected, + updateAttributes: vi.fn(), + deleteNode: vi.fn(), + }); + + beforeEach(async () => { + vi.clearAllMocks(); + }); + + it("opens file when title is clicked", async () => { + const item = createMockContextItem({ + id: { providerTitle: "file", itemId: "test-id" }, + uri: { type: "file", value: "/test/file.ts" }, + name: "test.ts", + }); + const props = createMockNodeViewProps(item); + + await renderWithProviders(); + + const title = screen.getByText("test.ts"); + title.click(); + + expect(postIde).toHaveBeenCalled(); + expect(postIde).toHaveBeenCalledWith("showFile", { + filepath: "/test/file.ts", + }); + }); +}); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx index b81a8c05f..f0a640a22 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx @@ -42,7 +42,7 @@ export const CodeBlockPreview = ({ }); } else if (item.id.providerTitle === "code") { const rif = ctxItemToRifWithContents(item, true); - ideMessenger.ide.showLines( + void ideMessenger.ide.showLines( rif.filepath, rif.range.start.line, rif.range.end.line, From 194b802ed3b1c67afeb6abfa7153401acecd51b6 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 19 Jul 2025 19:39:09 +0200 Subject: [PATCH 076/178] fix: set high default pruning length, let server throw error unless context length known --- core/llm/constants.ts | 2 ++ core/llm/countTokens.ts | 10 ++++++---- core/llm/index.ts | 13 ++++++++----- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 90de5c64d..b6759663d 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -1,6 +1,7 @@ const DEFAULT_MAX_TOKENS = 4096; const DEFAULT_CONTEXT_LENGTH = 32_768; const DEFAULT_TEMPERATURE = 0.5; +const DEFAULT_PRUNING_LENGTH = 128000; const DEFAULT_ARGS = { maxTokens: DEFAULT_MAX_TOKENS, @@ -24,5 +25,6 @@ export { DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, + DEFAULT_PRUNING_LENGTH, PROXY_URL, }; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 852638d1c..03a106144 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -17,6 +17,7 @@ import { import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js"; +import { DEFAULT_PRUNING_LENGTH } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; interface Encoding { encode: Tiktoken["encode"]; @@ -409,14 +410,14 @@ function pruneRawPromptFromTop( function compileChatMessages({ modelName, msgs, - contextLength, + knownContextLength, maxTokens, supportsImages, tools, }: { modelName: string; msgs: ChatMessage[]; - contextLength: number; + knownContextLength: number | undefined; maxTokens: number; supportsImages: boolean; tools?: Tool[]; @@ -465,6 +466,7 @@ function compileChatMessages({ toolTokens = countToolsTokens(tools, modelName); } + const contextLength = knownContextLength ?? DEFAULT_PRUNING_LENGTH; const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens); @@ -480,12 +482,12 @@ function compileChatMessages({ inputTokensAvailable -= lastMessagesTokens; // Make sure there's enough context for the non-excludable items - if (inputTokensAvailable < 0) { + if (knownContextLength !== undefined && inputTokensAvailable < 0) { throw new Error( `Not enough context available to include the system message, last user message, and tools. There must be at least ${minOutputTokens} tokens remaining for output. Request had the following token counts: - - contextLength: ${contextLength} + - contextLength: ${knownContextLength} - counting safety buffer: ${countingSafetyBuffer} - tools: ~${toolTokens} - system message: ~${systemMsgTokens} diff --git a/core/llm/index.ts b/core/llm/index.ts index fa16b8591..4d31e0902 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -145,7 +145,7 @@ export abstract class BaseLLM implements ILLM { baseChatSystemMessage?: string; basePlanSystemMessage?: string; baseAgentSystemMessage?: string; - contextLength: number; + _contextLength: number | undefined; maxStopWords?: number | undefined; completionOptions: CompletionOptions; requestOptions?: RequestOptions; @@ -217,8 +217,7 @@ export abstract class BaseLLM implements ILLM { this.baseAgentSystemMessage = options.baseAgentSystemMessage; this.basePlanSystemMessage = options.basePlanSystemMessage; this.baseChatSystemMessage = options.baseChatSystemMessage; - this.contextLength = - options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; + this._contextLength = options.contextLength ?? llmInfo?.contextLength; this.maxStopWords = options.maxStopWords ?? this.maxStopWords; this.completionOptions = { ...options.completionOptions, @@ -292,6 +291,10 @@ export abstract class BaseLLM implements ILLM { this.autocompleteOptions = options.autocompleteOptions; } + get contextLength() { + return this._contextLength ?? DEFAULT_CONTEXT_LENGTH; + } + getConfigurationStatus() { return LLMConfigurationStatuses.VALID; } @@ -895,7 +898,7 @@ export abstract class BaseLLM implements ILLM { return compileChatMessages({ modelName: completionOptions.model, msgs: message, - contextLength: this.contextLength, + knownContextLength: this._contextLength, maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, supportsImages: this.supportsImages(), tools: options.tools, @@ -944,7 +947,7 @@ export abstract class BaseLLM implements ILLM { const { compiledChatMessages } = compileChatMessages({ modelName: completionOptions.model, msgs: _messages, - contextLength: this.contextLength, + knownContextLength: this._contextLength, maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, supportsImages: this.supportsImages(), tools: options.tools, From 32911c07790b0cf2f7e2d9ff67ad5081184dbb67 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 19 Jul 2025 19:47:01 +0200 Subject: [PATCH 077/178] fix: assign to contextLength basellm getter --- core/llm/llms/HuggingFaceTGI.ts | 2 +- core/llm/llms/Ollama.ts | 2 +- core/llm/llms/Vllm.ts | 2 +- core/util/generateRepoMap.test.ts | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index 8a86634c8..ca4acc6d9 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -25,7 +25,7 @@ class HuggingFaceTGI extends BaseLLM { } const json = await response.json(); this.model = json.model_id; - this.contextLength = Number.parseInt(json.max_input_length); + this._contextLength = Number.parseInt(json.max_input_length); }) .catch((e) => { console.log(`Failed to list models for HuggingFace TGI: ${e.message}`); diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 106f99e1b..a944f90f9 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -184,7 +184,7 @@ class Ollama extends BaseLLM implements ModelInstaller { let value = parts[2]; switch (key) { case "num_ctx": - this.contextLength = + this._contextLength = options.contextLength ?? Number.parseInt(value); break; case "stop": diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts index ac550f153..97bd936cb 100644 --- a/core/llm/llms/Vllm.ts +++ b/core/llm/llms/Vllm.ts @@ -72,7 +72,7 @@ class Vllm extends OpenAI { const json = await response.json(); const data = json.data[0]; this.model = data.id; - this.contextLength = Number.parseInt(data.max_model_len); + this._contextLength = Number.parseInt(data.max_model_len); }) .catch((e) => { console.log(`Failed to list models for vLLM: ${e.message}`); diff --git a/core/util/generateRepoMap.test.ts b/core/util/generateRepoMap.test.ts index 78f879f63..67c58c6fd 100644 --- a/core/util/generateRepoMap.test.ts +++ b/core/util/generateRepoMap.test.ts @@ -55,7 +55,7 @@ describe.skip("generateRepoMap", () => { }); // Set testLLM properties - testLLM.contextLength = 2048; + testLLM._contextLength = 2048; testLLM.countTokens = jest.fn().mockReturnValue(10); // Act @@ -115,7 +115,7 @@ describe.skip("generateRepoMap", () => { }); // Set testLLM properties - testLLM.contextLength = 2048; + testLLM._contextLength = 2048; testLLM.countTokens = jest.fn().mockReturnValue(10); // Act @@ -184,7 +184,7 @@ describe.skip("generateRepoMap", () => { .mockImplementation(() => {}); // Set testLLM properties - testLLM.contextLength = 2048; + testLLM._contextLength = 2048; testLLM.countTokens = jest.fn().mockReturnValue(10); // Act From bcc8c5264d7f8e6b9b1a884c8793aa23d5c10496 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Sat, 19 Jul 2025 15:31:08 -0700 Subject: [PATCH 078/178] feat: add `slug` to rule obj on dev data --- gui/src/redux/thunks/streamNormalInput.ts | 1 + packages/config-yaml/src/schemas/data/chatInteraction/index.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 6c722817b..6e95191c4 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -253,6 +253,7 @@ export const streamNormalInput = createAsyncThunk< rules: appliedRules.map((rule) => ({ id: getRuleId(rule), rule: rule.rule, + slug: rule.slug, })), }), }, diff --git a/packages/config-yaml/src/schemas/data/chatInteraction/index.ts b/packages/config-yaml/src/schemas/data/chatInteraction/index.ts index f13b630af..14bb36ba9 100644 --- a/packages/config-yaml/src/schemas/data/chatInteraction/index.ts +++ b/packages/config-yaml/src/schemas/data/chatInteraction/index.ts @@ -13,6 +13,7 @@ export const chatInteractionEventAllSchema = baseDevDataAllSchema.extend({ z.object({ id: z.string(), rule: z.string(), + slug: z.string().optional(), }), ) .optional(), From ff5e7092dddd36ad746d1b5b524a0c9d5c47d0f2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 20 Jul 2025 10:14:14 +0200 Subject: [PATCH 079/178] feat: onlyUseSystemMessageTools experimental setting --- core/config/sharedConfig.ts | 6 ++++++ core/config/types.ts | 1 - core/index.d.ts | 1 + gui/src/pages/config/UserSettingsForm.tsx | 12 ++++++++++++ gui/src/pages/gui/StreamError.tsx | 2 -- 5 files changed, 19 insertions(+), 3 deletions(-) diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index c720f4272..8412c71b7 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -21,6 +21,7 @@ export const sharedConfigSchema = z useCurrentFileAsContext: z.boolean(), optInNextEditFeature: z.boolean(), enableExperimentalTools: z.boolean(), + onlyUseSystemMessageTools: z.boolean(), codebaseToolCallingOnly: z.boolean(), // `ui` in `ContinueConfig` @@ -184,6 +185,11 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.optInNextEditFeature = sharedConfig.optInNextEditFeature; } + if (sharedConfig.onlyUseSystemMessageTools !== undefined) { + configCopy.experimental.onlyUseSystemMessageTools = + sharedConfig.onlyUseSystemMessageTools; + } + if (sharedConfig.codebaseToolCallingOnly !== undefined) { configCopy.experimental.codebaseToolCallingOnly = sharedConfig.codebaseToolCallingOnly; diff --git a/core/config/types.ts b/core/config/types.ts index 406f40ddd..0c2a7cd70 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -1122,7 +1122,6 @@ declare global { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; - useTools?: boolean; modelContextProtocolServers?: MCPOptions[]; } diff --git a/core/index.d.ts b/core/index.d.ts index c2bc7487b..980048ef4 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1443,6 +1443,7 @@ export interface ExperimentalConfig { defaultContext?: DefaultContextProvider[]; promptPath?: string; enableExperimentalTools?: boolean; + onlyUseSystemMessageTools?: boolean; /** * Quick actions are a way to add custom commands to the Code Lens of diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 9eea8003b..eb4d30d1f 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -88,6 +88,8 @@ export function UserSettingsForm() { config.experimental?.useCurrentFileAsContext ?? false; const enableExperimentalTools = config.experimental?.enableExperimentalTools ?? false; + const onlyUseSystemMessageTools = + config.experimental?.onlyUseSystemMessageTools ?? false; const optInNextEditFeature = config.experimental?.optInNextEditFeature ?? false; const codebaseToolCallingOnly = @@ -419,6 +421,16 @@ export function UserSettingsForm() { text="Enable experimental tools" /> + + handleUpdate({ + onlyUseSystemMessageTools: !onlyUseSystemMessageTools, + }) + } + text="Only use system message tools" + /> + diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 58fcaf97b..a49e5f795 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -246,8 +246,6 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ); } - console.log({ message }); - return (
{/* Concise error title */} From dde117e471299c34bab98b4e1c1ab06ee3e6034d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 20 Jul 2025 10:22:43 +0200 Subject: [PATCH 080/178] feat: warning for models not great with tools --- core/llm/autodetect.ts | 20 +---- core/llm/toolSupport.ts | 29 +++++++ gui/src/components/ModeSelect/ModeSelect.tsx | 87 +++++++++++-------- .../StepContainer/ResponseActions.tsx | 4 +- gui/src/components/mainInput/InputToolbar.tsx | 6 +- gui/src/redux/thunks/streamNormalInput.ts | 4 +- 6 files changed, 86 insertions(+), 64 deletions(-) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index a220b5dbd..92693456d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -1,9 +1,4 @@ -import { - ChatMessage, - ModelCapability, - ModelDescription, - TemplateType, -} from "../index.js"; +import { ChatMessage, ModelCapability, TemplateType } from "../index.js"; import { anthropicTemplateMessages, @@ -41,7 +36,6 @@ import { xWinCoderEditPrompt, zephyrEditPrompt, } from "./templates/edit.js"; -import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js"; const PROVIDER_HANDLES_TEMPLATING: string[] = [ "lmstudio", @@ -107,17 +101,6 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "granite-vision", ]; -function modelSupportsTools(modelDescription: ModelDescription) { - if (modelDescription.capabilities?.tools !== undefined) { - return modelDescription.capabilities.tools; - } - const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; - if (!providerSupport) { - return false; - } - return providerSupport(modelDescription.model) ?? false; -} - function modelSupportsImages( provider: string, model: string, @@ -400,5 +383,4 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, - modelSupportsTools, }; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index ccaf906ce..f1eb14ad4 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -1,4 +1,5 @@ import { parseProxyModelName } from "@continuedev/config-yaml"; +import { ModelDescription } from ".."; export const PROVIDER_TOOL_SUPPORT: Record boolean> = { @@ -287,3 +288,31 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, }; + +export function isRecommendedAgentModel(modelName: string): boolean { + // AND behavior + const recs: RegExp[][] = [ + [/o[134]/], + [/deepseek/, /r1|reasoner/], + [/gemini/, /2\.5/, /pro/], + [/gpt/, /4/], + [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], + [/claude/, /opus/, /-4/], + ]; + for (const combo of recs) { + if (combo.every((regex) => modelName.toLowerCase().match(regex))) { + return true; + } + } + return false; +} +export function modelSupportsNativeTools(modelDescription: ModelDescription) { + if (modelDescription.capabilities?.tools !== undefined) { + return modelDescription.capabilities.tools; + } + const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; + if (!providerSupport) { + return false; + } + return providerSupport(modelDescription.model) ?? false; +} diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index b7bc81c2e..caffe9181 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -1,10 +1,12 @@ import { CheckIcon, ChevronDownIcon, + ExclamationCircleIcon, InformationCircleIcon, } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; +import { isRecommendedAgentModel } from "core/llm/toolSupport"; +import { capitalize } from "lodash"; import { useCallback, useEffect, useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; @@ -19,24 +21,17 @@ export function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector((store) => store.session.mode); const selectedModel = useAppSelector(selectSelectedChatModel); - const agentModeSupported = useMemo(() => { - return selectedModel && modelSupportsTools(selectedModel); + const showAgentModeWarning = useMemo(() => { + if (!selectedModel || isRecommendedAgentModel(selectedModel.model)) { + return false; // no need to show warning if no model is selected + } + return true; }, [selectedModel]); const { mainEditor } = useMainEditor(); const metaKeyLabel = useMemo(() => { return getMetaKeyLabel(); }, []); - // Switch to chat mode if agent mode is selected but not supported - useEffect(() => { - if (!selectedModel) { - return; - } - if (mode !== "chat" && !agentModeSupported) { - dispatch(setMode("chat")); - } - }, [mode, agentModeSupported, dispatch, selectedModel]); - const cycleMode = useCallback(() => { if (mode === "chat") { dispatch(setMode("plan")); @@ -76,6 +71,37 @@ export function ModeSelect() { return () => document.removeEventListener("keydown", handleKeyDown); }, [cycleMode]); + const agentWarning = ( + <> + + + {`${capitalize(mode)} might not work well with this model.`} + {/* can't seem to make link in tooltip clickable. globalCloseEvents or closeEvents? */} + {/* { + ideMessenger.post( + "openUrl", + "https://docs.continue.dev/agent/model-setup", + ); + }} + className="text-link cursor-pointer" + > + See docs + */} + + + ); + return (
@@ -117,11 +143,7 @@ export function ModeSelect() {
{mode === "chat" && } - +
Plan @@ -138,19 +160,13 @@ export function ModeSelect() { Read-only/MCP tools available
- {agentModeSupported ? ( - - ) : ( - (Not supported) - )} + {showAgentModeWarning && agentWarning} +
- + +
Agent @@ -167,13 +183,10 @@ export function ModeSelect() { All tools available
- {agentModeSupported ? ( - - ) : ( - (Not supported) - )} + {showAgentModeWarning && agentWarning} +
diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 068432792..0dc09a438 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -5,7 +5,7 @@ import { TrashIcon, } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; +import { modelSupportsNativeTools } from "core/llm/toolSupport"; import { renderChatMessage } from "core/util/messageContent"; import { useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -41,7 +41,7 @@ export default function ResponseActions({ ); const isPruned = useAppSelector((state) => state.session.isPruned); const ruleGenerationSupported = useMemo(() => { - return selectedModel && modelSupportsTools(selectedModel); + return selectedModel && modelSupportsNativeTools(selectedModel); }, [selectedModel]); const percent = Math.round((contextPercentage ?? 0) * 100); diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 9be9f25d9..f97c7d101 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -4,7 +4,7 @@ import { PhotoIcon, } from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; -import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect"; +import { modelSupportsImages } from "core/llm/autodetect"; import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -57,8 +57,6 @@ function InputToolbar(props: InputToolbarProps) { const isEnterDisabled = props.disabled || (isInEdit && codeToEdit.length === 0); - const toolsSupported = defaultModel && modelSupportsTools(defaultModel); - const supportsImages = defaultModel && modelSupportsImages( @@ -174,7 +172,7 @@ function InputToolbar(props: InputToolbarProps) { {!isInEdit && } {!props.toolbarOptions?.hideUseCodebase && !isInEdit && (