diff --git a/.continue/assistants/cli-assistant.yaml b/.continue/assistants/cli-assistant.yaml index 838a59c19..168731625 100644 --- a/.continue/assistants/cli-assistant.yaml +++ b/.continue/assistants/cli-assistant.yaml @@ -1,4 +1,4 @@ -name: CLI Assistant +name: CLI Agent version: 0.0.1 schema: v1 diff --git a/.continue/rules/continue-sdk-cli-and-hub-context.yaml b/.continue/rules/continue-sdk-cli-and-hub-context.yaml index d8d56b7cb..3041db0be 100644 --- a/.continue/rules/continue-sdk-cli-and-hub-context.yaml +++ b/.continue/rules/continue-sdk-cli-and-hub-context.yaml @@ -13,9 +13,9 @@ rules: - Continue SDK: Experimental package in early development, subject to breaking changes - - Continue Hub: Registry for custom AI code assistants + - Continue Hub: Registry for custom AI code agent - - Hub functionality: Manages assistant building blocks (models, rules, + - Hub functionality: Manages agent building blocks (models, rules, context providers, prompts, docs, etc.) - Governance: Allows central configuration for organizations diff --git a/.github/workflows/pr-description.yml.disabled b/.github/workflows/pr-description.yml.disabled index 24e87c4dd..9cdd544b6 100644 --- a/.github/workflows/pr-description.yml.disabled +++ b/.github/workflows/pr-description.yml.disabled @@ -53,7 +53,7 @@ jobs: - name: Analyze PR with Continue id: analyze run: | - continue-cli -p --assistant "starter/nextjs-assistant" "$(cat prompt.txt)" > analysis.txt + continue-cli -p --config "starter/nextjs-assistant" "$(cat prompt.txt)" > analysis.txt echo "analysis_file=analysis.txt" >> $GITHUB_OUTPUT env: ## TODO: This needs to be set on the repo diff --git a/.npmignore b/.npmignore index 6db353c65..bdce176fe 100644 --- a/.npmignore +++ b/.npmignore @@ -7,3 +7,6 @@ test AGENTS.md jest.config.mjs tsconfig.json +tsconfig.build.json +TESTING_STRATEGY.md +.env.example diff --git a/.releaserc.json b/.releaserc.json index ea82dfb9d..e69596bce 100644 --- a/.releaserc.json +++ b/.releaserc.json @@ -33,13 +33,6 @@ "pkgRoot": "." } ], - [ - "@semantic-release/git", - { - "assets": ["package.json", "CHANGELOG.md"], - "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}" - } - ], "@semantic-release/github" ] } diff --git a/.vscode/launch.json b/.vscode/launch.json index 5b8b7d2e1..c42cd04c7 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -25,7 +25,7 @@ "type": "node", "request": "launch", "program": "${workspaceFolder}/src/index.ts", - "args": ["--config", "nate/default-assistant"], + "args": [], "env": { "NODE_ENV": "development" }, diff --git a/README.md b/README.md index 0bf21c118..c68cf5e9c 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,6 @@ cn --resume ## Command Line Options - `-p`: Run in headless mode (no TUI) -- `--config `: Specify assistant configuration path +- `--config `: Specify agent configuration path - `--resume`: Resume the last session for this terminal - ``: Optional prompt to start with - diff --git a/jest.config.mjs b/jest.config.mjs index 9ed1d15ab..8407cab12 100644 --- a/jest.config.mjs +++ b/jest.config.mjs @@ -15,6 +15,8 @@ export default { "/node_modules/ink-testing-library/build/index.js", "^./SyntaxHighlighter\\.js$": "/src/ui/__mocks__/SyntaxHighlighter.ts", + "^./FreeTrialStatus\\.js$": + "/src/ui/__mocks__/FreeTrialStatus.tsx", }, extensionsToTreatAsEsm: [".ts", ".tsx"], preset: "ts-jest/presets/default-esm", @@ -23,6 +25,7 @@ export default { testPathIgnorePatterns: ["/dist/"], modulePathIgnorePatterns: ["/dist/"], transformIgnorePatterns: ["node_modules/(?!(highlight.js|lowlight)/)"], + setupFilesAfterEnv: ["/jest.setup.ts"], globals: { __dirname: path.dirname(fileURLToPath(import.meta.url)), __filename: path.resolve(fileURLToPath(import.meta.url)), diff --git a/jest.setup.ts b/jest.setup.ts new file mode 100644 index 000000000..efd9d9715 --- /dev/null +++ b/jest.setup.ts @@ -0,0 +1,2 @@ +// Disable telemetry for tests +process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index bcedc33d2..88735dd37 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,14 @@ "@continuedev/openai-adapters": "^1.0.48-beta", "@continuedev/sdk": "^0.0.13", "@modelcontextprotocol/sdk": "^1.9.0", + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.203.0", + "@opentelemetry/instrumentation-fs": "^0.23.0", + "@opentelemetry/instrumentation-http": "^0.203.0", + "@opentelemetry/resources": "^2.0.1", + "@opentelemetry/sdk-node": "^0.203.0", + "@opentelemetry/semantic-conventions": "^1.36.0", "@types/react": "^19.1.8", "@types/turndown": "^5.0.5", "@workos-inc/node": "^7.45.0", @@ -23,6 +31,7 @@ "glob": "^11.0.3", "ignore-walk": "^7.0.0", "ink": "^6.0.1", + "jszip": "^3.10.1", "lowlight": "^3.3.0", "minimatch": "^10.0.3", "node-fetch": "^3.3.2", @@ -49,6 +58,7 @@ "@types/ignore-walk": "^4.0.3", "@types/ink-testing-library": "^1.0.4", "@types/jest": "^29.5.14", + "@types/jszip": "^3.4.0", "@types/nock": "^10.0.3", "@types/readline-sync": "^1.4.8", "conventional-changelog-conventionalcommits": "^9.1.0", @@ -1899,6 +1909,37 @@ "node": ">=18" } }, + "node_modules/@grpc/grpc-js": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.13.4.tgz", + "integrity": "sha512-GsFaMXCkMqkKIvwCQjCrwH+GHbPKBjhwo/8ZuUkWHqbI73Kky9I+pQltrlT0+MWpedCoosda53lgjYfyEPgxBg==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/proto-loader": "^0.7.13", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.7.15", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz", + "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==", + "license": "Apache-2.0", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/@isaacs/balanced-match": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz", @@ -2586,6 +2627,16 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, "node_modules/@mixmark-io/domino": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz", @@ -2850,6 +2901,533 @@ "dev": true, "license": "MIT" }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/api-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.203.0.tgz", + "integrity": "sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/context-async-hooks": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.0.1.tgz", + "integrity": "sha512-XuY23lSI3d4PEqKA+7SLtAgwqIfc6E/E9eAQWLN1vlpC53ybO3o6jW4BsXo1xvz9lYyyWItfQDDLzezER01mCw==", + "license": "Apache-2.0", + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-grpc": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-grpc/-/exporter-logs-otlp-grpc-0.203.0.tgz", + "integrity": "sha512-g/2Y2noc/l96zmM+g0LdeuyYKINyBwN6FJySoU15LHPLcMN/1a0wNk2SegwKcxrRdE7Xsm7fkIR5n6XFe3QpPw==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/sdk-logs": "0.203.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-http": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.203.0.tgz", + "integrity": "sha512-s0hys1ljqlMTbXx2XiplmMJg9wG570Z5lH7wMvrZX6lcODI56sG4HL03jklF63tBeyNwK2RV1/ntXGo3HgG4Qw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/sdk-logs": "0.203.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-proto": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.203.0.tgz", + "integrity": "sha512-nl/7S91MXn5R1aIzoWtMKGvqxgJgepB/sH9qW0rZvZtabnsjbf8OQ1uSx3yogtvLr0GzwD596nQKz2fV7q2RBw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-grpc": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.203.0.tgz", + "integrity": "sha512-FCCj9nVZpumPQSEI57jRAA89hQQgONuoC35Lt+rayWY/mzCAc6BQT7RFyFaZKJ2B7IQ8kYjOCPsF/HGFWjdQkQ==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-metrics-otlp-http": "0.203.0", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-http": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.203.0.tgz", + "integrity": "sha512-HFSW10y8lY6BTZecGNpV3GpoSy7eaO0Z6GATwZasnT4bEsILp8UJXNG5OmEsz4SdwCSYvyCbTJdNbZP3/8LGCQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-proto": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.203.0.tgz", + "integrity": "sha512-OZnhyd9npU7QbyuHXFEPVm3LnjZYifuKpT3kTnF84mXeEQ84pJJZgyLBpU4FSkSwUkt/zbMyNAI7y5+jYTWGIg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-metrics-otlp-http": "0.203.0", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-prometheus": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-prometheus/-/exporter-prometheus-0.203.0.tgz", + "integrity": "sha512-2jLuNuw5m4sUj/SncDf/mFPabUxMZmmYetx5RKIMIQyPnl6G6ooFzfeE8aXNRf8YD1ZXNlCnRPcISxjveGJHNg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-trace-otlp-grpc": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.203.0.tgz", + "integrity": "sha512-322coOTf81bm6cAA8+ML6A+m4r2xTCdmAZzGNTboPXRzhwPt4JEmovsFAs+grpdarObd68msOJ9FfH3jxM6wqA==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-trace-otlp-http": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.203.0.tgz", + "integrity": "sha512-ZDiaswNYo0yq/cy1bBLJFe691izEJ6IgNmkjm4C6kE9ub/OMQqDXORx2D2j8fzTBTxONyzusbaZlqtfmyqURPw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-trace-otlp-proto": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.203.0.tgz", + "integrity": "sha512-1xwNTJ86L0aJmWRwENCJlH4LULMG2sOXWIVw+Szta4fkqKVY50Eo4HoVKKq6U9QEytrWCr8+zjw0q/ZOeXpcAQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-zipkin": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-2.0.1.tgz", + "integrity": "sha512-a9eeyHIipfdxzCfc2XPrE+/TI3wmrZUDFtG2RRXHSbZZULAny7SyybSvaDvS77a7iib5MPiAvluwVvbGTsHxsw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.0" + } + }, + "node_modules/@opentelemetry/instrumentation": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.203.0.tgz", + "integrity": "sha512-ke1qyM+3AK2zPuBPb6Hk/GCsc5ewbLvPNkEuELx/JmANeEp6ZjnZ+wypPAJSucTw0wvCGrUaibDSdcrGFoWxKQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-fs": { + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fs/-/instrumentation-fs-0.23.0.tgz", + "integrity": "sha512-Puan+QopWHA/KNYvDfOZN6M/JtF6buXEyD934vrb8WhsX1/FuM7OtoMlQyIqAadnE8FqqDL4KDPiEfCQH6pQcQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.203.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-http": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-http/-/instrumentation-http-0.203.0.tgz", + "integrity": "sha512-y3uQAcCOAwnO6vEuNVocmpVzG3PER6/YZqbPbbffDdJ9te5NkHEkfSMNzlC3+v7KlE+WinPGc3N7MR30G1HY2g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/instrumentation": "0.203.0", + "@opentelemetry/semantic-conventions": "^1.29.0", + "forwarded-parse": "2.1.2" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-exporter-base": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.203.0.tgz", + "integrity": "sha512-Wbxf7k+87KyvxFr5D7uOiSq/vHXWommvdnNE7vECO3tAhsA2GfOlpWINCMWUEPdHZ7tCXxw6Epp3vgx3jU7llQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-transformer": "0.203.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-grpc-exporter-base": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.203.0.tgz", + "integrity": "sha512-te0Ze1ueJF+N/UOFl5jElJW4U0pZXQ8QklgSfJ2linHN0JJsuaHG8IabEUi2iqxY8ZBDlSiz1Trfv5JcjWWWwQ==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-transformer": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.203.0.tgz", + "integrity": "sha512-Y8I6GgoCna0qDQ2W6GCRtaF24SnvqvA8OfeTi7fqigD23u8Jpb4R5KFv/pRvrlGagcCLICMIyh9wiejp4TXu/A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-metrics": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "protobufjs": "^7.3.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/propagator-b3": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-b3/-/propagator-b3-2.0.1.tgz", + "integrity": "sha512-Hc09CaQ8Tf5AGLmf449H726uRoBNGPBL4bjr7AnnUpzWMvhdn61F78z9qb6IqB737TffBsokGAK1XykFEZ1igw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/propagator-jaeger": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-jaeger/-/propagator-jaeger-2.0.1.tgz", + "integrity": "sha512-7PMdPBmGVH2eQNb/AtSJizQNgeNTfh6jQFqys6lfhd6P4r+m/nTh3gKPPpaCXVdRQ+z93vfKk+4UGty390283w==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.203.0.tgz", + "integrity": "sha512-vM2+rPq0Vi3nYA5akQD2f3QwossDnTDLvKbea6u/A2NZ3XDkPxMfo/PNrDoXhDUD/0pPo2CdH5ce/thn9K0kLw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.4.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-metrics": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.0.1.tgz", + "integrity": "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.9.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-node": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-node/-/sdk-node-0.203.0.tgz", + "integrity": "sha512-zRMvrZGhGVMvAbbjiNQW3eKzW/073dlrSiAKPVWmkoQzah9wfynpVPeL55f9fVIm0GaBxTLcPeukWGy0/Wj7KQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-logs-otlp-grpc": "0.203.0", + "@opentelemetry/exporter-logs-otlp-http": "0.203.0", + "@opentelemetry/exporter-logs-otlp-proto": "0.203.0", + "@opentelemetry/exporter-metrics-otlp-grpc": "0.203.0", + "@opentelemetry/exporter-metrics-otlp-http": "0.203.0", + "@opentelemetry/exporter-metrics-otlp-proto": "0.203.0", + "@opentelemetry/exporter-prometheus": "0.203.0", + "@opentelemetry/exporter-trace-otlp-grpc": "0.203.0", + "@opentelemetry/exporter-trace-otlp-http": "0.203.0", + "@opentelemetry/exporter-trace-otlp-proto": "0.203.0", + "@opentelemetry/exporter-zipkin": "2.0.1", + "@opentelemetry/instrumentation": "0.203.0", + "@opentelemetry/propagator-b3": "2.0.1", + "@opentelemetry/propagator-jaeger": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-metrics": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "@opentelemetry/sdk-trace-node": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-node": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.0.1.tgz", + "integrity": "sha512-UhdbPF19pMpBtCWYP5lHbTogLWx9N0EBxtdagvkn5YtsAnCBZzL7SjktG+ZmupRgifsHMjwUaCCaVmqGfSADmA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/context-async-hooks": "2.0.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.36.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.36.0.tgz", + "integrity": "sha512-TtxJSRD8Ohxp6bKkhrm27JRHAxPczQA7idtcTOMYI+wQRRrfgqxHv1cFbCApcSnNjtXkmzFozn6jQtFrOmbjPQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, "node_modules/@peculiar/asn1-schema": { "version": "2.3.15", "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.3.15.tgz", @@ -2934,6 +3512,70 @@ "node": ">=12" } }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==", + "license": "BSD-3-Clause" + }, "node_modules/@sec-ant/readable-stream": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", @@ -4216,6 +4858,16 @@ "pretty-format": "^29.0.0" } }, + "node_modules/@types/jszip": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@types/jszip/-/jszip-3.4.0.tgz", + "integrity": "sha512-GFHqtQQP3R4NNuvZH3hNCYD0NbyBZ42bkN7kO3NDrU/SnvIZWMS8Bp38XCsRKBT5BXvgm0y1zqpZWp/ZkRzBzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "jszip": "*" + } + }, "node_modules/@types/keygrip": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/@types/keygrip/-/keygrip-1.0.6.tgz", @@ -4441,7 +5093,6 @@ "version": "8.14.1", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", - "dev": true, "license": "MIT", "bin": { "acorn": "bin/acorn" @@ -4450,6 +5101,15 @@ "node": ">=0.4.0" } }, + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", + "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", + "license": "MIT", + "peerDependencies": { + "acorn": "^8" + } + }, "node_modules/acorn-walk": { "version": "8.3.4", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", @@ -5095,7 +5755,6 @@ "version": "1.4.3", "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", - "dev": true, "license": "MIT" }, "node_modules/clean-stack": { @@ -5347,7 +6006,6 @@ "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, "license": "ISC", "dependencies": { "string-width": "^4.2.0", @@ -5654,7 +6312,6 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", - "dev": true, "license": "MIT" }, "node_modules/cors": { @@ -6435,7 +7092,6 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -7029,6 +7685,12 @@ "node": ">= 0.6" } }, + "node_modules/forwarded-parse": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/forwarded-parse/-/forwarded-parse-2.1.2.tgz", + "integrity": "sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw==", + "license": "MIT" + }, "node_modules/fresh": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", @@ -7122,7 +7784,6 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, "license": "ISC", "engines": { "node": "6.* || 8.* || >= 10.*" @@ -7595,6 +8256,12 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "license": "MIT" + }, "node_modules/import-fresh": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", @@ -7636,6 +8303,18 @@ "node": ">=18.20" } }, + "node_modules/import-in-the-middle": { + "version": "1.14.2", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.14.2.tgz", + "integrity": "sha512-5tCuY9BV8ujfOpwtAGgsTx9CGUapcFMEEyByLv1B+v2+6DhAcw+Zr0nhQT7uwaZ7DiourxFEscghOR8e1aPLQw==", + "license": "Apache-2.0", + "dependencies": { + "acorn": "^8.14.0", + "acorn-import-attributes": "^1.9.5", + "cjs-module-lexer": "^1.2.2", + "module-details-from-path": "^1.0.3" + } + }, "node_modules/import-local": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", @@ -8010,7 +8689,6 @@ "version": "2.16.1", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dev": true, "license": "MIT", "dependencies": { "hasown": "^2.0.2" @@ -8202,7 +8880,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "dev": true, "license": "MIT" }, "node_modules/isexe": { @@ -9693,6 +10370,18 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/jszip": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", + "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "license": "(MIT OR GPL-3.0-or-later)", + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, "node_modules/kleur": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", @@ -9725,6 +10414,15 @@ "node": ">=6" } }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", @@ -9799,6 +10497,12 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT" + }, "node_modules/lodash.capitalize": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/lodash.capitalize/-/lodash.capitalize-4.2.1.tgz", @@ -9867,6 +10571,12 @@ "node": ">=0.1.90" } }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -10173,6 +10883,12 @@ "node": ">=16 || 14 >=14.17" } }, + "node_modules/module-details-from-path": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", + "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==", + "license": "MIT" + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -13345,6 +14061,12 @@ "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", "license": "BlueOak-1.0.0" }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -13464,7 +14186,6 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, "license": "MIT" }, "node_modules/path-scurry": { @@ -13704,7 +14425,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", - "dev": true, "license": "MIT" }, "node_modules/prompts": { @@ -13738,6 +14458,30 @@ "dev": true, "license": "ISC" }, + "node_modules/protobufjs": { + "version": "7.5.3", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.3.tgz", + "integrity": "sha512-sildjKwVqOI2kmFDiXQ6aEB0fjYTafpEvIBs8tOR8qI4spuL9OPROLVu2qZqi/xgCfsHIwVqlaF8JBjWFHnKbw==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/node": ">=13.7.0", + "long": "^5.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -14005,7 +14749,6 @@ "version": "2.3.8", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "dev": true, "license": "MIT", "dependencies": { "core-util-is": "~1.0.0", @@ -14021,7 +14764,6 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true, "license": "MIT" }, "node_modules/readline-sync": { @@ -14050,17 +14792,29 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" } }, + "node_modules/require-in-the-middle": { + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.2.tgz", + "integrity": "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "module-details-from-path": "^1.0.3", + "resolve": "^1.22.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, "node_modules/resolve": { "version": "1.22.10", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", - "dev": true, "license": "MIT", "dependencies": { "is-core-module": "^2.16.0", @@ -14475,6 +15229,12 @@ "node": ">= 18" } }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "license": "MIT" + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -15081,7 +15841,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -15926,7 +16685,6 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", @@ -15977,7 +16735,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, "license": "MIT", "dependencies": { "color-convert": "^2.0.1" @@ -16043,7 +16800,6 @@ "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, "license": "ISC", "engines": { "node": ">=10" @@ -16072,7 +16828,6 @@ "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, "license": "MIT", "dependencies": { "cliui": "^8.0.1", @@ -16091,7 +16846,6 @@ "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, "license": "ISC", "engines": { "node": ">=12" diff --git a/package.json b/package.json index f6b0c09e2..146d4f6de 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,14 @@ "@continuedev/openai-adapters": "^1.0.48-beta", "@continuedev/sdk": "^0.0.13", "@modelcontextprotocol/sdk": "^1.9.0", + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0", + "@opentelemetry/exporter-metrics-otlp-http": "^0.203.0", + "@opentelemetry/instrumentation-fs": "^0.23.0", + "@opentelemetry/instrumentation-http": "^0.203.0", + "@opentelemetry/resources": "^2.0.1", + "@opentelemetry/sdk-node": "^0.203.0", + "@opentelemetry/semantic-conventions": "^1.36.0", "@types/react": "^19.1.8", "@types/turndown": "^5.0.5", "@workos-inc/node": "^7.45.0", @@ -45,6 +53,7 @@ "glob": "^11.0.3", "ignore-walk": "^7.0.0", "ink": "^6.0.1", + "jszip": "^3.10.1", "lowlight": "^3.3.0", "minimatch": "^10.0.3", "node-fetch": "^3.3.2", @@ -68,6 +77,7 @@ "@types/ignore-walk": "^4.0.3", "@types/ink-testing-library": "^1.0.4", "@types/jest": "^29.5.14", + "@types/jszip": "^3.4.0", "@types/nock": "^10.0.3", "@types/readline-sync": "^1.4.8", "conventional-changelog-conventionalcommits": "^9.1.0", diff --git a/spec/onboarding.md b/spec/onboarding.md index a34afca14..7bc9dc39d 100644 --- a/spec/onboarding.md +++ b/spec/onboarding.md @@ -4,9 +4,10 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb ## Onboarding flow +**The onboarding flow runs when the user hasn't completed onboarding before, regardless of whether they have a valid config.yaml file.** + 1. If the --config flag is provided, load this config -2. If the user has a ~/.continue/config.yaml with an acceptable model, load this config automatically -3. Otherwise, we will present the user with two options: +2. Otherwise, we will present the user with two options: - Log in with Continue: log them in, which will automatically create their assistant and then we can load the first assistant from the first org - Enter your Anthropic API key: let them enter the key, and then either create a ~/.continue/config.yaml with the following contents OR update the existing config.yaml to add the model @@ -26,8 +27,10 @@ When something in the onboarding flow is done automatically, we should tell the ## Normal flow +**The normal flow runs when the user has already completed onboarding.** + 1. If the --config flag is provided, load this config 2. If the user is logged in, look for the first assistant in the selected org 3. If there are no assistants in that org, then look for a local ~/.continue/config.yaml 4. If there is no config.yaml, look for an ANTHROPIC_API_KEY in the environment and manually construct the config object to include just the claude-4-sonnet model with that API key -5. If none of the above, then bring the user to step 3 of the onboarding flow +5. If none of the above, then bring the user to step 3 of the onboarding flow \ No newline at end of file diff --git a/spec/otlp-metrics.md b/spec/otlp-metrics.md new file mode 100644 index 000000000..744709b10 --- /dev/null +++ b/spec/otlp-metrics.md @@ -0,0 +1,342 @@ +# OTLP Metrics Specification for Continue CLI + +This document specifies the OpenTelemetry Protocol (OTLP) metrics that should be emitted by the Continue CLI to provide comprehensive observability and usage monitoring. The metrics are designed to be compatible with Claude Code dashboards for easy migration. + +## Overview + +The Continue CLI should emit metrics that provide insights into: + +- Usage patterns and session analytics +- Performance and reliability +- Tool usage and effectiveness +- Error rates and types +- Resource utilization +- Code modification tracking + +## Configuration + +### Environment Variables + +| Environment Variable | Description | Example Values | +| ------------------------------- | --------------------------------------------------------- | ------------------------------------ | +| `CONTINUE_CLI_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` | +| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` | +| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` | +| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` | +| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` | +| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` | +| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable | + +### Metrics Cardinality Control + +| Environment Variable | Description | Default Value | Example to Disable | +| ----------------------------------- | ---------------------------------------------- | ------------- | ------------------ | +| `OTEL_METRICS_INCLUDE_SESSION_ID` | Include session.id attribute in metrics | `true` | `false` | +| `OTEL_METRICS_INCLUDE_VERSION` | Include app.version attribute in metrics | `false` | `true` | +| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Include user.account_uuid attribute in metrics | `true` | `false` | + +## Standard Attributes + +All metrics and events share these standard attributes: + +| Attribute | Description | Controlled By | +| ------------------- | ------------------------------------------------------------- | --------------------------------------------------- | +| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) | +| `app.version` | Current Continue CLI version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) | +| `organization.id` | Organization UUID (when authenticated) | Always included when available | +| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) | +| `terminal.type` | Terminal type (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected | + +## Core Metrics + +### ✅ `continue.cli.session.count` + +**Type:** Counter +**Unit:** `count` +**Description:** Count of CLI sessions started + +**Attributes:** + +- All [standard attributes](#standard-attributes) + +**Implementation:** Track in `src/commands/chat.ts` when session starts + +--- + +### ✅ `continue.cli.lines_of_code.count` + +**Type:** Counter +**Unit:** `count` +**Description:** Count of lines of code modified + +**Attributes:** + +- All [standard attributes](#standard-attributes) +- `type`: (`"added"`, `"removed"`) + +**Implementation:** Track in `src/tools/writeFile.ts` by analyzing file diffs + +--- + +### ✅ `continue.cli.pull_request.count` + +**Type:** Counter +**Unit:** `count` +**Description:** Number of pull requests created + +**Attributes:** + +- All [standard attributes](#standard-attributes) + +**Implementation:** Track when `runTerminalCommand` executes git/gh commands for PR creation + +--- + +### ✅ `continue.cli.commit.count` + +**Type:** Counter +**Unit:** `count` +**Description:** Number of git commits created + +**Attributes:** + +- All [standard attributes](#standard-attributes) + +**Implementation:** Track when `runTerminalCommand` executes `git commit` commands + +--- + +### ✅ `continue.cli.cost.usage` + +**Type:** Counter +**Unit:** `USD` +**Description:** Cost of the Continue CLI session + +**Attributes:** + +- All [standard attributes](#standard-attributes) +- `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022", "gpt-4") + +**Implementation:** Calculate costs based on token usage and model pricing in `src/streamChatResponse.ts` + +--- + +### ✅ `continue.cli.token.usage` + +**Type:** Counter +**Unit:** `tokens` +**Description:** Number of tokens used + +**Attributes:** + +- All [standard attributes](#standard-attributes) +- `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`) +- `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022", "gpt-4") + +**Implementation:** Track in `src/streamChatResponse.ts` after each API response + +--- + +### ❌ `continue.cli.code_edit_tool.decision` + +**Type:** Counter +**Unit:** `count` +**Description:** Count of code editing tool permission decisions + +**Attributes:** + +- All [standard attributes](#standard-attributes) +- `tool`: Tool name (`"writeFile"`, `"runTerminalCommand"`, etc.) +- `decision`: User decision (`"accept"`, `"reject"`) +- `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions. + +**Implementation:** Track in tool execution when user confirmation is required (if implemented) + +--- + +### ✅ `continue.cli.active_time.total` + +**Type:** Counter +**Unit:** `s` +**Description:** Total active time in seconds + +**Attributes:** + +- All [standard attributes](#standard-attributes) + +**Implementation:** Track in TUI mode (`src/ui/TUIChat.tsx`) and standard chat mode, measuring time during active interactions + +## Core Events + +### ✅ User Prompt Event + +**Event Name:** `continue.cli.user_prompt` + +**Attributes:** + +- All [standard attributes](#standard-attributes) +- `event.name`: `"user_prompt"` +- `event.timestamp`: ISO 8601 timestamp +- `prompt_length`: Length of the prompt +- `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`) + +**Implementation:** Log in `src/streamChatResponse.ts` when user message is added to chat history + +--- + +### ✅ Tool Result Event + +**Event Name:** `continue.cli.tool_result` + +**Attributes:** + +- All [standard attributes](#standard-attributes) +- `event.name`: `"tool_result"` +- `event.timestamp`: ISO 8601 timestamp +- `tool_name`: Name of the tool +- `success`: `"true"` or `"false"` +- `duration_ms`: Execution time in milliseconds +- `error`: Error message (if failed) +- `decision`: Either `"accept"` or `"reject"` (if applicable) +- `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` (if applicable) +- `tool_parameters`: JSON string containing tool-specific parameters (when available) + +**Implementation:** Log in `src/tools/index.ts` `executeToolCall` function + +--- + +### ✅ API Request Event + +**Event Name:** `continue.cli.api_request` + +**Attributes:** + +- All [standard attributes](#standard-attributes) +- `event.name`: `"api_request"` +- `event.timestamp`: ISO 8601 timestamp +- `model`: Model identifier +- `duration_ms`: Request duration in milliseconds +- `success`: `"true"` or `"false"` +- `error`: Error message (if failed) +- `input_tokens`: Number of input tokens +- `output_tokens`: Number of output tokens +- `cost_usd`: Request cost in USD + +**Implementation:** Log in `src/streamChatResponse.ts` for each API request + +## Additional Metrics + +These metrics are unique to Continue CLI and provide additional insights without conflicting with compatibility: + +### Authentication Metrics + +#### ✅ `continue.cli.auth.attempts` + +**Type:** Counter +**Unit:** `{attempt}` +**Description:** Authentication attempts + +**Labels:** + +- All [standard attributes](#standard-attributes) +- `result`: `success` | `failure` | `cancelled` +- `method`: `workos` | `token` + +**Implementation:** Track in `src/auth/workos.ts` + +### MCP Integration Metrics + +#### ❌ `continue.cli.mcp.connections` + +**Type:** Gauge +**Unit:** `{connection}` +**Description:** Active MCP connections + +**Labels:** + +- All [standard attributes](#standard-attributes) +- `server_name`: MCP server identifier +- `status`: `connected` | `disconnected` | `error` + +**Implementation:** Track in `src/mcp.ts` + +### Performance Metrics + +#### ❌ `continue.cli.startup.time` + +**Type:** Histogram +**Unit:** `ms` +**Description:** Time from CLI start to ready state + +**Labels:** + +- All [standard attributes](#standard-attributes) +- `mode`: `tui` | `headless` | `standard` +- `cold_start`: `true` | `false` + +**Implementation:** Track in `src/index.ts` and `src/commands/chat.ts` + +#### ✅ `continue.cli.response_time` + +**Type:** Histogram +**Unit:** `ms` +**Description:** LLM response time metrics (supplements API request events) + +**Labels:** + +- All [standard attributes](#standard-attributes) +- `model`: Model identifier +- `metric_type`: `time_to_first_token` | `total_response_time` +- `has_tools`: `true` | `false` + +**Implementation:** Track in `src/streamChatResponse.ts` + +## Implementation Guidelines + +### Migration from Claude Code Dashboards + +The core metrics (`session.count`, `lines_of_code.count`, `token.usage`, `cost.usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code.*` to `continue.cli.*`. + +### Privacy Considerations + +- **No PII**: Avoid logging file paths, user content, or other personally identifiable information +- **Redacted by Default**: User prompts are redacted unless `OTEL_LOG_USER_PROMPTS=1` +- **Configurable Attributes**: Use cardinality control variables to manage data granularity +- **Opt-out**: Provide mechanism to disable telemetry entirely + +### Resource Attributes + +All metrics should include these resource attributes: + +- `service.name`: `continue-cli` +- `service.version`: CLI version +- `deployment.environment`: `development` | `production` +- `os.type`: Operating system +- `process.pid`: Process ID + +### Implementation Points + +1. **Session Tracking**: Initialize session ID and track lifecycle in `src/commands/chat.ts` +2. **Token/Cost Tracking**: Implement in `src/streamChatResponse.ts` with model-specific pricing +3. **Tool Usage**: Track in `src/tools/index.ts` and individual tool implementations +4. **File Operations**: Implement diff analysis in `src/tools/writeFile.ts` for LOC tracking +5. **Command Detection**: Parse git/gh commands in `src/tools/runTerminalCommand.ts` +6. **Authentication**: Track auth flows in `src/auth/workos.ts` +7. **Performance**: Add timing measurements throughout the application lifecycle + +## Implementation Status + +✅ = Implemented +❌ = Not implemented yet + +**Core metrics:** 6/7 implemented (83%) +**Core events:** 3/3 implemented (100%) +**Additional metrics:** 4/7 implemented (57%) + +**Missing implementations:** + +- `continue.cli.code_edit_tool.decision` - requires user confirmation UI +- `continue.cli.mcp.connections` - needs MCP service monitoring +- `continue.cli.startup.time` - needs startup time tracking diff --git a/src/args.test.ts b/src/args.test.ts index 3d7c64baa..edff0dfce 100644 --- a/src/args.test.ts +++ b/src/args.test.ts @@ -1,4 +1,5 @@ -import { parseArgs } from "./args.js"; +import { jest } from '@jest/globals'; +import { parseArgs, processRule } from "./args.js"; describe("parseArgs", () => { const originalArgv = process.argv; @@ -245,3 +246,196 @@ describe("parseArgs", () => { ]); }); }); + +describe("processRule (loadRuleFromHub integration)", () => { + // Mock fetch for hub tests + const originalFetch = global.fetch; + const mockFetch = jest.fn() as jest.MockedFunction; + + beforeAll(() => { + global.fetch = mockFetch; + }); + + afterAll(() => { + global.fetch = originalFetch; + }); + + beforeEach(() => { + mockFetch.mockClear(); + }); + + describe("loadRuleFromHub", () => { + it("should successfully load a rule from the Continue Hub", async () => { + // Create a mock zip file containing a markdown rule + const JSZip = (await import("jszip")).default; + const zip = new JSZip(); + const ruleContent = "# Sentry Next.js Rule\n\nThis is a sample rule for Sentry integration with Next.js applications."; + zip.file("rule.md", ruleContent); + + const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); + + // Mock successful fetch response + mockFetch.mockResolvedValue({ + ok: true, + arrayBuffer: () => Promise.resolve(zipBuffer), + } as Response); + + const result = await processRule("continuedev/sentry-nextjs"); + + expect(result).toBe(ruleContent); + expect(mockFetch).toHaveBeenCalledWith( + new URL("v0/continuedev/sentry-nextjs/latest/download", "https://api.continue.dev/") + ); + }); + + it("should handle HTTP errors when loading from hub", async () => { + mockFetch.mockResolvedValue({ + ok: false, + status: 404, + statusText: "Not Found", + } as Response); + + await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow( + 'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found' + ); + }); + + it("should handle network errors when loading from hub", async () => { + mockFetch.mockRejectedValue(new Error("Network error")); + + await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow( + 'Failed to load rule from hub "continuedev/sentry-nextjs": Network error' + ); + }); + + it("should handle invalid slug format", async () => { + // "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug + // Let's test with a slug that has wrong format but contains "/" + await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow( + 'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts' + ); + }); + + it("should handle empty zip file", async () => { + const JSZip = (await import("jszip")).default; + const zip = new JSZip(); + const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); + + mockFetch.mockResolvedValue({ + ok: true, + arrayBuffer: () => Promise.resolve(zipBuffer), + } as Response); + + await expect(processRule("continuedev/empty-rule")).rejects.toThrow( + 'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file' + ); + }); + + it("should handle zip with only directories", async () => { + const JSZip = (await import("jszip")).default; + const zip = new JSZip(); + zip.folder("docs"); // Create a directory but no files + const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); + + mockFetch.mockResolvedValue({ + ok: true, + arrayBuffer: () => Promise.resolve(zipBuffer), + } as Response); + + await expect(processRule("continuedev/directory-only")).rejects.toThrow( + 'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file' + ); + }); + + it("should prefer markdown files and ignore other file types", async () => { + const JSZip = (await import("jszip")).default; + const zip = new JSZip(); + const mdContent = "# Main Rule\n\nThis is the markdown rule content."; + const txtContent = "This is just a text file."; + + zip.file("README.txt", txtContent); + zip.file("rule.md", mdContent); + zip.file("package.json", '{"name": "test"}'); + + const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); + + mockFetch.mockResolvedValue({ + ok: true, + arrayBuffer: () => Promise.resolve(zipBuffer), + } as Response); + + const result = await processRule("continuedev/mixed-files"); + + expect(result).toBe(mdContent); + }); + + it("should handle multiple markdown files and use the first one", async () => { + const JSZip = (await import("jszip")).default; + const zip = new JSZip(); + const rule1Content = "# First Rule\n\nThis is the first rule."; + const rule2Content = "# Second Rule\n\nThis is the second rule."; + + zip.file("rule1.md", rule1Content); + zip.file("rule2.md", rule2Content); + + const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); + + mockFetch.mockResolvedValue({ + ok: true, + arrayBuffer: () => Promise.resolve(zipBuffer), + } as Response); + + const result = await processRule("continuedev/multiple-rules"); + + // Should use the first markdown file found (alphabetically) + expect(result).toBe(rule1Content); + }); + + it("should handle malformed zip files", async () => { + const invalidZipBuffer = new ArrayBuffer(10); + + mockFetch.mockResolvedValue({ + ok: true, + arrayBuffer: () => Promise.resolve(invalidZipBuffer), + } as Response); + + await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow( + 'Failed to load rule from hub "continuedev/corrupted-zip"' + ); + }); + }); + + describe("processRule logic", () => { + it("should identify hub slugs correctly", async () => { + const JSZip = (await import("jszip")).default; + const zip = new JSZip(); + zip.file("rule.md", "# Hub Rule"); + const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); + + mockFetch.mockResolvedValue({ + ok: true, + arrayBuffer: () => Promise.resolve(zipBuffer), + } as Response); + + const result = await processRule("owner/package"); + expect(result).toBe("# Hub Rule"); + expect(mockFetch).toHaveBeenCalled(); + }); + + it("should treat direct strings as content", async () => { + const directContent = "This is direct rule content"; + const result = await processRule(directContent); + expect(result).toBe(directContent); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it("should distinguish between hub slugs and file paths", async () => { + // This would be treated as a file path, not a hub slug + // since it starts with "." + await expect(processRule("./owner/package")).rejects.toThrow( + 'Failed to read rule file "./owner/package": Rule file not found' + ); + expect(mockFetch).not.toHaveBeenCalled(); + }); + }); +}); \ No newline at end of file diff --git a/src/args.ts b/src/args.ts index 169ccbc24..eb2efcbb0 100644 --- a/src/args.ts +++ b/src/args.ts @@ -1,5 +1,7 @@ import * as fs from "fs"; +import JSZip from "jszip"; import * as path from "path"; +import { env } from "./env.js"; export interface CommandLineArgs { isHeadless: boolean; @@ -29,13 +31,52 @@ function loadRuleFromFile(filePath: string): string { } /** - * Load rule content from hub.continue.dev (not yet implemented) + * Load rule content from hub.continue.dev * @param slug - The slug in format "owner/package" * @returns The rule content from the hub */ -function loadRuleFromHub(slug: string): string { - // TODO: Implement hub integration - throw new Error(`Hub rules not yet supported: ${slug}`); +async function loadRuleFromHub(slug: string): Promise { + const parts = slug.split("/"); + if (parts.length !== 2) { + throw new Error( + `Invalid hub slug format. Expected "owner/package", got: ${slug}` + ); + } + + const [ownerSlug, ruleSlug] = parts; + const downloadUrl = new URL( + `v0/${ownerSlug}/${ruleSlug}/latest/download`, + env.apiBase + ); + + try { + const response = await fetch(downloadUrl); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + // The API returns a zip file, so we need to extract the rule content + const arrayBuffer = await response.arrayBuffer(); + const zip = new JSZip(); + const zipContents = await zip.loadAsync(arrayBuffer); + + // Find the first .md or .txt file (rule content) + const ruleFiles = Object.keys(zipContents.files).filter( + (filename) => filename.endsWith(".md") && !zipContents.files[filename].dir + ); + + if (ruleFiles.length === 0) { + throw new Error("No rule content found in downloaded zip file"); + } + + // Use the first rule file found - TODO support multiple rules and parse frontmatter + const ruleFile = zipContents.files[ruleFiles[0]]; + const content = await ruleFile.async("text"); + return content; + } catch (error: any) { + throw new Error(`Failed to load rule from hub "${slug}": ${error.message}`); + } } /** @@ -43,14 +84,14 @@ function loadRuleFromHub(slug: string): string { * @param ruleSpec - Can be a file path, hub slug, or direct string content * @returns The processed rule content */ -export function processRule(ruleSpec: string): string { +export async function processRule(ruleSpec: string): Promise { // If it looks like a hub slug (contains / but doesn't start with . or /) if ( ruleSpec.includes("/") && !ruleSpec.startsWith(".") && !ruleSpec.startsWith("/") ) { - return loadRuleFromHub(ruleSpec); + return await loadRuleFromHub(ruleSpec); } // If it looks like a file path (contains . or / or ends with common file extensions) diff --git a/src/asciiArt.ts b/src/asciiArt.ts index d83a7a20f..305cf75c5 100644 --- a/src/asciiArt.ts +++ b/src/asciiArt.ts @@ -1,9 +1,20 @@ +import chalk from "chalk"; + +const b = chalk.bold.magenta; +const d = chalk.dim; + export const CONTINUE_ASCII_ART = ` - _________ _ _____________ ____ ______ - / ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/ -/ /__/ /_/ / / / / _/ // / /_/ / _/ -\\___/\\____/_/|_/ /_/ /___/_/|_/\\____/___/ + ${b("_____")}${d("____ ")}${b("_ __")}${d("___________ ____ ______")} + ${b("/ ___/")}${d(" __ \\")}${b("/ |/ /")}${d("_ __/ _/ |/ / / / / __/")} +${b("/ /__")}${d("/ /_/ ")}${b("/ /")}${d(" / / _/ // / /_/ / _/ ")} +${b("\\___/")}${d("\\____")}${b("/_/|_/")}${d(" /_/ /___/_/|_/\\____/___/")} `; +// export const CONTINUE_ASCII_ART = ` +// _________ _ _____________ ____ ______ +// / ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/ +// / /__/ /_/ / / / / _/ // / /_/ / _/ +// \\___/\\____/_/|_/ /_/ /___/_/|_/\\____/___/ +// `; export const CONTINUE_LOGO_ASCII_ART = ` @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ -31,7 +42,7 @@ export const CONTINUE_LOGO_ASCII_ART = ` @@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ - @@@@@@@@@@@@ + CONTINUE @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ diff --git a/src/auth/workos.ts b/src/auth/workos.ts index ed3222815..f465c1a1b 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -1,7 +1,3 @@ -import { - Configuration, - DefaultApi, -} from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; import * as fs from "fs"; import open from "open"; @@ -12,6 +8,7 @@ import { env } from "../env.js"; // Polyfill fetch for Node < 18 import nodeFetch from "node-fetch"; +import { getApiClient } from "../config.js"; if (!globalThis.fetch) { globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch; } @@ -231,6 +228,7 @@ async function requestDeviceAuthorization(): Promise { }; } + console.info(chalk.white("\nSigning in with Continue...")); + + // Request device authorization + const deviceAuth = await requestDeviceAuthorization(); + + console.info( + chalk.white(`Your authentication code: ${chalk.bold(deviceAuth.user_code)}`) + ); + console.info( + chalk.dim( + `If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}` + ) + ); + + // Try to open the complete verification URL in browser try { - console.info(chalk.cyan("\nStarting authentication with Continue...")); - - // Request device authorization - const deviceAuth = await requestDeviceAuthorization(); - - console.info( - chalk.yellow( - `Your authentication code: ${chalk.bold(deviceAuth.user_code)}` - ) - ); - console.info( - chalk.dim( - `If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}` - ) - ); - - // Try to open the complete verification URL in browser - try { - await open(deviceAuth.verification_uri_complete); - } catch (error) { - console.info(chalk.yellow("Unable to open browser automatically")); - } - - console.info(chalk.cyan("\nWaiting for confirmation...")); - - // Poll for token - const authConfig = await pollForDeviceToken( - deviceAuth.device_code, - deviceAuth.interval, - deviceAuth.expires_in - ); - - console.info(chalk.green("\nAuthentication successful!")); - - return authConfig; - } catch (error: any) { - console.error(chalk.red("Authentication error:"), error.message || error); - throw error; + await open(deviceAuth.verification_uri_complete); + } catch (error) { + console.info(chalk.yellow("Unable to open browser automatically")); } + + console.info(chalk.dim("\nWaiting for confirmation...")); + + // Poll for token + const authConfig = await pollForDeviceToken( + deviceAuth.device_code, + deviceAuth.interval, + deviceAuth.expires_in + ); + + console.info(chalk.white("✅ Success!")); + + return authConfig; } /** @@ -509,11 +500,7 @@ export async function ensureOrganization( } // Need to select organization - const apiClient = new DefaultApi( - new Configuration({ - accessToken: authenticatedConfig.accessToken, - }) - ); + const apiClient = getApiClient(authenticatedConfig.accessToken); try { const resp = await apiClient.listOrganizations(); @@ -586,11 +573,7 @@ export async function listUserOrganizations(): Promise< return null; } - const apiClient = new DefaultApi( - new Configuration({ - accessToken: authConfig.accessToken, - }) - ); + const apiClient = getApiClient(authConfig.accessToken); try { const resp = await apiClient.listOrganizations(); diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 41216ad1c..b5def1f59 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -1,16 +1,24 @@ import chalk from "chalk"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import * as readlineSync from "readline-sync"; -import { ensureOrganization, loadAuthConfig } from "../auth/workos.js"; +import { CONTINUE_ASCII_ART } from "../asciiArt.js"; +import { + ensureOrganization, + getOrganizationId, + loadAuthConfig, +} from "../auth/workos.js"; import { introMessage } from "../intro.js"; import { configureLogger } from "../logger.js"; import { initializeWithOnboarding } from "../onboarding.js"; import { loadSession, saveSession } from "../session.js"; import { streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; +import telemetryService from "../telemetry/telemetryService.js"; import { startTUIChat } from "../ui/index.js"; +import { safeStdout } from "../util/consoleOverride.js"; import { formatError } from "../util/formatError.js"; import logger from "../util/logger.js"; +import { getVersion } from "../version.js"; export interface ChatOptions { headless?: boolean; @@ -23,7 +31,15 @@ async function initializeChat(options: ChatOptions) { const authConfig = loadAuthConfig(); // Use onboarding flow for initialization - const result = await initializeWithOnboarding(authConfig, options.config); + if (!options.headless) { + console.log(chalk.white(CONTINUE_ASCII_ART)); + console.info(chalk.gray(`v${getVersion()}\n`)); + } + const result = await initializeWithOnboarding( + authConfig, + options.config, + options.rule + ); // Ensure organization is selected if authenticated let finalAuthConfig = authConfig; @@ -32,6 +48,14 @@ async function initializeChat(options: ChatOptions) { authConfig, options.headless ?? false ); + + // Update telemetry with organization info + if (finalAuthConfig) { + const organizationId = getOrganizationId(finalAuthConfig); + if (organizationId) { + telemetryService.updateOrganization(organizationId); + } + } } return { @@ -39,6 +63,7 @@ async function initializeChat(options: ChatOptions) { llmApi: result.llmApi, model: result.model, mcpService: result.mcpService, + apiClient: result.apiClient, }; } @@ -47,7 +72,15 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { configureLogger(options.headless ?? false); try { - let { config, llmApi, model, mcpService } = await initializeChat(options); + let { config, llmApi, model, mcpService, apiClient } = await initializeChat( + options + ); + + // Record session start + telemetryService.recordSessionStart(); + + // Start active time tracking + telemetryService.startActiveTime(); // If not in headless mode, start the TUI chat (default) if (!options.headless) { @@ -56,6 +89,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { llmApi, model, mcpService, + apiClient, prompt, options.resume, options.config, @@ -86,7 +120,10 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // If no session loaded or not resuming, initialize with system message if (chatHistory.length === 0) { const rulesSystemMessage = ""; // TODO //assistant.systemMessage; - const systemMessage = constructSystemMessage(rulesSystemMessage, options.rule); + const systemMessage = await constructSystemMessage( + rulesSystemMessage, + options.rule + ); if (systemMessage) { chatHistory.push({ role: "system", content: systemMessage }); } @@ -107,6 +144,9 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { isFirstMessage = false; + // Track user prompt + telemetryService.logUserPrompt(userInput.length, userInput); + // Add user message to history chatHistory.push({ role: "user", content: userInput }); @@ -124,9 +164,9 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { abortController ); - // In headless mode, only print the final response + // In headless mode, only print the final response using safe stdout if (options.headless && finalResponse.trim()) { - console.log(finalResponse); + safeStdout(finalResponse + "\n"); } // Save session after each successful response @@ -143,5 +183,8 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { } catch (error: any) { logger.error(chalk.red(`Fatal error: ${formatError(error)}`)); process.exit(1); + } finally { + // Stop active time tracking + telemetryService.stopActiveTime(); } -} \ No newline at end of file +} diff --git a/src/commands/commands.ts b/src/commands/commands.ts new file mode 100644 index 000000000..918bb631a --- /dev/null +++ b/src/commands/commands.ts @@ -0,0 +1,91 @@ +import { type AssistantConfig } from "@continuedev/sdk"; + +export interface SlashCommand { + name: string; + description: string; + category: "system" | "assistant"; +} + +export interface SystemCommand extends SlashCommand { + category: "system"; + requiresMultipleOrgs?: boolean; +} + +// Central definition of all system slash commands +export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ + { + name: "help", + description: "Show help message", + category: "system", + }, + { + name: "clear", + description: "Clear the chat history", + category: "system", + }, + { + name: "exit", + description: "Exit the chat", + category: "system", + }, + { + name: "login", + description: "Authenticate with your account", + category: "system", + }, + { + name: "logout", + description: "Sign out of your current session", + category: "system", + }, + { + name: "whoami", + description: "Check who you're currently logged in as", + category: "system", + }, + { + name: "org", + description: "Switch organization", + category: "system", + requiresMultipleOrgs: true, + }, + { + name: "config", + description: "Switch configuration", + category: "system", + }, +]; + +/** + * Get all available slash commands including system commands and assistant prompts + */ +export function getAllSlashCommands( + assistant: AssistantConfig +): SlashCommand[] { + // Filter system commands based on requirements + const systemCommands = SYSTEM_SLASH_COMMANDS; + // Get assistant prompt commands + const assistantCommands: SlashCommand[] = + assistant.prompts?.map((prompt) => ({ + name: prompt?.name || "", + description: prompt?.description || "", + category: "assistant" as const, + })) || []; + + return [...systemCommands, ...assistantCommands]; +} + +/** + * Get assistant prompt commands only + */ +export function getAssistantSlashCommands( + assistant: AssistantConfig +): SlashCommand[] { + return ( + assistant.prompts?.map((prompt) => ({ + name: prompt?.name || "", + description: prompt?.description || "", + category: "assistant" as const, + })) || [] + ); +} diff --git a/src/commands/logout.ts b/src/commands/logout.ts index bd520191a..b6b40c62f 100644 --- a/src/commands/logout.ts +++ b/src/commands/logout.ts @@ -1,5 +1,19 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; import { logout as workosLogout } from "../auth/workos.js"; export async function logout() { + const onboardingFlagPath = path.join( + os.homedir(), + ".continue", + ".onboarding_complete" + ); + + // Remove onboarding completion flag so user will go through onboarding again + if (fs.existsSync(onboardingFlagPath)) { + fs.unlinkSync(onboardingFlagPath); + } + workosLogout(); } diff --git a/src/config.ts b/src/config.ts index 1553d9807..88e530845 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,5 +1,6 @@ import { AssistantUnrolled, + ModelConfig, RegistryClient, unrollAssistant, } from "@continuedev/config-yaml"; @@ -13,6 +14,7 @@ import { DefaultApi, DefaultApiInterface, } from "@continuedev/sdk/dist/api/dist/index.js"; +import chalk from "chalk"; import { dirname } from "node:path"; import { AuthConfig, @@ -27,7 +29,7 @@ import { MCPService } from "./mcp.js"; export function getLlmApi( assistant: AssistantUnrolled, authConfig: AuthConfig -): [BaseLlmApi, string] { +): [BaseLlmApi, ModelConfig] { const model = assistant.models?.find((model) => model?.roles?.includes("chat") ); @@ -71,7 +73,7 @@ export function getLlmApi( ); } - return [llmApi, model.model]; + return [llmApi, model]; } async function loadConfigYaml( @@ -97,24 +99,40 @@ async function loadConfigYaml( } ); - if (unrollResult.errors?.length || !unrollResult.config) { - const errorDetails = unrollResult.errors?.join("\n") ?? "Unknown error"; + const errorDetails = unrollResult.errors; + if (!unrollResult.config) { throw new Error(`Failed to load config file:\n${errorDetails}`); + } else if (errorDetails?.length) { + const warnings = + errorDetails?.length > 1 + ? errorDetails.map((d) => `\n- ${d.message}`) + : errorDetails[0].message; + console.warn(chalk.dim(`Warning: ${warnings}`)); } return unrollResult.config; } +export function getApiClient( + accessToken: string | undefined | null +): DefaultApi { + return new DefaultApi( + new Configuration({ + basePath: env.apiBase.replace(/\/$/, ""), + accessToken: accessToken ?? undefined, + }) + ); +} + export async function loadConfig( authConfig: AuthConfig, config: string | undefined, - organizationId: string | null + organizationId: string | null, + apiClient?: DefaultApiInterface ): Promise { - const apiClient = new DefaultApi( - new Configuration({ - accessToken: authConfig?.accessToken ?? undefined, - }) - ); + if (!apiClient) { + apiClient = getApiClient(authConfig?.accessToken); + } if (!config) { // Check if there's a saved assistant slug in auth config @@ -129,7 +147,22 @@ export async function loadConfig( organizationId: organizationId ?? undefined, }); + if (assistants.length === 0) { + // In case the user doesn't have any assistants, we fall back to a default - TODO + const resp = await apiClient.getAssistant({ + ownerSlug: "continuedev", + packageSlug: "default-agent", + organizationId: organizationId ?? undefined, + }); + + if (!resp.configResult.config) { + throw new Error("Failed to load default agent."); + } + return resp.configResult.config as AssistantUnrolled; + } + const result = assistants[0].configResult; + if (result.errors?.length || !result.config) { throw new Error( result.errors?.join("\n") ?? "Failed to load assistant." @@ -179,15 +212,20 @@ export async function initialize( ): Promise<{ config: AssistantUnrolled; llmApi: BaseLlmApi; - model: string; + model: ModelConfig; mcpService: MCPService; + apiClient: DefaultApiInterface; }> { - const accessToken = getAccessToken(authConfig); const organizationId = getOrganizationId(authConfig); - - const config = await loadConfig(authConfig, configPath, organizationId); + const apiClient = getApiClient(authConfig?.accessToken); + const config = await loadConfig( + authConfig, + configPath, + organizationId, + apiClient + ); const [llmApi, model] = getLlmApi(config, authConfig); const mcpService = await MCPService.create(config); - return { config, llmApi, model, mcpService }; + return { config, llmApi, model, mcpService, apiClient }; } diff --git a/src/freeTrialTransition.ts b/src/freeTrialTransition.ts new file mode 100644 index 000000000..1a8910a3d --- /dev/null +++ b/src/freeTrialTransition.ts @@ -0,0 +1,181 @@ +import chalk from "chalk"; +import { spawn } from "child_process"; +import * as fs from "fs"; +import open from "open"; +import * as os from "os"; +import * as path from "path"; +import * as readlineSync from "readline-sync"; +import * as YAML from "yaml"; +import { env } from "./env.js"; + +const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); + +/** + * Creates or updates the local config with Anthropic API key + */ +async function createOrUpdateConfig(apiKey: string): Promise { + const configDir = path.dirname(CONFIG_PATH); + + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true }); + } + + const newModel = { + uses: "anthropic/claude-4-sonnet", + with: { + ANTHROPIC_API_KEY: apiKey, + }, + }; + + if (fs.existsSync(CONFIG_PATH)) { + const existingContent = fs.readFileSync(CONFIG_PATH, "utf8"); + let config; + + try { + config = YAML.parse(existingContent); + + // Make sure models array exists + if (!config.models) { + config.models = []; + } + + // Check if model already exists + const existingModelIndex = config.models.findIndex( + (model: any) => model.uses === "anthropic/claude-4-sonnet" + ); + + if (existingModelIndex >= 0) { + // Update existing model + config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey; + } else { + // Add new model + config.models.push(newModel); + } + } catch (error) { + // If parsing fails, create a new config + config = { + name: "Local Config", + version: "1.0.0", + schema: "v1", + models: [newModel], + }; + } + + // Write back to file + fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); + } else { + // Create new config file + const config = { + name: "Local Config", + version: "1.0.0", + schema: "v1", + models: [newModel], + }; + + fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); + } +} + +/** + * Handles the free trial transition flow for users who have maxed out their free trial + * This function provides a specialized flow that: + * 1. Assumes the user is already authenticated + * 2. Provides two specific options for continuing + * 3. Returns to the chat without restarting the entire CLI + */ +export async function handleMaxedOutFreeTrial(): Promise { + // Clear the screen but don't show ASCII art - keep it minimal since we're resuming a conversation + console.clear(); + + console.log(chalk.yellow("🚀 Free trial limit reached!\n")); + console.log("Choose how you'd like to Continue:"); + console.log(chalk.white("1. 💳 Sign up for models add-on")); + console.log(chalk.white("2. 🔑 Enter your Anthropic API key")); + + const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), { + limit: ["1", "2", ""], + limitMessage: chalk.dim("Please enter 1 or 2"), + }); + + if (choice === "1" || choice === "") { + // Option 1: Open models setup page + const modelsUrl = new URL("setup-models", env.appUrl).toString(); + console.log(chalk.blue(`Opening ${modelsUrl}...`)); + + try { + await open(modelsUrl); + console.log(chalk.green("\n✓ Browser opened successfully!")); + console.log( + chalk.dim( + "After setting up your models subscription, restart the CLI to continue." + ) + ); + } catch (error) { + console.log(chalk.yellow("\n⚠ Could not open browser automatically")); + console.log(chalk.white(`Please visit: ${modelsUrl}`)); + console.log( + chalk.dim( + "After setting up your models subscription, restart the CLI to continue." + ) + ); + } + + // Wait for user to acknowledge + readlineSync.question(chalk.dim("\nPress Enter to exit...")); + process.exit(0); + } else if (choice === "2") { + // Option 2: Enter Anthropic API key + const apiKey = readlineSync.question( + chalk.white("\nEnter your Anthropic API key: "), + { + limit: /^sk-ant-.+$/, // Must start with "sk-ant-" and have additional characters + limitMessage: chalk.dim( + "Please enter a valid Anthropic key that starts with 'sk-ant'" + ), + hideEchoBack: true, + } + ); + + if (!apiKey || !apiKey.startsWith("sk-ant-")) { + console.log( + chalk.red( + "❌ Invalid Anthropic API key. Please make sure it starts with 'sk-ant'" + ) + ); + process.exit(1); + } + + try { + await createOrUpdateConfig(apiKey); + console.log(chalk.green(`✓ API key saved successfully!`)); + } catch (error) { + console.log(chalk.red(`❌ Error saving API key: ${error}`)); + process.exit(1); + } + } + + // After setup completes, restart the CLI to resume the conversation + console.log( + chalk.green("\n🔄 Restarting Continue CLI to resume your conversation...\n") + ); + + // Get the path to the current script + const scriptPath = path.resolve(process.argv[1]); + + // Restart the CLI with the same arguments, except for the first two (node and script path) + // Use spawn instead of spawnSync, since we want to exit this process + const child = spawn( + process.execPath, + [scriptPath, ...process.argv.slice(2)], + { + stdio: "inherit", + detached: true, + } + ); + + // Unref the child to allow the parent process to exit + child.unref(); + + // Exit the current process + process.exit(0); +} diff --git a/src/index.ts b/src/index.ts index e68b421fc..6fa275e20 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,7 +3,9 @@ // Add immediate logging to debug Windows CI issues // Only log on Windows when DEBUG_CLI_TESTS is set if (process.env.DEBUG_CLI_TESTS === "1" && process.platform === "win32") { - console.error(`[CLI_START] Node ${process.version} on ${process.platform} ${process.arch}`); + console.error( + `[CLI_START] Node ${process.version} on ${process.platform} ${process.arch}` + ); console.error(`[CLI_START] Args: ${JSON.stringify(process.argv)}`); console.error(`[CLI_START] CWD: ${process.cwd()}`); console.error(`[CLI_START] __dirname: ${import.meta.url}`); @@ -13,8 +15,9 @@ import { Command } from "commander"; import { chat } from "./commands/chat.js"; import { login } from "./commands/login.js"; import { logout } from "./commands/logout.js"; -import { getVersion } from "./version.js"; +import { configureConsoleForHeadless } from "./util/consoleOverride.js"; import logger from "./util/logger.js"; +import { getVersion } from "./version.js"; // Add global error handlers to prevent uncaught errors from crashing the process process.on("unhandledRejection", (reason, promise) => { @@ -56,21 +59,28 @@ program [] as string[] ) .action(async (prompt, options) => { + // Configure console overrides FIRST, before any other logging + const isHeadless = options.print; + configureConsoleForHeadless(isHeadless); + if (options.verbose) { - logger.setLevel('debug'); + logger.setLevel("debug"); const logPath = logger.getLogPath(); const sessionId = logger.getSessionId(); - console.log(`Verbose logging enabled (session: ${sessionId})`); - console.log(`Logs: ${logPath}`); - console.log(`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`); - logger.debug('Verbose logging enabled'); + // In headless mode, suppress these verbose logs + if (!isHeadless) { + console.log(`Verbose logging enabled (session: ${sessionId})`); + console.log(`Logs: ${logPath}`); + console.log( + `Filter this session: grep '\\[${sessionId}\\]' ${logPath}` + ); + } + logger.debug("Verbose logging enabled"); } - // Map CLI options to chat options - const chatOptions = { - ...options, - headless: options.print, // Map --print to headless mode - }; - await chat(prompt, chatOptions); + // Map --print to headless mode + options.headless = options.print; + options.print = undefined; + await chat(prompt, options); }); // Login subcommand @@ -105,12 +115,14 @@ async function main() { console.error("[CLI_ERROR] Message:", error.message); console.error("[CLI_ERROR] Stack:", error.stack); console.error("[CLI_ERROR] Code:", error.code); - + // More specific error messages - if (error.code === 'MODULE_NOT_FOUND') { - console.error("[CLI_ERROR] Missing module. This might be a build or path issue."); + if (error.code === "MODULE_NOT_FOUND") { + console.error( + "[CLI_ERROR] Missing module. This might be a build or path issue." + ); } - + process.exit(1); } } diff --git a/src/intro.ts b/src/intro.ts index 02c011c14..02c5c03b4 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -1,9 +1,24 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; -import { CONTINUE_ASCII_ART } from "./asciiArt.js"; +import { readFileSync } from "fs"; +import { dirname, join } from "path"; +import { fileURLToPath } from "url"; +import { getAllSlashCommands } from "./commands/commands.js"; import { MCPService } from "./mcp.js"; -import { getAllTools } from "./streamChatResponse.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +function getVersion(): string { + try { + const packagePath = join(__dirname, "..", "package.json"); + const packageJson = JSON.parse(readFileSync(packagePath, "utf-8")); + return packageJson.version; + } catch (error) { + return "unknown"; + } +} export function loadSystemMessage( assistant: AssistantConfig @@ -14,43 +29,42 @@ export function loadSystemMessage( .join("\n"); } -export function introMessage( +export async function introMessage( config: AssistantUnrolled, - modelName: string, + model: ModelConfig, mcpService: MCPService ) { const mcpTools = mcpService.getTools() ?? []; const mcpPrompts = mcpService.getPrompts() ?? []; - console.info(chalk.cyan(CONTINUE_ASCII_ART)); + // Get all slash commands from central definition + const allCommands = getAllSlashCommands(config); - console.info(`\n${chalk.bold.blue(`Agent: ${config.name}\n`)}`); - console.info(`${chalk.yellow("Model:")} ${modelName.split("/").pop()}\n`); + console.info(`\n${chalk.bold.yellow(`Agent: ${config.name}\n`)}`); + console.info(`${chalk.blue("Model:")} ${model.name.split("/").pop()}\n`); - console.info(chalk.yellow("Tools:")); - getAllTools().forEach((tool) => { + // console.info(chalk.blue("Tools:")); + // BUILTIN_TOOLS.forEach((tool) => { + // console.info( + // `- ${chalk.white(tool.displayName)}: ${chalk.dim(tool.description ?? "")}` + // ); + // }); + // console.info(""); + + console.info(chalk.blue("Slash commands:")); + + // Display all commands from central definition + for (const command of allCommands) { console.info( - `- ${chalk.green(tool.function.name)}: ${tool.function.description ?? ""}` + `- ${chalk.white("/" + command.name)}: ${chalk.dim(command.description)}` ); - }); - console.info(""); - - console.info(chalk.yellow("Slash commands:")); - console.info(`- ${chalk.green("/exit")}: Exit the chat`); - console.info(`- ${chalk.green("/clear")}: Clear the chat history`); - console.info(`- ${chalk.green("/help")}: Show help message`); - console.info(`- ${chalk.green("/login")}: Authenticate with your account`); - console.info(`- ${chalk.green("/logout")}: Sign out of your current session`); - console.info( - `- ${chalk.green("/whoami")}: Check who you're currently logged in as` - ); - console.info(`- ${chalk.green("/org")}: Switch organization`); - console.info(`- ${chalk.green("/config")}: Switch configuration`); - for (const prompt of config.prompts ?? []) { - console.info(`- /${prompt?.name}: ${prompt?.description}`); } + + // Display MCP prompts separately since they're not part of our central definition for (const prompt of mcpPrompts) { - console.info(`- /${prompt.name}: ${prompt.description}`); + console.info( + `- ${chalk.white("/" + prompt.name)}: ${chalk.dim(prompt.description)}` + ); } console.info(""); diff --git a/src/onboarding.ts b/src/onboarding.ts index 7bd54ad60..6b5ccd076 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -1,10 +1,12 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; import * as readlineSync from "readline-sync"; +import { processRule } from "./args.js"; import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; import { initialize } from "./config.js"; import { MCPService } from "./mcp.js"; @@ -14,8 +16,9 @@ const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); export interface OnboardingResult { config: AssistantUnrolled; llmApi: BaseLlmApi; - model: string; + model: ModelConfig; mcpService: MCPService; + apiClient: DefaultApiInterface; wasOnboarded: boolean; } @@ -103,48 +106,35 @@ export async function runOnboardingFlow( configPath: string | undefined, authConfig: AuthConfig ): Promise { - console.log(chalk.cyan("\n🚀 Welcome to Continue CLI!")); - // Step 1: Check if --config flag is provided if (configPath) { const result = await initialize(authConfig, configPath); return { ...result, wasOnboarded: false }; } - // Step 2: Check if user has ~/.continue/config.yaml with acceptable model - if (await checkHasAcceptableModel(CONFIG_PATH)) { - console.log(chalk.blue(`✓ Using existing ${CONFIG_PATH}`)); - const result = await initialize(authConfig, CONFIG_PATH); + // Step 2: Present user with two options + console.log(chalk.yellow("How do you want to get started?")); + console.log(chalk.white("1. ⏩ Log in with Continue")); + console.log(chalk.white("2. 🔑 Enter your Anthropic API key")); + + const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), { + limit: ["1", "2", ""], + limitMessage: chalk.dim("Please enter 1 or 2"), + }); + + if (choice === "1" || choice === "") { + const newAuthConfig = await login(); + + const result = await initialize(newAuthConfig, undefined); return { ...result, wasOnboarded: true }; - } - - // Step 3: Present user with two options - console.log(chalk.yellow("Choose how you'd like to set up your agent:")); - console.log(chalk.white("1. Log in with Continue")); - console.log(chalk.white("2. Enter your Anthropic API key")); - - const choice = readlineSync.question( - chalk.green("\nSelect option (1 or 2): ") - ); - - if (choice === "1") { - console.log(chalk.cyan("\n🔐 Logging in with Continue...")); - try { - const newAuthConfig = await login(); - - const result = await initialize(newAuthConfig, undefined); - return { ...result, wasOnboarded: true }; - } catch (error) { - console.error( - chalk.red("❌ Login failed. Please try again or use option 2.") - ); - throw error; - } } else if (choice === "2") { - console.log(chalk.cyan("\n🔑 Setting up with Anthropic API key...")); const apiKey = readlineSync.question( - chalk.green("Enter your Anthropic API key: "), + chalk.white("\nEnter your Anthropic API key: "), { + limit: /^sk-ant-.+$/, // Must start with "sk-ant-" and have additional characters + limitMessage: chalk.dim( + "Please enter a valid Anthropic key that starts with 'sk-ant'" + ), hideEchoBack: true, } ); @@ -181,7 +171,7 @@ export async function runNormalFlow( if (isAuthenticated()) { try { const result = await initialize(authConfig, undefined); - return { ...result, wasOnboarded: true }; + return { ...result, wasOnboarded: false }; } catch (error) {} } @@ -189,7 +179,7 @@ export async function runNormalFlow( if (fs.existsSync(CONFIG_PATH)) { try { const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: true }; + return { ...result, wasOnboarded: false }; } catch (error) { console.log(chalk.yellow("⚠ Invalid config file found")); } @@ -201,7 +191,7 @@ export async function runNormalFlow( await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); const result = await initialize(authConfig, CONFIG_PATH); - return { ...result, wasOnboarded: true }; + return { ...result, wasOnboarded: false }; } // Step 5: Fall back to onboarding flow @@ -225,9 +215,60 @@ export async function markOnboardingComplete(): Promise { fs.writeFileSync(flagPath, new Date().toISOString()); } +/** + * Process rules and inject them into the assistant config + * @param config - The assistant config to modify + * @param rules - Array of rule specifications to process and inject + * @returns The modified config with injected rules + */ +async function injectRulesIntoConfig( + config: AssistantUnrolled, + rules: string[] +): Promise { + if (!rules || rules.length === 0) { + return config; + } + + let processedRules: string[] = []; + for (const ruleSpec of rules) { + try { + const processedRule = await processRule(ruleSpec); + processedRules.push(processedRule); + } catch (error: any) { + console.warn( + chalk.yellow( + `Warning: Failed to process rule "${ruleSpec}": ${error.message}` + ) + ); + } + } + + if (processedRules.length === 0) { + return config; + } + + // Clone the config to avoid mutating the original + const modifiedConfig = { ...config }; + + // Combine processed rules with existing system message if the config has one + const existingSystemMessage = (modifiedConfig as any).systemMessage || ""; + const rulesSection = processedRules.join("\n\n"); + + if (existingSystemMessage) { + ( + modifiedConfig as any + ).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`; + } else { + (modifiedConfig as any).systemMessage = rulesSection; + } + + return modifiedConfig; +} + export async function initializeWithOnboarding( authConfig: AuthConfig, - configPath: string | undefined + configPath: string | undefined, + rules?: string[] ): Promise { const firstTime = await isFirstTime(); @@ -242,5 +283,10 @@ export async function initializeWithOnboarding( result = await runNormalFlow(configPath, authConfig); } + // Inject rules into the config if provided + if (rules && rules.length > 0) { + result.config = await injectRulesIntoConfig(result.config, rules); + } + return result; } diff --git a/src/slashCommands.ts b/src/slashCommands.ts index a978b513c..40fb81541 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -7,6 +7,7 @@ import { login, logout, } from "./auth/workos.js"; +import { getAllSlashCommands } from "./commands/commands.js"; export async function handleSlashCommands( input: string, @@ -25,19 +26,10 @@ export async function handleSlashCommands( const [command, ...args] = input.slice(1).split(" "); switch (command) { case "help": + const allCommands = getAllSlashCommands(assistant); const helpMessage = [ "Available commands:", - "/help - Show this help message", - "/clear - Clear the chat history", - "/exit - Exit the chat", - "/login - Authenticate with your account", - "/logout - Sign out of your current session", - "/whoami - Check who you're currently logged in as", - "/org - Switch organization", - "/config - Switch configuration", - ...(assistant.prompts?.map( - (prompt) => `/${prompt?.name} - ${prompt?.description}` - ) ?? []), + ...allCommands.map((cmd) => `/${cmd.name} - ${cmd.description}`), ].join("\n"); return { output: helpMessage }; case "clear": @@ -58,7 +50,7 @@ export async function handleSlashCommands( } else { console.info(chalk.green(`\nLogged in successfully`)); } - + // Reload everything after successful login if (onReload) { await onReload(); @@ -112,4 +104,4 @@ export async function handleSlashCommands( } } return null; -} \ No newline at end of file +} diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index fb097076b..f112951de 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -1,28 +1,35 @@ +import { CompletionOptions, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import chalk from "chalk"; import * as dotenv from "dotenv"; import type { + ChatCompletionCreateParamsStreaming, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionTool, } from "openai/resources.mjs"; import { parseArgs } from "./args.js"; import { MCPService } from "./mcp.js"; +import telemetryService from "./telemetry/telemetryService.js"; +import { calculateTokenCost } from "./telemetry/utils.js"; import { executeToolCall } from "./tools.js"; import { BUILTIN_TOOLS } from "./tools/index.js"; -import { chatCompletionStreamWithBackoff, withExponentialBackoff } from "./util/exponentialBackoff.js"; +import { + chatCompletionStreamWithBackoff, + withExponentialBackoff, +} from "./util/exponentialBackoff.js"; import logger from "./util/logger.js"; dotenv.config(); export function getAllTools() { const args = parseArgs(); - + // If no-tools mode is enabled, return empty array if (args.noTools) { return []; } - + const allTools: ChatCompletionTool[] = BUILTIN_TOOLS.map((tool) => ({ type: "function" as const, function: { @@ -59,8 +66,6 @@ export function getAllTools() { return allTools; } -type TODO = any; - export interface StreamCallbacks { onContent?: (content: string) => void; onContentComplete?: (content: string) => void; @@ -69,199 +74,343 @@ export interface StreamCallbacks { onToolError?: (error: string, toolName?: string) => void; } -// Define a function to handle streaming responses with tool calling +interface ToolCall { + id: string; + name: string; + arguments: any; + argumentsStr: string; + startNotified: boolean; +} + +function getDefaultCompletionOptions( + opts?: CompletionOptions +): Partial { + if (!opts) return {}; + return { + max_tokens: opts.maxTokens, + temperature: opts.temperature, + frequency_penalty: opts.frequencyPenalty, + presence_penalty: opts.presencePenalty, + top_p: opts.topP, + }; +} + +// Process a single streaming response and return whether we need to continue +async function processStreamingResponse( + chatHistory: ChatCompletionMessageParam[], + model: ModelConfig, + llmApi: BaseLlmApi, + abortController: AbortController, + callbacks?: StreamCallbacks, + isHeadless?: boolean, + tools?: ChatCompletionTool[] +): Promise<{ + content: string; + toolCalls: ToolCall[]; + shouldContinue: boolean; +}> { + const requestStartTime = Date.now(); + + const streamFactory = async () => { + logger.debug("Creating chat completion stream", { + model, + messageCount: chatHistory.length, + toolCount: tools?.length || 0, + }); + return await chatCompletionStreamWithBackoff( + llmApi, + { + model: model.model, + messages: chatHistory, + stream: true, + tools, + ...getDefaultCompletionOptions(model.defaultCompletionOptions), + }, + abortController.signal + ); + }; + + let aiResponse = ""; + const toolCallsMap = new Map(); + let firstTokenTime: number | null = null; + let inputTokens = 0; + let outputTokens = 0; + + try { + const streamWithBackoff = withExponentialBackoff( + streamFactory, + abortController.signal + ); + + let chunkCount = 0; + for await (const chunk of streamWithBackoff) { + chunkCount++; + + logger.debug("Received chunk", { chunkCount, chunk }); + + // Track first token time + if ( + firstTokenTime === null && + (chunk.choices[0].delta.content || chunk.choices[0].delta.tool_calls) + ) { + firstTokenTime = Date.now(); + telemetryService.recordResponseTime( + firstTokenTime - requestStartTime, + model.model, + "time_to_first_token", + (tools?.length || 0) > 0 + ); + } + + // Track token usage if available + if (chunk.usage) { + inputTokens = chunk.usage.prompt_tokens || 0; + outputTokens = chunk.usage.completion_tokens || 0; + } + + // Check if we should abort + if (abortController?.signal.aborted) { + logger.debug("Stream aborted"); + break; + } + + // Safety check: ensure chunk has the expected structure + if (!chunk.choices || !chunk.choices[0]) { + logger.warn("Malformed chunk received - missing choices", { chunk }); + continue; + } + + const choice = chunk.choices[0]; + if (!choice.delta) { + logger.warn("Malformed chunk received - missing delta", { chunk }); + continue; + } + + // Handle regular content + if (choice.delta.content) { + const content = choice.delta.content; + if (callbacks?.onContent) { + callbacks.onContent(content); + } else if (!isHeadless) { + process.stdout.write(chalk.white(content)); + } + aiResponse += content; + } + + // Handle tool calls + if (choice.delta.tool_calls) { + for (const toolCallDelta of choice.delta.tool_calls) { + // Get or create tool call + if (toolCallDelta.id) { + if (!toolCallsMap.has(toolCallDelta.id)) { + toolCallsMap.set(toolCallDelta.id, { + id: toolCallDelta.id, + name: "", + arguments: null, + argumentsStr: "", + startNotified: false, + }); + } + } + + const toolCall = toolCallsMap.get(toolCallDelta.id || ""); + if (!toolCall) continue; + + // Update name + if (toolCallDelta.function?.name) { + toolCall.name = toolCallDelta.function.name; + } + + // Accumulate arguments + if (toolCallDelta.function?.arguments) { + toolCall.argumentsStr += toolCallDelta.function.arguments; + + // Try to parse when we might have complete JSON + try { + toolCall.arguments = JSON.parse(toolCall.argumentsStr); + + // Notify on first successful parse + if (!toolCall.startNotified && toolCall.name) { + toolCall.startNotified = true; + if (callbacks?.onToolStart) { + callbacks.onToolStart(toolCall.name, toolCall.arguments); + } else if (!isHeadless) { + process.stdout.write( + `\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold( + toolCall.name + )}${chalk.yellow("]")}` + ); + } + } + } catch (e) { + // JSON not complete yet, continue + } + } + } + } + } + + const responseEndTime = Date.now(); + const totalDuration = responseEndTime - requestStartTime; + + // Record API request metrics + const cost = calculateTokenCost(inputTokens, outputTokens, model.model); + + telemetryService.recordTokenUsage(inputTokens, "input", model.model); + telemetryService.recordTokenUsage(outputTokens, "output", model.model); + telemetryService.recordCost(cost, model.model); + + telemetryService.recordResponseTime( + totalDuration, + model.model, + "total_response_time", + (tools?.length || 0) > 0 + ); + + // Log API request event + telemetryService.logApiRequest( + model.model, + totalDuration, + true, // success + undefined, // no error + inputTokens, + outputTokens, + cost + ); + + logger.debug("Stream complete", { + chunkCount, + responseLength: aiResponse.length, + toolCallsCount: toolCallsMap.size, + inputTokens, + outputTokens, + cost, + duration: totalDuration, + }); + } catch (error: any) { + const errorDuration = Date.now() - requestStartTime; + + // Log failed API request + telemetryService.logApiRequest( + model.model, + errorDuration, + false, // failed + error.message || String(error) + ); + + if (error.name === "AbortError" || abortController?.signal.aborted) { + logger.debug("Stream aborted by user"); + return { content: aiResponse, toolCalls: [], shouldContinue: false }; + } + throw error; + } + + const toolCalls = Array.from(toolCallsMap.values()); + + // Validate tool calls have complete arguments + const validToolCalls = toolCalls.filter((tc) => { + if (!tc.arguments || !tc.name) { + logger.error("Incomplete tool call", { + id: tc.id, + name: tc.name, + hasArguments: !!tc.arguments, + argumentsStr: tc.argumentsStr, + }); + return false; + } + return true; + }); + + return { + content: aiResponse, + toolCalls: validToolCalls, + shouldContinue: validToolCalls.length > 0, + }; +} + +// Main function that handles the conversation loop export async function streamChatResponse( chatHistory: ChatCompletionMessageParam[], - model: string, + model: ModelConfig, llmApi: BaseLlmApi, abortController: AbortController, callbacks?: StreamCallbacks ) { + logger.debug("streamChatResponse called", { + model, + historyLength: chatHistory.length, + hasCallbacks: !!callbacks, + }); + const args = parseArgs(); const isHeadless = args.isHeadless; - // Prepare tools for the API call - const toolsForRequest = getAllTools(); + const tools = getAllTools(); + + logger.debug("Tools prepared", { + toolCount: tools.length, + toolNames: tools.map((t) => t.function.name), + }); let fullResponse = ""; - let currentToolCalls: TODO[] = []; - let shouldContinueConversation = true; - while (shouldContinueConversation) { - logger.debug('Starting new conversation iteration', { hasToolCalls: currentToolCalls.length > 0 }); - // Factory function to create the stream generator - const streamFactory = async () => { - logger.debug('Creating chat completion stream', { model, messageCount: chatHistory.length, toolCount: toolsForRequest.length }); - return await chatCompletionStreamWithBackoff( + while (true) { + logger.debug("Starting conversation iteration"); + + // Get response from LLM + const { content, toolCalls, shouldContinue } = + await processStreamingResponse( + chatHistory, + model, llmApi, - { - model, - messages: chatHistory, - stream: true, - tools: toolsForRequest, - }, - abortController.signal - ); - }; - - let aiResponse = ""; - currentToolCalls = []; - let currentToolCallId = ""; - let toolArguments = ""; - - try { - // Use the exponential backoff wrapper for the entire stream - const streamWithBackoff = withExponentialBackoff( - streamFactory, - abortController.signal + abortController, + callbacks, + isHeadless, + tools ); - for await (const chunk of streamWithBackoff) { - logger.debug('Received stream chunk', { hasContent: !!chunk.choices[0].delta.content, hasToolCalls: !!chunk.choices[0].delta.tool_calls }); - // Check if we should abort - if (abortController?.signal.aborted) { - break; - } + fullResponse += content; - // Handle regular content - if (chunk.choices[0].delta.content) { - const content = chunk.choices[0].delta.content; - if (callbacks?.onContent) { - callbacks.onContent(content); - } else if (!isHeadless) { - process.stdout.write(chalk.white(content)); - } - aiResponse += content; - fullResponse += content; - } - - // Handle tool calls - if (chunk.choices[0].delta.tool_calls) { - for (const toolCallDelta of chunk.choices[0].delta.tool_calls) { - // Initialize a new tool call if we get an index and id - if (toolCallDelta.index !== undefined && toolCallDelta.id) { - if (!currentToolCalls[toolCallDelta.index]) { - currentToolCalls[toolCallDelta.index] = { - id: toolCallDelta.id, - name: "", - arguments: {}, - startNotified: false, - }; - } - currentToolCallId = toolCallDelta.id; - } - - // Add function name if present - if (toolCallDelta.function?.name) { - const toolCall = currentToolCalls.find( - (tc) => tc.id === currentToolCallId - ); - if (toolCall) { - if (!toolCall.name) { - toolCall.name = toolCallDelta.function.name; - toolCall.startNotified = false; - } - } - } - - // Collect function arguments - if (toolCallDelta.function?.arguments) { - const toolCall = currentToolCalls.find( - (tc) => tc.id === currentToolCallId - ); - if (toolCall) { - // Accumulate arguments as string to later parse as JSON - toolArguments += toolCallDelta.function.arguments; - - try { - // Try to parse complete JSON - const parsed = JSON.parse(toolArguments); - toolCall.arguments = parsed; - - // Notify start if we haven't already and have both name and args - if (toolCall.name && !toolCall.startNotified) { - toolCall.startNotified = true; - if (callbacks?.onToolStart) { - callbacks.onToolStart(toolCall.name, toolCall.arguments); - } else if (!isHeadless) { - process.stdout.write( - `\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold( - toolCall.name - )}${chalk.yellow("]")}` - ); - } - } - } catch (e) { - // Not complete JSON yet, continue collecting - } - } - } - } - } - } - } catch (error: any) { - // Handle AbortError gracefully - this is expected when user cancels - if (error.name === 'AbortError' || abortController?.signal.aborted) { - // Stream was aborted, this is expected behavior - return fullResponse; - } - // For other errors, re-throw them - logger.error( - chalk.red("Error in streamChatResponse:"), - error - ); - throw error; + // Add newline after content if needed + if (!callbacks?.onContent && !isHeadless && content) { + logger.info(""); } - if (!callbacks?.onContent && !isHeadless) { - logger.info(""); // Add a newline after the response + // Notify content complete + if (content && callbacks?.onContentComplete) { + callbacks.onContentComplete(content); } - // Notify that content is complete if we have content and are about to process tool calls - if ( - aiResponse.trim() && - currentToolCalls.length > 0 && - callbacks?.onContentComplete - ) { - callbacks.onContentComplete(aiResponse); - } - - // Add the assistant's response to chat history if there's content or tool calls - if (currentToolCalls.length > 0) { - const toolCalls: ChatCompletionMessageToolCall[] = currentToolCalls.map( - (tc) => ({ + // Add assistant message to history + if (toolCalls.length > 0) { + const toolCallsForHistory: ChatCompletionMessageToolCall[] = + toolCalls.map((tc) => ({ id: tc.id, type: "function", function: { name: tc.name, arguments: JSON.stringify(tc.arguments), }, - }) - ); + })); + chatHistory.push({ role: "assistant", - content: aiResponse, - tool_calls: toolCalls, + content: content || null, + tool_calls: toolCallsForHistory, }); - } else if (aiResponse.trim()) { - // Only add assistant response if there's actual content - chatHistory.push({ role: "assistant", content: aiResponse }); - // Also notify content complete for standalone messages - if (callbacks?.onContentComplete) { - callbacks.onContentComplete(aiResponse); - } - } - // If we have tool calls, execute them - if (currentToolCalls.length > 0) { - for (const toolCall of currentToolCalls) { + // Execute tool calls + for (const toolCall of toolCalls) { try { - // Execute the tool + logger.debug("Executing tool", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + const toolResult = await executeToolCall({ name: toolCall.name, arguments: toolCall.arguments, }); - // Add tool result to chat history chatHistory.push({ role: "tool", tool_call_id: toolCall.id, @@ -277,30 +426,45 @@ export async function streamChatResponse( const errorMessage = `Error executing tool ${toolCall.name}: ${ error instanceof Error ? error.message : String(error) }`; + + logger.error("Tool execution failed", { + name: toolCall.name, + error: errorMessage, + }); + chatHistory.push({ role: "tool", tool_call_id: toolCall.id, content: errorMessage, }); + if (callbacks?.onToolError) { callbacks.onToolError(errorMessage, toolCall.name); } else if (!isHeadless) { console.info( `${chalk.red("[Tool error:")} ${chalk.red( errorMessage - )}${chalk.red(")")}` + )}${chalk.red("]")}` ); } } } + } else if (content) { + // Just content, no tools + chatHistory.push({ role: "assistant", content }); + } - // Continue the conversation with the tool results - shouldContinueConversation = true; - } else { - // No more tool calls, end the conversation - shouldContinueConversation = false; + // Check if we should continue + if (!shouldContinue) { + logger.debug("Conversation complete - no more tool calls"); + break; } } + logger.debug("streamChatResponse complete", { + totalResponseLength: fullResponse.length, + totalMessages: chatHistory.length, + }); + return fullResponse; } \ No newline at end of file diff --git a/src/systemMessage.test.ts b/src/systemMessage.test.ts index 58706696f..e21058b12 100644 --- a/src/systemMessage.test.ts +++ b/src/systemMessage.test.ts @@ -1,9 +1,9 @@ import { constructSystemMessage } from './systemMessage.js'; describe('constructSystemMessage', () => { - it('should return base system message with rules when rulesSystemMessage is provided', () => { + it('should return base system message with rules when rulesSystemMessage is provided', async () => { const rulesMessage = 'These are the rules for the assistant.'; - const result = constructSystemMessage(rulesMessage); + const result = await constructSystemMessage(rulesMessage); expect(result).toContain('You are an agent in the Continue CLI'); expect(result).toContain(''); @@ -11,17 +11,17 @@ describe('constructSystemMessage', () => { expect(result).toContain(''); }); - it('should return base system message with agent content when no rules but agent file exists', () => { + it('should return base system message with agent content when no rules but agent file exists', async () => { // The implementation checks for agent files like AGENTS.md which exists in this project - const result = constructSystemMessage(''); + const result = await constructSystemMessage(''); expect(result).toContain('You are an agent in the Continue CLI'); expect(result).toContain(''); expect(result).toContain('AGENTS.md'); }); - it('should include base system message components', () => { - const result = constructSystemMessage(''); + it('should include base system message components', async () => { + const result = await constructSystemMessage(''); expect(result).toContain('You are an agent in the Continue CLI'); expect(result).toContain(''); @@ -30,72 +30,72 @@ describe('constructSystemMessage', () => { expect(result).toContain('Any file paths you return in your final response MUST be absolute'); }); - it('should handle whitespace-only rules message', () => { - const result = constructSystemMessage(' '); + it('should handle whitespace-only rules message', async () => { + const result = await constructSystemMessage(' '); expect(result).toContain('You are an agent in the Continue CLI'); expect(result).toContain(''); }); - it('should include working directory information', () => { - const result = constructSystemMessage(''); + it('should include working directory information', async () => { + const result = await constructSystemMessage(''); expect(result).toContain('Working directory:'); expect(result).toContain(''); }); - it('should include platform information', () => { - const result = constructSystemMessage(''); + it('should include platform information', async () => { + const result = await constructSystemMessage(''); expect(result).toContain('Platform:'); }); - it('should include current date', () => { - const result = constructSystemMessage(''); + it('should include current date', async () => { + const result = await constructSystemMessage(''); expect(result).toContain('Today\'s date:'); expect(result).toContain(new Date().toISOString().split('T')[0]); }); - it('should format rules section correctly', () => { + it('should format rules section correctly', async () => { const rulesMessage = 'Rule 1: Do this\nRule 2: Do that'; - const result = constructSystemMessage(rulesMessage); + const result = await constructSystemMessage(rulesMessage); expect(result).toContain(''); expect(result).toContain(rulesMessage); expect(result).toContain(''); }); - it('should handle multiline rules message', () => { + it('should handle multiline rules message', async () => { const rulesMessage = `Rule 1: First rule Rule 2: Second rule Rule 3: Third rule`; - const result = constructSystemMessage(rulesMessage); + const result = await constructSystemMessage(rulesMessage); expect(result).toContain(rulesMessage); expect(result).toContain(''); expect(result).toContain(''); }); - it('should handle special characters in rules message', () => { + it('should handle special characters in rules message', async () => { const rulesMessage = 'Rule with characters & symbols!'; - const result = constructSystemMessage(rulesMessage); + const result = await constructSystemMessage(rulesMessage); expect(result).toContain(rulesMessage); expect(result).toContain(''); }); - it('should handle very long rules message', () => { + it('should handle very long rules message', async () => { const rulesMessage = 'A'.repeat(1000); - const result = constructSystemMessage(rulesMessage); + const result = await constructSystemMessage(rulesMessage); expect(result).toContain(rulesMessage); expect(result).toContain(''); }); - it('should combine rules and agent content when both are present', () => { + it('should combine rules and agent content when both are present', async () => { const rulesMessage = 'These are the rules.'; - const result = constructSystemMessage(rulesMessage); + const result = await constructSystemMessage(rulesMessage); expect(result).toContain(''); expect(result).toContain(rulesMessage); diff --git a/src/systemMessage.ts b/src/systemMessage.ts index fe456f533..fa23d6016 100644 --- a/src/systemMessage.ts +++ b/src/systemMessage.ts @@ -99,7 +99,10 @@ ${getGitStatus()} * @param additionalRules - Additional rules from --rule flags * @returns The comprehensive system message with base message and rules section */ -export function constructSystemMessage(rulesSystemMessage: string, additionalRules?: string[]): string { +export async function constructSystemMessage( + rulesSystemMessage: string, + additionalRules?: string[] +): Promise { const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; let agentContent = ""; @@ -123,10 +126,12 @@ export function constructSystemMessage(rulesSystemMessage: string, additionalRul if (additionalRules && additionalRules.length > 0) { for (const ruleSpec of additionalRules) { try { - const processedRule = processRule(ruleSpec); + const processedRule = await processRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { - console.warn(`Warning: Failed to process rule "${ruleSpec}": ${error.message}`); + console.warn( + `Warning: Failed to process rule "${ruleSpec}": ${error.message}` + ); } } } @@ -149,7 +154,7 @@ export function constructSystemMessage(rulesSystemMessage: string, additionalRul // Add processed rules from --rule flags if (processedRules.length > 0) { - const separator = (rulesSystemMessage || agentContent) ? "\n\n" : "\n"; + const separator = rulesSystemMessage || agentContent ? "\n\n" : "\n"; systemMessage += `${separator}${processedRules.join("\n\n")}`; } diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts new file mode 100644 index 000000000..b9f77aa6e --- /dev/null +++ b/src/telemetry/telemetryService.ts @@ -0,0 +1,548 @@ +import { metrics } from "@opentelemetry/api"; +import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http"; +import { resourceFromAttributes } from "@opentelemetry/resources"; +import { + ConsoleMetricExporter, + MeterProvider, + PeriodicExportingMetricReader, +} from "@opentelemetry/sdk-metrics"; +import { + SEMRESATTRS_DEPLOYMENT_ENVIRONMENT, + SEMRESATTRS_OS_TYPE, + SEMRESATTRS_PROCESS_PID, + SEMRESATTRS_SERVICE_NAME, + SEMRESATTRS_SERVICE_VERSION, +} from "@opentelemetry/semantic-conventions"; +import os from "os"; +import { v4 as uuidv4 } from "uuid"; +import logger from "../util/logger.js"; +import { getVersion } from "../version.js"; + +export interface TelemetryConfig { + enabled: boolean; + sessionId: string; + organizationId?: string; + accountUuid?: string; + includeSessionId: boolean; + includeVersion: boolean; + includeAccountUuid: boolean; +} + +class TelemetryService { + private meterProvider: MeterProvider | null = null; + private meter: any = null; + private config: TelemetryConfig; + private startTime = Date.now(); + private activeStartTime: number | null = null; + private totalActiveTime = 0; + + // Metrics + private sessionCounter: any = null; + private linesOfCodeCounter: any = null; + private pullRequestCounter: any = null; + private commitCounter: any = null; + private costCounter: any = null; + private tokenCounter: any = null; + private codeEditDecisionCounter: any = null; + private activeTimeCounter: any = null; + private authAttemptsCounter: any = null; + private mcpConnectionsGauge: any = null; + private startupTimeHistogram: any = null; + private responseTimeHistogram: any = null; + + constructor() { + this.config = this.loadConfig(); + if (this.config.enabled) { + this.initialize(); + } + } + + private loadConfig(): TelemetryConfig { + const hasOtelConfig = !!( + process.env.OTEL_EXPORTER_OTLP_ENDPOINT || + process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT || + process.env.OTEL_METRICS_EXPORTER + ); + const enabled = + process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0" && hasOtelConfig; + const sessionId = uuidv4(); + + return { + enabled, + sessionId, + organizationId: process.env.ORGANIZATION_ID, + accountUuid: process.env.ACCOUNT_UUID, + includeSessionId: process.env.OTEL_METRICS_INCLUDE_SESSION_ID !== "false", + includeVersion: process.env.OTEL_METRICS_INCLUDE_VERSION === "true", + includeAccountUuid: + process.env.OTEL_METRICS_INCLUDE_ACCOUNT_UUID !== "false", + }; + } + + private initialize() { + try { + // Create resource + const resource = resourceFromAttributes({ + [SEMRESATTRS_SERVICE_NAME]: "continue-cli", + [SEMRESATTRS_SERVICE_VERSION]: getVersion(), + [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]: + process.env.NODE_ENV || "development", + [SEMRESATTRS_OS_TYPE]: os.type(), + [SEMRESATTRS_PROCESS_PID]: process.pid.toString(), + }); + + // Configure exporters + const readers: any[] = []; + const metricsExporters = ( + process.env.OTEL_METRICS_EXPORTER || "console" + ).split(","); + + for (const exporterType of metricsExporters) { + switch (exporterType.trim()) { + case "otlp": + readers.push( + new PeriodicExportingMetricReader({ + exporter: new OTLPMetricExporter({ + url: + process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT || + `${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/metrics` || + "http://localhost:4318/v1/metrics", + headers: this.parseHeaders( + process.env.OTEL_EXPORTER_OTLP_HEADERS || "" + ), + }), + exportIntervalMillis: parseInt( + process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000" + ), + }) + ); + break; + case "console": + readers.push( + new PeriodicExportingMetricReader({ + exporter: new ConsoleMetricExporter(), + exportIntervalMillis: parseInt( + process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000" + ), + }) + ); + break; + } + } + + // Create meter provider + this.meterProvider = new MeterProvider({ + resource, + readers, + }); + + metrics.setGlobalMeterProvider(this.meterProvider); + this.meter = metrics.getMeter("continue-cli", getVersion()); + + this.initializeMetrics(); + + logger.debug("Telemetry service initialized", { + sessionId: this.config.sessionId, + exporters: metricsExporters, + }); + } catch (error) { + logger.error("Failed to initialize telemetry", error); + } + } + + private parseHeaders(headersStr: string): Record { + const headers: Record = {}; + if (!headersStr) return headers; + + headersStr.split(",").forEach((header) => { + const [key, value] = header.split("="); + if (key && value) { + headers[key.trim()] = value.trim(); + } + }); + + return headers; + } + + private initializeMetrics() { + if (!this.meter) return; + + // Core metrics (Claude Code compatible) + this.sessionCounter = this.meter.createCounter( + "continue.cli.session.count", + { + description: "Count of CLI sessions started", + unit: "count", + } + ); + + this.linesOfCodeCounter = this.meter.createCounter( + "continue.cli.lines_of_code.count", + { + description: "Count of lines of code modified", + unit: "count", + } + ); + + this.pullRequestCounter = this.meter.createCounter( + "continue.cli.pull_request.count", + { + description: "Number of pull requests created", + unit: "count", + } + ); + + this.commitCounter = this.meter.createCounter("continue.cli.commit.count", { + description: "Number of git commits created", + unit: "count", + }); + + this.costCounter = this.meter.createCounter("continue.cli.cost.usage", { + description: "Cost of the Continue CLI session", + unit: "USD", + }); + + this.tokenCounter = this.meter.createCounter("continue.cli.token.usage", { + description: "Number of tokens used", + unit: "tokens", + }); + + this.codeEditDecisionCounter = this.meter.createCounter( + "continue.cli.code_edit_tool.decision", + { + description: "Count of code editing tool permission decisions", + unit: "count", + } + ); + + this.activeTimeCounter = this.meter.createCounter( + "continue.cli.active_time.total", + { + description: "Total active time in seconds", + unit: "s", + } + ); + + // Additional Continue CLI specific metrics + this.authAttemptsCounter = this.meter.createCounter( + "continue.cli.auth.attempts", + { + description: "Authentication attempts", + unit: "{attempt}", + } + ); + + this.mcpConnectionsGauge = this.meter.createObservableGauge( + "continue.cli.mcp.connections", + { + description: "Active MCP connections", + unit: "{connection}", + } + ); + + this.startupTimeHistogram = this.meter.createHistogram( + "continue.cli.startup.time", + { + description: "Time from CLI start to ready state", + unit: "ms", + } + ); + + this.responseTimeHistogram = this.meter.createHistogram( + "continue.cli.response_time", + { + description: "LLM response time metrics", + unit: "ms", + } + ); + } + + // Check if telemetry is enabled - this is the single point of checking + private isEnabled(): boolean { + return this.config.enabled && this.meter !== null; + } + + private getStandardAttributes( + additionalAttributes: Record = {} + ) { + const attributes: Record = { ...additionalAttributes }; + + if (this.config.includeSessionId) { + attributes["session.id"] = this.config.sessionId; + } + + if (this.config.includeVersion) { + attributes["app.version"] = getVersion(); + } + + if (this.config.organizationId) { + attributes["organization.id"] = this.config.organizationId; + } + + if (this.config.includeAccountUuid && this.config.accountUuid) { + attributes["user.account_uuid"] = this.config.accountUuid; + } + + // Detect terminal type + const terminalType = this.detectTerminalType(); + if (terminalType) { + attributes["terminal.type"] = terminalType; + } + + return attributes; + } + + private detectTerminalType(): string | undefined { + if (process.env.TERM_PROGRAM) { + return process.env.TERM_PROGRAM; + } + if (process.env.VSCODE_PID) { + return "vscode"; + } + if (process.env.TMUX) { + return "tmux"; + } + return undefined; + } + + // Public methods for tracking metrics + + public recordSessionStart() { + if (!this.isEnabled()) return; + + this.sessionCounter.add(1, this.getStandardAttributes()); + this.recordStartupTime(Date.now() - this.startTime); + } + + public recordLinesOfCodeModified( + type: "added" | "removed", + count: number, + language?: string + ) { + if (!this.isEnabled()) return; + + const attributes = this.getStandardAttributes({ type }); + if (language) { + attributes.language = language; + } + + this.linesOfCodeCounter.add(count, attributes); + } + + public recordPullRequestCreated() { + if (!this.isEnabled()) return; + + this.pullRequestCounter.add(1, this.getStandardAttributes()); + } + + public recordCommitCreated() { + if (!this.isEnabled()) return; + + this.commitCounter.add(1, this.getStandardAttributes()); + } + + public recordCost(cost: number, model: string) { + if (!this.isEnabled()) return; + + this.costCounter.add(cost, this.getStandardAttributes({ model })); + } + + public recordTokenUsage( + tokens: number, + type: "input" | "output" | "cacheRead" | "cacheCreation", + model: string + ) { + if (!this.isEnabled()) return; + + this.tokenCounter.add(tokens, this.getStandardAttributes({ type, model })); + } + + public recordCodeEditDecision( + tool: string, + decision: "accept" | "reject", + language?: string + ) { + if (!this.isEnabled()) return; + + const attributes = this.getStandardAttributes({ tool, decision }); + if (language) { + attributes.language = language; + } + + this.codeEditDecisionCounter.add(1, attributes); + } + + public startActiveTime() { + if (!this.isEnabled()) return; + + if (this.activeStartTime === null) { + this.activeStartTime = Date.now(); + } + } + + public stopActiveTime() { + if (!this.isEnabled()) return; + + if (this.activeStartTime !== null) { + this.totalActiveTime += Date.now() - this.activeStartTime; + this.activeStartTime = null; + + this.activeTimeCounter.add( + this.totalActiveTime / 1000, + this.getStandardAttributes() + ); + } + } + + public recordAuthAttempt( + result: "success" | "failure" | "cancelled", + method: "workos" | "token" + ) { + if (!this.isEnabled()) return; + + this.authAttemptsCounter.add( + 1, + this.getStandardAttributes({ result, method }) + ); + } + + public recordMCPConnection( + serverName: string, + status: "connected" | "disconnected" | "error" + ) { + if (!this.isEnabled()) return; + + const value = status === "connected" ? 1 : 0; + // Note: Observable gauge callback will be implemented when MCP monitoring is added + if (this.mcpConnectionsGauge) { + // This is a placeholder - observable gauges work differently + logger.debug("MCP connection status", { serverName, status, value }); + } + } + + public recordStartupTime( + timeMs: number, + mode?: "tui" | "headless" | "standard", + coldStart?: boolean + ) { + if (!this.isEnabled()) return; + + const attributes = this.getStandardAttributes(); + if (mode) attributes.mode = mode; + if (coldStart !== undefined) attributes.cold_start = coldStart.toString(); + + this.startupTimeHistogram.record(timeMs, attributes); + } + + public recordResponseTime( + timeMs: number, + model: string, + metricType: "time_to_first_token" | "total_response_time", + hasTools?: boolean + ) { + if (!this.isEnabled()) return; + + const attributes = this.getStandardAttributes({ + model, + metric_type: metricType, + }); + if (hasTools !== undefined) attributes.has_tools = hasTools.toString(); + + this.responseTimeHistogram.record(timeMs, attributes); + } + + // Event logging methods (these will be implemented when OTLP logs support is added) + public logUserPrompt(promptLength: number, prompt?: string) { + if (!this.isEnabled()) return; + + const attributes = this.getStandardAttributes({ + "event.name": "user_prompt", + "event.timestamp": new Date().toISOString(), + prompt_length: promptLength.toString(), + }); + + if (process.env.OTEL_LOG_USER_PROMPTS === "1" && prompt) { + attributes.prompt = prompt; + } + + // TODO: Implement OTLP logs export + logger.debug("User prompt event", attributes); + } + + public logToolResult( + toolName: string, + success: boolean, + durationMs: number, + error?: string, + decision?: "accept" | "reject", + source?: string, + toolParameters?: string + ) { + if (!this.isEnabled()) return; + + const attributes = this.getStandardAttributes({ + "event.name": "tool_result", + "event.timestamp": new Date().toISOString(), + tool_name: toolName, + success: success.toString(), + duration_ms: durationMs.toString(), + }); + + if (error) attributes.error = error; + if (decision) attributes.decision = decision; + if (source) attributes.source = source; + if (toolParameters) attributes.tool_parameters = toolParameters; + + // TODO: Implement OTLP logs export + logger.debug("Tool result event", attributes); + } + + public logApiRequest( + model: string, + durationMs: number, + success: boolean, + error?: string, + inputTokens?: number, + outputTokens?: number, + costUsd?: number + ) { + if (!this.isEnabled()) return; + + const attributes = this.getStandardAttributes({ + "event.name": "api_request", + "event.timestamp": new Date().toISOString(), + model, + duration_ms: durationMs.toString(), + success: success.toString(), + }); + + if (error) attributes.error = error; + if (inputTokens) attributes.input_tokens = inputTokens.toString(); + if (outputTokens) attributes.output_tokens = outputTokens.toString(); + if (costUsd) attributes.cost_usd = costUsd.toString(); + + // TODO: Implement OTLP logs export + logger.debug("API request event", attributes); + } + + public updateOrganization(organizationId: string) { + this.config.organizationId = organizationId; + } + + public updateAccountUuid(accountUuid: string) { + this.config.accountUuid = accountUuid; + } + + public getSessionId(): string { + return this.config.sessionId; + } + + public shutdown() { + this.stopActiveTime(); + return this.meterProvider?.shutdown(); + } +} + +// Export the singleton instance directly +export const telemetryService = new TelemetryService(); +export default telemetryService; diff --git a/src/telemetry/utils.ts b/src/telemetry/utils.ts new file mode 100644 index 000000000..132ce9b6c --- /dev/null +++ b/src/telemetry/utils.ts @@ -0,0 +1,154 @@ +import { diffLines } from "diff"; +import path from "path"; + +/** + * Calculate lines of code added/removed from a file diff + */ +export function calculateLinesOfCodeDiff( + oldContent: string, + newContent: string +): { added: number; removed: number } { + const diff = diffLines(oldContent, newContent); + let added = 0; + let removed = 0; + + for (const part of diff) { + if (part.added) { + added += part.count || 0; + } else if (part.removed) { + removed += part.count || 0; + } + } + + return { added, removed }; +} + +/** + * Extract programming language from file path + */ +export function getLanguageFromFilePath(filePath: string): string { + const ext = path.extname(filePath).toLowerCase(); + + const languageMap: Record = { + ".js": "JavaScript", + ".jsx": "JavaScript", + ".ts": "TypeScript", + ".tsx": "TypeScript", + ".py": "Python", + ".java": "Java", + ".cpp": "C++", + ".c": "C", + ".cs": "C#", + ".php": "PHP", + ".rb": "Ruby", + ".go": "Go", + ".rs": "Rust", + ".swift": "Swift", + ".kt": "Kotlin", + ".scala": "Scala", + ".clj": "Clojure", + ".hs": "Haskell", + ".ml": "OCaml", + ".elm": "Elm", + ".dart": "Dart", + ".lua": "Lua", + ".r": "R", + ".m": "Objective-C", + ".mm": "Objective-C++", + ".sh": "Shell", + ".bash": "Bash", + ".zsh": "Zsh", + ".fish": "Fish", + ".ps1": "PowerShell", + ".html": "HTML", + ".css": "CSS", + ".scss": "SCSS", + ".sass": "Sass", + ".less": "Less", + ".vue": "Vue", + ".svelte": "Svelte", + ".md": "Markdown", + ".json": "JSON", + ".xml": "XML", + ".yaml": "YAML", + ".yml": "YAML", + ".toml": "TOML", + ".ini": "INI", + ".cfg": "Config", + ".conf": "Config", + ".sql": "SQL", + ".dockerfile": "Dockerfile", + }; + + return languageMap[ext] || "unknown"; +} + +/** + * Extract the first word (command type) from a shell command + */ +export function extractCommandType(command: string): string { + return command.trim().split(/\s+/)[0] || "unknown"; +} + +/** + * Check if a command is a git commit command + */ +export function isGitCommitCommand(command: string): boolean { + const trimmed = command.trim().toLowerCase(); + return trimmed.startsWith("git commit") || trimmed.startsWith("git-commit"); +} + +/** + * Check if a command is a pull request creation command + */ +export function isPullRequestCommand(command: string): boolean { + const trimmed = command.trim().toLowerCase(); + return ( + trimmed.includes("gh pr create") || + (trimmed.includes("git push") && trimmed.includes("pull-request")) || + trimmed.includes("hub pull-request") || + trimmed.includes("gitlab mr create") + ); +} + +/** + * Simple cost calculation based on tokens and model + * This should be updated with actual pricing from model providers + */ +export function calculateTokenCost( + inputTokens: number, + outputTokens: number, + model: string +): number { + // Pricing per 1K tokens (these are approximate and should be updated) + const pricingMap: Record = { + "gpt-4": { input: 0.03, output: 0.06 }, + "gpt-4-turbo": { input: 0.01, output: 0.03 }, + "gpt-3.5-turbo": { input: 0.0015, output: 0.002 }, + "claude-3-5-sonnet-20241022": { input: 0.003, output: 0.015 }, + "claude-3-sonnet": { input: 0.003, output: 0.015 }, + "claude-3-haiku": { input: 0.00025, output: 0.00125 }, + "claude-3-opus": { input: 0.015, output: 0.075 }, + }; + + // Find pricing for model (case insensitive partial match) + const modelKey = Object.keys(pricingMap).find((key) => + model.toLowerCase().includes(key.toLowerCase()) + ); + + if (!modelKey) { + // Default pricing if model not found + return (inputTokens * 0.001 + outputTokens * 0.002) / 1000; + } + + const pricing = pricingMap[modelKey]; + return (inputTokens * pricing.input + outputTokens * pricing.output) / 1000; +} + +/** + * Get file type from extension for metrics + */ +export function getFileTypeFromPath(filePath: string): string { + const ext = path.extname(filePath).toLowerCase(); + return ext.startsWith(".") ? ext.substring(1) : "unknown"; +} diff --git a/src/tools/fetch.ts b/src/tools/fetch.ts index d2a7c897c..f075feca8 100644 --- a/src/tools/fetch.ts +++ b/src/tools/fetch.ts @@ -1,5 +1,5 @@ -import { Tool } from "./types.js"; import TurndownService from "turndown"; +import { Tool } from "./types.js"; const turndownService = new TurndownService({ headingStyle: "atx", @@ -31,7 +31,7 @@ turndownService.addRule("pre", { export const fetchTool: Tool = { name: "fetch", - displayName: "Fetch URL", + displayName: "Fetch", description: "Fetches content from a URL and converts it to markdown format", parameters: { url: { @@ -64,7 +64,8 @@ export const fetchTool: Tool = { signal: controller.signal, headers: { "User-Agent": "Continue-CLI/1.0 (https://continue.dev)", - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + Accept: + "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate", "Cache-Control": "no-cache", @@ -78,7 +79,7 @@ export const fetchTool: Tool = { } const contentType = response.headers.get("content-type") || ""; - + // Handle different content types if (contentType.includes("application/json")) { const json = await response.json(); @@ -96,10 +97,10 @@ export const fetchTool: Tool = { // Process HTML content const html = await response.text(); - + // Convert HTML to markdown const markdown = turndownService.turndown(html); - + // Clean up the markdown const cleanedMarkdown = markdown .replace(/\n\s*\n\s*\n/g, "\n\n") // Remove excessive newlines @@ -108,7 +109,6 @@ export const fetchTool: Tool = { .replace(/\\\]/g, "]"); return `# Content from ${url}\n\n${cleanedMarkdown}`; - } catch (error) { if (error instanceof TypeError && error.message.includes("fetch")) { return `Error: Failed to fetch URL "${url}". Please check the URL and try again.`; @@ -119,4 +119,4 @@ export const fetchTool: Tool = { return `Error: ${error instanceof Error ? error.message : String(error)}`; } }, -}; \ No newline at end of file +}; diff --git a/src/tools/index.ts b/src/tools/index.ts index 37b5bd2a5..00a1a527b 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -1,5 +1,7 @@ import { parseArgs } from "../args.js"; import { MCPService } from "../mcp.js"; +import telemetryService from "../telemetry/telemetryService.js"; +import logger from "../util/logger.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; import { listFilesTool } from "./listFiles.js"; @@ -7,9 +9,7 @@ import { readFileTool } from "./readFile.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; import { type Tool, type ToolParameters } from "./types.js"; -import { viewDiffTool } from "./viewDiff.js"; import { writeFileTool } from "./writeFile.js"; -import logger from "../util/logger.js"; export type { Tool, ToolParameters }; @@ -17,7 +17,6 @@ const ALL_BUILTIN_TOOLS: Tool[] = [ readFileTool, writeFileTool, listFilesTool, - viewDiffTool, searchCodeTool, runTerminalCommandTool, fetchTool, @@ -115,6 +114,8 @@ export async function executeToolCall(toolCall: { name: string; arguments: Record; }): Promise { + const startTime = Date.now(); + const args = parseArgs(); let mcpTools: Tool[] = []; @@ -151,6 +152,13 @@ export async function executeToolCall(toolCall: { const tool = allTools.find((t) => t.name === toolCall.name); if (!tool) { + const duration = Date.now() - startTime; + telemetryService.logToolResult( + toolCall.name, + false, + duration, + `Tool "${toolCall.name}" not found` + ); return `Error: Tool "${toolCall.name}" not found`; } @@ -160,18 +168,52 @@ export async function executeToolCall(toolCall: { (toolCall.arguments[paramName] === undefined || toolCall.arguments[paramName] === null) ) { - return `Error: Required parameter "${paramName}" missing for tool "${toolCall.name}"`; + const duration = Date.now() - startTime; + const error = `Required parameter "${paramName}" missing for tool "${toolCall.name}"`; + telemetryService.logToolResult(toolCall.name, false, duration, error); + return `Error: ${error}`; } } try { - logger.debug('Executing tool', { toolName: toolCall.name, arguments: toolCall.arguments }); + logger.debug("Executing tool", { + toolName: toolCall.name, + arguments: toolCall.arguments, + }); + const result = await tool.run(toolCall.arguments); - logger.debug('Tool execution completed', { toolName: toolCall.name, resultLength: result?.length || 0 }); + const duration = Date.now() - startTime; + + telemetryService.logToolResult( + toolCall.name, + true, + duration, + undefined, // no error + undefined, // no decision + undefined, // no source + JSON.stringify(toolCall.arguments) + ); + + logger.debug("Tool execution completed", { + toolName: toolCall.name, + resultLength: result?.length || 0, + }); + return result; } catch (error) { - return `Error executing tool "${toolCall.name}": ${ - error instanceof Error ? error.message : String(error) - }`; + const duration = Date.now() - startTime; + const errorMessage = error instanceof Error ? error.message : String(error); + + telemetryService.logToolResult( + toolCall.name, + false, + duration, + errorMessage, + undefined, // no decision + undefined, // no source + JSON.stringify(toolCall.arguments) + ); + + return `Error executing tool "${toolCall.name}": ${errorMessage}`; } } diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index b4161c6cc..a98898bf8 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -1,10 +1,15 @@ -import { Tool } from "./types.js"; import { exec } from "child_process"; +import telemetryService from "../telemetry/telemetryService.js"; +import { + isGitCommitCommand, + isPullRequestCommand, +} from "../telemetry/utils.js"; +import { Tool } from "./types.js"; export const runTerminalCommandTool: Tool = { name: "run_terminal_command", - displayName: "Terminal", - description: "Executes a terminal command and returns the output.", + displayName: "Bash", + description: "Executes a terminal command and returns the output", parameters: { command: { type: "string", @@ -16,10 +21,20 @@ export const runTerminalCommandTool: Tool = { run: async ({ command }: { command: string }): Promise => { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { + const exitCode = error?.code || 0; + if (error) { reject(`Error: ${error.message}`); return; } + + // Track specific git operations + if (isGitCommitCommand(command)) { + telemetryService.recordCommitCreated(); + } else if (isPullRequestCommand(command)) { + telemetryService.recordPullRequestCreated(); + } + if (stderr) { resolve(`Stderr: ${stderr}`); return; @@ -28,4 +43,4 @@ export const runTerminalCommandTool: Tool = { }); }); }, -}; \ No newline at end of file +}; diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index f432d5e79..b23387b88 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -1,9 +1,18 @@ +import { createTwoFilesPatch } from "diff"; import * as fs from "fs"; import * as path from "path"; -import { createTwoFilesPatch } from "diff"; +import telemetryService from "../telemetry/telemetryService.js"; +import { + calculateLinesOfCodeDiff, + getLanguageFromFilePath, +} from "../telemetry/utils.js"; import { Tool } from "./types.js"; -function generateDiff(oldContent: string, newContent: string, filePath: string): string { +function generateDiff( + oldContent: string, + newContent: string, + filePath: string +): string { return createTwoFilesPatch( filePath, filePath, @@ -40,23 +49,56 @@ export const writeFileTool: Tool = { } // Read existing file content if it exists - let oldContent = ''; + let oldContent = ""; if (fs.existsSync(args.filepath)) { oldContent = fs.readFileSync(args.filepath, "utf-8"); } // Write new content fs.writeFileSync(args.filepath, args.content, "utf-8"); - - // Generate diff if file existed before + + // Track lines of code changes if file existed before if (oldContent) { + const { added, removed } = calculateLinesOfCodeDiff( + oldContent, + args.content + ); + const language = getLanguageFromFilePath(args.filepath); + + if (added > 0) { + telemetryService.recordLinesOfCodeModified("added", added, language); + } + if (removed > 0) { + telemetryService.recordLinesOfCodeModified( + "removed", + removed, + language + ); + } + const diff = generateDiff(oldContent, args.content, args.filepath); + + // Record file operation + return `Successfully wrote to file: ${args.filepath}\n\nDiff:\n${diff}`; } else { + // New file creation - count all lines as added + const lineCount = args.content.split("\n").length; + const language = getLanguageFromFilePath(args.filepath); + + telemetryService.recordLinesOfCodeModified( + "added", + lineCount, + language + ); + return `Successfully created file: ${args.filepath}`; } } catch (error) { - return `Error writing to file: ${error instanceof Error ? error.message : String(error)}`; + const errorMessage = + error instanceof Error ? error.message : String(error); + + return `Error writing to file: ${errorMessage}`; } }, -}; \ No newline at end of file +}; diff --git a/src/ui/ConfigSelector.tsx b/src/ui/ConfigSelector.tsx index 435f4f638..527ea2ce8 100644 --- a/src/ui/ConfigSelector.tsx +++ b/src/ui/ConfigSelector.tsx @@ -1,7 +1,3 @@ -import { - Configuration, - DefaultApi, -} from "@continuedev/sdk/dist/api/dist/index.js"; import * as fs from "fs"; import { Box, Text, useInput } from "ink"; import * as os from "os"; @@ -12,6 +8,7 @@ import { getOrganizationId, loadAuthConfig, } from "../auth/workos.js"; +import { getApiClient } from "../config.js"; interface ConfigOption { id: string; @@ -56,11 +53,7 @@ const ConfigSelector: React.FC = ({ // Add assistants from current organization if authenticated if (accessToken) { - const apiClient = new DefaultApi( - new Configuration({ - accessToken, - }) - ); + const apiClient = getApiClient(accessToken); try { const assistants = await apiClient.listAssistants({ @@ -69,13 +62,13 @@ const ConfigSelector: React.FC = ({ }); for (const assistant of assistants) { - // Use packageSlug as the slug and create a display name from ownerSlug/packageSlug + // Use full ownerSlug/packageSlug as the slug and create a display name from ownerSlug/packageSlug const displayName = `${assistant.ownerSlug}/${assistant.packageSlug}`; options.push({ id: assistant.packageSlug, name: displayName, type: "assistant", - slug: assistant.packageSlug, + slug: `${assistant.ownerSlug}/${assistant.packageSlug}`, }); } } catch (err) { diff --git a/src/ui/FileSearchUI.tsx b/src/ui/FileSearchUI.tsx index 0be0d8817..4555fca9d 100644 --- a/src/ui/FileSearchUI.tsx +++ b/src/ui/FileSearchUI.tsx @@ -18,25 +18,19 @@ interface FileItem { const fileCache = new Map(); let allFiles: FileItem[] = []; let cacheInitialized = false; +let cacheInitializationPromise: Promise | null = null; -const FileSearchUI: React.FC = ({ - filter, - selectedIndex, - onSelect, - onFilesUpdated, -}) => { - const [files, setFiles] = useState([]); - const [isLoading, setIsLoading] = useState(false); - const initializingRef = useRef(false); - - // Initialize cache once - const initializeCache = async () => { - if (cacheInitialized || initializingRef.current) { - return; - } - - initializingRef.current = true; - +// Initialize cache once +const initializeCache = async (): Promise => { + if (cacheInitialized) { + return; + } + + if (cacheInitializationPromise) { + return cacheInitializationPromise; + } + + cacheInitializationPromise = (async () => { try { // Use a single, more efficient pattern const patterns = [ @@ -127,79 +121,94 @@ const FileSearchUI: React.FC = ({ cacheInitialized = true; } catch (error) { console.error("Error initializing file cache:", error); - } finally { - initializingRef.current = false; } - }; + })(); + + return cacheInitializationPromise; +}; - // Filter files from cache - const filterFiles = (filterText: string): FileItem[] => { - if (!cacheInitialized) { - return []; - } +// Export function to start indexing proactively +export const startFileIndexing = (): Promise => { + return initializeCache(); +}; - if (filterText.length === 0) { - // Show most recently modified files when no filter - return allFiles - .sort((a, b) => { - const aFileName = a.path.split('/').pop() || a.path; - const bFileName = b.path.split('/').pop() || b.path; - return aFileName.localeCompare(bFileName); - }) - .slice(0, 10); - } +// Filter files from cache +const filterFiles = (filterText: string): FileItem[] => { + if (!cacheInitialized) { + return []; + } - const lowerFilter = filterText.toLowerCase(); - - // Check cache first - const cacheKey = lowerFilter; - if (fileCache.has(cacheKey)) { - return fileCache.get(cacheKey)!; - } - - const filteredFiles = allFiles - .filter((file) => { - return ( - file.displayName.toLowerCase().includes(lowerFilter) || - file.path.toLowerCase().includes(lowerFilter) - ); - }) + if (filterText.length === 0) { + // Show most recently modified files when no filter + return allFiles .sort((a, b) => { const aFileName = a.path.split('/').pop() || a.path; const bFileName = b.path.split('/').pop() || b.path; - - // Prioritize exact matches in file name - const aNameMatch = aFileName.toLowerCase().includes(lowerFilter); - const bNameMatch = bFileName.toLowerCase().includes(lowerFilter); - - if (aNameMatch && !bNameMatch) return -1; - if (!aNameMatch && bNameMatch) return 1; - - // Then prioritize files that start with the filter - const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter); - const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter); - - if (aStartsWith && !bStartsWith) return -1; - if (!aStartsWith && bStartsWith) return 1; - - // Finally, sort by file name return aFileName.localeCompare(bFileName); }) .slice(0, 10); + } - // Cache the result - fileCache.set(cacheKey, filteredFiles); - - // Limit cache size - if (fileCache.size > 100) { - const firstKey = fileCache.keys().next().value; - if (firstKey) { - fileCache.delete(firstKey); - } + const lowerFilter = filterText.toLowerCase(); + + // Check cache first + const cacheKey = lowerFilter; + if (fileCache.has(cacheKey)) { + return fileCache.get(cacheKey)!; + } + + const filteredFiles = allFiles + .filter((file) => { + return ( + file.displayName.toLowerCase().includes(lowerFilter) || + file.path.toLowerCase().includes(lowerFilter) + ); + }) + .sort((a, b) => { + const aFileName = a.path.split('/').pop() || a.path; + const bFileName = b.path.split('/').pop() || b.path; + + // Prioritize exact matches in file name + const aNameMatch = aFileName.toLowerCase().includes(lowerFilter); + const bNameMatch = bFileName.toLowerCase().includes(lowerFilter); + + if (aNameMatch && !bNameMatch) return -1; + if (!aNameMatch && bNameMatch) return 1; + + // Then prioritize files that start with the filter + const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter); + const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter); + + if (aStartsWith && !bStartsWith) return -1; + if (!aStartsWith && bStartsWith) return 1; + + // Finally, sort by file name + return aFileName.localeCompare(bFileName); + }) + .slice(0, 10); + + // Cache the result + fileCache.set(cacheKey, filteredFiles); + + // Limit cache size + if (fileCache.size > 100) { + const firstKey = fileCache.keys().next().value; + if (firstKey) { + fileCache.delete(firstKey); } + } - return filteredFiles; - }; + return filteredFiles; +}; + +const FileSearchUI: React.FC = ({ + filter, + selectedIndex, + onSelect, + onFilesUpdated, +}) => { + const [files, setFiles] = useState([]); + const [isLoading, setIsLoading] = useState(false); useEffect(() => { const searchFiles = async () => { diff --git a/src/ui/FreeTrialStatus.tsx b/src/ui/FreeTrialStatus.tsx new file mode 100644 index 000000000..47a7a9c1a --- /dev/null +++ b/src/ui/FreeTrialStatus.tsx @@ -0,0 +1,108 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { + DefaultApiInterface, + GetFreeTrialStatus200Response, +} from "@continuedev/sdk/dist/api/dist/index.js"; +import { Text } from "ink"; +import React, { useEffect, useState } from "react"; + +export function isModelUsingFreeTrial(model: ModelConfig): boolean { + return ( + model.provider === "continue-proxy" && + (model as any).apiKeyLocation.startsWith("free_trial:") + ); +} + +interface FreeTrialStatusProps { + apiClient?: DefaultApiInterface; + onTransitionStateChange?: (isShowingTransition: boolean) => void; + model: ModelConfig; +} + +const FreeTrialStatus: React.FC = ({ + apiClient, + onTransitionStateChange, + model, +}) => { + const [status, setStatus] = useState( + null + ); + const [loading, setLoading] = useState(true); + + const fetchStatus = async () => { + try { + if (!apiClient) { + setStatus(null); + setLoading(false); + return; + } + + const response = await apiClient.getFreeTrialStatus(); + setStatus(response); + setLoading(false); + } catch (error) { + // Silently handle errors - component returns null if no status + setStatus(null); + setLoading(false); + } + }; + + useEffect(() => { + // Initial fetch + fetchStatus(); + + // Don't poll in test environment + if (process.env.NODE_ENV === "test") { + return; + } + + // Poll every 5 seconds + const interval = setInterval(fetchStatus, 5000); + + return () => clearInterval(interval); + }, []); + + // Check if user has maxed out their free trial and notify parent + useEffect(() => { + if (!status || !status.optedInToFreeTrial || loading) { + // No transition needed + if (onTransitionStateChange) { + onTransitionStateChange(false); + } + return; + } + + const chatUsed = status.chatCount ?? 0; + const chatLimit = status.chatLimit; + + // Check if user has maxed out their free trial + const shouldShowTransition = + chatUsed >= chatLimit && isModelUsingFreeTrial(model); + + if (onTransitionStateChange) { + onTransitionStateChange(shouldShowTransition); + } + }, [status, loading, onTransitionStateChange, model]); + + // Don't render anything while loading or if no status + if ( + loading || + !status || + !status.optedInToFreeTrial || + !isModelUsingFreeTrial(model) + ) { + return null; + } + + const chatUsed = status.chatCount ?? 0; + const chatLimit = status.chatLimit; + + // Only show the normal status text - transition UI is handled by parent + return ( + + {chatUsed}/{chatLimit} free trial + + ); +}; + +export default FreeTrialStatus; diff --git a/src/ui/FreeTrialTransitionUI.tsx b/src/ui/FreeTrialTransitionUI.tsx new file mode 100644 index 000000000..1f4584951 --- /dev/null +++ b/src/ui/FreeTrialTransitionUI.tsx @@ -0,0 +1,304 @@ +import * as fs from "fs"; +import { Box, Text, useInput } from "ink"; +import open from "open"; +import * as os from "os"; +import * as path from "path"; +import React, { useState } from "react"; +import * as YAML from "yaml"; +import { env } from "../env.js"; + +const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); + +interface FreeTrialTransitionUIProps { + onComplete: () => void; + onSwitchToLocalConfig?: () => void; + onFullReload?: () => void; +} + +/** + * Creates or updates the local config with Anthropic API key + */ +async function createOrUpdateConfig(apiKey: string): Promise { + const configDir = path.dirname(CONFIG_PATH); + + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true }); + } + + const newModel = { + uses: "anthropic/claude-4-sonnet", + with: { + ANTHROPIC_API_KEY: apiKey, + }, + }; + + if (fs.existsSync(CONFIG_PATH)) { + const existingContent = fs.readFileSync(CONFIG_PATH, "utf8"); + let config; + + try { + config = YAML.parse(existingContent); + + // Make sure models array exists + if (!config.models) { + config.models = []; + } + + // Check if model already exists + const existingModelIndex = config.models.findIndex( + (model: any) => model.uses === "anthropic/claude-4-sonnet" + ); + + if (existingModelIndex >= 0) { + // Update existing model + config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey; + } else { + // Add new model + config.models.push(newModel); + } + } catch (error) { + // If parsing fails, create a new config + config = { + name: "Local Config", + version: "1.0.0", + schema: "v1", + models: [newModel], + }; + } + + // Write back to file + fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); + } else { + // Create new config file + const config = { + name: "Local Config", + version: "1.0.0", + schema: "v1", + models: [newModel], + }; + + fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); + } +} + +const FreeTrialTransitionUI: React.FC = ({ + onComplete, + onSwitchToLocalConfig, + onFullReload, +}) => { + const [currentStep, setCurrentStep] = useState< + "choice" | "enterApiKey" | "processing" | "success" | "error" + >("choice"); + const [selectedOption, setSelectedOption] = useState(1); + const [apiKey, setApiKey] = useState(""); + const [errorMessage, setErrorMessage] = useState(""); + const [successMessage, setSuccessMessage] = useState(""); + const [wasModelsSetup, setWasModelsSetup] = useState(false); + + useInput((input, key) => { + if (currentStep === "choice") { + if (key.upArrow && selectedOption > 1) { + setSelectedOption(selectedOption - 1); + } else if (key.downArrow && selectedOption < 2) { + setSelectedOption(selectedOption + 1); + } else if (input === "1") { + setSelectedOption(1); + } else if (input === "2") { + setSelectedOption(2); + } else if (key.return) { + handleOptionSelect(); + } + } else if (currentStep === "enterApiKey") { + if (key.return) { + if (apiKey && apiKey.startsWith("sk-ant-")) { + handleApiKeySubmit(); + } else { + setErrorMessage( + "Please enter a valid Anthropic API key that starts with 'sk-ant-'" + ); + } + } else if (key.backspace || key.delete) { + setApiKey(apiKey.slice(0, -1)); + setErrorMessage(""); + } else if (input && !key.ctrl && !key.meta) { + setApiKey(apiKey + input); + setErrorMessage(""); + } + } else if (currentStep === "success" || currentStep === "error") { + if (key.return) { + // If user went through models setup, do a full reload to register their purchase + if (wasModelsSetup && onFullReload) { + onFullReload(); + } else { + onComplete(); + } + } + } + }); + + const handleOptionSelect = async () => { + if (selectedOption === 1) { + // Option 1: Open models setup page + setCurrentStep("processing"); + const modelsUrl = new URL("setup-models", env.appUrl).toString(); + setWasModelsSetup(true); // Track that user went through models setup + + try { + await open(modelsUrl); + setSuccessMessage( + `Browser opened to ${modelsUrl}. After setting up your models subscription, press Enter to continue.` + ); + setCurrentStep("success"); + } catch (error) { + setErrorMessage( + `Could not open browser automatically. Please visit: ${modelsUrl}. After setting up your models subscription, press Enter to continue.` + ); + setCurrentStep("error"); + } + } else { + // Option 2: Enter API key + setCurrentStep("enterApiKey"); + setWasModelsSetup(false); // This is not models setup + } + }; + + const handleApiKeySubmit = async () => { + setCurrentStep("processing"); + + try { + await createOrUpdateConfig(apiKey); + setSuccessMessage( + "✓ API key saved successfully! Switching to local configuration..." + ); + setCurrentStep("success"); + + // After a brief delay, switch to local configuration + setTimeout(() => { + if (onSwitchToLocalConfig) { + onSwitchToLocalConfig(); + } else { + onComplete(); + } + }, 1000); + } catch (error) { + setErrorMessage( + `❌ Error saving API key: ${error}. Press Enter to try again.` + ); + setCurrentStep("error"); + } + }; + + if (currentStep === "choice") { + return ( + + + 🚀 Free trial limit reached! + + Choose how you'd like to continue: + + + {selectedOption === 1 ? "▶ " : " "}1. 💳 Sign up for models add-on + (recommended) + + + {selectedOption === 2 ? "▶ " : " "}2. 🔑 Enter your Anthropic API key + + + + Use ↑↓ arrows or 1/2 to select, Enter to confirm + + + ); + } + + if (currentStep === "enterApiKey") { + return ( + + + Enter your Anthropic API key + + + API Key: {"*".repeat(apiKey.length)} + + {errorMessage && {errorMessage}} + + Type your API key and press Enter (must start with 'sk-ant-') + + + ); + } + + if (currentStep === "processing") { + return ( + + + Processing... + + Please wait... + + ); + } + + if (currentStep === "success") { + return ( + + + Success! + + {successMessage} + + + {wasModelsSetup + ? "Press Enter to reload and continue with your new subscription" + : "Press Enter to continue your conversation"} + + + ); + } + + if (currentStep === "error") { + return ( + + + Error + + {errorMessage} + + + {wasModelsSetup + ? "Press Enter to reload and try again" + : "Press Enter to continue"} + + + ); + } + + return null; +}; + +export default FreeTrialTransitionUI; diff --git a/src/ui/LoadingAnimation.tsx b/src/ui/LoadingAnimation.tsx index d955de134..4debfe1a3 100644 --- a/src/ui/LoadingAnimation.tsx +++ b/src/ui/LoadingAnimation.tsx @@ -150,7 +150,7 @@ interface LoadingAnimationProps { const LoadingAnimation: React.FC = ({ visible = true, - color = "blue", + color = "magenta", }) => { const [currentIndex, setCurrentIndex] = useState(0); const animationChars = diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index 089b28987..447a75dee 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -1,72 +1,25 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text } from "ink"; -import React, { useEffect, useState } from "react"; -import { hasMultipleOrganizations } from "../auth/workos.js"; +import React, { useMemo } from "react"; + +import { getAllSlashCommands } from "../commands/commands.js"; interface SlashCommandUIProps { assistant: AssistantConfig; filter: string; selectedIndex: number; - onSelect: (command: string) => void; -} - -interface SlashCommand { - name: string; - description: string; - category: "system" | "assistant"; } const SlashCommandUI: React.FC = ({ assistant, filter, selectedIndex, - onSelect, }) => { - const [hasMultipleOrgs, setHasMultipleOrgs] = useState(false); - - useEffect(() => { - hasMultipleOrganizations().then(setHasMultipleOrgs); - }, []); - - // Get all available slash commands - const getSlashCommands = (): SlashCommand[] => { - const systemCommands: SlashCommand[] = [ - { name: "help", description: "Show help message", category: "system" }, - { name: "clear", description: "Clear the chat history", category: "system" }, - { name: "exit", description: "Exit the chat", category: "system" }, - { - name: "login", - description: "Authenticate with your account", - category: "system", - }, - { - name: "logout", - description: "Sign out of your current session", - category: "system", - }, - { - name: "whoami", - description: "Check who you're currently logged in as", - category: "system", - }, - ...(hasMultipleOrgs ? [{ - name: "org", - description: "Switch organization", - category: "system" as const, - }] : []), - ]; - - const assistantCommands: SlashCommand[] = - assistant.prompts?.map((prompt) => ({ - name: prompt?.name || "", - description: prompt?.description || "", - category: "assistant" as const, - })) || []; - - return [...systemCommands, ...assistantCommands]; - }; - - const allCommands = getSlashCommands(); + // Memoize the slash commands to prevent excessive re-renders + // Only recalculate when assistant.prompts changes + const allCommands = useMemo(() => { + return getAllSlashCommands(assistant); + }, [assistant.prompts]); // Filter commands based on the current filter const filteredCommands = allCommands diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index ea84a3734..82d852a29 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,25 +1,36 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import { Box, Text } from "ink"; -import React, { useState } from "react"; +import * as os from "node:os"; +import * as path from "node:path"; +import React, { useEffect, useState } from "react"; import { loadAuthConfig } from "../auth/workos.js"; import { initialize } from "../config.js"; import { introMessage } from "../intro.js"; import { MCPService } from "../mcp.js"; import ConfigSelector from "./ConfigSelector.js"; +import { startFileIndexing } from "./FileSearchUI.js"; +import FreeTrialStatus from "./FreeTrialStatus.js"; +import FreeTrialTransitionUI from "./FreeTrialTransitionUI.js"; import { useChat } from "./hooks/useChat.js"; import { useConfigSelector } from "./hooks/useConfigSelector.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; import LoadingAnimation from "./LoadingAnimation.js"; import OrganizationSelector from "./OrganizationSelector.js"; +import Timer from "./Timer.js"; +import UpdateNotification from "./UpdateNotification.js"; import UserInput from "./UserInput.js"; +const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); + interface TUIChatProps { config: AssistantUnrolled; - model: string; + model: ModelConfig; llmApi: BaseLlmApi; mcpService: MCPService; + apiClient?: DefaultApiInterface; configPath?: string; initialPrompt?: string; resume?: boolean; @@ -31,6 +42,7 @@ const TUIChat: React.FC = ({ model: initialModel, llmApi: initialLlmApi, mcpService: initialMcpService, + apiClient, configPath, initialPrompt, resume, @@ -49,6 +61,18 @@ const TUIChat: React.FC = ({ } | null>(null); const [loginToken, setLoginToken] = useState(""); + // State for free trial transition + const [isShowingFreeTrialTransition, setIsShowingFreeTrialTransition] = + useState(false); + + // Start file indexing as soon as the component mounts + useEffect(() => { + // Start indexing files in the background immediately + startFileIndexing().catch((error) => { + console.error("Failed to start file indexing:", error); + }); + }, []); + // Custom login prompt handler for TUI const handleLoginPrompt = (promptText: string): Promise => { return new Promise((resolve) => { @@ -65,7 +89,37 @@ const TUIChat: React.FC = ({ } }; - // Reload function for after login + // Full reload function - clears history and reinitializes (for models subscription) + const handleFullReload = async () => { + try { + // Reload auth config and reinitialize + const authConfig = loadAuthConfig(); + const { + config: newAssistant, + llmApi: newLlmApi, + model: newModel, + mcpService: newMcpService, + } = await initialize(authConfig, configPath); + + // Update all the state + setAssistant(newAssistant); + setModel(newModel); + setLlmApi(newLlmApi); + setMcpService(newMcpService); + + // Clear the screen completely + process.stdout.write("\x1b[2J\x1b[H"); + + // Show the new intro message + introMessage(newAssistant, newModel, newMcpService); + } catch (error: any) { + console.error( + `Failed to reload after models subscription: ${error.message}` + ); + } + }; + + // Partial reload function - preserves history (for login or other config changes) const handleReload = async () => { try { // Reload auth config and reinitialize @@ -92,7 +146,56 @@ const TUIChat: React.FC = ({ // Show the new intro message introMessage(newAssistant, newModel, newMcpService); } catch (error: any) { - console.error(`Failed to reload after login: ${error.message}`); + console.error( + `Failed to reload after configuration change: ${error.message}` + ); + } + }; + + // Switch to local config - preserves chat history unlike handleReload + const handleSwitchToLocalConfig = async () => { + try { + // Reload auth config and reinitialize with local config path + const authConfig = loadAuthConfig(); + const { + config: newAssistant, + llmApi: newLlmApi, + model: newModel, + mcpService: newMcpService, + } = await initialize(authConfig, CONFIG_PATH); + + // Update configuration state but preserve chat history + setAssistant(newAssistant); + setModel(newModel); + setLlmApi(newLlmApi); + setMcpService(newMcpService); + + // Add a system message to indicate the configuration switch + setMessages((prev) => [ + ...prev, + { + role: "system", + content: + "✓ Switched to local configuration with your Anthropic API key", + messageType: "system" as const, + }, + ]); + + // Don't clear screen or reset chat history - just continue the conversation! + } catch (error: any) { + console.error( + `Failed to switch to local configuration: ${error.message}` + ); + + // Show error message in chat but don't break the flow + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `❌ Error switching to local configuration: ${error.message}`, + messageType: "system" as const, + }, + ]); } }; @@ -100,6 +203,7 @@ const TUIChat: React.FC = ({ messages, setMessages, isWaitingForResponse, + responseStartTime, inputMode, handleUserMessage, handleInterrupt, @@ -158,6 +262,29 @@ const TUIChat: React.FC = ({ onChatReset: resetChatHistory, }); + // Handle free trial transition completion + const handleFreeTrialTransitionComplete = () => { + setIsShowingFreeTrialTransition(false); + handleReload(); + }; + + const handleFreeTrialSwitchToLocal = () => { + setIsShowingFreeTrialTransition(false); + handleSwitchToLocalConfig(); + }; + + const handleFreeTrialFullReload = () => { + setIsShowingFreeTrialTransition(false); + handleFullReload(); + }; + + // Determine if input should be disabled + const isInputDisabled = + showOrgSelector || + showConfigSelector || + !!loginPrompt || + isShowingFreeTrialTransition; + return ( {/* Chat history - takes up all available space above input */} @@ -168,10 +295,12 @@ const TUIChat: React.FC = ({ {/* Fixed bottom section */} {/* Status */} - {isWaitingForResponse && ( + {isWaitingForResponse && responseStartTime && ( - esc to interrupt + ( + + • esc to interrupt ) )} @@ -216,22 +345,48 @@ const TUIChat: React.FC = ({ /> )} - {/* Input area - always at bottom */} - - - ● Continue CLI + {/* Free trial transition UI - replaces input when active */} + {isShowingFreeTrialTransition && ( + + )} + + {/* Input area - only show when not showing free trial transition */} + {!isShowingFreeTrialTransition && ( + + )} + + {/* Free trial status and Continue CLI info - always show */} + + + + + + + ); }; -export default TUIChat; \ No newline at end of file +export default TUIChat; diff --git a/src/ui/Timer.tsx b/src/ui/Timer.tsx new file mode 100644 index 000000000..32fc2e090 --- /dev/null +++ b/src/ui/Timer.tsx @@ -0,0 +1,25 @@ +import { Text } from "ink"; +import React, { useEffect, useState } from "react"; + +interface TimerProps { + startTime: number; + color?: string; +} + +const Timer: React.FC = ({ startTime, color = "gray" }) => { + const [elapsed, setElapsed] = useState(0); + + useEffect(() => { + const interval = setInterval(() => { + const now = Date.now(); + const elapsedSeconds = Math.floor((now - startTime) / 1000); + setElapsed(elapsedSeconds); + }, 1000); // Update every 1000ms for efficient display + + return () => clearInterval(interval); + }, [startTime]); + + return {elapsed}s; +}; + +export default Timer; \ No newline at end of file diff --git a/src/ui/UpdateNotification.tsx b/src/ui/UpdateNotification.tsx new file mode 100644 index 000000000..5a80b5632 --- /dev/null +++ b/src/ui/UpdateNotification.tsx @@ -0,0 +1,40 @@ +import { Text } from "ink"; +import React, { useEffect, useState } from "react"; +import { compareVersions, getLatestVersion, getVersion } from "../version.js"; + +const UpdateNotification: React.FC = () => { + const [updateAvailable, setUpdateAvailable] = useState(false); + const [latestVersion, setLatestVersion] = useState(""); + const [currentVersion] = useState(getVersion()); + + useEffect(() => { + const checkForUpdate = async () => { + try { + const latest = await getLatestVersion(); + if (latest) { + setLatestVersion(latest); + const comparison = compareVersions(currentVersion, latest); + setUpdateAvailable(comparison === "older"); + } + } catch (error) { + // Silently fail - we don't want to interrupt the user experience + console.debug("Failed to check for updates:", error); + } + }; + + // Check for updates but don't block + checkForUpdate(); + }, [currentVersion]); + + if (!updateAvailable) { + return ● Continue CLI; + } + + return ( + + Update available: v{latestVersion} (npm i -g @continuedev/cli) + + ); +}; + +export default UpdateNotification; diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index ae965edaa..7204ce830 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -91,14 +91,31 @@ const UserInput: React.FC = ({ // Only show slash commands if slash is the very first character if (text.trimStart().startsWith("/")) { const trimmedText = text.trimStart(); - const beforeCursor = trimmedText.slice(0, cursor - (text.length - trimmedText.length)); - + const beforeCursor = trimmedText.slice( + 0, + cursor - (text.length - trimmedText.length) + ); + // Only show if cursor is after the slash and before any whitespace if (beforeCursor.length > 0 && beforeCursor.startsWith("/")) { const afterSlash = beforeCursor.slice(1); - + if (!afterSlash.includes(" ") && !afterSlash.includes("\n")) { - // We're in a slash command context + // We're in a slash command context - check if it's a complete command + const allCommands = getSlashCommands(); + const exactMatch = allCommands.find(cmd => cmd.name === afterSlash); + + // Hide selector if we have an exact match and there's more content after the cursor + if (exactMatch) { + const restOfText = text.slice(cursor); + // If there's a space immediately after cursor, or we're at end of line/text, hide selector + if (restOfText.startsWith(" ") || restOfText === "" || restOfText.startsWith("\n")) { + setShowSlashCommands(false); + return; + } + } + + // Show selector for partial matches setShowSlashCommands(true); setSlashCommandFilter(afterSlash); setSelectedCommandIndex(0); @@ -488,7 +505,6 @@ const UserInput: React.FC = ({ assistant={assistant} filter={slashCommandFilter} selectedIndex={selectedCommandIndex} - onSelect={selectSlashCommand} /> )} @@ -505,4 +521,4 @@ const UserInput: React.FC = ({ ); }; -export default UserInput; +export default UserInput; \ No newline at end of file diff --git a/src/ui/__mocks__/FreeTrialStatus.tsx b/src/ui/__mocks__/FreeTrialStatus.tsx new file mode 100644 index 000000000..1f0ab6c20 --- /dev/null +++ b/src/ui/__mocks__/FreeTrialStatus.tsx @@ -0,0 +1,11 @@ +import React from "react"; + +// Mock FreeTrialStatus component that doesn't create any timers +const FreeTrialStatus: React.FC = () => { + return null; +}; + +export default FreeTrialStatus; +export function isModelUsingFreeTrial(): boolean { + return false; +} \ No newline at end of file diff --git a/src/ui/__tests__/TUIChat.basic.test.tsx b/src/ui/__tests__/TUIChat.basic.test.tsx index 5ebdfcf26..c8c96863a 100644 --- a/src/ui/__tests__/TUIChat.basic.test.tsx +++ b/src/ui/__tests__/TUIChat.basic.test.tsx @@ -44,20 +44,20 @@ describe("TUIChat - Basic UI Tests", () => { }); describe("Loading States", () => { - it("shows loading spinner when loading", async () => { + it("shows UI correctly when loading", async () => { const { lastFrame, stdin } = render(); // Trigger loading by sending a message - stdin.write("trigger loading"); + stdin.write("test message"); stdin.write("\r"); - // Give it a moment to start loading + // Give it a moment to process await new Promise((resolve) => setTimeout(resolve, 50)); const frame = lastFrame(); - // The message was submitted (shows in the UI) - expect(frame).toContain("trigger loading"); - // Note: The actual loading spinner might not be visible in this test environment + // The UI should still be properly rendered + expect(frame).toContain("Ask anything"); + // Note: The actual loading spinner behavior might not be visible in this test environment }); it("hides loading spinner when not loading", () => { @@ -78,13 +78,10 @@ describe("TUIChat - Basic UI Tests", () => { const frame = lastFrame(); - // Should show the submitted message - expect(frame).toContain("test"); - // Should show placeholder message rather than text in input box expect(frame).toContain( "Ask anything, @ for context, / for slash commands" ); }); }); -}); +}); \ No newline at end of file diff --git a/src/ui/__tests__/TUIChat.setup.ts b/src/ui/__tests__/TUIChat.setup.ts index 9a5c3b74e..ffcfb3890 100644 --- a/src/ui/__tests__/TUIChat.setup.ts +++ b/src/ui/__tests__/TUIChat.setup.ts @@ -95,11 +95,35 @@ jest.mock("glob", () => ({ ]), })); +// Mock API Client +export class MockApiClient { + async getFreeTrialStatus() { + return { + optedInToFreeTrial: true, + chatCount: 5, + chatLimit: 100, + }; + } + async listAssistants() { + return []; + } + async getAssistant() { + return { configResult: { config: mockAssistant } }; + } + async listOrganizations() { + return { organizations: [] }; + } + async syncSecrets() { + return []; + } +} + export const createProps = (overrides: any = {}) => ({ config: mockAssistant, model: "test-model", llmApi: new MockLlmApi(), mcpService: new MockMCPService(), + apiClient: new MockApiClient(), configPath: undefined, initialPrompt: undefined, resume: false, @@ -113,4 +137,4 @@ describe("TUIChat setup", () => { expect(createProps).toBeDefined(); expect(mockAssistant).toBeDefined(); }); -}); \ No newline at end of file +}); diff --git a/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/src/ui/__tests__/TUIChat.slashCommands.test.tsx index d01ea6247..f00cb9aa1 100644 --- a/src/ui/__tests__/TUIChat.slashCommands.test.tsx +++ b/src/ui/__tests__/TUIChat.slashCommands.test.tsx @@ -11,7 +11,7 @@ describe("TUIChat - Slash Commands Tests", () => { stdin.write("/log"); // Wait a bit for the UI to update - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => setTimeout(resolve, 100)); const frame = lastFrame(); @@ -38,4 +38,89 @@ describe("TUIChat - Slash Commands Tests", () => { // Should autocomplete to /login (first matching command) expect(frameAfterTab).toContain("/login "); }); + + it("hides slash command selector when complete command is typed", async () => { + const { lastFrame, stdin } = render(); + + // Type /cle to show partial command dropdown + stdin.write("/cle"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const framePartial = lastFrame(); + + // Should show the slash command dropdown for partial match + expect(framePartial).toContain("/clear"); + expect(framePartial).toContain("Clear the chat history"); + + // Type the rest to complete the command /clear + stdin.write("ar"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameComplete = lastFrame(); + + // Should NOT show the slash command dropdown anymore since we have a complete command + expect(frameComplete).not.toContain("Clear the chat history"); + expect(frameComplete).not.toContain( + "Use ↑/↓ to navigate, Enter to select, Tab to complete" + ); + + // But should still show the input with /clear + expect(frameComplete).toContain("/clear"); + }); + + it("shows slash command selector again if typing continues past complete command", async () => { + const { lastFrame, stdin } = render(); + + // Type complete command /clear + stdin.write("/clear"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameComplete = lastFrame(); + + // Should NOT show the dropdown for complete command + expect(frameComplete).not.toContain("Clear the chat history"); + + // Type more characters to make it not match any command + stdin.write("xyz"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameInvalid = lastFrame(); + + // Should show "No matching commands found" since /clearxyz doesn't match anything + expect(frameInvalid).toContain("No matching commands found"); + }); + + it("hides slash command selector when space is typed after complete command", async () => { + const { lastFrame, stdin } = render(); + + // Type complete command /help + stdin.write("/help"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameComplete = lastFrame(); + + // Should NOT show the dropdown for complete command + expect(frameComplete).not.toContain("Show help message"); + + // Type a space after the complete command + stdin.write(" "); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameWithSpace = lastFrame(); + + // Should still NOT show the dropdown after space + expect(frameWithSpace).not.toContain("Show help message"); + expect(frameWithSpace).not.toContain( + "Use ↑/↓ to navigate, Enter to select, Tab to complete" + ); + + // But should show the input with /help + expect(frameWithSpace).toContain("/help "); + }); }); diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 03700dec5..33c4f7822 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { useApp } from "ink"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; @@ -11,6 +11,7 @@ import { streamChatResponse, } from "../../streamChatResponse.js"; import { constructSystemMessage } from "../../systemMessage.js"; +import telemetryService from "../../telemetry/telemetryService.js"; import { getToolDisplayName } from "../../tools.js"; import { formatError } from "../../util/formatError.js"; import logger from "../../util/logger.js"; @@ -19,7 +20,7 @@ import { DisplayMessage } from "../types.js"; interface UseChatProps { assistant: AssistantUnrolled; - model: string; + model: ModelConfig; llmApi: BaseLlmApi; initialPrompt?: string; resume?: boolean; @@ -57,8 +58,19 @@ export function useChat({ if (history.length === 0) { const rulesSystemMessage = ""; - const systemMessage = constructSystemMessage(rulesSystemMessage, additionalRules); - if (systemMessage) { + const systemMessage = constructSystemMessage( + rulesSystemMessage, + additionalRules + ); + if (systemMessage instanceof Promise) { + // Handle the promise case - we'll need to initialize this asynchronously + systemMessage.then((resolvedMessage) => { + if (resolvedMessage) { + history.push({ role: "system", content: resolvedMessage }); + setChatHistory([...history]); + } + }); + } else if (systemMessage) { history.push({ role: "system", content: systemMessage }); } } @@ -83,6 +95,9 @@ export function useChat({ }); const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); + const [responseStartTime, setResponseStartTime] = useState( + null + ); const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = useState(null); @@ -90,6 +105,25 @@ export function useChat({ Array<{ path: string; content: string }> >([]); + useEffect(() => { + // Initialize system message asynchronously + const initializeSystemMessage = async () => { + if (chatHistory.length === 0 || !chatHistory.some(msg => msg.role === "system")) { + const rulesSystemMessage = ""; + const systemMessage = await constructSystemMessage( + rulesSystemMessage, + additionalRules + ); + if (systemMessage) { + const newHistory = [{ role: "system" as const, content: systemMessage }]; + setChatHistory(newHistory); + } + } + }; + + initializeSystemMessage(); + }, []); + useEffect(() => { if (initialPrompt) { handleUserMessage(initialPrompt); @@ -110,7 +144,12 @@ export function useChat({ } // Handle slash commands - const commandResult = await handleSlashCommands(message, assistant, onLoginPrompt, onReload); + const commandResult = await handleSlashCommands( + message, + assistant, + onLoginPrompt, + onReload + ); if (commandResult) { if (commandResult.exit) { exit(); @@ -160,6 +199,12 @@ export function useChat({ } } + // Start active time tracking for telemetry + telemetryService.startActiveTime(); + + // Track user prompt + telemetryService.logUserPrompt(message.length, message); + // Add user message to history and display let messageContent = message; @@ -185,8 +230,12 @@ export function useChat({ const controller = new AbortController(); setAbortController(controller); setIsWaitingForResponse(true); + setResponseStartTime(Date.now()); setInputMode(false); - logger.debug('Starting chat response stream', { messageLength: message.length, historyLength: newHistory.length }); + logger.debug("Starting chat response stream", { + messageLength: message.length, + historyLength: newHistory.length, + }); try { let currentStreamingMessage: DisplayMessage | null = null; @@ -312,12 +361,14 @@ export function useChat({ // Update the chat history with the complete conversation after streaming setChatHistory(finalHistory); - logger.debug('Chat history updated', { finalHistoryLength: finalHistory.length }); - + logger.debug("Chat history updated", { + finalHistoryLength: finalHistory.length, + }); + // Save the updated history to session - logger.debug('Saving session', { historyLength: finalHistory.length }); + logger.debug("Saving session", { historyLength: finalHistory.length }); saveSession(finalHistory); - logger.debug('Session saved'); + logger.debug("Session saved"); } catch (error: any) { const errorMessage = `Error: ${formatError(error)}`; setMessages((prev) => [ @@ -329,8 +380,12 @@ export function useChat({ }, ]); } finally { + // Stop active time tracking + telemetryService.stopActiveTime(); + setAbortController(null); setIsWaitingForResponse(false); + setResponseStartTime(null); setInputMode(true); } }; @@ -353,9 +408,12 @@ export function useChat({ setAttachedFiles((prev) => [...prev, { path: filePath, content }]); }; - const resetChatHistory = () => { + const resetChatHistory = async () => { const rulesSystemMessage = ""; - const systemMessage = constructSystemMessage(rulesSystemMessage, additionalRules); + const systemMessage = await constructSystemMessage( + rulesSystemMessage, + additionalRules + ); const newHistory = systemMessage ? [{ role: "system" as const, content: systemMessage }] : []; @@ -369,6 +427,7 @@ export function useChat({ chatHistory, setChatHistory, isWaitingForResponse, + responseStartTime, inputMode, attachedFiles, handleUserMessage, diff --git a/src/ui/hooks/useConfigSelector.ts b/src/ui/hooks/useConfigSelector.ts index 592928e48..6e54837b8 100644 --- a/src/ui/hooks/useConfigSelector.ts +++ b/src/ui/hooks/useConfigSelector.ts @@ -1,13 +1,13 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { useState } from "react"; import { exec } from "child_process"; +import * as os from "os"; +import * as path from "path"; +import { useState } from "react"; import { loadAuthConfig, updateAssistantSlug } from "../../auth/workos.js"; import { initialize } from "../../config.js"; import { introMessage } from "../../intro.js"; import { MCPService } from "../../mcp.js"; -import * as path from "path"; -import * as os from "os"; interface ConfigOption { id: string; @@ -20,7 +20,7 @@ interface UseConfigSelectorProps { configPath?: string; onAssistantChange: ( assistant: AssistantUnrolled, - model: string, + model: ModelConfig, llmApi: BaseLlmApi, mcpService: MCPService ) => void; @@ -48,7 +48,7 @@ export function useConfigSelector({ if (config.type === "create") { // Open the web browser to create new assistant const url = "https://hub.continue.dev/new?type=assistant"; - + try { let command: string; if (process.platform === "darwin") { @@ -58,13 +58,13 @@ export function useConfigSelector({ } else { command = `xdg-open "${url}"`; } - + exec(command, (error) => { if (error) { console.error("Failed to open browser:", error); } }); - + onMessage({ role: "system", content: `Opening ${url} in your browser to create a new assistant...`, @@ -152,4 +152,4 @@ export function useConfigSelector({ handleConfigCancel, showConfigSelectorUI, }; -} \ No newline at end of file +} diff --git a/src/ui/hooks/useMessageRenderer.tsx b/src/ui/hooks/useMessageRenderer.tsx index 00d3d5623..66e8a06f8 100644 --- a/src/ui/hooks/useMessageRenderer.tsx +++ b/src/ui/hooks/useMessageRenderer.tsx @@ -58,7 +58,7 @@ export function useMessageRenderer() { return ( - ● + ● {isUser ? ( {message.content} diff --git a/src/ui/hooks/useOrganizationSelector.ts b/src/ui/hooks/useOrganizationSelector.ts index 06b50e27c..a767faa1f 100644 --- a/src/ui/hooks/useOrganizationSelector.ts +++ b/src/ui/hooks/useOrganizationSelector.ts @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { useState } from "react"; import { @@ -14,7 +14,7 @@ interface UseOrganizationSelectorProps { configPath?: string; onAssistantChange: ( assistant: AssistantUnrolled, - model: string, + model: ModelConfig, llmApi: BaseLlmApi, mcpService: MCPService ) => void; diff --git a/src/ui/index.ts b/src/ui/index.ts index ea540841f..930a118fe 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -1,5 +1,6 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import { render } from "ink"; import React from "react"; import { introMessage } from "../intro.js"; @@ -11,8 +12,9 @@ export { default as MarkdownRenderer } from "./MarkdownRenderer.js"; export async function startTUIChat( config: AssistantUnrolled, llmApi: BaseLlmApi, - model: string, + model: ModelConfig, mcpService: MCPService, + apiClient?: DefaultApiInterface, initialPrompt?: string, resume?: boolean, configPath?: string, @@ -28,6 +30,7 @@ export async function startTUIChat( model, llmApi, mcpService, + apiClient, configPath, initialPrompt, resume, @@ -42,4 +45,4 @@ export async function startTUIChat( }); return { unmount }; -} \ No newline at end of file +} diff --git a/src/util/consoleOverride.ts b/src/util/consoleOverride.ts new file mode 100644 index 000000000..431d71f14 --- /dev/null +++ b/src/util/consoleOverride.ts @@ -0,0 +1,98 @@ +/** + * Console override utility to prevent unwanted output in headless mode + * This ensures that only intentional stdout output reaches the user + */ + +interface ConsoleBackup { + log: typeof console.log; + info: typeof console.info; + warn: typeof console.warn; + error: typeof console.error; + debug: typeof console.debug; +} + +let originalConsole: ConsoleBackup | null = null; +let isHeadlessMode = false; + +/** + * Override console methods to prevent unwanted output in headless mode + * In headless mode, only console.error and explicitly allowed outputs should reach stdout + */ +export function configureConsoleForHeadless(headless: boolean): void { + isHeadlessMode = headless; + + if (headless && !originalConsole) { + // Backup original console methods + originalConsole = { + log: console.log, + info: console.info, + warn: console.warn, + error: console.error, + debug: console.debug, + }; + + // Override console methods to suppress output in headless mode + console.log = () => {}; // Suppress all console.log + console.info = () => {}; // Suppress all console.info + console.warn = () => {}; // Suppress all console.warn + console.debug = () => {}; // Suppress all console.debug + + // Keep console.error for genuine errors, but send to stderr + console.error = (...args: any[]) => { + originalConsole!.error(...args); + }; + } else if (!headless && originalConsole) { + // Restore original console methods + console.log = originalConsole.log; + console.info = originalConsole.info; + console.warn = originalConsole.warn; + console.error = originalConsole.error; + console.debug = originalConsole.debug; + + originalConsole = null; + } +} + +/** + * Safe stdout output that bypasses console overrides + * Use this for intentional output in headless mode + */ +export function safeStdout(message: string): void { + process.stdout.write(message); +} + +/** + * Safe stderr output that bypasses console overrides + * Use this for error messages that should always be visible + */ +export function safeStderr(message: string): void { + process.stderr.write(message); +} + +/** + * Temporarily restore console for a specific operation + * Useful for debugging or when you need original console behavior + */ +export function withOriginalConsole(fn: () => T): T { + if (!originalConsole || !isHeadlessMode) { + return fn(); + } + + // Temporarily restore + const tempConsole = { ...console }; + Object.assign(console, originalConsole); + + try { + return fn(); + } finally { + // Restore overrides + Object.assign(console, tempConsole); + } +} + +/** + * Check if currently in headless mode + */ +export function isInHeadlessMode(): boolean { + return isHeadlessMode; +} \ No newline at end of file diff --git a/src/version.ts b/src/version.ts index 8d2b4b98b..99001961b 100644 --- a/src/version.ts +++ b/src/version.ts @@ -14,3 +14,46 @@ export function getVersion(): string { return "unknown"; } } + +export async function getLatestVersion(): Promise { + try { + const response = await fetch( + "https://registry.npmjs.org/@continuedev/cli/latest" + ); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + const data = await response.json(); + return data.version; + } catch (error) { + console.warn("Warning: Could not fetch latest version from npm registry"); + return null; + } +} + +export function compareVersions( + current: string, + latest: string +): "newer" | "same" | "older" { + if (current === "unknown" || latest === "unknown") { + return "same"; + } + + // Simple semantic version comparison + const parseVersion = (version: string) => { + const parts = version.replace(/^v/, "").split(".").map(part => parseInt(part, 10)); + return { major: parts[0] || 0, minor: parts[1] || 0, patch: parts[2] || 0 }; + }; + + const currentParts = parseVersion(current); + const latestParts = parseVersion(latest); + + if (currentParts.major > latestParts.major) return "newer"; + if (currentParts.major < latestParts.major) return "older"; + if (currentParts.minor > latestParts.minor) return "newer"; + if (currentParts.minor < latestParts.minor) return "older"; + if (currentParts.patch > latestParts.patch) return "newer"; + if (currentParts.patch < latestParts.patch) return "older"; + + return "same"; +}