aiagentmarket 3.0.48 → 3.0.49

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.
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var r=Object.getOwnPropertyDescriptor(t,s);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,r)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[t.length]=s);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var s={};if(null!=t)for(var n=e(t),r=0;r<n.length;r++)"default"!==n[r]&&__createBinding(s,t,n[r]);return __setModuleDefault(s,t),s}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlueLampProtectionSystem=void 0;const index_js_1=require("@modelcontextprotocol/sdk/server/index.js"),stdio_js_1=require("@modelcontextprotocol/sdk/server/stdio.js"),types_js_1=require("@modelcontextprotocol/sdk/types.js"),fs=__importStar(require("fs")),path=__importStar(require("path"));class BlueLampProtectionSystem{constructor(){this.server=new index_js_1.Server({name:"bluelamp-protection-system",version:"1.0.0"},{capabilities:{tools:{}}}),this.validTokens=new Set,this.accessLogs=[],this.initializeTokens(),this.setupHandlers()}initializeTokens(){const e=process.env.BLUELAMP_TOKEN;e&&this.validTokens.add(e),this.validTokens.add("test-token-12345"),this.validTokens.add("bluelamp-secure-token-67890")}setupHandlers(){this.server.setRequestHandler(types_js_1.ListToolsRequestSchema,async()=>({tools:[{name:"authenticate_agent",description:"Authenticate access to protected agent",inputSchema:{type:"object",properties:{token:{type:"string",description:"Authentication token"},agentName:{type:"string",description:"Name of the agent to access"}},required:["token","agentName"]}},{name:"get_protected_prompt",description:"Get protected prompt for authenticated agent",inputSchema:{type:"object",properties:{token:{type:"string",description:"Authentication token"},agentName:{type:"string",description:"Name of the agent"},promptId:{type:"string",description:"ID of the prompt to retrieve"}},required:["token","agentName","promptId"]}},{name:"list_protected_agents",description:"List all protected agents available",inputSchema:{type:"object",properties:{token:{type:"string",description:"Authentication token"}},required:["token"]}}]})),this.server.setRequestHandler(types_js_1.CallToolRequestSchema,async e=>{const{name:t,arguments:s}=e.params;try{switch(t){case"authenticate_agent":return await this.handleAuthenticateAgent(s);case"get_protected_prompt":return await this.handleGetProtectedPrompt(s);case"list_protected_agents":return await this.handleListProtectedAgents(s);default:throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound,`Unknown tool: ${t}`)}}catch(e){if(e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`Tool execution failed: ${t}: ${e}`)}})}validateToken(e){return this.validTokens.has(e)}logAccess(e,t,s){this.accessLogs.push({timestamp:new Date,token:e.substring(0,8)+"...",agentName:t,success:s}),this.accessLogs.length>100&&(this.accessLogs=this.accessLogs.slice(-100))}async handleAuthenticateAgent(e){const{token:t,agentName:s}=e;return this.validateToken(t)?(this.logAccess(t,s,!0),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Authentication successful for agent: ${s}`,sessionId:`session_${Date.now()}`,expiresAt:new Date(Date.now()+36e5).toISOString()})}]}):(this.logAccess(t,s,!1),{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_FAILED"})}]})}async handleGetProtectedPrompt(e){const{token:t,agentName:s,promptId:n}=e;if(!this.validateToken(t))return this.logAccess(t,s,!1),{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_FAILED"})}]};try{const e=path.join(process.cwd(),"protected-prompts",s),r=path.join(e,`${n}.md`);if(!fs.existsSync(r))return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Prompt not found: ${n} for agent: ${s}`,code:"PROMPT_NOT_FOUND"})}]};const o=fs.readFileSync(r,"utf-8");return this.logAccess(t,s,!0),{content:[{type:"text",text:JSON.stringify({success:!0,agentName:s,promptId:n,content:o,retrievedAt:(new Date).toISOString()})}]}}catch(e){return this.logAccess(t,s,!1),{content:[{type:"text",text:JSON.stringify({success:!1,error:`Failed to retrieve prompt: ${e.message}`,code:"RETRIEVAL_ERROR"})}]}}}async handleListProtectedAgents(e){const{token:t}=e;if(!this.validateToken(t))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_FAILED"})}]};try{const e=path.join(process.cwd(),"protected-prompts");if(!fs.existsSync(e))return{content:[{type:"text",text:JSON.stringify({success:!0,agents:[],message:"No protected agents directory found"})}]};const t=fs.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(t=>{const s=path.join(e,t.name),n=fs.readdirSync(s).filter(e=>e.endsWith(".md")).map(e=>e.replace(".md",""));return{name:t.name,promptCount:n.length,prompts:n}});return{content:[{type:"text",text:JSON.stringify({success:!0,agents:t,totalAgents:t.length,accessLogs:this.accessLogs.slice(-10)})}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Failed to list agents: ${e.message}`,code:"LIST_ERROR"})}]}}}async run(){const e=new stdio_js_1.StdioServerTransport;await this.server.connect(e)}}exports.BlueLampProtectionSystem=BlueLampProtectionSystem,require.main===module&&new BlueLampProtectionSystem;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(t,e,s,n){void 0===n&&(n=s);var r=Object.getOwnPropertyDescriptor(e,s);r&&!("get"in r?!e.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return e[s]}}),Object.defineProperty(t,n,r)}:function(t,e,s,n){void 0===n&&(n=s),t[n]=e[s]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),__importStar=this&&this.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(t){var e=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[e.length]=s);return e},t(e)};return function(e){if(e&&e.__esModule)return e;var s={};if(null!=e)for(var n=t(e),r=0;r<n.length;r++)"default"!==n[r]&&__createBinding(s,e,n[r]);return __setModuleDefault(s,e),s}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlueLampProtectionSystem=void 0;const index_js_1=require("@modelcontextprotocol/sdk/server/index.js"),stdio_js_1=require("@modelcontextprotocol/sdk/server/stdio.js"),types_js_1=require("@modelcontextprotocol/sdk/types.js"),fs=__importStar(require("fs")),path=__importStar(require("path"));class BlueLampProtectionSystem{constructor(){this.server=new index_js_1.Server({name:"bluelamp-protection-system",version:"1.0.0"},{capabilities:{tools:{}}}),this.validTokens=new Set,this.accessLogs=[],this.initializeTokens(),this.setupHandlers()}initializeTokens(){const t=process.env.BLUELAMP_TOKEN;t&&this.validTokens.add(t),this.validTokens.add("test-token-12345"),this.validTokens.add("bluelamp-secure-token-67890")}setupHandlers(){this.server.setRequestHandler(types_js_1.ListToolsRequestSchema,async()=>({tools:[{name:"authenticate_agent",description:"Authenticate access to protected agent",inputSchema:{type:"object",properties:{token:{type:"string",description:"Authentication token"},agentName:{type:"string",description:"Name of the agent to access"}},required:["token","agentName"]}},{name:"get_protected_prompt",description:"Get protected prompt for authenticated agent",inputSchema:{type:"object",properties:{token:{type:"string",description:"Authentication token"},agentName:{type:"string",description:"Name of the agent"},promptId:{type:"string",description:"ID of the prompt to retrieve"}},required:["token","agentName","promptId"]}},{name:"list_protected_agents",description:"List all protected agents available",inputSchema:{type:"object",properties:{token:{type:"string",description:"Authentication token"}},required:["token"]}}]})),this.server.setRequestHandler(types_js_1.CallToolRequestSchema,async t=>{const{name:e,arguments:s}=t.params;try{switch(e){case"authenticate_agent":return await this.handleAuthenticateAgent(s);case"get_protected_prompt":return await this.handleGetProtectedPrompt(s);case"list_protected_agents":return await this.handleListProtectedAgents(s);default:throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound,`Unknown tool: ${e}`)}}catch(t){if(t instanceof types_js_1.McpError)throw t;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`Tool execution failed: ${e}: ${t}`)}})}validateToken(t){return this.validTokens.has(t)}logAccess(t,e,s){this.accessLogs.push({timestamp:new Date,token:t.substring(0,8)+"...",agentName:e,success:s}),this.accessLogs.length>100&&(this.accessLogs=this.accessLogs.slice(-100))}async handleAuthenticateAgent(t){const{token:e,agentName:s}=t;return this.validateToken(e)?(this.logAccess(e,s,!0),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Authentication successful for agent: ${s}`,sessionId:`session_${Date.now()}`,expiresAt:new Date(Date.now()+36e5).toISOString()})}]}):(this.logAccess(e,s,!1),{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_FAILED"})}]})}async handleGetProtectedPrompt(t){const{token:e,agentName:s,promptId:n}=t;if(!this.validateToken(e))return this.logAccess(e,s,!1),{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_FAILED"})}]};try{const t=path.join(process.cwd(),"protected-prompts",s),r=path.join(t,`${n}.md`);if(!fs.existsSync(r))return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Prompt not found: ${n} for agent: ${s}`,code:"PROMPT_NOT_FOUND"})}]};const o=fs.readFileSync(r,"utf-8");return this.logAccess(e,s,!0),{content:[{type:"text",text:JSON.stringify({success:!0,agentName:s,promptId:n,content:o,retrievedAt:(new Date).toISOString()})}]}}catch(t){this.logAccess(e,s,!1);const n=t instanceof Error?t.message:String(t);return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Failed to retrieve prompt: ${n}`,code:"RETRIEVAL_ERROR"})}]}}}async handleListProtectedAgents(t){const{token:e}=t;if(!this.validateToken(e))return{content:[{type:"text",text:JSON.stringify({success:!1,error:"Invalid authentication token",code:"AUTH_FAILED"})}]};try{const t=path.join(process.cwd(),"protected-prompts");if(!fs.existsSync(t))return{content:[{type:"text",text:JSON.stringify({success:!0,agents:[],message:"No protected agents directory found"})}]};const e=fs.readdirSync(t,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(e=>{const s=path.join(t,e.name),n=fs.readdirSync(s).filter(t=>t.endsWith(".md")).map(t=>t.replace(".md",""));return{name:e.name,promptCount:n.length,prompts:n}});return{content:[{type:"text",text:JSON.stringify({success:!0,agents:e,totalAgents:e.length,accessLogs:this.accessLogs.slice(-10)})}]}}catch(t){const e=t instanceof Error?t.message:String(t);return{content:[{type:"text",text:JSON.stringify({success:!1,error:`Failed to list agents: ${e}`,code:"LIST_ERROR"})}]}}}async run(){const t=new stdio_js_1.StdioServerTransport;await this.server.connect(t)}}exports.BlueLampProtectionSystem=BlueLampProtectionSystem,require.main===module&&new BlueLampProtectionSystem;
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(t,e,r,i){void 0===i&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);s&&!("get"in s?!e.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){void 0===i&&(i=r),t[i]=e[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),__importStar=this&&this.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[e.length]=r);return e},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var i=t(e),s=0;s<i.length;s++)"default"!==i[s]&&__createBinding(r,e,i[s]);return __setModuleDefault(r,e),r}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.CryptoUtils=void 0;const crypto=__importStar(require("crypto")),fs=__importStar(require("fs")),path=__importStar(require("path"));class CryptoUtils{static deriveKey(t,e){return crypto.pbkdf2Sync(t,e,this.iterations,this.keyLength,"sha256")}static encryptFile(t,e,r){const i=fs.readFileSync(t,"utf-8"),s=crypto.randomBytes(this.saltLength),n=crypto.randomBytes(this.ivLength),c=this.deriveKey(r,s),o=crypto.createCipheriv(this.algorithm,c,n),a=Buffer.concat([o.update(i,"utf8"),o.final()]),l=o.getAuthTag(),p=Buffer.concat([s,n,l,a]);fs.writeFileSync(e,p)}static decryptFile(t,e){const r=fs.readFileSync(t);let i=0;const s=r.slice(i,i+this.saltLength);i+=this.saltLength;const n=r.slice(i,i+this.ivLength);i+=this.ivLength;const c=r.slice(i,i+this.tagLength);i+=this.tagLength;const o=r.slice(i),a=this.deriveKey(e,s),l=crypto.createDecipheriv(this.algorithm,a,n);return l.setAuthTag(c),Buffer.concat([l.update(o),l.final()]).toString("utf-8")}static encryptString(t,e,r){const i=crypto.randomBytes(this.saltLength),s=crypto.randomBytes(this.ivLength),n=this.deriveKey(r,i),c=crypto.createCipheriv(this.algorithm,n,s),o=Buffer.concat([c.update(t,"utf8"),c.final()]),a=c.getAuthTag(),l=Buffer.concat([i,s,a,o]);fs.writeFileSync(e,l)}static async encryptPerformerDemo(){const t="/Users/tatsuya/Desktop/マルチエージェントウェブ/mcp-sample-server/secure-prompts",e=path.join(t,"performer-protected.enc");fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0});const r=process.env.BLUELAMP_ENCRYPTION_KEY||"demo-encryption-password-2024";try{this.encryptFile("/Users/tatsuya/Desktop/マルチエージェントウェブ/.claude/agents/core/パフォーマー.md",e,r),fs.statSync(e),fs.readFileSync(e).slice(0,100),this.decryptFile(e,r)}catch(t){throw t}}}exports.CryptoUtils=CryptoUtils,CryptoUtils.algorithm="aes-256-gcm",CryptoUtils.saltLength=32,CryptoUtils.tagLength=16,CryptoUtils.ivLength=16,CryptoUtils.iterations=1e5,CryptoUtils.keyLength=32;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(t,e,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(e,r);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,n)}:function(t,e,r,i){void 0===i&&(i=r),t[i]=e[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),__importStar=this&&this.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[e.length]=r);return e},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var i=t(e),n=0;n<i.length;n++)"default"!==i[n]&&__createBinding(r,e,i[n]);return __setModuleDefault(r,e),r}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.CryptoUtils=void 0;const crypto=__importStar(require("crypto")),fs=__importStar(require("fs")),path=__importStar(require("path")),EncryptionKeyManager_1=require("./security/EncryptionKeyManager");class CryptoUtils{static deriveKey(t,e){return crypto.pbkdf2Sync(t,e,this.iterations,this.keyLength,"sha256")}static encryptFile(t,e,r){const i=fs.readFileSync(t,"utf-8"),n=crypto.randomBytes(this.saltLength),s=crypto.randomBytes(this.ivLength),c=this.deriveKey(r,n),a=crypto.createCipheriv(this.algorithm,c,s),o=Buffer.concat([a.update(i,"utf8"),a.final()]),y=a.getAuthTag(),p=Buffer.concat([n,s,y,o]);fs.writeFileSync(e,p)}static decryptFile(t,e){const r=fs.readFileSync(t);let i=0;const n=r.slice(i,i+this.saltLength);i+=this.saltLength;const s=r.slice(i,i+this.ivLength);i+=this.ivLength;const c=r.slice(i,i+this.tagLength);i+=this.tagLength;const a=r.slice(i),o=this.deriveKey(e,n),y=crypto.createDecipheriv(this.algorithm,o,s);return y.setAuthTag(c),Buffer.concat([y.update(a),y.final()]).toString("utf-8")}static encryptString(t,e,r){const i=crypto.randomBytes(this.saltLength),n=crypto.randomBytes(this.ivLength),s=this.deriveKey(r,i),c=crypto.createCipheriv(this.algorithm,s,n),a=Buffer.concat([c.update(t,"utf8"),c.final()]),o=c.getAuthTag(),y=Buffer.concat([i,n,o,a]);fs.writeFileSync(e,y)}static async encryptPerformerDemo(){const t="/Users/tatsuya/Desktop/マルチエージェントウェブ/mcp-sample-server/secure-prompts",e=path.join(t,"performer-protected.enc");fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0});const r=EncryptionKeyManager_1.EncryptionKeyManager.getEncryptionKey();try{this.encryptFile("/Users/tatsuya/Desktop/マルチエージェントウェブ/.claude/agents/core/パフォーマー.md",e,r),fs.statSync(e),fs.readFileSync(e).slice(0,100),this.decryptFile(e,r)}catch(t){throw t}}}exports.CryptoUtils=CryptoUtils,CryptoUtils.algorithm="aes-256-gcm",CryptoUtils.saltLength=32,CryptoUtils.tagLength=16,CryptoUtils.ivLength=16,CryptoUtils.iterations=1e5,CryptoUtils.keyLength=32;
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PromptDatabase=exports.DatabaseMCPServer=void 0;const index_js_1=require("@modelcontextprotocol/sdk/server/index.js"),stdio_js_1=require("@modelcontextprotocol/sdk/server/stdio.js"),types_js_1=require("@modelcontextprotocol/sdk/types.js");function debugLog(e,t){}class PromptDatabase{constructor(){}initializeDatabase(){debugLog("データベーススキーマ初期化",{schema:"\n CREATE TABLE IF NOT EXISTS prompts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n uri TEXT UNIQUE NOT NULL,\n title TEXT NOT NULL,\n content TEXT NOT NULL,\n category TEXT DEFAULT 'general',\n tags TEXT DEFAULT '',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n );\n\n CREATE INDEX IF NOT EXISTS idx_prompts_category ON prompts(category);\n CREATE INDEX IF NOT EXISTS idx_prompts_uri ON prompts(uri);\n CREATE VIRTUAL TABLE IF NOT EXISTS prompts_fts USING fts5(\n title, content, tags, content='prompts', content_rowid='id'\n );\n "})}async searchPrompts(e,t,r=10){debugLog("プロンプト検索",{query:e,category:t,limit:r});let s=[{id:1,uri:"prompt://sample/greeting",title:"挨拶プロンプト",content:"こんにちは!私はAIアシスタントです。",category:"general",tags:"挨拶,基本",created_at:(new Date).toISOString(),updated_at:(new Date).toISOString()},{id:2,uri:"prompt://sample/analysis",title:"分析プロンプト",content:"データを詳細に分析し、洞察を提供します。",category:"analysis",tags:"分析,データ",created_at:(new Date).toISOString(),updated_at:(new Date).toISOString()}];if(t&&(s=s.filter(e=>e.category===t)),e){const t=e.toLowerCase();s=s.filter(e=>e.title.toLowerCase().includes(t)||e.content.toLowerCase().includes(t)||e.tags.toLowerCase().includes(t))}return s.slice(0,r)}async getPromptByUri(e){return debugLog("URI検索",{uri:e}),(await this.searchPrompts()).find(t=>t.uri===e)||null}async addPrompt(e){return debugLog("プロンプト追加",e),{id:Date.now(),uri:e.uri,title:e.title,content:e.content,category:e.category||"general",tags:e.tags||"",created_at:(new Date).toISOString(),updated_at:(new Date).toISOString()}}async getCategories(){return debugLog("カテゴリ一覧取得"),["general","analysis","creative","technical"]}}exports.PromptDatabase=PromptDatabase;class DatabaseMCPServer{constructor(){this.server=new index_js_1.Server({name:"database-mcp-server",version:"1.0.0"},{capabilities:{resources:{},tools:{}}}),this.database=new PromptDatabase,this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema,async()=>{debugLog("リソース一覧要求");try{const e=(await this.database.searchPrompts()).map(e=>({uri:e.uri,name:e.title,description:`${e.category} - ${e.content.substring(0,100)}...`,mimeType:"text/plain"}));return debugLog("リソース一覧応答",{count:e.length}),{resources:e}}catch(e){return debugLog("リソース一覧エラー",{error:e.message}),{resources:[]}}}),this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema,async e=>{const{uri:t}=e.params;debugLog("リソース読み取り要求",{uri:t});try{const e=await this.database.getPromptByUri(t);if(!e)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest,`プロンプトが見つかりません: ${t}`);return debugLog("リソース読み取り成功",{uri:t,title:e.title}),{contents:[{uri:e.uri,mimeType:"text/plain",text:e.content}]}}catch(e){if(debugLog("リソース読み取りエラー",{uri:t,error:e.message}),e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`リソース読み取りエラー: ${e.message}`)}}),this.server.setRequestHandler(types_js_1.ListToolsRequestSchema,async()=>(debugLog("ツール一覧要求"),{tools:[{name:"search_prompts",description:"データベースからプロンプトを検索します",inputSchema:{type:"object",properties:{query:{type:"string",description:"検索クエリ(タイトル、内容、タグを対象)"},category:{type:"string",description:"カテゴリでフィルタ"},limit:{type:"number",description:"取得件数の上限",default:10}},required:[]}},{name:"add_prompt",description:"データベースに新しいプロンプトを追加します",inputSchema:{type:"object",properties:{uri:{type:"string",description:"プロンプトのURI"},title:{type:"string",description:"プロンプトのタイトル"},content:{type:"string",description:"プロンプトの内容"},category:{type:"string",description:"カテゴリ",default:"general"},tags:{type:"string",description:"タグ(カンマ区切り)"}},required:["uri","title","content"]}},{name:"get_categories",description:"利用可能なカテゴリ一覧を取得します",inputSchema:{type:"object",properties:{},required:[]}}]})),this.server.setRequestHandler(types_js_1.CallToolRequestSchema,async e=>{const{name:t,arguments:r}=e.params;debugLog(`ツール実行要求: ${t}`,r);try{switch(t){case"search_prompts":return await this.handleSearchPrompts(r||{});case"add_prompt":return await this.handleAddPrompt(r);case"get_categories":return await this.handleGetCategories();default:throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound,`不明なツール: ${t}`)}}catch(e){if(debugLog("ツール実行エラー",{name:t,error:e.message}),e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`ツール実行エラー: ${e.message}`)}})}async handleSearchPrompts(e){const{query:t,category:r,limit:s=10}=e;debugLog("プロンプト検索実行",{query:t,category:r,limit:s});try{const e=await this.database.searchPrompts(t,r,s),a={type:"text",text:`検索結果: ${e.length}件\n\n`+e.map(e=>`【${e.title}】\nURI: ${e.uri}\nカテゴリ: ${e.category}\n内容: ${e.content.substring(0,100)}...\nタグ: ${e.tags}\n`).join("\n")};return debugLog("プロンプト検索完了",{count:e.length}),{content:[a]}}catch(e){throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`検索エラー: ${e.message}`)}}async handleAddPrompt(e){const{uri:t,title:r,content:s,category:a,tags:o}=e;if(!t||!r||!s)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,"uri, title, contentは必須です");debugLog("プロンプト追加実行",{uri:t,title:r,category:a});try{const e=await this.database.addPrompt({uri:t,title:r,content:s,category:a,tags:o}),n={type:"text",text:`プロンプトを追加しました:\n\n【${e.title}】\nURI: ${e.uri}\nカテゴリ: ${e.category}\nID: ${e.id}\n作成日時: ${e.created_at}`};return debugLog("プロンプト追加完了",{id:e.id,uri:e.uri}),{content:[n]}}catch(e){throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`追加エラー: ${e.message}`)}}async handleGetCategories(){debugLog("カテゴリ一覧取得実行");try{const e=await this.database.getCategories(),t={type:"text",text:"利用可能なカテゴリ:\n\n"+e.map(e=>`- ${e}`).join("\n")};return debugLog("カテゴリ一覧取得完了",{count:e.length}),{content:[t]}}catch(e){throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`カテゴリ取得エラー: ${e.message}`)}}async run(){debugLog("データベース版MCPサーバー開始");const e=new stdio_js_1.StdioServerTransport;await this.server.connect(e),debugLog("データベース版MCPサーバー接続完了")}}exports.DatabaseMCPServer=DatabaseMCPServer,require.main===module&&(new DatabaseMCPServer).run().catch(e=>{process.exit(1)});
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PromptDatabase=exports.DatabaseMCPServer=void 0;const index_js_1=require("@modelcontextprotocol/sdk/server/index.js"),stdio_js_1=require("@modelcontextprotocol/sdk/server/stdio.js"),types_js_1=require("@modelcontextprotocol/sdk/types.js");function debugLog(e,t){}class PromptDatabase{constructor(){}initializeDatabase(){debugLog("データベーススキーマ初期化",{schema:"\n CREATE TABLE IF NOT EXISTS prompts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n uri TEXT UNIQUE NOT NULL,\n title TEXT NOT NULL,\n content TEXT NOT NULL,\n category TEXT DEFAULT 'general',\n tags TEXT DEFAULT '',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n );\n\n CREATE INDEX IF NOT EXISTS idx_prompts_category ON prompts(category);\n CREATE INDEX IF NOT EXISTS idx_prompts_uri ON prompts(uri);\n CREATE VIRTUAL TABLE IF NOT EXISTS prompts_fts USING fts5(\n title, content, tags, content='prompts', content_rowid='id'\n );\n "})}async searchPrompts(e,t,r=10){debugLog("プロンプト検索",{query:e,category:t,limit:r});let s=[{id:1,uri:"prompt://sample/greeting",title:"挨拶プロンプト",content:"こんにちは!私はAIアシスタントです。",category:"general",tags:"挨拶,基本",created_at:(new Date).toISOString(),updated_at:(new Date).toISOString()},{id:2,uri:"prompt://sample/analysis",title:"分析プロンプト",content:"データを詳細に分析し、洞察を提供します。",category:"analysis",tags:"分析,データ",created_at:(new Date).toISOString(),updated_at:(new Date).toISOString()}];if(t&&(s=s.filter(e=>e.category===t)),e){const t=e.toLowerCase();s=s.filter(e=>e.title.toLowerCase().includes(t)||e.content.toLowerCase().includes(t)||e.tags.toLowerCase().includes(t))}return s.slice(0,r)}async getPromptByUri(e){return debugLog("URI検索",{uri:e}),(await this.searchPrompts()).find(t=>t.uri===e)||null}async addPrompt(e){return debugLog("プロンプト追加",e),{id:Date.now(),uri:e.uri,title:e.title,content:e.content,category:e.category||"general",tags:e.tags||"",created_at:(new Date).toISOString(),updated_at:(new Date).toISOString()}}async getCategories(){return debugLog("カテゴリ一覧取得"),["general","analysis","creative","technical"]}}exports.PromptDatabase=PromptDatabase;class DatabaseMCPServer{constructor(){this.server=new index_js_1.Server({name:"database-mcp-server",version:"1.0.0"},{capabilities:{resources:{},tools:{}}}),this.database=new PromptDatabase,this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema,async()=>{debugLog("リソース一覧要求");try{const e=(await this.database.searchPrompts()).map(e=>({uri:e.uri,name:e.title,description:`${e.category} - ${e.content.substring(0,100)}...`,mimeType:"text/plain"}));return debugLog("リソース一覧応答",{count:e.length}),{resources:e}}catch(e){return debugLog("リソース一覧エラー",{error:e instanceof Error?e.message:String(e)}),{resources:[]}}}),this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema,async e=>{const{uri:t}=e.params;debugLog("リソース読み取り要求",{uri:t});try{const e=await this.database.getPromptByUri(t);if(!e)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest,`プロンプトが見つかりません: ${t}`);return debugLog("リソース読み取り成功",{uri:t,title:e.title}),{contents:[{uri:e.uri,mimeType:"text/plain",text:e.content}]}}catch(e){const r=e instanceof Error?e.message:String(e);if(debugLog("リソース読み取りエラー",{uri:t,error:r}),e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`リソース読み取りエラー: ${r}`)}}),this.server.setRequestHandler(types_js_1.ListToolsRequestSchema,async()=>(debugLog("ツール一覧要求"),{tools:[{name:"search_prompts",description:"データベースからプロンプトを検索します",inputSchema:{type:"object",properties:{query:{type:"string",description:"検索クエリ(タイトル、内容、タグを対象)"},category:{type:"string",description:"カテゴリでフィルタ"},limit:{type:"number",description:"取得件数の上限",default:10}},required:[]}},{name:"add_prompt",description:"データベースに新しいプロンプトを追加します",inputSchema:{type:"object",properties:{uri:{type:"string",description:"プロンプトのURI"},title:{type:"string",description:"プロンプトのタイトル"},content:{type:"string",description:"プロンプトの内容"},category:{type:"string",description:"カテゴリ",default:"general"},tags:{type:"string",description:"タグ(カンマ区切り)"}},required:["uri","title","content"]}},{name:"get_categories",description:"利用可能なカテゴリ一覧を取得します",inputSchema:{type:"object",properties:{},required:[]}}]})),this.server.setRequestHandler(types_js_1.CallToolRequestSchema,async e=>{const{name:t,arguments:r}=e.params;debugLog(`ツール実行要求: ${t}`,r);try{switch(t){case"search_prompts":return await this.handleSearchPrompts(r||{});case"add_prompt":return await this.handleAddPrompt(r);case"get_categories":return await this.handleGetCategories();default:throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound,`不明なツール: ${t}`)}}catch(e){const r=e instanceof Error?e.message:String(e);if(debugLog("ツール実行エラー",{name:t,error:r}),e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`ツール実行エラー: ${r}`)}})}async handleSearchPrompts(e){const{query:t,category:r,limit:s=10}=e;debugLog("プロンプト検索実行",{query:t,category:r,limit:s});try{const e=await this.database.searchPrompts(t,r,s),n={type:"text",text:`検索結果: ${e.length}件\n\n`+e.map(e=>`【${e.title}】\nURI: ${e.uri}\nカテゴリ: ${e.category}\n内容: ${e.content.substring(0,100)}...\nタグ: ${e.tags}\n`).join("\n")};return debugLog("プロンプト検索完了",{count:e.length}),{content:[n]}}catch(e){const t=e instanceof Error?e.message:String(e);throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`検索エラー: ${t}`)}}async handleAddPrompt(e){const{uri:t,title:r,content:s,category:n,tags:o}=e;if(!t||!r||!s)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,"uri, title, contentは必須です");debugLog("プロンプト追加実行",{uri:t,title:r,category:n});try{const e=await this.database.addPrompt({uri:t,title:r,content:s,category:n,tags:o}),a={type:"text",text:`プロンプトを追加しました:\n\n【${e.title}】\nURI: ${e.uri}\nカテゴリ: ${e.category}\nID: ${e.id}\n作成日時: ${e.created_at}`};return debugLog("プロンプト追加完了",{id:e.id,uri:e.uri}),{content:[a]}}catch(e){const t=e instanceof Error?e.message:String(e);throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`追加エラー: ${t}`)}}async handleGetCategories(){debugLog("カテゴリ一覧取得実行");try{const e=await this.database.getCategories(),t={type:"text",text:"利用可能なカテゴリ:\n\n"+e.map(e=>`- ${e}`).join("\n")};return debugLog("カテゴリ一覧取得完了",{count:e.length}),{content:[t]}}catch(e){const t=e instanceof Error?e.message:String(e);throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`カテゴリ取得エラー: ${t}`)}}async run(){debugLog("データベース版MCPサーバー開始");const e=new stdio_js_1.StdioServerTransport;await this.server.connect(e),debugLog("データベース版MCPサーバー接続完了")}}exports.DatabaseMCPServer=DatabaseMCPServer,require.main===module&&(new DatabaseMCPServer).run().catch(e=>{process.exit(1)});
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var n=e(t),s=0;s<n.length;s++)"default"!==n[s]&&__createBinding(r,t,n[s]);return __setModuleDefault(r,t),r}}();Object.defineProperty(exports,"__esModule",{value:!0});const index_js_1=require("@modelcontextprotocol/sdk/server/index.js"),stdio_js_1=require("@modelcontextprotocol/sdk/server/stdio.js"),types_js_1=require("@modelcontextprotocol/sdk/types.js"),plugin_manager_js_1=require("./plugins/plugin-manager.js");function debugLog(e,t){}class SampleMCPServer{constructor(){this.server=new index_js_1.Server({name:"bluelamp-mcp-server",version:"1.2.0"},{capabilities:{tools:{},resources:{}}}),this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema,async()=>(debugLog("リソース一覧要求"),{resources:[]})),this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema,async e=>{const{uri:t}=e.params;throw debugLog("リソース読み取り要求",{uri:t}),new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest,`リソースが見つかりません: ${t}`)}),this.server.setRequestHandler(types_js_1.ListToolsRequestSchema,async()=>{debugLog("ツール一覧要求");const e=[{name:"get_current_time",description:"現在の日時を取得します",inputSchema:{type:"object",properties:{timezone:{type:"string",description:"タイムゾーン (例: Asia/Tokyo)",default:"Asia/Tokyo"}},required:[]}},{name:"calculate",description:"数学的な計算を実行します",inputSchema:{type:"object",properties:{expression:{type:"string",description:"計算式 (例: 2 + 3 * 4)"}},required:["expression"]}},{name:"echo",description:"メッセージをそのまま返します",inputSchema:{type:"object",properties:{message:{type:"string",description:"返すメッセージ"}},required:["message"]}},{name:"inject_knowledge",description:"Portal APIから専門知識を注入します",inputSchema:{type:"object",properties:{keyword:{type:"string",description:"注入する知識のキーワード",enum:["オーケストレーター","要件定義質問テンプレート","要件定義","デザイナー","デザイン設計","UIUX","本番環境準備ガイドテンプレート","データ設計","デプロイ","GitHub","実装計画","プロトタイプ","検証","バックエンド","総合テスト","テスター","フロントエンド","認証追加テンプレート","ブルーランプ","ディレクトリ構造"]},context:{type:"string",description:"追加のコンテキスト情報"},token:{type:"string",description:"Portal APIトークン(省略時は自動取得)",default:"auto"}},required:["keyword"]}}];let t=[];try{plugin_manager_js_1.pluginManager&&(t=plugin_manager_js_1.pluginManager.getAvailableTools(),debugLog(`プラグインツール取得完了: ${t.length}個`))}catch(e){debugLog("プラグインツール取得エラー",e)}const r=[...e,...t];return debugLog(`全ツール数: ${r.length} (基本: ${e.length}, プラグイン: ${t.length})`),{tools:r}}),this.server.setRequestHandler(types_js_1.CallToolRequestSchema,async e=>{const{name:t,arguments:r}=e.params;debugLog(`ツール実行要求: ${t}`,r);try{switch(t){case"get_current_time":return await this.handleGetCurrentTime(r||{});case"calculate":return await this.handleCalculate(r||{});case"echo":return await this.handleEcho(r||{});case"inject_knowledge":return await this.handleInjectKnowledge(r||{})}const e=await this.handlePluginTool(t,r);if(e)return e;throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound,`不明なツール: ${t}`)}catch(e){if(debugLog("ツール実行エラー",{name:t,error:e.message}),e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`ツール実行中にエラーが発生しました: ${e.message}`)}})}async handleGetCurrentTime(e){const{timezone:t="Asia/Tokyo"}=e;debugLog("現在時刻取得",{timezone:t});try{const e=(new Date).toLocaleString("ja-JP",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),r={type:"text",text:`現在の日時: ${e} (${t})`};return debugLog("現在時刻取得完了",{timeString:e,timezone:t}),{content:[r]}}catch(e){throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`時刻取得エラー: ${e.message}`)}}async handleCalculate(e){const{expression:t}=e;if(!t)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,"計算式が指定されていません");debugLog("計算実行",{expression:t});try{const e=t.replace(/[^0-9+\-*/().\s]/g,"");if(e!==t)throw new Error("無効な文字が含まれています");const r=Function(`"use strict"; return (${e})`)(),n={type:"text",text:`計算結果: ${t} = ${r}`};return debugLog("計算完了",{expression:t,result:r}),{content:[n]}}catch(e){throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,`計算エラー: ${e.message}`)}}async handleEcho(e){const{message:t}=e;if(!t)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,"メッセージが指定されていません");debugLog("エコー実行",{message:t});const r={type:"text",text:`エコー: ${t}`};return debugLog("エコー完了",{message:t}),{content:[r]}}async handleInjectKnowledge(e){const{keyword:t,token:r="auto"}=e;if(!t)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,"キーワードが指定されていません");debugLog("Knowledge Injection実行",{keyword:t,token:r});Date.now();try{const{spawn:e}=await Promise.resolve().then(()=>__importStar(require("child_process"))),n="/Users/tatsuya/Desktop/bluelamp-test/knowledge-injection/hooks/inject-encrypted.sh",s={...process.env};"auto"!==r&&(s.PORTAL_TOKEN=r),s.KNOWLEDGE_KEYWORD=t,debugLog("スクリプト実行開始",{scriptPath:n,keyword:t});const o=e("bash",[n],{env:s,stdio:["pipe","pipe","pipe"]});let a="",i="";o.stdout.on("data",e=>{a+=e.toString()}),o.stderr.on("data",e=>{i+=e.toString()});const c=await new Promise(e=>{o.on("close",e)});if(debugLog("スクリプト実行完了",{exitCode:c,stdout:a.substring(0,200),stderr:i.substring(0,200)}),Date.now(),0===c)return{content:[{type:"text",text:`Knowledge Injection成功: "${t}" の知識が注入されました。\n\n実行結果:\n${a}\n\n統計記録: ⚠️ スキップ`}]};throw new Error(`スクリプト実行失敗 (exit code: ${c})\nstderr: ${i}`)}catch(e){throw debugLog("Knowledge Injectionエラー",{keyword:t,error:e.message}),new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`Knowledge Injection実行エラー: ${e.message}`)}}async handlePluginTool(e,t){try{if(!plugin_manager_js_1.pluginManager)return null;if(!plugin_manager_js_1.pluginManager.getAvailableTools().find(t=>t.name===e))return null;debugLog(`プラグインツール実行: ${e}`,t);const r={userId:"current_user",service:"leonardo",apiKey:process.env.LEONARDO_API_KEY,settings:{}};let n="leonardo";e.startsWith("leonardo_")?n="leonardo":e.startsWith("notion_")?n="notion":e.startsWith("slack_")&&(n="slack");const s=await plugin_manager_js_1.pluginManager.executePlugin(n,e,t,r);if(s.success)return debugLog(`プラグインツール実行成功: ${e}`),{content:s.content,_meta:s.metadata};throw debugLog(`プラグインツール実行失敗: ${e}`,s.error),new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`プラグインツール実行エラー: ${s.error}`)}catch(t){if(debugLog(`プラグインツール処理エラー: ${e}`,t),t instanceof types_js_1.McpError)throw t;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`プラグイン処理中にエラーが発生しました: ${t.message}`)}}async run(){debugLog("MCPサーバー開始");try{await plugin_manager_js_1.pluginManager.initialize(),debugLog("プラグインマネージャー初期化完了")}catch(e){debugLog("プラグインマネージャー初期化エラー",e)}const e=new stdio_js_1.StdioServerTransport;await this.server.connect(e),debugLog("MCPサーバー接続完了")}}const server=new SampleMCPServer;server.run().catch(e=>{process.exit(1)});
2
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var n=e(t),s=0;s<n.length;s++)"default"!==n[s]&&__createBinding(r,t,n[s]);return __setModuleDefault(r,t),r}}();Object.defineProperty(exports,"__esModule",{value:!0});const index_js_1=require("@modelcontextprotocol/sdk/server/index.js"),stdio_js_1=require("@modelcontextprotocol/sdk/server/stdio.js"),types_js_1=require("@modelcontextprotocol/sdk/types.js"),plugin_manager_js_1=require("./plugins/plugin-manager.js");function getErrorMessage(e){return e instanceof Error?e.message:String(e)}function debugLog(e,t){}class SampleMCPServer{constructor(){this.server=new index_js_1.Server({name:"bluelamp-mcp-server",version:"1.2.0"},{capabilities:{tools:{},resources:{}}}),this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema,async()=>(debugLog("リソース一覧要求"),{resources:[]})),this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema,async e=>{const{uri:t}=e.params;throw debugLog("リソース読み取り要求",{uri:t}),new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest,`リソースが見つかりません: ${t}`)}),this.server.setRequestHandler(types_js_1.ListToolsRequestSchema,async()=>{debugLog("ツール一覧要求");const e=[{name:"get_current_time",description:"現在の日時を取得します",inputSchema:{type:"object",properties:{timezone:{type:"string",description:"タイムゾーン (例: Asia/Tokyo)",default:"Asia/Tokyo"}},required:[]}},{name:"calculate",description:"数学的な計算を実行します",inputSchema:{type:"object",properties:{expression:{type:"string",description:"計算式 (例: 2 + 3 * 4)"}},required:["expression"]}},{name:"echo",description:"メッセージをそのまま返します",inputSchema:{type:"object",properties:{message:{type:"string",description:"返すメッセージ"}},required:["message"]}},{name:"inject_knowledge",description:"Portal APIから専門知識を注入します",inputSchema:{type:"object",properties:{keyword:{type:"string",description:"注入する知識のキーワード",enum:["オーケストレーター","要件定義質問テンプレート","要件定義","デザイナー","デザイン設計","UIUX","本番環境準備ガイドテンプレート","データ設計","デプロイ","GitHub","実装計画","プロトタイプ","検証","バックエンド","総合テスト","テスター","フロントエンド","認証追加テンプレート","ブルーランプ","ディレクトリ構造"]},context:{type:"string",description:"追加のコンテキスト情報"},token:{type:"string",description:"Portal APIトークン(省略時は自動取得)",default:"auto"}},required:["keyword"]}}];let t=[];try{plugin_manager_js_1.pluginManager&&(t=plugin_manager_js_1.pluginManager.getAvailableTools(),debugLog(`プラグインツール取得完了: ${t.length}個`))}catch(e){debugLog("プラグインツール取得エラー",e)}const r=[...e,...t];return debugLog(`全ツール数: ${r.length} (基本: ${e.length}, プラグイン: ${t.length})`),{tools:r}}),this.server.setRequestHandler(types_js_1.CallToolRequestSchema,async e=>{const{name:t,arguments:r}=e.params;debugLog(`ツール実行要求: ${t}`,r);try{switch(t){case"get_current_time":return await this.handleGetCurrentTime(r||{});case"calculate":return await this.handleCalculate(r||{});case"echo":return await this.handleEcho(r||{});case"inject_knowledge":return await this.handleInjectKnowledge(r||{})}const e=await this.handlePluginTool(t,r||{});if(e)return e;throw new types_js_1.McpError(types_js_1.ErrorCode.MethodNotFound,`不明なツール: ${t}`)}catch(e){if(debugLog("ツール実行エラー",{name:t,error:getErrorMessage(e)}),e instanceof types_js_1.McpError)throw e;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`ツール実行中にエラーが発生しました: ${getErrorMessage(e)}`)}})}async handleGetCurrentTime(e){const{timezone:t="Asia/Tokyo"}=e;debugLog("現在時刻取得",{timezone:t});try{const e=(new Date).toLocaleString("ja-JP",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),r={type:"text",text:`現在の日時: ${e} (${t})`};return debugLog("現在時刻取得完了",{timeString:e,timezone:t}),{content:[r]}}catch(e){throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`時刻取得エラー: ${getErrorMessage(e)}`)}}async handleCalculate(e){const{expression:t}=e;if(!t)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,"計算式が指定されていません");debugLog("計算実行",{expression:t});try{const e=t.replace(/[^0-9+\-*/().\s]/g,"");if(e!==t)throw new Error("無効な文字が含まれています");const r=Function(`"use strict"; return (${e})`)(),n={type:"text",text:`計算結果: ${t} = ${r}`};return debugLog("計算完了",{expression:t,result:r}),{content:[n]}}catch(e){throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,`計算エラー: ${getErrorMessage(e)}`)}}async handleEcho(e){const{message:t}=e;if(!t)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,"メッセージが指定されていません");debugLog("エコー実行",{message:t});const r={type:"text",text:`エコー: ${t}`};return debugLog("エコー完了",{message:t}),{content:[r]}}async handleInjectKnowledge(e){const{keyword:t,token:r="auto"}=e;if(!t)throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams,"キーワードが指定されていません");debugLog("Knowledge Injection実行",{keyword:t,token:r});Date.now();try{const{spawn:e}=await Promise.resolve().then(()=>__importStar(require("child_process"))),n="/Users/tatsuya/Desktop/AiAgentMarket/mcp/knowledge-injection/hooks/inject-encrypted.sh",s={...process.env};"auto"!==r&&(s.PORTAL_TOKEN=r),s.KNOWLEDGE_KEYWORD=t,debugLog("スクリプト実行開始",{scriptPath:n,keyword:t});const o=e("bash",[n],{env:s,stdio:["pipe","pipe","pipe"]});let a="",i="";o.stdout.on("data",e=>{a+=e.toString()}),o.stderr.on("data",e=>{i+=e.toString()});const c=await new Promise(e=>{o.on("close",e)});if(debugLog("スクリプト実行完了",{exitCode:c,stdout:a.substring(0,200),stderr:i.substring(0,200)}),Date.now(),0===c)return{content:[{type:"text",text:`Knowledge Injection成功: "${t}" の知識が注入されました。\n\n実行結果:\n${a}\n\n統計記録: ⚠️ スキップ`}]};throw new Error(`スクリプト実行失敗 (exit code: ${c})\nstderr: ${i}`)}catch(e){throw debugLog("Knowledge Injectionエラー",{keyword:t,error:getErrorMessage(e)}),new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`Knowledge Injection実行エラー: ${getErrorMessage(e)}`)}}async handlePluginTool(e,t){try{if(!plugin_manager_js_1.pluginManager)return null;if(!plugin_manager_js_1.pluginManager.getAvailableTools().find(t=>t.name===e))return null;debugLog(`プラグインツール実行: ${e}`,t);const r={userId:"current_user",service:"leonardo",apiKey:process.env.LEONARDO_API_KEY,settings:{}};let n="leonardo";e.startsWith("leonardo_")?n="leonardo":e.startsWith("notion_")?n="notion":e.startsWith("slack_")&&(n="slack");const s=await plugin_manager_js_1.pluginManager.executePlugin(n,e,t,r);if(s.success)return debugLog(`プラグインツール実行成功: ${e}`),{content:(s.content||[{type:"text",text:"OK"}]).map(e=>({type:e.type,text:e.text||""})),_meta:s.metadata};throw debugLog(`プラグインツール実行失敗: ${e}`,s.error),new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`プラグインツール実行エラー: ${s.error}`)}catch(t){if(debugLog(`プラグインツール処理エラー: ${e}`,t),t instanceof types_js_1.McpError)throw t;throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError,`プラグイン処理中にエラーが発生しました: ${getErrorMessage(t)}`)}}async run(){debugLog("MCPサーバー開始");try{await plugin_manager_js_1.pluginManager.initialize(),debugLog("プラグインマネージャー初期化完了")}catch(e){debugLog("プラグインマネージャー初期化エラー",e)}const e=new stdio_js_1.StdioServerTransport;await this.server.connect(e),debugLog("MCPサーバー接続完了")}}const server=new SampleMCPServer;server.run().catch(e=>{process.exit(1)});
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,s,i){void 0===i&&(i=s);var n=Object.getOwnPropertyDescriptor(t,s);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,i,n)}:function(e,t,s,i){void 0===i&&(i=s),e[i]=t[s]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[t.length]=s);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var s={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&__createBinding(s,t,i[n]);return __setModuleDefault(s,t),s}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.PluginLoader=exports.BasePlugin=void 0;const zod_1=require("zod");class BasePlugin{constructor(){this._initialized=!1,this._credentials=new Map}get isInitialized(){return this._initialized}markInitialized(){this._initialized=!0}validateArgs(e,t){try{return t.parse(e)}catch(e){if(e instanceof zod_1.z.ZodError){const t=e.issues.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ");throw new Error(`引数の検証に失敗しました: ${t}`)}throw e}}async getCredentials(e){const t=`${e}-${this.manifest.id}`;if(this._credentials.has(t))return this._credentials.get(t);const s=await this.fetchCredentialsFromPortal(e);return this._credentials.set(t,s),s}async fetchCredentialsFromPortal(e){const t=process.env[`${this.manifest.id.toUpperCase()}_API_KEY`];return{userId:e,service:this.manifest.id,apiKey:t,settings:{}}}async recordUsage(e,t,s,i,n){const r={userId:t,pluginId:this.manifest.id,toolName:e,executionTime:i,success:s,timestamp:new Date,metadata:n};await this.sendStatsToPortal(r)}async sendStatsToPortal(e){console.log(`[STATS] ${this.manifest.id}:${e.toolName} - ${e.success?"SUCCESS":"FAILED"} (${e.executionTime}ms)`)}handleError(e,t){const s=e?.message||String(e),i=e?.code||"UNKNOWN_ERROR";return console.error(`[ERROR] ${this.manifest.id} - ${t}: ${s}`),{success:!1,error:`${t}: ${s}`,metadata:{errorCode:i,pluginId:this.manifest.id,timestamp:(new Date).toISOString()}}}createSuccessResponse(e,t){return{success:!0,content:e,metadata:{pluginId:this.manifest.id,timestamp:(new Date).toISOString(),...t}}}supportsTool(e){return this.manifest.tools.some(t=>t.name===e)}async healthCheck(){try{return this.isInitialized?(await this.performHealthCheck(),{status:"healthy",details:{initialized:!0,toolCount:this.manifest.tools.length,version:this.manifest.version}}):{status:"unhealthy",message:"プラグインが初期化されていません"}}catch(e){return{status:"unhealthy",message:`ヘルスチェックに失敗しました: ${e}`,details:{error:String(e)}}}}async performHealthCheck(){}}exports.BasePlugin=BasePlugin;class PluginLoader{constructor(){this.loadedPlugins=new Map}static getInstance(){return PluginLoader.instance||(PluginLoader.instance=new PluginLoader),PluginLoader.instance}async loadPlugin(e){try{if(this.loadedPlugins.has(e))return this.loadedPlugins.get(e);const t=await Promise.resolve(`./services/${e}-plugin.js`).then(e=>__importStar(require(e))),s=new(t.default||t[Object.keys(t)[0]]);return await s.initialize(),this.loadedPlugins.set(e,s),console.log(`✅ プラグイン読み込み成功: ${e}`),s}catch(t){return console.error(`❌ プラグイン読み込み失敗: ${e} - ${t}`),null}}async unloadPlugin(e){const t=this.loadedPlugins.get(e);t&&(await t.shutdown(),this.loadedPlugins.delete(e),console.log(`🗑️ プラグインアンロード完了: ${e}`))}async unloadAllPlugins(){const e=Array.from(this.loadedPlugins.keys()).map(e=>this.unloadPlugin(e));await Promise.all(e)}getLoadedPlugins(){return Array.from(this.loadedPlugins.keys())}}exports.PluginLoader=PluginLoader;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,s,i){void 0===i&&(i=s);var n=Object.getOwnPropertyDescriptor(t,s);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,i,n)}:function(e,t,s,i){void 0===i&&(i=s),e[i]=t[s]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[t.length]=s);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var s={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&__createBinding(s,t,i[n]);return __setModuleDefault(s,t),s}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.PluginLoader=exports.BasePlugin=void 0;const zod_1=require("zod");class BasePlugin{constructor(){this._initialized=!1,this._credentials=new Map}get isInitialized(){return this._initialized}markInitialized(){this._initialized=!0}validateArgs(e,t){try{return t.parse(e)}catch(e){if(e instanceof zod_1.z.ZodError){const t=e.issues.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ");throw new Error(`引数の検証に失敗しました: ${t}`)}throw e}}async getCredentials(e){const t=`${e}-${this.manifest.id}`;if(this._credentials.has(t))return this._credentials.get(t);const s=await this.fetchCredentialsFromPortal(e);return this._credentials.set(t,s),s}async fetchCredentialsFromPortal(e){const t=process.env[`${this.manifest.id.toUpperCase()}_API_KEY`];return{userId:e,service:this.manifest.id,apiKey:t,settings:{}}}async recordUsage(e,t,s,i,n){const r={userId:t,pluginId:this.manifest.id,toolName:e,executionTime:i,success:s,timestamp:new Date,metadata:n};await this.sendStatsToPortal(r)}async sendStatsToPortal(e){console.log(`[STATS] ${this.manifest.id}:${e.toolName} - ${e.success?"SUCCESS":"FAILED"} (${e.executionTime}ms)`)}handleError(e,t){const s=e instanceof Error?e.message:String(e),i=e?.code||"UNKNOWN_ERROR";return console.error(`[ERROR] ${this.manifest.id} - ${t}: ${s}`),{success:!1,error:`${t}: ${s}`,metadata:{errorCode:i,pluginId:this.manifest.id,timestamp:(new Date).toISOString()}}}createSuccessResponse(e,t){return{success:!0,content:e,metadata:{pluginId:this.manifest.id,timestamp:(new Date).toISOString(),...t}}}supportsTool(e){return this.manifest.tools.some(t=>t.name===e)}async healthCheck(){try{return this.isInitialized?(await this.performHealthCheck(),{status:"healthy",details:{initialized:!0,toolCount:this.manifest.tools.length,version:this.manifest.version}}):{status:"unhealthy",message:"プラグインが初期化されていません"}}catch(e){return{status:"unhealthy",message:`ヘルスチェックに失敗しました: ${e}`,details:{error:String(e)}}}}async performHealthCheck(){}}exports.BasePlugin=BasePlugin;class PluginLoader{constructor(){this.loadedPlugins=new Map}static getInstance(){return PluginLoader.instance||(PluginLoader.instance=new PluginLoader),PluginLoader.instance}async loadPlugin(e){try{if(this.loadedPlugins.has(e))return this.loadedPlugins.get(e);const t=await Promise.resolve(`./services/${e}-plugin.js`).then(e=>__importStar(require(e))),s=new(t.default||t[Object.keys(t)[0]]);return await s.initialize(),this.loadedPlugins.set(e,s),console.log(`✅ プラグイン読み込み成功: ${e}`),s}catch(t){return console.error(`❌ プラグイン読み込み失敗: ${e} - ${t}`),null}}async unloadPlugin(e){const t=this.loadedPlugins.get(e);t&&(await t.shutdown(),this.loadedPlugins.delete(e),console.log(`🗑️ プラグインアンロード完了: ${e}`))}async unloadAllPlugins(){const e=Array.from(this.loadedPlugins.keys()).map(e=>this.unloadPlugin(e));await Promise.all(e)}getLoadedPlugins(){return Array.from(this.loadedPlugins.keys())}}exports.PluginLoader=PluginLoader;
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,o,a){void 0===a&&(a=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,a,r)}:function(e,t,o,a){void 0===a&&(a=o),e[a]=t[o]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[t.length]=o);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var o={};if(null!=t)for(var a=e(t),r=0;r<a.length;r++)"default"!==a[r]&&__createBinding(o,t,a[r]);return __setModuleDefault(o,t),o}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const sdk_1=require("@leonardo-ai/sdk"),zod_1=require("zod"),fs=__importStar(require("fs/promises")),path=__importStar(require("path")),node_fetch_1=__importDefault(require("node-fetch")),sharp_1=__importDefault(require("sharp")),base_plugin_js_1=require("../base-plugin.js"),ApiKeyManager_js_1=require("../../security/ApiKeyManager.js"),leonardo_prompt_parser_js_1=require("./leonardo-prompt-parser.js"),LeonardoAnimateSchema=zod_1.z.object({folderPath:zod_1.z.string().default("./outputs").describe("画像が保存されているフォルダパス"),pattern:zod_1.z.string().default("*.png").describe("対象ファイルのパターン(例: *.png, leonardo_*.png)"),motionStrength:zod_1.z.number().int().min(1).max(10).default(5).describe("動きの強さ(1:穏やか~10:激しい)"),fileLimit:zod_1.z.number().int().min(1).max(10).optional().describe("処理する画像の最大数"),sortBy:zod_1.z.enum(["newest","oldest","name"]).default("newest").describe("ファイルの並び順"),outputPath:zod_1.z.string().default("./outputs/videos").describe("動画の保存先"),isPublic:zod_1.z.boolean().default(!1).describe("生成した動画を公開するか")}),LeonardoGenerateSchema=zod_1.z.object({prompt:zod_1.z.string().min(1,"プロンプトは必須です"),width:zod_1.z.number().int().min(512).max(2048).default(1024),height:zod_1.z.number().int().min(512).max(2048).default(1024),num_images:zod_1.z.number().int().min(1).max(8).default(1),modelId:zod_1.z.string().optional(),negativePrompt:zod_1.z.string().optional(),photoReal:zod_1.z.boolean().default(!1),photoRealVersion:zod_1.z.enum(["v1","v2"]).default("v2"),alchemy:zod_1.z.boolean().default(!0),ultra:zod_1.z.boolean().default(!1).describe("Ultra mode for higher quality (Phoenix only)"),guidance_scale:zod_1.z.number().min(1).max(30).default(7),seed:zod_1.z.number().int().optional(),steps:zod_1.z.number().int().min(30).max(60).default(50),contrast:zod_1.z.number().min(1).max(4.5).default(1),outputPath:zod_1.z.string().default("./outputs"),presetStyle:zod_1.z.enum(["CINEMATIC","DYNAMIC","ENVIRONMENTAL","GENERAL","ILLUSTRATION","PHOTOGRAPHY","RAYTRACED","RENDER_3D","SKETCH_BW","SKETCH_COLOR","VIBRANT"]).optional()});class LeonardoPlugin extends base_plugin_js_1.BasePlugin{constructor(){super(...arguments),this.manifest={id:"leonardo",name:"Leonardo AI",version:"1.0.0",category:"AI",description:"Leonardo AIによる高品質な画像生成。PhotoReal、Alchemy v2対応",authType:"api_key",loadPriority:"high",tools:[{name:"leonardo_generate",description:"Leonardo AIで高品質な画像を生成します。プロンプトに基づいて1-8枚の画像を作成し、指定されたフォルダに保存します。",inputSchema:LeonardoGenerateSchema,outputExample:{success:!0,content:[{type:"text",text:"✅ Leonardo AIで2枚の画像を生成しました\\n📁 保存先:\\n- ./outputs/leonardo_20250830_001.png\\n- ./outputs/leonardo_20250830_002.png"}]}},{name:"leonardo_animate",description:"フォルダ内の画像をLeonardo AI Motion 1.0で動画化します。画像をアップロードして動きを追加し、MP4形式で保存します。",inputSchema:LeonardoAnimateSchema,outputExample:{success:!0,content:[{type:"text",text:"🎬 3枚の画像を動画化しました\\n📁 保存先:\\n- ./outputs/videos/motion_20250830_001.mp4\\n- ./outputs/videos/motion_20250830_002.mp4\\n- ./outputs/videos/motion_20250830_003.mp4"}]}}]},this.availableModels=[]}async initialize(){try{this.availableModels=await this.getDefaultModels(),this.markInitialized()}catch(e){throw e}}async shutdown(){this.leonardo=void 0}async executeTool(e,t,o){if(!this.isInitialized)return this.handleError("プラグインが初期化されていません","executeTool");switch(e){case"leonardo_generate":return await this.generateImage(t,o);case"leonardo_animate":return await this.animateImages(t,o);default:return this.handleError(`未知のツール: ${e}`,"executeTool")}}async generateImage(e,t){const o=Date.now();try{const a=this.validateArgs(e,LeonardoGenerateSchema),r=leonardo_prompt_parser_js_1.LeonardoPromptParser.parsePrompt(a.prompt),n=this.mergeSettings(r,a);console.log("🔍 プロンプト解析結果:",{original:a.prompt,clean:r.cleanPrompt,extracted:{model:r.modelName,size:`${r.width}x${r.height}`,style:r.presetStyle,count:r.num_images}});const i=leonardo_prompt_parser_js_1.LeonardoPromptParser.validateSettings(n);if(i.length>0&&console.warn("⚠️ 設定警告:",i),await this.initializeLeonardoClient(t),!this.leonardo)return this.handleError("Leonardo AI クライアントの初期化に失敗","generateImage");await this.ensureOutputDirectory(n.outputPath||"./outputs");const s=await this.requestGeneration(n),d=await this.waitForGeneration(s.generationId);if("FAILED"===d.status)return this.handleError("画像生成に失敗しました","generateImage");if(!d.images||0===d.images.length)return this.handleError("生成された画像が見つかりません","generateImage");const l=await this.downloadAndSaveImages(d.images,n.outputPath||"./outputs"),u=Date.now()-o;return await this.recordUsage("leonardo_generate",t.userId,!0,u,{imageCount:l.length,prompt:n.cleanPrompt,modelId:n.modelId,parsedFromPrompt:!0}),this.createSuccessResponse([{type:"text",text:`✅ Leonardo AIで${l.length}枚の画像を生成しました\n📝 設定: ${n.modelName||"デフォルト"} / ${n.width}x${n.height}\n📁 保存先:\n${l.map(e=>`- ${e}`).join("\n")}`}],{generationId:d.id,imageCount:l.length,executionTimeMs:u,savedFiles:l,parsedSettings:{model:n.modelName,size:`${n.width}x${n.height}`,style:n.presetStyle}})}catch(e){const a=Date.now()-o;return await this.recordUsage("leonardo_generate",t.userId,!1,a,{error:String(e)}),this.handleError(e,"generateImage")}}mergeSettings(e,t){return{prompt:e.cleanPrompt||t.prompt,width:t.width||e.width||1024,height:t.height||e.height||1024,num_images:t.num_images||e.num_images||1,modelId:t.modelId||e.modelId,modelName:e.modelName,photoReal:void 0!==t.photoReal?t.photoReal:e.photoReal,photoRealVersion:t.photoRealVersion||e.photoRealVersion||"v2",presetStyle:t.presetStyle||e.presetStyle,alchemy:void 0!==t.alchemy?t.alchemy:void 0===e.alchemy||e.alchemy,guidance_scale:t.guidance_scale||e.guidanceScale||7,steps:t.steps||e.steps||50,contrast:t.contrast||e.contrast||1,negativePrompt:t.negativePrompt,seed:t.seed,outputPath:t.outputPath,originalPrompt:t.prompt,cleanPrompt:e.cleanPrompt}}async initializeLeonardoClient(e){if(this.leonardo)return;const t=await ApiKeyManager_js_1.ApiKeyManager.getApiKey("leonardo-ai");if(!t)throw new Error("Leonardo APIキーがPortalに設定されていません。https://bluelamp.vercel.app/settings で設定してください");this.leonardo=new sdk_1.Leonardo({bearerAuth:t})}async requestGeneration(e){if(!this.leonardo)throw new Error("Leonardo AIクライアントが初期化されていません");try{const t={prompt:e.prompt,width:e.width||1024,height:e.height||1024,numImages:e.num_images||1,guidanceScale:e.guidance_scale||7,alchemy:!1!==e.alchemy};e.modelId&&(t.modelId=e.modelId),e.negativePrompt&&(t.negativePrompt=e.negativePrompt),e.photoReal&&(t.photoReal=!0,t.photoRealVersion=e.photoRealVersion||"v2"),!0===e.ultra&&(t.ultra=!0,t.alchemy&&delete t.alchemy),e.seed&&(t.seed=e.seed),e.steps&&(t.numInferenceSteps=e.steps),e.presetStyle&&(t.presetStyle=e.presetStyle);const o=await this.leonardo.image.createGeneration(t),a=o?.object?.sdGenerationJob?.generationId;if(!a)throw new Error("生成IDが取得できませんでした");return{generationId:a}}catch(e){throw new Error(`Leonardo AI API エラー: ${e.message||e}`)}}async waitForGeneration(e){if(!this.leonardo)throw new Error("Leonardo AIクライアントが初期化されていません");let t=0;for(;t<30;)try{const o=await this.leonardo.image.getGenerationById(e),a=o?.object?.generationsByPk;if("COMPLETE"===a?.status)return{id:e,status:"COMPLETE",images:a.generatedImages?.map(e=>({id:e.id||"",url:e.url||"",likelyGuid:e.likelyGuid||""}))};if("FAILED"===a?.status)return{id:e,status:"FAILED"};await new Promise(e=>setTimeout(e,1e4)),t++}catch(e){if(t++,t>=30)throw new Error(`生成確認の最大試行回数を超えました: ${e}`);await new Promise(e=>setTimeout(e,5e3))}throw new Error("生成がタイムアウトしました。Leonardo AIのサーバーが混雑している可能性があります。")}async downloadAndSaveImages(e,t){const o=[],a=new Date,r=a.toISOString().replace(/[:\-]/g,"").replace("T","_").replace(/\..+/,""),n=`${a.getTime()}_${Math.random().toString(36).substring(2,8)}`;for(let a=0;a<e.length;a++){const i=e[a];try{const e=await(0,node_fetch_1.default)(i.url);if(!e.ok)throw new Error(`ダウンロード失敗: ${e.status} ${e.statusText}`);const s=Buffer.from(await e.arrayBuffer()),d=`leonardo_${r}_${n}_${i.id?i.id.substring(0,8):""}_${String(a+1).padStart(2,"0")}.png`,l=path.join(t,d);await(0,sharp_1.default)(s).png({quality:95,compressionLevel:6}).toFile(l),o.push(l)}catch(e){}}if(0===o.length)throw new Error("画像の保存に全て失敗しました");return o}async ensureOutputDirectory(e){try{await fs.mkdir(e,{recursive:!0})}catch(t){throw new Error(`出力ディレクトリの作成に失敗: ${e} - ${t}`)}}async getDefaultModels(){return[{id:"6bef9f1b-29cb-40c7-b9df-32b51c1f67d3",name:"Leonardo Phoenix",description:"2024年リリースの最新モデル。高いプロンプト忠実度と詳細なテキスト生成が特徴",supportsAlchemy:!0},{id:"aa77f04e-3eec-4034-9c07-d0f619684628",name:"Leonardo Diffusion XL",description:"SDXL基盤の高品質汎用モデル",supportsPhotoReal:!0,supportsAlchemy:!0},{id:"1e60896f-3c26-4296-8ecc-53e2afecc132",name:"Leonardo Kino XL",description:"シネマティック品質の画像生成に特化",supportsPhotoReal:!0,supportsAlchemy:!0},{id:"5c232a9e-9061-4777-980a-ddc8e65647c6",name:"Leonardo Vision XL",description:"フォトリアルな画像生成に最適化",supportsPhotoReal:!0,supportsAlchemy:!0}]}async performHealthCheck(){const e=await ApiKeyManager_js_1.ApiKeyManager.getApiKey("leonardo-ai");if(!e)throw new Error("Leonardo APIキーがPortalに設定されていません。https://bluelamp.vercel.app/settings で設定してください");try{new sdk_1.Leonardo({bearerAuth:e})}catch(e){throw new Error(`Leonardo AI接続テストに失敗: ${e}`)}}async animateImages(e,t){const o=Date.now();try{const a=this.validateArgs(e,LeonardoAnimateSchema);if(await this.initializeLeonardoClient(t),!this.leonardo)return this.handleError("Leonardo AI クライアントの初期化に失敗","animateImages");const r=await this.findImageFiles(a.folderPath,a.pattern,a.sortBy,a.fileLimit);if(0===r.length)return this.handleError(`${a.folderPath}に対象画像が見つかりません(パターン: ${a.pattern})`,"animateImages");console.log(`🎬 ${r.length}枚の画像を動画化開始`),await this.ensureOutputDirectory(a.outputPath);const n=[],i=[];for(let e=0;e<r.length;e++){const t=r[e];console.log(`📸 処理中 (${e+1}/${r.length}): ${path.basename(t)}`);try{const e=await this.uploadImageToLeonardo(t),o=await this.requestMotionGeneration(e,a.motionStrength,a.isPublic),r=await this.waitForMotionGeneration(o),i=await this.downloadVideo(r,a.outputPath,t);n.push(i),console.log(`✅ 動画保存: ${path.basename(i)}`)}catch(e){const o=`❌ ${path.basename(t)}: ${e}`;console.error(o),i.push(o)}}const s=Date.now()-o;return await this.recordUsage("leonardo_animate",t.userId,n.length>0,s,{processedImages:r.length,generatedVideos:n.length,errors:i.length}),0===n.length?this.handleError("すべての動画生成に失敗しました","animateImages"):this.createSuccessResponse([{type:"text",text:`🎬 ${n.length}/${r.length}個の動画を生成しました\n📁 保存先:\n${n.map(e=>`- ${e}`).join("\n")}${i.length>0?`\n\n⚠️ エラー:\n${i.join("\n")}`:""}`}],{processedImages:r.length,generatedVideos:n.length,executionTimeMs:s,savedFiles:n})}catch(e){const a=Date.now()-o;return await this.recordUsage("leonardo_animate",t.userId,!1,a,{error:String(e)}),this.handleError(e,"animateImages")}}async findImageFiles(e,t,o,a){const r=(await Promise.resolve().then(()=>__importStar(require("glob")))).glob,n=path.join(e,t),i=await r(n,{nodir:!0,absolute:!0});if(0===i.length)return[];const s=await Promise.all(i.map(async e=>({path:e,stat:await fs.stat(e)})));return s.sort((e,t)=>{switch(o){case"newest":return t.stat.mtime.getTime()-e.stat.mtime.getTime();case"oldest":return e.stat.mtime.getTime()-t.stat.mtime.getTime();default:return e.path.localeCompare(t.path)}}),(a?s.slice(0,a):s).map(e=>e.path)}async uploadImageToLeonardo(e){if(!this.leonardo)throw new Error("Leonardo AIクライアントが初期化されていません");const t=await fs.readFile(e),o=path.basename(e),a=await this.leonardo.image.uploadInitImage({extension:path.extname(o).substring(1)});if(!a.object?.uploadInitImage?.url||!a.object?.uploadInitImage?.id)throw new Error("アップロードURL取得に失敗しました");const{url:r,id:n}=a.object.uploadInitImage,i=await(0,node_fetch_1.default)(r,{method:"PUT",body:t,headers:{"Content-Type":"image/png"}});if(!i.ok)throw new Error(`画像アップロード失敗: ${i.status}`);return n}async requestMotionGeneration(e,t,o){if(!this.leonardo)throw new Error("Leonardo AIクライアントが初期化されていません");const a=await this.getLeonardoApiKey(),r=await(0,node_fetch_1.default)("https://cloud.leonardo.ai/api/rest/v1/generations-motion-svd",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({imageId:e,motionStrength:t,isInitImage:!0,isPublic:o})});if(!r.ok){const e=await r.text();throw new Error(`Motion生成リクエスト失敗: ${r.status} - ${e}`)}const n=await r.json();if(!n.motionSvdGenerationJob?.generationId)throw new Error("Motion生成IDが取得できませんでした");return n.motionSvdGenerationJob.generationId}async waitForMotionGeneration(e){let t=0;const o=await this.getLeonardoApiKey();for(;t<60;)try{const a=await(0,node_fetch_1.default)(`https://cloud.leonardo.ai/api/rest/v1/generations/${e}`,{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"}});if(!a.ok)throw new Error(`生成状況確認失敗: ${a.status}`);const r=(await a.json()).generationsByPk;if("COMPLETE"===r?.status){const e=r.generatedVideos?.[0];if(e?.url)return e.url;throw new Error("動画URLが見つかりません")}if("FAILED"===r?.status)throw new Error("動画生成に失敗しました");await new Promise(e=>setTimeout(e,1e4)),t++}catch(e){if(t++,t>=60)throw new Error(`生成確認の最大試行回数を超えました: ${e}`);await new Promise(e=>setTimeout(e,5e3))}throw new Error("動画生成がタイムアウトしました")}async getLeonardoApiKey(){if(this.leonardo){const e=this.leonardo.config;if(e?.bearerAuth)return e.bearerAuth}const e=await ApiKeyManager_js_1.ApiKeyManager.getApiKey("leonardo-ai");if(!e)throw new Error("Leonardo APIキーがPortalに設定されていません。https://bluelamp.vercel.app/settings で設定してください");return e}async downloadVideo(e,t,o){const a=await(0,node_fetch_1.default)(e);if(!a.ok)throw new Error(`動画ダウンロード失敗: ${a.status}`);const r=Buffer.from(await a.arrayBuffer()),n=(new Date).toISOString().replace(/[:\-]/g,"").replace("T","_").replace(/\..+/,""),i=`motion_${path.basename(o,path.extname(o))}_${n}.mp4`,s=path.join(t,i);return await fs.writeFile(s,r),s}}exports.default=LeonardoPlugin;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,o,a){void 0===a&&(a=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,a,r)}:function(e,t,o,a){void 0===a&&(a=o),e[a]=t[o]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[t.length]=o);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var o={};if(null!=t)for(var a=e(t),r=0;r<a.length;r++)"default"!==a[r]&&__createBinding(o,t,a[r]);return __setModuleDefault(o,t),o}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const sdk_1=require("@leonardo-ai/sdk"),zod_1=require("zod"),fs=__importStar(require("fs/promises")),path=__importStar(require("path")),node_fetch_1=__importDefault(require("node-fetch")),sharp_1=__importDefault(require("sharp")),base_plugin_js_1=require("../base-plugin.js"),ApiKeyManager_js_1=require("../../security/ApiKeyManager.js"),leonardo_prompt_parser_js_1=require("./leonardo-prompt-parser.js"),LeonardoAnimateSchema=zod_1.z.object({folderPath:zod_1.z.string().default("./outputs").describe("画像が保存されているフォルダパス"),pattern:zod_1.z.string().default("*.png").describe("対象ファイルのパターン(例: *.png, leonardo_*.png)"),motionStrength:zod_1.z.number().int().min(1).max(10).default(5).describe("動きの強さ(1:穏やか~10:激しい)"),fileLimit:zod_1.z.number().int().min(1).max(10).optional().describe("処理する画像の最大数"),sortBy:zod_1.z.enum(["newest","oldest","name"]).default("newest").describe("ファイルの並び順"),outputPath:zod_1.z.string().default("./outputs/videos").describe("動画の保存先"),isPublic:zod_1.z.boolean().default(!1).describe("生成した動画を公開するか")}),LeonardoGenerateSchema=zod_1.z.object({prompt:zod_1.z.string().min(1,"プロンプトは必須です"),width:zod_1.z.number().int().min(512).max(2048).default(1024),height:zod_1.z.number().int().min(512).max(2048).default(1024),num_images:zod_1.z.number().int().min(1).max(8).default(1),modelId:zod_1.z.string().optional(),negativePrompt:zod_1.z.string().optional(),photoReal:zod_1.z.boolean().default(!1),photoRealVersion:zod_1.z.enum(["v1","v2"]).default("v2"),alchemy:zod_1.z.boolean().default(!0),ultra:zod_1.z.boolean().default(!1).describe("Ultra mode for higher quality (Phoenix only)"),guidance_scale:zod_1.z.number().min(1).max(30).default(7),seed:zod_1.z.number().int().optional(),steps:zod_1.z.number().int().min(30).max(60).default(50),contrast:zod_1.z.number().min(1).max(4.5).default(1),outputPath:zod_1.z.string().default("./outputs"),presetStyle:zod_1.z.enum(["CINEMATIC","DYNAMIC","ENVIRONMENTAL","GENERAL","ILLUSTRATION","PHOTOGRAPHY","RAYTRACED","RENDER_3D","SKETCH_BW","SKETCH_COLOR","VIBRANT"]).optional()});function getErrorMessage(e){return e instanceof Error?e.message:String(e)}class LeonardoPlugin extends base_plugin_js_1.BasePlugin{constructor(){super(...arguments),this.manifest={id:"leonardo",name:"Leonardo AI",version:"1.0.0",category:"AI",description:"Leonardo AIによる高品質な画像生成。PhotoReal、Alchemy v2対応",authType:"api_key",loadPriority:"high",tools:[{name:"leonardo_generate",description:"Leonardo AIで高品質な画像を生成します。プロンプトに基づいて1-8枚の画像を作成し、指定されたフォルダに保存します。",inputSchema:LeonardoGenerateSchema,outputExample:{success:!0,content:[{type:"text",text:"✅ Leonardo AIで2枚の画像を生成しました\\n📁 保存先:\\n- ./outputs/leonardo_20250830_001.png\\n- ./outputs/leonardo_20250830_002.png"}]}},{name:"leonardo_animate",description:"フォルダ内の画像をLeonardo AI Motion 1.0で動画化します。画像をアップロードして動きを追加し、MP4形式で保存します。",inputSchema:LeonardoAnimateSchema,outputExample:{success:!0,content:[{type:"text",text:"🎬 3枚の画像を動画化しました\\n📁 保存先:\\n- ./outputs/videos/motion_20250830_001.mp4\\n- ./outputs/videos/motion_20250830_002.mp4\\n- ./outputs/videos/motion_20250830_003.mp4"}]}}]},this.availableModels=[]}async initialize(){try{this.availableModels=await this.getDefaultModels(),this.markInitialized()}catch(e){throw e}}async shutdown(){this.leonardo=void 0}async executeTool(e,t,o){if(!this.isInitialized)return this.handleError("プラグインが初期化されていません","executeTool");switch(e){case"leonardo_generate":return await this.generateImage(t,o);case"leonardo_animate":return await this.animateImages(t,o);default:return this.handleError(`未知のツール: ${e}`,"executeTool")}}async generateImage(e,t){const o=Date.now();try{const a=this.validateArgs(e,LeonardoGenerateSchema),r=leonardo_prompt_parser_js_1.LeonardoPromptParser.parsePrompt(a.prompt),n=this.mergeSettings(r,a);console.log("🔍 プロンプト解析結果:",{original:a.prompt,clean:r.cleanPrompt,extracted:{model:r.modelName,size:`${r.width}x${r.height}`,style:r.presetStyle,count:r.num_images}});const i=leonardo_prompt_parser_js_1.LeonardoPromptParser.validateSettings(n);if(i.length>0&&console.warn("⚠️ 設定警告:",i),await this.initializeLeonardoClient(t),!this.leonardo)return this.handleError("Leonardo AI クライアントの初期化に失敗","generateImage");await this.ensureOutputDirectory(n.outputPath||"./outputs");const s=await this.requestGeneration(n),d=await this.waitForGeneration(s.generationId);if("FAILED"===d.status)return this.handleError("画像生成に失敗しました","generateImage");if(!d.images||0===d.images.length)return this.handleError("生成された画像が見つかりません","generateImage");const l=await this.downloadAndSaveImages(d.images,n.outputPath||"./outputs"),u=Date.now()-o;return await this.recordUsage("leonardo_generate",t.userId,!0,u,{imageCount:l.length,prompt:n.cleanPrompt,modelId:n.modelId,parsedFromPrompt:!0}),this.createSuccessResponse([{type:"text",text:`✅ Leonardo AIで${l.length}枚の画像を生成しました\n📝 設定: ${n.modelName||"デフォルト"} / ${n.width}x${n.height}\n📁 保存先:\n${l.map(e=>`- ${e}`).join("\n")}`}],{generationId:d.id,imageCount:l.length,executionTimeMs:u,savedFiles:l,parsedSettings:{model:n.modelName,size:`${n.width}x${n.height}`,style:n.presetStyle}})}catch(e){const a=Date.now()-o;return await this.recordUsage("leonardo_generate",t.userId,!1,a,{error:String(e)}),this.handleError(e,"generateImage")}}mergeSettings(e,t){return{prompt:e.cleanPrompt||t.prompt,width:t.width||e.width||1024,height:t.height||e.height||1024,num_images:t.num_images||e.num_images||1,modelId:t.modelId||e.modelId,modelName:e.modelName,photoReal:void 0!==t.photoReal?t.photoReal:e.photoReal,photoRealVersion:t.photoRealVersion||e.photoRealVersion||"v2",presetStyle:t.presetStyle||e.presetStyle,alchemy:void 0!==t.alchemy?t.alchemy:void 0===e.alchemy||e.alchemy,guidance_scale:t.guidance_scale||e.guidanceScale||7,steps:t.steps||e.steps||50,contrast:t.contrast||e.contrast||1,negativePrompt:t.negativePrompt,seed:t.seed,outputPath:t.outputPath,originalPrompt:t.prompt,cleanPrompt:e.cleanPrompt}}async initializeLeonardoClient(e){if(this.leonardo)return;const t=await ApiKeyManager_js_1.ApiKeyManager.getApiKey("leonardo-ai");if(!t)throw new Error("Leonardo APIキーがPortalに設定されていません。https://bluelamp.vercel.app/settings で設定してください");this.leonardo=new sdk_1.Leonardo({bearerAuth:t})}async requestGeneration(e){if(!this.leonardo)throw new Error("Leonardo AIクライアントが初期化されていません");try{const t={prompt:e.prompt,width:e.width||1024,height:e.height||1024,numImages:e.num_images||1,guidanceScale:e.guidance_scale||7,alchemy:!1!==e.alchemy};e.modelId&&(t.modelId=e.modelId),e.negativePrompt&&(t.negativePrompt=e.negativePrompt),e.photoReal&&(t.photoReal=!0,t.photoRealVersion=e.photoRealVersion||"v2"),!0===e.ultra&&(t.ultra=!0,t.alchemy&&delete t.alchemy),e.seed&&(t.seed=e.seed),e.steps&&(t.numInferenceSteps=e.steps),e.presetStyle&&(t.presetStyle=e.presetStyle);const o=await this.leonardo.image.createGeneration(t),a=o?.object?.sdGenerationJob?.generationId;if(!a)throw new Error("生成IDが取得できませんでした");return{generationId:a}}catch(e){throw new Error(`Leonardo AI API エラー: ${getErrorMessage(e)}`)}}async waitForGeneration(e){if(!this.leonardo)throw new Error("Leonardo AIクライアントが初期化されていません");let t=0;for(;t<30;)try{const o=await this.leonardo.image.getGenerationById(e),a=o?.object?.generationsByPk;if("COMPLETE"===a?.status)return{id:e,status:"COMPLETE",images:(a.generatedImages||[]).map(e=>({id:e.id||"",url:e.url||"",likelyGuid:e.likelyGuid||""}))};if("FAILED"===a?.status)return{id:e,status:"FAILED"};await new Promise(e=>setTimeout(e,1e4)),t++}catch(e){if(t++,t>=30)throw new Error(`生成確認の最大試行回数を超えました: ${e}`);await new Promise(e=>setTimeout(e,5e3))}throw new Error("生成がタイムアウトしました。Leonardo AIのサーバーが混雑している可能性があります。")}async downloadAndSaveImages(e,t){const o=[],a=new Date,r=a.toISOString().replace(/[:\-]/g,"").replace("T","_").replace(/\..+/,""),n=`${a.getTime()}_${Math.random().toString(36).substring(2,8)}`;for(let a=0;a<e.length;a++){const i=e[a];try{const e=await(0,node_fetch_1.default)(i.url);if(!e.ok)throw new Error(`ダウンロード失敗: ${e.status} ${e.statusText}`);const s=Buffer.from(await e.arrayBuffer()),d=`leonardo_${r}_${n}_${i.id?i.id.substring(0,8):""}_${String(a+1).padStart(2,"0")}.png`,l=path.join(t,d);await(0,sharp_1.default)(s).png({quality:95,compressionLevel:6}).toFile(l),o.push(l)}catch(e){}}if(0===o.length)throw new Error("画像の保存に全て失敗しました");return o}async ensureOutputDirectory(e){try{await fs.mkdir(e,{recursive:!0})}catch(t){throw new Error(`出力ディレクトリの作成に失敗: ${e} - ${t}`)}}async getDefaultModels(){return[{id:"6bef9f1b-29cb-40c7-b9df-32b51c1f67d3",name:"Leonardo Phoenix",description:"2024年リリースの最新モデル。高いプロンプト忠実度と詳細なテキスト生成が特徴",supportsAlchemy:!0},{id:"aa77f04e-3eec-4034-9c07-d0f619684628",name:"Leonardo Diffusion XL",description:"SDXL基盤の高品質汎用モデル",supportsPhotoReal:!0,supportsAlchemy:!0},{id:"1e60896f-3c26-4296-8ecc-53e2afecc132",name:"Leonardo Kino XL",description:"シネマティック品質の画像生成に特化",supportsPhotoReal:!0,supportsAlchemy:!0},{id:"5c232a9e-9061-4777-980a-ddc8e65647c6",name:"Leonardo Vision XL",description:"フォトリアルな画像生成に最適化",supportsPhotoReal:!0,supportsAlchemy:!0}]}async performHealthCheck(){const e=await ApiKeyManager_js_1.ApiKeyManager.getApiKey("leonardo-ai");if(!e)throw new Error("Leonardo APIキーがPortalに設定されていません。https://bluelamp.vercel.app/settings で設定してください");try{new sdk_1.Leonardo({bearerAuth:e})}catch(e){throw new Error(`Leonardo AI接続テストに失敗: ${e}`)}}async animateImages(e,t){const o=Date.now();try{const a=this.validateArgs(e,LeonardoAnimateSchema);if(await this.initializeLeonardoClient(t),!this.leonardo)return this.handleError("Leonardo AI クライアントの初期化に失敗","animateImages");const r=await this.findImageFiles(a.folderPath,a.pattern,a.sortBy,a.fileLimit);if(0===r.length)return this.handleError(`${a.folderPath}に対象画像が見つかりません(パターン: ${a.pattern})`,"animateImages");console.log(`🎬 ${r.length}枚の画像を動画化開始`),await this.ensureOutputDirectory(a.outputPath);const n=[],i=[];for(let e=0;e<r.length;e++){const t=r[e];console.log(`📸 処理中 (${e+1}/${r.length}): ${path.basename(t)}`);try{const e=await this.uploadImageToLeonardo(t),o=await this.requestMotionGeneration(e,a.motionStrength,a.isPublic),r=await this.waitForMotionGeneration(o),i=await this.downloadVideo(r,a.outputPath,t);n.push(i),console.log(`✅ 動画保存: ${path.basename(i)}`)}catch(e){const o=`❌ ${path.basename(t)}: ${e}`;console.error(o),i.push(o)}}const s=Date.now()-o;return await this.recordUsage("leonardo_animate",t.userId,n.length>0,s,{processedImages:r.length,generatedVideos:n.length,errors:i.length}),0===n.length?this.handleError("すべての動画生成に失敗しました","animateImages"):this.createSuccessResponse([{type:"text",text:`🎬 ${n.length}/${r.length}個の動画を生成しました\n📁 保存先:\n${n.map(e=>`- ${e}`).join("\n")}${i.length>0?`\n\n⚠️ エラー:\n${i.join("\n")}`:""}`}],{processedImages:r.length,generatedVideos:n.length,executionTimeMs:s,savedFiles:n})}catch(e){const a=Date.now()-o;return await this.recordUsage("leonardo_animate",t.userId,!1,a,{error:String(e)}),this.handleError(e,"animateImages")}}async findImageFiles(e,t,o,a){const r=(await Promise.resolve().then(()=>__importStar(require("glob")))).glob,n=path.join(e,t),i=await r(n,{nodir:!0,absolute:!0});if(0===i.length)return[];const s=await Promise.all(i.map(async e=>({path:e,stat:await fs.stat(e)})));return s.sort((e,t)=>{switch(o){case"newest":return t.stat.mtime.getTime()-e.stat.mtime.getTime();case"oldest":return e.stat.mtime.getTime()-t.stat.mtime.getTime();default:return e.path.localeCompare(t.path)}}),(a?s.slice(0,a):s).map(e=>e.path)}async uploadImageToLeonardo(e){if(!this.leonardo)throw new Error("Leonardo AIクライアントが初期化されていません");const t=await fs.readFile(e),o=path.basename(e),a=await this.leonardo.image.uploadInitImage({extension:path.extname(o).substring(1)});if(!a.object?.uploadInitImage?.url||!a.object?.uploadInitImage?.id)throw new Error("アップロードURL取得に失敗しました");const{url:r,id:n}=a.object.uploadInitImage,i=await(0,node_fetch_1.default)(r,{method:"PUT",body:t,headers:{"Content-Type":"image/png"}});if(!i.ok)throw new Error(`画像アップロード失敗: ${i.status}`);return n}async requestMotionGeneration(e,t,o){if(!this.leonardo)throw new Error("Leonardo AIクライアントが初期化されていません");const a=await this.getLeonardoApiKey(),r=await(0,node_fetch_1.default)("https://cloud.leonardo.ai/api/rest/v1/generations-motion-svd",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({imageId:e,motionStrength:t,isInitImage:!0,isPublic:o})});if(!r.ok){const e=await r.text();throw new Error(`Motion生成リクエスト失敗: ${r.status} - ${e}`)}const n=await r.json();if(!n.motionSvdGenerationJob?.generationId)throw new Error("Motion生成IDが取得できませんでした");return n.motionSvdGenerationJob.generationId}async waitForMotionGeneration(e){let t=0;const o=await this.getLeonardoApiKey();for(;t<60;)try{const a=await(0,node_fetch_1.default)(`https://cloud.leonardo.ai/api/rest/v1/generations/${e}`,{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"}});if(!a.ok)throw new Error(`生成状況確認失敗: ${a.status}`);const r=(await a.json()).generationsByPk;if("COMPLETE"===r?.status){const e=r.generatedVideos?.[0];if(e?.url)return e.url;throw new Error("動画URLが見つかりません")}if("FAILED"===r?.status)throw new Error("動画生成に失敗しました");await new Promise(e=>setTimeout(e,1e4)),t++}catch(e){if(t++,t>=60)throw new Error(`生成確認の最大試行回数を超えました: ${e}`);await new Promise(e=>setTimeout(e,5e3))}throw new Error("動画生成がタイムアウトしました")}async getLeonardoApiKey(){if(this.leonardo){const e=this.leonardo.config;if(e?.bearerAuth)return e.bearerAuth}const e=await ApiKeyManager_js_1.ApiKeyManager.getApiKey("leonardo-ai");if(!e)throw new Error("Leonardo APIキーがPortalに設定されていません。https://bluelamp.vercel.app/settings で設定してください");return e}async downloadVideo(e,t,o){const a=await(0,node_fetch_1.default)(e);if(!a.ok)throw new Error(`動画ダウンロード失敗: ${a.status}`);const r=Buffer.from(await a.arrayBuffer()),n=(new Date).toISOString().replace(/[:\-]/g,"").replace("T","_").replace(/\..+/,""),i=`motion_${path.basename(o,path.extname(o))}_${n}.mp4`,s=path.join(t,i);return await fs.writeFile(s,r),s}}exports.default=LeonardoPlugin;