galaxy-code 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +149 -600
  2. package/dist/app.js +1 -1
  3. package/dist/cli.min.js +589 -0
  4. package/package.json +12 -10
  5. package/dist/node_modules/@workspace/agent-core/connections/claude.d.ts +0 -72
  6. package/dist/node_modules/@workspace/agent-core/connections/claude.d.ts.map +0 -1
  7. package/dist/node_modules/@workspace/agent-core/connections/claude.js +0 -270
  8. package/dist/node_modules/@workspace/agent-core/connections/claude.js.map +0 -1
  9. package/dist/node_modules/@workspace/agent-core/connections/gemini.d.ts +0 -41
  10. package/dist/node_modules/@workspace/agent-core/connections/gemini.d.ts.map +0 -1
  11. package/dist/node_modules/@workspace/agent-core/connections/gemini.js +0 -203
  12. package/dist/node_modules/@workspace/agent-core/connections/gemini.js.map +0 -1
  13. package/dist/node_modules/@workspace/agent-core/connections/index.d.ts +0 -12
  14. package/dist/node_modules/@workspace/agent-core/connections/index.d.ts.map +0 -1
  15. package/dist/node_modules/@workspace/agent-core/connections/index.js +0 -12
  16. package/dist/node_modules/@workspace/agent-core/connections/index.js.map +0 -1
  17. package/dist/node_modules/@workspace/agent-core/connections/ollama.d.ts +0 -38
  18. package/dist/node_modules/@workspace/agent-core/connections/ollama.d.ts.map +0 -1
  19. package/dist/node_modules/@workspace/agent-core/connections/ollama.js +0 -64
  20. package/dist/node_modules/@workspace/agent-core/connections/ollama.js.map +0 -1
  21. package/dist/node_modules/@workspace/agent-core/connections/types.d.ts +0 -23
  22. package/dist/node_modules/@workspace/agent-core/connections/types.d.ts.map +0 -1
  23. package/dist/node_modules/@workspace/agent-core/connections/types.js +0 -8
  24. package/dist/node_modules/@workspace/agent-core/connections/types.js.map +0 -1
  25. package/dist/node_modules/@workspace/agent-core/index.d.ts +0 -13
  26. package/dist/node_modules/@workspace/agent-core/index.d.ts.map +0 -1
  27. package/dist/node_modules/@workspace/agent-core/index.js +0 -22
  28. package/dist/node_modules/@workspace/agent-core/index.js.map +0 -1
  29. package/dist/node_modules/@workspace/agent-core/package.json +0 -53
  30. package/dist/node_modules/@workspace/agent-core/prompts/ba-it-analyzer.d.ts +0 -2
  31. package/dist/node_modules/@workspace/agent-core/prompts/ba-it-analyzer.d.ts.map +0 -1
  32. package/dist/node_modules/@workspace/agent-core/prompts/ba-it-analyzer.js +0 -144
  33. package/dist/node_modules/@workspace/agent-core/prompts/ba-it-analyzer.js.map +0 -1
  34. package/dist/node_modules/@workspace/agent-core/prompts/index.d.ts +0 -12
  35. package/dist/node_modules/@workspace/agent-core/prompts/index.d.ts.map +0 -1
  36. package/dist/node_modules/@workspace/agent-core/prompts/index.js +0 -12
  37. package/dist/node_modules/@workspace/agent-core/prompts/index.js.map +0 -1
  38. package/dist/node_modules/@workspace/agent-core/prompts/orchestrator.d.ts +0 -9
  39. package/dist/node_modules/@workspace/agent-core/prompts/orchestrator.d.ts.map +0 -1
  40. package/dist/node_modules/@workspace/agent-core/prompts/orchestrator.js +0 -89
  41. package/dist/node_modules/@workspace/agent-core/prompts/orchestrator.js.map +0 -1
  42. package/dist/node_modules/@workspace/agent-core/prompts/planning-agent.d.ts +0 -9
  43. package/dist/node_modules/@workspace/agent-core/prompts/planning-agent.d.ts.map +0 -1
  44. package/dist/node_modules/@workspace/agent-core/prompts/planning-agent.js +0 -196
  45. package/dist/node_modules/@workspace/agent-core/prompts/planning-agent.js.map +0 -1
  46. package/dist/node_modules/@workspace/agent-core/prompts/universal-agent.d.ts +0 -8
  47. package/dist/node_modules/@workspace/agent-core/prompts/universal-agent.d.ts.map +0 -1
  48. package/dist/node_modules/@workspace/agent-core/prompts/universal-agent.js +0 -112
  49. package/dist/node_modules/@workspace/agent-core/prompts/universal-agent.js.map +0 -1
  50. package/dist/node_modules/@workspace/agent-core/providers/agent-selector.d.ts +0 -30
  51. package/dist/node_modules/@workspace/agent-core/providers/agent-selector.d.ts.map +0 -1
  52. package/dist/node_modules/@workspace/agent-core/providers/agent-selector.js +0 -76
  53. package/dist/node_modules/@workspace/agent-core/providers/agent-selector.js.map +0 -1
  54. package/dist/node_modules/@workspace/agent-core/providers/claude-agent.d.ts +0 -30
  55. package/dist/node_modules/@workspace/agent-core/providers/claude-agent.d.ts.map +0 -1
  56. package/dist/node_modules/@workspace/agent-core/providers/claude-agent.js +0 -107
  57. package/dist/node_modules/@workspace/agent-core/providers/claude-agent.js.map +0 -1
  58. package/dist/node_modules/@workspace/agent-core/providers/gemini-agent.d.ts +0 -37
  59. package/dist/node_modules/@workspace/agent-core/providers/gemini-agent.d.ts.map +0 -1
  60. package/dist/node_modules/@workspace/agent-core/providers/gemini-agent.js +0 -144
  61. package/dist/node_modules/@workspace/agent-core/providers/gemini-agent.js.map +0 -1
  62. package/dist/node_modules/@workspace/agent-core/providers/index.d.ts +0 -13
  63. package/dist/node_modules/@workspace/agent-core/providers/index.d.ts.map +0 -1
  64. package/dist/node_modules/@workspace/agent-core/providers/index.js +0 -13
  65. package/dist/node_modules/@workspace/agent-core/providers/index.js.map +0 -1
  66. package/dist/node_modules/@workspace/agent-core/providers/ollama-agent.d.ts +0 -54
  67. package/dist/node_modules/@workspace/agent-core/providers/ollama-agent.d.ts.map +0 -1
  68. package/dist/node_modules/@workspace/agent-core/providers/ollama-agent.js +0 -247
  69. package/dist/node_modules/@workspace/agent-core/providers/ollama-agent.js.map +0 -1
  70. package/dist/node_modules/@workspace/agent-core/providers/orchestrator.d.ts +0 -17
  71. package/dist/node_modules/@workspace/agent-core/providers/orchestrator.d.ts.map +0 -1
  72. package/dist/node_modules/@workspace/agent-core/providers/orchestrator.js +0 -62
  73. package/dist/node_modules/@workspace/agent-core/providers/orchestrator.js.map +0 -1
  74. package/dist/node_modules/@workspace/agent-core/tools/ba-it-analyzer.d.ts +0 -67
  75. package/dist/node_modules/@workspace/agent-core/tools/ba-it-analyzer.d.ts.map +0 -1
  76. package/dist/node_modules/@workspace/agent-core/tools/ba-it-analyzer.js +0 -81
  77. package/dist/node_modules/@workspace/agent-core/tools/ba-it-analyzer.js.map +0 -1
  78. package/dist/node_modules/@workspace/agent-core/tools/code-generate-agent.d.ts +0 -52
  79. package/dist/node_modules/@workspace/agent-core/tools/code-generate-agent.d.ts.map +0 -1
  80. package/dist/node_modules/@workspace/agent-core/tools/code-generate-agent.js +0 -150
  81. package/dist/node_modules/@workspace/agent-core/tools/code-generate-agent.js.map +0 -1
  82. package/dist/node_modules/@workspace/agent-core/tools/command-runner.d.ts +0 -15
  83. package/dist/node_modules/@workspace/agent-core/tools/command-runner.d.ts.map +0 -1
  84. package/dist/node_modules/@workspace/agent-core/tools/command-runner.js +0 -121
  85. package/dist/node_modules/@workspace/agent-core/tools/command-runner.js.map +0 -1
  86. package/dist/node_modules/@workspace/agent-core/tools/document-parser.d.ts +0 -12
  87. package/dist/node_modules/@workspace/agent-core/tools/document-parser.d.ts.map +0 -1
  88. package/dist/node_modules/@workspace/agent-core/tools/document-parser.js +0 -84
  89. package/dist/node_modules/@workspace/agent-core/tools/document-parser.js.map +0 -1
  90. package/dist/node_modules/@workspace/agent-core/tools/file-operations.d.ts +0 -18
  91. package/dist/node_modules/@workspace/agent-core/tools/file-operations.d.ts.map +0 -1
  92. package/dist/node_modules/@workspace/agent-core/tools/file-operations.js +0 -126
  93. package/dist/node_modules/@workspace/agent-core/tools/file-operations.js.map +0 -1
  94. package/dist/node_modules/@workspace/agent-core/tools/galaxy-ui-integration.d.ts +0 -95
  95. package/dist/node_modules/@workspace/agent-core/tools/galaxy-ui-integration.d.ts.map +0 -1
  96. package/dist/node_modules/@workspace/agent-core/tools/galaxy-ui-integration.js +0 -245
  97. package/dist/node_modules/@workspace/agent-core/tools/galaxy-ui-integration.js.map +0 -1
  98. package/dist/node_modules/@workspace/agent-core/tools/git-operations.d.ts +0 -12
  99. package/dist/node_modules/@workspace/agent-core/tools/git-operations.d.ts.map +0 -1
  100. package/dist/node_modules/@workspace/agent-core/tools/git-operations.js +0 -115
  101. package/dist/node_modules/@workspace/agent-core/tools/git-operations.js.map +0 -1
  102. package/dist/node_modules/@workspace/agent-core/tools/index.d.ts +0 -11
  103. package/dist/node_modules/@workspace/agent-core/tools/index.d.ts.map +0 -1
  104. package/dist/node_modules/@workspace/agent-core/tools/index.js +0 -11
  105. package/dist/node_modules/@workspace/agent-core/tools/index.js.map +0 -1
  106. package/dist/node_modules/@workspace/agent-core/tools/planning-agent.d.ts +0 -30
  107. package/dist/node_modules/@workspace/agent-core/tools/planning-agent.d.ts.map +0 -1
  108. package/dist/node_modules/@workspace/agent-core/tools/planning-agent.js +0 -125
  109. package/dist/node_modules/@workspace/agent-core/tools/planning-agent.js.map +0 -1
  110. package/dist/node_modules/@workspace/agent-core/tools/progress-reporter.d.ts +0 -20
  111. package/dist/node_modules/@workspace/agent-core/tools/progress-reporter.d.ts.map +0 -1
  112. package/dist/node_modules/@workspace/agent-core/tools/progress-reporter.js +0 -46
  113. package/dist/node_modules/@workspace/agent-core/tools/progress-reporter.js.map +0 -1
  114. package/dist/node_modules/@workspace/agent-core/tools/registry.d.ts +0 -22
  115. package/dist/node_modules/@workspace/agent-core/tools/registry.d.ts.map +0 -1
  116. package/dist/node_modules/@workspace/agent-core/tools/registry.js +0 -651
  117. package/dist/node_modules/@workspace/agent-core/tools/registry.js.map +0 -1
  118. package/dist/node_modules/@workspace/agent-core/tools/tool-event-emitter.d.ts +0 -25
  119. package/dist/node_modules/@workspace/agent-core/tools/tool-event-emitter.d.ts.map +0 -1
  120. package/dist/node_modules/@workspace/agent-core/tools/tool-event-emitter.js +0 -26
  121. package/dist/node_modules/@workspace/agent-core/tools/tool-event-emitter.js.map +0 -1
  122. package/dist/node_modules/@workspace/agent-core/tools/types.d.ts +0 -32
  123. package/dist/node_modules/@workspace/agent-core/tools/types.d.ts.map +0 -1
  124. package/dist/node_modules/@workspace/agent-core/tools/types.js +0 -2
  125. package/dist/node_modules/@workspace/agent-core/tools/types.js.map +0 -1
  126. package/dist/node_modules/@workspace/agent-core/types.d.ts +0 -40
  127. package/dist/node_modules/@workspace/agent-core/types.d.ts.map +0 -1
  128. package/dist/node_modules/@workspace/agent-core/types.js +0 -9
  129. package/dist/node_modules/@workspace/agent-core/types.js.map +0 -1
  130. package/dist/node_modules/@workspace/agent-core/utils/config-manager.d.ts +0 -103
  131. package/dist/node_modules/@workspace/agent-core/utils/config-manager.d.ts.map +0 -1
  132. package/dist/node_modules/@workspace/agent-core/utils/config-manager.js +0 -307
  133. package/dist/node_modules/@workspace/agent-core/utils/config-manager.js.map +0 -1
  134. package/dist/node_modules/@workspace/agent-core/utils/devtools.d.ts +0 -22
  135. package/dist/node_modules/@workspace/agent-core/utils/devtools.d.ts.map +0 -1
  136. package/dist/node_modules/@workspace/agent-core/utils/devtools.js +0 -62
  137. package/dist/node_modules/@workspace/agent-core/utils/devtools.js.map +0 -1
  138. package/dist/node_modules/@workspace/agent-core/utils/message-formatters.d.ts +0 -33
  139. package/dist/node_modules/@workspace/agent-core/utils/message-formatters.d.ts.map +0 -1
  140. package/dist/node_modules/@workspace/agent-core/utils/message-formatters.js +0 -591
  141. package/dist/node_modules/@workspace/agent-core/utils/message-formatters.js.map +0 -1
  142. package/dist/node_modules/@workspace/agent-core/utils/progress-tracker.d.ts +0 -60
  143. package/dist/node_modules/@workspace/agent-core/utils/progress-tracker.d.ts.map +0 -1
  144. package/dist/node_modules/@workspace/agent-core/utils/progress-tracker.js +0 -204
  145. package/dist/node_modules/@workspace/agent-core/utils/progress-tracker.js.map +0 -1
