luigi12345 commited on
Commit
df82a8c
1 Parent(s): cbcfee2

3d4d430fdc6c4817251cca13ca14d482b4155423564b910e7aa9b75b7cf593cc

Browse files
Files changed (50) hide show
  1. workers1/auto3d/.editorconfig +12 -0
  2. workers1/auto3d/.gitignore +172 -0
  3. workers1/auto3d/.prettierrc +6 -0
  4. workers1/auto3d/CursorLens/.env.example +7 -0
  5. workers1/auto3d/CursorLens/.eslintrc.json +3 -0
  6. workers1/auto3d/CursorLens/.gitignore +39 -0
  7. workers1/auto3d/CursorLens/.prettierrc +3 -0
  8. workers1/auto3d/CursorLens/CONTRIBUTING.md +57 -0
  9. workers1/auto3d/CursorLens/Dockerfile +30 -0
  10. workers1/auto3d/CursorLens/LICENSE +663 -0
  11. workers1/auto3d/CursorLens/README.md +148 -0
  12. workers1/auto3d/CursorLens/components.json +17 -0
  13. workers1/auto3d/CursorLens/docker-compose.yml +41 -0
  14. workers1/auto3d/CursorLens/index.html +52 -0
  15. workers1/auto3d/CursorLens/next.config.js +8 -0
  16. workers1/auto3d/CursorLens/next.config.mjs +4 -0
  17. workers1/auto3d/CursorLens/package.json +74 -0
  18. workers1/auto3d/CursorLens/pnpm-lock.yaml +0 -0
  19. workers1/auto3d/CursorLens/postcss.config.mjs +8 -0
  20. workers1/auto3d/CursorLens/prisma/migrations/20240815195611_init/migration.sql +12 -0
  21. workers1/auto3d/CursorLens/prisma/migrations/20240815203248_add_metadata/migration.sql +2 -0
  22. workers1/auto3d/CursorLens/prisma/migrations/20240815204542_add_config/migration.sql +19 -0
  23. workers1/auto3d/CursorLens/prisma/migrations/20240815210443_add_provider_to_ai_configuration/migration.sql +2 -0
  24. workers1/auto3d/CursorLens/prisma/migrations/20240816193734_add_api_key/migration.sql +2 -0
  25. workers1/auto3d/CursorLens/prisma/migrations/20240816194453_add_configuration_relation/migration.sql +5 -0
  26. workers1/auto3d/CursorLens/prisma/migrations/20240824081904_add_cost_model/migration.sql +32 -0
  27. workers1/auto3d/CursorLens/prisma/migrations/migration_lock.toml +3 -0
  28. workers1/auto3d/CursorLens/prisma/schema.prisma +53 -0
  29. workers1/auto3d/CursorLens/prisma/seed.ts +58 -0
  30. workers1/auto3d/CursorLens/public/ant-cache-create.png +0 -0
  31. workers1/auto3d/CursorLens/public/ant-cache-read.png +0 -0
  32. workers1/auto3d/CursorLens/public/anthropicCashedXConfig.png +0 -0
  33. workers1/auto3d/CursorLens/public/cl-dashboard.png +0 -0
  34. workers1/auto3d/CursorLens/public/cl-settings.png +0 -0
  35. workers1/auto3d/CursorLens/public/cl-stats.jpeg +0 -0
  36. workers1/auto3d/CursorLens/public/cl-stats.png +0 -0
  37. workers1/auto3d/CursorLens/scripts/update-log-costs.ts +72 -0
  38. workers1/auto3d/CursorLens/src/app/[...openai]/route.ts +438 -0
  39. workers1/auto3d/CursorLens/src/app/actions.ts +325 -0
  40. workers1/auto3d/CursorLens/src/app/api/configurations/route.ts +70 -0
  41. workers1/auto3d/CursorLens/src/app/api/logs/[id]/route.ts +36 -0
  42. workers1/auto3d/CursorLens/src/app/api/logs/route.ts +37 -0
  43. workers1/auto3d/CursorLens/src/app/api/stats/route.ts +18 -0
  44. workers1/auto3d/CursorLens/src/app/configurations/page.tsx +392 -0
  45. workers1/auto3d/CursorLens/src/app/favicon.ico +0 -0
  46. workers1/auto3d/CursorLens/src/app/globals.css +75 -0
  47. workers1/auto3d/CursorLens/src/app/layout.tsx +62 -0
  48. workers1/auto3d/CursorLens/src/app/logs/page.tsx +223 -0
  49. workers1/auto3d/CursorLens/src/app/opengraph-image.png +0 -0
  50. workers1/auto3d/CursorLens/src/app/page.tsx +266 -0
