@friggframework/ai-agents 2.0.0--canary.522.cbd3d5a.0

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 (33) hide show
  1. package/LICENSE.md +9 -0
  2. package/jest.config.js +8 -0
  3. package/package.json +60 -0
  4. package/src/domain/entities/agent-event.js +55 -0
  5. package/src/domain/entities/agent-proposal.js +81 -0
  6. package/src/domain/entities/index.js +9 -0
  7. package/src/domain/index.js +7 -0
  8. package/src/domain/interfaces/agent-framework.js +29 -0
  9. package/src/domain/interfaces/index.js +10 -0
  10. package/src/domain/interfaces/validation-pipeline.js +61 -0
  11. package/src/index.js +41 -0
  12. package/src/infrastructure/adapters/claude-agent-adapter.js +148 -0
  13. package/src/infrastructure/adapters/index.js +10 -0
  14. package/src/infrastructure/adapters/vercel-ai-adapter.js +135 -0
  15. package/src/infrastructure/git/git-checkpoint-service.js +110 -0
  16. package/src/infrastructure/git/index.js +3 -0
  17. package/src/infrastructure/mcp/frigg-tools.js +1918 -0
  18. package/src/infrastructure/mcp/index.js +25 -0
  19. package/src/infrastructure/streaming/agent-stream-handler.js +117 -0
  20. package/src/infrastructure/streaming/index.js +3 -0
  21. package/src/infrastructure/validation/index.js +3 -0
  22. package/src/infrastructure/validation/validation-pipeline.js +226 -0
  23. package/tests/integration/agent-workflow.test.js +276 -0
  24. package/tests/unit/domain/entities/agent-event.test.js +73 -0
  25. package/tests/unit/domain/entities/agent-proposal.test.js +121 -0
  26. package/tests/unit/domain/interfaces/agent-framework.test.js +66 -0
  27. package/tests/unit/domain/interfaces/validation-pipeline.test.js +83 -0
  28. package/tests/unit/infrastructure/adapters/claude-agent-adapter.test.js +193 -0
  29. package/tests/unit/infrastructure/adapters/vercel-ai-adapter.test.js +174 -0
  30. package/tests/unit/infrastructure/git/git-checkpoint-service.test.js +182 -0
  31. package/tests/unit/infrastructure/mcp/frigg-tools.test.js +810 -0
  32. package/tests/unit/infrastructure/streaming/agent-stream-handler.test.js +214 -0
  33. package/tests/unit/infrastructure/validation/validation-pipeline.test.js +288 -0
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Left Hook Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/jest.config.js ADDED
@@ -0,0 +1,8 @@
1
+ module.exports = {
2
+ testEnvironment: 'node',
3
+ testMatch: ['**/tests/**/*.test.js'],
4
+ collectCoverageFrom: ['src/**/*.js'],
5
+ coverageDirectory: 'coverage',
6
+ coverageReporters: ['text', 'lcov'],
7
+ verbose: true
8
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@friggframework/ai-agents",
3
+ "version": "2.0.0--canary.522.cbd3d5a.0",
4
+ "description": "AI agent integration for Frigg Framework",
5
+ "main": "src/index.js",
6
+ "author": "",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/friggframework/frigg.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/friggframework/frigg/issues"
14
+ },
15
+ "homepage": "https://github.com/friggframework/frigg#readme",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "scripts": {
20
+ "test": "jest",
21
+ "test:watch": "jest --watch",
22
+ "test:coverage": "jest --coverage",
23
+ "lint:fix": "prettier --write --loglevel error . && eslint . --fix"
24
+ },
25
+ "keywords": [
26
+ "frigg",
27
+ "ai",
28
+ "agents",
29
+ "mcp",
30
+ "llm"
31
+ ],
32
+ "dependencies": {
33
+ "@friggframework/schemas": "2.0.0--canary.522.cbd3d5a.0"
34
+ },
35
+ "peerDependencies": {
36
+ "@ai-sdk/openai": ">=1.0.0",
37
+ "@anthropic-ai/claude-agent-sdk": ">=0.1.0",
38
+ "ai": ">=4.0.0"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "ai": {
42
+ "optional": true
43
+ },
44
+ "@ai-sdk/openai": {
45
+ "optional": true
46
+ },
47
+ "@anthropic-ai/claude-agent-sdk": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "devDependencies": {
52
+ "@friggframework/eslint-config": "2.0.0--canary.522.cbd3d5a.0",
53
+ "@friggframework/prettier-config": "2.0.0--canary.522.cbd3d5a.0",
54
+ "eslint": "^8.22.0",
55
+ "jest": "^29.7.0",
56
+ "prettier": "^2.7.1"
57
+ },
58
+ "prettier": "@friggframework/prettier-config",
59
+ "gitHead": "cbd3d5a81315519842f308fc0bd786a3f8786b79"
60
+ }
@@ -0,0 +1,55 @@
1
+ const AgentEventType = {
2
+ CONTENT: 'content',
3
+ TOOL_CALL: 'tool_call',
4
+ TOOL_RESULT: 'tool_result',
5
+ USAGE: 'usage',
6
+ DONE: 'done',
7
+ ERROR: 'error'
8
+ };
9
+
10
+ class AgentEvent {
11
+ constructor({ type, timestamp = new Date(), ...data }) {
12
+ this.type = type;
13
+ this.timestamp = timestamp;
14
+ Object.assign(this, data);
15
+ }
16
+
17
+ static content(text) {
18
+ return new AgentEvent({ type: AgentEventType.CONTENT, content: text });
19
+ }
20
+
21
+ static toolCall(name, args) {
22
+ return new AgentEvent({ type: AgentEventType.TOOL_CALL, name, args });
23
+ }
24
+
25
+ static toolResult(name, result) {
26
+ return new AgentEvent({ type: AgentEventType.TOOL_RESULT, name, result });
27
+ }
28
+
29
+ static usage(usage) {
30
+ return new AgentEvent({ type: AgentEventType.USAGE, usage });
31
+ }
32
+
33
+ static done() {
34
+ return new AgentEvent({ type: AgentEventType.DONE });
35
+ }
36
+
37
+ static error(error) {
38
+ return new AgentEvent({ type: AgentEventType.ERROR, error });
39
+ }
40
+
41
+ toJSON() {
42
+ return {
43
+ type: this.type,
44
+ timestamp: this.timestamp.toISOString(),
45
+ ...(this.content && { content: this.content }),
46
+ ...(this.name && { name: this.name }),
47
+ ...(this.args && { args: this.args }),
48
+ ...(this.result && { result: this.result }),
49
+ ...(this.usage && { usage: this.usage }),
50
+ ...(this.error && { error: this.error.message || String(this.error) })
51
+ };
52
+ }
53
+ }
54
+
55
+ module.exports = { AgentEvent, AgentEventType };
@@ -0,0 +1,81 @@
1
+ const ProposalStatus = {
2
+ PENDING: 'pending',
3
+ APPROVED: 'approved',
4
+ REJECTED: 'rejected',
5
+ MODIFIED: 'modified'
6
+ };
7
+
8
+ class AgentProposal {
9
+ constructor({ id, files, validation, checkpointId = null }) {
10
+ this.id = id;
11
+ this.files = files;
12
+ this.validation = validation;
13
+ this.checkpointId = checkpointId;
14
+ this.status = ProposalStatus.PENDING;
15
+ this.createdAt = new Date();
16
+ this.approvedAt = null;
17
+ this.rejectedAt = null;
18
+ this.rejectionReason = null;
19
+ }
20
+
21
+ getSummary() {
22
+ let linesAdded = 0;
23
+ let createdFiles = 0;
24
+ let modifiedFiles = 0;
25
+
26
+ for (const file of this.files) {
27
+ if (file.action === 'create') {
28
+ createdFiles++;
29
+ if (file.content) {
30
+ linesAdded += file.content.split('\n').length;
31
+ }
32
+ } else if (file.action === 'modify') {
33
+ modifiedFiles++;
34
+ }
35
+ }
36
+
37
+ return {
38
+ fileCount: this.files.length,
39
+ createdFiles,
40
+ modifiedFiles,
41
+ linesAdded,
42
+ confidence: this.validation?.confidence,
43
+ recommendation: this.validation?.recommendation
44
+ };
45
+ }
46
+
47
+ approve() {
48
+ if (this.status === ProposalStatus.REJECTED) {
49
+ throw new Error('Cannot approve rejected proposal');
50
+ }
51
+ this.status = ProposalStatus.APPROVED;
52
+ this.approvedAt = new Date();
53
+ }
54
+
55
+ reject(reason) {
56
+ this.status = ProposalStatus.REJECTED;
57
+ this.rejectedAt = new Date();
58
+ this.rejectionReason = reason;
59
+ }
60
+
61
+ canRollback() {
62
+ return this.checkpointId !== null;
63
+ }
64
+
65
+ toJSON() {
66
+ return {
67
+ id: this.id,
68
+ status: this.status,
69
+ files: this.files.map(f => ({ path: f.path, action: f.action })),
70
+ validation: this.validation,
71
+ checkpointId: this.checkpointId,
72
+ summary: this.getSummary(),
73
+ createdAt: this.createdAt.toISOString(),
74
+ approvedAt: this.approvedAt?.toISOString(),
75
+ rejectedAt: this.rejectedAt?.toISOString(),
76
+ rejectionReason: this.rejectionReason
77
+ };
78
+ }
79
+ }
80
+
81
+ module.exports = { AgentProposal, ProposalStatus };
@@ -0,0 +1,9 @@
1
+ const { AgentEvent, AgentEventType } = require('./agent-event');
2
+ const { AgentProposal, ProposalStatus } = require('./agent-proposal');
3
+
4
+ module.exports = {
5
+ AgentEvent,
6
+ AgentEventType,
7
+ AgentProposal,
8
+ ProposalStatus
9
+ };
@@ -0,0 +1,7 @@
1
+ const interfaces = require('./interfaces');
2
+ const entities = require('./entities');
3
+
4
+ module.exports = {
5
+ ...interfaces,
6
+ ...entities
7
+ };
@@ -0,0 +1,29 @@
1
+ class NotImplementedError extends Error {
2
+ constructor(method) {
3
+ super(`Not implemented: ${method}`);
4
+ this.name = 'NotImplementedError';
5
+ }
6
+ }
7
+
8
+ class IAgentFramework {
9
+ async runAgent(_params) {
10
+ throw new NotImplementedError('runAgent');
11
+ }
12
+
13
+ async loadMcpTools(_serverConfig) {
14
+ throw new NotImplementedError('loadMcpTools');
15
+ }
16
+
17
+ getCapabilities() {
18
+ throw new NotImplementedError('getCapabilities');
19
+ }
20
+
21
+ async validateRunParams(params) {
22
+ if (!params.prompt) {
23
+ throw new Error('prompt is required');
24
+ }
25
+ return true;
26
+ }
27
+ }
28
+
29
+ module.exports = { IAgentFramework, NotImplementedError };
@@ -0,0 +1,10 @@
1
+ const { IAgentFramework, NotImplementedError } = require('./agent-framework');
2
+ const { IValidationPipeline, WEIGHTS, THRESHOLDS } = require('./validation-pipeline');
3
+
4
+ module.exports = {
5
+ IAgentFramework,
6
+ IValidationPipeline,
7
+ NotImplementedError,
8
+ WEIGHTS,
9
+ THRESHOLDS
10
+ };
@@ -0,0 +1,61 @@
1
+ const { NotImplementedError } = require('./agent-framework');
2
+
3
+ const WEIGHTS = {
4
+ schema: 0.30,
5
+ patterns: 0.25,
6
+ security: 0.15,
7
+ tests: 0.20,
8
+ lint: 0.10
9
+ };
10
+
11
+ const THRESHOLDS = {
12
+ autoApprove: 95,
13
+ requireReview: 80
14
+ };
15
+
16
+ class IValidationPipeline {
17
+ async validate(_files) {
18
+ throw new NotImplementedError('validate');
19
+ }
20
+
21
+ calculateConfidence(layerResults) {
22
+ let totalScore = 0;
23
+
24
+ for (const [layer, weight] of Object.entries(WEIGHTS)) {
25
+ const result = layerResults[layer];
26
+ if (result && typeof result.score === 'number') {
27
+ totalScore += result.score * weight;
28
+ }
29
+ }
30
+
31
+ return Math.round(totalScore);
32
+ }
33
+
34
+ getRecommendation(confidence, thresholds = THRESHOLDS) {
35
+ if (confidence >= thresholds.autoApprove) {
36
+ return 'auto_approve';
37
+ }
38
+ if (confidence >= thresholds.requireReview) {
39
+ return 'require_review';
40
+ }
41
+ return 'manual_approval';
42
+ }
43
+
44
+ generateFeedback(layerResults) {
45
+ const feedback = [];
46
+
47
+ for (const [layer, result] of Object.entries(layerResults)) {
48
+ if (!result.passed) {
49
+ feedback.push({
50
+ layer,
51
+ score: result.score,
52
+ issues: result.errors || result.violations || result.vulnerabilities || result.failures || []
53
+ });
54
+ }
55
+ }
56
+
57
+ return feedback;
58
+ }
59
+ }
60
+
61
+ module.exports = { IValidationPipeline, WEIGHTS, THRESHOLDS };
package/src/index.js ADDED
@@ -0,0 +1,41 @@
1
+ const { IAgentFramework, NotImplementedError } = require('./domain/interfaces/agent-framework');
2
+ const { IValidationPipeline } = require('./domain/interfaces/validation-pipeline');
3
+
4
+ const { AgentEvent, AgentEventType } = require('./domain/entities/agent-event');
5
+ const { AgentProposal, ProposalStatus } = require('./domain/entities/agent-proposal');
6
+
7
+ const { VercelAIAdapter, SUPPORTED_PROVIDERS } = require('./infrastructure/adapters/vercel-ai-adapter');
8
+ const { ClaudeAgentAdapter } = require('./infrastructure/adapters/claude-agent-adapter');
9
+
10
+ const { ValidationPipeline, ValidationLayer, LAYER_WEIGHTS } = require('./infrastructure/validation/validation-pipeline');
11
+
12
+ const { createFriggMcpTools, KNOWN_MODULES } = require('./infrastructure/mcp/frigg-tools');
13
+
14
+ const { GitCheckpointService } = require('./infrastructure/git/git-checkpoint-service');
15
+
16
+ const { AgentStreamHandler } = require('./infrastructure/streaming/agent-stream-handler');
17
+
18
+ module.exports = {
19
+ IAgentFramework,
20
+ IValidationPipeline,
21
+ NotImplementedError,
22
+
23
+ AgentEvent,
24
+ AgentEventType,
25
+ AgentProposal,
26
+ ProposalStatus,
27
+
28
+ VercelAIAdapter,
29
+ ClaudeAgentAdapter,
30
+ SUPPORTED_PROVIDERS,
31
+
32
+ ValidationPipeline,
33
+ ValidationLayer,
34
+ LAYER_WEIGHTS,
35
+
36
+ createFriggMcpTools,
37
+ KNOWN_MODULES,
38
+
39
+ GitCheckpointService,
40
+ AgentStreamHandler
41
+ };
@@ -0,0 +1,148 @@
1
+ const { IAgentFramework } = require('../../domain/interfaces/agent-framework');
2
+ const { AgentEvent } = require('../../domain/entities/agent-event');
3
+
4
+ const DEFAULT_CONFIG = {
5
+ model: 'claude-3-5-sonnet-20241022',
6
+ maxTokens: 4096,
7
+ temperature: 0.7
8
+ };
9
+
10
+ class ClaudeAgentAdapter extends IAgentFramework {
11
+ constructor(config = {}) {
12
+ super();
13
+ this.config = { ...DEFAULT_CONFIG, ...config };
14
+ this.tools = [];
15
+ this.approvalConfig = {
16
+ requireApproval: true,
17
+ confidenceThreshold: 80
18
+ };
19
+ this._paused = false;
20
+ }
21
+
22
+ getCapabilities() {
23
+ return {
24
+ streaming: true,
25
+ toolCalling: true,
26
+ mcpSupport: true,
27
+ nativeMcp: true,
28
+ multiProvider: false,
29
+ providers: ['anthropic'],
30
+ subagentOrchestration: true,
31
+ contextWindow: 200000
32
+ };
33
+ }
34
+
35
+ async loadMcpTools(serverConfig) {
36
+ const { tools = [] } = serverConfig;
37
+
38
+ this.tools = tools.map(tool => ({
39
+ name: tool.name,
40
+ description: tool.description,
41
+ inputSchema: tool.inputSchema || { type: 'object', properties: {} },
42
+ execute: tool.handler
43
+ }));
44
+
45
+ return this.tools;
46
+ }
47
+
48
+ createStreamingHandler(onEvent) {
49
+ return {
50
+ onContent: (text) => {
51
+ onEvent(AgentEvent.content(text));
52
+ },
53
+ onToolCall: (name, args) => {
54
+ onEvent(AgentEvent.toolCall(name, args));
55
+ },
56
+ onToolResult: (name, result) => {
57
+ onEvent(AgentEvent.toolResult(name, result));
58
+ },
59
+ onFinish: (result) => {
60
+ if (result?.usage) {
61
+ onEvent(AgentEvent.usage(result.usage));
62
+ }
63
+ onEvent(AgentEvent.done());
64
+ },
65
+ onError: (error) => {
66
+ onEvent(AgentEvent.error(error));
67
+ }
68
+ };
69
+ }
70
+
71
+ buildSystemPrompt(context = {}) {
72
+ const { integrationContext = '' } = context;
73
+
74
+ return `You are an AI agent specialized in building integrations with the Frigg Framework.
75
+
76
+ You have access to Frigg-specific MCP tools that help you generate valid, secure code:
77
+
78
+ ## Available Tools
79
+
80
+ - **frigg_validate_schema**: Validate JSON against Frigg schemas (app-definition, integration-definition, api-module-definition)
81
+ - **frigg_get_template**: Get starter templates for OAuth2, API key, or webhook integrations
82
+ - **frigg_check_patterns**: Verify code follows hexagonal architecture and IntegrationBase patterns
83
+ - **frigg_list_modules**: List available pre-built API modules (HubSpot, Salesforce, Slack, etc.)
84
+ - **frigg_security_scan**: Scan for hardcoded credentials, SQL injection, and other vulnerabilities
85
+ - **frigg_git_checkpoint**: Create rollback points before making changes
86
+ - **frigg_get_example**: Get working examples of common patterns
87
+
88
+ ${integrationContext ? `\nCurrent context: ${integrationContext}` : ''}
89
+
90
+ ## Required Patterns
91
+
92
+ All integrations must:
93
+ 1. Extend IntegrationBase from @friggframework/core
94
+ 2. Have static Definition property with name, version, modules, display
95
+ 3. Implement: onCreate, onUpdate, onDelete, getConfigOptions, testAuth
96
+ 4. Follow hexagonal architecture (ports and adapters)
97
+ 5. Use environment variables for credentials
98
+
99
+ ## Workflow
100
+
101
+ 1. Start with frigg_git_checkpoint to enable rollback
102
+ 2. Use frigg_get_template for initial structure
103
+ 3. Customize based on requirements
104
+ 4. Run frigg_check_patterns to verify structure
105
+ 5. Run frigg_security_scan before finalizing
106
+ 6. Run frigg_validate_schema for any JSON configs
107
+
108
+ Human approval is required for all generated code. Present proposals clearly with file paths, content, and confidence scores.`;
109
+ }
110
+
111
+ async runAgent(params) {
112
+ await this.validateRunParams(params);
113
+
114
+ const { prompt, context = {}, onEvent } = params;
115
+
116
+ if (params.mock) {
117
+ return {
118
+ stream: this._mockResponse ? this._mockResponse() : this._createMockStream(),
119
+ cancel: () => {}
120
+ };
121
+ }
122
+
123
+ throw new Error('Claude Agent SDK not configured. Install "@anthropic-ai/claude-agent-sdk" and set ANTHROPIC_API_KEY.');
124
+ }
125
+
126
+ async *_createMockStream() {
127
+ yield AgentEvent.content('Mock response - Claude Agent SDK not initialized');
128
+ yield AgentEvent.done();
129
+ }
130
+
131
+ configureHumanApproval(config) {
132
+ this.approvalConfig = { ...this.approvalConfig, ...config };
133
+ }
134
+
135
+ pause() {
136
+ this._paused = true;
137
+ }
138
+
139
+ resume() {
140
+ this._paused = false;
141
+ }
142
+
143
+ isPaused() {
144
+ return this._paused;
145
+ }
146
+ }
147
+
148
+ module.exports = { ClaudeAgentAdapter, DEFAULT_CONFIG };
@@ -0,0 +1,10 @@
1
+ const { VercelAIAdapter, DEFAULT_CONFIG: VERCEL_DEFAULT_CONFIG, SUPPORTED_PROVIDERS } = require('./vercel-ai-adapter');
2
+ const { ClaudeAgentAdapter, DEFAULT_CONFIG: CLAUDE_DEFAULT_CONFIG } = require('./claude-agent-adapter');
3
+
4
+ module.exports = {
5
+ VercelAIAdapter,
6
+ ClaudeAgentAdapter,
7
+ VERCEL_DEFAULT_CONFIG,
8
+ CLAUDE_DEFAULT_CONFIG,
9
+ SUPPORTED_PROVIDERS
10
+ };
@@ -0,0 +1,135 @@
1
+ const { IAgentFramework } = require('../../domain/interfaces/agent-framework');
2
+ const { AgentEvent } = require('../../domain/entities/agent-event');
3
+
4
+ const DEFAULT_CONFIG = {
5
+ model: 'gpt-4-turbo',
6
+ provider: 'openai',
7
+ maxTokens: 4096,
8
+ temperature: 0.7
9
+ };
10
+
11
+ const SUPPORTED_PROVIDERS = ['openai', 'anthropic', 'google', 'azure', 'amazon-bedrock'];
12
+
13
+ class VercelAIAdapter extends IAgentFramework {
14
+ constructor(config = {}) {
15
+ super();
16
+ this.config = { ...DEFAULT_CONFIG, ...config };
17
+ this.tools = [];
18
+ this.approvalConfig = {
19
+ requireApproval: true,
20
+ confidenceThreshold: 80
21
+ };
22
+ this._paused = false;
23
+ }
24
+
25
+ getCapabilities() {
26
+ return {
27
+ streaming: true,
28
+ toolCalling: true,
29
+ mcpSupport: true,
30
+ multiProvider: true,
31
+ providers: SUPPORTED_PROVIDERS,
32
+ nativeMcp: false,
33
+ subagentOrchestration: false
34
+ };
35
+ }
36
+
37
+ async loadMcpTools(serverConfig) {
38
+ const { tools = [] } = serverConfig;
39
+
40
+ this.tools = tools.map(tool => ({
41
+ name: tool.name,
42
+ description: tool.description,
43
+ parameters: tool.inputSchema || { type: 'object', properties: {} },
44
+ execute: tool.handler
45
+ }));
46
+
47
+ return this.tools;
48
+ }
49
+
50
+ createStreamingHandler(onEvent) {
51
+ return {
52
+ onContent: (text) => {
53
+ onEvent(AgentEvent.content(text));
54
+ },
55
+ onToolCall: (name, args) => {
56
+ onEvent(AgentEvent.toolCall(name, args));
57
+ },
58
+ onToolResult: (name, result) => {
59
+ onEvent(AgentEvent.toolResult(name, result));
60
+ },
61
+ onFinish: (result) => {
62
+ if (result?.usage) {
63
+ onEvent(AgentEvent.usage(result.usage));
64
+ }
65
+ onEvent(AgentEvent.done());
66
+ },
67
+ onError: (error) => {
68
+ onEvent(AgentEvent.error(error));
69
+ }
70
+ };
71
+ }
72
+
73
+ buildSystemPrompt(context = {}) {
74
+ const { integrationContext = '' } = context;
75
+
76
+ return `You are an AI agent specialized in building integrations with the Frigg Framework.
77
+
78
+ Your role is to help developers create, modify, and maintain integrations following Frigg's hexagonal architecture patterns.
79
+
80
+ ${integrationContext ? `Current context: ${integrationContext}` : ''}
81
+
82
+ Key patterns to follow:
83
+ - Always extend IntegrationBase for integration classes
84
+ - Implement required methods: onCreate, onUpdate, onDelete, getConfigOptions, testAuth
85
+ - Use static Definition property for integration metadata
86
+ - Follow OAuth2 patterns for authentication
87
+ - Use environment variables for credentials, never hardcode
88
+
89
+ When generating code:
90
+ 1. Use frigg_validate_schema to validate JSON definitions
91
+ 2. Use frigg_check_patterns to verify code follows Frigg patterns
92
+ 3. Use frigg_security_scan to check for vulnerabilities
93
+ 4. Always include test files for generated code
94
+
95
+ Validation is critical - run validation tools after every code generation step.`;
96
+ }
97
+
98
+ async runAgent(params) {
99
+ await this.validateRunParams(params);
100
+
101
+ const { prompt, context = {}, onEvent } = params;
102
+
103
+ if (params.mock) {
104
+ return {
105
+ stream: this._mockResponse ? this._mockResponse() : this._createMockStream(),
106
+ cancel: () => {}
107
+ };
108
+ }
109
+
110
+ throw new Error('Vercel AI SDK not configured. Install "ai" package and set API keys.');
111
+ }
112
+
113
+ async *_createMockStream() {
114
+ yield AgentEvent.content('Mock response - Vercel AI SDK not initialized');
115
+ yield AgentEvent.done();
116
+ }
117
+
118
+ configureHumanApproval(config) {
119
+ this.approvalConfig = { ...this.approvalConfig, ...config };
120
+ }
121
+
122
+ pause() {
123
+ this._paused = true;
124
+ }
125
+
126
+ resume() {
127
+ this._paused = false;
128
+ }
129
+
130
+ isPaused() {
131
+ return this._paused;
132
+ }
133
+ }
134
+
135
+ module.exports = { VercelAIAdapter, DEFAULT_CONFIG, SUPPORTED_PROVIDERS };