package/package.json CHANGED
@@ -1,14 +1,10 @@
1
1
  {
2
2
  "name": "galaxy-code",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "license": "MIT",
5
5
  "description": "Galaxy Code - AI-powered coding assistant with MCP integration",
6
6
  "author": "Galaxy Agent <galaxy.ai.dev@gmail.com> (https://github.com/galaxy-agent)",
7
- "homepage": "https://github.com/buikevin/galaxy-code#readme",
8
- "repository": {
9
- "type": "git",
10
- "url": "https://github.com/buikevin/galaxy-code.git"
11
- },
7
+ "homepage": "https://galaxy-code-cli.vercel.app",
12
8
  "bugs": {
13
9
  "url": "https://github.com/buikevin/galaxy-code/issues"
14
10
  },
@@ -22,22 +18,24 @@
22
18
  "galaxy"
23
19
  ],
24
20
  "bin": {
25
- "galaxy-code": "./dist/cli.js"
21
+ "galaxy-code": "./dist/cli.min.js"
26
22
  },
27
23
  "type": "module",
28
24
  "engines": {
29
25
  "node": ">=18.14.1"
30
26
  },
31
27
  "scripts": {
32
- "build": "tsc",
28
+ "build": "tsc && node scripts/build-minified.js",
29
+ "build:tsc": "tsc",
30
+ "build:min": "node scripts/build-minified.js",
33
31
  "build:bundle": "node scripts/build-bundle.js",
34
32
  "dev": "tsc --watch",
35
33
  "test": "prettier --check . && xo && ava",
36
34
  "docs:dev": "cd docs && astro dev",
37
35
  "docs:build": "cd docs && astro build",
38
36
  "devtools": "react-devtools",
39
- "debug": "npm run build && NODE_ENV=development node dist/cli.js --dev",
40
- "prepublish": "npm run build:bundle",
37
+ "debug": "npm run build && NODE_ENV=development node dist/cli.min.js --dev",
38
+ "prepublish": "npm run build",
41
39
  "publish:npm": "node scripts/publish-npm.js"
42
40
  },