workers1/auto3d/.editorconfig ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # http://editorconfig.org
2
+ root = true
3
+
4
+ [*]
5
+ indent_style = tab
6
+ end_of_line = lf
7
+ charset = utf-8
8
+ trim_trailing_whitespace = true
9
+ insert_final_newline = true
10
+
11
+ [*.yml]
12
+ indent_style = space
workers1/auto3d/.gitignore ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+
3
+ logs
4
+ _.log
5
+ npm-debug.log_
6
+ yarn-debug.log*
7
+ yarn-error.log*
8
+ lerna-debug.log*
9
+ .pnpm-debug.log*
10
+
11
+ # Diagnostic reports (https://nodejs.org/api/report.html)
12
+
13
+ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
14
+
15
+ # Runtime data
16
+
17
+ pids
18
+ _.pid
19
+ _.seed
20
+ \*.pid.lock
21
+
22
+ # Directory for instrumented libs generated by jscoverage/JSCover
23
+
24
+ lib-cov
25
+
26
+ # Coverage directory used by tools like istanbul
27
+
28
+ coverage
29
+ \*.lcov
30
+
31
+ # nyc test coverage
32
+
33
+ .nyc_output
34
+
35
+ # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
36
+
37
+ .grunt
38
+
39
+ # Bower dependency directory (https://bower.io/)
40
+
41
+ bower_components
42
+
43
+ # node-waf configuration
44
+
45
+ .lock-wscript
46
+
47
+ # Compiled binary addons (https://nodejs.org/api/addons.html)
48
+
49
+ build/Release
50
+
51
+ # Dependency directories
52
+
53
+ node_modules/
54
+ jspm_packages/
55
+
56
+ # Snowpack dependency directory (https://snowpack.dev/)
57
+
58
+ web_modules/
59
+
60
+ # TypeScript cache
61
+
62
+ \*.tsbuildinfo
63
+
64
+ # Optional npm cache directory
65
+
66
+ .npm
67
+
68
+ # Optional eslint cache
69
+
70
+ .eslintcache
71
+
72
+ # Optional stylelint cache
73
+
74
+ .stylelintcache
75
+
76
+ # Microbundle cache
77
+
78
+ .rpt2_cache/
79
+ .rts2_cache_cjs/
80
+ .rts2_cache_es/
81
+ .rts2_cache_umd/
82
+
83
+ # Optional REPL history
84
+
85
+ .node_repl_history
86
+
87
+ # Output of 'npm pack'
88
+
89
+ \*.tgz
90
+
91
+ # Yarn Integrity file
92
+
93
+ .yarn-integrity
94
+
95
+ # dotenv environment variable files
96
+
97
+ .env
98
+ .env.development.local
99
+ .env.test.local
100
+ .env.production.local
101
+ .env.local
102
+
103
+ # parcel-bundler cache (https://parceljs.org/)
104
+
105
+ .cache
106
+ .parcel-cache
107
+
108
+ # Next.js build output
109
+
110
+ .next
111
+ out
112
+
113
+ # Nuxt.js build / generate output
114
+
115
+ .nuxt
116
+ dist
117
+
118
+ # Gatsby files
119
+
120
+ .cache/
121
+
122
+ # Comment in the public line in if your project uses Gatsby and not Next.js
123
+
124
+ # https://nextjs.org/blog/next-9-1#public-directory-support
125
+
126
+ # public
127
+
128
+ # vuepress build output
129
+
130
+ .vuepress/dist
131
+
132
+ # vuepress v2.x temp and cache directory
133
+
134
+ .temp
135
+ .cache
136
+
137
+ # Docusaurus cache and generated files
138
+
139
+ .docusaurus
140
+
141
+ # Serverless directories
142
+
143
+ .serverless/
144
+
145
+ # FuseBox cache
146
+
147
+ .fusebox/
148
+
149
+ # DynamoDB Local files
150
+
151
+ .dynamodb/
152
+
153
+ # TernJS port file
154
+
155
+ .tern-port
156
+
157
+ # Stores VSCode versions used for testing VSCode extensions
158
+
159
+ .vscode-test
160
+
161
+ # yarn v2
162
+
163
+ .yarn/cache
164
+ .yarn/unplugged
165
+ .yarn/build-state.yml
166
+ .yarn/install-state.gz
167
+ .pnp.\*
168
+
169
+ # wrangler project
170
+
171
+ .dev.vars
172
+ .wrangler/
workers1/auto3d/.prettierrc ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "printWidth": 140,
3
+ "singleQuote": true,
4
+ "semi": true,
5
+ "useTabs": true
6
+ }
workers1/auto3d/CursorLens/.env.example ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ OPENAI_API_KEY=your_openai_api_key_here
2
+ ANTHROPIC_API_KEY=your_anthropic_api_key_here
3
+ COHERE_API_KEY=your_cohere_api_key_here
4
+ MISTRAL_API_KEY=your_mistral_api_key_here
5
+ GROQ_API_KEY=your_groq_api_key_here
6
+
7
+ DATABASE_URL=
workers1/auto3d/CursorLens/.eslintrc.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "extends": "next/core-web-vitals"
3
+ }
workers1/auto3d/CursorLens/.gitignore ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
+
3
+ # dependencies
4
+ /node_modules
5
+ /.pnp
6
+ .pnp.js
7
+ .yarn/install-state.gz
8
+
9
+ # testing
10
+ /coverage
11
+
12
+ # next.js
13
+ /.next/
14
+ /out/
15
+
16
+ # production
17
+ /build
18
+
19
+ # misc
20
+ .DS_Store
21
+ *.pem
22
+
23
+ # debug
24
+ npm-debug.log*
25
+ yarn-debug.log*
26
+ yarn-error.log*
27
+
28
+ # local env files
29
+ .env*.local
30
+
31
+ # vercel
32
+ .vercel
33
+
34
+ # typescript
35
+ *.tsbuildinfo
36
+ next-env.d.ts
37
+
38
+ .env
39
+ certificates
workers1/auto3d/CursorLens/.prettierrc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "plugins": ["prettier-plugin-tailwindcss"]
3
+ }
workers1/auto3d/CursorLens/CONTRIBUTING.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to Cursor Lens
2
+
3
+ We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's:
4
+
5
+ - Reporting a bug
6
+ - Discussing the current state of the code
7
+ - Submitting a fix
8
+ - Proposing new features
9
+ - Becoming a maintainer
10
+
11
+ ## We Develop with Github
12
+
13
+ We use github to host code, to track issues and feature requests, as well as accept pull requests.
14
+
15
+ ## We Use [Github Flow](https://guides.github.com/introduction/flow/index.html), So All Code Changes Happen Through Pull Requests
16
+
17
+ Pull requests are the best way to propose changes to the codebase. We actively welcome your pull requests:
18
+
19
+ 1. Fork the repo and create your branch from `main`.
20
+ 2. If you've added code that should be tested, add tests.
21
+ 3. If you've changed APIs, update the documentation.
22
+ 4. Ensure the test suite passes.
23
+ 5. Make sure your code lints.
24
+ 6. Issue that pull request!
25
+
26
+ ## Any contributions you make will be under the Apache License 2.0
27
+
28
+ In short, when you submit code changes, your submissions are understood to be under the same [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) that covers the project. Feel free to contact the maintainers if that's a concern.
29
+
30
+ ## Report bugs using Github's [issues](https://github.com/HamedMP/CursorLens/issues)
31
+
32
+ We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/HamedMP/CursorLens/issues/new); it's that easy!
33
+
34
+ ## Write bug reports with detail, background, and sample code
35
+
36
+ **Great Bug Reports** tend to have:
37
+
38
+ - A quick summary and/or background
39
+ - Steps to reproduce
40
+ - Be specific!
41
+ - Give sample code if you can.
42
+ - What you expected would happen
43
+ - What actually happens
44
+ - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work)
45
+
46
+ ## Use a Consistent Coding Style
47
+
48
+ - 2 spaces for indentation rather than tabs
49
+ - You can try running `pnpm lint` for style unification
50
+
51
+ ## License
52
+
53
+ By contributing, you agree that your contributions will be licensed under its Apache License 2.0.
54
+
55
+ ## References
56
+
57
+ This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md)
workers1/auto3d/CursorLens/Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:18-alpine
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apk add --no-cache libc6-compat
6
+ RUN apk update
7
+
8
+ # Install pnpm
9
+ RUN npm install -g pnpm
10
+
11
+ # Copy package.json and pnpm-lock.yaml
12
+ COPY package.json pnpm-lock.yaml ./
13
+
14
+ # Install dependencies
15
+ RUN pnpm install
16
+
17
+ # Copy the rest of the application
18
+ COPY . .
19
+
20
+ # Generate Prisma Client
21
+ RUN pnpm prisma generate
22
+
23
+ # Build the application
24
+ RUN pnpm run build
25
+
26
+ # Expose the port the app runs on
27
+ EXPOSE 3000
28
+
29
+ # Start the application
30
+ CMD ["sh", "./start.sh"]
workers1/auto3d/CursorLens/LICENSE ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (C) 2024 Hamed Mohammadpour
2
+
3
+ GNU AFFERO GENERAL PUBLIC LICENSE
4
+ Version 3, 19 November 2007
5
+
6
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
7
+ Everyone is permitted to copy and distribute verbatim copies
8
+ of this license document, but changing it is not allowed.
9
+
10
+ Preamble
11
+
12
+ The GNU Affero General Public License is a free, copyleft license for
13
+ software and other kinds of works, specifically designed to ensure
14
+ cooperation with the community in the case of network server software.
15
+
16
+ The licenses for most software and other practical works are designed
17
+ to take away your freedom to share and change the works. By contrast,
18
+ our General Public Licenses are intended to guarantee your freedom to
19
+ share and change all versions of a program--to make sure it remains free
20
+ software for all its users.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ Developers that use our General Public Licenses protect your rights
30
+ with two steps: (1) assert copyright on the software, and (2) offer
31
+ you this License which gives you legal permission to copy, distribute
32
+ and/or modify the software.
33
+
34
+ A secondary benefit of defending all users' freedom is that
35
+ improvements made in alternate versions of the program, if they
36
+ receive widespread use, become available for other developers to
37
+ incorporate. Many developers of free software are heartened and
38
+ encouraged by the resulting cooperation. However, in the case of
39
+ software used on network servers, this result may fail to come about.
40
+ The GNU General Public License permits making a modified version and
41
+ letting the public access it on a server without ever releasing its
42
+ source code to the public.
43
+
44
+ The GNU Affero General Public License is designed specifically to
45
+ ensure that, in such cases, the modified source code becomes available
46
+ to the community. It requires the operator of a network server to
47
+ provide the source code of the modified version running there to the
48
+ users of that server. Therefore, public use of a modified version, on
49
+ a publicly accessible server, gives the public access to the source
50
+ code of the modified version.
51
+
52
+ An older license, called the Affero General Public License and
53
+ published by Affero, was designed to accomplish similar goals. This is
54
+ a different license, not a version of the Affero GPL, but Affero has
55
+ released a new version of the Affero GPL which permits relicensing under
56
+ this license.
57
+
58
+ The precise terms and conditions for copying, distribution and
59
+ modification follow.
60
+
61
+ TERMS AND CONDITIONS
62
+
63
+ 0. Definitions.
64
+
65
+ "This License" refers to version 3 of the GNU Affero General Public License.
66
+
67
+ "Copyright" also means copyright-like laws that apply to other kinds of
68
+ works, such as semiconductor masks.
69
+
70
+ "The Program" refers to any copyrightable work licensed under this
71
+ License. Each licensee is addressed as "you". "Licensees" and
72
+ "recipients" may be individuals or organizations.
73
+
74
+ To "modify" a work means to copy from or adapt all or part of the work
75
+ in a fashion requiring copyright permission, other than the making of an
76
+ exact copy. The resulting work is called a "modified version" of the
77
+ earlier work or a work "based on" the earlier work.
78
+
79
+ A "covered work" means either the unmodified Program or a work based
80
+ on the Program.
81
+
82
+ To "propagate" a work means to do anything with it that, without
83
+ permission, would make you directly or secondarily liable for
84
+ infringement under applicable copyright law, except executing it on a
85
+ computer or modifying a private copy. Propagation includes copying,
86
+ distribution (with or without modification), making available to the
87
+ public, and in some countries other activities as well.
88
+
89
+ To "convey" a work means any kind of propagation that enables other
90
+ parties to make or receive copies. Mere interaction with a user through
91
+ a computer network, with no transfer of a copy, is not conveying.
92
+
93
+ An interactive user interface displays "Appropriate Legal Notices"
94
+ to the extent that it includes a convenient and prominently visible
95
+ feature that (1) displays an appropriate copyright notice, and (2)
96
+ tells the user that there is no warranty for the work (except to the
97
+ extent that warranties are provided), that licensees may convey the
98
+ work under this License, and how to view a copy of this License. If
99
+ the interface presents a list of user commands or options, such as a
100
+ menu, a prominent item in the list meets this criterion.
101
+
102
+ 1. Source Code.
103
+
104
+ The "source code" for a work means the preferred form of the work
105
+ for making modifications to it. "Object code" means any non-source
106
+ form of a work.
107
+
108
+ A "Standard Interface" means an interface that either is an official
109
+ standard defined by a recognized standards body, or, in the case of
110
+ interfaces specified for a particular programming language, one that
111
+ is widely used among developers working in that language.
112
+
113
+ The "System Libraries" of an executable work include anything, other
114
+ than the work as a whole, that (a) is included in the normal form of
115
+ packaging a Major Component, but which is not part of that Major
116
+ Component, and (b) serves only to enable use of the work with that
117
+ Major Component, or to implement a Standard Interface for which an
118
+ implementation is available to the public in source code form. A
119
+ "Major Component", in this context, means a major essential component
120
+ (kernel, window system, and so on) of the specific operating system
121
+ (if any) on which the executable work runs, or a compiler used to
122
+ produce the work, or an object code interpreter used to run it.
123
+
124
+ The "Corresponding Source" for a work in object code form means all
125
+ the source code needed to generate, install, and (for an executable
126
+ work) run the object code and to modify the work, including scripts to
127
+ control those activities. However, it does not include the work's
128
+ System Libraries, or general-purpose tools or generally available free
129
+ programs which are used unmodified in performing those activities but
130
+ which are not part of the work. For example, Corresponding Source
131
+ includes interface definition files associated with source files for
132
+ the work, and the source code for shared libraries and dynamically
133
+ linked subprograms that the work is specifically designed to require,
134
+ such as by intimate data communication or control flow between those
135
+ subprograms and other parts of the work.
136
+
137
+ The Corresponding Source need not include anything that users
138
+ can regenerate automatically from other parts of the Corresponding
139
+ Source.
140
+
141
+ The Corresponding Source for a work in source code form is that
142
+ same work.
143
+
144
+ 2. Basic Permissions.
145
+
146
+ All rights granted under this License are granted for the term of
147
+ copyright on the Program, and are irrevocable provided the stated
148
+ conditions are met. This License explicitly affirms your unlimited
149
+ permission to run the unmodified Program. The output from running a
150
+ covered work is covered by this License only if the output, given its
151
+ content, constitutes a covered work. This License acknowledges your
152
+ rights of fair use or other equivalent, as provided by copyright law.
153
+
154
+ You may make, run and propagate covered works that you do not
155
+ convey, without conditions so long as your license otherwise remains
156
+ in force. You may convey covered works to others for the sole purpose
157
+ of having them make modifications exclusively for you, or provide you
158
+ with facilities for running those works, provided that you comply with
159
+ the terms of this License in conveying all material for which you do
160
+ not control copyright. Those thus making or running the covered works
161
+ for you must do so exclusively on your behalf, under your direction
162
+ and control, on terms that prohibit them from making any copies of
163
+ your copyrighted material outside their relationship with you.
164
+
165
+ Conveying under any other circumstances is permitted solely under
166
+ the conditions stated below. Sublicensing is not allowed; section 10
167
+ makes it unnecessary.
168
+
169
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
170
+
171
+ No covered work shall be deemed part of an effective technological
172
+ measure under any applicable law fulfilling obligations under article
173
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
174
+ similar laws prohibiting or restricting circumvention of such
175
+ measures.
176
+
177
+ When you convey a covered work, you waive any legal power to forbid
178
+ circumvention of technological measures to the extent such circumvention
179
+ is effected by exercising rights under this License with respect to
180
+ the covered work, and you disclaim any intention to limit operation or
181
+ modification of the work as a means of enforcing, against the work's
182
+ users, your or third parties' legal rights to forbid circumvention of
183
+ technological measures.
184
+
185
+ 4. Conveying Verbatim Copies.
186
+
187
+ You may convey verbatim copies of the Program's source code as you
188
+ receive it, in any medium, provided that you conspicuously and
189
+ appropriately publish on each copy an appropriate copyright notice;
190
+ keep intact all notices stating that this License and any
191
+ non-permissive terms added in accord with section 7 apply to the code;
192
+ keep intact all notices of the absence of any warranty; and give all
193
+ recipients a copy of this License along with the Program.
194
+
195
+ You may charge any price or no price for each copy that you convey,
196
+ and you may offer support or warranty protection for a fee.
197
+
198
+ 5. Conveying Modified Source Versions.
199
+
200
+ You may convey a work based on the Program, or the modifications to
201
+ produce it from the Program, in the form of source code under the
202
+ terms of section 4, provided that you also meet all of these conditions:
203
+
204
+ a) The work must carry prominent notices stating that you modified
205
+ it, and giving a relevant date.
206
+
207
+ b) The work must carry prominent notices stating that it is
208
+ released under this License and any conditions added under section
209
+ 7. This requirement modifies the requirement in section 4 to
210
+ "keep intact all notices".
211
+
212
+ c) You must license the entire work, as a whole, under this
213
+ License to anyone who comes into possession of a copy. This
214
+ License will therefore apply, along with any applicable section 7
215
+ additional terms, to the whole of the work, and all its parts,
216
+ regardless of how they are packaged. This License gives no
217
+ permission to license the work in any other way, but it does not
218
+ invalidate such permission if you have separately received it.
219
+
220
+ d) If the work has interactive user interfaces, each must display
221
+ Appropriate Legal Notices; however, if the Program has interactive
222
+ interfaces that do not display Appropriate Legal Notices, your
223
+ work need not make them do so.
224
+
225
+ A compilation of a covered work with other separate and independent
226
+ works, which are not by their nature extensions of the covered work,
227
+ and which are not combined with it such as to form a larger program,
228
+ in or on a volume of a storage or distribution medium, is called an
229
+ "aggregate" if the compilation and its resulting copyright are not
230
+ used to limit the access or legal rights of the compilation's users
231
+ beyond what the individual works permit. Inclusion of a covered work
232
+ in an aggregate does not cause this License to apply to the other
233
+ parts of the aggregate.
234
+
235
+ 6. Conveying Non-Source Forms.
236
+
237
+ You may convey a covered work in object code form under the terms
238
+ of sections 4 and 5, provided that you also convey the
239
+ machine-readable Corresponding Source under the terms of this License,
240
+ in one of these ways:
241
+
242
+ a) Convey the object code in, or embodied in, a physical product
243
+ (including a physical distribution medium), accompanied by the
244
+ Corresponding Source fixed on a durable physical medium
245
+ customarily used for software interchange.
246
+
247
+ b) Convey the object code in, or embodied in, a physical product
248
+ (including a physical distribution medium), accompanied by a
249
+ written offer, valid for at least three years and valid for as
250
+ long as you offer spare parts or customer support for that product
251
+ model, to give anyone who possesses the object code either (1) a
252
+ copy of the Corresponding Source for all the software in the
253
+ product that is covered by this License, on a durable physical
254
+ medium customarily used for software interchange, for a price no
255
+ more than your reasonable cost of physically performing this
256
+ conveying of source, or (2) access to copy the
257
+ Corresponding Source from a network server at no charge.
258
+
259
+ c) Convey individual copies of the object code with a copy of the
260
+ written offer to provide the Corresponding Source. This
261
+ alternative is allowed only occasionally and noncommercially, and
262
+ only if you received the object code with such an offer, in accord
263
+ with subsection 6b.
264
+
265
+ d) Convey the object code by offering access from a designated
266
+ place (gratis or for a charge), and offer equivalent access to the
267
+ Corresponding Source in the same way through the same place at no
268
+ further charge. You need not require recipients to copy the
269
+ Corresponding Source along with the object code. If the place to
270
+ copy the object code is a network server, the Corresponding Source
271
+ may be on a different server (operated by you or a third party)
272
+ that supports equivalent copying facilities, provided you maintain
273
+ clear directions next to the object code saying where to find the
274
+ Corresponding Source. Regardless of what server hosts the
275
+ Corresponding Source, you remain obligated to ensure that it is
276
+ available for as long as needed to satisfy these requirements.
277
+
278
+ e) Convey the object code using peer-to-peer transmission, provided
279
+ you inform other peers where the object code and Corresponding
280
+ Source of the work are being offered to the general public at no
281
+ charge under subsection 6d.
282
+
283
+ A separable portion of the object code, whose source code is excluded
284
+ from the Corresponding Source as a System Library, need not be
285
+ included in conveying the object code work.
286
+
287
+ A "User Product" is either (1) a "consumer product", which means any
288
+ tangible personal property which is normally used for personal, family,
289
+ or household purposes, or (2) anything designed or sold for incorporation
290
+ into a dwelling. In determining whether a product is a consumer product,
291
+ doubtful cases shall be resolved in favor of coverage. For a particular
292
+ product received by a particular user, "normally used" refers to a
293
+ typical or common use of that class of product, regardless of the status
294
+ of the particular user or of the way in which the particular user
295
+ actually uses, or expects or is expected to use, the product. A product
296
+ is a consumer product regardless of whether the product has substantial
297
+ commercial, industrial or non-consumer uses, unless such uses represent
298
+ the only significant mode of use of the product.
299
+
300
+ "Installation Information" for a User Product means any methods,
301
+ procedures, authorization keys, or other information required to install
302
+ and execute modified versions of a covered work in that User Product from
303
+ a modified version of its Corresponding Source. The information must
304
+ suffice to ensure that the continued functioning of the modified object
305
+ code is in no case prevented or interfered with solely because
306
+ modification has been made.
307
+
308
+ If you convey an object code work under this section in, or with, or
309
+ specifically for use in, a User Product, and the conveying occurs as
310
+ part of a transaction in which the right of possession and use of the
311
+ User Product is transferred to the recipient in perpetuity or for a
312
+ fixed term (regardless of how the transaction is characterized), the
313
+ Corresponding Source conveyed under this section must be accompanied
314
+ by the Installation Information. But this requirement does not apply
315
+ if neither you nor any third party retains the ability to install
316
+ modified object code on the User Product (for example, the work has
317
+ been installed in ROM).
318
+
319
+ The requirement to provide Installation Information does not include a
320
+ requirement to continue to provide support service, warranty, or updates
321
+ for a work that has been modified or installed by the recipient, or for
322
+ the User Product in which it has been modified or installed. Access to a
323
+ network may be denied when the modification itself materially and
324
+ adversely affects the operation of the network or violates the rules and
325
+ protocols for communication across the network.
326
+
327
+ Corresponding Source conveyed, and Installation Information provided,
328
+ in accord with this section must be in a format that is publicly
329
+ documented (and with an implementation available to the public in
330
+ source code form), and must require no special password or key for
331
+ unpacking, reading or copying.
332
+
333
+ 7. Additional Terms.
334
+
335
+ "Additional permissions" are terms that supplement the terms of this
336
+ License by making exceptions from one or more of its conditions.
337
+ Additional permissions that are applicable to the entire Program shall
338
+ be treated as though they were included in this License, to the extent
339
+ that they are valid under applicable law. If additional permissions
340
+ apply only to part of the Program, that part may be used separately
341
+ under those permissions, but the entire Program remains governed by
342
+ this License without regard to the additional permissions.
343
+
344
+ When you convey a copy of a covered work, you may at your option
345
+ remove any additional permissions from that copy, or from any part of
346
+ it. (Additional permissions may be written to require their own
347
+ removal in certain cases when you modify the work.) You may place
348
+ additional permissions on material, added by you to a covered work,
349
+ for which you have or can give appropriate copyright permission.
350
+
351
+ Notwithstanding any other provision of this License, for material you
352
+ add to a covered work, you may (if authorized by the copyright holders of
353
+ that material) supplement the terms of this License with terms:
354
+
355
+ a) Disclaiming warranty or limiting liability differently from the
356
+ terms of sections 15 and 16 of this License; or
357
+
358
+ b) Requiring preservation of specified reasonable legal notices or
359
+ author attributions in that material or in the Appropriate Legal
360
+ Notices displayed by works containing it; or
361
+
362
+ c) Prohibiting misrepresentation of the origin of that material, or
363
+ requiring that modified versions of such material be marked in
364
+ reasonable ways as different from the original version; or
365
+
366
+ d) Limiting the use for publicity purposes of names of licensors or
367
+ authors of the material; or
368
+
369
+ e) Declining to grant rights under trademark law for use of some
370
+ trade names, trademarks, or service marks; or
371
+
372
+ f) Requiring indemnification of licensors and authors of that
373
+ material by anyone who conveys the material (or modified versions of
374
+ it) with contractual assumptions of liability to the recipient, for
375
+ any liability that these contractual assumptions directly impose on
376
+ those licensors and authors.
377
+
378
+ All other non-permissive additional terms are considered "further
379
+ restrictions" within the meaning of section 10. If the Program as you
380
+ received it, or any part of it, contains a notice stating that it is
381
+ governed by this License along with a term that is a further
382
+ restriction, you may remove that term. If a license document contains
383
+ a further restriction but permits relicensing or conveying under this
384
+ License, you may add to a covered work material governed by the terms
385
+ of that license document, provided that the further restriction does
386
+ not survive such relicensing or conveying.
387
+
388
+ If you add terms to a covered work in accord with this section, you
389
+ must place, in the relevant source files, a statement of the
390
+ additional terms that apply to those files, or a notice indicating
391
+ where to find the applicable terms.
392
+
393
+ Additional terms, permissive or non-permissive, may be stated in the
394
+ form of a separately written license, or stated as exceptions;
395
+ the above requirements apply either way.
396
+
397
+ 8. Termination.
398
+
399
+ You may not propagate or modify a covered work except as expressly
400
+ provided under this License. Any attempt otherwise to propagate or
401
+ modify it is void, and will automatically terminate your rights under
402
+ this License (including any patent licenses granted under the third
403
+ paragraph of section 11).
404
+
405
+ However, if you cease all violation of this License, then your
406
+ license from a particular copyright holder is reinstated (a)
407
+ provisionally, unless and until the copyright holder explicitly and
408
+ finally terminates your license, and (b) permanently, if the copyright
409
+ holder fails to notify you of the violation by some reasonable means
410
+ prior to 60 days after the cessation.
411
+
412
+ Moreover, your license from a particular copyright holder is
413
+ reinstated permanently if the copyright holder notifies you of the
414
+ violation by some reasonable means, this is the first time you have
415
+ received notice of violation of this License (for any work) from that
416
+ copyright holder, and you cure the violation prior to 30 days after
417
+ your receipt of the notice.
418
+
419
+ Termination of your rights under this section does not terminate the
420
+ licenses of parties who have received copies or rights from you under
421
+ this License. If your rights have been terminated and not permanently
422
+ reinstated, you do not qualify to receive new licenses for the same
423
+ material under section 10.
424
+
425
+ 9. Acceptance Not Required for Having Copies.
426
+
427
+ You are not required to accept this License in order to receive or
428
+ run a copy of the Program. Ancillary propagation of a covered work
429
+ occurring solely as a consequence of using peer-to-peer transmission
430
+ to receive a copy likewise does not require acceptance. However,
431
+ nothing other than this License grants you permission to propagate or
432
+ modify any covered work. These actions infringe copyright if you do
433
+ not accept this License. Therefore, by modifying or propagating a
434
+ covered work, you indicate your acceptance of this License to do so.
435
+
436
+ 10. Automatic Licensing of Downstream Recipients.
437
+
438
+ Each time you convey a covered work, the recipient automatically
439
+ receives a license from the original licensors, to run, modify and
440
+ propagate that work, subject to this License. You are not responsible
441
+ for enforcing compliance by third parties with this License.
442
+
443
+ An "entity transaction" is a transaction transferring control of an
444
+ organization, or substantially all assets of one, or subdividing an
445
+ organization, or merging organizations. If propagation of a covered
446
+ work results from an entity transaction, each party to that
447
+ transaction who receives a copy of the work also receives whatever
448
+ licenses to the work the party's predecessor in interest had or could
449
+ give under the previous paragraph, plus a right to possession of the
450
+ Corresponding Source of the work from the predecessor in interest, if
451
+ the predecessor has it or can get it with reasonable efforts.
452
+
453
+ You may not impose any further restrictions on the exercise of the
454
+ rights granted or affirmed under this License. For example, you may
455
+ not impose a license fee, royalty, or other charge for exercise of
456
+ rights granted under this License, and you may not initiate litigation
457
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
458
+ any patent claim is infringed by making, using, selling, offering for
459
+ sale, or importing the Program or any portion of it.
460
+
461
+ 11. Patents.
462
+
463
+ A "contributor" is a copyright holder who authorizes use under this
464
+ License of the Program or a work on which the Program is based. The
465
+ work thus licensed is called the contributor's "contributor version".
466
+
467
+ A contributor's "essential patent claims" are all patent claims
468
+ owned or controlled by the contributor, whether already acquired or
469
+ hereafter acquired, that would be infringed by some manner, permitted
470
+ by this License, of making, using, or selling its contributor version,
471
+ but do not include claims that would be infringed only as a
472
+ consequence of further modification of the contributor version. For
473
+ purposes of this definition, "control" includes the right to grant
474
+ patent sublicenses in a manner consistent with the requirements of
475
+ this License.
476
+
477
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
478
+ patent license under the contributor's essential patent claims, to
479
+ make, use, sell, offer for sale, import and otherwise run, modify and
480
+ propagate the contents of its contributor version.
481
+
482
+ In the following three paragraphs, a "patent license" is any express
483
+ agreement or commitment, however denominated, not to enforce a patent
484
+ (such as an express permission to practice a patent or covenant not to
485
+ sue for patent infringement). To "grant" such a patent license to a
486
+ party means to make such an agreement or commitment not to enforce a
487
+ patent against the party.
488
+
489
+ If you convey a covered work, knowingly relying on a patent license,
490
+ and the Corresponding Source of the work is not available for anyone
491
+ to copy, free of charge and under the terms of this License, through a
492
+ publicly available network server or other readily accessible means,
493
+ then you must either (1) cause the Corresponding Source to be so
494
+ available, or (2) arrange to deprive yourself of the benefit of the
495
+ patent license for this particular work, or (3) arrange, in a manner
496
+ consistent with the requirements of this License, to extend the patent
497
+ license to downstream recipients. "Knowingly relying" means you have
498
+ actual knowledge that, but for the patent license, your conveying the
499
+ covered work in a country, or your recipient's use of the covered work
500
+ in a country, would infringe one or more identifiable patents in that
501
+ country that you have reason to believe are valid.
502
+
503
+ If, pursuant to or in connection with a single transaction or
504
+ arrangement, you convey, or propagate by procuring conveyance of, a
505
+ covered work, and grant a patent license to some of the parties
506
+ receiving the covered work authorizing them to use, propagate, modify
507
+ or convey a specific copy of the covered work, then the patent license
508
+ you grant is automatically extended to all recipients of the covered
509
+ work and works based on it.
510
+
511
+ A patent license is "discriminatory" if it does not include within
512
+ the scope of its coverage, prohibits the exercise of, or is
513
+ conditioned on the non-exercise of one or more of the rights that are
514
+ specifically granted under this License. You may not convey a covered
515
+ work if you are a party to an arrangement with a third party that is
516
+ in the business of distributing software, under which you make payment
517
+ to the third party based on the extent of your activity of conveying
518
+ the work, and under which the third party grants, to any of the
519
+ parties who would receive the covered work from you, a discriminatory
520
+ patent license (a) in connection with copies of the covered work
521
+ conveyed by you (or copies made from those copies), or (b) primarily
522
+ for and in connection with specific products or compilations that
523
+ contain the covered work, unless you entered into that arrangement,
524
+ or that patent license was granted, prior to 28 March 2007.
525
+
526
+ Nothing in this License shall be construed as excluding or limiting
527
+ any implied license or other defenses to infringement that may
528
+ otherwise be available to you under applicable patent law.
529
+
530
+ 12. No Surrender of Others' Freedom.
531
+
532
+ If conditions are imposed on you (whether by court order, agreement or
533
+ otherwise) that contradict the conditions of this License, they do not
534
+ excuse you from the conditions of this License. If you cannot convey a
535
+ covered work so as to satisfy simultaneously your obligations under this
536
+ License and any other pertinent obligations, then as a consequence you may
537
+ not convey it at all. For example, if you agree to terms that obligate you
538
+ to collect a royalty for further conveying from those to whom you convey
539
+ the Program, the only way you could satisfy both those terms and this
540
+ License would be to refrain entirely from conveying the Program.
541
+
542
+ 13. Remote Network Interaction; Use with the GNU General Public License.
543
+
544
+ Notwithstanding any other provision of this License, if you modify the
545
+ Program, your modified version must prominently offer all users
546
+ interacting with it remotely through a computer network (if your version
547
+ supports such interaction) an opportunity to receive the Corresponding
548
+ Source of your version by providing access to the Corresponding Source
549
+ from a network server at no charge, through some standard or customary
550
+ means of facilitating copying of software. This Corresponding Source
551
+ shall include the Corresponding Source for any work covered by version 3
552
+ of the GNU General Public License that is incorporated pursuant to the
553
+ following paragraph.
554
+
555
+ Notwithstanding any other provision of this License, you have
556
+ permission to link or combine any covered work with a work licensed
557
+ under version 3 of the GNU General Public License into a single
558
+ combined work, and to convey the resulting work. The terms of this
559
+ License will continue to apply to the part which is the covered work,
560
+ but the work with which it is combined will remain governed by version
561
+ 3 of the GNU General Public License.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU Affero General Public License from time to time. Such new versions
567
+ will be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU Affero General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU Affero General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU Affero General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU Affero General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU Affero General Public License for more details.
646
+
647
+ You should have received a copy of the GNU Affero General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If your software can interact with users remotely through a computer
653
+ network, you should also make sure that it provides a way for users to
654
+ get its source. For example, if your program is a web application, its
655
+ interface could display a "Source" link that leads users to an archive
656
+ of the code. There are many ways you could offer source, and different
657
+ solutions will be better for different programs; see section 13 for the
658
+ specific requirements.
659
+
660
+ You should also get your employer (if you work as a programmer) or school,
661
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
662
+ For more information on this, and how to apply and follow the GNU AGPL, see
663
+ <https://www.gnu.org/licenses/>.
workers1/auto3d/CursorLens/README.md ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cursor Lens ✨
2
+
3
+ Cursor Lens is an open-source tool designed to provide insights into AI-assisted coding sessions using Cursor AI. It acts as a proxy between Cursor and various AI providers, logging interactions and providing detailed analytics to help developers optimize their use of AI in their coding workflow.
4
+
5
+ We are live on ProductHunt today, please upvote us if you find this useful! 🙏
6
+
7
+ <a href="https://www.producthunt.com/posts/cursor-lens?embed=true&utm_source=badge-featured&utm_medium=badge&utm_souce=badge-cursor&#0045;lens" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=480850&theme=neutral" alt="Cursor&#0032;Lens - Open&#0032;Source&#0032;Dashboard&#0032;and&#0032;Analytics&#0032;for&#0032;Cursor&#0032;IDE | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
8
+
9
+ ![Cursor Lens Dashboard](public/cl-dashboard.png)
10
+
11
+ ## Features
12
+
13
+ - **AI Provider Integration**: Supports multiple AI providers including OpenAI, Anthropic, and more.
14
+ - **Request Logging**: Captures and logs all requests between Cursor and AI providers.
15
+ - **Analytics Dashboard**: Provides visual analytics on AI usage, including token consumption and request patterns.
16
+ - **Configurable AI Models**: Allows users to set up and switch between different AI configurations.
17
+ - **Real-time Monitoring**: Offers a live view of ongoing AI interactions.
18
+ - **Token Usage Tracking**: Monitors and reports on token usage across different models.
19
+ - **Cost Estimation**: Provides estimated costs based on token usage and model pricing.
20
+
21
+ ## Technology Stack
22
+
23
+ - **Frontend/Backend**: Next.js with React
24
+ - **Database**: PostgreSQL with Prisma ORM
25
+ - **AI Library**: Vercel AI SDK
26
+ - **Styling**: Tailwind CSS with shadcn/ui components
27
+
28
+ ## Getting Started
29
+
30
+ For detailed installation instructions, please refer to our [Installation Guide](https://www.cursorlens.com/docs/getting-started/installation).
31
+
32
+ ### Prerequisites
33
+
34
+ - Node.js (v14 or later)
35
+ - pnpm
36
+ - PostgreSQL
37
+ - ngrok
38
+
39
+ ### Quick Installation Steps
40
+
41
+ 1. Clone the repository
42
+ 2. Install dependencies with `pnpm install`
43
+ 3. Set up environment variables
44
+ 4. Set up the database with `pnpm prisma migrate dev`
45
+ 5. Build the project with `pnpm build`
46
+ 6. Set up ngrok
47
+ 7. Configure Cursor to use your ngrok URL as the API endpoint
48
+
49
+ For full details on each step, please see the [Installation Guide](https://www.cursorlens.com/docs/getting-started/installation).
50
+
51
+ ## Usage
52
+
53
+ 1. Configure Cursor to use Cursor Lens as its API endpoint by overriding `OpenAI Base URL`.
54
+ 2. Choose a `gpt-` model. Use Cursor as normal for AI-assisted coding.
55
+ 3. Visit the Cursor Lens dashboard to view logs, statistics, and insights.
56
+
57
+ ![Cursor settings](public/cl-settings.png)
58
+
59
+ ## Stats page
60
+
61
+ ![Cursor Lens Stats](public/cl-stats.jpeg)
62
+
63
+ ## Prompt caching with Anthropic (v0.1.2):
64
+
65
+ 1. Create a new config on `/configuration` page, choose `antropicCached` with Sonnet 3.5. Name it as you like.
66
+ 2. Mark it as default.
67
+ 3. Use Cursor with CursorLens as normal. The system and context messages in `CMD+L` and `CMD+i` chats will be cached from now on.
68
+
69
+ > Note that TTL for the cache is 5 minutes.
70
+
71
+ ![Add a new config with Antropic Cached](public/anthropicCashedXConfig.png)
72
+ ![Example Cache creation response](public/ant-cache-create.png)
73
+ ![Example Cache read response](public/ant-cache-read.png)
74
+
75
+ # Releases
76
+
77
+ ## Nightly - 2024-08-24
78
+
79
+ - Add new cost calculation
80
+
81
+ To run it, make sure to run:
82
+
83
+ - `npx prisma seed db` and then
84
+ - `pnpm run update-log-costs` to add cost info in metadata for all previous logs
85
+
86
+ ## [0.1.2-alpha] - 2024-08-22
87
+
88
+ ### ⚠️ ALPHA RELEASE
89
+
90
+ ### Added
91
+
92
+ - Add Anthropic Cache support for context messages
93
+ - Increase Token limit for Anthropic to 8192 tokens
94
+ - Improved statistics page: Now you can select the data points you want to see
95
+
96
+ ### Improved and fixed
97
+
98
+ - Log details are now collapsible
99
+ - Full response is captured in the logs
100
+
101
+ ## [0.1.1-alpha] - 2024-08-18
102
+
103
+ ### ⚠️ ALPHA RELEASE
104
+
105
+ ### Added
106
+
107
+ - Added support for Mistral AI, Cohere, Groq, and Ollama
108
+
109
+ ## [0.1.0-alpha] - 2024-08-17
110
+
111
+ This is the initial alpha release of CursorLens. As an alpha version, it may contain bugs and is not yet feature-complete. Use with caution in non-production environments.
112
+
113
+ ### Added
114
+
115
+ - Initial project setup with Next.js
116
+ - Basic proxy functionality between Cursor and AI providers (OpenAI, Anthropic)
117
+ - Simple dashboard for viewing AI interaction logs
118
+ - Token usage tracking for OpenAI and Anthropic models
119
+ - Basic cost estimation based on token usage
120
+ - Support for PostgreSQL database with Prisma ORM
121
+ - Environment variable configuration for API keys and database connection
122
+ - Basic error handling and logging
123
+
124
+ ### Known Issues
125
+
126
+ - Limited error handling for edge cases
127
+ - Incomplete test coverage
128
+ - Basic UI with limited customization options
129
+ - Potential performance issues with large volumes of requests
130
+ - Cost calculation for cached messages in Anthropic are not correct
131
+
132
+ ## Contributing
133
+
134
+ We welcome contributions to Cursor Lens! Please see our [Contributing Guide](CONTRIBUTING.md) for more details on how to get started.
135
+
136
+ ## License
137
+
138
+ Cursor Lens is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). See the [LICENSE](LICENSE) file for details.
139
+
140
+ ## Support
141
+
142
+ If you encounter any issues or have questions, please file an issue on the GitHub repository or contact the maintainers directly.
143
+
144
+ For more detailed information, please visit our [documentation](https://www.cursorlens.com/docs/project/introduction).
145
+
146
+ ---
147
+
148
+ Happy coding with Cursor Lens!
workers1/auto3d/CursorLens/components.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema.json",
3
+ "style": "new-york",
4
+ "rsc": true,
5
+ "tsx": true,
6
+ "tailwind": {
7
+ "config": "tailwind.config.ts",
8
+ "css": "src/app/globals.css",
9
+ "baseColor": "stone",
10
+ "cssVariables": true,
11
+ "prefix": ""
12
+ },
13
+ "aliases": {
14
+ "components": "@/components",
15
+ "utils": "@/lib/utils"
16
+ }
17
+ }
workers1/auto3d/CursorLens/docker-compose.yml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ db:
3
+ image: postgres:14
4
+ environment:
5
+ - POSTGRES_USER=postgres
6
+ - POSTGRES_PASSWORD=postgres
7
+ - POSTGRES_DB=postgres
8
+ volumes:
9
+ - postgres_data:/var/lib/postgresql/data
10
+ healthcheck:
11
+ test: ["CMD-SHELL", "pg_isready -U postgres"]
12
+ interval: 5s
13
+ timeout: 5s
14
+ retries: 5
15
+ ports:
16
+ - "5432:5432"
17
+
18
+ app:
19
+ build:
20
+ context: .
21
+ dockerfile: Dockerfile
22
+ ports:
23
+ - "3000:3000"
24
+ environment:
25
+ - DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres
26
+ depends_on:
27
+ db:
28
+ condition: service_healthy
29
+
30
+ ngrok:
31
+ image: ngrok/ngrok:latest
32
+ environment:
33
+ NGROK_AUTHTOKEN: ${NGROK_AUTHTOKEN}
34
+ command: http app:3000
35
+ ports:
36
+ - "4040:4040"
37
+ depends_on:
38
+ - app
39
+
40
+ volumes:
41
+ postgres_data:
workers1/auto3d/CursorLens/index.html ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Cursor Dashboard</title>
7
+ <style>
8
+ body {
9
+ font-family: Arial, sans-serif;
10
+ line-height: 1.6;
11
+ color: #333;
12
+ max-width: 800px;
13
+ margin: 0 auto;
14
+ padding: 20px;
15
+ }
16
+ h1 {
17
+ color: #2c3e50;
18
+ }
19
+ .cta-button {
20
+ display: inline-block;
21
+ background-color: #3498db;
22
+ color: white;
23
+ padding: 10px 20px;
24
+ text-decoration: none;
25
+ border-radius: 5px;
26
+ margin-top: 20px;
27
+ }
28
+ </style>
29
+ </head>
30
+ <body>
31
+ <h1>Cursor Dashboard</h1>
32
+ <p>
33
+ Cursor Dashboard is a powerful Next.js application for managing and
34
+ analyzing AI configurations and logs.
35
+ </p>
36
+ <h2>Features:</h2>
37
+ <ul>
38
+ <li>View total logs and tokens used</li>
39
+ <li>Manage AI configurations</li>
40
+ <li>Browse recent logs</li>
41
+ </ul>
42
+ <h2>Getting Started:</h2>
43
+ <ol>
44
+ <li>Clone the repository</li>
45
+ <li>Install dependencies with <code>npm install</code></li>
46
+ <li>Run the development server with <code>npm run dev</code></li>
47
+ </ol>
48
+ <a href="https://github.com/yourusername/your-repo-name" class="cta-button"
49
+ >View on GitHub</a
50
+ >
51
+ </body>
52
+ </html>
workers1/auto3d/CursorLens/next.config.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ /** @type {import('next').NextConfig} */
2
+ const nextConfig = {
3
+ typescript: {
4
+ ignoreBuildErrors: true,
5
+ },
6
+ };
7
+
8
+ module.exports = nextConfig;
workers1/auto3d/CursorLens/next.config.mjs ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ /** @type {import('next').NextConfig} */
2
+ const nextConfig = {};
3
+
4
+ export default nextConfig;
workers1/auto3d/CursorLens/package.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "cursor-analytics",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "scripts": {
6
+ "dev": "next dev",
7
+ "build": "next build",
8
+ "start": "next start",
9
+ "lint": "next lint",
10
+ "seed": "tsx prisma/seed.ts",
11
+ "update-log-costs": "tsx scripts/update-log-costs.ts"
12
+ },
13
+ "prisma": {
14
+ "seed": "tsx prisma/seed.ts"
15
+ },
16
+ "dependencies": {
17
+ "@ai-sdk/amazon-bedrock": "^0.0.17",
18
+ "@ai-sdk/anthropic": "^0.0.46",
19
+ "@ai-sdk/cohere": "^0.0.17",
20
+ "@ai-sdk/google-vertex": "^0.0.28",
21
+ "@ai-sdk/mistral": "^0.0.34",
22
+ "@ai-sdk/openai": "^0.0.46",
23
+ "@prisma/client": "^5.18.0",
24
+ "@radix-ui/react-checkbox": "^1.1.1",
25
+ "@radix-ui/react-dialog": "^1.1.1",
26
+ "@radix-ui/react-icons": "^1.3.0",
27
+ "@radix-ui/react-label": "^2.1.0",
28
+ "@radix-ui/react-popover": "^1.1.1",
29
+ "@radix-ui/react-progress": "^1.1.0",
30
+ "@radix-ui/react-scroll-area": "^1.1.0",
31
+ "@radix-ui/react-select": "^2.1.1",
32
+ "@radix-ui/react-slot": "^1.1.0",
33
+ "@radix-ui/react-switch": "^1.1.0",
34
+ "@t3-oss/env-nextjs": "^0.11.0",
35
+ "@types/react-syntax-highlighter": "^15.5.13",
36
+ "ai": "^3.3.14",
37
+ "class-variance-authority": "^0.7.0",
38
+ "clsx": "^2.1.1",
39
+ "date-fns": "^3.6.0",
40
+ "lodash": "^4.17.21",
41
+ "lucide-react": "^0.427.0",
42
+ "next": "14.2.5",
43
+ "next-themes": "^0.3.0",
44
+ "ollama-ai-provider": "^0.12.0",
45
+ "openai": "^4.55.7",
46
+ "react": "^18",
47
+ "react-day-picker": "8.10.1",
48
+ "react-dom": "^18",
49
+ "react-markdown": "^9.0.1",
50
+ "react-syntax-highlighter": "^15.5.0",
51
+ "recharts": "^2.12.7",
52
+ "sonner": "^1.5.0",
53
+ "sqlite": "^5.1.1",
54
+ "sqlite3": "^5.1.7",
55
+ "tailwind-merge": "^2.5.2",
56
+ "tailwindcss-animate": "^1.0.7",
57
+ "zod": "^3.23.8"
58
+ },
59
+ "devDependencies": {
60
+ "@types/lodash": "^4.17.7",
61
+ "@types/node": "^20",
62
+ "@types/react": "^18",
63
+ "@types/react-dom": "^18",
64
+ "eslint": "^8",
65
+ "eslint-config-next": "14.2.5",
66
+ "postcss": "^8",
67
+ "prettier": "^3.3.3",
68
+ "prettier-plugin-tailwindcss": "^0.6.6",
69
+ "prisma": "^5.18.0",
70
+ "tailwindcss": "^3.4.1",
71
+ "tsx": "^4.7.1",
72
+ "typescript": "^5"
73
+ }
74
+ }
workers1/auto3d/CursorLens/pnpm-lock.yaml ADDED
The diff for this file is too large to render. See raw diff
 
workers1/auto3d/CursorLens/postcss.config.mjs ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ /** @type {import('postcss-load-config').Config} */
2
+ const config = {
3
+ plugins: {
4
+ tailwindcss: {},
5
+ },
6
+ };
7
+
8
+ export default config;
workers1/auto3d/CursorLens/prisma/migrations/20240815195611_init/migration.sql ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- CreateTable
2
+ CREATE TABLE "Log" (
3
+ "id" TEXT NOT NULL,
4
+ "method" TEXT NOT NULL,
5
+ "url" TEXT NOT NULL,
6
+ "headers" TEXT NOT NULL,
7
+ "body" TEXT NOT NULL,
8
+ "response" TEXT NOT NULL,
9
+ "timestamp" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
10
+
11
+ CONSTRAINT "Log_pkey" PRIMARY KEY ("id")
12
+ );
workers1/auto3d/CursorLens/prisma/migrations/20240815203248_add_metadata/migration.sql ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ -- AlterTable
2
+ ALTER TABLE "Log" ADD COLUMN "metadata" JSONB;
workers1/auto3d/CursorLens/prisma/migrations/20240815204542_add_config/migration.sql ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- CreateTable
2
+ CREATE TABLE "AIConfiguration" (
3
+ "id" TEXT NOT NULL,
4
+ "name" TEXT NOT NULL,
5
+ "model" TEXT NOT NULL,
6
+ "temperature" DOUBLE PRECISION,
7
+ "maxTokens" INTEGER,
8
+ "topP" DOUBLE PRECISION,
9
+ "frequencyPenalty" DOUBLE PRECISION,
10
+ "presencePenalty" DOUBLE PRECISION,
11
+ "isDefault" BOOLEAN NOT NULL DEFAULT false,
12
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
13
+ "updatedAt" TIMESTAMP(3) NOT NULL,
14
+
15
+ CONSTRAINT "AIConfiguration_pkey" PRIMARY KEY ("id")
16
+ );
17
+
18
+ -- CreateIndex
19
+ CREATE UNIQUE INDEX "AIConfiguration_name_key" ON "AIConfiguration"("name");
workers1/auto3d/CursorLens/prisma/migrations/20240815210443_add_provider_to_ai_configuration/migration.sql ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ -- AlterTable
2
+ ALTER TABLE "AIConfiguration" ADD COLUMN "provider" TEXT NOT NULL DEFAULT 'openai';
workers1/auto3d/CursorLens/prisma/migrations/20240816193734_add_api_key/migration.sql ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ -- AlterTable
2
+ ALTER TABLE "AIConfiguration" ADD COLUMN "apiKey" TEXT;
workers1/auto3d/CursorLens/prisma/migrations/20240816194453_add_configuration_relation/migration.sql ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ -- AlterTable
2
+ ALTER TABLE "Log" ADD COLUMN "configurationId" TEXT;
3
+
4
+ -- AddForeignKey
5
+ ALTER TABLE "Log" ADD CONSTRAINT "Log_configurationId_fkey" FOREIGN KEY ("configurationId") REFERENCES "AIConfiguration"("id") ON DELETE SET NULL ON UPDATE CASCADE;
workers1/auto3d/CursorLens/prisma/migrations/20240824081904_add_cost_model/migration.sql ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Warnings:
3
+
4
+ - You are about to drop the column `configurationId` on the `Log` table. All the data in the column will be lost.
5
+ - Made the column `metadata` on table `Log` required. This step will fail if there are existing NULL values in that column.
6
+
7
+ */
8
+ -- DropForeignKey
9
+ ALTER TABLE "Log" DROP CONSTRAINT "Log_configurationId_fkey";
10
+
11
+ -- AlterTable
12
+ ALTER TABLE "Log" DROP COLUMN "configurationId",
13
+ ALTER COLUMN "metadata" SET NOT NULL;
14
+
15
+ -- CreateTable
16
+ CREATE TABLE "ModelCost" (
17
+ "id" TEXT NOT NULL,
18
+ "provider" TEXT NOT NULL,
19
+ "model" TEXT NOT NULL,
20
+ "inputTokenCost" DOUBLE PRECISION NOT NULL,
21
+ "outputTokenCost" DOUBLE PRECISION NOT NULL,
22
+ "validFrom" TIMESTAMP(3) NOT NULL,
23
+ "validTo" TIMESTAMP(3),
24
+
25
+ CONSTRAINT "ModelCost_pkey" PRIMARY KEY ("id")
26
+ );
27
+
28
+ -- CreateIndex
29
+ CREATE UNIQUE INDEX "ModelCost_provider_model_validFrom_key" ON "ModelCost"("provider", "model", "validFrom");
30
+
31
+ -- CreateIndex
32
+ CREATE INDEX "Log_timestamp_idx" ON "Log"("timestamp");
workers1/auto3d/CursorLens/prisma/migrations/migration_lock.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Please do not edit this file manually
2
+ # It should be added in your version-control system (i.e. Git)
3
+ provider = "postgresql"
workers1/auto3d/CursorLens/prisma/schema.prisma ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This is your Prisma schema file,
2
+ // learn more about it in the docs: https://pris.ly/d/prisma-schema
3
+
4
+ generator client {
5
+ provider = "prisma-client-js"
6
+ binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
7
+ }
8
+
9
+ datasource db {
10
+ provider = "postgresql"
11
+ url = env("DATABASE_URL")
12
+ }
13
+
14
+ model Log {
15
+ id String @id @default(cuid())
16
+ method String
17
+ url String
18
+ headers String
19
+ body Json
20
+ response Json
21
+ timestamp DateTime @default(now())
22
+ metadata Json
23
+
24
+ @@index([timestamp])
25
+ }
26
+
27
+ model AIConfiguration {
28
+ id String @id @default(cuid())
29
+ name String @unique
30
+ provider String @default("openai")
31
+ model String
32
+ temperature Float?
33
+ maxTokens Int?
34
+ topP Float?
35
+ frequencyPenalty Float?
36
+ presencePenalty Float?
37
+ isDefault Boolean @default(false)
38
+ apiKey String?
39
+ createdAt DateTime @default(now())
40
+ updatedAt DateTime @updatedAt
41
+ }
42
+
43
+ model ModelCost {
44
+ id String @id @default(cuid())
45
+ provider String
46
+ model String
47
+ inputTokenCost Float
48
+ outputTokenCost Float
49
+ validFrom DateTime
50
+ validTo DateTime?
51
+
52
+ @@unique([provider, model, validFrom])
53
+ }
workers1/auto3d/CursorLens/prisma/seed.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PrismaClient } from "@prisma/client";
2
+ import { getModelConfigurations } from "../src/lib/model-config";
3
+
4
+ const prisma = new PrismaClient();
5
+
6
+ function convertToCostPerMillionTokens(cost: number): number {
7
+ return cost * 1_000_000;
8
+ }
9
+
10
+ async function main() {
11
+ const modelConfigurations = getModelConfigurations();
12
+
13
+ for (const [provider, models] of Object.entries(modelConfigurations)) {
14
+ for (const [model, config] of Object.entries(models)) {
15
+ if (config && "inputTokenCost" in config && "outputTokenCost" in config) {
16
+ await prisma.modelCost.upsert({
17
+ where: {
18
+ provider_model_validFrom: {
19
+ provider,
20
+ model,
21
+ validFrom: new Date(),
22
+ },
23
+ },
24
+ update: {
25
+ inputTokenCost: convertToCostPerMillionTokens(
26
+ config.inputTokenCost,
27
+ ),
28
+ outputTokenCost: convertToCostPerMillionTokens(
29
+ config.outputTokenCost,
30
+ ),
31
+ },
32
+ create: {
33
+ provider,
34
+ model,
35
+ inputTokenCost: convertToCostPerMillionTokens(
36
+ config.inputTokenCost,
37
+ ),
38
+ outputTokenCost: convertToCostPerMillionTokens(
39
+ config.outputTokenCost,
40
+ ),
41
+ validFrom: new Date(),
42
+ },
43
+ });
44
+ }
45
+ }
46
+ }
47
+
48
+ console.log("Seed data inserted successfully");
49
+ }
50
+
51
+ main()
52
+ .catch((e) => {
53
+ console.error(e);
54
+ process.exit(1);
55
+ })
56
+ .finally(async () => {
57
+ await prisma.$disconnect();
58
+ });
workers1/auto3d/CursorLens/public/ant-cache-create.png ADDED
workers1/auto3d/CursorLens/public/ant-cache-read.png ADDED
workers1/auto3d/CursorLens/public/anthropicCashedXConfig.png ADDED
workers1/auto3d/CursorLens/public/cl-dashboard.png ADDED
workers1/auto3d/CursorLens/public/cl-settings.png ADDED
workers1/auto3d/CursorLens/public/cl-stats.jpeg ADDED
workers1/auto3d/CursorLens/public/cl-stats.png ADDED
workers1/auto3d/CursorLens/scripts/update-log-costs.ts ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PrismaClient } from "@prisma/client";
2
+ import { getModelCost } from "../src/lib/cost-calculator";
3
+
4
+ const prisma = new PrismaClient();
5
+
6
+ async function updateLogCosts() {
7
+ const logs = await prisma.log.findMany();
8
+
9
+ console.log(`Found ${logs.length} logs to update`);
10
+
11
+ for (const log of logs) {
12
+ try {
13
+ const metadata = log.metadata as any;
14
+ const { provider, model } = metadata;
15
+
16
+ if (!provider || !model) {
17
+ console.warn(`Skipping log ${log.id}: Missing provider or model`);
18
+ continue;
19
+ }
20
+
21
+ const modelCost = await getModelCost(provider, model);
22
+
23
+ let updatedMetadata = { ...metadata };
24
+ let response =
25
+ typeof log.response === "string"
26
+ ? JSON.parse(log.response)
27
+ : log.response;
28
+
29
+ // Extract token usage from response
30
+ const usage = response?.usage || {};
31
+ const inputTokens = usage.promptTokens || metadata.inputTokens || 0;
32
+ const outputTokens = usage.completionTokens || metadata.outputTokens || 0;
33
+ const totalTokens = usage.totalTokens || inputTokens + outputTokens;
34
+
35
+ // Calculate costs
36
+ const inputCost = (inputTokens / 1000000) * modelCost.inputTokenCost;
37
+ const outputCost = (outputTokens / 1000000) * modelCost.outputTokenCost;
38
+ const totalCost = inputCost + outputCost;
39
+
40
+ updatedMetadata = {
41
+ ...updatedMetadata,
42
+ inputTokens,
43
+ outputTokens,
44
+ totalTokens,
45
+ inputCost,
46
+ outputCost,
47
+ totalCost,
48
+ };
49
+
50
+ await prisma.log.update({
51
+ where: { id: log.id },
52
+ data: { metadata: updatedMetadata },
53
+ });
54
+
55
+ console.log(
56
+ `Updated log ${log.id}: inputTokens=${inputTokens}, outputTokens=${outputTokens}, totalCost=${totalCost}`,
57
+ );
58
+ } catch (error) {
59
+ console.error(`Error updating log ${log.id}:`, error);
60
+ }
61
+ }
62
+
63
+ console.log("Finished updating logs");
64
+ }
65
+
66
+ updateLogCosts()
67
+ .catch((error) => {
68
+ console.error("Error in updateLogCosts:", error);
69
+ })
70
+ .finally(async () => {
71
+ await prisma.$disconnect();
72
+ });
workers1/auto3d/CursorLens/src/app/[...openai]/route.ts ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { openai, createOpenAI } from "@ai-sdk/openai";
2
+ import { anthropic, createAnthropic } from "@ai-sdk/anthropic";
3
+ import { createCohere } from "@ai-sdk/cohere";
4
+ import { createMistral } from "@ai-sdk/mistral";
5
+ import { ollama } from "ollama-ai-provider";
6
+
7
+ import { generateText, streamText } from "ai";
8
+ import { insertLog, getDefaultConfiguration } from "@/lib/db";
9
+ import { type NextRequest, NextResponse } from "next/server";
10
+ import OpenAI from "openai";
11
+ import { env } from "@/env";
12
+ import { calculateCost, getModelCost } from "@/lib/cost-calculator";
13
+
14
+ const openaiClient = new OpenAI({
15
+ apiKey: env.OPENAI_API_KEY,
16
+ });
17
+
18
+ // Allow streaming responses up to 30 seconds
19
+ export const maxDuration = 30;
20
+
21
+ async function getAIModelClient(provider: string, model: string) {
22
+ switch (provider.toLowerCase()) {
23
+ case "openai":
24
+ return openai(model);
25
+ case "anthropic": {
26
+ const anthropicClient = createAnthropic({
27
+ apiKey: env.ANTHROPIC_API_KEY,
28
+ });
29
+ return anthropicClient(model);
30
+ }
31
+ case "anthropiccached": {
32
+ const anthropicClient = createAnthropic({
33
+ apiKey: env.ANTHROPIC_API_KEY,
34
+ });
35
+ return anthropicClient(model, { cacheControl: true });
36
+ }
37
+ case "cohere": {
38
+ const cohereClient = createCohere({
39
+ apiKey: env.COHERE_API_KEY,
40
+ });
41
+ return cohereClient(model);
42
+ }
43
+ case "mistral": {
44
+ const mistralClient = createMistral({
45
+ apiKey: env.MISTRAL_API_KEY,
46
+ });
47
+ return mistralClient(model);
48
+ }
49
+ case "groq": {
50
+ const groqClient = createOpenAI({
51
+ apiKey: env.GROQ_API_KEY,
52
+ });
53
+ return groqClient(model);
54
+ }
55
+ case "ollama":
56
+ return ollama("llama3.1");
57
+ case "google-vertex":
58
+ throw new Error("Google Vertex AI is not currently supported");
59
+ default:
60
+ throw new Error(`Unsupported provider: ${provider}`);
61
+ }
62
+ }
63
+
64
+ export async function POST(
65
+ request: NextRequest,
66
+ { params }: { params: { openai: string[] } },
67
+ ) {
68
+ const endpoint = params.openai.join("/");
69
+ if (endpoint !== "chat/completions" && endpoint !== "v1/chat/completions") {
70
+ return NextResponse.json({ error: "Not found", endpoint }, { status: 404 });
71
+ }
72
+
73
+ const body = await request.json();
74
+ const { messages, model: cursorModel, stream = false, ...otherParams } = body;
75
+
76
+ try {
77
+ const defaultConfig = await getDefaultConfiguration();
78
+ if (!defaultConfig) {
79
+ throw new Error("No default configuration found");
80
+ }
81
+
82
+ const {
83
+ id: configId,
84
+ provider,
85
+ model,
86
+ temperature,
87
+ maxTokens,
88
+ topP,
89
+ frequencyPenalty,
90
+ presencePenalty,
91
+ } = defaultConfig;
92
+
93
+ if (!provider) {
94
+ throw new Error("Provider is not defined in the default configuration");
95
+ }
96
+
97
+ const aiModel = await getAIModelClient(provider, model);
98
+
99
+ let modifiedMessages = messages;
100
+
101
+ if (provider.toLowerCase() === "anthropiccached") {
102
+ const hasPotentialContext = messages.some(
103
+ (message: any) => message.name === "potential_context",
104
+ );
105
+
106
+ modifiedMessages = messages.map((message: any) => {
107
+ if (message.name === "potential_context") {
108
+ return {
109
+ ...message,
110
+ experimental_providerMetadata: {
111
+ anthropic: { cacheControl: { type: "ephemeral" } },
112
+ },
113
+ };
114
+ }
115
+ return message;
116
+ });
117
+
118
+ if (!hasPotentialContext && modifiedMessages.length >= 2) {
119
+ modifiedMessages[1] = {
120
+ ...modifiedMessages[1],
121
+ experimental_providerMetadata: {
122
+ anthropic: { cacheControl: { type: "ephemeral" } },
123
+ },
124
+ };
125
+ }
126
+ }
127
+
128
+ const streamTextOptions = {
129
+ model: aiModel,
130
+ messages: modifiedMessages,
131
+ maxTokens: ["anthropic", "anthropiccached"].includes(
132
+ provider.toLowerCase(),
133
+ )
134
+ ? 8192
135
+ : undefined,
136
+ // Add other parameters from defaultConfig if needed
137
+ };
138
+
139
+ const logEntry = {
140
+ method: "POST",
141
+ url: `/api/${endpoint}`,
142
+ headers: JSON.stringify(Object.fromEntries(request.headers)),
143
+ body: {
144
+ ...body,
145
+ ...streamTextOptions,
146
+ model: model,
147
+ },
148
+ response: {},
149
+ timestamp: new Date(),
150
+ metadata: {
151
+ configId,
152
+ provider,
153
+ model,
154
+ temperature,
155
+ maxTokens,
156
+ topP,
157
+ frequencyPenalty,
158
+ presencePenalty,
159
+ inputTokens: 0,
160
+ outputTokens: 0,
161
+ totalTokens: 0,
162
+ inputCost: 0,
163
+ outputCost: 0,
164
+ totalCost: 0,
165
+ },
166
+ };
167
+
168
+ if (stream) {
169
+ const result = await streamText({
170
+ ...streamTextOptions,
171
+ async onFinish({
172
+ text,
173
+ toolCalls,
174
+ toolResults,
175
+ usage,
176
+ finishReason,
177
+ ...otherProps
178
+ }) {
179
+ const inputTokens = usage?.promptTokens ?? 0;
180
+ const outputTokens = usage?.completionTokens ?? 0;
181
+ const totalTokens = usage?.totalTokens ?? 0;
182
+
183
+ const modelCost = await getModelCost(provider, model);
184
+ const inputCost = (inputTokens / 1000000) * modelCost.inputTokenCost;
185
+ const outputCost =
186
+ (outputTokens / 1000000) * modelCost.outputTokenCost;
187
+ const totalCost = inputCost + outputCost;
188
+
189
+ logEntry.response = {
190
+ text,
191
+ toolCalls,
192
+ toolResults,
193
+ usage,
194
+ finishReason,
195
+ ...otherProps,
196
+ };
197
+ logEntry.metadata = {
198
+ ...logEntry.metadata,
199
+ inputTokens,
200
+ outputTokens,
201
+ totalTokens,
202
+ inputCost,
203
+ outputCost,
204
+ totalCost,
205
+ };
206
+ await insertLog(logEntry);
207
+ },
208
+ });
209
+
210
+ // Convert the result to a ReadableStream in OpenAI's format
211
+ const stream = new ReadableStream({
212
+ async start(controller) {
213
+ for await (const chunk of result.textStream) {
214
+ const data = JSON.stringify({
215
+ id: `chatcmpl-${Math.random().toString(36).substr(2, 9)}`,
216
+ object: "chat.completion.chunk",
217
+ created: Math.floor(Date.now() / 1000),
218
+ model: model,
219
+ choices: [
220
+ {
221
+ delta: { content: chunk },
222
+ index: 0,
223
+ finish_reason: null,
224
+ },
225
+ ],
226
+ });
227
+ controller.enqueue(new TextEncoder().encode(`data: ${data}\n\n`));
228
+ }
229
+ controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n"));
230
+ controller.close();
231
+ },
232
+ });
233
+
234
+ // Return a streaming response
235
+ return new Response(stream, {
236
+ headers: {
237
+ "Content-Type": "text/event-stream",
238
+ "Cache-Control": "no-cache",
239
+ Connection: "keep-alive",
240
+ },
241
+ });
242
+ }
243
+ // For non-streaming requests, use the AI SDK
244
+ const result = await generateText({
245
+ model: aiModel,
246
+ messages,
247
+ });
248
+
249
+ const inputTokens = result.usage?.prompt_tokens ?? 0;
250
+ const outputTokens = result.usage?.completion_tokens ?? 0;
251
+ const totalTokens = result.usage?.total_tokens ?? 0;
252
+
253
+ const modelCost = await getModelCost(provider, model);
254
+ const inputCost = inputTokens * modelCost.inputTokenCost;
255
+ const outputCost = outputTokens * modelCost.outputTokenCost;
256
+ const totalCost = inputCost + outputCost;
257
+
258
+ logEntry.response = JSON.stringify(result);
259
+ logEntry.metadata = {
260
+ ...logEntry.metadata,
261
+ inputTokens,
262
+ outputTokens,
263
+ totalTokens,
264
+ inputCost,
265
+ outputCost,
266
+ totalCost,
267
+ };
268
+ await insertLog(logEntry);
269
+
270
+ return NextResponse.json(result);
271
+ } catch (error) {
272
+ console.error("Error in chat completion:", error);
273
+ const errorMessage = error instanceof Error ? error.message : String(error);
274
+ const errorLogEntry = {
275
+ method: "POST",
276
+ url: `/api/${endpoint}`,
277
+ headers: JSON.stringify(Object.fromEntries(request.headers)),
278
+ body: JSON.stringify(body),
279
+ response: JSON.stringify({ error: errorMessage }),
280
+ timestamp: new Date(),
281
+ metadata: JSON.stringify({
282
+ error: errorMessage,
283
+ stack: (error as Error).stack,
284
+ }),
285
+ };
286
+ await insertLog(errorLogEntry);
287
+ return NextResponse.json({ error: errorMessage }, { status: 500 });
288
+ }
289
+ }
290
+
291
+ export async function GET(
292
+ request: NextRequest,
293
+ { params }: { params: { openai: string[] } },
294
+ ) {
295
+ const endpoint = params.openai.join("/");
296
+
297
+ // Existing 'models' endpoint
298
+ if (endpoint === "models") {
299
+ const logEntry = {
300
+ method: "GET",
301
+ url: "/api/v1/models",
302
+ headers: JSON.stringify(Object.fromEntries(request.headers)),
303
+ body: "",
304
+ response: "",
305
+ timestamp: new Date(),
306
+ };
307
+
308
+ try {
309
+ const models = await openaiClient.models.list();
310
+ logEntry.response = JSON.stringify(models);
311
+ await insertLog(logEntry);
312
+ return NextResponse.json(models);
313
+ } catch (error) {
314
+ console.error("Error fetching models:", error);
315
+ logEntry.response = JSON.stringify({ error: String(error) });
316
+ await insertLog(logEntry);
317
+ return NextResponse.json({ error: String(error) }, { status: 500 });
318
+ }
319
+ }
320
+
321
+ // New test routes
322
+ else if (endpoint === "test/openai") {
323
+ return testOpenAI();
324
+ } else if (endpoint === "test/anthropic") {
325
+ return testAnthropic();
326
+ } else if (endpoint === "test/anthropiccached") {
327
+ return testAnthropicCached();
328
+ } else if (endpoint === "test/cohere") {
329
+ return testCohere();
330
+ } else if (endpoint === "test/mistral") {
331
+ return testMistral();
332
+ } else if (endpoint === "test/groq") {
333
+ return testGroq();
334
+ }
335
+
336
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
337
+ }
338
+
339
+ async function testOpenAI() {
340
+ try {
341
+ const model = openai("gpt-3.5-turbo");
342
+ const result = await generateText({
343
+ model,
344
+ messages: [{ role: "user", content: 'Say "Hello from OpenAI!"' }],
345
+ });
346
+ return NextResponse.json({ provider: "OpenAI", result });
347
+ } catch (error) {
348
+ console.error("Error testing OpenAI:", error);
349
+ return NextResponse.json({ error: String(error) }, { status: 500 });
350
+ }
351
+ }
352
+
353
+ async function testAnthropicCached() {
354
+ try {
355
+ const model = anthropic("claude-3-5-sonnet-20240620", {
356
+ cacheControl: true,
357
+ });
358
+
359
+ const result = await generateText({
360
+ model,
361
+ messages: [
362
+ { role: "user", content: 'Say "Hello from Anthropic and Vercel"' },
363
+ ],
364
+ });
365
+ return NextResponse.json({ provider: "Anthropic Cached", result });
366
+ } catch (error) {
367
+ console.error("Error testing Anthropic:", error);
368
+ return NextResponse.json({ error: String(error) }, { status: 500 });
369
+ }
370
+ }
371
+
372
+ async function testAnthropic() {
373
+ try {
374
+ const anthropicClient = createAnthropic({
375
+ apiKey: env.ANTHROPIC_API_KEY,
376
+ });
377
+ const model = anthropicClient("claude-3-haiku-20240307");
378
+ const result = await generateText({
379
+ model,
380
+ messages: [{ role: "user", content: 'Say "Hello from Anthropic!"' }],
381
+ });
382
+ return NextResponse.json({ provider: "Anthropic", result });
383
+ } catch (error) {
384
+ console.error("Error testing Anthropic:", error);
385
+ return NextResponse.json({ error: String(error) }, { status: 500 });
386
+ }
387
+ }
388
+
389
+ async function testCohere() {
390
+ try {
391
+ const cohereClient = createCohere({
392
+ apiKey: env.COHERE_API_KEY,
393
+ });
394
+ const model = cohereClient("command");
395
+ const result = await generateText({
396
+ model,
397
+ messages: [{ role: "user", content: 'Say "Hello from Cohere!"' }],
398
+ });
399
+ return NextResponse.json({ provider: "Cohere", result });
400
+ } catch (error) {
401
+ console.error("Error testing Cohere:", error);
402
+ return NextResponse.json({ error: String(error) }, { status: 500 });
403
+ }
404
+ }
405
+
406
+ async function testMistral() {
407
+ try {
408
+ const mistralClient = createMistral({
409
+ apiKey: env.MISTRAL_API_KEY,
410
+ });
411
+ const model = mistralClient("mistral-small-latest");
412
+ const result = await generateText({
413
+ model,
414
+ messages: [{ role: "user", content: 'Say "Hello from Mistral!"' }],
415
+ });
416
+ return NextResponse.json({ provider: "Mistral", result });
417
+ } catch (error) {
418
+ console.error("Error testing Mistral:", error);
419
+ return NextResponse.json({ error: String(error) }, { status: 500 });
420
+ }
421
+ }
422
+
423
+ async function testGroq() {
424
+ try {
425
+ const groqClient = createOpenAI({
426
+ apiKey: env.GROQ_API_KEY,
427
+ });
428
+ const model = groqClient("llama-3.1-70b-versatile");
429
+ const result = await generateText({
430
+ model,
431
+ messages: [{ role: "user", content: 'Say "Hello from Groq!"' }],
432
+ });
433
+ return NextResponse.json({ provider: "Groq", result });
434
+ } catch (error) {
435
+ console.error("Error testing Groq:", error);
436
+ return NextResponse.json({ error: String(error) }, { status: 500 });
437
+ }
438
+ }
workers1/auto3d/CursorLens/src/app/actions.ts ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use server";
2
+
3
+ import { getModelConfigurations } from "@/lib/model-config";
4
+ import prisma from "@/lib/prisma";
5
+ import type { Log, AIConfiguration, Prisma } from "@prisma/client";
6
+
7
+ // Helper function to serialize dates
8
+ function serializeDates<T>(obj: T): T {
9
+ return JSON.parse(JSON.stringify(obj));
10
+ }
11
+
12
+ // Add the metadata type definition
13
+ type LogMetadata = {
14
+ topP: number;
15
+ model: string;
16
+ configId: string;
17
+ provider: string;
18
+ maxTokens: number;
19
+ temperature: number;
20
+ presencePenalty: number;
21
+ frequencyPenalty: number;
22
+ totalTokens: number;
23
+ inputTokens: number;
24
+ outputTokens: number;
25
+ totalCost: number;
26
+ };
27
+
28
+ export async function getLogs({
29
+ provider = "all",
30
+ startDate = "",
31
+ endDate = "",
32
+ }: { provider?: string; startDate?: string; endDate?: string } = {}) {
33
+ try {
34
+ const query: Prisma.LogFindManyArgs = {
35
+ orderBy: {
36
+ timestamp: "desc",
37
+ },
38
+ };
39
+
40
+ const whereConditions: Prisma.LogWhereInput = {};
41
+
42
+ if (provider !== "all") {
43
+ whereConditions.metadata = {
44
+ path: ["provider"],
45
+ equals: provider,
46
+ };
47
+ }
48
+
49
+ if (startDate || endDate) {
50
+ whereConditions.timestamp = {};
51
+ if (startDate) {
52
+ whereConditions.timestamp.gte = new Date(startDate);
53
+ }
54
+ if (endDate) {
55
+ whereConditions.timestamp.lte = new Date(endDate);
56
+ }
57
+ }
58
+
59
+ // Only add the where clause if we have conditions
60
+ if (Object.keys(whereConditions).length > 0) {
61
+ query.where = whereConditions;
62
+ }
63
+
64
+ const logs = await prisma.log.findMany(query);
65
+
66
+ // Cast the metadata to the correct type
67
+ return logs.map((log) => ({
68
+ ...log,
69
+ metadata: log.metadata as LogMetadata,
70
+ }));
71
+ } catch (error) {
72
+ console.error("Error fetching logs:", error);
73
+ throw error;
74
+ }
75
+ }
76
+
77
+ export async function getStats(timeFilter = "all"): Promise<{
78
+ totalLogs: number;
79
+ totalTokens: number;
80
+ totalPromptTokens: number;
81
+ totalCompletionTokens: number;
82
+ perModelProviderStats: {
83
+ [key: string]: {
84
+ logs: number;
85
+ tokens: number;
86
+ promptTokens: number;
87
+ completionTokens: number;
88
+ cost: number;
89
+ provider: string;
90
+ model: string;
91
+ };
92
+ };
93
+ tokenUsageOverTime: {
94
+ date: string;
95
+ tokens: number;
96
+ promptTokens: number;
97
+ completionTokens: number;
98
+ }[];
99
+ }> {
100
+ let startDate = new Date(0); // Default to all time
101
+
102
+ switch (timeFilter) {
103
+ case "day":
104
+ startDate = new Date(Date.now() - 24 * 60 * 60 * 1000);
105
+ break;
106
+ case "week":
107
+ startDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
108
+ break;
109
+ case "month":
110
+ startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
111
+ break;
112
+ }
113
+
114
+ const logs = await prisma.log.findMany({
115
+ where: {
116
+ timestamp: {
117
+ gte: startDate,
118
+ },
119
+ },
120
+ orderBy: {
121
+ timestamp: "asc",
122
+ },
123
+ });
124
+
125
+ const perModelProviderStats: {
126
+ [key: string]: {
127
+ logs: number;
128
+ tokens: number;
129
+ promptTokens: number;
130
+ completionTokens: number;
131
+ cost: number;
132
+ provider: string;
133
+ model: string;
134
+ };
135
+ } = {};
136
+
137
+ let totalTokens = 0;
138
+ let totalPromptTokens = 0;
139
+ let totalCompletionTokens = 0;
140
+ const tokenUsageOverTime: {
141
+ date: string;
142
+ tokens: number;
143
+ promptTokens: number;
144
+ completionTokens: number;
145
+ }[] = [];
146
+
147
+ for (const log of logs) {
148
+ const metadata = log.metadata as LogMetadata;
149
+ const model = metadata.model || "unknown";
150
+ const provider = metadata.provider || "unknown";
151
+ const key = `${provider}:${model}`;
152
+
153
+ if (!perModelProviderStats[key]) {
154
+ perModelProviderStats[key] = {
155
+ logs: 0,
156
+ tokens: 0,
157
+ promptTokens: 0,
158
+ completionTokens: 0,
159
+ cost: 0,
160
+ provider,
161
+ model,
162
+ };
163
+ }
164
+ perModelProviderStats[key].logs += 1;
165
+
166
+ const tokens = metadata.totalTokens || 0;
167
+ const promptTokens = metadata.inputTokens || 0;
168
+ const completionTokens = metadata.outputTokens || 0;
169
+ const cost = metadata.totalCost || 0;
170
+
171
+ perModelProviderStats[key].tokens += tokens;
172
+ perModelProviderStats[key].promptTokens += promptTokens;
173
+ perModelProviderStats[key].completionTokens += completionTokens;
174
+ perModelProviderStats[key].cost += cost;
175
+
176
+ totalTokens += tokens;
177
+ totalPromptTokens += promptTokens;
178
+ totalCompletionTokens += completionTokens;
179
+
180
+ const date = log.timestamp.toISOString().split("T")[0];
181
+ const existingEntry = tokenUsageOverTime.find(
182
+ (entry) => entry.date === date,
183
+ );
184
+ if (existingEntry) {
185
+ existingEntry.tokens += tokens;
186
+ existingEntry.promptTokens += promptTokens;
187
+ existingEntry.completionTokens += completionTokens;
188
+ } else {
189
+ tokenUsageOverTime.push({
190
+ date,
191
+ tokens,
192
+ promptTokens,
193
+ completionTokens,
194
+ });
195
+ }
196
+ }
197
+
198
+ return {
199
+ totalLogs: logs.length,
200
+ totalTokens,
201
+ totalPromptTokens,
202
+ totalCompletionTokens,
203
+ perModelProviderStats,
204
+ tokenUsageOverTime,
205
+ };
206
+ }
207
+
208
+ export async function getConfigurations(): Promise<AIConfiguration[]> {
209
+ const configs = await prisma.aIConfiguration.findMany();
210
+ return serializeDates(configs);
211
+ }
212
+
213
+ export async function updateDefaultConfiguration(
214
+ configId: string,
215
+ ): Promise<void> {
216
+ await prisma.aIConfiguration.updateMany({
217
+ where: { isDefault: true },
218
+ data: { isDefault: false },
219
+ });
220
+ await prisma.aIConfiguration.update({
221
+ where: { id: configId },
222
+ data: { isDefault: true },
223
+ });
224
+ }
225
+
226
+ export async function createConfiguration(config: Partial<AIConfiguration>) {
227
+ const {
228
+ name,
229
+ provider,
230
+ model,
231
+ temperature,
232
+ maxTokens,
233
+ topP,
234
+ frequencyPenalty,
235
+ presencePenalty,
236
+ isDefault,
237
+ apiKey,
238
+ } = config;
239
+
240
+ // TODO: Consider using Zod schemas for validation and potentially integrate
241
+ // https://github.com/vantezzen/auto-form for form generation and validation
242
+
243
+ // Guard clause to ensure required fields are present
244
+ if (!name || !provider || !model) {
245
+ throw new Error("Name, provider, and model are required fields");
246
+ }
247
+
248
+ const newConfig = await prisma.aIConfiguration.create({
249
+ data: {
250
+ name,
251
+ provider,
252
+ model,
253
+ temperature: temperature,
254
+ maxTokens: maxTokens,
255
+ topP: topP,
256
+ frequencyPenalty: frequencyPenalty,
257
+ presencePenalty: presencePenalty,
258
+ isDefault: isDefault,
259
+ apiKey: apiKey,
260
+ },
261
+ });
262
+
263
+ return serializeDates(newConfig);
264
+ }
265
+
266
+ export async function updateConfiguration(
267
+ id: string,
268
+ data: Partial<AIConfiguration>,
269
+ ): Promise<AIConfiguration> {
270
+ const updatedConfig = await prisma.aIConfiguration.update({
271
+ where: { id },
272
+ data,
273
+ });
274
+ return serializeDates(updatedConfig);
275
+ }
276
+
277
+ export async function deleteConfiguration(id: string): Promise<void> {
278
+ await prisma.aIConfiguration.delete({
279
+ where: { id },
280
+ });
281
+ }
282
+
283
+ type ConfigurationCost = {
284
+ provider: string;
285
+ model: string;
286
+ inputTokenCost: number;
287
+ outputTokenCost: number;
288
+ };
289
+
290
+ export async function getConfigurationCosts(): Promise<ConfigurationCost[]> {
291
+ const modelConfigurations = getModelConfigurations();
292
+ return Object.entries(modelConfigurations).flatMap(([provider, models]) =>
293
+ Object.entries(models)
294
+ .filter(
295
+ (entry): entry is [string, NonNullable<(typeof entry)[1]>] =>
296
+ entry[1] !== null &&
297
+ "inputTokenCost" in entry[1] &&
298
+ "outputTokenCost" in entry[1],
299
+ )
300
+ .map(([model, config]) => ({
301
+ provider,
302
+ model,
303
+ inputTokenCost: config.inputTokenCost,
304
+ outputTokenCost: config.outputTokenCost,
305
+ })),
306
+ );
307
+ }
308
+
309
+ export { getModelConfigurations };
310
+
311
+ export async function setDefaultConfiguration(configId: string): Promise<void> {
312
+ try {
313
+ await prisma.aIConfiguration.updateMany({
314
+ where: { isDefault: true },
315
+ data: { isDefault: false },
316
+ });
317
+ await prisma.aIConfiguration.update({
318
+ where: { id: configId },
319
+ data: { isDefault: true },
320
+ });
321
+ } catch (error) {
322
+ console.error("Error setting default configuration:", error);
323
+ throw error;
324
+ }
325
+ }
workers1/auto3d/CursorLens/src/app/api/configurations/route.ts ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import {
3
+ getConfigurations,
4
+ createConfiguration,
5
+ updateConfiguration,
6
+ deleteConfiguration,
7
+ } from "@/app/actions";
8
+
9
+ export async function GET() {
10
+ try {
11
+ const configurations = await getConfigurations();
12
+ return NextResponse.json(configurations);
13
+ } catch (error) {
14
+ console.error("Error fetching configurations:", error);
15
+ return NextResponse.json(
16
+ { error: "Error fetching configurations" },
17
+ { status: 500 },
18
+ );
19
+ }
20
+ }
21
+
22
+ export async function POST(request: NextRequest) {
23
+ try {
24
+ const configData = await request.json();
25
+ const newConfig = await createConfiguration(configData);
26
+ return NextResponse.json(newConfig);
27
+ } catch (error) {
28
+ console.error("Error creating configuration:", error);
29
+ return NextResponse.json(
30
+ { error: "Error creating configuration" },
31
+ { status: 500 },
32
+ );
33
+ }
34
+ }
35
+
36
+ export async function PUT(request: NextRequest) {
37
+ try {
38
+ const { id, ...data } = await request.json();
39
+ const updatedConfig = await updateConfiguration(id, data);
40
+ return NextResponse.json(updatedConfig);
41
+ } catch (error) {
42
+ console.error("Error updating configuration:", error);
43
+ return NextResponse.json(
44
+ { error: "Error updating configuration" },
45
+ { status: 500 },
46
+ );
47
+ }
48
+ }
49
+
50
+ export async function DELETE(request: NextRequest) {
51
+ const { searchParams } = request.nextUrl;
52
+ const id = searchParams.get("id");
53
+ if (!id) {
54
+ return NextResponse.json(
55
+ { error: "Configuration ID is required" },
56
+ { status: 400 },
57
+ );
58
+ }
59
+
60
+ try {
61
+ await deleteConfiguration(id);
62
+ return NextResponse.json({ message: "Configuration deleted successfully" });
63
+ } catch (error) {
64
+ console.error("Error deleting configuration:", error);
65
+ return NextResponse.json(
66
+ { error: "Error deleting configuration" },
67
+ { status: 500 },
68
+ );
69
+ }
70
+ }
workers1/auto3d/CursorLens/src/app/api/logs/[id]/route.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // app/api/logs/[id]/route.ts
2
+ import { NextRequest, NextResponse } from 'next/server';
3
+ import prisma from '@/lib/prisma';
4
+
5
+ interface RouteParams {
6
+ params: { id: string };
7
+ }
8
+
9
+ export async function GET(
10
+ request: NextRequest,
11
+ { params }: RouteParams
12
+ ): Promise<NextResponse> {
13
+ try {
14
+ const logId = params.id;
15
+
16
+ if (!logId) {
17
+ return NextResponse.json({ error: 'Invalid log ID' }, { status: 400 });
18
+ }
19
+
20
+ const log = await prisma.log.findUnique({
21
+ where: { id: logId },
22
+ });
23
+
24
+ if (log) {
25
+ return NextResponse.json(log);
26
+ } else {
27
+ return NextResponse.json({ error: 'Log not found' }, { status: 404 });
28
+ }
29
+ } catch (error) {
30
+ console.error('Error fetching log:', error);
31
+ return NextResponse.json(
32
+ { error: 'Internal server error' },
33
+ { status: 500 }
34
+ );
35
+ }
36
+ }
workers1/auto3d/CursorLens/src/app/api/logs/route.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // app/api/logs/route.ts
2
+ import { NextRequest, NextResponse } from "next/server";
3
+ import { getLogs } from "@/app/actions";
4
+ import prisma from "@/lib/prisma"; // Make sure to import prisma client
5
+
6
+ export async function GET(request: NextRequest) {
7
+ const { searchParams } = request.nextUrl;
8
+ const provider = searchParams.get("provider") || "all";
9
+ const startDate = searchParams.get("startDate") || "";
10
+ const endDate = searchParams.get("endDate") || "";
11
+
12
+ try {
13
+ const logs = await getLogs({ provider, startDate, endDate });
14
+ return NextResponse.json(logs);
15
+ } catch (error) {
16
+ console.error("Error fetching logs:", error);
17
+ return NextResponse.json({ error: "Error fetching logs" }, { status: 500 });
18
+ }
19
+ }
20
+
21
+ export async function POST(request: NextRequest) {
22
+ try {
23
+ const logData = await request.json();
24
+ const log = await prisma.log.create({
25
+ data: {
26
+ ...logData,
27
+ metadata: logData.metadata as any,
28
+ response: logData.response as any, // Ensure response is stored as Json
29
+ timestamp: new Date(),
30
+ },
31
+ });
32
+ return NextResponse.json(log);
33
+ } catch (error) {
34
+ console.error("Error creating log:", error);
35
+ return NextResponse.json({ error: "Error creating log" }, { status: 500 });
36
+ }
37
+ }
workers1/auto3d/CursorLens/src/app/api/stats/route.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { getStats } from "@/app/actions";
3
+
4
+ export async function GET(request: NextRequest) {
5
+ const { searchParams } = request.nextUrl;
6
+ const timeFilter = searchParams.get("timeFilter") || "all";
7
+
8
+ try {
9
+ const stats = await getStats(timeFilter);
10
+ return NextResponse.json(stats);
11
+ } catch (error) {
12
+ console.error("Error fetching stats:", error);
13
+ return NextResponse.json(
14
+ { error: "Error fetching stats" },
15
+ { status: 500 },
16
+ );
17
+ }
18
+ }
workers1/auto3d/CursorLens/src/app/configurations/page.tsx ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useEffect, useMemo, useCallback } from "react";
4
+ import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
5
+ import { Button } from "@/components/ui/button";
6
+ import { Input } from "@/components/ui/input";
7
+ import { Label } from "@/components/ui/label";
8
+ import {
9
+ Table,
10
+ TableBody,
11
+ TableCell,
12
+ TableHead,
13
+ TableHeader,
14
+ TableRow,
15
+ } from "@/components/ui/table";
16
+ import {
17
+ Dialog,
18
+ DialogContent,
19
+ DialogHeader,
20
+ DialogTitle,
21
+ DialogTrigger,
22
+ } from "@/components/ui/dialog";
23
+ import { Switch } from "@/components/ui/switch";
24
+ import { PlusIcon } from "lucide-react";
25
+ import {
26
+ Select,
27
+ SelectContent,
28
+ SelectItem,
29
+ SelectTrigger,
30
+ SelectValue,
31
+ } from "@/components/ui/select";
32
+ import {
33
+ getConfigurations,
34
+ updateDefaultConfiguration,
35
+ createConfiguration,
36
+ } from "../actions";
37
+ import {
38
+ getModelConfigurations,
39
+ type ModelConfigurations,
40
+ } from "@/lib/model-config";
41
+
42
+ interface AIConfiguration {
43
+ id: string;
44
+ name: string;
45
+ provider: string;
46
+ model: string;
47
+ temperature: number | null;
48
+ maxTokens: number | null;
49
+ topP: number | null;
50
+ frequencyPenalty: number | null;
51
+ presencePenalty: number | null;
52
+ isDefault: boolean;
53
+ createdAt: Date;
54
+ updatedAt: Date;
55
+ apiKey: string | null;
56
+ }
57
+
58
+ export default function ConfigurationsPage() {
59
+ const [configurations, setConfigurations] = useState<AIConfiguration[]>([]);
60
+ const [newConfig, setNewConfig] = useState<Partial<AIConfiguration>>({});
61
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
62
+ const [error, setError] = useState<string | null>(null);
63
+ const [selectedProvider, setSelectedProvider] = useState<string>("");
64
+ const [selectedModel, setSelectedModel] = useState<string>("");
65
+ const [customProvider, setCustomProvider] = useState<string>("");
66
+ const [customModel, setCustomModel] = useState<string>("");
67
+ const modelConfigurations: ModelConfigurations = useMemo(
68
+ () => getModelConfigurations(),
69
+ [],
70
+ );
71
+
72
+ const sortedConfigurations = useMemo(() => {
73
+ return [...configurations].sort((a, b) => {
74
+ if (a.provider !== b.provider) {
75
+ return a.provider.localeCompare(b.provider);
76
+ }
77
+ return a.name.localeCompare(b.name);
78
+ });
79
+ }, [configurations]);
80
+
81
+ useEffect(() => {
82
+ fetchConfigurations();
83
+ }, []);
84
+
85
+ const fetchConfigurations = useCallback(async () => {
86
+ try {
87
+ const configData = await getConfigurations();
88
+ setConfigurations(configData as AIConfiguration[]);
89
+ } catch (error) {
90
+ console.error("Error fetching configurations:", error);
91
+ setError("Error loading configurations");
92
+ }
93
+ }, []);
94
+
95
+ const handleCreateConfig = useCallback(async () => {
96
+ if (!newConfig.name || !newConfig.provider || !newConfig.model) {
97
+ setError("Name, provider, and model are required fields");
98
+ return;
99
+ }
100
+
101
+ try {
102
+ await createConfiguration(newConfig);
103
+ setIsDialogOpen(false);
104
+ setNewConfig({});
105
+ fetchConfigurations();
106
+ } catch (error) {
107
+ console.error("Error creating configuration:", error);
108
+ // TODO: Implement better error handling and user feedback
109
+ // - Handle specific errors (e.g., unique constraint violations)
110
+ // - Display error messages in the UI (e.g., using a toast notification)
111
+ // - Highlight fields with errors
112
+ // - Prevent dialog from closing on error
113
+ if (
114
+ error instanceof Error &&
115
+ error.message.includes("Unique constraint failed")
116
+ ) {
117
+ setError(
118
+ "A configuration with this name already exists. Please choose a different name.",
119
+ );
120
+ } else {
121
+ setError("Error creating configuration. Please try again.");
122
+ }
123
+ }
124
+ }, [newConfig, fetchConfigurations]);
125
+
126
+ const handleToggleDefault = useCallback(
127
+ async (configId: string, isDefault: boolean) => {
128
+ try {
129
+ await updateDefaultConfiguration(configId);
130
+ fetchConfigurations();
131
+ } catch (error) {
132
+ console.error("Error updating default configuration:", error);
133
+ setError("Error updating default configuration");
134
+ }
135
+ },
136
+ [fetchConfigurations],
137
+ );
138
+
139
+ // TODO: Implement proper handling when turning off a default configuration
140
+ // - Prevent turning off the last default configuration
141
+ // - Show a toast message explaining why the action is not allowed
142
+ // - Implement logic to ensure at least one configuration is always set as default
143
+
144
+ const handleTemplateSelect = useCallback(
145
+ (provider: string, model: string): void => {
146
+ const providerConfigs = modelConfigurations[provider];
147
+
148
+ if (!providerConfigs) {
149
+ console.error(`No configurations found for provider: ${provider}`);
150
+ return;
151
+ }
152
+
153
+ const config = providerConfigs[model];
154
+
155
+ if (!config || !("isTemplate" in config) || !config.isTemplate) {
156
+ console.error(
157
+ `No valid template configuration found for model: ${model}`,
158
+ );
159
+ return;
160
+ }
161
+
162
+ const readableName = `${provider.charAt(0).toUpperCase() + provider.slice(1)} ${model}`;
163
+
164
+ setNewConfig({
165
+ ...config,
166
+ name: readableName,
167
+ provider,
168
+ model,
169
+ });
170
+ setSelectedProvider(provider);
171
+ setSelectedModel(model);
172
+ },
173
+ [modelConfigurations],
174
+ );
175
+
176
+ const templateButtons = useMemo(
177
+ () =>
178
+ Object.entries(modelConfigurations).flatMap(([provider, models]) =>
179
+ Object.entries(models)
180
+ .filter(
181
+ ([_, config]) =>
182
+ config && "isTemplate" in config && config.isTemplate,
183
+ )
184
+ .map(([model, config]) => (
185
+ <Button
186
+ key={`${provider}-${model}`}
187
+ variant="outline"
188
+ className="w-full"
189
+ onClick={() => handleTemplateSelect(provider, model)}
190
+ >
191
+ {config && "name" in config
192
+ ? config.name
193
+ : `${provider} ${model}`}
194
+ </Button>
195
+ )),
196
+ ),
197
+ [modelConfigurations, handleTemplateSelect],
198
+ );
199
+
200
+ const handleProviderChange = useCallback(
201
+ (value: string) => {
202
+ setSelectedProvider(value);
203
+ setSelectedModel("");
204
+ setNewConfig({
205
+ ...newConfig,
206
+ provider: value === "other" ? "" : value,
207
+ model: "",
208
+ });
209
+ setCustomProvider("");
210
+ },
211
+ [newConfig],
212
+ );
213
+
214
+ const handleModelChange = useCallback(
215
+ (value: string) => {
216
+ setSelectedModel(value);
217
+ setNewConfig({ ...newConfig, model: value === "other" ? "" : value });
218
+ setCustomModel("");
219
+ },
220
+ [newConfig],
221
+ );
222
+
223
+ const handleCustomProviderChange = useCallback(
224
+ (e: React.ChangeEvent<HTMLInputElement>) => {
225
+ setCustomProvider(e.target.value);
226
+ setNewConfig({ ...newConfig, provider: e.target.value });
227
+ },
228
+ [newConfig],
229
+ );
230
+
231
+ const handleCustomModelChange = useCallback(
232
+ (e: React.ChangeEvent<HTMLInputElement>) => {
233
+ setCustomModel(e.target.value);
234
+ setNewConfig({ ...newConfig, model: e.target.value });
235
+ },
236
+ [newConfig],
237
+ );
238
+
239
+ return (
240
+ <div className="container mx-auto p-8">
241
+ <h1 className="mb-8 text-3xl font-bold">AI Configurations</h1>
242
+
243
+ <Card className="mb-8">
244
+ <CardHeader>
245
+ <CardTitle>Configuration List</CardTitle>
246
+ </CardHeader>
247
+ <CardContent>
248
+ <Table>
249
+ <TableHeader>
250
+ <TableRow>
251
+ <TableHead>Name</TableHead>
252
+ <TableHead>Provider</TableHead>
253
+ <TableHead>Model</TableHead>
254
+ <TableHead>Temperature</TableHead>
255
+ <TableHead>Max Tokens</TableHead>
256
+ <TableHead>Default</TableHead>
257
+ {/* TODO: Add an "Actions" column for edit functionality */}
258
+ </TableRow>
259
+ </TableHeader>
260
+ <TableBody>
261
+ {sortedConfigurations.map((config) => (
262
+ <TableRow key={config.id}>
263
+ <TableCell>{config.name}</TableCell>
264
+ <TableCell>{config.provider}</TableCell>
265
+ <TableCell>{config.model}</TableCell>
266
+ <TableCell>{config.temperature}</TableCell>
267
+ <TableCell>{config.maxTokens}</TableCell>
268
+ <TableCell>
269
+ <Switch
270
+ checked={config.isDefault}
271
+ onCheckedChange={(checked) =>
272
+ handleToggleDefault(config.id, checked)
273
+ }
274
+ />
275
+ </TableCell>
276
+ {/* TODO: Add an edit button or icon in this cell */}
277
+ </TableRow>
278
+ ))}
279
+ </TableBody>
280
+ </Table>
281
+ </CardContent>
282
+ </Card>
283
+
284
+ <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
285
+ <DialogTrigger asChild>
286
+ <Button onClick={() => setIsDialogOpen(true)}>
287
+ <PlusIcon className="mr-2 h-4 w-4" />
288
+ Add Configuration
289
+ </Button>
290
+ </DialogTrigger>
291
+ <DialogContent className="sm:max-w-[475px]">
292
+ <DialogHeader>
293
+ <DialogTitle>Add New Configuration</DialogTitle>
294
+ </DialogHeader>
295
+ <div className="grid max-h-[60vh] gap-4 overflow-y-auto py-4">
296
+ <div className="mt-4">
297
+ <Label>Templates</Label>
298
+ <div className="mt-2 grid grid-cols-2 gap-2">
299
+ {templateButtons}
300
+ </div>
301
+ </div>
302
+ <div className="mt-2 grid grid-cols-4 items-center gap-4">
303
+ <Label htmlFor="name" className="text-right">
304
+ Name
305
+ </Label>
306
+ <Input
307
+ id="name"
308
+ value={newConfig.name || ""}
309
+ onChange={(e) =>
310
+ setNewConfig({ ...newConfig, name: e.target.value })
311
+ }
312
+ className="col-span-3"
313
+ />
314
+ </div>
315
+ <div className="grid grid-cols-4 items-center gap-4">
316
+ <Label htmlFor="provider" className="text-right">
317
+ Provider
318
+ </Label>
319
+ <div className="col-span-3">
320
+ <Select
321
+ value={selectedProvider}
322
+ onValueChange={handleProviderChange}
323
+ >
324
+ <SelectTrigger>
325
+ <SelectValue placeholder="Select provider" />
326
+ </SelectTrigger>
327
+ <SelectContent>
328
+ {Object.keys(modelConfigurations).map((provider) => (
329
+ <SelectItem key={provider} value={provider}>
330
+ {provider}
331
+ </SelectItem>
332
+ ))}
333
+ </SelectContent>
334
+ </Select>
335
+ {selectedProvider === "other" && (
336
+ <Input
337
+ id="customProvider"
338
+ value={customProvider}
339
+ onChange={handleCustomProviderChange}
340
+ placeholder="Enter custom provider"
341
+ className="mt-2"
342
+ />
343
+ )}
344
+ </div>
345
+ </div>
346
+ <div className="grid grid-cols-4 items-center gap-4">
347
+ <Label htmlFor="model" className="text-right">
348
+ Model
349
+ </Label>
350
+ <div className="col-span-3">
351
+ <Select
352
+ value={selectedModel}
353
+ onValueChange={handleModelChange}
354
+ disabled={!selectedProvider}
355
+ >
356
+ <SelectTrigger>
357
+ <SelectValue placeholder="Select model" />
358
+ </SelectTrigger>
359
+ <SelectContent>
360
+ {selectedProvider &&
361
+ Object.keys(
362
+ modelConfigurations[selectedProvider] || {},
363
+ ).map((model) => (
364
+ <SelectItem key={model} value={model}>
365
+ {model}
366
+ </SelectItem>
367
+ ))}
368
+ </SelectContent>
369
+ </Select>
370
+ {selectedModel === "other" && (
371
+ <Input
372
+ id="customModel"
373
+ value={customModel}
374
+ onChange={handleCustomModelChange}
375
+ placeholder="Enter custom model"
376
+ className="mt-2"
377
+ />
378
+ )}
379
+ </div>
380
+ </div>
381
+ {error && (
382
+ <div className="mb-4 mt-2 text-sm text-red-500">{error}</div>
383
+ )}
384
+ <div className="mt-4 flex justify-end">
385
+ <Button onClick={handleCreateConfig}>Create Configuration</Button>
386
+ </div>
387
+ </div>
388
+ </DialogContent>
389
+ </Dialog>
390
+ </div>
391
+ );
392
+ }
workers1/auto3d/CursorLens/src/app/favicon.ico ADDED
workers1/auto3d/CursorLens/src/app/globals.css ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ @layer base {
6
+ :root {
7
+ --background: 0 0% 100%;
8
+ --foreground: 20 14.3% 4.1%;
9
+ --card: 0 0% 100%;
10
+ --card-foreground: 20 14.3% 4.1%;
11
+ --popover: 0 0% 100%;
12
+ --popover-foreground: 20 14.3% 4.1%;
13
+ --primary: 24 9.8% 10%;
14
+ --primary-foreground: 60 9.1% 97.8%;
15
+ --secondary: 60 4.8% 95.9%;
16
+ --secondary-foreground: 24 9.8% 10%;
17
+ --muted: 60 4.8% 95.9%;
18
+ --muted-foreground: 25 5.3% 44.7%;
19
+ --accent: 60 4.8% 95.9%;
20
+ --accent-foreground: 24 9.8% 10%;
21
+ --destructive: 0 84.2% 60.2%;
22
+ --destructive-foreground: 60 9.1% 97.8%;
23
+ --border: 20 5.9% 90%;
24
+ --input: 20 5.9% 90%;
25
+ --ring: 20 14.3% 4.1%;
26
+ --radius: 0.5rem;
27
+ }
28
+
29
+ .dark {
30
+ --background: 0 0% 10%;
31
+ --foreground: 60 9.1% 97.8%;
32
+ --card: 20 14.3% 4.1%;
33
+ --card-foreground: 60 9.1% 97.8%;
34
+ --popover: 20 14.3% 4.1%;
35
+ --popover-foreground: 60 9.1% 97.8%;
36
+ --primary: 60 9.1% 97.8%;
37
+ --primary-foreground: 24 9.8% 10%;
38
+ --secondary: 12 6.5% 15.1%;
39
+ --secondary-foreground: 60 9.1% 97.8%;
40
+ --muted: 12 6.5% 15.1%;
41
+ --muted-foreground: 24 5.4% 63.9%;
42
+ --accent: 12 6.5% 15.1%;
43
+ --accent-foreground: 60 9.1% 97.8%;
44
+ --destructive: 0 62.8% 30.6%;
45
+ --destructive-foreground: 60 9.1% 97.8%;
46
+ --border: 12 6.5% 15.1%;
47
+ --input: 12 6.5% 15.1%;
48
+ --ring: 24 5.7% 82.9%;
49
+ }
50
+ }
51
+
52
+ @layer base {
53
+ * {
54
+ @apply border-border;
55
+ }
56
+ body {
57
+ @apply bg-background text-foreground;
58
+ }
59
+ }
60
+
61
+ :root {
62
+ --chart-1: 12 76% 61%;
63
+ --chart-2: 173 58% 39%;
64
+ --chart-3: 197 37% 24%;
65
+ --chart-4: 43 74% 66%;
66
+ --chart-5: 27 87% 67%;
67
+ }
68
+
69
+ .dark {
70
+ --chart-1: 220 70% 50%;
71
+ --chart-2: 160 60% 45%;
72
+ --chart-3: 30 80% 55%;
73
+ --chart-4: 280 65% 60%;
74
+ --chart-5: 340 75% 55%;
75
+ }
workers1/auto3d/CursorLens/src/app/layout.tsx ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Metadata } from "next";
2
+ import { Inter } from "next/font/google";
3
+ import "./globals.css";
4
+ import NavBar from "@/components/NavBar";
5
+ import Link from "next/link";
6
+ import { ThemeProvider } from "@/components/theme-provider";
7
+ import { Toaster } from "@/components/ui/sonner";
8
+
9
+ const inter = Inter({ subsets: ["latin"] });
10
+
11
+ export const metadata: Metadata = {
12
+ title: "Cursor Lens",
13
+ description: "Analytics and Routing for Cursor IDE",
14
+ metadataBase: new URL("https://cursorlens.com"),
15
+ };
16
+
17
+ export default function RootLayout({
18
+ children,
19
+ }: Readonly<{
20
+ children: React.ReactNode;
21
+ }>) {
22
+ return (
23
+ <html lang="en" suppressHydrationWarning>
24
+ <body className={`${inter.className} bg-background text-foreground`}>
25
+ <ThemeProvider
26
+ attribute="class"
27
+ defaultTheme="system"
28
+ enableSystem
29
+ disableTransitionOnChange
30
+ >
31
+ <div className="flex min-h-screen flex-col">
32
+ <header className="sticky top-0 z-50 bg-primary px-6 py-4 text-primary-foreground">
33
+ <div className="flex items-center justify-between">
34
+ <Link href="/" className="flex items-center space-x-2">
35
+ <svg
36
+ xmlns="http://www.w3.org/2000/svg"
37
+ width="24"
38
+ height="24"
39
+ viewBox="0 0 24 24"
40
+ fill="none"
41
+ stroke="currentColor"
42
+ strokeWidth="2"
43
+ strokeLinecap="round"
44
+ strokeLinejoin="round"
45
+ className="lucide lucide-mouse-pointer-2"
46
+ style={{ transform: "scaleX(-1)" }}
47
+ >
48
+ <path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z" />
49
+ </svg>
50
+ <span className="text-lg font-bold">Cursor Lens</span>
51
+ </Link>
52
+ <NavBar />
53
+ </div>
54
+ </header>
55
+ <main className="flex-grow">{children}</main>
56
+ </div>
57
+ </ThemeProvider>
58
+ <Toaster richColors closeButton />
59
+ </body>
60
+ </html>
61
+ );
62
+ }
workers1/auto3d/CursorLens/src/app/logs/page.tsx ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useEffect, useCallback, useMemo } from "react";
4
+ import { format } from "date-fns";
5
+ import { Calendar as CalendarIcon } from "lucide-react";
6
+ import { RefreshCw } from "lucide-react";
7
+ import LogsList from "@/components/LogsList";
8
+ import LogDetails from "@/components/LogDetails";
9
+ import { getLogs, getStats } from "@/app/actions";
10
+ import { Skeleton } from "@/components/ui/skeleton";
11
+ import {
12
+ Select,
13
+ SelectContent,
14
+ SelectItem,
15
+ SelectTrigger,
16
+ SelectValue,
17
+ } from "@/components/ui/select";
18
+ import { Button } from "@/components/ui/button";
19
+ import { Calendar } from "@/components/ui/calendar";
20
+ import {
21
+ Popover,
22
+ PopoverContent,
23
+ PopoverTrigger,
24
+ } from "@/components/ui/popover";
25
+ import { cn } from "@/lib/utils";
26
+ import { debounce } from "lodash";
27
+
28
+ interface Stats {
29
+ totalLogs: number;
30
+ totalTokens: number;
31
+ perModelStats: {
32
+ [key: string]: {
33
+ logs: number;
34
+ tokens: number;
35
+ };
36
+ };
37
+ }
38
+
39
+ export default function Logs() {
40
+ const [logs, setLogs] = useState<any[]>([]);
41
+ const [stats, setStats] = useState<Stats | null>(null);
42
+ const [selectedLogId, setSelectedLogId] = useState<string | undefined>(
43
+ undefined,
44
+ );
45
+ const [error, setError] = useState<string | null>(null);
46
+ const [provider, setProvider] = useState<string>("all");
47
+ const [startDate, setStartDate] = useState<Date | undefined>(undefined);
48
+ const [endDate, setEndDate] = useState<Date | undefined>(undefined);
49
+ const [isLoading, setIsLoading] = useState(true);
50
+
51
+ const handleLogSelect = (logId: string) => {
52
+ setSelectedLogId(logId);
53
+ };
54
+
55
+ const fetchData = useCallback(async () => {
56
+ setIsLoading(true);
57
+ setError(null);
58
+
59
+ try {
60
+ const [fetchedLogs, fetchedStats] = await Promise.all([
61
+ getLogs({
62
+ provider,
63
+ startDate: startDate ? format(startDate, "yyyy-MM-dd") : undefined,
64
+ endDate: endDate ? format(endDate, "yyyy-MM-dd") : undefined,
65
+ }),
66
+ getStats(),
67
+ ]);
68
+
69
+ setLogs(fetchedLogs);
70
+ setStats(fetchedStats);
71
+ } catch (error) {
72
+ setError("Error loading data");
73
+ } finally {
74
+ setIsLoading(false);
75
+ }
76
+ }, [provider, startDate, endDate]);
77
+
78
+ const debouncedFetchData = useMemo(
79
+ () => debounce(fetchData, 500),
80
+ [fetchData],
81
+ );
82
+
83
+ useEffect(() => {
84
+ debouncedFetchData();
85
+ // Cleanup function to cancel any pending debounced calls
86
+ return () => debouncedFetchData.cancel();
87
+ }, [debouncedFetchData]);
88
+
89
+ const handleRefresh = useCallback(() => {
90
+ fetchData();
91
+ }, [fetchData]);
92
+
93
+ const LoadingSkeleton = () => (
94
+ <>
95
+ {[...Array(5)].map((_, i) => (
96
+ <div key={i} className="flex items-center space-x-4 p-4">
97
+ <Skeleton className="h-12 w-12 rounded-full" />
98
+ <div className="space-y-2">
99
+ <Skeleton className="h-4 w-[250px]" />
100
+ <Skeleton className="h-4 w-[200px]" />
101
+ </div>
102
+ </div>
103
+ ))}
104
+ </>
105
+ );
106
+
107
+ return (
108
+ <div className="flex h-screen flex-col">
109
+ <div className="flex flex-grow">
110
+ <div className="flex w-1/3 flex-col border-r">
111
+ <div className="sticky top-0 z-10 border-b p-4">
112
+ <div className="flex items-center justify-between">
113
+ <h2 className="text-xl font-bold">Logs List</h2>
114
+ <Button
115
+ onClick={handleRefresh}
116
+ variant="outline"
117
+ size="icon"
118
+ disabled={isLoading}
119
+ >
120
+ <RefreshCw
121
+ className={cn("size-4", isLoading && "animate-spin")}
122
+ />
123
+ </Button>
124
+ </div>
125
+ </div>
126
+ <div className="space-y-2 p-4">
127
+ <Select onValueChange={(value) => setProvider(value)}>
128
+ <SelectTrigger>
129
+ <SelectValue placeholder="Select provider" />
130
+ </SelectTrigger>
131
+ <SelectContent>
132
+ <SelectItem value="all">All Providers</SelectItem>
133
+ <SelectItem value="openai">OpenAI</SelectItem>
134
+ <SelectItem value="anthropic">Anthropic</SelectItem>
135
+ <SelectItem value="cohere">Cohere</SelectItem>
136
+ <SelectItem value="mistral">Mistral</SelectItem>
137
+ <SelectItem value="groq">Groq</SelectItem>
138
+ <SelectItem value="ollama">Ollama</SelectItem>
139
+ </SelectContent>
140
+ </Select>
141
+ <Popover>
142
+ <PopoverTrigger asChild>
143
+ <Button
144
+ variant={"outline"}
145
+ className={cn(
146
+ "w-full justify-start text-left font-normal",
147
+ !startDate && "text-muted-foreground",
148
+ )}
149
+ >
150
+ <CalendarIcon className="mr-2 h-4 w-4" />
151
+ {startDate ? (
152
+ format(startDate, "PPP")
153
+ ) : (
154
+ <span>Start Date</span>
155
+ )}
156
+ </Button>
157
+ </PopoverTrigger>
158
+ <PopoverContent className="w-auto p-0">
159
+ <Calendar
160
+ mode="single"
161
+ selected={startDate}
162
+ onSelect={setStartDate}
163
+ initialFocus
164
+ />
165
+ </PopoverContent>
166
+ </Popover>
167
+ <Popover>
168
+ <PopoverTrigger asChild>
169
+ <Button
170
+ variant={"outline"}
171
+ className={cn(
172
+ "w-full justify-start text-left font-normal",
173
+ !endDate && "text-muted-foreground",
174
+ )}
175
+ >
176
+ <CalendarIcon className="mr-2 h-4 w-4" />
177
+ {endDate ? format(endDate, "PPP") : <span>End Date</span>}
178
+ </Button>
179
+ </PopoverTrigger>
180
+ <PopoverContent className="w-auto p-0">
181
+ <Calendar
182
+ mode="single"
183
+ selected={endDate}
184
+ onSelect={setEndDate}
185
+ initialFocus
186
+ />
187
+ </PopoverContent>
188
+ </Popover>
189
+ </div>
190
+ <div className="flex-grow overflow-y-auto">
191
+ {isLoading ? (
192
+ <LoadingSkeleton />
193
+ ) : error ? (
194
+ <p className="p-4">{error}</p>
195
+ ) : logs.length > 0 ? (
196
+ <LogsList
197
+ logs={logs}
198
+ onLogSelect={handleLogSelect}
199
+ selectedLogId={selectedLogId}
200
+ />
201
+ ) : (
202
+ <p className="p-4">No logs found.</p>
203
+ )}
204
+ </div>
205
+ </div>
206
+ <div className="flex w-2/3 flex-col">
207
+ <h2 className="sticky top-0 z-10 border-b p-4 text-xl font-bold">
208
+ Log Details
209
+ </h2>
210
+ <div className="relative flex-grow overflow-y-auto">
211
+ <div className="absolute inset-0">
212
+ {selectedLogId ? (
213
+ <LogDetails logId={selectedLogId} />
214
+ ) : (
215
+ <p className="p-4">Select a log to view details.</p>
216
+ )}
217
+ </div>
218
+ </div>
219
+ </div>
220
+ </div>
221
+ </div>
222
+ );
223
+ }
workers1/auto3d/CursorLens/src/app/opengraph-image.png ADDED
workers1/auto3d/CursorLens/src/app/page.tsx ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState, useEffect } from "react";
4
+ import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
5
+ import {
6
+ Select,
7
+ SelectContent,
8
+ SelectItem,
9
+ SelectTrigger,
10
+ SelectValue,
11
+ } from "@/components/ui/select";
12
+ import LogsList from "../components/LogsList";
13
+ import Link from "next/link";
14
+ import { useRouter } from "next/navigation";
15
+ import { Label } from "@/components/ui/label";
16
+ import { ArrowRight } from "lucide-react";
17
+ import {
18
+ getLogs,
19
+ getStats,
20
+ getConfigurations,
21
+ updateDefaultConfiguration,
22
+ createConfiguration,
23
+ } from "./actions";
24
+ import { Skeleton } from "@/components/ui/skeleton";
25
+
26
+ interface Log {
27
+ id: string;
28
+ method: string;
29
+ url: string;
30
+ headers: string;
31
+ body: string;
32
+ response: string;
33
+ timestamp: Date;
34
+ metadata: any;
35
+ }
36
+
37
+ interface Stats {
38
+ totalLogs: number;
39
+ totalTokens: number;
40
+ }
41
+
42
+ interface AIConfiguration {
43
+ id: string;
44
+ name: string;
45
+ provider: string;
46
+ model: string;
47
+ temperature: number | null;
48
+ maxTokens: number | null;
49
+ topP: number | null;
50
+ frequencyPenalty: number | null;
51
+ presencePenalty: number | null;
52
+ isDefault: boolean;
53
+ createdAt: Date;
54
+ updatedAt: Date;
55
+ }
56
+
57
+ export default function Home() {
58
+ const [logs, setLogs] = useState<Log[]>([]);
59
+ const [stats, setStats] = useState<Stats>({ totalLogs: 0, totalTokens: 0 });
60
+ const [aiConfigurations, setAIConfigurations] = useState<AIConfiguration[]>(
61
+ [],
62
+ );
63
+ const [selectedConfig, setSelectedConfig] = useState<string>("");
64
+ const [loading, setLoading] = useState(true);
65
+ const [error, setError] = useState<string | null>(null);
66
+ const router = useRouter();
67
+ const [newConfigName, setNewConfigName] = useState("");
68
+ const [newConfigModel, setNewConfigModel] = useState("");
69
+ const [newConfigProvider, setNewConfigProvider] = useState("");
70
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
71
+
72
+ useEffect(() => {
73
+ const fetchData = async () => {
74
+ try {
75
+ const [logsData, statsData, configData] = await Promise.all([
76
+ getLogs(),
77
+ getStats(),
78
+ getConfigurations(),
79
+ ]);
80
+
81
+ setLogs(logsData as Log[]); // Type assertion
82
+ setStats(statsData);
83
+ setAIConfigurations(configData as AIConfiguration[]); // Type assertion
84
+ const defaultConfig = configData.find((config) => config.isDefault);
85
+ setSelectedConfig(defaultConfig ? defaultConfig.name : "");
86
+
87
+ setLoading(false);
88
+ } catch (error) {
89
+ console.error("Error fetching data:", error);
90
+ setError("Error loading data. Please try again later.");
91
+ setLoading(false);
92
+ }
93
+ };
94
+ fetchData();
95
+ }, []);
96
+
97
+ const handleConfigChange = async (configName: string) => {
98
+ setSelectedConfig(configName);
99
+ try {
100
+ await updateDefaultConfiguration(configName);
101
+ router.refresh();
102
+ } catch (error) {
103
+ console.error("Error updating configuration:", error);
104
+ setError("Error updating configuration");
105
+ }
106
+ };
107
+
108
+ const handleCreateConfig = async () => {
109
+ if (!newConfigName || !newConfigModel || !newConfigProvider) {
110
+ setError(
111
+ "Please provide name, model, and provider for the new configuration",
112
+ );
113
+ return;
114
+ }
115
+
116
+ try {
117
+ await createConfiguration({
118
+ name: newConfigName,
119
+ model: newConfigModel,
120
+ provider: newConfigProvider,
121
+ isDefault: false,
122
+ });
123
+
124
+ const configData = await getConfigurations();
125
+ setAIConfigurations(configData as AIConfiguration[]); // Type assertion
126
+
127
+ setNewConfigName("");
128
+ setNewConfigModel("");
129
+ setNewConfigProvider("");
130
+
131
+ setError(null);
132
+ setIsDialogOpen(false);
133
+ } catch (error) {
134
+ console.error("Error creating configuration:", error);
135
+ setError("Error creating configuration");
136
+ }
137
+ };
138
+
139
+ const handleLogSelect = (logId: string) => {
140
+ router.push(`/logs?selectedLogId=${logId}`);
141
+ };
142
+
143
+ if (loading)
144
+ return (
145
+ <div className="mx-auto flex w-full max-w-4xl flex-col items-center justify-start space-y-8 p-12">
146
+ <Skeleton className="mb-8 h-12 w-64" />
147
+ <div className="mb-8 grid w-full grid-cols-1 gap-6 md:grid-cols-2">
148
+ <Skeleton className="h-32 w-full" />
149
+ <Skeleton className="h-32 w-full" />
150
+ </div>
151
+ <Skeleton className="mb-8 h-64 w-full" />
152
+ <Skeleton className="h-96 w-full" />
153
+ </div>
154
+ );
155
+ if (error) return <div>Error: {error}</div>;
156
+
157
+ return (
158
+ <main className="flex min-h-screen flex-col items-center justify-start p-12">
159
+ <svg
160
+ xmlns="http://www.w3.org/2000/svg"
161
+ width="64"
162
+ height="64"
163
+ viewBox="0 0 24 24"
164
+ fill="currentColor"
165
+ stroke="currentColor"
166
+ strokeWidth="2"
167
+ strokeLinecap="round"
168
+ strokeLinejoin="round"
169
+ className="lucide lucide-mouse-pointer-2 mb-4"
170
+ style={{
171
+ transform: "scaleX(-1)",
172
+ transition: "filter 0.1s ease-out",
173
+ }}
174
+ onMouseMove={(e) => {
175
+ const rect = e.currentTarget.getBoundingClientRect();
176
+ const x = e.clientX - rect.left - rect.width / 2;
177
+ const y = e.clientY - rect.top - rect.height / 2;
178
+ e.currentTarget.style.filter = `drop-shadow(${x / 10}px ${
179
+ y / 10
180
+ }px 4px rgba(0, 0, 0, 0.5))`;
181
+ }}
182
+ onMouseEnter={(e) => {
183
+ e.currentTarget.style.filter =
184
+ "drop-shadow(0px 0px 4px rgba(0, 0, 0, 0.5))";
185
+ }}
186
+ onMouseLeave={(e) => {
187
+ e.currentTarget.style.filter = "none";
188
+ }}
189
+ >
190
+ <path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z" />
191
+ </svg>
192
+
193
+ <div className="mb-8 grid w-full max-w-4xl grid-cols-1 gap-6 md:grid-cols-2">
194
+ <Card>
195
+ <CardHeader>
196
+ <CardTitle>Total Logs</CardTitle>
197
+ </CardHeader>
198
+ <CardContent>
199
+ <p className="text-3xl font-semibold">{stats.totalLogs}</p>
200
+ </CardContent>
201
+ </Card>
202
+ <Card>
203
+ <CardHeader>
204
+ <CardTitle>Total Tokens Used</CardTitle>
205
+ </CardHeader>
206
+ <CardContent>
207
+ <p className="text-3xl font-semibold">
208
+ {stats.totalTokens.toLocaleString()}
209
+ </p>
210
+ </CardContent>
211
+ </Card>
212
+ </div>
213
+
214
+ <Card className="mb-8 w-full max-w-4xl">
215
+ <CardHeader>
216
+ <CardTitle>AI Configuration</CardTitle>
217
+ </CardHeader>
218
+ <CardContent>
219
+ <div className="mb-4 flex items-center space-x-4">
220
+ <Label>Default model:</Label>
221
+ <Select onValueChange={handleConfigChange} value={selectedConfig}>
222
+ <SelectTrigger className="w-64">
223
+ <SelectValue placeholder="Select a configuration" />
224
+ </SelectTrigger>
225
+ <SelectContent>
226
+ {aiConfigurations.map((config) => (
227
+ <SelectItem key={config.name} value={config.name}>
228
+ {config.name} ({config.model})
229
+ </SelectItem>
230
+ ))}
231
+ </SelectContent>
232
+ </Select>
233
+ </div>
234
+ <Link
235
+ href="/configurations"
236
+ className="inline-flex h-10 items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
237
+ >
238
+ Manage Configurations
239
+ <ArrowRight className="ml-2 h-4 w-4" />
240
+ </Link>
241
+ </CardContent>
242
+ </Card>
243
+
244
+ <Card className="w-full max-w-4xl">
245
+ <CardHeader>
246
+ <CardTitle>Recent Logs</CardTitle>
247
+ </CardHeader>
248
+ <CardContent className="flex flex-col">
249
+ <div className="mb-4 max-h-[300px] flex-grow overflow-y-auto">
250
+ <LogsList
251
+ logs={logs}
252
+ onLogSelect={handleLogSelect}
253
+ selectedLogId={undefined}
254
+ />
255
+ </div>
256
+ <Link
257
+ href="/logs"
258
+ className="inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
259
+ >
260
+ View all logs
261
+ </Link>
262
+ </CardContent>
263
+ </Card>
264
+ </main>
265
+ );
266
+ }