43
41
  "files": [
@@ -66,6 +64,8 @@
66
64
  },
67
65
  "devDependencies": {
68
66
  "@astrojs/starlight": "0.36.0",
67
+ "@rollup/plugin-commonjs": "^29.0.0",
68
+ "@rollup/plugin-node-resolve": "^16.0.3",
69
69
  "@sindresorhus/tsconfig": "^3.0.1",
70
70
  "@types/react": "^18.0.32",
71
71
  "@types/semver": "^7.5.6",
@@ -73,6 +73,7 @@
73
73
  "astro": "5.14.5",
74
74
  "ava": "^5.2.0",
75
75
  "chalk": "^5.2.0",
76
+ "esbuild": "^0.27.0",
76
77
  "eslint-config-xo-react": "^0.27.0",
77
78
  "eslint-plugin-react": "^7.32.2",
78
79
  "eslint-plugin-react-hooks": "^4.6.0",
@@ -80,6 +81,7 @@
80
81
  "prettier": "^2.8.7",
81
82
  "react-devtools": "^7.0.0",
82
83
  "react-devtools-core": "^7.0.0",
84
+ "rollup": "^4.53.3",
83
85
  "ts-node": "^10.9.1",
84
86
  "typescript": "^5.0.3",
85
87
  "xo": "^0.53.1"
@@ -1,72 +0,0 @@
1
- /**
2
- * @author Bùi Trọng Hiếu
3
- * @email kevinbui210191@gmail.com
4
- * @create 2024-10-13
5
- * @modify 2024-10-13
6
- * @desc Claude API connection using Anthropic SDK
7
- */
8
- import Anthropic from '@anthropic-ai/sdk';
9
- import type { AgentConfig } from '../utils/config-manager.js';
10
- import type { MessageCallback } from './types.js';
11
- export type ClaudeModelId = 'claude-3-5-sonnet-20241022' | 'claude-3-5-haiku-20241022' | 'claude-3-opus-20240229' | 'claude-sonnet-4-20250514' | 'claude-sonnet-4.5-20250929';
12
- export interface ClaudeMessage {
13
- role: 'user' | 'assistant';
14
- content: string;
15
- }
16
- export interface ClaudeStreamChunk {
17
- type: 'content_block_delta' | 'message_delta' | 'message_stop';
18
- delta?: {
19
- text?: string;
20
- type?: string;
21
- };
22
- }
23
- export declare class ClaudeConnection {
24
- private client;
25
- private model;
26
- private conversationHistory;
27
- private conversationHistoryWithTools;
28
- private systemPrompt?;
29
- private toolsRegistry;
30
- constructor(config?: AgentConfig, systemPrompt?: string);
31
- /**
32
- * Send a message and get response
33
- */
34
- chat(userMessage: string): Promise<string>;
35
- /**
36
- * Stream response (for future implementation)
37
- */
38
- chatStream(userMessage: string): AsyncGenerator<string, void, unknown>;
39
- /**
40
- * Generate single response without conversation history
41
- */
42
- generate(prompt: string, systemPrompt?: string): Promise<string>;
43
- /**
44
- * Clear conversation history
45
- */
46
- clearHistory(): void;
47
- /**
48
- * Get conversation history
49
- */
50
- getHistory(): ClaudeMessage[];
51
- /**
52
- * Set system prompt
53
- */
54
- setSystemPrompt(prompt: string): void;
55
- /**
56
- * Get current model
57
- */
58
- getModel(): ClaudeModelId;
59
- /**
60
- * Change model
61
- */
62
- setModel(model: ClaudeModelId): void;
63
- /**
64
- * Chat with tools support - handles full tool loop
65
- */
66
- chatWithTools(userMessage: string, tools: Anthropic.Tool[], onMessage?: MessageCallback): Promise<string>;
67
- /**
68
- * Clear tool conversation history
69
- */
70
- clearToolHistory(): void;
71
- }
72
- //# sourceMappingURL=claude.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"claude.d.ts","sourceRoot":"","sources":["../../src/connections/claude.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,SAAS,MAAM,mBAAmB,CAAA;AAMzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAE7D,OAAO,KAAK,EAAqB,eAAe,EAAE,MAAM,YAAY,CAAA;AAEpE,MAAM,MAAM,aAAa,GACrB,4BAA4B,GAC5B,2BAA2B,GAC3B,wBAAwB,GACxB,0BAA0B,GAC1B,4BAA4B,CAAA;AAEhC,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,GAAG,WAAW,CAAA;IAC1B,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,qBAAqB,GAAG,eAAe,GAAG,cAAc,CAAA;IAC9D,KAAK,CAAC,EAAE;QACN,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;KACd,CAAA;CACF;AAED,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,KAAK,CAAe;IAC5B,OAAO,CAAC,mBAAmB,CAAsB;IACjD,OAAO,CAAC,4BAA4B,CAAqB;IACzD,OAAO,CAAC,YAAY,CAAC,CAAQ;IAC7B,OAAO,CAAC,aAAa,CAAqB;gBAE9B,MAAM,CAAC,EAAE,WAAW,EAAE,YAAY,CAAC,EAAE,MAAM;IAkBvD;;OAEG;IACG,IAAI,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA+BhD;;OAEG;IACI,UAAU,CAAC,WAAW,EAAE,MAAM,GAAG,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC;IAoC7E;;OAEG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAqBtE;;OAEG;IACH,YAAY,IAAI,IAAI;IAIpB;;OAEG;IACH,UAAU,IAAI,aAAa,EAAE;IAI7B;;OAEG;IACH,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAIrC;;OAEG;IACH,QAAQ,IAAI,aAAa;IAIzB;;OAEG;IACH,QAAQ,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI;IAIpC;;OAEG;IACG,aAAa,CACjB,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,SAAS,CAAC,IAAI,EAAE,EACvB,SAAS,CAAC,EAAE,eAAe,GAC1B,OAAO,CAAC,MAAM,CAAC;IAgIlB;;OAEG;IACH,gBAAgB,IAAI,IAAI;CAGzB"}
@@ -1,270 +0,0 @@
1
- /**
2
- * @author Bùi Trọng Hiếu
3
- * @email kevinbui210191@gmail.com
4
- * @create 2024-10-13
5
- * @modify 2024-10-13
6
- * @desc Claude API connection using Anthropic SDK
7
- */
8
- import Anthropic from '@anthropic-ai/sdk';
9
- import { ToolRegistry } from '../tools/index.js';
10
- export class ClaudeConnection {
11
- client;
12
- model;
13
- conversationHistory = [];
14
- conversationHistoryWithTools = [];
15
- systemPrompt;
16
- toolsRegistry = new ToolRegistry();
17
- constructor(config, systemPrompt) {
18
- // Only get apiKey from config - no fallback to env
19
- const apiKey = config?.apiKey;
20
- // if (!apiKey) {
21
- // throw new Error(
22
- // 'Hiện tại bạn chưa thêm apikey cho model claude. Vui lòng thêm để dùng phần mềm'
23
- // );
24
- // }
25
- this.client = new Anthropic({
26
- apiKey,
27
- });
28
- this.model = config?.model || 'claude-sonnet-4.5-20250929';
29
- this.systemPrompt = systemPrompt;
30
- }
31
- /**
32
- * Send a message and get response
33
- */
34
- async chat(userMessage) {
35
- // Add user message to history
36
- this.conversationHistory.push({
37
- role: 'user',
38
- content: userMessage,
39
- });
40
- try {
41
- const response = await this.client.messages.create({
42
- model: this.model,
43
- max_tokens: 8192,
44
- system: this.systemPrompt,
45
- messages: this.conversationHistory,
46
- });
47
- // Extract assistant response
48
- const assistantMessage = response.content[0]?.type === 'text' ? response.content[0].text : '';
49
- // Add to history
50
- this.conversationHistory.push({
51
- role: 'assistant',
52
- content: assistantMessage,
53
- });
54
- return assistantMessage;
55
- }
56
- catch (error) {
57
- console.error('Claude API Error:', error);
58
- throw error;
59
- }
60
- }
61
- /**
62
- * Stream response (for future implementation)
63
- */
64
- async *chatStream(userMessage) {
65
- this.conversationHistory.push({
66
- role: 'user',
67
- content: userMessage,
68
- });
69
- try {
70
- const stream = await this.client.messages.create({
71
- model: this.model,
72
- max_tokens: 8192,
73
- system: this.systemPrompt,
74
- messages: this.conversationHistory,
75
- stream: true,
76
- });
77
- let fullResponse = '';
78
- for await (const chunk of stream) {
79
- if (chunk.type === 'content_block_delta' && chunk.delta.type === 'text_delta') {
80
- const text = chunk.delta.text || '';
81
- fullResponse += text;
82
- yield text;
83
- }
84
- }
85
- // Add complete response to history
86
- this.conversationHistory.push({
87
- role: 'assistant',
88
- content: fullResponse,
89
- });
90
- }
91
- catch (error) {
92
- console.error('Claude Stream Error:', error);
93
- throw error;
94
- }
95
- }
96
- /**
97
- * Generate single response without conversation history
98
- */
99
- async generate(prompt, systemPrompt) {
100
- try {
101
- const response = await this.client.messages.create({
102
- model: this.model,
103
- max_tokens: 8192,
104
- system: systemPrompt || this.systemPrompt,
105
- messages: [
106
- {
107
- role: 'user',
108
- content: prompt,
109
- },
110
- ],
111
- });
112
- return response.content[0]?.type === 'text' ? response.content[0].text : '';
113
- }
114
- catch (error) {
115
- console.error('Claude Generate Error:', error);
116
- throw error;
117
- }
118
- }
119
- /**
120
- * Clear conversation history
121
- */
122
- clearHistory() {
123
- this.conversationHistory = [];
124
- }
125
- /**
126
- * Get conversation history
127
- */
128
- getHistory() {
129
- return [...this.conversationHistory];
130
- }
131
- /**
132
- * Set system prompt
133
- */
134
- setSystemPrompt(prompt) {
135
- this.systemPrompt = prompt;
136
- }
137
- /**
138
- * Get current model
139
- */
140
- getModel() {
141
- return this.model;
142
- }
143
- /**
144
- * Change model
145
- */
146
- setModel(model) {
147
- this.model = model;
148
- }
149
- /**
150
- * Chat with tools support - handles full tool loop
151
- */
152
- async chatWithTools(userMessage, tools, onMessage) {
153
- // Add user message to history
154
- this.conversationHistoryWithTools.push({
155
- role: 'user',
156
- content: userMessage,
157
- });
158
- let iteration = 0;
159
- const MAX_ITERATIONS = 100; // Safety limit
160
- while (iteration < MAX_ITERATIONS) {
161
- iteration++;
162
- // Call Claude API
163
- const response = await this.client.messages.create({
164
- model: this.model,
165
- max_tokens: 8192,
166
- system: this.systemPrompt,
167
- messages: this.conversationHistoryWithTools,
168
- tools: tools,
169
- });
170
- // Check stop reason
171
- if (response.stop_reason !== 'tool_use') {
172
- // No more tools to execute - add final response to history
173
- this.conversationHistoryWithTools.push({
174
- role: 'assistant',
175
- content: response.content,
176
- });
177
- // Extract text from response
178
- const textBlock = response.content.find((block) => block.type === 'text');
179
- return textBlock?.text || '';
180
- }
181
- // Add assistant response with tool_use to history
182
- this.conversationHistoryWithTools.push({
183
- role: 'assistant',
184
- content: response.content,
185
- });
186
- // Execute tools and collect results
187
- const toolResults = [];
188
- for (const block of response.content) {
189
- if (block.type === 'tool_use') {
190
- const toolUseBlock = block;
191
- const toolName = toolUseBlock.name;
192
- const toolInput = toolUseBlock.input;
193
- // Special handling for plan_task and progress_reporter
194
- if (toolName === 'plan_task' || toolName === 'progress_reporter') {
195
- try {
196
- const result = await this.toolsRegistry.executeTool(toolName, toolInput);
197
- const resultStr = typeof result === 'string' ? result : JSON.stringify(result);
198
- toolResults.push({
199
- type: 'tool_result',
200
- tool_use_id: toolUseBlock.id,
201
- content: resultStr,
202
- });
203
- }
204
- catch (error) {
205
- const errorMsg = error instanceof Error ? error.message : String(error);
206
- toolResults.push({
207
- type: 'tool_result',
208
- tool_use_id: toolUseBlock.id,
209
- content: `Error: ${errorMsg}`,
210
- is_error: true,
211
- });
212
- }
213
- }
214
- else {
215
- // Regular tool handling with notification
216
- try {
217
- const result = await this.toolsRegistry.executeTool(toolName, toolInput);
218
- const resultStr = typeof result === 'string' ? result : JSON.stringify(result);
219
- // Notify tool execution
220
- if (onMessage) {
221
- const success = !resultStr.startsWith('❌');
222
- onMessage('tool', resultStr, toolName, {
223
- success,
224
- output: resultStr,
225
- });
226
- }
227
- toolResults.push({
228
- type: 'tool_result',
229
- tool_use_id: toolUseBlock.id,
230
- content: resultStr,
231
- });
232
- }
233
- catch (error) {
234
- const errorMsg = error instanceof Error ? error.message : String(error);
235
- // Notify error
236
- if (onMessage) {
237
- onMessage('tool', `❌ Error: ${errorMsg}`, toolName, {
238
- success: false,
239
- error: errorMsg,
240
- });
241
- }
242
- toolResults.push({
243
- type: 'tool_result',
244
- tool_use_id: toolUseBlock.id,
245
- content: `Error: ${errorMsg}`,
246
- is_error: true,
247
- });
248
- }
249
- }
250
- }
251
- }
252
- // Add tool results to history
253
- this.conversationHistoryWithTools.push({
254
- role: 'user',
255
- content: toolResults,
256
- });
257
- // Loop continues to call API again with tool results
258
- }
259
- // Safety limit reached
260
- console.warn(`⚠️ Safety limit (${MAX_ITERATIONS}) reached in Claude tool loop.`);
261
- return 'Maximum iteration limit reached. Please try again.';
262
- }
263
- /**
264
- * Clear tool conversation history
265
- */
266
- clearToolHistory() {
267
- this.conversationHistoryWithTools = [];
268
- }
269
- }
270
- //# sourceMappingURL=claude.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"claude.js","sourceRoot":"","sources":["../../src/connections/claude.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,SAAS,MAAM,mBAAmB,CAAA;AAOzC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAuBhD,MAAM,OA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EAAE,MAAM;gBACZ,OAAO,EAAE,WAAW;aACrB,CAAC,CAAA;YAEF,qDAAqD;QACvD,CAAC;QAED,uBAAuB;QACvB,OAAO,CAAC,IAAI,CAAC,oBAAoB,cAAc,gCAAgC,CAAC,CAAA;QAChF,OAAO,oDAAoD,CAAA;IAC7D,CAAC;IAED;;OAEG;IACH,gBAAgB;QACd,IAAI,CAAC,4BAA4B,GAAG,EAAE,CAAA;IACxC,CAAC;CACF"}
@@ -1,41 +0,0 @@
1
- /**
2
- * @author Bùi Trọng Hiếu
3
- * @email kevinbui210191@gmail.com
4
- * @create 2024-10-08
5
- * @modify 2024-10-13
6
- * @desc Gemini connection helper using @google/genai with improved function call handling.
7
- */
8
- import { FunctionDeclaration, type GenerateContentConfig } from '@google/genai';
9
- import type { AgentConfig } from '../utils/config-manager.js';
10
- import type { ToolExecutionInfo } from './types.js';
11
- export type GeminiGenerateParameters = {
12
- readonly prompt: string;
13
- readonly config?: GenerateContentConfig;
14
- };
15
- export type GeminiChatParameters = {
16
- readonly prompt: string;
17
- readonly tools?: FunctionDeclaration[];
18
- readonly message: string;
19
- };
20
- export type GeminiGenerateResult<T = unknown> = {
21
- readonly text: string;
22
- readonly raw: T;
23
- };
24
- export declare class GeminiConnection {
25
- private client;
26
- private readonly apiKey;
27
- private chatSession;
28
- private readonly systemInstruction?;
29
- private readonly model;
30
- private toolsRegistry;
31
- constructor(config?: AgentConfig, systemPrompt?: string);
32
- initChat(): void;
33
- generate(parameters: GeminiGenerateParameters): Promise<GeminiGenerateResult>;
34
- chat(message: string, onMessage?: (author: 'tool' | 'assistant', content: string, toolName?: string, toolInfo?: ToolExecutionInfo) => void): Promise<string>;
35
- private getToolDeclarations;
36
- private convertToFunctionDeclaration;
37
- private convertSchemaToGeminiSchema;
38
- private convertPropertyToGeminiSchema;
39
- private mapTypeToGemini;
40
- }
41
- //# sourceMappingURL=gemini.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"gemini.d.ts","sourceRoot":"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AG,WAAW,EAC5B,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,iBAAiB,KACzB,IAAI,GACR,OAAO,CAAC,MAAM,CAAC;IAkGlB,OAAO,CAAC,mBAAmB;IAK3B,OAAO,CAAC,4BAA4B;IAYpC,OAAO,CAAC,2BAA2B;IA4BnC,OAAO,CAAC,6BAA6B;IA+BrC,OAAO,CAAC,eAAe;CAWxB"}
@@ -1,203 +0,0 @@
1
- /**
2
- * @author Bùi Trọng Hiếu
3
- * @email kevinbui210191@gmail.com
4
- * @create 2024-10-08
5
- * @modify 2024-10-13
6
- * @desc Gemini connection helper using @google/genai with improved function call handling.
7
- */
8
- import { GoogleGenAI, Type, } from '@google/genai';
9
- import { globalToolRegistry } from '../tools/registry.js';
10
- const geminiModel = 'gemini-2.5-flash';
11
- export class GeminiConnection {
12
- client;
13
- apiKey;
14
- chatSession;
15
- systemInstruction;
16
- model;
17
- toolsRegistry = globalToolRegistry;
18
- constructor(config, systemPrompt) {
19
- // Only get apiKey from config - no fallback to env
20
- this.apiKey = config?.apiKey;
21
- this.model = config?.model ?? 'gemini-2.5-flash';
22
- this.client = new GoogleGenAI({ apiKey: this.apiKey });
23
- this.systemInstruction = systemPrompt;
24
- this.initChat();
25
- }
26
- initChat() {
27
- this.chatSession = this.client.chats.create({
28
- model: this.model,
29
- config: {
30
- systemInstruction: this.systemInstruction,
31
- tools: [{ functionDeclarations: this.getToolDeclarations() }],
32
- temperature: 0.7,
33
- thinkingConfig: {
34
- thinkingBudget: 0,
35
- },
36
- },
37
- });
38
- }
39
- async generate(parameters) {
40
- const response = await this.client.models.generateContent({
41
- model: geminiModel,
42
- contents: parameters.prompt,
43
- });
44
- const text = response.text ?? '';
45
- return { text, raw: response };
46
- }
47
- async chat(message, onMessage) {
48
- if (!this.chatSession) {
49
- throw new Error('Chat session is not initialized.');
50
- }
51
- let currentMessage = message;
52
- let response;
53
- let iteration = 0;
54
- const MAX_ITERATIONS = 15; // Tăng lên vì xử lý từng tool một
55
- while (currentMessage && iteration < MAX_ITERATIONS) {
56
- iteration++;
57
- response = await this.chatSession.sendMessage({
58
- message: currentMessage,
59
- });
60
- if (response.functionCalls && response.functionCalls.length > 0) {
61
- const functionResponses = [];
62
- // **IMPROVED: Sequential execution với early feedback**
63
- for (const functionCall of response.functionCalls) {
64
- try {
65
- const toolName = functionCall.name || 'unknown';
66
- const args = functionCall.args || {};
67
- const toolResult = await this.toolsRegistry.executeTool(toolName, args);
68
- const resultStr = typeof toolResult === 'string' ? toolResult : JSON.stringify(toolResult);
69
- if (onMessage) {
70
- // Pass tool execution info for better formatting
71
- const toolInfo = {
72
- toolName,
73
- args,
74
- result: toolResult,
75
- };
76
- onMessage('tool', resultStr, toolName, toolInfo);
77
- }
78
- functionResponses.push({
79
- functionResponse: {
80
- name: functionCall.name,
81
- response: { result: resultStr },
82
- },
83
- });
84
- // **NEW: Cho phép xử lý từng tool một nếu cần**
85
- // Nếu có nhiều function calls, có thể break ở đây để feedback sớm
86
- // Nhưng hiện tại vẫn xử lý hết để tương thích
87
- }
88
- catch (error) {
89
- const errorMsg = error instanceof Error ? error.message : String(error);
90
- // Log error
91
- if (onMessage) {
92
- const toolInfo = {
93
- toolName: functionCall.name || 'unknown',
94
- args: functionCall.args || {},
95
- result: `❌ Error: ${errorMsg}`,
96
- };
97
- onMessage('tool', `❌ Error: ${errorMsg}`, functionCall.name, toolInfo);
98
- }
99
- functionResponses.push({
100
- functionResponse: {
101
- name: functionCall.name,
102
- response: {
103
- error: errorMsg,
104
- },
105
- },
106
- });
107
- // **NEW: Stop on critical errors**
108
- // Nếu là lỗi nghiêm trọng, có thể break để không lãng phí
109
- // nhưng hiện tại vẫn tiếp tục để AI có đầy đủ context
110
- }
111
- }
112
- // Gửi tất cả function responses
113
- currentMessage = functionResponses;
114
- }
115
- else {
116
- // Không có function calls → trả về text response
117
- return response.text ?? '';
118
- }
119
- }
120
- if (iteration >= MAX_ITERATIONS) {
121
- console.warn(`⚠️ Max iterations (${MAX_ITERATIONS}) reached. This may indicate:`);
122
- console.warn(' - Too many sequential tool calls');
123
- console.warn(' - AI stuck in a reasoning loop');
124
- console.warn(' - Consider reviewing system prompt or tool definitions');
125
- throw new Error(`Max iterations (${MAX_ITERATIONS}) reached`);
126
- }
127
- return '';
128
- }
129
- getToolDeclarations() {
130
- const tools = this.toolsRegistry.list();
131
- return tools.map(tool => this.convertToFunctionDeclaration(tool));
132
- }
133
- convertToFunctionDeclaration(tool) {
134
- return {
135
- name: tool.name,
136
- description: tool.description,
137
- parameters: this.convertSchemaToGeminiSchema(tool.inputSchema),
138
- };
139
- }
140
- convertSchemaToGeminiSchema(schema) {
141
- if (!schema) {
142
- return {
143
- type: Type.OBJECT,
144
- properties: {},
145
- };
146
- }
147
- const converted = {
148
- type: Type.OBJECT,
149
- properties: {},
150
- };
151
- if (schema['properties']) {
152
- converted.properties = {};
153
- for (const [key, value] of Object.entries(schema['properties'])) {
154
- const prop = value;
155
- converted.properties[key] = this.convertPropertyToGeminiSchema(prop);
156
- }
157
- }
158
- if (schema['required']) {
159
- converted.required = schema['required'];
160
- }
161
- return converted;
162
- }
163
- convertPropertyToGeminiSchema(prop) {
164
- const propSchema = {
165
- type: this.mapTypeToGemini(prop.type),
166
- description: prop.description || '',
167
- };
168
- if (prop.type === 'object' && prop.properties) {
169
- propSchema.properties = {};
170
- for (const [key, value] of Object.entries(prop.properties)) {
171
- propSchema.properties[key] = this.convertPropertyToGeminiSchema(value);
172
- }
173
- if (prop.required) {
174
- propSchema.required = prop.required;
175
- }
176
- }
177
- if (prop.type === 'array') {
178
- if (prop.items && typeof prop.items === 'object') {
179
- propSchema.items = this.convertPropertyToGeminiSchema(prop.items);
180
- }
181
- else {
182
- // Gemini requires items field for arrays
183
- propSchema.items = {
184
- type: Type.STRING,
185
- description: '',
186
- };
187
- }
188
- }
189
- return propSchema;
190
- }
191
- mapTypeToGemini(type) {
192
- const typeMap = {
193
- string: Type.STRING,
194
- number: Type.NUMBER,
195
- integer: Type.INTEGER,
196
- boolean: Type.BOOLEAN,
197
- object: Type.OBJECT,
198
- array: Type.ARRAY,
199
- };
200
- return typeMap[type.toLowerCase()] || Type.STRING;
201
- }
202
- }
203
- //# sourceMappingURL=gemini.js.map